quintodrome/ui/src/common/StarButton.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

105 lines
2.4 KiB
JavaScript
Raw Normal View History

import React, { useCallback, useEffect, useRef, useState } from 'react'
2020-08-22 19:41:25 -08:00
import PropTypes from 'prop-types'
import { useNotify, useDataProvider } from 'react-admin'
2020-08-22 19:41:25 -08:00
import StarIcon from '@material-ui/icons/Star'
import StarBorderIcon from '@material-ui/icons/StarBorder'
import IconButton from '@material-ui/core/IconButton'
import { makeStyles } from '@material-ui/core/styles'
import subsonic from '../subsonic'
2020-08-22 19:41:25 -08:00
const useStyles = makeStyles({
star: {
color: (props) => props.color,
visibility: (props) =>
props.visible === false
? 'hidden'
: props.starred
? 'visible'
: 'inherit',
2020-08-22 19:41:25 -08:00
},
})
2020-11-13 17:11:24 -09:00
export const StarButton = ({
resource,
record,
color,
visible,
size,
component: Button,
addLabel,
...rest
}) => {
const [loading, setLoading] = useState(false)
2020-08-22 19:41:25 -08:00
const classes = useStyles({ color, visible, starred: record.starred })
const notify = useNotify()
const mountedRef = useRef(false)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
2020-08-22 19:41:25 -08:00
}
}, [])
const dataProvider = useDataProvider()
const refreshRecord = useCallback(() => {
dataProvider.getOne(resource, { id: record.id }).then(() => {
if (mountedRef.current) {
setLoading(false)
}
})
}, [dataProvider, record.id, resource])
2020-08-22 19:41:25 -08:00
const handleToggleStar = (e) => {
e.preventDefault()
const toggleStar = record.starred ? subsonic.unstar : subsonic.star
setLoading(true)
toggleStar(record.id)
.then(refreshRecord)
.catch((e) => {
console.log('Error toggling star: ', e)
notify('ra.page.error', 'warning')
if (mountedRef.current) {
setLoading(false)
}
})
2020-08-22 19:41:25 -08:00
e.stopPropagation()
}
return (
2020-11-13 17:11:24 -09:00
<Button
2020-08-22 19:41:25 -08:00
onClick={handleToggleStar}
size={'small'}
disabled={loading}
className={classes.star}
2020-11-13 17:11:24 -09:00
{...rest}
2020-08-22 19:41:25 -08:00
>
{record.starred ? (
<StarIcon fontSize={size} />
) : (
<StarBorderIcon fontSize={size} />
)}
2020-11-13 17:11:24 -09:00
</Button>
2020-08-22 19:41:25 -08:00
)
}
StarButton.propTypes = {
resource: PropTypes.string.isRequired,
record: PropTypes.object.isRequired,
visible: PropTypes.bool,
color: PropTypes.string,
size: PropTypes.string,
2020-11-13 17:11:24 -09:00
component: PropTypes.object,
2020-08-22 19:41:25 -08:00
}
StarButton.defaultProps = {
2020-08-25 15:07:51 -08:00
addLabel: true,
record: {},
2020-08-22 19:41:25 -08:00
visible: true,
size: 'small',
2020-08-24 15:38:29 -08:00
color: 'inherit',
2020-11-13 17:11:24 -09:00
component: IconButton,
2020-08-22 19:41:25 -08:00
}