PNet/js/graphics/tragable.ts

72 lines
2.1 KiB
TypeScript
Raw Permalink Normal View History

2023-06-28 18:02:41 +02:00
export class InteractionEvent {
x: number;
y: number;
}
2023-06-22 17:47:04 +02:00
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;
}
2023-06-28 18:02:41 +02:00
#moveCB: (event: InteractionEvent) => any = () => { };
#clickCB: (event: InteractionEvent) => any = () => { };
2023-06-22 17:47:04 +02:00
initTrag(element: SVGElement) {
let svg = Tragable.getRootSVG(element);
let selected = false;
2023-06-28 16:06:31 +02:00
let moved = true;
2023-06-22 17:47:04 +02:00
element.addEventListener('mousedown', () => {
selected = true;
2023-06-28 16:06:31 +02:00
moved = false;
2023-06-22 17:47:04 +02:00
});
svg.addEventListener('mousemove', event => {
2023-06-28 16:06:31 +02:00
if (selected) {
moved = true;
this.#moveCB(event);
}
2023-06-22 17:47:04 +02:00
});
svg.addEventListener('mouseup', () => {
selected = false;
});
svg.addEventListener('mouseleave', event => {
selected = false;
});
2023-06-27 09:19:06 +02:00
element.addEventListener('click', event => {
2023-06-28 16:06:31 +02:00
if (!selected && !moved) this.#clickCB(event);
2023-06-22 17:47:04 +02:00
});
2023-06-28 18:02:41 +02:00
element.addEventListener('touchstart', () => {
selected = true;
moved = false;
console.log("td");
});
svg.addEventListener('touchmove', event => {
if (selected) {
moved = true;
let e = event.touches[0];
this.#moveCB({ x: e.clientX, y: e.clientY });
}
});
svg.addEventListener('touchend', () => {
selected = false;
});
svg.addEventListener('touchcancel', event => {
selected = false;
});
2023-06-22 17:47:04 +02:00
}
2023-06-28 18:22:29 +02:00
initOnlyClick(element: SVGElement) {
element.addEventListener('click', event => {
this.#clickCB(event);
});
}
2023-06-22 17:47:04 +02:00
2023-06-28 18:02:41 +02:00
onMove(cb: (event: InteractionEvent) => any) {
2023-06-22 17:47:04 +02:00
this.#moveCB = cb;
}
2023-06-28 18:02:41 +02:00
onClick(cb: (event: InteractionEvent) => any) {
2023-06-22 17:47:04 +02:00
this.#clickCB = cb;
}
}