Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / components / hooks / useAutocompleteAriaProps.tsx
blobd48c5507f44deb61785f2293c172fbfc0602693f
1 import { c, msgid } from 'ttag';
3 const useAutocompleteAriaProps = ({ baseId, selectedSuggest }: { baseId: string; selectedSuggest?: number }) => {
4     const helpTextId = `${baseId}-help-text`;
5     const helpText = (
6         <span id={helpTextId} className="sr-only">
7             {c('Help')
8                 .t`Use Up and Down keys to access and browse suggestions after input. Press Enter to confirm your choice, or Escape to close the suggestions box.`}
9         </span>
10     );
11     const getNumberHelpText = (numberOfSuggests: number) =>
12         numberOfSuggests > 0 ? (
13             <div className="sr-only" aria-atomic="true" aria-live="assertive">
14                 {c('Help').ngettext(
15                     msgid`Found ${numberOfSuggests} suggestion, use keyboard to navigate.`,
16                     `Found ${numberOfSuggests} suggestions, use keyboard to navigate.`,
17                     numberOfSuggests
18                 )}
19             </div>
20         ) : (
21             ''
22         );
23     const suggestionsId = `${baseId}-suggestions`;
24     const getOptionId = (idx: number) => `${baseId}-option-${idx}`;
25     return {
26         labelAriaProps: {
27             for: baseId,
28         },
29         inputAriaProps: {
30             id: baseId,
31             role: 'combobox',
32             'aria-autocomplete': 'list' as const,
33             'aria-owns': suggestionsId,
34             'aria-activedescendant': selectedSuggest !== undefined ? getOptionId(selectedSuggest) : undefined,
35             'aria-describedby': helpTextId,
36             autoCorrect: 'off',
37             autoCapitalize: 'off',
38             spellCheck: false,
39             autoComplete: 'off',
40         },
41         suggestionsAriaProps: {
42             role: 'listbox',
43             id: suggestionsId,
44         },
45         getAriaPropsForOption: (idx: number) => ({
46             id: getOptionId(idx),
47             role: 'option',
48         }),
49         helpText,
50         getNumberHelpText,
51     };
54 export default useAutocompleteAriaProps;