Constellations/js/Mode.js

58 lines
1.2 KiB
JavaScript
Raw Permalink Normal View History

2022-07-26 19:39:06 +02:00
var mode;
var modes;
var mouseEvents = ['onClick', 'onMousedown', 'onMouseup', 'onMouseenter'];
var currentMode = 'play';
2022-07-26 19:39:06 +02:00
return {
init: init,
dispatch: dispatch,
set: set,
setEnabled: setEnabled
2022-07-26 19:39:06 +02:00
}
function init(chosenModes, elementId) {
2022-07-26 19:39:06 +02:00
mode = document.getElementById(elementId || 'mode');
mode.addEventListener('change', onChange);
modes = chosenModes;
}
function setEnabled(enabled, targets) {
if(!Array.isArray(targets)) {
targets = [targets];
}
for(var i = 0; i < mode.options.length; i++) {
var option = mode.options[i];
if(targets.indexOf(option.value) >= 0) {
option.disabled = !enabled;
}
}
}
function runEvent(eventName) {
var handler = modes[currentMode].events[eventName];
if(typeof handler == 'function') {
handler.apply(null, Array.prototype.slice.call(arguments, 1));
}
}
function onChange() {
runEvent('onLeave');
currentMode = mode.value;
runEvent('onEnter');
}
function set(newMode) {
if(modes[newMode]) {
mode.value = newMode;
onChange();
}
}
2022-08-10 21:12:39 +02:00
function dispatch(cell) {
var handler = {};
mouseEvents.forEach(function(eventName) {
2022-08-10 21:12:39 +02:00
handler[eventName] = function(e) {runEvent(eventName, e, cell);};
2022-07-26 19:39:06 +02:00
});
return handler;
2022-07-26 19:39:06 +02:00
}