refactor: smooth rotation (#436)

This commit is contained in:
Avan 2025-01-01 00:42:21 +08:00 committed by GitHub
parent c8269c3496
commit c7e252d418
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -15,20 +15,39 @@ const FloatingApp: React.FC = () => {
const [upload, setUpload] = useState(0) const [upload, setUpload] = useState(0)
const [download, setDownload] = useState(0) const [download, setDownload] = useState(0)
const slowest = 10
const fastest = 0.1
const spinDuration = useMemo(() => { // 根据总速率计算旋转速度
let duration = upload + download === 0 ? slowest : 409600 / (upload + download) const spinSpeed = useMemo(() => {
if (duration > slowest) { const total = upload + download
duration = slowest if (total === 0) return 0
} if (total < 1024) return 2
if (duration < fastest) { if (total < 1024 * 1024) return 3
duration = fastest if (total < 1024 * 1024 * 1024) return 4
} return 5
return duration
}, [upload, download]) }, [upload, download])
const [rotation, setRotation] = useState(0)
useEffect(() => {
if (!spinFloatingIcon) return
let animationFrameId: number
const animate = (): void => {
setRotation((prev) => {
if (prev === 360) {
return 0
}
return prev + spinSpeed
})
animationFrameId = requestAnimationFrame(animate)
}
animationFrameId = requestAnimationFrame(animate)
return (): void => {
cancelAnimationFrame(animationFrameId)
}
}, [spinSpeed, spinFloatingIcon])
useEffect(() => { useEffect(() => {
window.electron.ipcRenderer.on('mihomoTraffic', async (_e, info: IMihomoTrafficInfo) => { window.electron.ipcRenderer.on('mihomoTraffic', async (_e, info: IMihomoTrafficInfo) => {
setUpload(info.up) setUpload(info.up)
@ -51,7 +70,14 @@ const FloatingApp: React.FC = () => {
onClick={() => { onClick={() => {
triggerMainWindow() triggerMainWindow()
}} }}
style={spinFloatingIcon ? { animation: `spin ${spinDuration}s linear infinite` } : {}} style={
spinFloatingIcon
? {
transform: `rotate(${rotation}deg)`,
transition: 'transform 0.1s linear'
}
: {}
}
className={`app-nodrag cursor-pointer floating-thumb ${tunEnabled ? 'bg-secondary' : sysProxyEnabled ? 'bg-primary' : 'bg-default'} hover:opacity-hover rounded-full h-[calc(100%-4px)] aspect-square`} className={`app-nodrag cursor-pointer floating-thumb ${tunEnabled ? 'bg-secondary' : sysProxyEnabled ? 'bg-primary' : 'bg-default'} hover:opacity-hover rounded-full h-[calc(100%-4px)] aspect-square`}
> >
<MihomoIcon className="floating-icon text-primary-foreground h-full leading-full text-[22px] mx-auto" /> <MihomoIcon className="floating-icon text-primary-foreground h-full leading-full text-[22px] mx-auto" />