Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

showThreadUndoNotice.ts

123 lines3.9 KB

1import {
2 type AtomCommandResult,
3 isAtomCommandInterrupted,
4 squashAtomCommandFailure,
5} from "@t3tools/client-runtime/state/runtime";
6import { create } from "zustand";
7​
8import { stackedThreadToast, toastManager } from "../components/ui/toast";
9import * as ThreadUndo from "./threadUndo";
10​
11type UndoOptions = {
12 action: "Settled" | "Snoozed" | "Unpinned" | "Archived" | "Discarded";
13 undo: () => Promise<AtomCommandResult<unknown, unknown>>;
14 failureTitle: string;
15 claim: ReturnType<typeof ThreadUndo.begin>;
16 commit?: () => void;
17};
18​
19type UndoNotice = {
20 action: UndoOptions["action"];
21 count: number;
22 undo: () => Promise<void>;
23};
24​
25export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null }));
26​
27let liveUndos: UndoOptions[] = [];
28let expiry: ReturnType<typeof setTimeout> | undefined;
29// A new notice owns mod+z even inside a text field, until the user presses
30// another key or edits text. After that, mod+z is the field's own undo again.
31let shortcutClaimed = false;
32​
33function refreshNotice() {
34 const stale = liveUndos.filter(({ claim }) => !claim.isCurrent());
35 liveUndos = liveUndos.filter((entry) => !stale.includes(entry));
36 for (const entry of stale) entry.commit?.();
37 const latest = liveUndos.at(-1);
38 if (!latest) {
39 clearTimeout(expiry);
40 useThreadUndoNotice.setState({ notice: null });
41 return;
42 }
43 const group: UndoOptions[] = [];
44 for (let index = liveUndos.length - 1; index >= 0; index--) {
45 const entry = liveUndos[index]!;
46 if (entry.action !== latest.action) break;
47 group.push(entry);
48 }
49 useThreadUndoNotice.setState({
50 notice: {
51 action: latest.action,
52 count: group.length,
53 undo: async () => {
54 const current = group.filter(
55 (entry) => liveUndos.includes(entry) && entry.claim.isCurrent(),
56 );
57 liveUndos = liveUndos.filter((entry) => !group.includes(entry));
58 // Consume every claim before awaiting, so repeated clicks or shortcuts
59 // cannot restore the same group twice.
60 for (const entry of current) entry.claim.finish();
61 refreshNotice();
62 await Promise.all(
63 current.map(async ({ undo, failureTitle }) => {
64 const reportFailure = (error: unknown) => {
65 toastManager.add(
66 stackedThreadToast({
67 type: "error",
68 title: failureTitle,
69 description: error instanceof Error ? error.message : "An error occurred.",
70 }),
71 );
72 };
73 try {
74 const result = await undo();
75 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
76 reportFailure(squashAtomCommandFailure(result));
77 }
78 } catch (error) {
79 reportFailure(error);
80 }
81 }),
82 );
83 },
84 },
85 });
87​
88ThreadUndo.subscribe(refreshNotice);
89​
90export function undoLatestThreadAction(): boolean {
91 const notice = useThreadUndoNotice.getState().notice;
92 if (!notice) return false;
93 void notice.undo();
94 return true;
96​
97/** Whether mod+z should undo the notice's actions even while a text field is focused. */
98export function threadUndoClaimsShortcut(): boolean {
99 return shortcutClaimed && useThreadUndoNotice.getState().notice !== null;
101​
102/** Called on any other keypress or text edit; hands mod+z back to text fields. */
103export function releaseThreadUndoShortcut() {
104 shortcutClaimed = false;
106​
107/** Shows one compact confirmation for the currently undoable thread actions. */
108export function showThreadUndoNotice(options: UndoOptions) {
109 if (!options.claim.isCurrent()) return;
110 liveUndos.push(options);
111 shortcutClaimed = true;
112 refreshNotice();
113 clearTimeout(expiry);
114 expiry = setTimeout(() => {
115 const expired = liveUndos;
116 liveUndos = [];
117 for (const { claim, commit } of expired) {
118 claim.finish();
119 commit?.();
120 }
121 refreshNotice();
122 }, 5_000);