Improve snappiness and add speed setting.
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
|
||||
// Playback speed for the battle replay. A multiplier: 2 means everything (JS
|
||||
// step timers and CSS animation durations alike) runs twice as fast. The choice
|
||||
// is remembered across sessions in localStorage so a player who likes it quick
|
||||
// doesn't have to re-set it every battle.
|
||||
|
||||
const STORAGE_KEY = 'sap:battleSpeed'
|
||||
|
||||
// The values offered in the speed picker. 1 is the honest, savour-it pace;
|
||||
// higher values are for players who've seen enough clashes for one evening.
|
||||
export const SPEED_OPTIONS = [0.5, 1, 1.5, 2, 3] as const
|
||||
|
||||
const DEFAULT_SPEED = 1
|
||||
|
||||
function load(): number {
|
||||
if (typeof localStorage === 'undefined') return DEFAULT_SPEED
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
const n = raw ? Number(raw) : NaN
|
||||
// Guard against stale/garbage values, and snap to a known option.
|
||||
return SPEED_OPTIONS.includes(n as (typeof SPEED_OPTIONS)[number]) ? n : DEFAULT_SPEED
|
||||
}
|
||||
|
||||
export function useBattleSpeed(): [number, (n: number) => void] {
|
||||
const [speed, setSpeed] = useState<number>(load)
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, String(speed))
|
||||
} catch {
|
||||
// Private-mode / storage-disabled: keep the in-memory value, just don't persist.
|
||||
}
|
||||
}, [speed])
|
||||
|
||||
const set = useCallback((n: number) => setSpeed(n), [])
|
||||
return [speed, set]
|
||||
}
|
||||
Reference in New Issue
Block a user