({
isEnabled,
isResting,
isReading,
prefersReducedMotion,
}: UsePatchyIdleProps)
| 91 | const still: PatchyIdleState = { face: null, motion: null, key: 0 }; |
| 92 | |
| 93 | export const usePatchyIdle = ({ |
| 94 | isEnabled, |
| 95 | isResting, |
| 96 | isReading, |
| 97 | prefersReducedMotion, |
| 98 | }: UsePatchyIdleProps): PatchyIdleState => { |
| 99 | const [state, setState] = useState<PatchyIdleState>(still); |
| 100 | const keyRef = useRef(0); |
| 101 | const readingRef = useRef(isReading); |
| 102 | readingRef.current = isReading; |
| 103 | |
| 104 | useEffect(() => { |
| 105 | if (!isEnabled || isResting) { |
| 106 | setState(still); |
| 107 | return undefined; |
| 108 | } |
| 109 | const timers = new Set<ReturnType<typeof setTimeout>>(); |
| 110 | let isBusy = false; |
| 111 | const later = (fn: () => void, ms: number) => { |
| 112 | const id = setTimeout(() => { |
| 113 | timers.delete(id); |
| 114 | fn(); |
| 115 | }, ms); |
| 116 | timers.add(id); |
| 117 | }; |
| 118 | const play = (name: PatchyIdleActionName) => { |
| 119 | if (document.hidden) { |
| 120 | return; |
| 121 | } |
| 122 | const action: PatchyIdleAction = patchyIdleActions[name]; |
| 123 | isBusy = true; |
| 124 | keyRef.current += 1; |
| 125 | setState({ |
| 126 | face: action.face, |
| 127 | motion: prefersReducedMotion ? null : (action.motion ?? null), |
| 128 | key: keyRef.current, |
| 129 | }); |
| 130 | later(() => { |
| 131 | isBusy = false; |
| 132 | setState((current) => ({ ...current, face: null, motion: null })); |
| 133 | }, action.ms); |
| 134 | }; |
| 135 | const blinkLoop = () => { |
| 136 | later(() => { |
| 137 | if (!isBusy) { |
| 138 | play('blink'); |
| 139 | } |
| 140 | blinkLoop(); |
| 141 | }, between(BLINK_EVERY_MS)); |
| 142 | }; |
| 143 | const actionLoop = () => { |
| 144 | later(() => { |
| 145 | if (!isBusy && !prefersReducedMotion) { |
| 146 | play( |
| 147 | pickPatchyIdleAction(Math.random(), { |
| 148 | isReading: readingRef.current, |
| 149 | isEvening: new Date().getHours() >= 21, |
| 150 | }), |
no test coverage detected