ember-toggle
Version:
Checkbox based toggle switch component for Ember.js
101 lines (84 loc) • 2.32 kB
JavaScript
import { action } from '@ember/object';
import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { getOwner } from '@ember/application';
import { guidFor } from '@ember/object/internals';
import { cached } from '@glimmer/tracking';
function configValue(configName, defaultValue) {
return function (target, name) {
return {
get() {
return (
this.args[name] ??
(configName && this.config?.[configName]) ??
defaultValue
);
},
};
};
}
export default class XToggle extends Component {
focused = false;
container;
disabled;
value;
name;
onLabel;
offLabel;
theme;
variant;
showLabels;
size;
get config() {
return (
getOwner(this).resolveRegistration('config:environment')[
'ember-toggle'
] || {}
);
}
get toggled() {
return this.value;
}
get forId() {
return guidFor(this) + '-x-toggle';
}
toggleSwitch(value) {
let onToggle = this.args.onToggle;
let disabled = this.disabled;
if (!disabled && value !== this.value && typeof onToggle === 'function') {
let name = this.name;
onToggle(value, name);
// The click on input/label will toggle the input unconditionally.
// Input state has to be updated manually to prevent it going out of
// sync in case the action didn't update value.
const checkbox = this.container.querySelector('.x-toggle');
const newValue = this.value;
if (checkbox.checked !== newValue) {
checkbox.checked = newValue;
}
}
}
setContainer(element) {
this.container = element;
}
spacebarToggle(event) {
// spacebar: 32
if (event.which === 32) {
event.preventDefault();
this.toggleSwitch(!this.value);
}
}
handleFocusIn() {
this.focused = true;
}
handleFocusOut() {
this.focused = false;
}
}