refs #14565-login-as
[arvados.git] / src / views-components / search-bar / search-bar-autocomplete-view.tsx
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 import * as React from 'react';
6 import { Paper, StyleRulesCallback, withStyles, WithStyles, List, ListItem, ListItemText } from '@material-ui/core';
7 import { GroupContentsResource } from '~/services/groups-service/groups-service';
8 import Highlighter from "react-highlight-words";
9 import { SearchBarSelectedItem } from "~/store/search-bar/search-bar-reducer";
10
11 type CssRules = 'searchView' | 'list' | 'listItem';
12
13 const styles: StyleRulesCallback<CssRules> = theme => {
14     return {
15         searchView: {
16             borderRadius: `0 0 ${theme.spacing.unit / 2}px ${theme.spacing.unit / 2}px`
17         },
18         list: {
19             padding: 0
20         },
21         listItem: {
22             paddingLeft: theme.spacing.unit,
23             paddingRight: theme.spacing.unit * 2,
24         }
25     };
26 };
27
28 export interface SearchBarAutocompleteViewDataProps {
29     searchResults: GroupContentsResource[];
30     searchValue?: string;
31     selectedItem: SearchBarSelectedItem;
32 }
33
34 export interface SearchBarAutocompleteViewActionProps {
35     navigateTo: (uuid: string) => void;
36 }
37
38 type SearchBarAutocompleteViewProps = SearchBarAutocompleteViewDataProps & SearchBarAutocompleteViewActionProps & WithStyles<CssRules>;
39
40 export const SearchBarAutocompleteView = withStyles(styles)(
41     ({ classes, searchResults, searchValue, navigateTo, selectedItem }: SearchBarAutocompleteViewProps) => {
42         return <Paper className={classes.searchView}>
43             <List component="nav" className={classes.list}>
44                 <ListItem button className={classes.listItem} selected={!selectedItem || searchValue === selectedItem.id}>
45                     <ListItemText secondary={searchValue}/>
46                 </ListItem>
47                 {searchResults.map((item: GroupContentsResource) =>
48                     <ListItem button key={item.uuid} className={classes.listItem} selected={item.uuid === selectedItem.id}>
49                         <ListItemText secondary={getFormattedText(item.name, searchValue)}
50                                       onClick={() => navigateTo(item.uuid)}/>
51                     </ListItem>
52                 )}
53             </List>
54         </Paper>;
55     });
56
57 const getFormattedText = (textToHighlight: string, searchString = '') => {
58     return <Highlighter searchWords={[searchString]} autoEscape={true} textToHighlight={textToHighlight} />;
59 };