@@ -25,12 +25,13 @@ export default class PgInputSelect extends HTMLElement {
2525
2626 connectedCallback ( ) {
2727 this . $button . addEventListener ( 'click' , this . #handleClick. bind ( this ) ) ;
28+ this . $button . addEventListener ( 'keydown' , this . #handleKeyPress. bind ( this ) ) ;
2829 }
2930
3031 render ( changes ) {
3132 if ( changes . value || changes . default ) {
3233 this . $label . textContent = this . value
33- ? this . value
34+ ? ( this . options . find ( x => x . value === this . value ) ?? { label : this . value } ) . label
3435 : this . default
3536 ? this . default . label
3637 : '\u00A0' ; // nbsp
@@ -45,16 +46,68 @@ export default class PgInputSelect extends HTMLElement {
4546 source : this . $button ,
4647 default : this . default ,
4748 value : this . options . find ( x => x . value === this . value ) ?? null ,
48- items : this . options
49+ items : this . options ,
4950 } ) ;
5051 if ( result !== undefined ) {
5152 this . dispatchEvent ( new CustomEvent ( 'change' , {
5253 detail : {
53- value : result . value
54- }
54+ value : result . value ,
55+ } ,
5556 } ) ) ;
5657 this . $label . textContent = result . label ;
5758 }
5859 this . #menuOpen = false ;
5960 }
61+
62+ #handleKeyPress( e : KeyboardEvent ) {
63+ switch ( e . key ) {
64+ case 'ArrowDown' :
65+ e . preventDefault ( ) ;
66+ if ( this . options . length <= 1 ) {
67+ return ;
68+ }
69+ this . #handleKeyDownArrowDown( ) ;
70+ break ;
71+ case 'ArrowUp' :
72+ e . preventDefault ( ) ;
73+ if ( this . options . length <= 1 ) {
74+ return ;
75+ }
76+ this . #handleKeyDownArrowUp( ) ;
77+ break ;
78+ }
79+ }
80+
81+ #handleKeyDownArrowDown( ) {
82+ const index = this . options . findIndex ( x => x . value === this . value ) ;
83+ let newValue = '' ;
84+ if ( index === - 1 || index === this . options . length - 1 ) {
85+ // select first or loop to top
86+ newValue = this . options [ 0 ] . value ;
87+ } else {
88+ newValue = this . options [ index + 1 ] . value ;
89+ }
90+ this . dispatchEvent ( new CustomEvent ( 'change' , {
91+ detail : {
92+ value : newValue ,
93+ } ,
94+ } ) ) ;
95+ }
96+
97+ #handleKeyDownArrowUp( ) {
98+ const index = this . options . findIndex ( x => x . value === this . value ) ;
99+ const normalizeIndex = index === - 1 ? 0 : index ;
100+ let newValue = '' ;
101+ if ( normalizeIndex === 0 ) {
102+ // loop to bottom
103+ newValue = this . options [ this . options . length - 1 ] . value ;
104+ } else {
105+ newValue = this . options [ normalizeIndex - 1 ] . value ;
106+ }
107+ this . dispatchEvent ( new CustomEvent ( 'change' , {
108+ detail : {
109+ value : newValue ,
110+ } ,
111+ } ) ) ;
112+ }
60113}
0 commit comments