@gravity-ui/graph
Version:
Modern graph editor component
84 lines (83 loc) • 2.49 kB
JavaScript
import { computed, signal } from "@preact/signals-core";
import { ESchedulerPriority } from "../../../lib";
import { debounce } from "../../../utils/utils/schedule";
import { PortState } from "./Port";
export class PortsStore {
constructor(rootStore, graph) {
this.rootStore = rootStore;
this.graph = graph;
this.$ports = computed(() => {
return Array.from(this.$portsMap.value.values());
});
this.$portsMap = signal(new Map());
this.notifyPortMapChanged = debounce(() => {
this.$portsMap.value = new Map(this.$portsMap.value);
}, {
priority: ESchedulerPriority.LOW,
frameInterval: 1,
});
}
createPort(id, component) {
if (this.$portsMap.value.has(id)) {
const existingPort = this.$portsMap.value.get(id);
if (existingPort) {
existingPort.setOwner(component);
return existingPort;
}
}
const newPort = new PortState({
id,
x: 0,
y: 0,
component,
lookup: !component,
});
this.$portsMap.value.set(id, newPort);
this.notifyPortMapChanged();
return newPort;
}
getPort(id) {
return this.$portsMap.value.get(id);
}
getOrCreatePort(id, component) {
const existingPort = this.getPort(id);
if (existingPort) {
if (component && !existingPort.owner) {
existingPort.setOwner(component);
}
return existingPort;
}
return this.createPort(id, component);
}
deletePort(id) {
const deleted = this.$portsMap.value.delete(id);
if (deleted) {
this.notifyPortMapChanged();
}
return deleted;
}
deletePorts(ids) {
ids.forEach((id) => {
this.$portsMap.value.delete(id);
});
}
clearPorts() {
this.$portsMap.value.clear();
this.notifyPortMapChanged();
}
getPortsByComponent(component) {
return this.$ports.value.filter((port) => port.component === component);
}
ownPort(port, component) {
port.addObserver(component);
}
unownPort(port, component) {
port.removeObserver(component);
if (port.observers.size === 0 && !port.component) {
this.deletePort(port.id);
}
}
reset() {
this.clearPorts();
}
}