aotds-docks/src/lib/components/Output/Print/movable.js

77 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-04-10 21:41:09 +00:00
import VanillaMoveable, { PROPERTIES, EVENTS } from "moveable";
import { camelize, isUndefined } from "@daybrush/utils";
function createMoveable(node, options) {
2022-04-10 22:21:44 +00:00
let translate = [0, 0];
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
let ship = options.ship;
let system = options.system;
delete options.ship;
delete options.system;
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
if (Array.isArray(system)) {
system = { system: system[0], systemId: system[1] };
} else {
system = { system };
}
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
options = {
originDraggable: true,
originRelative: true,
draggable: true,
throttleDrag: 0,
zoom: 1,
origin: false,
onDrag(e) {
translate = e.beforeTranslate;
node.dispatchEvent(new CustomEvent("translate", { detail: translate }));
ship.dispatch.setUITransform({ ...system, translate });
},
target: node,
...options,
};
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
const moveable = new VanillaMoveable(document.body, options);
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
EVENTS.forEach((name) => {
const onName = camelize(`on ${name}`);
moveable.on(name, (e) => {
const result = options[onName] && options[onName](e);
const result2 = node.dispatchEvent(new CustomEvent(name, { detail: e }));
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
return !isUndefined(result)
? result
: !isUndefined(result2)
? result2
: undefined;
2022-04-10 21:41:09 +00:00
});
2022-04-10 22:21:44 +00:00
});
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
return moveable;
2022-04-10 21:41:09 +00:00
}
export function movable(node, options) {
2022-04-10 22:21:44 +00:00
let moveable = options.disabled ? undefined : createMoveable(options);
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
const destroy = () => {
if (!moveable) return;
moveable.destroy();
moveable = undefined;
};
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
const update = async (params) => {
if (params.disabled) {
destroy();
} else {
if (!moveable) {
moveable = createMoveable(node, params);
}
}
};
2022-04-10 21:41:09 +00:00
2022-04-10 22:21:44 +00:00
return {
destroy,
update,
};
2022-04-10 21:41:09 +00:00
}