Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve star highlighting behavior #24

Merged
merged 6 commits into from
Nov 27, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 35 additions & 10 deletions components/Stars.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,30 @@ export type StarsProps = {
updateCallback?: (update: number) => void
}

const Star = ({ index, selected }: { index?: string; selected?: boolean }) => {
let fill = 'rgba(30, 30, 30, 0.3)'
if (selected) {
fill = 'rgba(255, 214, 0, 0.8)'
}
const Star = ({
hovered,
index,
onStarHover,
onStarLeave,
selected
}: {
hovered?: boolean
index?: string
onStarHover: () => void
onStarLeave: () => void
selected?: boolean
}) => {
// Fill with yellow if the star is selected or hovered, otherwise fill is gray
const fill =
selected || hovered ? 'rgba(255, 214, 0, 0.8)' : 'rgba(30, 30, 30, 0.3'

return (
<svg
aria-label={index ? `${Number(index) + 1} stars` : ''}
className={starStyles.star}
height="55"
onMouseEnter={onStarHover}
onMouseLeave={onStarLeave}
width="54"
xmlns="http://www.w3.org/2000/svg"
>
Expand All @@ -38,6 +51,7 @@ const Stars = ({
updateCallback
}: StarsProps) => {
const [selectedOption, updateSelectedOption] = useState(defaultOptionIndex)
const [hoveredStar, setHoveredStar] = useState<number | null>(null)

useEffect(
() => {
Expand All @@ -51,6 +65,15 @@ const Stars = ({
const onStarChange = useCallback((e) => {
return updateSelectedOption(parseInt((e.target as HTMLInputElement).value))
}, [])

const handleStarHover = (index: number) => {
setHoveredStar(index)
}

const handleStarLeave = () => {
setHoveredStar(null)
}

return (
<div className={starStyles.container}>
{Array(number)
Expand Down Expand Up @@ -80,11 +103,13 @@ const Stars = ({
/>
<label htmlFor={`star-rating-${index}`}>
<span>
{selectedOption >= index ? (
<Star index={`${index}`} selected />
) : (
<Star />
)}
<Star
hovered={hoveredStar !== null && index <= hoveredStar}
index={`${index}`}
onStarHover={() => handleStarHover(index)}
onStarLeave={handleStarLeave}
selected={selectedOption >= index}
/>
</span>
</label>
</React.Fragment>
Expand Down
2 changes: 1 addition & 1 deletion styles/Stars.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
margin-right: 15px;
}
.star:hover {
opacity: 0.5;
cursor: pointer;
}

.input:focus + label path {
Expand Down
Loading