feat(switch): make key handlers protected, enable arrow keys

This commit is contained in:
jorenbroekema 2021-08-19 15:34:45 +02:00
parent c1397d86e7
commit 4ae3e9e20b
3 changed files with 29 additions and 11 deletions

View file

@ -0,0 +1,5 @@
---
'@lion/switch': minor
---
Make keyup handlers protected, enables subclassers to switch using alternative keys.

View file

@ -80,9 +80,9 @@ export class LionSwitchButton extends DisabledWithTabIndexMixin(LitElement) {
/** @protected */
this._toggleChecked = this._toggleChecked.bind(this);
/** @private */
this.__handleKeydown = this.__handleKeydown.bind(this);
this.__handleKeydown = this._handleKeydown.bind(this);
/** @private */
this.__handleKeyup = this.__handleKeyup.bind(this);
this.__handleKeyup = this._handleKeyup.bind(this);
}
connectedCallback() {
@ -121,23 +121,23 @@ export class LionSwitchButton extends DisabledWithTabIndexMixin(LitElement) {
}
/**
* @param {KeyboardEvent} e
* @private
* @param {KeyboardEvent} ev
* @protected
*/
// eslint-disable-next-line class-methods-use-this
__handleKeydown(e) {
_handleKeydown(ev) {
// prevent "space" scrolling on "macOS"
if (e.keyCode === 32) {
e.preventDefault();
if (ev.key === ' ') {
ev.preventDefault();
}
}
/**
* @param {KeyboardEvent} e
* @private
* @param {KeyboardEvent} ev
* @protected
*/
__handleKeyup(e) {
if ([32 /* space */, 13 /* enter */].indexOf(e.keyCode) !== -1) {
_handleKeyup(ev) {
if ([' ', 'Enter'].includes(ev.key)) {
this._toggleChecked();
}
}

View file

@ -50,6 +50,19 @@ describe('lion-switch-button', () => {
expect(el.hasAttribute('checked')).to.be.false;
});
it('should toggle the value of "checked" on key-up', async () => {
expect(el.checked).to.be.false;
expect(el.hasAttribute('checked')).to.be.false;
el.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }));
await el.updateComplete;
expect(el.checked).to.be.true;
expect(el.hasAttribute('checked')).to.be.true;
el.dispatchEvent(new KeyboardEvent('keyup', { key: ' ' }));
await el.updateComplete;
expect(el.checked).to.be.false;
expect(el.hasAttribute('checked')).to.be.false;
});
it('can be disabled', async () => {
el.disabled = true;
expect(el.checked).to.be.false;