38 lines
1.1 KiB
TypeScript
38 lines
1.1 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;
|
||
|
element.addEventListener('mousedown', () => {
|
||
|
selected = true;
|
||
|
});
|
||
|
svg.addEventListener('mousemove', event => {
|
||
|
if (selected) this.#moveCB(event);
|
||
|
});
|
||
|
svg.addEventListener('mouseup', () => {
|
||
|
selected = false;
|
||
|
});
|
||
|
svg.addEventListener('mouseleave', event => {
|
||
|
selected = false;
|
||
|
});
|
||
|
svg.addEventListener('click', event => {
|
||
|
if (!selected) this.#clickCB(event);
|
||
|
});
|
||
|
}
|
||
|
|
||
|
onMove(cb) {
|
||
|
this.#moveCB = cb;
|
||
|
}
|
||
|
onClick(cb) {
|
||
|
this.#clickCB = cb;
|
||
|
}
|
||
|
}
|