DataTools3/elements/Connector.js

106 lines
2.0 KiB
JavaScript

class Connector {
static INPUT = 0;
static OUTPUT = 1;
direction;
type;
label;
connection;
element;
circle;
listeners = [];
cache;
constructor(direction, type, label = null) {
this.direction = direction;
this.type = type;
this.element = "";
this.label = label;
if (this.label == null) {
switch (this.direction) {
case Connector.INPUT:
this.label = "Input";
break;
case Connector.OUTPUT:
this.label = "Output";
break;
}
}
}
buildElement() {
if (this.element) return this.element;
this.element = document.createElement("div");
this.element.classList.add("connector");
if (this.direction == Connector.INPUT) {
this.element.classList.add("connectorInput");
}
if (this.direction == Connector.OUTPUT) {
this.element.classList.add("connectorOutput");
}
this.circle = document.createElement("span");
this.circle.classList.add("connectorCircle");
let label = document.createElement("span");
label.innerText = this.label;
label.classList.add("connectorLabel");
this.element.appendChild(this.circle);
this.element.appendChild(label);
this.element.addEventListener("click", () => {
ConnectionController.clickConnector(this);
})
return this.element;
}
connect(connector) {
this.connection = connector;
this.element.classList.add("connected");
if (this.direction == this.INPUT) {
this.cache = this.connection.cache;
}
}
disconnect() {
this.connection = null;
this.element.classList.remove("connected");
}
disconnectBoth() {
if (!this.connection) return;
this.connection.disconnect();
this.disconnect();
}
send(data) {
if (!this.connection) return;
this.cache = data;
this.connection.receive(data);
}
receive(data) {
if (this.type != "any" && typeof data != this.type) {
console.error("invalid type received", data, typeof data, this.type);
return;
}
this.cache = data;
for (let listener of this.listeners) {
listener(data);
}
}
addListener(listener) {
this.listeners.push(listener);
}
}