F #3951: Add searcher to lists (#500)

This commit is contained in:
Sergio Betanzos authored and GitHub committed 2020-11-30 11:40:49 +01:00
1 parent c256c434f2
commit 8bcd933738
21 files changed
+353 -157

No files matched your search

@@ -3,11 +3,12 @@ import PropTypes from 'prop-types'
import { Box } from '@material-ui/core'
import { Alert } from '@material-ui/lab'
import { Tr } from 'client/components/HOC'
const AlertError = ({ children, ...props }) => (
<Box pt={3} display="flex" justifyContent="center" {...props}>
<Alert severity="error" icon={false} variant="filled">
{children}
{typeof children === 'string' ? Tr(children) : children}
</Alert>
</Box>
)
@@ -46,12 +46,14 @@ const ProvisionCard = memo(
icon={isProvider ? <ProviderIcon /> : <ProvisionIcon />}
{...(imgAsAvatar
? {
icon: <Avatar
src={isExternalURL ? image : `${STATIC_FILES_URL}/${image}`}
variant="rounded"
style={{ width: 100, height: 80 }}
imgProps={{ onError }}
/>
icon: image && (
<Avatar
src={isExternalURL ? image : `${STATIC_FILES_URL}/${image}`}
variant="rounded"
style={{ width: 100, height: 80 }}
imgProps={{ onError }}
/>
)
}
: { mediaProps: { component: 'img', image, onError } }
)}
@@ -0,0 +1,49 @@
import * as React from 'react'
import PropTypes from 'prop-types'
import clsx from 'clsx'
import { makeStyles, Fab } from '@material-ui/core'
const useStyles = makeStyles(theme => ({
root: {
transition: '0.5s ease',
zIndex: theme.zIndex.appBar,
position: 'absolute',
bottom: 60,
right: theme.spacing(5)
}
}))
const FloatingActionButton = React.memo(
({ icon, className, ...props }) => {
const classes = useStyles()
return (
<Fab className={clsx(classes.root, className)} {...props}>
{icon}
</Fab>
)
}
)
FloatingActionButton.propTypes = {
icon: PropTypes.node.isRequired,
className: PropTypes.string,
color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']),
disabled: PropTypes.bool,
size: PropTypes.oneOf(['large', 'medium', 'small']),
variant: PropTypes.oneOf(['extended', 'round'])
}
FloatingActionButton.defaultProps = {
icon: undefined,
className: undefined,
color: 'primary',
disabled: false,
size: 'large',
variant: 'round'
}
FloatingActionButton.displayName = 'FloatingActionButton'
export default FloatingActionButton
@@ -1,4 +1,4 @@
import React from 'react'
import * as React from 'react'
import PropTypes from 'prop-types'
import { makeStyles, CircularProgress, Button, Fab } from '@material-ui/core'
@@ -25,22 +25,25 @@ ButtonComponent.propTypes = {
children: PropTypes.any
}
const SubmitButton = ({ isSubmitting, label, fab, ...props }) => {
const classes = useStyles()
const SubmitButton = React.memo(
({ isSubmitting, label, fab, ...props }) => {
const classes = useStyles()
return (
<ButtonComponent
color="primary"
className={classes.root}
disabled={isSubmitting}
fab={fab}
{...props}
>
{isSubmitting && <CircularProgress size={24} />}
{!isSubmitting && (label ?? Tr(T.Submit))}
</ButtonComponent>
)
}
return (
<ButtonComponent
color="primary"
className={classes.root}
disabled={isSubmitting}
fab={fab}
{...props}
>
{isSubmitting && <CircularProgress size={24} />}
{!isSubmitting && (label ?? Tr(T.Submit))}
</ButtonComponent>
)
},
(prev, next) => prev.isSubmitting === next.isSubmitting
)
SubmitButton.propTypes = {
fab: PropTypes.bool,
@@ -1,29 +1,19 @@
import React, { memo } from 'react'
import PropTypes from 'prop-types'
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import {
makeStyles,
CardActionArea,
CardContent,
Card,
Grid,
LinearProgress
CardActionArea, Card, Grid, LinearProgress, useMediaQuery
} from '@material-ui/core'
import AddIcon from '@material-ui/icons/Add'
import { EmptyCard } from 'client/components/Cards'
const useStyles = makeStyles(() => ({
cardPlus: {
height: '100%',
minHeight: 140,
display: 'flex',
textAlign: 'center'
},
loading: { width: '100%' }
}))
import { EmptyCard } from 'client/components/Cards'
import FloatingActionButton from 'client/components/Fab'
import listCardsStyles from 'client/components/List/ListCards/styles'
const ListCards = memo(({
list,
keyProp,
breakpoints,
handleCreate,
ButtonCreateComponent,
@@ -33,7 +23,8 @@ const ListCards = memo(({
displayEmpty,
isLoading
}) => {
const classes = useStyles()
const classes = listCardsStyles()
const isMobile = useMediaQuery(theme => theme.breakpoints.only('xs'))
if (isLoading) {
return <LinearProgress className={classes.loading} />
@@ -42,29 +33,38 @@ const ListCards = memo(({
return (
<Grid container spacing={3}>
{/* CREATE CARD COMPONENT */}
{handleCreate && (
<Grid item {...breakpoints}>
{ButtonCreateComponent ? (
<ButtonCreateComponent onClick={handleCreate} />
) : (
{handleCreate && (ButtonCreateComponent ? (
<ButtonCreateComponent onClick={handleCreate} />
) : (
isMobile ? (
<FloatingActionButton icon={<AddIcon />} onClick={handleCreate} />
) : (
<Grid item {...breakpoints}>
<Card className={classes.cardPlus} raised>
<CardActionArea onClick={handleCreate}>
<CardContent>
<AddIcon />
</CardContent>
<AddIcon />
</CardActionArea>
</Card>
)}
</Grid>
)}
</Grid>
)
))}
{/* LIST */}
{list.length > 0 ? (
list?.map((value, index) => (
<Grid key={`card-${index}`} item {...breakpoints}>
<CardComponent value={value} {...cardsProps({ index, value })} />
</Grid>
))
<TransitionGroup component={null}>
{list?.map((value, index) => (
<CSSTransition
// use key to render transition (default: id or ID)
key={`card-${value[keyProp] ?? value[String(keyProp).toUpperCase()]}`}
classNames={classes.item}
timeout={400}
>
<Grid item {...breakpoints}>
<CardComponent value={value} {...cardsProps({ index, value })} />
</Grid>
</CSSTransition>
))}
</TransitionGroup>
) : (
(displayEmpty || EmptyComponent) && (
<Grid item {...breakpoints}>
@@ -74,12 +74,14 @@ const ListCards = memo(({
)}
</Grid>
)
})
}, (prev, next) =>
prev.isLoading === next.isLoading && prev.list === next.list)
const gridValues = [false, 'auto', true, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
ListCards.propTypes = {
list: PropTypes.arrayOf(PropTypes.any).isRequired,
keyProp: PropTypes.string,
breakpoints: PropTypes.shape({
xs: PropTypes.oneOf(gridValues),
sm: PropTypes.oneOf(gridValues),
@@ -110,6 +112,7 @@ ListCards.propTypes = {
ListCards.defaultProps = {
list: [],
keyProp: 'id',
breakpoints: { xs: 12, sm: 4, md: 3, lg: 2 },
handleCreate: undefined,
ButtonCreateComponent: undefined,
@@ -0,0 +1,23 @@
import { makeStyles } from '@material-ui/core'
export default makeStyles(() => ({
cardPlus: {
height: '100%',
minHeight: 140,
display: 'flex',
textAlign: 'center'
},
loading: { width: '100%' },
item: {
'&-enter': { opacity: 0 },
'&-enter-active': {
opacity: 1,
transition: 'opacity 400ms ease-in'
},
'&-exit': { opacity: 1 },
'&-exit-active': {
opacity: 0,
transition: 'opacity 400ms ease-in'
}
}
}))
@@ -1,57 +0,0 @@
import React, { memo } from 'react'
import PropTypes from 'prop-types'
import { makeStyles, Box, Typography, Divider } from '@material-ui/core'
import RefreshIcon from '@material-ui/icons/Autorenew'
import SubmitButton from 'client/components/FormControl/SubmitButton'
const useStyles = makeStyles(theme => ({
title: { marginLeft: theme.spacing(1) }
}))
const ListHeader = memo(({
title,
hasReloadButton,
reloadButtonProps
}) => {
const classes = useStyles()
return (
<>
<Box p={3} display="flex" alignItems="center">
{hasReloadButton && (
<SubmitButton fab label={<RefreshIcon />} {...reloadButtonProps} />
)}
{title && (
<Typography variant="h5" className={classes.title}>
{title}
</Typography>
)}
</Box>
<Divider />
</>
)
})
ListHeader.propTypes = {
title: PropTypes.string,
hasReloadButton: PropTypes.bool,
reloadButtonProps: PropTypes.shape({
onClick: PropTypes.func,
isSubmitting: PropTypes.bool
})
}
ListHeader.defaultProps = {
title: undefined,
hasReloadButton: false,
reloadButtonProps: {
onClick: undefined,
isSubmitting: false
}
}
ListHeader.displayName = 'ListHeader'
export default ListHeader
@@ -0,0 +1,83 @@
import React, { memo } from 'react'
import PropTypes from 'prop-types'
import { Box, Typography, InputBase } from '@material-ui/core'
import SearchIcon from '@material-ui/icons/Search'
import RefreshIcon from '@material-ui/icons/Autorenew'
import SubmitButton from 'client/components/FormControl/SubmitButton'
import listHeaderStyles from 'client/components/List/ListHeader/styles'
import { Tr } from 'client/components/HOC'
const ListHeader = memo(({
title,
hasReloadButton,
reloadButtonProps,
hasSearch,
searchProps
}) => {
const classes = listHeaderStyles()
const { handleChange } = searchProps
return (
<Box p={3} className={classes.root}>
{hasReloadButton && (
<SubmitButton fab label={<RefreshIcon />} {...reloadButtonProps} />
)}
{title && (
<Typography variant="h5" className={classes.title}>
{Tr(title)}
</Typography>
)}
{hasSearch && (
<Box className={classes.search}>
<Box className={classes.searchIcon}>
<SearchIcon />
</Box>
<InputBase
type="search"
onChange={handleChange}
fullWidth
placeholder="Search..."
classes={{
root: classes.inputRoot,
input: classes.inputInput
}}
/>
</Box>
)}
</Box>
)
}, (prev, next) =>
prev?.reloadButtonProps.isSubmitting === next?.reloadButtonProps.isSubmitting)
ListHeader.propTypes = {
title: PropTypes.string,
hasReloadButton: PropTypes.bool,
reloadButtonProps: PropTypes.shape({
onClick: PropTypes.func,
isSubmitting: PropTypes.bool
}),
hasSearch: PropTypes.bool,
searchProps: PropTypes.shape({
query: PropTypes.string,
handleChange: PropTypes.func
})
}
ListHeader.defaultProps = {
title: undefined,
hasReloadButton: false,
reloadButtonProps: {
onClick: undefined,
isSubmitting: false
},
searchProps: {
query: undefined,
handleChange: undefined
}
}
ListHeader.displayName = 'ListHeader'
export default ListHeader
@@ -0,0 +1,43 @@
import { makeStyles, fade } from '@material-ui/core'
export default makeStyles(theme => ({
root: {
display: 'flex',
alignItems: 'center',
flexWrap: 'wrap'
},
title: {
marginLeft: theme.spacing(1),
flexGrow: 1
},
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.primary.main, 0.15),
'&:hover': {
backgroundColor: fade(theme.palette.primary.main, 0.25)
},
margin: theme.spacing(3, 0),
width: '100%',
[theme.breakpoints.up('sm')]: {
marginLeft: theme.spacing(1),
width: 'auto'
}
},
searchIcon: {
padding: theme.spacing(0, 2),
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center'
},
inputRoot: { color: 'inherit' },
inputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
width: '100%'
}
}))
@@ -16,7 +16,7 @@ const Search = ({
const [query, setQuery] = useState('')
const [result, setResult] = useState(undefined)
const listFuse = useMemo(
() => new Fuse(list, listOptions, Fuse.createIndex(listOptions.keys, list)),
() => new Fuse(list, listOptions, Fuse.createIndex(listOptions?.keys, list)),
[list, listOptions]
)
@@ -72,7 +72,7 @@ Search.propTypes = {
Search.defaultProps = {
list: [],
listOptions: {},
listOptions: { keys: [] },
renderResult: item => item,
startAdornment: undefined,
searchBoxProps: undefined
@@ -9,11 +9,7 @@ import DialogInfo from 'client/containers/ApplicationsInstances/DialogInfo'
import { ListHeader, ListCards } from 'client/components/List'
import AlertError from 'client/components/Alerts/Error'
import { ApplicationCard, EmptyCard } from 'client/components/Cards'
import { DONE } from 'client/constants/states'
import { APPLICATION_STATES } from 'client/constants/flow'
import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
import { T, DONE, APPLICATION_STATES } from 'client/constants'
function ApplicationsInstances () {
const { applications, getApplications } = useApplication()
@@ -33,7 +29,7 @@ function ApplicationsInstances () {
return (
<Container disableGutters>
<ListHeader
title={Tr(T.ApplicationsInstancesLabel)}
title={T.ApplicationsInstances}
hasReloadButton
reloadButtonProps={{
onClick: () => fetchRequest(undefined, { reload: true, delay: 500 }),
@@ -42,9 +38,7 @@ function ApplicationsInstances () {
/>
<Box p={3}>
{error ? (
<AlertError>
{Tr(T.CannotConnectOneFlow)}
</AlertError>
<AlertError>{T.CannotConnectOneFlow}</AlertError>
) : (
<ListCards
list={list}
@@ -11,8 +11,6 @@ import DeployForm from 'client/containers/ApplicationsTemplates/Form/Deploy'
import { ListHeader, ListCards } from 'client/components/List'
import AlertError from 'client/components/Alerts/Error'
import { ApplicationTemplateCard } from 'client/components/Cards'
import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
function ApplicationsTemplates () {
@@ -31,7 +29,7 @@ function ApplicationsTemplates () {
return (
<Container disableGutters>
<ListHeader
title={Tr(T.ApplicationsTemplatesLabel)}
title={T.ApplicationsTemplates}
hasReloadButton
reloadButtonProps={{
onClick: () => fetchRequest(undefined, { reload: true, delay: 500 }),
@@ -40,9 +38,7 @@ function ApplicationsTemplates () {
/>
<Box p={3}>
{error ? (
<AlertError>
{Tr(T.CannotConnectOneFlow)}
</AlertError>
<AlertError>{T.CannotConnectOneFlow}</AlertError>
) : (
<ListCards
list={applicationsTemplates}
@@ -44,6 +44,7 @@ const Locations = () => ({
return (
<ListCards
list={locationsList}
keyProp='key'
EmptyComponent={<EmptyCard title={'Your locations list is empty'} />}
CardComponent={LocationCard}
cardsProps={({ value: { key } }) => {
@@ -55,6 +55,7 @@ const Provider = () => ({
const isSelected = data?.some(selected => selected === name)
return {
id: name.replace(/\s/g, ''),
isProvider: true,
isSelected,
handleClick: () => handleClick(name, isSelected)
@@ -8,6 +8,7 @@ import DeleteIcon from '@material-ui/icons/Delete'
import { PATH } from 'client/router/provision'
import useProvision from 'client/hooks/useProvision'
import useFetch from 'client/hooks/useFetch'
import useSearch from 'client/hooks/useSearch'
import { ListHeader, ListCards } from 'client/components/List'
import AlertError from 'client/components/Alerts/Error'
@@ -15,39 +16,40 @@ import { ProvisionCard } from 'client/components/Cards'
import { DialogRequest } from 'client/components/Dialogs'
import Information from 'client/containers/Providers/Sections/info'
import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
function Providers () {
const history = useHistory()
const [showDialog, setShowDialog] = useState(false)
const { providers, getProviders, getProvider, deleteProvider } = useProvision()
const {
error,
fetchRequest,
loading,
reloading
} = useFetch(getProviders)
const { error, fetchRequest, loading, reloading } = useFetch(getProviders)
const { result, handleChange } = useSearch({
list: providers,
listOptions: { shouldSort: true, keys: ['ID', 'NAME'] }
})
useEffect(() => { fetchRequest() }, [])
return (
<Container disableGutters>
<ListHeader
title={Tr(T.Providers)}
title={T.Providers}
hasReloadButton
reloadButtonProps={{
onClick: () => fetchRequest(undefined, { reload: true }),
isSubmitting: Boolean(loading || reloading)
}}
hasSearch
searchProps={{ handleChange }}
/>
<Box p={3}>
{error ? (
<AlertError>{Tr(T.CannotConnectOneProvision)}</AlertError>
<AlertError>{T.CannotConnectOneProvision}</AlertError>
) : (
<ListCards
list={providers}
list={result ?? providers}
isLoading={providers.length === 0 && loading}
handleCreate={() => history.push(PATH.PROVIDERS.CREATE)}
CardComponent={ProvisionCard}
@@ -56,6 +56,7 @@ const Provision = () => ({
const { provision: { provider } = {} } = defaults
return {
id: name.replace(/\s/g, ''),
isSelected,
handleClick: () => handleClick(name, provider, isSelected)
}
@@ -7,6 +7,7 @@ import DeleteIcon from '@material-ui/icons/Delete'
import { PATH } from 'client/router/provision'
import useProvision from 'client/hooks/useProvision'
import useFetch from 'client/hooks/useFetch'
import useSearch from 'client/hooks/useSearch'
import { ListHeader, ListCards } from 'client/components/List'
import AlertError from 'client/components/Alerts/Error'
@@ -14,41 +15,41 @@ import { ProvisionCard } from 'client/components/Cards'
import { DialogRequest } from 'client/components/Dialogs'
import DialogInfo from 'client/containers/Provisions/DialogInfo'
import { Tr } from 'client/components/HOC'
import { T } from 'client/constants'
function Provisions () {
const history = useHistory()
const [showDialog, setShowDialog] = useState(false)
const {
provisions,
getProvisions,
getProvision,
deleteProvision
} = useProvision()
const { provisions, getProvisions, getProvision, deleteProvision } = useProvision()
const { error, fetchRequest, loading, reloading } = useFetch(getProvisions)
const { result, handleChange } = useSearch({
list: provisions,
listOptions: { shouldSort: true, keys: ['ID', 'NAME'] }
})
useEffect(() => { fetchRequest() }, [])
return (
<Container disableGutters>
<ListHeader
title={Tr(T.Provisions)}
title={T.Provisions}
hasReloadButton
reloadButtonProps={{
onClick: () => fetchRequest(undefined, { reload: true }),
isSubmitting: Boolean(loading || reloading)
}}
hasSearch
searchProps={{ handleChange }}
/>
<Box p={3}>
{error ? (
<AlertError>{Tr(T.CannotConnectOneProvision)}</AlertError>
<AlertError>{T.CannotConnectOneProvision}</AlertError>
) : (
<ListCards
list={provisions}
isLoading={provisions.length === 0 && loading}
list={result ?? provisions}
isLoading={provisions.length > 0 && loading}
handleCreate={() => history.push(PATH.PROVISIONS.CREATE)}
CardComponent={ProvisionCard}
cardsProps={({ value: { ID, NAME } }) => ({
+1 -1
View File
@@ -111,9 +111,9 @@ export default function useAuth () {
logout,
getAuthInfo,
setPrimaryGroup,
isLogged: !!jwt,
authUser,
isOneAdmin: authUser?.ID === ONEADMIN_ID,
isLogged: Boolean(jwt),
isLoginInProcess,
isLoading,
firstRender,
@@ -10,7 +10,7 @@ const useNearScreen = ({ externalRef, distance, once = true }) => {
const element = externalRef ? externalRef.current : fromRef.current
const onChange = entries => {
element && entries.forEach(({ isIntersecting }) => {
observer && entries.forEach(({ isIntersecting }) => {
if (isIntersecting) {
setShow(true)
once && observer.disconnect()
@@ -0,0 +1,50 @@
import { useState, useMemo, useCallback } from 'react'
import PropTypes from 'prop-types'
import { debounce } from '@material-ui/core'
import Fuse from 'fuse.js'
function useSearch ({ list, listOptions }) {
const [query, setQuery] = useState('')
const [result, setResult] = useState(undefined)
const listFuse = useMemo(
() => new Fuse(list, listOptions, Fuse.createIndex(listOptions?.keys, list)),
[list, listOptions]
)
const debounceResult = useCallback(
debounce(value => {
const search = listFuse.search(value)?.map(({ item }) => item)
setResult(value ? search : undefined)
}, 1000),
[list]
)
const handleChange = event => {
const { value: nextValue } = event?.target
setQuery(nextValue)
debounceResult(nextValue)
}
return { query, result, handleChange }
}
useSearch.propTypes = {
list: PropTypes.arrayOf(PropTypes.object).isRequired,
listOptions: PropTypes.shape({
isCaseSensitive: PropTypes.bool,
shouldSort: PropTypes.bool,
sortFn: PropTypes.func,
keys: PropTypes.arrayOf(PropTypes.string)
})
}
useSearch.defaultProps = {
list: [],
listOptions: { keys: [] }
}
export default useSearch
+2 -2
View File
@@ -67,7 +67,7 @@ export default {
},
'&-enter-active': {
opacity: 1,
transition: 'opacity 100ms'
transition: 'opacity 100ms ease-in'
},
'&-exit': {
opacity: 1,
@@ -75,7 +75,7 @@ export default {
},
'&-exit-active': {
opacity: 0,
transition: 'opacity 100ms'
transition: 'opacity 100ms ease-in'
}
}
}