Skip to content

Commit

Permalink
feat(stepper): add keyboard accessible keys
Browse files Browse the repository at this point in the history
  • Loading branch information
mseyfayi authored and majidsajadi committed May 13, 2024
1 parent ce779e0 commit d93f740
Showing 1 changed file with 42 additions and 4 deletions.
46 changes: 42 additions & 4 deletions src/stepper/stepper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,46 @@ export class Stepper extends LitElement {
`;
}

connectedCallback() {
super.connectedCallback();
this.addEventListener('keydown', this.handleKeyDown);
}

disconnectedCallback() {
super.disconnectedCallback();
this.removeEventListener('keydown', this.handleKeyDown);
}

private handleKeyDown = (event: KeyboardEvent) => {
switch (event.code) {
case 'ArrowDown':
this.handleDecrease();
event.preventDefault();
event.stopPropagation();
break;
case 'ArrowUp':
this.handleIncrease();
event.preventDefault();
event.stopPropagation();
break;
case 'Home':
this.handleChange(this.min);
event.preventDefault();
event.stopPropagation();
break;
case 'End':
this.handleChange(this.max);
event.preventDefault();
event.stopPropagation();
break;
}
};

private handleChange = (newValue: number) => {
this.value = newValue;
this.dispatchChangeEvent();
};

private dispatchChangeEvent = () => {
this.dispatchEvent(
new CustomEvent('stepper-change', {
Expand All @@ -80,15 +120,13 @@ export class Stepper extends LitElement {

private handleIncrease = () => {
if (this.value < this.max) {
this.value += this.step;
this.dispatchChangeEvent();
this.handleChange(this.value + this.step);
}
};

private handleDecrease = () => {
if (this.value > this.min) {
this.value -= this.step;
this.dispatchChangeEvent();
this.handleChange(this.value - this.step);
}
};
}

0 comments on commit d93f740

Please sign in to comment.