The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo"; |
| 2 | import { useSyncExternalStore } from "react"; |
| 3 | |
| 4 | type UndoNotice = { |
| 5 | readonly action: "Settled" | "Snoozed" | "Unpinned"; |
| 6 | readonly claim: ReturnType<typeof ThreadUndo.begin>; |
| 7 | readonly undo: () => Promise<void>; |
| 8 | }; |
| 9 | |
| 10 | let notice: UndoNotice | null = null; |
| 11 | let expiry: ReturnType<typeof setTimeout> | undefined; |
| 12 | const listeners = new Set<() => void>(); |
| 13 | |
| 14 | function notify() { |
| 15 | for (const listener of listeners) listener(); |
| 16 | } |
| 17 | |
| 18 | export function readThreadUndoNotice() { |
| 19 | return notice; |
| 20 | } |
| 21 | |
| 22 | export function dismissThreadUndoNotice() { |
| 23 | const previous = notice; |
| 24 | notice = null; |
| 25 | clearTimeout(expiry); |
| 26 | previous?.claim.finish(); |
| 27 | notify(); |
| 28 | } |
| 29 | |
| 30 | ThreadUndo.subscribe(() => { |
| 31 | if (notice !== null && !notice.claim.isCurrent()) dismissThreadUndoNotice(); |
| 32 | }); |
| 33 | |
| 34 | export function showThreadUndoNotice(options: UndoNotice) { |
| 35 | if (!options.claim.isCurrent()) return; |
| 36 | dismissThreadUndoNotice(); |
| 37 | notice = { |
| 38 | ...options, |
| 39 | undo: async () => { |
| 40 | if (notice?.claim !== options.claim || !options.claim.isCurrent()) return; |
| 41 | dismissThreadUndoNotice(); |
| 42 | await options.undo(); |
| 43 | }, |
| 44 | }; |
| 45 | notify(); |
| 46 | expiry = setTimeout(dismissThreadUndoNotice, 5_000); |
| 47 | } |
| 48 | |
| 49 | export function useThreadUndoNotice() { |
| 50 | return useSyncExternalStore((listener) => { |
| 51 | listeners.add(listener); |
| 52 | return () => { |
| 53 | listeners.delete(listener); |
| 54 | }; |
| 55 | }, readThreadUndoNotice); |
| 56 | } |