MCPcopy Create free account
hub / github.com/dailydotdev/apps / usePatchyIdle

Function usePatchyIdle

packages/shared/src/features/patchy/patchyIdle.ts:93–183  ·  view source on GitHub ↗
({
  isEnabled,
  isResting,
  isReading,
  prefersReducedMotion,
}: UsePatchyIdleProps)

Source from the content-addressed store, hash-verified

91const still: PatchyIdleState = { face: null, motion: null, key: 0 };
92
93export 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 }),

Callers 1

usePatchyCompanionFunction · 0.90

Calls 2

blinkLoopFunction · 0.85
actionLoopFunction · 0.85

Tested by

no test coverage detected