useGenerator 의 상태는 useReducer 하나다. idle 에서 start 로 running 이 되고(에러도 함께 비운다), yield 는 status 를 두고 value 만 바꾸며, generator 가 끝나면 done, 본문 어디서든 throw 하면 catch 에서 error 로 errored 다. cancel 은 abort 하고 idle 로 되돌린다 — 안 하면 running 에 멈춘다. unmount 되면 cleanup 이 abort 하고, 기다리던 await wait 가 reject 돼 throw 가 나지만 aborted 라 에러로 치지 않는다. 같은 훅을 쓰는 쪽이 재진입 정책을 고른다: LoadingButton 은 running 동안 disabled 로 다시 못 누르게 하고 JSX 를 yield 하면 그대로 라벨이 된다. 검색은 run(q) 마다 직전 실행을 abort 하고 다시 시작해, a 다음 ab 를 치면 a 의 remote 결과가 끼어들지 않는다.

-- isLoading 없이 onClick 에서 yield 만 한다 — 시간이 코드의 한 방향(↓)으로만 흐를 때
--   멀티 단계 loading · progressive search · optimistic mutation(optimistic | reconciled | rolledBack)
data Status  = Idle | Running | Errored | Done
data Event a = Start | Yield a | Finish | Throw Error | Cancel

step :: State a -> Event a -> State a
step s Start     = s { status = Running, error = Nothing }   -- 상태와 에러 초기화가 한 번에 — 따로 set 하다 어긋날 일이 없다
step s (Yield v) = s { value = v }                           -- status 는 두고 값만
step s Finish    = s { status = Done }
step s (Throw e) = s { status = Errored, error = Just e }
step s Cancel    = s { status = Idle }                       -- 없으면 Running 에 멈춘다

-- 핸들러는 값의 흐름(async generator), 훅은 그걸 접는다
state = foldl step initial (run fn args)

run :: (Signal -> args -> Stream a) -> args -> [Event a]
run fn args = Start : map Yield (untilAborted (fn signal args)) ++ end
  where end | aborted   = []          -- abort 로 생긴 throw 는 에러가 아니다
            | otherwise = [Finish]    -- 본문 어디서 throw 하든 Throw e
-- run 은 직전 실행을 abort 하고 다시 시작한다 · unmount 도 abort

-- 재진입 정책은 쓰는 쪽이 고른다
--   버튼: Running 동안 disabled, yield 한 JSX 가 곧 라벨
--   검색: run 마다 재시작 — tier 경계(await wait)가 곧 취소 지점이라 debounce 가 필요 없다
searchTiers q = do wait 100; yield [q ++ ":local"]
                   wait 300; yield [q ++ ":local", q ++ ":remote"]

-- 확인: a 를 치고 150ms 에 ab
shown == [["a:local"], ["ab:local"], ["ab:local", "ab:remote"]]   -- a:remote 는 끼어들지 않는다
#540