@@ -6,10 +6,19 @@ import {getImplicitAriaRoles} from './role-helpers'
6
6
7
7
const normalize = getDefaultNormalizer ( )
8
8
9
- function getLabelTextFor ( element ) {
10
- let label =
11
- element . labels &&
12
- Array . from ( element . labels ) . find ( el => Boolean ( normalize ( el . textContent ) ) )
9
+ function isElementWithLabels (
10
+ element : HTMLElement ,
11
+ ) : element is HTMLInputElement {
12
+ // We cast with HTMLInputElement, but it could be a HTMLSelectElement
13
+ return ( element as HTMLInputElement ) . labels !== undefined
14
+ }
15
+
16
+ function getLabelTextFor ( element : HTMLElement ) : string | undefined {
17
+ let label : HTMLLabelElement | undefined =
18
+ isElementWithLabels ( element ) &&
19
+ Array . from ( element . labels ) . find ( ( el : HTMLLabelElement ) =>
20
+ Boolean ( normalize ( el . textContent ) ) ,
21
+ )
13
22
14
23
// non form elements that are using aria-labelledby won't be included in `element.labels`
15
24
if ( ! label ) {
@@ -30,7 +39,16 @@ function escapeRegExp(string) {
30
39
return string . replace ( / [ . * + \- ? ^ $ { } ( ) | [ \] \\ ] / g, '\\$&' ) // $& means the whole matched string
31
40
}
32
41
33
- function makeSuggestion ( queryName , content , { variant = 'get' , name} ) {
42
+ interface MakeSuggestionOptions {
43
+ variant ?: string
44
+ name ?: string
45
+ }
46
+
47
+ function makeSuggestion (
48
+ queryName ,
49
+ content ,
50
+ { variant = 'get' , name} : MakeSuggestionOptions ,
51
+ ) {
34
52
const queryArgs = [ content ]
35
53
36
54
if ( name ) {
@@ -55,7 +73,20 @@ function makeSuggestion(queryName, content, {variant = 'get', name}) {
55
73
}
56
74
}
57
75
58
- export function getSuggestedQuery ( element , variant ) {
76
+ function isElementWithValue ( element : HTMLElement ) : element is HTMLInputElement {
77
+ // We cast with HTMLInputElement, but it could be a HTMLSelectElement
78
+ return Boolean ( ( element as HTMLInputElement ) . value )
79
+ }
80
+
81
+ export interface Suggestion {
82
+ queryName : string
83
+ toString ( ) : string
84
+ }
85
+
86
+ export function getSuggestedQuery (
87
+ element : HTMLElement ,
88
+ variant ?: string ,
89
+ ) : Suggestion | undefined {
59
90
const role =
60
91
element . getAttribute ( 'role' ) ?? getImplicitAriaRoles ( element ) ?. [ 0 ]
61
92
if ( role ) {
@@ -80,7 +111,7 @@ export function getSuggestedQuery(element, variant) {
80
111
return makeSuggestion ( 'Text' , textContent , { variant} )
81
112
}
82
113
83
- if ( element . value ) {
114
+ if ( isElementWithValue ( element ) ) {
84
115
return makeSuggestion ( 'DisplayValue' , normalize ( element . value ) , { variant} )
85
116
}
86
117
0 commit comments