@woosh/meep-engine
Version:
Pure JavaScript game engine. Fully featured and production ready.
125 lines (99 loc) • 3.46 kB
JavaScript
import { createSound } from "../../engine/EntityCreator.js";
import { SoundEmitterChannels } from "../../engine/sound/ecs/emitter/SoundEmitterSystem.js";
import ButtonView from "../elements/button/ButtonView.js";
import { globalMetrics } from "../../engine/metrics/GlobalMetrics.js";
import { MetricsCategory } from "../../engine/metrics/MetricsCategory.js";
/**
*
* @param {InterfaceCommand} command
* @param {GUIEngine} gui
* @param {EntityComponentDataset} ecd
* @returns {View}
*/
export function createInterfaceCommandButton({
command,
gui,
ecd
}) {
/**
*
* @type {InteractionCommand}
*/
const interaction = command.command;
/**
*
* @param {SoundTrack} sound
*/
function playSound(sound) {
if (sound === null) {
return;
}
createSound({
timeout: 5,
track: sound,
positioned: false,
channel: SoundEmitterChannels.Effects
}).build(ecd);
// track.on.ended.add(console.log);
}
const button = new ButtonView({
action() {
if (interaction.enabled.getValue()) {
interaction.action();
playSound(command.actionSound);
globalMetrics.record("command-used", {
category: MetricsCategory.Interaction,
label: interaction.id
});
}
},
classList: [
`command-${interaction.id}`
],
css: command.style
});
button.el.addEventListener('mouseenter', () => {
if (interaction.enabled.getValue()) {
//only play the sound if the button is enabled
playSound(command.hoverSound);
}
});
function updateEnableStatus() {
const v = interaction.enabled.getValue();
button.enabled = v;
}
function featureClassName(f) {
return "feature-" + f;
}
function addCommandFeature(f) {
button.addClass(featureClassName(f));
}
function removeCommandFeature(f) {
button.removeClass(featureClassName(f));
}
if (interaction.features !== undefined) {
interaction.features.forEach(addCommandFeature);
interaction.features.on.added.add(addCommandFeature);
interaction.features.on.removed.add(removeCommandFeature);
}
button.bindSignal(interaction.enabled.onChanged, updateEnableStatus);
button.bindSignal(interaction.features.on.added, addCommandFeature);
button.bindSignal(interaction.features.on.removed, removeCommandFeature);
function tooltipFactory() {
return gui.localization.getString(command.tooltip);
}
if (command.tooltip !== undefined) {
gui.viewTooltips.manage(button, tooltipFactory);
}
button.on.linked.add(() => {
interaction.features.forEach(addCommandFeature);
updateEnableStatus();
});
button.on.unlinked.add(() => {
interaction.features.forEach(removeCommandFeature);
});
command.tags.forEach(tag => {
button.addClass(`tag-${tag}`);
});
return button;
}