Explore на одной высоте летит вертолет. он вылетел из питера. пролетел на юг 500 км. затем на… Save Share Download ▾ ReportJump to turn (21) 1 на одной высоте летит вертолет. он вылетел из питера. пролетел на юг 500 км. зат 2 на одной высоте летит вертолет. он вылетел из питера. пролетел на север 500 км. 3 а если учитывать кривизну планеты? 4 у меня ест ьвот такой код import React, { RefObject, useCallback, useEffect, use 5 отличия ребейз от мердж в гите 6 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 7 но это не сработало теперь связь просто не добавляется ни при кликах ни при пере 8 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 9 у меня есть группа объектов. это ппимитив. вот она import React, { forwardRef } 10 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 11 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 12 у меня есть вот такой код import React, { useCallback, useEffect, useRef, useSta 13 у меня етс ьвот такой код import React, { useCallback, useEffect, useRef, useSta 14 я хочу добавить сюда отображение превью связи для этого мне нужно отслеживать дв 15 у меня есть овт такоф код import React, { forwardRef, useEffect, useRef, useStat 16 как сделать эту линю пунктирной? 17 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 18 у менч есть код import React, { forwardRef, useEffect, useRef, useState } from ' 19 TS2304: Cannot find name setHovered 20 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 21 у меня есть код import React, { forwardRef, useEffect, useRef, useState } from ' на одной высоте летит вертолет. он вылетел из питера. пролетел на юг 500 км. затем на запад 500 км. затем на юг 500 км. затем на восток 500 км.
в какой точке окажается вертолет? севернее/восточнее/южнее/западнее?
Assistant2024-11-17 08:25 UTC Copy response
Давайте шаг за шагом проследим за перемещением вертолета:
Вертолет вылетел из Санкт-Петербурга и пролетел на юг 500 км.
Затем он пролетел на запад 500 км.
Далее он снова пролетел на юг 500 км.
Наконец, он полетел на восток 500 км.
Поскольку движение на запад и потом на восток составили одинаковые расстояния (500 км), это компенсировало друг друга, и вертолет остается на той же долготе, с которой начал.
Но за два перемещения на юг (каждое по 500 км) вертолет пролетел 1000 км на юг от начальной точки. Таким образом, вертолет окажется южнее начальной точки (Санкт-Петербурга).
User
Copy first prompt Copy first response
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 21 (42 messages)
Language en
Conversation date Nov 19, 2024
Added to archive Nov 16, 2026
ID 01m7h429zgwmbkwg8j2nze466tSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 6e10a7a7a506ca9572c8b9d38500f7a4
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
Copy prompt
на одной высоте летит вертолет. он вылетел из питера. пролетел на север 500 км. затем на запад 500 км. затем на юг 500 км. затем на восток 500 км.
в какой точке окажается вертолет? севернее/восточнее/южнее/западнее?
Assistant2024-11-17 08:26 UTC Copy response
Давайте проанализируем перемещение вертолета шаг за шагом:
Вертолет вылетел из Санкт-Петербурга и пролетел на север 500 км.
Затем он пролетел на запад 500 км.
Далее он пролетел на юг 500 км.
Наконец, он полетел на восток 500 км.
Давайте посмотрим на результат перемещений:
После первого перемещения на север 500 км вертолет находится севернее исходной точки.
После перемещения на запад 500 км он смещается на запад.
Перемещение на юг 500 км возвращает его на ту же широту, с которой он начал.
Затем перемещение на восток 500 км возвращает вертолет на изначальную долготу.
Таким образом, окончательная точка вертолета будет иметь ту же широту и долготу, что и начальная точка. Вертолет оказывается в той же точке, с которой начал, то есть Севере, Восточнее, Южнее и Западнее изменения нет.
а если учитывать кривизну планеты?
Assistant2024-11-17 08:28 UTC Copy response
При учёте кривизны Земли, результат может немного отличаться, и это связано с понятием ортодромы (кратчайшего пути между двумя точками на сфере) и локсодромы (линии, пересекающей все меридианы под одним и тем же углом).
Когда вертолет перемещается:
На север 500 км: он находится севернее исходной точки.
Затем на запад по горизонтали вдоль параллели на 500 км: из-за кривизны Земли, линия движения по западной дуге одной и той же параллели длиннее, чем по той же долготе (вдоль меридиана).
На юг 500 км: он возвращается на сомой связаной широте.
На восток 500 км: применяются те же принципы.
Таким образом, перемещения по параллелям и меридианам могут привести к неточности из-за того, что меридианы сходятся на полюсах. Если исходная точка близка к полюсам, то после вышеописанных перемещений полет может закончиться немного восточнее изначальной долготы из-за особенностей пересечения меридианов под углами и эффекта локсодром.
Однако из Санкт-Петербурга (который находится не близко к полюсу и достаточно далеко от экватора), в результате описанного движения вертолет окажется в точке, близкой к исходной. С учетом небольшой кривизны Земли, он может оказаться не точно в начальной точке, но близко к ней, и значительных изменений положения по направлениям других не будет.
у меня ест ьвот такой код
import React, { RefObject, useCallback, useEffect, useRef, useState } from 'react';
import { ContextMenu } from 'primereact/contextmenu';
import {
Tree,
TreeCheckboxSelectionKeys,
TreeExpandedEvent,
TreeNodeClickEvent,
TreeNodeDoubleClickEvent,
TreeSelectionEvent,
} from 'primereact/tree';
import { CustomTreeNode, HotKeyParams, isCustomTreeNode } from '../types';
import { ObjectEntity } from '@tecon/shared-objects-client';
import { TreeNode } from 'primereact/treenode';
import { useObjectTree } from '../hooks/objectTree-hook';
import { FieldName, HotKeys } from '../constants';
interface Props {
sources: Array;
selectionMode: 'checkbox' | 'single';
onSelectObject: (object: TreeCheckboxSelectionKeys | string | null) => void;
loading?: boolean;
onDoubleNodeClick?: (object: string | null) => void;
searchText?: string;
affiliation?: string;
contextMenuRef?: RefObject | null;
setNodeKey?: (key: string | undefined) => void;
externalSelectedObject?: string | null;
types?: Array;
onDragStart?: (node: CustomTreeNode, event: React.DragEvent) => void;
onFinishTreeBuild?: () => void;
expandedObjects?: string[];
onKeyPress?: (event: KeyboardEvent) => void;
overriddenKeyPress?: string[];
hotKeyFromContextMenu?: HotKeyParams | null;
propagateSelection?: boolean;
onClickNodeInCheckboxMode?: (selectedObjectId: string | undefined) => void;
}
/**
Компонент дерева
@constructor
@param sources — источники данных
@param selectionMode — режим выбора узлов в дереве
@param onSelectObject — обрабатывает выбранный объект(ы)
@param loading — состояние лоадера
@param searchText — тест поиска по дереву
@param affiliation — принадлежность объектов (объекты, документы и т.п.)
@param contextMenuRef — ссылка на контекстное меню
@param setNodeKey — устанавливает id, выбранного узла для открытия контекстного меню
@param externalSelectedObject — выбранный из вне объект
@param onDoubleNodeClick — функция обработки двойного клика по узлу
@param onDragStart — функция обработки начала переноса объекта
@param onFinishTreeBuild — функция обработки завершения построения дерева
@param expandedObjects — развернутые узлы
@param onKeyPress — функция обработки нажатия клавиш
@param overriddenKeyPress — переопределяемые клавиши
@param hotKeyFromContextMenu - нажатая кнопка из контекстного меню, отвечающая за раскрытие узла
@param propagateSelection - рекурсивное выделение дочерних элементов при выборе родителя
@param onClickNodeInCheckboxMode - выбор узла в режиме checkbox
/
const TreeComponent = ({
sources,
selectionMode,
onSelectObject,
loading,
searchText,
affiliation,
contextMenuRef,
setNodeKey,
externalSelectedObject,
onDoubleNodeClick,
onDragStart,
onFinishTreeBuild,
expandedObjects,
onKeyPress,
overriddenKeyPress,
hotKeyFromContextMenu,
propagateSelection = false,
onClickNodeInCheckboxMode,
}: Props) => {
/ * Состояние для хранения объектов дерева */
const [objects, setObjects] = useState<CustomTreeNode[]>();
Show full message · 1,308 lines Assistant2024-11-18 07:54 UTC Copy response
Чтобы автоматически прокрутить дерево до уровня открытого узла при его разворачивании, можно использовать метод, который вычисляет позицию узла и прокручивает контейнер до этой позиции. В примере ниже продемонстрировано, как можно это реализовать в компоненте TreeComponent с помощью рефа на узлы и функции scrollIntoView.
Шаги для реализации:
Добавьте рефы к узлам дерева: Создайте реф для каждого узла, чтобы иметь возможность обращаться к DOM-элементам узлов для получения их позиции и выполнения прокрутки.
Прокрутка до выбраного узла: Используя scrollIntoView, прокрутите контейнер так, чтобы узел выбранного элемента стал видимым.
Измените код в TreeComponent для отслеживания и прокрутки: Ниже представлен пример изменений в коде компонента TreeComponent.
Пример кода:
отличия ребейз от мердж в гите
Assistant2024-11-18 08:19 UTC Copy response
В системах контроля версий, таких как Git, rebase и merge — это два разных подхода к интеграции изменений из одной ветки в другую. Вот основные отличия между ними:
Merge (слияние):
Создание коммита слияния : Когда вы выполняете git merge, создается специальный коммит слияния, который объединяет историю изменений из двух веток. История обеих веток сохраняется, и возникшая из этого структура называется DAG (Directed Acyclic Graph).
Сохранение истории : История коммитов каждой ветки остается неизменной и отображается так, как она была изначально. Это позволяет сохранить полный контекст разработки.
Коммит с несколькими родителями : Коммит слияния имеет два родителя: один из текущей ветки и другой из объединяемой. Он служит связующим звеном между ними.
Удобство использования : merge часто предпочтителен, когда важно сохранить всю историю изменений. Это позволяет легче отслеживать, как конкретные изменения были внесены и кто их выполнил.
Rebase (перебазирование):
Переписывание истории : git rebase переписывает историю коммитов из одной ветки поверх другой. Коммиты размещаются в линии, как если бы они были сделаны поочередно.
Линейная история : После ребейза история выглядит более прямолинейной, что упрощает её понимание. Нет коммитов слияния, и все изменения находятся на одной прямой.
Изменение идентификаторов коммитов : Так как история переписывается, идентификаторы (SHA) всех коммитов, которые были передвинуты, изменяются.
Риски : Если изменения уже были запушены и видны другим, выполнение rebase может привести к проблемам, так как древняя и новая истории между собой несовместимы. Поэтому rebase лучше использовать для личной ветки или на стадии, когда изменения еще не были сделаны общедоступными.
Организационные особенности : rebase удобен, когда необходимо сохранить историю в чистом и линейном виде, что может быть полезным, например, перед интеграцией изменений в основную ветку проекта.
В общем:
Используйте merge, чтобы сохранить историю разработки со всеми промежуточными коммитами и сливанием изменений (что полезно в командной работе).
Используйте rebase, если хотите сделать историю чище и линейнее, но помните об опасности переписывания публичной истории.
Каждый подход имеет свои преимущества и идеален в разных ситуациях. Важно выбирать метод в зависимости от того, как вы организуете рабочий процесс и какие у вас задачи.
у меня есть вот такой код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
setSelectedConnector(null);
}
};
code Copy code
window.addEventListener('keydown', handleKeyDown);
// Clean up the event listener when the component unmounts
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
}, [setSelectedConnector]);
const handleConnectorClick = (e: KonvaEventObject) => {
if (props.isExporting) {
return;
}
e.evt.stopPropagation(); // Останавливаем распространение события
console.log('connector', props.id, 'clicked');
Show full message · 174 lines Assistant2024-11-18 08:28 UTC Copy response
Чтобы изменить логику создания связей между коннекторами по вашим требованиям, нам нужно обновить обработчики событий для отслеживания нажатий и удержания кнопки мыши, а также отпуска кнопки мыши. Мы также уберём обработку клавиши "Esc" для сброса выделенного коннектора. Вот как можно это сделать:
Активация режима создания связи : Установить выбранный коннектор при нажатии и удержании левой кнопки мыши.
Создание связи : Установить соединение при отпускании левой кнопкой мыши над коннектором-приемником.
Деактивация режима создания связи : Удалять выбранный коннектор при отпускании кнопки мыши, если не было установлено соединение.
Вот пример изменения вашего компонента SnapConnector:
но это не сработало
теперь связь просто не добавляется
ни при кликах ни при перетягивании
все подходящие дл ясоединения коннекторы горят подсвеченными кружками и ничего не происходит
Assistant2024-11-18 08:35 UTC Copy response
Мне жаль, что предложенное решение не сработало. Давайте пересмотрим логику и попробуем подход, который будет соответствовать вашим требованиям. Чтобы реализовать взаимодействие с использованием "нажатия и удержания" (drag-and-drop) для создания связи, нужно следовать более точному алгоритму обработки событий мыши.
Вот обновленная логика:
Начать соединение : Когда пользователь нажимает и удерживает левую кнопку мыши на исходном коннекторе (зеленый круг), мы начинаем операцию создания соединения.
Отпустить кнопку мыши : Когда пользователь отпускает кнопку мыши на приемном коннекторе, устанавливается связь.
Сброс выделенного коннектора : Если кнопка мыши отпущена в любом другом месте, "режим соединения" отключается (аналогично escape).
Обновленный код:
у меня есть вот такой код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting) {
return;
}
code Copy code
e.evt.stopPropagation(); // Останавливаем распространение события
// console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
Show full message · 635 lines Assistant2024-11-18 08:43 UTC Copy response
Судя по предоставленному коду и описанию проблемы, существует несколько возможных причин, почему перемещается весь примитив, когда вы пытаетесь "потянуть" только коннектор:
События перетаскивания на уровне группы : Скорее всего, события перетаскивания обрабатываются на уровне группы (Group), что приводит к перемещению всего компонента. Коннектор, как часть группы, "сводит" к тому же обработчику перетаскивания.
Пропса draggable : Пропс draggable задаётся для компонента SnapGroup, что делает его перетаскиваемым. Коннектор в этой ситуации также становится перетаскиваемым вместе с группой.
Чтобы исправить это, необходимо изменить логику так, чтобы можно было различать и обрабатывать действия с коннекторами и другими элементами в пределах одного примитива отдельно. Вот несколько шагов, которые могут помочь:
Решение:
Отделение логики перетаскивания для коннекторов : Сделайте так, чтобы события onDragStart, onDragMove и onDragEnd не вызывались на уровне соединителей внутри группы.
Конкретизация управлением событиями для коннектора : Сделайте коннекторы интерактивными элементами, которые не будут пропускать события на уровень группы.
Вот код, чтобы сделать это:
у меня есть группа объектов. это ппимитив. вот она
import React, { forwardRef } from 'react';
import { Group } from 'react-konva';
import withSnap from '../hoc/withSnap';
import { GroupPrimitive } from '../models/groups/groupPrimitive';
import Konva from 'konva';
import RenderPrimitiveByType from './RenderPrimitiveByType';
interface SnapGroupProps extends GroupPrimitive {
isExporting?: boolean;
}
const SnapGroup = forwardRef<Konva.Group, SnapGroupProps>((props, ref) => {
return (
props.primitives && (
<Group {...props} ref={ref}>
{Array.from(props.primitives.values())
.sort((a, b) => a.order - b.order)
.map((x) => (
))}
)
);
});
// Устанавливаем displayName для SnapGroup
SnapGroup.displayName = 'SnapGroup';
export default withSnap<GroupPrimitive, Konva.Group>(SnapGroup);
еще у меня есть вот такой хук
он используется для всех объектов на канве
import { useEffect, useRef, useState } from 'react';
import Konva from 'konva';
import { useGridStore, useSelectionStore } from '../store';
import { useDocumentContext } from './useDocumentContext';
import { Subject } from 'rxjs';
import { Primitives } from '../models/types';
import { IPoint } from '../models/infrastucture/point';
import { PrimitiveBase } from '../models/base/primitives.base';
import { useUpdateConnectors } from './useUpdateConnectors';
import Node = Konva.Node;
import Stage = Konva.Stage;
import { TextPrimitive } from '../models/primitives/primitives';
import { EditorPrimitives } from '../models/primitives/enums/editor-primitives';
const positionSource = new Subject<{ id: string | number; x: number; y: number }>();
const orderSource = new Subject<{ pageId: string | number; primitives: Map<string | number, Primitives> }>();
const transformSource = new Subject<{
id: string | number;
pageId: string | number;
scaleX: number;
scaleY: number;
rotation: number;
transformTextSize: boolean;
}>();
const connectorPositionSource = new Subject<Map<string | number, IPoint>>();
export const position= p o s i t i o n S o u r c e . a s O b s e r v a b l e ( ) ; e x p o r = orderSource.asObservable();
export const transform = connectorPositionSource.asObservable();
Show full message · 493 lines Assistant2024-11-18 10:20 UTC Copy response
Чтобы избежать события перетаскивания для всей группы, когда вы начинаете перетаскивание с коннектора, вы можете использовать метод остановки распространения событий в обработчике onDragStart коннектора. Это обеспечит, что событие не будет "подниматься" и не вызовет перетаскивание группы.
Шаги:
Отключите функцию перетаскивания группы, если взаимодействие началось с коннектора.
Разделение событий перетаскивания : Используйте остановку распространения события в коннекторе, чтобы предотвратить перехват события на уровне группы.
Вот как можно это сделать:
у меня есть вот такой код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject) => {
console.log('llllllllllll');
code Copy code
if (props.isExporting) {
return;
}
e.evt.stopPropagation(); // Останавливаем распространение события
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject) => {
console.log('wwwwwwwww');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
Show full message · 161 lines Assistant2024-11-18 12:03 UTC Copy response
Для реализации предварительного просмотра связи при перетаскивании коннектора, вы можете создать динамическую линию или стрелку на сцене, которая будет отображаться при нажатии и удерживании кнопки мыши, и изменяться по мере перемещения мыши. Подход включает в себя использование состояния для отслеживания координат динамической линии и обновление этих координат при перемещении мыши.
Вот как вы можете это реализовать:
Создайте состояние для хранения позиции предварительного просмотра линии.
Добавьте обработчики для onMouseMove и onMouseDown для обновления и сброса координат линии.
Рендерьте линию в компоненте, используя Line из react-konva, и обновляйте её по мере движения мыши.
Вот обновленный пример вашего кода:
у меня есть вот такой код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting) {
return;
}
code Copy code
// Останавливаем распространение события
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject) => {
console.log('!!!!!!!!!!!!!!!!!');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
Show full message · 160 lines Assistant2024-11-18 12:40 UTC Copy response
Проблема заключается в том, что вы не обрабатываете событие отпускания мыши, если конечная точка линии не находится на другом коннекторе. Эффективно вы можете не видеть события mouseup на коннекторе, потому что мышь отпускается не на этом элементе.
Вот список шагов, чтобы исправить это:
Отслеживайте событие mouseup на окне или сцене (вместо отдельного элемента). Это гарантирует, что вы всегда получите событие mouseup, даже если мышь была отпущена вне пределов вашего коннектора.
Обновите обработчик mouseup, чтобы сбросить состояние предварительно выбранного коннектора.
Вот как можно реализовать это решение:
у меня есть вот такой код
import React, { useCallback, useEffect, 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 } 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';
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 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] });
}
Show full message · 1,151 lines Assistant2024-11-19 06:43 UTC Copy response
Для реализации превью линии связи во время перетаскивания в вашем приложении, не сохраняющейся до отпускания мыши, нам следует добавлять временную линию в компонент GraphEditor. Эта линия будет обновляться по мере перемещения мыши и исчезать после того, как мышь отпущена.
Шаги для реализации:
Создать состояние для хранения стартовой и текущей позиций линии предварительного просмотра.
Добавить события mousedown, mousemove, и mouseup для управления состоянием линии.
Вот пример, как это можно сделать:
у меня етс ьвот такой код
import React, { useCallback, useEffect, 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 } 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';
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 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] });
}
Show full message · 423 lines Assistant2024-11-19 06:50 UTC Copy response
Для реализации предварительного просмотра линии при перетаскивании, который не сохраняется до отпускания мыши, необходимо:
Создать состояние для отслеживания начальной и текущей точки предварительного просмотра линии.
Регистрировать обработчики событий mousedown, mousemove и mouseup для управления состоянием линии.
Отображать линию на сцене только в процессе перетаскивания, а не сохранять ее точки, пока не будет отпущена мышь.
Вот пример, как это можно реализовать:
Обновление SnapConnectionLine
Добавьте логику для предварительного просмотра внутри вашего компонента SnapConnectionLine:
Show full message · 456 lines я хочу добавить сюда отображение превью связи
для этого мне нужно отслеживать движение мыши после нажатия на коннектор пока я перетаскиваю связь
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
/**
Сбрасывает выбранный коннектор, если левая кнопка мыши была отпущена
*/
useEffect(() => {
// Добавление глобального слушателя
const handleGlobalMouseUp = () => {
// Сбрасываем выбранный коннектор
if (selectedConnector) {
setSelectedConnector(null);
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
code Copy code
// Удаление глобального слушателя при размонтировании
code Copy code
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
};
}, [selectedConnector, setSelectedConnector]);
/**
Обработчик нажатия левой клавиши мыши по коннектору
*/
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
Show full message · 195 lines Assistant2024-11-19 07:56 UTC Copy response
Чтобы добавить отображение предварительной линии связи при перетаскивании мыши после нажатия на коннектор, вы можете использовать следующее решение:
Создайте состояние для отслеживания начальной и конечной позиции линии предварительного просмотра.
Добавьте обработчики событий mousemove и mouseup, чтобы обновлять позицию линии по мере движения мыши.
Отображайте эту временную линию, используя компонент Line из react-konva.
Вот пример, как можно это реализовать:
Show full message · 236 lines у меня есть овт такоф код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
// const { previewConnection, setPreviewConnection } = useSelectionStore();
const [previewConnection, setPreviewConnection] = useState<number[]>([]);
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
/**
Сбрасывает выбранный коннектор, если левая кнопка мыши была отпущена
*/
useEffect(() => {
const handleMouseMove = () => {
// if (!previewLine || previewLine.length < 2) return;
const stage = circleRef.current?.getStage();
if (!stage) return;
// circleRef.current.getAbsolutePosition()
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
const newEndPoint = [
pointerPosition.x,
pointerPosition.y,
// (pointerPosition.x - stage.x()) / stage.scaleX(),
// (pointerPosition.y - stage.y()) / stage.scaleY(),
];
if (!selectedConnector) return;
setPreviewConnection([selectedConnector.position.x, selectedConnector.position.y, ...newEndPoint]);
};
code Copy code
// Добавление глобального слушателя
Show full message · 225 lines Assistant2024-11-19 08:40 UTC Copy response
Проблема, с которой вы столкнулись, возникает из-за того, что каждый экземпляр компонента SnapConnector самостоятельно отслеживает движение мыши и рисует свою собственную линию предварительного просмотра. Чтобы решить эту проблему, желательно отслеживать активный предварительный просмотр линии на более высоком уровне, таким образом, чтобы только один экземпляр линии предварительного просмотра отображался, когда пользователь активирует его.
Вот как это можно исправить:
Используйте контекст или глобальное состояние для отслеживания линии предварительного просмотра , что позволит вам иметь одну общую линию, контролируемую извне.
Измените соответствующим образом компонент SnapConnector, чтобы он устанавливал состояние линии предварительного просмотра только когда он активен . Это предотвратит рендеринг множества линий предварительного просмотра.
Ниже приведен пример:
Контекст для управления состоянием предварительного просмотра
Создайте новый файл, например, ConnectionPreviewContext.js:
javascript Copy code
import React, { createContext, useContext, useState } from 'react';
const ConnectionPreviewContext = createContext();
export const ConnectionPreviewProvider = ({ children }) => {
const [previewConnection, setPreviewConnection] = useState([]);
return (
<ConnectionPreviewContext.Provider value={{ previewConnection, setPreviewConnection }}>
{children}
</ConnectionPreviewContext.Provider>
);
};
export const useConnectionPreview = () => {
return useContext(ConnectionPreviewContext);
};
Обновленный SnapConnector
Используйте контекст для управления состоянием предварительного просмотра линии:
как сделать эту линю пунктирной?
Assistant2024-11-19 09:03 UTC Copy response
Чтобы сделать линию пунктирной при использовании компонента Line из react-konva, вы можете использовать свойство dash. Это свойство принимает массив чисел, который определяет чередование длин сплошных и пробельных сегментов линии.
Вот пример, как это может быть реализовано:
jsx Copy code
<Line
points={previewConnection}
stroke='grey'
strokeWidth={1}
dash={[4, 4]} // Определяет пунктирную линию
/>
Объяснение:
dash : Это свойство принимает массив чисел, где каждое число представляет собой длину чередующегося сегмента линии в пикселях. Например, [4, 4] определяет сегменты длиной 4 пикселя и такие же пробелы между ними. Вы можете отрегулировать значения по своему усмотрению: увеличение первого числа сделает длиннее сплошные сегменты, увеличение второго числа - длину пробелов.
Цвет и ширина линии : Параметры stroke и strokeWidth отвечают за цвет и ширину линии соответственно. Вы можете настроить их по своему усмотрению.
Это позволит создать визуальный эффект пунктирной линии.
у меня есть вот такой код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const { previewConnection, setPreviewConnection } = useSelectionStore();
// const [previewConnection, setPreviewConnection] = useState<number[]>([]);
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
/**
Сбрасывает выбранный коннектор, если левая кнопка мыши была отпущена
*/
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
const newEndPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
if (!selectedConnector) return;
previewConnectionSource.next({
points: [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
...newEndPoint,
],
});
};
Show full message · 229 lines Assistant2024-11-19 10:26 UTC Copy response
Ваш код использует Subject из библиотеки RxJS для управления состоянием линии предварительного просмотра, но сама линия не исчезает при отпускании кнопки мыши. Давайте проверим несколько моментов, которые могут быть причиной этой проблемы, и как можно это исправить:
Проверьте, где происходит рендеринг линии :
Убедитесь, что линия предварительного просмотра действительно рендерится в компоненте SnapConnector или в другом месте на основе полученных данных из previewConnection$.
Сброс состояния предварительного просмотра :
Обязательно сбрасывайте состояние предварительного просмотра в handleGlobalMouseUp или handleMouseUp с помощью функции next() на Subject.
Отображение линии :
Убедитесь, что линия предварительного просмотра рендерится только при наличии данных в state.previewConnection.
Исправленный код:
Вот пример того, как может выглядеть исправление для обеспечения сброса линии предварительного просмотра:
Show full message · 210 lines у менч есть код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
// Строит превью связи при перемещении указателя мыши
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector) {
return;
}
const firstPoint = [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewConnectionSource.next({
points: [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint],
});
};
Show full message · 230 lines Assistant2024-11-19 10:49 UTC Copy response
Чтобы сделать так, чтобы конечный коннектор подсвечивался, когда наводят на него указатель мыши, вы можете использовать метод изменения цвета заливки коннектора при событии onMouseEnter и возвращать его в исходное состояние при onMouseLeave. Это довольно типичный паттерн для работы с hover-эффектами в React и react-konva.
Вот пример, как можно это реализовать:
Show full message · 207 lines TS2304: Cannot find name setHovered
Assistant2024-11-19 10:56 UTC Copy response
Ошибка TS2304: "Cannot find name 'setHovered'" указывает на то, что имя setHovered не определено. Скорее всего, проблема связана с тем, что вы забыли определить hovered и setHovered с помощью хука useState.
Для исправления проблемы:
Убедитесь, что у вас правильно импортирован useState.
Определите состояние hovered, используя useState.
Вот пример исправленного кода:
Show full message · 210 lines у меня есть вот такой код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [hovered, setHovered] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
// Строит превью связи при перемещении указателя мыши
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector) {
return;
}
const firstPoint = [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewConnectionSource.next({
points: [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint],
});
};
Show full message · 460 lines Assistant2024-11-19 11:20 UTC Copy response
Для реализации динамического обновления вашей линии предварительного просмотра (preview line), чтобы она соответствовала реализации "окончательной" линии при наведении на конечный коннектор, вы можете использовать следующее решение:
Определите логику для переключения между этими двумя висуализми : визуализация "в воздухе" и визуализация при наведении на коннектор.
Используйте функцию calculateLinePoints для обработки и получения координат линии, когда наводите на коннектор .
Вот пример того, как вы можете это сделать:
Show full message · 241 lines у меня есть код
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
import { calculateLinePoints } from '../utils/calculateLinePoints';
import { getObstacles } from '../utils/getObstacles';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [pointOnTargetConnector, setPointOnTargetConnector] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
// Строит превью связи при перемещении указателя мыши
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector || !circleRef.current) {
return;
}
const fromAbsolute = selectedConnector.position;
const toAbsolute = {
x: (pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
y: (pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
};
let previewPoints;
console.log('!!!!!!!!!!!', pointOnTargetConnector);
if (pointOnTargetConnector) {
// Используем calculateLinePoints, если находимся над другим коннектором
previewPoints = calculateLinePoints(
fromAbsolute,
toAbsolute,
selectedConnector.id,
props.id,
stageInteraction.scale,
stageInteraction.point,
getObstacles(circleRef.current.getLayer()),
);
} else {
// Визуализация в "воздухе"s
const firstPoint = [
// (selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewPoints = [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint];
}
previewConnectionSource.next({
points: previewPoints,
});
};
Show full message · 264 lines Assistant2024-11-19 11:54 UTC Copy response
Если pointOnTargetConnector становится true, когда курсор находится над конечным коннектором и коннектор подсвечивается желтым, но это состояние никогда не используется в расчете координат линии при построении линии, вероятно, происходит синхронизационная ошибка или неточное управление состоянием в хуках событий.
Учитывая ваш код, вот несколько возможных причин и решений для этой проблемы:
Асинхронность состояния : В setState в React обновление состояния является асинхронным. Поэтому, если вы используете pointOnTargetConnector в том же эффекте, в котором устанавливаете его, возможно, React еще не обновил это состояние к моменту проверки.
Использование useEffect без зависимостей : Если вы проверяете состояние pointOnTargetConnector в useEffect, необходимо убедиться, что зависимость pointOnTargetConnector добавлена в массив зависимостей. Это обеспечит повторное выполнение useEffect при изменении pointOnTargetConnector.
Текущее состояние компонента : Проверьте, что состояние изменяется и используется в компоненте корректно, возможно, замыкание или потеря справочной ссылки на текущее состояние.
Вот небольшой пример конструктивного подхода:
Show full message · 229 lines Not yet included in a published release.
Turns (21) 1 на одной высоте летит вертолет. он вылетел из питера. пролетел на юг 500 км. зат 2 на одной высоте летит вертолет. он вылетел из питера. пролетел на север 500 км. 3 а если учитывать кривизну планеты? 4 у меня ест ьвот такой код import React, { RefObject, useCallback, useEffect, use 5 отличия ребейз от мердж в гите 6 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 7 но это не сработало теперь связь просто не добавляется ни при кликах ни при пере 8 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 9 у меня есть группа объектов. это ппимитив. вот она import React, { forwardRef } 10 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 11 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 12 у меня есть вот такой код import React, { useCallback, useEffect, useRef, useSta 13 у меня етс ьвот такой код import React, { useCallback, useEffect, useRef, useSta 14 я хочу добавить сюда отображение превью связи для этого мне нужно отслеживать дв 15 у меня есть овт такоф код import React, { forwardRef, useEffect, useRef, useStat 16 как сделать эту линю пунктирной? 17 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 18 у менч есть код import React, { forwardRef, useEffect, useRef, useState } from ' 19 TS2304: Cannot find name setHovered 20 у меня есть вот такой код import React, { forwardRef, useEffect, useRef, useStat 21 у меня есть код import React, { forwardRef, useEffect, useRef, useState } from ' /** Состояние для хранения объектов дерева после фильтрации */
const [filteredTree, setFilteredTree] = useState<CustomTreeNode[]>();
/** Состояние для управления выбранными вершинами */
const [selectedKeys, setSelectedKeys] = useState<string | TreeCheckboxSelectionKeys | null>(null);
/** Состояние для управления вершиной, на которой было открыто меню */
const [selectedNodeKey, setSelectedNodeKey] = useState<string | undefined>(undefined);
/** Состояние для управления развернутыми узлами */
const [expandedKeys, setExpandedKeys] = useState<Record<string, boolean>>();
/** Ссылка для управления меню */
const contentTreeRef = useRef(null);
/** Хук для работы с деревом */
const tree = useObjectTree();
const expandedKeysBeforeFiltration = useRef<Record<string, boolean> | null>(null);
/**
Выполняет восстановление состояния при монтировании компонента
*/
useEffect(() => {
restoreScrollPosition();
const restoredKeys = affiliation && tree.restoreExpandedKeys(affiliation);
if (restoredKeys) setExpandedKeys(restoredKeys);
}, []);
Восстанавливает положение скролла после перезагрузки
*/
const restoreScrollPosition = () => {
const savedScrollPosition = affiliation ? localStorage.getItem(scrollPosition${affiliation}) : undefined;
if (savedScrollPosition && contentTreeRef.current) {
contentTreeRef.current.scrollTop = parseInt(savedScrollPosition, 10);
}
};
Восстанавливает положение скролла
*/
useEffect(() => {
restoreScrollPosition();
}, [filteredTree]);
Осуществляет первоначальную инициализацию дерева
*/
const initializeTree = useCallback(async () => {
expandedKeysBeforeFiltration.current = {};
setExpandedKeys({});
code Copy code
if (sources.length > 0) {
code Copy code
const newTree = await tree.buildTree(sources);
if (!newTree) {
onFinishTreeBuild?.();
return;
}
setObjects(newTree);
setFilteredTree(newTree);
restoreScrollPosition();
onFinishTreeBuild?.();
} else {
onFinishTreeBuild?.();
setFilteredTree([]);
}
Сворачивает узлы
@param nodes - узлы дерева
*/
const collapseNodes = (nodes?: CustomTreeNode[]) => {
return nodes?.map((node) => {
node.expanded = false;
if (node.children?.length) {
collapseNodes(node.children);
}
return node;
});
};
Устанавливает узел выбранным
*/
useEffect(() => {
if (!externalSelectedObject) {
return;
}
setSelectedKeys(externalSelectedObject);
}, [externalSelectedObject]);
Разворачивает узлы
*/
useEffect(() => {
if (!expandedObjects) {
return;
}
setExpandedKeys((expanded) => ({
...expanded,
...expandedObjects.reduce((acc, key) => ({ ...acc, [key]: true }), {}),
}));
}, [expandedObjects]);
Регистрация обработчика для нажатия клавиш
*/
useEffect(() => {
if (!overriddenKeyPress || overriddenKeyPress.length === 0) {
return;
}
pressKeyHolder();
}, []);
useEffect(() => {
if (!hotKeyFromContextMenu) {
return;
}
code Copy code
handleKeyDown(hotKeyFromContextMenu);
}, [hotKeyFromContextMenu]);
/**
Обработчик нажатия клавиш
*/
const pressKeyHolder = () => {
const handleKeyPress = (event: KeyboardEvent) => {
if (!overriddenKeyPress?.includes(event.key)) {
return;
}
onKeyPress?.(event);
event.stopPropagation();
event.returnValue = false;
};
window.addEventListener('keydown', handleKeyPress);
return () => {
window.removeEventListener('keydown', handleKeyPress);
};
};
Обрабатывает введенные данные в поиск
@param searchText - поисковый текст
*/
const handleFilter = useCallback(
(searchText: string) => {
if (searchText?.length > 0) {
if (objects) {
const filteredTree = tree.filterNodes(objects, searchText);
setSelectedKeys(null);
setFilteredTree(collapseNodes(filteredTree));
}
} else {
setFilteredTree(collapseNodes(objects));
}
},
[searchText],
);
useEffect(() => {
if (!affiliation || !expandedKeysBeforeFiltration || !expandedKeys) {
return;
}
code Copy code
if (filteredTree && searchText && searchText?.length > 0) {
const newExpandedKeys = getAllExpandedKeys(filteredTree, {}) ?? {};
const previousKeysWithoutCurrentOnes = newExpandedKeys
? Object.keys(expandedKeys).filter((key) => !Object.keys(newExpandedKeys).includes(key))
: null;
expandedKeysBeforeFiltration.current =
previousKeysWithoutCurrentOnes?.reduce(
(acc, key) => {
acc[key] = true;
return acc;
},
{} as Record<string, boolean>,
) ?? {};
setExpandedKeys(newExpandedKeys);
tree.putExpandedKeysInLocalStorage({ ...newExpandedKeys, ...expandedKeysBeforeFiltration.current }, affiliation);
} else {
setExpandedKeys({ ...expandedKeys, ...expandedKeysBeforeFiltration.current });
tree.putExpandedKeysInLocalStorage({ ...expandedKeys, ...expandedKeysBeforeFiltration.current }, affiliation);
}
Возвращает коллекцию раскрытых ключей массива узлов
@param nodes - массив узлов
@param keys - коллекция раскрытых узлов
*/
const getAllExpandedKeys = (nodes: CustomTreeNode[], keys: Record<string, boolean>) => {
for (const node of nodes) {
if (node.children && node.children.length > 0) {
keys[node.key as string] = true;
getAllExpandedKeys(node.children, keys);
}
}
return keys;
};
useEffect(() => {
initializeTree().catch(console.error);
code Copy code
const restoredKeys = tree.restoreExpandedKeys(affiliation);
if (restoredKeys) setExpandedKeys(restoredKeys);
}, [initializeTree, sources]);
Обрабатывает введенные данные в поиск
*/
useEffect(() => {
if (searchText !== undefined) {
handleFilter(searchText);
}
}, [handleFilter, searchText]);
Рендерит название узла
@param node
*/
const nodeTemplate = (node: TreeNode) => {
if (isCustomTreeNode(node)) {
const className = flex p-2 ml-2 border-round-sm text-left;
const handleDragStart = (e: React.DragEvent) => {
onDragStart?.(node as CustomTreeNode, e);
};
return (
code Copy code
return <></>;
Запоминает раскрытые узлы
@param e
*/
const onToggle = (e: TreeExpandedEvent) => {
if (affiliation) {
tree.putExpandedKeysInLocalStorage(e.value, affiliation);
}
setExpandedKeys(e.value);
};
Запоминает состояние скролла
*/
const handleScroll = () => {
if (affiliation && contentTreeRef.current) {
localStorage.setItem(scrollPosition${affiliation}, String(contentTreeRef.current.scrollTop?.toString()));
}
};
Устанавливает выбранные ключи узлов
@param e
*/
const handleSelectionChange = (e: TreeSelectionEvent) => {
if (!e.value) {
return;
}
code Copy code
if (selectionMode === 'single') {
code Copy code
setSelectedKeys(e.value as string);
setSelectedNodeKey(e.value as string);
onSelectObject(e.value as string);
} else {
const target = e.originalEvent.target as HTMLInputElement;
//выбор по checkbox
if (
typeof target === 'object' &&
Object.prototype.hasOwnProperty.call(target, 'type') &&
target.type === 'checkbox'
) {
setSelectedKeys(e.value as TreeCheckboxSelectionKeys);
setSelectedNodeKey(e.value as string);
onSelectObject(e.value as TreeCheckboxSelectionKeys);
}
}
Устанавливает выбранный ключ по двойному щелчку
@param e
*/
const handleDoubleClick = (e: TreeNodeDoubleClickEvent) => {
if (e.node.key && selectionMode === 'single') {
setSelectedKeys(e.node.key as string);
onDoubleNodeClick?.(e.node.key as string);
}
};
Управляет нажатием по горячим клавишам
@param hotKey - парраметры нажатой клавиши
*/
const handleKeyDown = (hotKey: HotKeyParams) => {
if (!selectedNodeKey) return;
code Copy code
//Обрабатывает команду РАСКРЫТИЯ коллекции дочерних элементов, выбранного узла
code Copy code
if (hotKey.pressedCtrl && hotKey.key === HotKeys.ARROW_RIGHT) {
setExpandedKeys((prevKeys) => ({
...prevKeys,
[selectedNodeKey]: true,
}));
tree.putExpandedKeysInLocalStorage({ ...expandedKeys, [selectedNodeKey]: true }, affiliation);
}
//Обрабатывает команду СКРЫТИЯ коллекции дочерних элементов, выбранного узла
if (hotKey.pressedCtrl && hotKey.key === HotKeys.ARROW_LEFT) {
if (objects) {
const selectedNode = tree.findNodeByKey(objects, selectedNodeKey);
if (selectedNode && selectedNode.children) {
const newExpandedKeys = { ...expandedKeys };
selectedNode.children.forEach((node) => {
tree.removeAllKeys(node, newExpandedKeys);
});
setExpandedKeys(newExpandedKeys);
tree.putExpandedKeysInLocalStorage(newExpandedKeys, affiliation);
}
}
}
//Обрабатывает команду РАСКРЫТИЯ дочерних элементов, выбранного узла
if (!hotKey.pressedCtrl && hotKey.key === HotKeys.ARROW_RIGHT) {
if (objects) {
const selectedNode = tree.findNodeByKey(objects, selectedNodeKey);
if (selectedNode) {
const allDescendantKeys = tree.getAllKeys(selectedNode);
setExpandedKeys((prevExpandedKeys) => ({
...prevExpandedKeys,
...allDescendantKeys, // Добавляем ключи всех потомков
}));
tree.putExpandedKeysInLocalStorage({ ...expandedKeys, ...allDescendantKeys }, affiliation);
}
}
}
//Обрабатывает команду СКРЫТИЯ дочерних элементов, выбранного узла
if (!hotKey.pressedCtrl && hotKey.key === HotKeys.ARROW_LEFT) {
setExpandedKeys((prevKeys) => {
const updatedKeys: Record<string, boolean> = { ...prevKeys };
delete updatedKeys[selectedNodeKey];
tree.putExpandedKeysInLocalStorage(updatedKeys, affiliation);
return updatedKeys;
});
}
const onNodeClick = (e: TreeNodeClickEvent) => {
const target = e.originalEvent.target as HTMLInputElement;
//выбор по checkbox
if (target.type === 'checkbox') {
return;
}
code Copy code
if (onClickNodeInCheckboxMode) {
onClickNodeInCheckboxMode(e.node.key as string);
}
return (
<div
className='object-tree min-h-full max-h-full min-w-full flex flex-column flex-1 overflow-y-auto'
ref={contentTreeRef}
onScroll={handleScroll}
onKeyDown={(e) => handleKeyDown({ pressedCtrl: e.ctrlKey, key: e.key })}
>
<Tree
dragdropScope={affiliation === FieldName.OBJECTS ? 'editor' : undefined}
value={filteredTree}
selectionMode={selectionMode}
selectionKeys={selectedKeys}
onSelectionChange={(e) => {
handleSelectionChange(e);
}}
onNodeDoubleClick={(e: TreeNodeDoubleClickEvent) => {
handleDoubleClick(e);
}}
onNodeClick={onNodeClick}
emptyMessage='Результаты не найдены'
className='max-h-full md:w-full'
filter={false}
filterMode='lenient'
filterPlaceholder='Найти...'
loading={loading}
nodeTemplate={nodeTemplate}
contextMenuSelectionKey={selectedNodeKey}
onContextMenuSelectionChange={(e) => {
setNodeKey?.(e.value as string);
setSelectedNodeKey(e.value as string);
}}
onContextMenu={(e) => {
contextMenuRef?.current?.show(e.originalEvent);
}}
expandedKeys={expandedKeys}
onToggle={onToggle}
propagateSelectionUp={propagateSelection}
propagateSelectionDown={propagateSelection}
/>
);
};
export default TreeComponent;
при этом данное дерево используется вот тут
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { instance } from '../api.config';
import FilterTemplate from './features/FilterTemplate';
import TreeComponent from './TreeComponent';
import { ObjectEntity, ObjectsClient } from '@tecon/shared-objects-client';
import ContextTreeMenu from './features/ContextTreeMenu';
import { ContextMenu } from 'primereact/contextmenu';
import { TreeCheckboxSelectionKeys } from 'primereact/tree';
import { TreeDialog } from '@tecon/dialogs';
import { DefaultMenuItems, HotKeys, NotificationText } from '../constants';
import { CustomTreeNode, HotKeyParams } from '../types';
import ExpandNodeDarkblueIcon from '@tecon/svg-icons/dist/cjs/icons/ExpandNodeDarkblueIcon';
import CollapseNodeDarkblueIcon from '@tecon/svg-icons/dist/cjs/icons/CollapseNodeDarkblueIcon';
import { MenuItem } from 'primereact/menuitem';
import { SignalRContext, SynchronizationData } from '@tecon/shared-objects-client';
import { useObjectTree } from '../hooks/objectTree-hook';
const ObjectsService = new ObjectsClient(undefined, instance);
interface Props {
types: string[];
affiliation: string;
solutionId: string | undefined;
setSelectedObject: (id: string | null) => void;
setNotification?: (text: string) => void;
externalSelectedObject?: string | null;
setExternalSelectedObject?: (id: string | null) => void;
onDragStart?: (node: CustomTreeNode, event: React.DragEvent) => void;
menuItems?: (DefaultMenuItems | MenuItem)[];
onDoubleNodeClick?: (id: string | null) => void;
onKeyPress?: (event: KeyboardEvent) => void;
overriddenKeyPress?: string[];
openInDetailedTree?: (selectedObjectId: string | undefined) => void;
selectionMode?: 'single' | 'checkbox';
}
Компонент области Объектов
@constructor
@param types — типы объектов
@param affiliation — принадлежность объектов (например, объекты, документы и т.п.)
@param solutionId — идентификатор решения
@param setNotification — функция для отображения уведомлений
@param setSelectedObject — функция для установки выбранного объекта
@param externalSelectedObject — выбранный из вне объект
@param setExternalSelectedObject — устанавливает выбранный из вне объект
@param onDragStart — обработчик начала перетаскивания объекта
@param menuItems — элементы контекстного меню
@param onDoubleNodeClick — обработчик двойного клика по вершине
@param onKeyPress — обработчик нажатия клавиш
@param overriddenKeyPress — переопределяемые клавиши
@param openInDetailedTree - открывает узел и дочернюю иерархию в детализированном древе
@param selectionMode - режим выбора объектов
/
const ObjectsTree = ({
types,
affiliation,
solutionId,
setNotification,
setSelectedObject,
externalSelectedObject,
setExternalSelectedObject,
onDragStart,
menuItems,
onDoubleNodeClick,
onKeyPress,
overriddenKeyPress,
openInDetailedTree,
selectionMode,
}: Props) => {
/ * Состояние для хранения отображаемых объектов */
const [objects, setObjects] = useState<Array>([]);
/** Состояние для управления отображением лоадера */
const [loading, setLoading] = useState(true);
/** Состояние для хранения строки поиска */
const [filterValue, setFilterValue] = useState('');
/** Состояние для хранения id скопированного объекта */
const [copiedObjectId, setCopiedObjectId] = useState<string | undefined>();
/** Состояние для хранения выбранного узла */
const [selectedNodeKey, setSelectedNodeKey] = useState<string | undefined>(undefined);
/** Состояние для хранения разворачиваемых из вне объектов */
const [expandedObjects, setExpandedObjects] = useState<string[]>([]);
/** Состояние для управления отображением модального окна */
const [isVisibleModalWin, setIsVisibleModalWin] = useState(false);
/** Состояние для хранения допустимых дочерних типов */
const [allowedObjectTypes, setAllowedObjectTypes] = useState<ObjectEntity[]>();
/** Ссылка на элемент контекстного меню */
const contextMenuRef = useRef<ContextMenu | null>(null);
const [hotKeyParams, setHotKeyParams] = useState<HotKeyParams | null>(null);
const tree = useObjectTree();
/**
Получает данные объекта с сервера
*/
const getObjects = useCallback(async () => {
if (!solutionId) {
return;
}
setLoading(true);
setFilterValue('');
code Copy code
await ObjectsService.getTree(solutionId, types)
code Copy code
.then((responseData) => {
if (responseData) {
setObjects(responseData);
}
})
.catch(console.error);
// eslint-disable-next-line
Выполняет первоначальное получение данных
*/
useEffect(() => {
getObjects().catch(console.error);
}, [getObjects, solutionId, types]);
Обрабатывает введенные в поиск данные
@param searchText - поисковый текст
*/
const handleFilter = (searchText: string) => {
setFilterValue(searchText);
};
Получает допустимые дочерние типы
*/
const getAvailableObjectTypes = async () => {
if (!solutionId || !selectedNodeKey) {
return;
}
await ObjectsService.getAllowedChildTypes(solutionId, selectedNodeKey)
.then((data) => {
if (data) {
setAllowedObjectTypes(data);
}
})
.catch(console.error);
};
Открывает модальное окно с допустимыми типами для объекта
@param parentId - Идентификатор родителя
*/
const addNewObject = async (parentId?: string) => {
if (!solutionId || !parentId) {
return;
}
await getAvailableObjectTypes();
setIsVisibleModalWin(true);
};
Создает экземпляр при выбранном типе
@param typeId - id типа
*/
const createObject = async (typeId: string | TreeCheckboxSelectionKeys | null) => {
const parentId = selectedNodeKey;
code Copy code
if (!solutionId || !parentId || typeof typeId !== 'string') {
code Copy code
return;
}
await ObjectsService.createObject(solutionId, parentId, typeId)
.then((responseData) => {
if (responseData) {
getObjects();
tree.addExpandedKeyInLocalStorage(parentId, affiliation);
}
})
.catch(console.error);
Копирует выбранные объекты
@param selectedKey - выбранные ключи узлов дерева
*/
const copyObjects = (selectedKey: string | undefined) => {
if (selectedKey) {
setCopiedObjectId(selectedKey);
} else {
setNotification?.(NotificationText.NOTHING_SELECTED);
}
};
Вставляет скопированные данные в узел дерева
@param targetId - выбранный узел для вставки
*/
const pasteObjects = async (targetId?: string) => {
if (solutionId && targetId && copiedObjectId) {
await ObjectsService.duplicateObjects(solutionId, targetId, [copiedObjectId])
.then((responseData) => {
if (responseData.length > 0) {
getObjects();
tree.addExpandedKeyInLocalStorage(targetId, affiliation);
}
//если нельзя вставить объект в выбранный узел
if (responseData.length == 0) {
setNotification?.(NotificationText.NOT_ALLOWED_TO_PASTE);
}
})
.catch(console.error)
.finally(() => setLoading(false));
} else {
setNotification?.(NotificationText.NOTHING_COPIED_TO_PASTE);
}
};
Удаляет выбранные объекты
@param selectedKey - выбранный ключ узла
*/
const deleteObject = async (selectedKey: string | undefined) => {
if (solutionId && selectedKey) {
setLoading(true);
await ObjectsService.deleteObjects(solutionId, [selectedKey])
.then((responseData) => {
if (responseData) {
getObjects();
}
setSelectedObject(null);
})
.catch(console.error)
.finally(() => setLoading(false));
} else {
setNotification?.(NotificationText.NOTHING_SELECTED);
}
};
Устанавливает выбранный узел при открытии контекстного меню
@param key - ключ узла
*/
const setNodeKey = (key: string | undefined) => {
if (key) {
setSelectedNodeKey(key);
}
};
Выбирает объект по id
@param objectId
*/
const selectObject = (objectId: TreeCheckboxSelectionKeys | string | null) => {
if (objectId) {
setSelectedObject(objectId as string);
setSelectedNodeKey(objectId as string);
}
};
Разворачивает все родительские узлы при выборе элемента
*/
useEffect(() => {
if (!(externalSelectedObject && solutionId)) {
return;
}
ObjectsService.getParentsHierarchy(solutionId, externalSelectedObject)
.then(setExpandedObjects)
.catch(console.error);
selectObject(externalSelectedObject || null);
setExternalSelectedObject?.(null);
}, [externalSelectedObject]);
Создает кастомизированное меню
*/
const createMenuItems = () => {
return menuItems?.map((item) => {
switch (item) {
case DefaultMenuItems.ADD:
return {
label: DefaultMenuItems.ADD,
command: async () => {
await addNewObject(selectedNodeKey);
},
};
case DefaultMenuItems.COPY:
return {
label: DefaultMenuItems.COPY,
command: () => {
copyObjects(selectedNodeKey);
},
};
case DefaultMenuItems.PASTE:
return {
label: DefaultMenuItems.PASTE,
command: async () => {
await pasteObjects(selectedNodeKey);
},
};
case DefaultMenuItems.REMOVE:
return {
label: DefaultMenuItems.REMOVE,
command: async () => {
await deleteObject(selectedNodeKey);
},
};
case DefaultMenuItems.RELOAD:
return {
label: DefaultMenuItems.RELOAD,
command: async () => {
await getObjects();
},
};
case DefaultMenuItems.EXPAND_COLLAPSE:
return {
label: DefaultMenuItems.EXPAND_COLLAPSE,
items: [
{
label: DefaultMenuItems.EXPAND_NODE,
icon: ExpandNodeDarkblueIcon({ width: 24, height: 24 }),
command: () => {
setHotKeyParams({ pressedCtrl: false, key: HotKeys.ARROW_RIGHT });
},
},
{
label: DefaultMenuItems.COLLAPSE_NODE,
icon: CollapseNodeDarkblueIcon({ width: 24, height: 24 }),
command: () => {
setHotKeyParams({ pressedCtrl: false, key: HotKeys.ARROW_LEFT });
},
},
{
label: DefaultMenuItems.EXPAND_CHILD_NODES,
icon: ExpandNodeDarkblueIcon({ width: 24, height: 24 }),
command: () => {
setHotKeyParams({ pressedCtrl: true, key: HotKeys.ARROW_RIGHT });
},
},
{
label: DefaultMenuItems.COLLAPSE_CHILD_NODES,
icon: CollapseNodeDarkblueIcon({ width: 24, height: 24 }),
command: () => {
setHotKeyParams({ pressedCtrl: true, key: HotKeys.ARROW_LEFT });
},
},
],
};
case DefaultMenuItems.SHOW_IN_DETAILED_TREE:
return {
label: DefaultMenuItems.SHOW_IN_DETAILED_TREE,
command: () => {
if (openInDetailedTree && selectedNodeKey) openInDetailedTree(selectedNodeKey);
},
};
case DefaultMenuItems.SEPARATOR:
return {
label: DefaultMenuItems.SEPARATOR,
separator: true,
};
default:
return item;
}
}) as MenuItem[] | undefined;
};
SignalRContext.useSignalREffect(
'SendUpdatedObject',
(id, fullName, order) => {
setObjects((prevState) =>
prevState.map((x) => {
if (x.id != id) {
return x;
}
code Copy code
x.name = fullName;
x.order = order;
return x;
}),
);
console.log(id, fullName, order);
},
[],
SignalRContext.useSignalREffect(
'SendSynchronizationPayload',
(data: SynchronizationData) => {
setObjects((prevState) => {
const removedItemsIds = new Set(data.removedObjects.map((x) => x.id));
const filteredNodes = [...prevState].filter((x) => !removedItemsIds.has(x.id));
code Copy code
for (const addedObject of data.addedObjects) {
const foundedNodeIndex = filteredNodes.findIndex((x) => x.id === addedObject.id);
if (foundedNodeIndex !== -1) {
filteredNodes[foundedNodeIndex] = addedObject;
continue;
}
const parentNode = filteredNodes.find((x) => x.id === addedObject.parentId);
if (!parentNode) {
continue;
}
filteredNodes.push(addedObject);
}
return filteredNodes;
});
},
[],
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Delete') {
if (selectedNodeKey) {
deleteObject(selectedNodeKey).catch((err) => console.error(err));
}
}
};
code Copy code
<ContextTreeMenu contextMenuRef={contextMenuRef} menuItems={createMenuItems()} />
<TreeComponent
sources={objects}
selectionMode={selectionMode || 'single'}
searchText={filterValue}
affiliation={affiliation}
loading={loading}
contextMenuRef={contextMenuRef}
setNodeKey={setNodeKey}
onSelectObject={selectObject}
onDragStart={onDragStart}
onFinishTreeBuild={() => setLoading(false)}
onDoubleNodeClick={onDoubleNodeClick}
externalSelectedObject={externalSelectedObject}
expandedObjects={expandedObjects}
onKeyPress={onKeyPress}
overriddenKeyPress={overriddenKeyPress}
hotKeyFromContextMenu={hotKeyParams}
/>
<TreeDialog
sources={allowedObjectTypes ?? []}
headerTitle={'Выбор типа объекта'}
visible={isVisibleModalWin}
selectionMode={'single'}
setVisible={setIsVisibleModalWin}
onSelectObject={createObject}
/>
</div>
</div>
export default ObjectsTree;
и даьлше во тут
import React, { useEffect, useState } from 'react';
import { FieldName, SeverityNotification } from '../../constants.ts';
import { useGlobalStore } from '../../app/store/globalStore.ts';
import { useObjectStore } from './objectStore.ts';
import ObjectsTree from '../../packages/objects-tree/src/components/ObjectsTree.tsx';
import { CustomTreeNode } from '../../packages/objects-tree/src/types.ts';
import { DefaultMenuItems } from '../../packages/objects-tree/src/constants.ts';
import { MenuItem } from 'primereact/menuitem';
interface Props {
types: Array;
affiliation: FieldName;
}
Компонент области объектов
@constructor
@param types - типы объектов
@param affiliation - принадлежность объектов (объекты, документы и т.п.)
*/
const Objects = ({ types, affiliation }: Props) => {
const solution = useGlobalStore((state) => state.solution);
const setNotification = useGlobalStore((state) => state.setNotification);
const setSelectedObjectId = useObjectStore((state) => state.setSelectedIdObject);
const setSelectedObject = useObjectStore((state) => state.setSelectedObject);
const setDragObjectId = useObjectStore((state) => state.setDragObjectId);
const objectReferenceId = useObjectStore((state) => state.objectReferenceId);
const objectReferenceIdCounter = useObjectStore((state) => state.objectReferenceIdCounter);
const [externalSelectedObject, setExternalSelectedObject] = useState<string | null>(null);
useEffect(() => {
setSelectedObject(null);
setSelectedObjectId(undefined);
}, [solution]);
const handleSetNotification = (text: string) => {
setNotification({
type: SeverityNotification.WARN,
text: text,
});
};
const handleDragStart = (node: CustomTreeNode, e: React.DragEvent) => {
const img = new Image();
img.src = '';
e.dataTransfer.setDragImage(img, 0, 0);
code Copy code
setDragObjectId(node.key);
const menuItems: (DefaultMenuItems | MenuItem)[] = [
DefaultMenuItems.ADD,
DefaultMenuItems.COPY,
DefaultMenuItems.PASTE,
DefaultMenuItems.EXPAND_COLLAPSE,
DefaultMenuItems.RELOAD,
];
if (affiliation === FieldName.OBJECTS) {
menuItems.push(DefaultMenuItems.SHOW_IN_DETAILED_TREE);
}
menuItems.push(DefaultMenuItems.SEPARATOR, DefaultMenuItems.REMOVE);
Открывает узел и иерахию дочерних элементов в детализированном древе
@param selectedObjectId
*/
const openInDetailedTree = (selectedObjectId: string | undefined) => {
if (!selectedObjectId) {
return;
}
setSelectedObject({
id: selectedObjectId,
affiliation: affiliation,
});
};
Обрабатывает выбранный объект
@param id - id выбранного объекта
*/
const selectObject = (id: string | null) => {
setSelectedObjectId(id);
};
Разворачивает и выбирает заданный узел
*/
useEffect(() => {
setExternalSelectedObject(objectReferenceId);
}, [objectReferenceId, objectReferenceIdCounter]);
return (
<ObjectsTree
types={types}
affiliation={affiliation}
solutionId={solution?.id}
setNotification={handleSetNotification}
setSelectedObject={selectObject}
onDragStart={handleDragStart}
onDoubleNodeClick={(e) => setSelectedObject({ id: e!, affiliation: affiliation })}
menuItems={menuItems}
openInDetailedTree={openInDetailedTree}
externalSelectedObject={externalSelectedObject}
setExternalSelectedObject={setExternalSelectedObject}
/>
);
};
и дальше тутimport { TabPanel, TabView, TabViewTabChangeEvent } from 'primereact/tabview';
import { DivId, documentTab, FieldName, objectTab } from '../../constants.ts';
import Objects from '../objects/Objects.tsx';
import { useEffect, useRef, useState } from 'react';
import { useMenuStore } from '../mainMenu/store/menuStore.ts';
Компонент панели документов и объектов
@constructor
*/
const ObjectsTabs = () => {
const [height, setHeight] = useState(0);
const openLeftTabs = useMenuStore((state) => state.openLeftTabs);
const deleteLeftTabs = useMenuStore((state) => state.deleteLeftTabs);
const activeTab = useMenuStore((state) => state.activeTab);
const setActiveTab = useMenuStore((state) => state.setActiveTab);
const closingTab = useRef(false);
useEffect(() => {
setPanelHeight();
code Copy code
// Добавляем обработчик события изменения размера окна
window.addEventListener('resize', setPanelHeight);
// Очищаем обработчик при размонтировании компонента
return () => {
window.removeEventListener('resize', setPanelHeight);
};
// eslint-disable-next-line
useEffect(() => {
const leftSplitter = document.getElementById(DivId.LEFT_SPLITTER);
if (!leftSplitter) {
return;
}
if (openLeftTabs.length === 0) {
leftSplitter.style.display = 'none';
}
if (openLeftTabs.length === 1) {
leftSplitter.style.display = 'flex';
}
setPanelHeight();
// eslint-disable-next-line
}, [openLeftTabs]);
useEffect(() => {
setPanelHeight();
// eslint-disable-next-line
}, [height]);
useEffect(() => {
setPanelHeight();
// eslint-disable-next-line
}, [activeTab]);
/**
Считаем высоту контейнера панели
*/
const setPanelHeight = () => {
const containerHeight = document.getElementById(DivId.OBJECT_TAB_VIEW_PANEL)?.offsetHeight;
const panel = activeTab
? document.getElementById(${DivId.OBJECT_TAB_PANEL}-${activeTab})
: document.getElementById(${DivId.OBJECT_TAB_PANEL}-${0});
code Copy code
containerHeight && setHeight(containerHeight);
code Copy code
if (panel && containerHeight) panel.style.height = containerHeight - 55 + 'px';
Закрывает вкладки на панели
@param index - index элемента массива
*/
const handleOnTabClose = (index: number) => {
closingTab.current = true;
code Copy code
const deletedTab = [...openLeftTabs].splice(index, 1);
code Copy code
switch (deletedTab[0].affiliation) {
case FieldName.OBJECTS:
deleteLeftTabs({ ...objectTab });
break;
case FieldName.DOCUMENTS:
deleteLeftTabs({ ...documentTab });
break;
}
if (index === activeTab) {
setActiveTab(Math.max(0, activeTab - 1)); // Переход на предыдущую вкладку или на первую
} else if (index < activeTab) {
setActiveTab(activeTab - 1); // Сдвигаем индекс, если удалена вкладка перед активной
}
const handleOnTabChange = (e: TabViewTabChangeEvent) => {
// Игнорируем onTabChange, если только что была закрыта вкладка
if (!closingTab.current) {
setActiveTab(e.index);
} else {
closingTab.current = false; // Сбрасываем флаг после игнорирования
}
};
Рендерит иконку закрытия вкладки
@param index - index в массиве табов
*/
const closeTemplate = (index: number) => {
return (
return (
{openLeftTabs.length > 0 && (
{openLeftTabs?.map((tab, index) => {
const headerTitle = tab.affiliation === FieldName.OBJECTS ? 'Объекты' : 'Документы';
return (
<TabPanel
key={${tab.key}}
header={headerTitle}
id={${DivId.OBJECT_TAB_PANEL}-${index}}
closable
closeIcon={() => closeTemplate(index)}
>
);
})}
)}
);
};
export default ObjectsTabs;
и тут
import { Splitter, SplitterPanel } from 'primereact/splitter';
import { DivId } from '../../../constants.ts';
import FieldComponent from '../../../widgets/fieldComponent/FieldComponent.tsx';
import PropertiesTable from '../../../packages/properties/src/components/propertiesTable/PropertiesTable.tsx';
import { useState } from 'react';
import TabsPanel from '../../../widgets/TabsPanel/TabsPanel.tsx';
import ObjectsTabs from '../../../widgets/objectsTabs/ObjectsTabs.tsx';
import { useGlobalStore } from '../../../app/store/globalStore.ts';
import { useObjectStore } from '../../../widgets/objects/objectStore.ts';
Компонент шаблона главной страницы
@constructor
*/
const Layout = () => {
const [sizes] = useState([24, 52, 24]);
const solution = useGlobalStore((state) => state.solution);
const selectedObjectId = useObjectStore((state) => state.selectedObjectId);
return (
<Splitter
className='min-h-full min-w-full'
style={{ height: 'auto', width: 'auto' }}
gutterSize={3}
id={DivId.SPLITTER}
>
<SplitterPanel
size={sizes[0]}
minSize={0}
style={{ maxWidth: '100%', overflow: 'hidden', flexGrow: 0 }}
id={DivId.LEFT_SPLITTER}
>
<SplitterPanel
className='flex flex-column align-items-center justify-content-start flex-grow-1 flex-shrink-1'
size={sizes[1]}
minSize={0}
style={{ maxWidth: '100%', overflow: 'hidden', flex: 1 }}
>
<SplitterPanel
size={sizes[2]}
minSize={0}
style={{ maxWidth: '100%', overflow: 'hidden', maxHeight: '100%', flexGrow: 0 }}
id={DivId.PROPERTY_SPLITTER}
>
<FieldComponent title={'Свойства'}>
{selectedObjectId && }
);
};
когда я разворачиваю узел из вне (в файле tereecomponent функция
/**
Устанавливает узел выбранным
*/
useEffect(() => {
if (!externalSelectedObject) {
return;
}
setSelectedKeys(externalSelectedObject);
}, [externalSelectedObject]);)
мне следует промотать дерево до уровня открытого узла. т.е. дерево находится в скролле
мне надо оупстить скролл до этого самого уровня чтобы отобразить выбранный узел
как мне это сделать
import React, { RefObject, useCallback, useEffect, useRef, useState } from 'react';
import { ContextMenu } from 'primereact/contextmenu';
import {
Tree,
TreeCheckboxSelectionKeys,
TreeExpandedEvent,
TreeNodeClickEvent,
TreeNodeDoubleClickEvent,
TreeSelectionEvent,
} from 'primereact/tree';
import { CustomTreeNode, HotKeyParams, isCustomTreeNode } from '../types';
import { ObjectEntity } from '@tecon/shared-objects-client';
import { TreeNode } from 'primereact/treenode';
import { useObjectTree } from '../hooks/objectTree-hook';
import { FieldName, HotKeys } from '../constants';
interface Props {
sources: Array<ObjectEntity>;
selectionMode: 'checkbox' | 'single';
onSelectObject: (object: TreeCheckboxSelectionKeys | string | null) => void;
loading?: boolean;
onDoubleNodeClick?: (object: string | null) => void;
searchText?: string;
affiliation?: string;
contextMenuRef?: RefObject<ContextMenu> | null;
setNodeKey?: (key: string | undefined) => void;
externalSelectedObject?: string | null;
types?: Array<string>;
onDragStart?: (node: CustomTreeNode, event: React.DragEvent<HTMLDivElement>) => void;
onFinishTreeBuild?: () => void;
expandedObjects?: string[];
onKeyPress?: (event: KeyboardEvent) => void;
overriddenKeyPress?: string[];
hotKeyFromContextMenu?: HotKeyParams | null;
propagateSelection?: boolean;
onClickNodeInCheckboxMode?: (selectedObjectId: string | undefined) => void;
}
const TreeComponent = ({
sources,
selectionMode,
onSelectObject,
loading,
searchText,
affiliation,
contextMenuRef,
setNodeKey,
externalSelectedObject,
onDoubleNodeClick,
onDragStart,
onFinishTreeBuild,
expandedObjects,
onKeyPress,
overriddenKeyPress,
hotKeyFromContextMenu,
propagateSelection = false,
onClickNodeInCheckboxMode,
}: Props) => {
const [objects, setObjects] = useState<CustomTreeNode[]>();
const [filteredTree, setFilteredTree] = useState<CustomTreeNode[]>();
const [selectedKeys, setSelectedKeys] = useState<string | TreeCheckboxSelectionKeys | null>(null);
const [selectedNodeKey, setSelectedNodeKey] = useState<string | undefined>(undefined);
const [expandedKeys, setExpandedKeys] = useState<Record<string, boolean>>();
const contentTreeRef = useRef<HTMLDivElement>(null);
const nodeRefs = useRef<Record<string, HTMLDivElement>>({});
const tree = useObjectTree();
const expandedKeysBeforeFiltration = useRef<Record<string, boolean> | null>(null);
// Функция для прокрутки к выбранному узлу
useEffect(() => {
if (externalSelectedObject) {
setSelectedKeys(externalSelectedObject);
const nodeRef = nodeRefs.current[externalSelectedObject];
if (nodeRef) {
nodeRef.scrollIntoView({ behavior: 'smooth', block: 'center' });
}
}
}, [externalSelectedObject]);
const nodeTemplate = (node: TreeNode) => {
if (isCustomTreeNode(node)) {
return (
<div
ref={(el) => {
if (el && node.key) {
nodeRefs.current[node.key as string] = el;
}
}}
draggable={affiliation === FieldName.OBJECTS}
onDragStart={(e) => onDragStart?.(node as CustomTreeNode, e)}
>
{node.label}
</div>
);
}
return <></>;
};
return (
<div
className='object-tree min-h-full max-h-full min-w-full flex flex-column flex-1 overflow-y-auto'
ref={contentTreeRef}
>
<Tree
value={filteredTree}
selectionMode={selectionMode}
selectionKeys={selectedKeys}
nodeTemplate={nodeTemplate}
// ... ваш остальной код
/>
</div>
);
};
export default TreeComponent;
Рефы на узлы : Рефы используются для хранения ссылок на HTML-элементы узлов дерева. Это позволяет программно управлять их положением.
Прокрутка : Метод scrollIntoView обеспечивает плавную прокрутку и центрирование узла в области просмотра.
Совместимость : Убедитесь в совместимости браузеров с scrollIntoView. Этот метод может иметь различное поведение в разных браузерах.
Теперь, при передаче externalSelectedObject, ваше дерево будет автоматически прокручиваться к соответствующему узлу.
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (!selectedConnector) {
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
} else {
// Проверяем, что коннекторы разных типов
if (selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
}
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={!props.inGroup}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onClick={handleConnectorClick}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
сейчас мне надопоменять логику постороения связи
вот моя задача
Доработать механизм создания связей между коннекторами следующим образом:
code Copy code
Активация режима создания связи должно осуществляться при нажатии и удержании левой кнопки мыши над областью коннектора источника - зеленым кругом (сейчас осуществляется при нажатии плевой кнопкой мыши над областью коннектора - источника).
Создание связи должно осуществляться при отпускании левой кнопки мыши над областью коннектора - приемника - зеленым кругом (сейчас осуществляется при нажатии плевой кнопкой мыши над областью коннектора - приемника).
Деактивация режима создание связи должно осуществляться при отпускании левой кнопки мыши (сейчас осуществляется при нажатии на клавишу "Esc").
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting) {
return;
}
e.evt.stopPropagation(); // Останавливаем распространение события
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
setSelectedConnector(null);
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Основные изменения:
handleMouseDown : Теперь мы активируем режим создания соединения при нажатии и удержании мыши на коннекторе.
handleMouseUp : При отпускании мыши на коннекторе-приемнике создается связь, если выделенный коннектор отличается по типу. В любом случае деактивируется режим соединения.
Убран handleKeyDown : Деактивация режима соединения через нажатие "Escape" убрана из-за изменения логики.
Такой подход позволит вам соответствовать новым требованиям к созданию связей между коннекторами.
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
// Begin connection
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting) {
return;
}
e.evt.stopPropagation(); // Останавливаем распространение события
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
// Finish connection or deactivate
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!selectedConnector || !circleRef.current || e.evt.button !== 0) {
setSelectedConnector(null);
return;
}
const isDifferentType = selectedConnector.connectorType !== props.connectorType;
const isOverTarget = selectedConnector.id !== props.id;
if (isDifferentType && isOverTarget) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Объяснения:
Начало соединения (handleMouseDown) : При нажатии и удержании мыши на исходном коннекторе устанавливали "режим соединения" (установили selectedConnector).
Завершение соединения или сброс (handleMouseUp) : Когда отпускаем мышь над приемником (получателем соединения), проверяем, что он другого типа, и устанавливаем связь. В любом случае, после отпускания везде сбрасываем selectedConnector.
Обратите внимание, важно, чтобы событие mouseUp обрабатывалось правильно и проверялся статус целевого элемента, чтобы упрощать и предотвращать ошибки. Убедитесь, что ваш компонент корректно обновляется при изменении состояния (например, через использование setConnection).
// Проверяем, что коннекторы разных типов
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
return (
<Group
id={'group-connector' + props.id}
ref={ref}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
но почему-то поеретягиваение не работает для коннектора
вместо этого у меня начинает перемещаться весь мой примитив
мне кажется это связанно с моим перещенеим по канве
вот так я рендерю примитив
import React, { memo } from 'react';
import { EditorPrimitives } from '../models/primitives/enums/editor-primitives';
import SnapGroup from './RenderGroup';
import SnapRect from './RenderRect';
import { Primitives } from '../models/types';
import SnapText from './RenderText';
import SnapCircle from './RenderCircle';
import SnapEllipse from './RenderEllipse';
import SnapImage from './RenderImage';
import SnapConnector from './RenderConnector';
import SnapLine from './RenderLine';
import SnapFunction from './RenderFunction';
import Konva from 'konva';
import SnapConnection from './RenderConnection';
import SnapInlinePageLink from './RenderPageLink';
import SnapCrossPageLink from './RenderCrossPageLink';
import KonvaEventObject = Konva.KonvaEventObject;
Пропсы для компонента RenderPrimitiveByType.
*/
interface RenderPrimitiveByTypeProps {
primitive: Primitives;
onClick?: (e: KonvaEventObject) => void;
onDragStart?: (e: KonvaEventObject) => void;
onDragMove?: (e: KonvaEventObject) => void;
onDragEnd?: (e: KonvaEventObject) => void;
isExporting?: boolean;
listening?: boolean;
overrideId?: number | string;
}
Маппинг типов EditorPrimitives на соответствующие компоненты рендеринга.
*/
type PrimitiveRenderMap = {
[K in EditorPrimitives]: React.FC;
};
const primitiveRenderMap: PrimitiveRenderMap = {
[EditorPrimitives.Group]: SnapGroup,
[EditorPrimitives.Rect]: SnapRect,
[EditorPrimitives.Image]: SnapImage,
[EditorPrimitives.Circle]: SnapCircle,
[EditorPrimitives.Text]: SnapText,
[EditorPrimitives.Ellipse]: SnapEllipse,
[EditorPrimitives.Connector]: SnapConnector,
[EditorPrimitives.Line]: SnapLine,
[EditorPrimitives.Function]: SnapFunction,
[EditorPrimitives.Connection]: SnapConnection,
[EditorPrimitives.InlinePageLink]: SnapInlinePageLink,
[EditorPrimitives.CrossPageLink]: SnapCrossPageLink,
};
Компонент, который выбирает и рендерит правильный компонент рендеринга
на основе типа примитива.
Использует React.memo для оптимизации производительности.
*/
const RenderPrimitiveByType: React.FC = (props) => {
const RenderComponent = primitiveRenderMap[props.primitive.type];
if (!RenderComponent) {
console.warn(Неизвестный тип примитива: ${props.primitive.type});
return null;
}
return (
<RenderComponent
{...{
...props.primitive,
isExporting: props.isExporting,
listening: props.listening,
overrideId: props.overrideId,
}}
/>
);
};
export default memo(RenderPrimitiveByType, (prevProps, nextProps) => prevProps.primitive === nextProps.primitive);
вот так группу
import React, { forwardRef } from 'react';
import { Group } from 'react-konva';
import withSnap from '../hoc/withSnap';
import { GroupPrimitive } from '../models/groups/groupPrimitive';
import Konva from 'konva';
import RenderPrimitiveByType from './RenderPrimitiveByType';
interface SnapGroupProps extends GroupPrimitive {
isExporting?: boolean;
}
const SnapGroup = forwardRef<Konva.Group, SnapGroupProps>((props, ref) => {
return (
props.primitives && (
<Group {...props} ref={ref}>
{Array.from(props.primitives.values())
.sort((a, b) => a.order - b.order)
.map((x) => (
))}
)
);
});
// Устанавливаем displayName для SnapGroup
SnapGroup.displayName = 'SnapGroup';
export default withSnap<GroupPrimitive, Konva.Group>(SnapGroup);
вот привязки
import React, { forwardRef, memo } from 'react';
import useSnap from '../hooks/useSnap';
import Konva from 'konva';
import { KonvaNodeEvents } from 'react-konva';
import { PrimitiveBase } from '../models/base/primitives.base';
// Обобщённые пропсы, требующие базовые свойства примитива
interface WithSnapProps extends PrimitiveBase, KonvaNodeEvents {
onSelect?: (connector: PrimitiveBase) => void;
isExporting: boolean;
listening?: boolean;
overrideId?: number | string;
}
// HOC с использованием forwardRef
const withSnap = <P extends PrimitiveBase, T extends Konva.Node>(WrappedComponent: React.ComponentType) => {
const ComponentWithSnap = forwardRef<
T,
P &
KonvaNodeEvents & {
isExporting: boolean;
}
((props: WithSnapProps, ref) => {
const snap = useSnap({
primitive: props,
isExporting: props.isExporting,
});
code Copy code
return (
<WrappedComponent
{...(props as P & { isExporting: boolean })}
ref={snap.ref}
id={props.overrideId ?? props.id}
strokeScaleEnabled={false}
{...(props.listening !== undefined && { listening: props.listening })}
draggable={props.listening !== undefined ? !props.listening : !props.inGroup}
onDragStart={snap.handleDragStart}
onDragMove={snap.handleDragMove}
onDragEnd={snap.handleDragEnd}
onTransformEnd={snap.handleTransformEnd}
onSelect={props.onSelect}
isExporting={props.isExporting}
{...(!props.inGroup && { onClick: snap.handleClick })}
/>
);
const wrappedComponentName = WrappedComponent.displayName || WrappedComponent.name || 'Component';
ComponentWithSnap.displayName = withSnap(${wrappedComponentName});
return memo(ComponentWithSnap);
};
import { useEffect, useRef, useState } from 'react';
import Konva from 'konva';
import { useGridStore, useSelectionStore } from '../store';
import { useDocumentContext } from './useDocumentContext';
import { Subject } from 'rxjs';
import { Primitives } from '../models/types';
import { IPoint } from '../models/infrastucture/point';
import { PrimitiveBase } from '../models/base/primitives.base';
import { useUpdateConnectors } from './useUpdateConnectors';
import Node = Konva.Node;
import Stage = Konva.Stage;
import { TextPrimitive } from '../models/primitives/primitives';
import { EditorPrimitives } from '../models/primitives/enums/editor-primitives';
const positionSource = new Subject<{ id: string | number; x: number; y: number }>();
const orderSource = new Subject<{ pageId: string | number; primitives: Map<string | number, Primitives> }>();
const transformSource = new Subject<{
id: string | number;
pageId: string | number;
scaleX: number;
scaleY: number;
rotation: number;
transformTextSize: boolean;
}>();
const connectorPositionSource = new Subject<Map<string | number, IPoint>>();
export const position= p o s i t i o n S o u r c e . a s O b s e r v a b l e ( ) ; e x p o r t c o n s t o r d e r = positionSource.asObservable();
export const order = p os i t i o n S o u r ce . a s O b ser v ab l e ( ) ; e x p or t co n s t or d er = orderSource.asObservable();
export const transform= t r a n s f o r m S o u r c e . a s O b s e r v a b l e ( ) ; e x p o r t c o n s t c o n n e c t o r P o s i t i o n = transformSource.asObservable();
export const connectorPosition = t r an s f or m S o u r ce . a s O b ser v ab l = connectorPositionSource.asObservable();
interface UseSnapProps {
primitive: PrimitiveBase;
isExporting?: boolean;
}
export const useSnap = ({ primitive, isExporting }: UseSnapProps) => {
const gridSize = useGridStore((state) => state.gridSize);
const document = useDocumentContext();
const ref = useRef(null);
const { getConnectorsPositions } = useUpdateConnectors();
const [isCtrlPressed, setIsCtrlPressed] = useState(false);
const [initialPosition, setInitialPosition] = useState<IPoint | null>(null);
const { selectedIds, setSelectedIds, setSelectedObjectReferenceId } = useSelectionStore();
// Обработчики событий для отслеживания нажатия клавиши Ctrl
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Control') {
setIsCtrlPressed(true);
}
};
code Copy code
const handleKeyUp = (e: KeyboardEvent) => {
if (e.key === 'Control') {
setIsCtrlPressed(false);
}
};
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
// Очистка обработчиков при размонтировании компонента
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('keyup', handleKeyUp);
};
Получает абсолютную позицию коннектора на сцене.
*/
const getAbsolutePosition = (): IPoint => {
if (!ref.current) return { x: 0, y: 0 };
code Copy code
const absolutePos = ref.current.getAbsoluteTransform().point({ x: 0, y: 0 });
code Copy code
return { x: absolutePos.x, y: absolutePos.y };
Ограничивает позицию объекта в пределах страницы и сетки.
*/
const constrainPosition = (node: Node | Stage, newPosition: IPoint) => {
if (!document.activePage) {
return;
}
code Copy code
const parent = node.getParent();
code Copy code
if (!parent) {
return;
}
const boundingBox = node.getClientRect({ relativeTo: parent });
// Получаем значения отступов
const offsetX = node.getAttr('offsetX') || 0;
const offsetY = node.getAttr('offsetY') || 0;
// Если мы в пределах листа
if (
boundingBox.x + offsetX >= 0 &&
boundingBox.y + offsetY >= 0 &&
boundingBox.x + boundingBox.width <= document.activePage.width &&
boundingBox.y + boundingBox.height <= document.activePage.height
) {
// Привязка к сетке
newPosition.x = Math.round(newPosition.x / gridSize) * gridSize;
newPosition.y = Math.round(newPosition.y / gridSize) * gridSize;
} else {
// Если за пределами листа
if (boundingBox.x + offsetX < 0) {
newPosition.x = newPosition.x - (boundingBox.x + offsetX);
}
if (boundingBox.y + offsetY < 0) {
newPosition.y = newPosition.y - (boundingBox.y + offsetY);
}
if (boundingBox.x + boundingBox.width > document.activePage.width) {
newPosition.x = newPosition.x - (boundingBox.x + boundingBox.width - document.activePage.width);
}
if (boundingBox.y + boundingBox.height > document.activePage.height) {
newPosition.y = newPosition.y - (boundingBox.y + boundingBox.height - document.activePage.height);
}
}
useEffect(() => {
const node = ref.current;
if (primitive.inGroup || primitive.type !== EditorPrimitives.Text || !node) {
return;
}
updatePosition(node.x(), node.y());
}, [(primitive as TextPrimitive).offsetX, (primitive as TextPrimitive).offsetY]);
Обновляет позицию объекта и эмиттит изменения.
*/
const updatePosition = (x: number, y: number) => {
if (isExporting) {
return;
}
const node = ref.current;
if (!node) return;
code Copy code
const newPosition = { x, y };
code Copy code
constrainPosition(node, newPosition);
node.position(newPosition);
positionSource.next({ id: primitive.id, x: newPosition.x, y: newPosition.y });
Переставляет элемент в конец порядка отображения.
entity получает максимальный order, остальные сдвигаются на -1.
*/
const reorderElements = (entityId: string | number) => {
if (!document.activePage || document.activePage.primitives.size === 0 || isExporting) return;
code Copy code
// Клонируем primitives, чтобы избежать мутаций оригинальных данных
code Copy code
const primitives = new Map(Array.from(document.activePage.primitives, ([key, value]) => [key, { ...value }]));
const entity = primitives.get(entityId);
if (!entity) {
console.error('Entity not found');
return;
}
const currentOrder = entity.order;
// Найти максимальный order среди всех элементов
let maxOrder = -1;
for (const primitive of primitives.values()) {
if (primitive.order > maxOrder) {
maxOrder = primitive.order;
}
}
// Если entity уже имеет максимальный order, ничего не делаем
if (currentOrder === maxOrder) {
console.log('Entity уже имеет максимальный order');
return;
}
// Сдвигаем order всех элементов с order > currentOrder на -1
primitives.forEach((primitive) => {
if (primitive.order > currentOrder) {
primitive.order -= 1;
primitives.set(primitive.id, primitive);
}
});
// Устанавливаем entity.order на максимальный +1
entity.order = maxOrder;
primitives.set(entityId, entity);
// Обновляем источник порядка
orderSource.next({ pageId: document.activePage.id, primitives });
Обработчик события начала перетаскивания.
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
if (!(e.evt.buttons & 1)) {
e.target.stopDrag();
return;
}
code Copy code
// Можно добавить логику, связанную с глобальным Transformer
code Copy code
setInitialPosition(e.target.position());
Обработчик события перемещения при перетаскивании.
*/
const handleDragMove = (e: Konva.KonvaEventObject) => {
const node = e.target;
const newPosition = {
x: node.x(),
y: node.y(),
};
code Copy code
constrainPosition(node, newPosition);
code Copy code
node.position(newPosition);
Обработчик события окончания перетаскивания.
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
const node = e.target;
node.moveToTop();
reorderElements(node.id());
code Copy code
if (!initialPosition || initialPosition === node.position()) {
code Copy code
return;
}
updatePosition(node.x(), node.y());
const positions = getConnectorsPositions(node);
connectorPositionSource.next(positions);
setInitialPosition(null);
const handleClick = (e: Konva.KonvaEventObject) => {
e.evt.preventDefault();
e.currentTarget.stopDrag();
code Copy code
if (primitive.inGroup && !e.currentTarget) {
return;
}
if (e.evt.button !== 0) return; // Только левая кнопка мыши
const targetId = e.target.id();
if (targetId.includes('connector')) {
console.log('connector clicked hoc');
return;
}
if ('objectReferenceId' in primitive) {
setSelectedObjectReferenceId(primitive.objectReferenceId);
}
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]);
}
const handleTransformEnd = (evt: Konva.KonvaEventObject) => {
if (!ref.current || isExporting) {
return;
}
code Copy code
const scaleX = ref.current.scaleX();
const scaleY = ref.current.scaleY();
const rotation = ref.current.rotation();
updatePosition(ref.current.x(), ref.current.y());
transformSource.next({
id: primitive.id,
pageId: document.activePage?.id ?? '0',
scaleX: scaleX,
scaleY: scaleY,
rotation: rotation,
transformTextSize: isCtrlPressed,
});
const positions = getConnectorsPositions(evt.target);
connectorPositionSource.next(positions);
return { ref, handleDragStart, handleDragMove, handleDragEnd, handleClick, handleTransformEnd, getAbsolutePosition };
};
почему же когда я тяну коннектор тянется и перемещается весь примитив
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting) {
return;
}
e.evt.stopPropagation(); // Останавливаем распространение события
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!selectedConnector || !circleRef.current || e.evt.button !== 0) {
setSelectedConnector(null);
return;
}
const isDifferentType = selectedConnector.connectorType !== props.connectorType;
if (isDifferentType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
draggable={false} // Make the group itself not draggable
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
draggable={false} // Ensure that the circle itself is not draggable
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Основные изменения:
Убедитесь, что Группа не является перетаскиваемой (draggable={false}), что препятствует вызову обработчиков событий для перетаскивания.
Также убедитесь, что сами круги внутри SVG не перетаскиваемы .
Эти изменения должны гарантировать, что только необходимые элементы обрабатывают события мыши, и соответственно, избежать "перемещения" всей группы или примитива в случае взаимодействия с конкретными узлами/коннекторами.
t c o n s t o r d e r = positionSource.asObservable();
export const order = p os i t i o n S o u r ce . a s O b ser v ab l e ( ) ; e x p or t co n s t or d er
= t r a n s f o r m S o u r c e . a s O b s e r v a b l e ( ) ; e x p o r t c o n s t c o n n e c t o r P o s i t i o n = transformSource.asObservable();
export const connectorPosition = t r an s f or m S o u r ce . a s O b ser v ab l e ( ) ; e x p or t co n s t co nn ec t or P os i t i o n interface UseSnapProps {
primitive: PrimitiveBase;
isExporting?: boolean;
}
export const useSnap = ({ primitive, isExporting }: UseSnapProps) => {
const gridSize = useGridStore((state) => state.gridSize);
const document = useDocumentContext();
const ref = useRef(null);
const { getConnectorsPositions } = useUpdateConnectors();
const [isCtrlPressed, setIsCtrlPressed] = useState(false);
const [initialPosition, setInitialPosition] = useState<IPoint | null>(null);
const { selectedIds, setSelectedIds, setSelectedObjectReferenceId } = useSelectionStore();
// Обработчики событий для отслеживания нажатия клавиши Ctrl
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Control') {
setIsCtrlPressed(true);
}
};
code Copy code
const handleKeyUp = (e: KeyboardEvent) => {
if (e.key === 'Control') {
setIsCtrlPressed(false);
}
};
window.addEventListener('keydown', handleKeyDown);
window.addEventListener('keyup', handleKeyUp);
// Очистка обработчиков при размонтировании компонента
return () => {
window.removeEventListener('keydown', handleKeyDown);
window.removeEventListener('keyup', handleKeyUp);
};
Получает абсолютную позицию коннектора на сцене.
*/
const getAbsolutePosition = (): IPoint => {
if (!ref.current) return { x: 0, y: 0 };
code Copy code
const absolutePos = ref.current.getAbsoluteTransform().point({ x: 0, y: 0 });
code Copy code
return { x: absolutePos.x, y: absolutePos.y };
Ограничивает позицию объекта в пределах страницы и сетки.
*/
const constrainPosition = (node: Node | Stage, newPosition: IPoint) => {
if (!document.activePage) {
return;
}
code Copy code
const parent = node.getParent();
code Copy code
if (!parent) {
return;
}
const boundingBox = node.getClientRect({ relativeTo: parent });
// Получаем значения отступов
const offsetX = node.getAttr('offsetX') || 0;
const offsetY = node.getAttr('offsetY') || 0;
// Если мы в пределах листа
if (
boundingBox.x + offsetX >= 0 &&
boundingBox.y + offsetY >= 0 &&
boundingBox.x + boundingBox.width <= document.activePage.width &&
boundingBox.y + boundingBox.height <= document.activePage.height
) {
// Привязка к сетке
newPosition.x = Math.round(newPosition.x / gridSize) * gridSize;
newPosition.y = Math.round(newPosition.y / gridSize) * gridSize;
} else {
// Если за пределами листа
if (boundingBox.x + offsetX < 0) {
newPosition.x = newPosition.x - (boundingBox.x + offsetX);
}
if (boundingBox.y + offsetY < 0) {
newPosition.y = newPosition.y - (boundingBox.y + offsetY);
}
if (boundingBox.x + boundingBox.width > document.activePage.width) {
newPosition.x = newPosition.x - (boundingBox.x + boundingBox.width - document.activePage.width);
}
if (boundingBox.y + boundingBox.height > document.activePage.height) {
newPosition.y = newPosition.y - (boundingBox.y + boundingBox.height - document.activePage.height);
}
}
useEffect(() => {
const node = ref.current;
if (primitive.inGroup || primitive.type !== EditorPrimitives.Text || !node) {
return;
}
updatePosition(node.x(), node.y());
}, [(primitive as TextPrimitive).offsetX, (primitive as TextPrimitive).offsetY]);
Обновляет позицию объекта и эмиттит изменения.
*/
const updatePosition = (x: number, y: number) => {
if (isExporting) {
return;
}
const node = ref.current;
if (!node) return;
code Copy code
const newPosition = { x, y };
code Copy code
constrainPosition(node, newPosition);
node.position(newPosition);
positionSource.next({ id: primitive.id, x: newPosition.x, y: newPosition.y });
Переставляет элемент в конец порядка отображения.
entity получает максимальный order, остальные сдвигаются на -1.
*/
const reorderElements = (entityId: string | number) => {
if (!document.activePage || document.activePage.primitives.size === 0 || isExporting) return;
code Copy code
// Клонируем primitives, чтобы избежать мутаций оригинальных данных
code Copy code
const primitives = new Map(Array.from(document.activePage.primitives, ([key, value]) => [key, { ...value }]));
const entity = primitives.get(entityId);
if (!entity) {
console.error('Entity not found');
return;
}
const currentOrder = entity.order;
// Найти максимальный order среди всех элементов
let maxOrder = -1;
for (const primitive of primitives.values()) {
if (primitive.order > maxOrder) {
maxOrder = primitive.order;
}
}
// Если entity уже имеет максимальный order, ничего не делаем
if (currentOrder === maxOrder) {
console.log('Entity уже имеет максимальный order');
return;
}
// Сдвигаем order всех элементов с order > currentOrder на -1
primitives.forEach((primitive) => {
if (primitive.order > currentOrder) {
primitive.order -= 1;
primitives.set(primitive.id, primitive);
}
});
// Устанавливаем entity.order на максимальный +1
entity.order = maxOrder;
primitives.set(entityId, entity);
// Обновляем источник порядка
orderSource.next({ pageId: document.activePage.id, primitives });
Обработчик события начала перетаскивания.
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
if (!(e.evt.buttons & 1)) {
e.target.stopDrag();
return;
}
code Copy code
// Можно добавить логику, связанную с глобальным Transformer
code Copy code
setInitialPosition(e.target.position());
Обработчик события перемещения при перетаскивании.
*/
const handleDragMove = (e: Konva.KonvaEventObject) => {
const node = e.target;
const newPosition = {
x: node.x(),
y: node.y(),
};
code Copy code
constrainPosition(node, newPosition);
code Copy code
node.position(newPosition);
Обработчик события окончания перетаскивания.
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
const node = e.target;
node.moveToTop();
reorderElements(node.id());
code Copy code
if (!initialPosition || initialPosition === node.position()) {
code Copy code
return;
}
updatePosition(node.x(), node.y());
const positions = getConnectorsPositions(node);
connectorPositionSource.next(positions);
setInitialPosition(null);
const handleClick = (e: Konva.KonvaEventObject) => {
e.evt.preventDefault();
e.currentTarget.stopDrag();
code Copy code
if (primitive.inGroup && !e.currentTarget) {
return;
}
if (e.evt.button !== 0) return; // Только левая кнопка мыши
const targetId = e.target.id();
if (targetId.includes('connector')) {
console.log('connector clicked hoc');
return;
}
if ('objectReferenceId' in primitive) {
setSelectedObjectReferenceId(primitive.objectReferenceId);
}
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]);
}
const handleTransformEnd = (evt: Konva.KonvaEventObject) => {
if (!ref.current || isExporting) {
return;
}
code Copy code
const scaleX = ref.current.scaleX();
const scaleY = ref.current.scaleY();
const rotation = ref.current.rotation();
updatePosition(ref.current.x(), ref.current.y());
transformSource.next({
id: primitive.id,
pageId: document.activePage?.id ?? '0',
scaleX: scaleX,
scaleY: scaleY,
rotation: rotation,
transformTextSize: isCtrlPressed,
});
const positions = getConnectorsPositions(evt.target);
connectorPositionSource.next(positions);
return { ref, handleDragStart, handleDragMove, handleDragEnd, handleClick, handleTransformEnd, getAbsolutePosition };
};
к некоторых примитивах есть коннекторы. т.е. объект коннектор внутри группы.
вот он
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState(false);
const [scale, setScale] = useState({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
code Copy code
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting) {
return;
}
code Copy code
e.evt.stopPropagation(); // Останавливаем распространение события
// console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
const handleMouseUp = (e: KonvaEventObject) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={!props.inGroup}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
когда я кликаю по коннетору и начинаю тянуть, то у меня сдвигается весь примитив, хотя так должна начать строится связь. т.е. событие драга вызывается из юз снап для всей группы
как мне сделать чтобы когда я тяну коннектор драг для группы не вызывался. чтобы вообще ничего не вызывалось кроме логики самого коннектора
// Обновим SnapConnector
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
// Отмена перетаскивания
const [isDragging, setIsDragging] = useState<boolean>(false);
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
// Начало соединения
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting) {
return;
}
// Ставим флаг, чтобы отменить перетаскивание группы
setIsDragging(true);
e.evt.stopPropagation(); // Останавливаем распространение события
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
// Завершение соединения
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
setIsDragging(false);
if (!circleRef.current || e.evt.button !== 0) {
return;
}
// Проверяем, что коннекторы разных типов
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={!isDragging} // Отменяем перетаскивание, когда событие начинается с коннектора
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
draggable={false} // Обеспечиваем, что сам круг не перетаскивается
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Пояснения:
Переменные состояния : Мы добавили флаг isDragging, который будет true, когда начинается перетаскивание с коннектора. Это помогает управлять состоянием всего примитива при начале соединения.
Отмена распространения события : Используем e.evt.stopPropagation() в обработчике handleMouseDown в SnapConnector для предотвращения перехвата событий на уровне группы.
Перемещение флага : Флаг isDragging отключает перетаскивание всей группы на уровне коннектора, что обеспечивает независимость и собственную логику обработки событий.
Эти изменения должны оставить логику SnapConnector, которая будет работать с созданием подключения, а не с перемещением всей группы.
// Проверяем, что коннекторы разных типов
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
const handleDragStart = (e: Konva.KonvaEventObject) => {
console.log('eeeeeeeeeee');
if (props.inGroup) {
e.target.stopDrag();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
как мне реализовать превьюшку связи? чтобы было виддно как она тащится
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import Konva from 'konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const [previewLine, setPreviewLine] = useState<{ x: number; y: number } | null>(null);
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
const systemRef = useRef(window);
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting) {
return;
}
e.evt.stopPropagation();
if (!circleRef.current || e.evt.button !== 0) {
return;
}
// Начинаем отслеживать линию предварительного просмотра
const pos = circleRef.current.getAbsolutePosition();
setPreviewLine({ x: pos.x, y: pos.y });
systemRef.current.addEventListener('mousemove', handleMouseMove);
};
const handleMouseMove = (e: MouseEvent) => {
if (!previewLine) return;
setPreviewLine({ x: e.clientX, y: e.clientY });
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
setPreviewLine(null);
systemRef.current.removeEventListener('mousemove', handleMouseMove);
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
};
return (
<>
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={false}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
</Group>
{previewLine && selectedConnector && (
<Line
points={[
selectedConnector.position.x,
selectedConnector.position.y,
previewLine.x,
previewLine.y,
]}
stroke="gray"
strokeWidth={1}
dash={[4, 4]}
/>
)}
</>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Пояснения:
Состояние previewLine : Мы добавили состояние для отслеживания текущей позиции линии предварительного просмотра связи.
Обработчики событий : handleMouseDown включает добавление обработчика движения мыши и устанавливает начальную точку линии. handleMouseMove обновляет конец линии, вытянув его к позиции курсора.
Удаление обработчика : По завершении соединения в handleMouseUp мы удаляем обработчик движения мыши.
Рендеринг линии : Мы добавляем Line для отображения линии предварительного просмотра на сцене.
Теперь линия будет появляться при нажатии на коннектор и следовать движению курсора, визуализируя процесс соединения.
// Проверяем, что коннекторы разных типов
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
const handleDragStart = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.target.stopDrag();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
он отлично строит связи но если я не доведу связь до окончательного коннектора и брошу ее на середине канвы то почему-то я не зайду в функцию handleMouseUp и коннеткоры так и останутся гореть и ждать продолжения постороения
что это
как это иправить
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
// Добавление глобального слушателя
const handleGlobalMouseUp = () => {
// Сбрасываем выбранный коннектор, если нет конструктора
if (selectedConnector) {
setSelectedConnector(null);
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
// Удаление глобального слушателя при размонтировании
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
};
}, [selectedConnector]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting) {
return;
}
e.evt.stopPropagation(); // Останавливаем распространение события
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
console.log('!!!!!!!!!!!!!!!!!');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
// Проверяем, что коннекторы разных типов
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Объяснение:
Глобальный обработчик события mouseup : Мы добавляем обработчик для окна (window.addEventListener('mouseup', handleGlobalMouseUp)), который сбрасывает выбранный коннектор, если курсор отпущен в любом месте сцены.
Эффект очистки : Удаление события mouseup при размонтировании компонента для предотвращения утечек памяти.
Таким образом, даже если вы отпустите мышь за пределами коннектора, соединение будет сброшено, и интерфейс вернется в исходное состояние.
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 getPointerPosition = (e: KonvaEventObject): IPoint => {
const stage = e.target.getStage();
if (!stage || !initialPointerPosition.current) return { x: 0, y: 0 };
code Copy code
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 sourcePosition = connectorsPositions.get(props.sourceId);
const targetPosition = connectorsPositions.get(props.targetId);
code Copy code
if (!sourcePosition && !targetPosition) {
return;
}
const layer = groupRef.current?.getLayer();
// Убедимся, что слой существует
if (!layer || !editorDocument.activePage?.id) {
return;
}
/**
* Ищет Id примитива, которому принадлежит коннектор
* @param node
* @param parentId
* @param connectorId
*/
const findParentPrimitive = (
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 = findParentPrimitive(child, parentId, connectorId);
if (foundId) {
return foundId;
}
}
}
return null;
};
// Найдем id примитивов, которым принадлежат коннекторы, независимо
const sourceParentPosition = layer.children
.map((primitive) => findParentPrimitive(primitive, primitive.id(), props.sourceId))
.find((result) => result !== null);
const targetParentPosition = layer.children
.map((primitive) => findParentPrimitive(primitive, primitive.id(), props.targetId))
.find((result) => result !== null);
// Если ни один из родителей не найден, выход
if (!sourceParentPosition || !targetParentPosition) {
return;
}
// Рассчитаем точки для линии, если оба родителя и позиции найдены
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 });
},
[props.id, props.sourceId, props.targetId, editorDocument.activePage?.id, stageInteraction],
const handleClick = (e: Konva.KonvaEventObject) => {
e.evt.preventDefault();
e.currentTarget.stopDrag();
code Copy code
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) });
code Copy code
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;
});
});
code Copy code
return () => {
code Copy code
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;
code Copy code
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);
а вот так я вычисляю динии связи
import { IPoint } from '../models/infrastucture/point';
Рассчитывает точки линии между двумя коннекторами.
Если коннекторы на одном уровне по Y, рисует прямую линию.
Если на разных, рисует три сегмента: горизонтальный, вертикальный, горизонтальный.
@param fromAbsolute Абсолютная позиция источника.
@param toAbsolute Абсолютная позиция назначения.
@param fromId
@param toId
@param scale
@param stagePoint
@param obstacles
@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 }>,
): 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[] = [];
// Если коннекторы смотрят в разные стороны
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 [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);
code Copy code
// Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов
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;
}
}
// Если между объектами есть расстояние (связь из трех отрезков)
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);
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);
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);
code Copy code
// Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов
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];
};
а вот мой граф эдитор
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Group, Layer, Line, Rect, Stage } from 'react-konva';
import Grid from './Grid';
import { SizeContext } from '../contexts/size-context';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import { useDocumentContext } from '../hooks/useDocumentContext';
import Konva from 'konva';
import WebFont from 'webfontloader';
import { useGridStore, useSelectionStore } from '../store';
import { ContextMenu } from 'primereact/contextmenu';
import { MenuItem } from 'primereact/menuitem';
import { Subject } from 'rxjs';
import TrashIcon from '@tecon/svg-icons/dist/esm/icons/TrashIcon';
import { IPoint } from '../models/infrastucture/point';
import { useEditorToolsStore } from '../store/editorTools-store';
import { Actions } from '../enums/actions';
import RenderPage from '../renderers/RenderPage';
import RenderFrame from '../renderers/RenderFrame';
import { EditorPrimitives } from '../models/primitives/enums/editor-primitives';
import { Frame } from '../models/frames/frame';
import InputOutputDarkblueIcon from '../../../svg-icons/src/icons/InputOutputDarkblueIcon';
import LinkDarkblueIcon from '../../../svg-icons/src/icons/LinkDarkblueIcon';
import CopyDarkblueIcon from '@tecon/svg-icons/dist/cjs/icons/CopyDarkblueIcon';
import PasteDarkblueIcon from '@tecon/svg-icons/dist/cjs/icons/PasteDarkblueIcon';
import TreeDarkblueIcon from '../../../svg-icons/src/icons/TreeDarkblueIcon';
export enum ObjectChange {
Remove,
Paste,
Add,
AddLink,
}
const objectChangeSource = new Subject<{
pageId: string | number | undefined;
id: Array<string | number>;
action: ObjectChange;
data?: object;
}>();
export const objectChange$ = objectChangeSource.asObservable();
const dragSource = new Subject<{ pageId: string | number; position: IPoint }>();
export const drag$ = dragSource.asObservable();
const inversionSource = new Subject<{ id: string | number; inversion: boolean }>();
export const inversion$ = inversionSource.asObservable();
const breakSource = new Subject<{ id: string | number; position: IPoint }>();
export const break$ = breakSource.asObservable();
const goTreeSource = new Subject<{ id: string }>();
export const goTree$ = goTreeSource.asObservable();
interface GraphEditorProps {
isDrag: boolean;
onDragEnd: () => void;
actionSource: Subject<{ action: Actions; pageId?: string | number; x?: number; y?: number }>;
}
const GraphEditor = ({ isDrag, onDragEnd, actionSource }: GraphEditorProps) => {
const editorDocument = useDocumentContext();
const stageInteraction = useStageInteractionContext();
const size = useContext(SizeContext);
const stageRef = useRef<Konva.Stage | null>(null);
const [fontLoaded, setFontLoaded] = useState(false);
const [pointerPosition, setPointerPosition] = useState({ x: 0, y: 0 });
const [idForCopy, setIdForCopy] = useState<Array<string | number>>([]);
const selectedIds = useSelectionStore((state) => state.selectedIds);
const setSelectedIds = useSelectionStore((state) => state.setSelectedIds);
const selectedObjectReferenceId = useSelectionStore((state) => state.selectedObjectReferenceId);
const setSelectedObjectReferenceId = useSelectionStore((state) => state.setSelectedObjectReferenceId);
const [isDraggingStage, setIsDraggingStage] = useState(false);
const editorToolsStore = useEditorToolsStore();
const gridSize = useGridStore((state) => state.gridSize);
useEffect(() => {
WebFont.load({
custom: {
families: ['GOST Type A'], // Name of the font
urls: ['../../index.css'], // URL to the font file
},
active: () => {
setFontLoaded(true);
console.log('Fonts loaded successfully');
},
inactive: () => {
console.error('Failed to load fonts');
},
});
}, []);
useEffect(() => {
const stageContainer = document.querySelector('canvas')?.parentElement;
code Copy code
if (!stageContainer) return;
if (editorToolsStore.action) {
stageContainer.style.cursor = 'pointer';
} else {
stageContainer.style.cursor = 'default';
}
return () => {
if (stageContainer) {
stageContainer.style.cursor = 'default';
}
};
}, [editorToolsStore.action]);
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
editorToolsStore.setAction(null);
editorToolsStore.setPageId(null);
}
};
code Copy code
window.addEventListener('keydown', handleKeyDown);
return () => {
window.removeEventListener('keydown', handleKeyDown);
};
useEffect(() => {
setSelectedIds([]);
setSelectedObjectReferenceId(null);
}, [editorDocument.activePage?.id]);
const handleStageClick = (e: Konva.KonvaEventObject) => {
switch (e.evt.button) {
case 0: {
if (e.target === stageRef.current || e.target.id() === 'page') {
setSelectedIds([]);
setSelectedObjectReferenceId(null);
}
break;
}
}
code Copy code
if (editorToolsStore.action) {
addSimplePrimitiveOnStage();
}
const addSimplePrimitiveOnStage = () => {
const startPoints = getPointerPositionOnStage();
if (!editorToolsStore.action || !editorToolsStore.pageId) {
return;
}
code Copy code
actionSource.next({
action: editorToolsStore.action,
pageId: editorToolsStore.pageId,
x: startPoints.x,
y: startPoints.y,
});
editorToolsStore.setAction(null);
editorToolsStore.setPageId(null);
const onDelete = () => {
console.log('objects deletion', selectedIds);
const ids: (string | number)[] = [];
selectedIds.forEach((id) =>
id.toString().startsWith('connection-')
? ids.push(id.toString().replace(/connection-(.+?)-segment-\d+/, '$1'))
: ids.push(id),
);
code Copy code
objectChangeSource.next({
pageId: editorDocument.activePage?.id,
id: [...ids],
action: ObjectChange.Remove,
});
setSelectedIds([]);
setSelectedObjectReferenceId(null);
const onPaste = () => {
console.log('objects paste', selectedIds);
code Copy code
// Get the mouse position relative to the stage
const stage = stageRef.current;
const mousePosition = stage?.getPointerPosition() ?? { x: 0, y: 0 };
// Calculate the position relative to the page
const pageX = (mousePosition.x - stageInteraction.point.x) / stageInteraction.scale;
const pageY = (mousePosition.y - stageInteraction.point.y) / stageInteraction.scale;
// Use the calculated coordinates
objectChangeSource.next({
pageId: editorDocument.activePage?.id,
id: idForCopy,
action: ObjectChange.Paste,
data: { x: pageX, y: pageY },
});
Инвертирует коннектор
@param connector
*/
const onInversion = (connector: Konva.Shape) => {
const inversion = connector.getAttr('inversion');
inversionSource.next({
id: connector.id().toString().replace('connector-', ''),
inversion: !inversion,
});
connector.setAttr('inversion', !inversion);
};
Добавляет излом на связь
*/
const onAddBreak = () => {
const stage = stageRef.current;
const mousePosition = stage?.getPointerPosition() ?? { x: 0, y: 0 };
const x = (mousePosition.x - stageInteraction.point.x) / stageInteraction.scale;
const y = (mousePosition.y - stageInteraction.point.y) / stageInteraction.scale;
code Copy code
if (mousePosition) {
code Copy code
breakSource.next({
id: selectedIds[0],
position: { x: x, y: y },
});
}
Осуществляет переход к объекту в древе объектов
*/
const onGoTree = () => {
if (!selectedObjectReferenceId) {
return;
}
goTreeSource.next({ id: selectedObjectReferenceId });
};
Обработчик отображения контекстного меню
@param e
*/
const handleContextMenu = (e: Konva.KonvaEventObject) => {
e.evt.preventDefault(); // Prevent the default browser context menu
code Copy code
if (e.target.id().startsWith('connector-')) {
code Copy code
// Меню для коннектора
setMenuItems([
{
label: 'Инверсия',
command: () => {
onInversion(e.target as Konva.Shape);
},
icon: InputOutputDarkblueIcon({ width: 25, height: 25 }),
},
]);
} else if (e.target.parent?.id().startsWith('connection-')) {
// Меню для связи
setMenuItems([
{
label: 'Излом',
icon: <i className='pi pi-wave-pulse' style={{ color: '#1769AA' }} />,
command: () => onAddBreak(),
},
{
label: 'Удалить',
icon: TrashIcon({ width: 25, height: 25 }),
command: onDelete,
},
]);
} else {
// Меню для оставшихся элементов
setMenuItems([
{
disabled: selectedIds.length === 0 || selectedIds.length > 1,
label: 'Создать ссылку',
icon: LinkDarkblueIcon({ width: 25, height: 25 }),
command: () => {
objectChangeSource.next({
pageId: editorDocument.activePage?.id,
id: [selectedIds[0]],
action: ObjectChange.AddLink,
});
},
},
{
disabled: selectedIds.length === 0,
label: 'Копировать',
icon: CopyDarkblueIcon({ width: 25, height: 25 }),
command: () => setIdForCopy([...selectedIds]),
},
{
disabled: idForCopy.length === 0,
label: 'Вставить',
icon: PasteDarkblueIcon({ width: 25, height: 25 }),
command: onPaste,
},
{
disabled: selectedObjectReferenceId === null,
label: 'Выделить в древе',
icon: TreeDarkblueIcon({ width: 25, height: 25 }),
command: onGoTree,
},
{ separator: true },
{
disabled: selectedIds.length === 0,
label: 'Удалить',
icon: TrashIcon({ width: 25, height: 25 }),
command: onDelete,
},
]);
}
if (cm.current) {
cm.current.show(e.evt);
}
const cm = useRef(null);
const [menuItems, setMenuItems] = useState<MenuItem[]>([]);
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.code === 'Delete' && selectedIds.length > 0) {
onDelete();
}
code Copy code
if (e.ctrlKey && e.code === 'KeyC' && selectedIds.length > 0) {
setIdForCopy([...selectedIds]);
}
if (e.ctrlKey && e.code === 'KeyV') {
onPaste();
}
Получение положения мыши на сцене
@returns {{x: number, y: number}} - Положение мыши на сцене.
*/
const getPointerPositionOnStage = useCallback((): IPoint => {
if (!stageRef.current) return { x: 0, y: 0 };
const pointerPosition = stageRef.current.getPointerPosition();
if (!pointerPosition) {
return { x: 0, y: 0 };
}
code Copy code
const x = (pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale;
code Copy code
const y = (pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale;
return { x: x, y: y };
}, [stageInteraction.point.x, stageInteraction.point.y, stageInteraction.scale]);
Обработчик события перетаскивания над элементом
@param {React.DragEvent} e - Событие перетаскивания
*/
const handleDragOver = useCallback(
(e: React.DragEvent) => {
if (!isDrag) {
return;
}
e.preventDefault();
stageRef.current?.setPointersPositions(e);
// Вычисляем смещение относительно предыдущей позиции
const pointerPosition = getPointerPositionOnStage();
setPointerPosition({ x: pointerPosition.x, y: pointerPosition.y });
},
[isDrag, getPointerPositionOnStage],
);
Обработчик события отпускания перетаскиваемого элемента
*/
const handleDrop = useCallback(() => {
if (!editorDocument.activePage) {
return;
}
code Copy code
const pointerPosition = getPointerPositionOnStage();
code Copy code
dragSource.next({
position: {
x: Math.round(pointerPosition.x / gridSize) * gridSize,
y: Math.round(pointerPosition.y / gridSize) * gridSize,
},
pageId: editorDocument.activePage.id,
});
// Удаляем превью
}, [editorDocument.activePage, getPointerPositionOnStage, gridSize]);
Функция для включения режима перемещения сцены
*/
const enableStageDragging = () => {
setIsDraggingStage(true);
code Copy code
// Делаем всю сцену draggable
code Copy code
stageRef.current?.draggable(true);
Функция для выключения режима перемещения сцены
*/
const disableStageDragging = () => {
setIsDraggingStage(false);
code Copy code
// Отключаем draggable у сцены
code Copy code
stageRef.current?.draggable(false);
Обработчик кликов по сцене
*/
const handleMouseDown = (e: Konva.KonvaEventObject) => {
// Проверяем, нажата ли средняя кнопка мыши
if (e.evt.button === 1) {
enableStageDragging();
}
};
return fontLoaded ? (
fontLoaded && editorDocument.activePage && (
<div
style={{ outline: 'none' }}
tabIndex={1}
onKeyDown={onKeyDown}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragEnd={onDragEnd}
>
<Stage
ref={stageRef}
width={size.width}
height={size.height}
scaleX={stageInteraction.scale}
scaleY={stageInteraction.scale}
x={stageInteraction.point.x}
y={stageInteraction.point.y}
onWheel={stageInteraction.handleWheel}
onClick={handleStageClick}
onContextMenu={handleContextMenu}
onMouseDown={handleMouseDown}
onMouseUp={disableStageDragging}
onDragMove={(e) => {
if (isDraggingStage) {
// Меняем позицию канвы, только если активен режим перетаскивания сцены
stageInteraction.setPoint(e.currentTarget.position());
}
}}
>
<Rect
id={'page'}
key={p-${editorDocument.activePage.id}}
x={0}
y={0}
width={editorDocument.activePage.width}
height={editorDocument.activePage.height}
strokeWidth={1}
dash={[5, 10]}
stroke={'#cf03fc'}
/>
{Array.from(editorDocument.activePage.primitives.values())
.filter((x) => x.type === EditorPrimitives.Frame)
.map((x) => (
<RenderFrame key={x.id} {...(x as Frame)} />
))}
{/{previewDraggingPrimitive && } /}
code Copy code
{isDrag && (
<Group
x={Math.round(pointerPosition.x / gridSize) * gridSize - 2.5}
y={Math.round(pointerPosition.y / gridSize) * gridSize - 2.5}
>
<Line points={[0, 0, 5, 5]} stroke={'black'} strokeWidth={1} />
<Line points={[5, 0, 0, 5]} stroke={'black'} strokeWidth={1} />
</Group>
)}
</Layer>
<Layer>
<Grid />
</Layer>
<Layer id={'pageLayer'}>
<RenderPage page={editorDocument.activePage} />
</Layer>
</Stage>
{/* Context Menu */}
<ContextMenu ref={cm} model={menuItems} />
</div>
)
export default GraphEditor;
как мне отобразить превьюшки линии связи? чтобы она рисовалась во время того как я тяну ее
но при этом бы не сохранялась до самого отпускания
import React, { useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Group, Layer, Line, Rect, Stage } from 'react-konva';
import Grid from './Grid';
import { SizeContext } from '../contexts/size-context';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import { useDocumentContext } from '../hooks/useDocumentContext';
import Konva from 'konva';
import { useGridStore, useSelectionStore } from '../store';
import { ContextMenu } from 'primereact/contextmenu';
import { Subject } from 'rxjs';
import TrashIcon from '@tecon/svg-icons/dist/esm/icons/TrashIcon';
import { IPoint } from '../models/infrastucture/point';
import RenderPage from '../renderers/RenderPage';
import { EditorPrimitives } from '../models/primitives/enums/editor-primitives';
import { Frame } from '../models/frames/frame';
export enum ObjectChange {
Remove,
Paste,
Add,
AddLink,
}
const objectChangeSource = new Subject<{
pageId: string | number | undefined;
id: Array<string | number>;
action: ObjectChange;
data?: object;
}>();
export const objectChange$ = objectChangeSource.asObservable();
const GraphEditor = ({ isDrag, onDragEnd, actionSource }) => {
const editorDocument = useDocumentContext();
const stageInteraction = useStageInteractionContext();
const size = useContext(SizeContext);
const stageRef = useRef<Konva.Stage | null>(null);
const [fontLoaded, setFontLoaded] = useState(false);
const [pointerPosition, setPointerPosition] = useState<IPoint>({ x: 0, y: 0 });
const [previewLine, setPreviewLine] = useState<{ startX: number; startY: number; endX: number; endY: number } | null>(null);
// Add event listeners for mouse events to control the preview line
useEffect(() => {
const handleMouseMove = (e) => {
if (previewLine) {
const stage = stageRef.current;
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
setPreviewLine((prev) => ({
...prev,
endX: pointerPosition.x,
endY: pointerPosition.y,
}));
}
};
const handleMouseUp = () => {
setPreviewLine(null); // Clear the preview line on mouse up
};
window.addEventListener('mousemove', handleMouseMove);
window.addEventListener('mouseup', handleMouseUp);
return () => {
window.removeEventListener('mousemove', handleMouseMove);
window.removeEventListener('mouseup', handleMouseUp);
};
}, [previewLine]);
const handleConnectorMouseDown = (connectorX, connectorY) => {
setPreviewLine({
startX: connectorX,
startY: connectorY,
endX: connectorX,
endY: connectorY,
});
};
// Use this function to render connectors and call `handleConnectorMouseDown` on `mousedown` event
return fontLoaded ? (
<div
style={{ outline: 'none' }}
tabIndex={1}
onDrop={handleDrop}
onDragOver={handleDragOver}
onDragEnd={onDragEnd}
>
<Stage
ref={stageRef}
width={size.width}
height={size.height}
scaleX={stageInteraction.scale}
scaleY={stageInteraction.scale}
x={stageInteraction.point.x}
y={stageInteraction.point.y}
onWheel={stageInteraction.handleWheel}
onClick={handleStageClick}
onMouseDown={handleMouseDown}
>
<Layer>
{editorDocument.activePage && (
<>
<Rect
id={'page'}
key={`p-${editorDocument.activePage.id}`}
x={0}
y={0}
width={editorDocument.activePage.width}
height={editorDocument.activePage.height}
strokeWidth={1}
dash={[5, 10]}
stroke={'#cf03fc'}
/>
{/* Render primitives like frames and connectors here */}
{previewLine && (
<Line
points={[previewLine.startX, previewLine.startY, previewLine.endX, previewLine.endY]}
stroke='black'
strokeWidth={2}
lineCap='round'
lineJoin='round'
dash={[4, 2]}
/>
)}
</>
)}
</Layer>
<Layer>
<Grid />
</Layer>
<Layer id={'pageLayer'}>
<RenderPage page={editorDocument.activePage} />
</Layer>
</Stage>
{/* Context Menu */}
<ContextMenu ref={cm} model={menuItems} />
</div>
) : (
// <Loader />
<></>
);
};
export default GraphEditor;
Пояснения:
Состояние previewLine : Это состоянии используется для хранения начальной и конечной позиции линии во время перетаскивания.
Обработчики событий : В useEffect добавили обработчики событий глобально для mousemove и mouseup:
mousemove обновляет конечную точку линии.
mouseup очищает линию, так как это сигнал окончания создания связи.
Отображение линии : Вставляется Line в сцену на слой, который обновляется при каждом рендере, если previewLine не равен null.
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 getPointerPosition = (e: KonvaEventObject): IPoint => {
const stage = e.target.getStage();
if (!stage || !initialPointerPosition.current) return { x: 0, y: 0 };
code Copy code
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 sourcePosition = connectorsPositions.get(props.sourceId);
const targetPosition = connectorsPositions.get(props.targetId);
code Copy code
if (!sourcePosition && !targetPosition) {
return;
}
const layer = groupRef.current?.getLayer();
// Убедимся, что слой существует
if (!layer || !editorDocument.activePage?.id) {
return;
}
/**
* Ищет Id примитива, которому принадлежит коннектор
* @param node
* @param parentId
* @param connectorId
*/
const findParentPrimitive = (
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 = findParentPrimitive(child, parentId, connectorId);
if (foundId) {
return foundId;
}
}
}
return null;
};
// Найдем id примитивов, которым принадлежат коннекторы, независимо
const sourceParentPosition = layer.children
.map((primitive) => findParentPrimitive(primitive, primitive.id(), props.sourceId))
.find((result) => result !== null);
const targetParentPosition = layer.children
.map((primitive) => findParentPrimitive(primitive, primitive.id(), props.targetId))
.find((result) => result !== null);
// Если ни один из родителей не найден, выход
if (!sourceParentPosition || !targetParentPosition) {
return;
}
// Рассчитаем точки для линии, если оба родителя и позиции найдены
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 });
},
[props.id, props.sourceId, props.targetId, editorDocument.activePage?.id, stageInteraction],
const handleClick = (e: Konva.KonvaEventObject) => {
e.evt.preventDefault();
e.currentTarget.stopDrag();
code Copy code
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) });
code Copy code
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;
});
});
code Copy code
return () => {
code Copy code
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;
code Copy code
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);
я хочу чтобы у меня отображалась превьюшка линии
т.е чтобы во время предсталвения рисовалась полоска но она ыб не сохранялась пока я не отпущу мышь
import React, { useCallback, useEffect, 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 } 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';
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<SnapConnectionLineProps> = (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);
// State for preview line
const [previewLine, setPreviewLine] = useState<number[]>([]);
const calculateSegments = useCallback(
(points: number[]) => {
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 getPointerPosition = (e: KonvaEventObject<DragEvent>): 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 sourcePosition = connectorsPositions.get(props.sourceId);
const targetPosition = connectorsPositions.get(props.targetId);
if (!sourcePosition && !targetPosition) {
return;
}
const layer = groupRef.current?.getLayer();
if (!layer || !editorDocument.activePage?.id) {
return;
}
const findParentPrimitive = (
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 = findParentPrimitive(child, parentId, connectorId);
if (foundId) {
return foundId;
}
}
}
return null;
};
const sourceParentPosition = layer.children
.map((primitive) => findParentPrimitive(primitive, primitive.id(), props.sourceId))
.find((result) => result !== null);
const targetParentPosition = layer.children
.map((primitive) => findParentPrimitive(primitive, primitive.id(), props.targetId))
.find((result) => result !== null);
if (!sourceParentPosition || !targetParentPosition) {
return;
}
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 });
},
[props.id, props.sourceId, props.targetId, editorDocument.activePage?.id, stageInteraction],
);
const handleClick = (e: KonvaEventObject<MouseEvent>) => {
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]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
const stage = e.target.getStage();
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
setPreviewLine([pointerPosition.x, pointerPosition.y, pointerPosition.x, pointerPosition.y]);
stage.on('mousemove', (e) => {
const newPointerPosition = stage.getPointerPosition();
if (!newPointerPosition) return;
setPreviewLine((prev) => [
prev[0],
prev[1],
newPointerPosition.x,
newPointerPosition.y,
]);
});
stage.on('mouseup', () => {
stage.off('mousemove');
setPreviewLine([]);
});
};
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))}
onMouseDown={handleMouseDown}
>
<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();
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) {
newPointsArray[2 * segment.index] += delta;
newPointsArray[2 * (segment.index + 1)] += delta;
} else {
newPointsArray[2 * segment.index + 1] += delta;
newPointsArray[2 * (segment.index + 1) + 1] += delta;
}
setStatePoints(newPointsArray);
return newPointsArray;
});
initialPointerPosition.current = currentPointerPosition;
e.target.setAttrs({
x: segment.center.x - 5,
y: segment.center.y - 5,
});
}}
/>
)}
</Group>
);
})}
{previewLine.length === 4 && (
<Line
points={previewLine}
stroke="grey"
strokeWidth={2}
lineCap="round"
dash={[4, 4]}
/>
)}
</>
);
};
// Устанавливаем displayName для SnapConnectionLine
SnapConnectionLine.displayName = 'SnapConnectionLine';
export default withSnap<SnapConnectionLineProps, Konva.Group>(SnapConnectionLine);
Объяснение:
Состояние previewLine : Это состояние используется для хранения начальной и конечной точки линии предварительного просмотра.
Обработчики :
handleMouseDown : Инициализирует состояние previewLine с начальной точкой, добавляя события прослушивания для mousemove и mouseup.
mousemove : Обновляет конечную точку previewLine в соответствии с текущим положением указателя мыши, создавая тем самым визуальный эффект перетаскивания линии.
mouseup : Сбрасывает previewLine и удаляет слушатель mousemove, прекращая предварительный просмотр.
Таким образом, линия будет визуально рисоваться в процессе перетаскивания и удаляться при отпускании мыши.
// Останавливаем распространение события
code Copy code
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
Обработчик отпускания левой клавиши мыши на коннекторе
*/
const handleMouseUp = (e: KonvaEventObject) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
code Copy code
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
Обработчик начала перетаскивания
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
// Если коннектор в группе, останавливаем его перетаскивание
if (props.inGroup) {
e.target.stopDrag();
}
};
Обработчик завершения перетаскивания
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const [previewLine, setPreviewLine] = useState<number[]>([]);
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = (e) => {
if (!previewLine || previewLine.length < 2) return;
const stage = e.target.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!pointerPosition) return;
const newEndPoint = [
(pointerPosition.x - stage.x()) / stage.scaleX(),
(pointerPosition.y - stage.y()) / stage.scaleY(),
];
setPreviewLine(prev => [prev[0], prev[1], ...newEndPoint]);
};
const handleMouseUp = () => {
setPreviewLine([]);
window.removeEventListener('mousemove', handleMouseMove);
};
window.addEventListener('mouseup', handleMouseUp);
return () => {
window.removeEventListener('mouseup', handleMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [previewLine]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
const startPosition = circleRef.current.getAbsolutePosition();
setPreviewLine([startPosition.x, startPosition.y]);
window.addEventListener('mousemove', (e) => {
const stage = circleRef.current?.getStage();
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
const newPreviewLine = [
startPosition.x,
startPosition.y,
(pointerPosition.x - stage.x()) / stage.scaleX(),
(pointerPosition.y - stage.y()) / stage.scaleY()
];
setPreviewLine(newPreviewLine);
});
setSelectedConnector({
id: props.id,
position: startPosition,
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
setPreviewLine([]);
};
const handleDragStart = (e: Konva.KonvaEventObject<DragEvent>) => {
if (props.inGroup) {
e.target.stopDrag();
}
};
const handleDragEnd = (e: Konva.KonvaEventObject<DragEvent>) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
{previewLine.length === 4 && (
<Line
points={previewLine}
stroke="grey"
strokeWidth={2}
lineCap="round"
dash={[4, 4]}
/>
)}
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Основные моменты:
Состояние previewLine : Мы используем его для хранения текущего состояния линии предварительного просмотра, которую мы будем отображать.
Обработчики для событий мыши :
mousedown инициализирует предварительную линию и устанавливает обработчик mousemove.
mousemove обновляет конечную точку линии.
mouseup сбрасывает линию и удаляет обработчик mousemove.
Показетеля линии : Используем компонент Line из react-konva, чтобы отобразить линию на сцене в процессе перетаскивания.
const handleGlobalMouseUp = () => {
// Сбрасываем выбранный коннектор
if (selectedConnector) {
setSelectedConnector(null);
setPreviewConnection([]);
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
// Удаление глобального слушателя при размонтировании
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [selectedConnector, setSelectedConnector]);
Обработчик нажатия левой клавиши мыши по коннектору
*/
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
code Copy code
// Останавливаем распространение события
code Copy code
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
Обработчик отпускания левой клавиши мыши на коннекторе
*/
const handleMouseUp = (e: KonvaEventObject) => {
setPreviewConnection([]);
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
code Copy code
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
Обработчик начала перетаскивания
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
// Если коннектор в группе, останавливаем его перетаскивание
if (props.inGroup) {
e.target.stopDrag();
}
};
Обработчик завершения перетаскивания
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
но почему-то превью связи рисуется для всех объектов на сцене
т.е. сколько коннекторов столько же и связей будет нарисовано
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import { useConnectionPreview } from '../contexts/ConnectionPreviewContext'; // Подключаем контекст
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const { previewConnection, setPreviewConnection } = useConnectionPreview(); // Используем контекст
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition || !selectedConnector) return;
const newEndPoint = [
pointerPosition.x,
pointerPosition.y,
];
// Устанавливаем только если текущий коннектор активен
if (selectedConnector.id === props.id) {
setPreviewConnection([selectedConnector.position.x, selectedConnector.position.y, ...newEndPoint]);
}
};
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
setPreviewConnection([]);
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [selectedConnector, setSelectedConnector, setPreviewConnection, props.id]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
/>
{previewConnection.length === 4 && selectedConnector?.id === props.id && (
<Line
points={previewConnection}
stroke='grey'
strokeWidth={2}
lineCap='round'
/>
)}
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Примечания:
Использование контекста : Контекст используется для управления состоянием previewConnection, что позволяет следить за состоянием из одного места и рендерить только одну линию.
Отслеживание активного коннектора : Убедитесь, что линия предварительного просмотра отображается только для активного, перемещаемого коннектора.
С использованием такого подхода вы сможете избежать множества линий предварительного просмотра, ведь контекст будет управлять всем этим состоянием централизованно.
// Добавление глобального слушателя
code Copy code
const handleGlobalMouseUp = () => {
// Сбрасываем выбранный коннектор
if (selectedConnector) {
setSelectedConnector(null);
setPreviewConnection([]);
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
// Удаление глобального слушателя при размонтировании
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [selectedConnector, setSelectedConnector]);
Обработчик нажатия левой клавиши мыши по коннектору
*/
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
code Copy code
// Останавливаем распространение события
code Copy code
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
Обработчик отпускания левой клавиши мыши на коннекторе
*/
const handleMouseUp = (e: KonvaEventObject) => {
setPreviewConnection([]);
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
code Copy code
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
Обработчик начала перетаскивания
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
// Если коннектор в группе, останавливаем его перетаскивание
if (props.inGroup) {
e.target.stopDrag();
}
};
Обработчик завершения перетаскивания
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
он работает но почему-то моя превьюшка связи не пропадает когда я отпускаю линию
она должна исчезать когда я отпустила мышку
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const { previewConnection, setPreviewConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
if (!stage) return;
const pointerPosition = stage.getPointerPosition();
if (!pointerPosition) return;
const newEndPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
if (!selectedConnector) return;
previewConnectionSource.next({
points: [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
...newEndPoint,
],
});
};
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] }); // Сбрасываем данные линии
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [selectedConnector, setSelectedConnector]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
previewConnectionSource.next({ points: [] }); // Сбрасываем данные линии после отпускания
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
{previewConnection.length === 4 && (
<Line points={previewConnection} stroke='grey' strokeWidth={1} dash={[5, 5]} />
)}
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Ключевые изменения:
Сброс линии предварительного просмотра : Обеспечьте вызов previewConnectionSource.next({ points: [] }) в обработчиках handleGlobalMouseUp и handleMouseUp для удаления данных после отпускания кнопки мыши.
Отображение линии : Рендеринг линии (Line) происходит только тогда, когда имеются точки в массиве previewConnection.
// Сбрасывает выбранный коннектор и превью, если левая кнопка мыши была отпущена
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
}
};
// Добавление глобальных слушателей
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
// Удаление глобального слушателя при размонтировании
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
]);
Обработчик нажатия левой клавиши мыши по коннектору
*/
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
code Copy code
// Останавливаем распространение события
code Copy code
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
Обработчик отпускания левой клавиши мыши на коннекторе
*/
const handleMouseUp = (e: KonvaEventObject) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
code Copy code
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
Обработчик начала перетаскивания
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
// Если коннектор в группе, останавливаем его перетаскивание
if (props.inGroup) {
e.target.stopDrag();
}
};
Обработчик завершения перетаскивания
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
сделай так, чтобы при наведении указателя мыши на конечный коннектор, он тоже загорался желтым, как и уже выбранный стартовый
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [hovered, setHovered] = useState<boolean>(false); // Add state for hover effect
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector) {
return;
}
const firstPoint = [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewConnectionSource.next({
points: [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint],
});
};
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id || hovered
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={() => setHovered(true)} // Highlight on hover
onMouseLeave={() => setHovered(false)} // Remove highlight when not hovered
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Изменения:
Добавлен стейт hovered для отслеживания, находится ли указатель мыши над коннектором.
Обработчики onMouseEnter и onMouseLeave используются для изменения состояния hovered, за счет чего конечный коннектор, на который наведен указатель мыши, будет подсвечиваться.
Условие подсветки дополнено, чтобы учитывать состояние hovered, когда коннектор подсвечивается желтым при наведении мыши.
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [hovered, setHovered] = useState<boolean>(false); // Определяем состояние для hover
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector) {
return;
}
const firstPoint = [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewConnectionSource.next({
points: [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint],
});
};
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id || hovered
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={() => setHovered(true)} // Обрабатываем наведение
onMouseLeave={() => setHovered(false)} // Обрабатываем снятие наведения
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Пояснение:
useState : вызов useState определяет состояние hovered, которое управляет тем, должна ли заливка быть желтой, когда мышь находится над конечным коннектором.
// Сбрасывает выбранный коннектор и превью, если левая кнопка мыши была отпущена
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
}
};
// Добавление глобальных слушателей
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
// Удаление глобального слушателя при размонтировании
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
]);
Обработчик нажатия левой клавиши мыши по коннектору
*/
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
code Copy code
// Останавливаем распространение события
code Copy code
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
Обработчик отпускания левой клавиши мыши на коннекторе
*/
const handleMouseUp = (e: KonvaEventObject) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
code Copy code
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
Обработчик начала перетаскивания
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
// Если коннектор в группе, останавливаем его перетаскивание
if (props.inGroup) {
e.target.stopDrag();
}
};
Обработчик завершения перетаскивания
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id || hovered
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={() => {
if (selectedConnector) setHovered(true);
}}
onMouseLeave={() => setHovered(false)}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
и вот такая функция для рассчета координат
import { IPoint } from '../models/infrastucture/point';
Рассчитывает точки линии между двумя коннекторами.
Если коннекторы на одном уровне по Y, рисует прямую линию.
Если на разных, рисует три сегмента: горизонтальный, вертикальный, горизонтальный.
@param fromAbsolute Абсолютная позиция источника.
@param toAbsolute Абсолютная позиция назначения.
@param fromId
@param toId
@param scale
@param stagePoint
@param obstacles
@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 }>,
): 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[] = [];
// Если коннекторы смотрят в разные стороны
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 [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);
code Copy code
// Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов
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;
}
}
// Если между объектами есть расстояние (связь из трех отрезков)
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);
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);
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);
code Copy code
// Вертикальная линия выше наивысшего или ниже нижайшего из двух примитивов
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];
};
сейчас моя превьюшка свсязи линия всегда рисутеся одинаково из трех отрезков. а по окончании постороения связи она рисуется уже как надо чреез функцию расчет акоординат
я же хочу чтобы первьюшка строилась из трех отрезков только окогда я тащу еще где-то в воздухе а когда я навожу на коннектор она перестраивалась согласно функции рассчета.
чтобы я заранее видела как будет постороена связь на самом деле
сделай это
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
import { calculateLinePoints } from '../utils/calculateLinePoints';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [hovered, setHovered] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector) {
return;
}
const fromAbsolute = selectedConnector.position;
const toAbsolute = {
x: (pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
y: (pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale
};
let previewPoints;
if (hovered) {
// Используем calculateLinePoints, если находимся над другим коннектором
const obstacles = []; // Ваш массив препятствий
previewPoints = calculateLinePoints(
fromAbsolute,
toAbsolute,
selectedConnector.id,
'targetId', // Здесь можно использовать реальный ID элемента назначения
stageInteraction.scale,
stageInteraction.point,
obstacles
);
} else {
// Визуализация в "воздухе"
const firstPoint = [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewPoints = [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint];
}
previewConnectionSource.next({
points: previewPoints,
});
};
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
hovered,
]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
>
{props.inversion && (
<Circle x={props.x} y={props.y} radius={3.78} stroke='black' strokeWidth={1} strokeScaleEnabled={false} />
)}
<Line
x={props.x}
y={props.y}
points={points}
stroke='black'
rotation={props.rotation}
strokeWidth={1}
strokeScaleEnabled={false}
/>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id || hovered
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={() => {
if (selectedConnector) setHovered(true);
}}
onMouseLeave={() => setHovered(false)}
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Пояснения:
Когда вы находитесь "в воздухе" (то есть, не над коннектором) визуализация линии строится из трёх частей.
При наведении на коннектор, переключается логика построения на функцию calculateLinePoints, передавая текущие позиции для расчета корректных координат линии.
Используется состояние hovered, которому присваивается значение true, когда конечный коннектор находится под указателем, вызывая тем самым пересчет линии.
code Copy code
// Сбрасывает выбранный коннектор и превью, если левая кнопка мыши была отпущена
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
}
};
// Добавление глобальных слушателей
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
// Удаление глобального слушателя при размонтировании
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
]);
Обработчик нажатия левой клавиши мыши по коннектору
*/
const handleMouseDown = (e: KonvaEventObject) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
code Copy code
// Останавливаем распространение события
code Copy code
e.evt.stopPropagation();
console.log('connector', props.id, 'clicked');
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
Обработчик отпускания левой клавиши мыши на коннекторе
*/
const handleMouseUp = (e: KonvaEventObject) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
code Copy code
// Проверяем, что коннекторы разных типов
code Copy code
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
// Определяем направление соединения
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
// Сбрасываем выбранный коннектор
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
Обработчик начала перетаскивания
*/
const handleDragStart = (e: Konva.KonvaEventObject) => {
// Если коннектор в группе, останавливаем его перетаскивание
if (props.inGroup) {
e.target.stopDrag();
}
};
Обработчик завершения перетаскивания
*/
const handleDragEnd = (e: Konva.KonvaEventObject) => {
if (props.inGroup) {
e.evt.stopPropagation();
}
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
{props.inversion && (
)}
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id || pointOnTargetConnector
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={() => {
if (selectedConnector) setPointOnTargetConnector(true);
}}
onMouseLeave={() => setPointOnTargetConnector(false)}
/>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
когда я навожу курсор во время постороениясвязи на конечный коннектор то он подсвечивается желтым и все супер
но при построении первью он почему-то никошга не заходит в функцию построения связи согласно функции калькуэйт лайн поинтс
в консоли я вижу что pointOnTargetConnector всегда равно фолс
но у меня е загорается желтым коннектор который зависит тоже от pointOnTargetConnector на который я навожу мышь когда строю связь
как такое можент быть
import React, { forwardRef, useEffect, useRef, useState } from 'react';
import { Circle, Group, Line } from 'react-konva';
import { ConnectorTypes } from '../models/primitives/enums/connector-types';
import { ConnectorPrimitive } from '../models/primitives/primitives';
import Konva from 'konva';
import withSnap from '../hoc/withSnap';
import { useSelectionStore } from '../store';
import { useStageInteractionContext } from '../hooks/useStageInteractionContext';
import KonvaEventObject = Konva.KonvaEventObject;
import Vector2d = Konva.Vector2d;
import { Subject } from 'rxjs';
import { calculateLinePoints } from '../utils/calculateLinePoints';
import { getObstacles } from '../utils/getObstacles';
const previewConnectionSource = new Subject<{ points: number[] }>();
export const previewConnection$ = previewConnectionSource.asObservable();
interface SnapConnectorProps extends ConnectorPrimitive {
onSelect: (connector: ConnectorPrimitive) => void;
isExporting: boolean;
}
const SnapConnector = forwardRef<Konva.Group, SnapConnectorProps>((props, ref) => {
const points = props.connectorType === ConnectorTypes.Input ? [0, 0, -10, 0] : [0, 0, 10, 0];
const [highlight, setHighlight] = useState<boolean>(false);
const [pointOnTargetConnector, setPointOnTargetConnector] = useState<boolean>(false);
const [scale, setScale] = useState<Vector2d>({ x: 1, y: 1 });
const circleRef = useRef<Konva.Circle>(null);
const { selectedConnector, setSelectedConnector, setConnection } = useSelectionStore();
const stageInteraction = useStageInteractionContext();
useEffect(() => {
if (!circleRef.current || !circleRef.current.parent?.parent) return;
const parentScale = circleRef.current.parent.parent.scale();
if (!parentScale) {
return;
}
setScale({
x: 1 / parentScale.x / stageInteraction.scale,
y: 1 / parentScale.y / stageInteraction.scale,
});
}, [highlight, stageInteraction.scale]);
useEffect(() => {
const handleMouseMove = () => {
const stage = circleRef.current?.getStage();
const pointerPosition = stage?.getPointerPosition();
if (!stage || !pointerPosition || !selectedConnector || !circleRef.current) {
return;
}
const fromAbsolute = selectedConnector.position;
const toAbsolute = {
x: (pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
y: (pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
};
let previewPoints;
if (pointOnTargetConnector) {
previewPoints = calculateLinePoints(
fromAbsolute,
toAbsolute,
selectedConnector.id,
props.id,
stageInteraction.scale,
stageInteraction.point,
getObstacles(circleRef.current.getLayer()),
);
} else {
const firstPoint = [
(selectedConnector.position.x - stageInteraction.point.x) / stageInteraction.scale,
(selectedConnector.position.y - stageInteraction.point.y) / stageInteraction.scale,
];
const fourthPoint = [
(pointerPosition.x - stageInteraction.point.x) / stageInteraction.scale,
(pointerPosition.y - stageInteraction.point.y) / stageInteraction.scale,
];
const secondPoint = [(firstPoint[0] + fourthPoint[0]) / 2, firstPoint[1]];
const thirdPoint = [secondPoint[0], fourthPoint[1]];
previewPoints = [...firstPoint, ...secondPoint, ...thirdPoint, ...fourthPoint];
}
previewConnectionSource.next({
points: previewPoints,
});
};
const handleGlobalMouseUp = () => {
if (selectedConnector) {
setSelectedConnector(null);
setPointOnTargetConnector(false); // Сброс
previewConnectionSource.next({ points: [] });
}
};
window.addEventListener('mouseup', handleGlobalMouseUp);
window.addEventListener('mousemove', handleMouseMove);
return () => {
window.removeEventListener('mouseup', handleGlobalMouseUp);
window.removeEventListener('mousemove', handleMouseMove);
};
}, [
selectedConnector,
setSelectedConnector,
stageInteraction.point.x,
stageInteraction.point.y,
stageInteraction.scale,
pointOnTargetConnector,
]);
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
if (props.isExporting || e.evt.button !== 0) {
return;
}
e.evt.stopPropagation();
if (!circleRef.current || e.evt.button !== 0) {
return;
}
setSelectedConnector({
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
});
};
const handleMouseUp = (e: KonvaEventObject<MouseEvent>) => {
if (!circleRef.current || e.evt.button !== 0) {
return;
}
if (selectedConnector && selectedConnector.connectorType !== props.connectorType) {
const fromConnector =
selectedConnector.connectorType === ConnectorTypes.Output
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
const toConnector =
selectedConnector.connectorType === ConnectorTypes.Input
? selectedConnector
: {
id: props.id,
position: circleRef.current.getAbsolutePosition(),
connectorType: props.connectorType,
parentId: circleRef.current.parent?.parent?.id() || '',
};
setConnection({
fromId: fromConnector.id,
fromPosition: fromConnector.position,
toId: toConnector.id,
toPosition: toConnector.position,
fromParentId: fromConnector.parentId,
toParentId: toConnector.parentId,
});
}
setSelectedConnector(null);
previewConnectionSource.next({ points: [] });
};
return (
<Group
id={'group-connector' + props.id}
ref={ref}
draggable={true}
onMouseEnter={() => setHighlight(true)}
onMouseLeave={() => setHighlight(false)}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
>
<Circle
ref={circleRef}
scale={scale}
id={'connector-' + props.id}
inversion={props.inversion}
x={props.connectorType === ConnectorTypes.Input ? -10 + props.x : 10 + props.x}
y={props.y}
radius={6}
hitStrokeWidth={10}
fill={
selectedConnector?.id === props.id || pointOnTargetConnector
? 'yellow'
: highlight || (selectedConnector && selectedConnector.connectorType !== props.connectorType)
? 'green'
: 'transparent'
}
onMouseDown={handleMouseDown}
onMouseUp={handleMouseUp}
onMouseEnter={() => {
if (selectedConnector) setPointOnTargetConnector(true);
}}
onMouseLeave={() => setPointOnTargetConnector(false)}
/>
</Group>
);
});
SnapConnector.displayName = 'SnapConnector';
export default withSnap<SnapConnectorProps, Konva.Group>(SnapConnector);
Дельные улучшения:
Убедитесь, что вы используете контекст или глобальное состояние только в случае, если это оправдано. Проверьте, если ваши локальные состояния играют более важную роль в логике.
Убедитесь, что аннулируете состояние pointOnTargetConnector при сбросе выделенного коннектора.
e
(
)
;
e
x
p
or
t
co
n
s
t
co
nn
ec
t
or
P
os
i
t
i
o
n