Created
June 6, 2024 07:32
-
-
Save EduardoAC/88194dda3d1e107b05c7d56e857835b3 to your computer and use it in GitHub Desktop.
Site review extension - Rating component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { MessageRate } from "../../../types/message.types" | |
import { sendMessage } from "../../messages/sendMessage" | |
import { clearUrlParams } from "../..//utils/url" | |
import "./Rating.css" | |
import { useCallback, useEffect, useState } from "react" | |
const totalRating = Array.from({ length: 5 }, (_, index) => index + 1) | |
export function Rating() { | |
const [rating, setRating] = useState<number>(0) | |
const [hover, setHover] = useState<number>(0) | |
const cleanUrl = clearUrlParams(window.location.href) | |
useEffect(() => { | |
async function loadRating(url: string) { | |
try { | |
const rate = await sendMessage<MessageRate, number>({ | |
type: "rating", | |
subType: "get", | |
data: { url }, | |
}) | |
if (rate) { | |
setRating(rate) | |
} | |
} catch (error) { | |
console.error(error) | |
} | |
} | |
loadRating(cleanUrl) | |
}, [cleanUrl]) | |
const updateRating = useCallback( | |
async (newRating: number) => { | |
try { | |
await sendMessage<MessageRate, void>({ | |
type: "rating", | |
subType: "update", | |
data: { url: cleanUrl, rate: newRating }, | |
}) | |
setRating(newRating) | |
} catch (error) { | |
console.error(error) | |
} | |
}, | |
[cleanUrl], | |
) | |
return ( | |
<div className="rating" data-testid="rating-component"> | |
{totalRating.map((star, index) => { | |
const currentRating = index + 1 | |
return ( | |
<label key={index}> | |
<input | |
key={star} | |
type="radio" | |
name="rating" | |
data-testid={`input-${index}`} | |
value={currentRating} | |
onChange={() => updateRating(currentRating)} | |
/> | |
<span | |
className="star" | |
data-testid="star" | |
style={{ | |
color: | |
currentRating <= (hover || rating) | |
? "#ffc107" | |
: "#e4e5e9", | |
}} | |
onMouseEnter={() => setHover(currentRating)} | |
onMouseLeave={() => setHover(0)} | |
> | |
★ | |
</span> | |
</label> | |
) | |
})} | |
</div> | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Up to date project file can be found on https://github.com/EduardoAC/site-review-extension/blob/master/src/contentScript/components/Rating/Rating.tsx