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

showThreadUndoNotice.ts

122 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 // Claim before awaiting to prevent repeated actions restoring a group twice.
59 for (const entry of current) entry.claim.finish();
60 refreshNotice();
61 await Promise.all(
62 current.map(async ({ undo, failureTitle }) => {
63 const reportFailure = (error: unknown) => {
64 toastManager.add(
65 stackedThreadToast({
66 type: "error",
67 title: failureTitle,
68 description: error instanceof Error ? error.message : "An error occurred.",
69 }),
70 );
71 };
72 try {
73 const result = await undo();
74 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
75 reportFailure(squashAtomCommandFailure(result));
76 }
77 } catch (error) {
78 reportFailure(error);
79 }
80 }),
81 );
82 },
83 },
84 });
86​
87ThreadUndo.subscribe(refreshNotice);
88​
89export function undoLatestThreadAction(): boolean {
90 const notice = useThreadUndoNotice.getState().notice;
91 if (!notice) return false;
92 void notice.undo();
93 return true;
95​
96/** Whether mod+z should undo the notice's actions even while a text field is focused. */
97export function threadUndoClaimsShortcut(): boolean {
98 return shortcutClaimed && useThreadUndoNotice.getState().notice !== null;
100​
101/** Called on any other keypress or text edit; hands mod+z back to text fields. */
102export function releaseThreadUndoShortcut() {
103 shortcutClaimed = false;
105​
106/** Shows one compact confirmation for the currently undoable thread actions. */
107export function showThreadUndoNotice(options: UndoOptions) {
108 if (!options.claim.isCurrent()) return;
109 liveUndos.push(options);
110 shortcutClaimed = true;
111 refreshNotice();
112 clearTimeout(expiry);
113 expiry = setTimeout(() => {
114 const expired = liveUndos;
115 liveUndos = [];
116 for (const { claim, commit } of expired) {
117 claim.finish();
118 commit?.();
119 }
120 refreshNotice();
121 }, 5_000);