@gravity-ui/graph
Version:
Modern graph editor component
59 lines (58 loc) • 2.2 kB
JavaScript
import { computed, signal } from "@preact/signals-core";
import cloneDeep from "lodash/cloneDeep";
import { ESelectionStrategy } from "../../utils/types/types";
export const IS_CONNECTION_TYPE = "Connection";
export class ConnectionState {
get id() {
return this.$state.value.id;
}
get sourceBlockId() {
return this.$state.value.sourceBlockId;
}
get sourceAnchorId() {
return this.$state.value.sourceAnchorId;
}
get targetBlockId() {
return this.$state.value.targetBlockId;
}
get targetAnchorId() {
return this.$state.value.targetAnchorId;
}
static getConnectionId(connection) {
if (connection.id)
return connection.id;
if (connection.sourceAnchorId && connection.targetAnchorId) {
return [connection.sourceAnchorId, connection.targetAnchorId].join(":");
}
return [connection.sourceBlockId, connection.targetBlockId].join(":");
}
constructor(store, connectionState) {
this.store = store;
this.$state = signal(undefined);
this.$sourceBlock = computed(() => {
return this.store.getBlock(this.$state.value.sourceBlockId);
});
this.$targetBlock = computed(() => {
return this.store.getBlock(this.$state.value.targetBlockId);
});
this.$geometry = computed(() => {
return [this.$sourceBlock.value?.$geometry.value, this.$targetBlock.value?.$geometry.value];
});
const id = ConnectionState.getConnectionId(connectionState);
this.$state.value = { ...connectionState, id };
}
isSelected() {
return this.$state.value.selected;
}
setSelection(selected, strategy = ESelectionStrategy.REPLACE) {
this.store.setConnectionsSelection([this.id], selected, strategy);
}
asTConnection() {
return cloneDeep(this.$state.toJSON());
}
updateConnection(connection) {
const { styles, ...newProps } = connection;
const newStyles = Object.assign({}, this.$state.value.styles, styles);
this.$state.value = Object.assign({}, this.$state.value, newProps, { styles: newStyles });
}
}