PNet/js/graphics/tragable.ts
2023-06-28 16:06:31 +02:00

43 lines
No EOL
1.3 KiB
TypeScript

export class Tragable {
static getRootSVG(elem: SVGElement): SVGSVGElement {
while (!(elem instanceof SVGSVGElement)) {
if (!(elem instanceof SVGElement)) throw new Error("Not in an SVG");
elem = elem.parentElement as any;
}
return elem;
}
#moveCB: (event: MouseEvent) => any = () => { };
#clickCB: (event: MouseEvent) => any = () => { };
initTrag(element: SVGElement) {
let svg = Tragable.getRootSVG(element);
let selected = false;
let moved = true;
element.addEventListener('mousedown', () => {
selected = true;
moved = false;
});
svg.addEventListener('mousemove', event => {
if (selected) {
moved = true;
this.#moveCB(event);
}
});
svg.addEventListener('mouseup', () => {
selected = false;
});
svg.addEventListener('mouseleave', event => {
selected = false;
});
element.addEventListener('click', event => {
if (!selected && !moved) this.#clickCB(event);
});
}
onMove(cb: (event: MouseEvent) => any) {
this.#moveCB = cb;
}
onClick(cb: (event: MouseEvent) => any) {
this.#clickCB = cb;
}
}