Open History to see the last commit
1import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
2import {
3 type AtomCommandResult,
4 isAtomCommandInterrupted,
5 squashAtomCommandFailure,
6} from "@t3tools/client-runtime/state/runtime";
7import { msg, plural, part, type Msg } from "gt-react";
8import { create } from "zustand";
9
10import { stackedThreadToast, toastManager } from "../components/ui/toast";
11import { m, type MessageResolver } from "../i18n/messages";
12import { shortcutLabelForCommand } from "../keybindings";
13import { announce, cancelAnnouncement } from "../lib/announce";
14import { appAtomRegistry } from "../rpc/atomRegistry";
15import { primaryServerKeybindingsAtom } from "../state/server";
16import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
17
18type UndoOptions = {
19 action: "Settled" | "Snoozed" | "Unpinned" | "Archived" | "Discarded";
20 undo: () => Promise<AtomCommandResult<unknown, unknown>>;
21 failureTitle: string;
22 claim: ReturnType<typeof ThreadUndo.begin>;
23 commit?: () => void;
24};
25
26type UndoNotice = {
27 action: UndoOptions["action"];
28 count: number;
29 undo: () => Promise<void>;
30};
31
32export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null }));
33
34const SUMMARY = {
35 Settled: ({ count }: { count: number }) =>
36 msg`Settled ${plural(
37 { count },
38 {
39 one: part`${{ count }} thread`,
40 other: part`${{ count }} threads`,
41 },
42 )}`,
43 Snoozed: ({ count }: { count: number }) =>
44 msg`Snoozed ${plural(
45 { count },
46 {
47 one: part`${{ count }} thread`,
48 other: part`${{ count }} threads`,
49 },
50 )}`,
51 Unpinned: ({ count }: { count: number }) =>
52 msg`Unpinned ${plural(
53 { count },
54 {
55 one: part`${{ count }} thread`,
56 other: part`${{ count }} threads`,
57 },
58 )}`,
59 Archived: ({ count }: { count: number }) =>
60 msg`Archived ${plural(
61 { count },
62 {
63 one: part`${{ count }} thread`,
64 other: part`${{ count }} threads`,
65 },
66 )}`,
67 Discarded: ({ count }: { count: number }) =>
68 msg`Discarded ${plural(
69 { count },
70 {
71 one: part`${{ count }} draft`,
72 other: part`${{ count }} drafts`,
73 },
74 )}`,
75} satisfies Record<UndoOptions["action"], (values: { count: number }) => string | Msg>;
76
77const UNDONE = {
78 Settled: ({ count }: { count: number }) =>
79 msg`Undid settle of ${plural(
80 { count },
81 {
82 one: part`${{ count }} thread`,
83 other: part`${{ count }} threads`,
84 },
85 )}`,
86 Snoozed: ({ count }: { count: number }) =>
87 msg`Undid snooze of ${plural(
88 { count },
89 {
90 one: part`${{ count }} thread`,
91 other: part`${{ count }} threads`,
92 },
93 )}`,
94 Unpinned: ({ count }: { count: number }) =>
95 msg`Undid unpin of ${plural(
96 { count },
97 {
98 one: part`${{ count }} thread`,
99 other: part`${{ count }} threads`,
100 },
101 )}`,
102 Archived: ({ count }: { count: number }) =>
103 msg`Undid archive of ${plural(
104 { count },
105 {
106 one: part`${{ count }} thread`,
107 other: part`${{ count }} threads`,
108 },
109 )}`,
110 Discarded: ({ count }: { count: number }) =>
111 msg`Undid discard of ${plural(
112 { count },
113 {
114 one: part`${{ count }} draft`,
115 other: part`${{ count }} drafts`,
116 },
117 )}`,
118} satisfies Record<UndoOptions["action"], (values: { count: number }) => string | Msg>;
119
120function threadUndoNoticeSummary(notice: Pick<UndoNotice, "action" | "count">): string {
121 return m(SUMMARY[notice.action]({ count: notice.count }));
122}
123
124/** Components pass `useMessages()` so the label follows a language switch. */
125export function threadUndoLabel(
126 keybindings: Parameters<typeof shortcutLabelForCommand>[0],
127 resolve: MessageResolver = m,
128) {
129 const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
130 return shortcut ? resolve(msg`${{ shortcut }} to undo`) : resolve(msg("Undo"));
131}
132
133let announcedSummary: string | null = null;
134
135// A live region that mounts already filled is skipped by screen readers, and settling
136// usually moves focus to the next thread at the same moment, so the notice is announced
137// separately from the alert that shows it.
138function setNotice(notice: UndoNotice | null) {
139 useThreadUndoNotice.setState({ notice });
140 const summary = notice ? threadUndoNoticeSummary(notice) : null;
141 if (summary === announcedSummary) return;
142 announcedSummary = summary;
143 if (summary) {
144 const label = threadUndoLabel(appAtomRegistry.get(primaryServerKeybindingsAtom));
145 announce(m(msg`${{ summary }}, ${{ label }}`), "thread-undo-notice");
146 } else {
147 cancelAnnouncement("thread-undo-notice");
148 }
149}
150
151let liveUndos: UndoOptions[] = [];
152let expiry: ReturnType<typeof setTimeout> | undefined;
153// A new notice owns mod+z even inside a text field, until the user presses
154// another key or edits text. After that, mod+z is the field's own undo again.
155let shortcutClaimed = false;
156
157function refreshNotice() {
158 const stale = liveUndos.filter(({ claim }) => !claim.isCurrent());
159 liveUndos = liveUndos.filter((entry) => !stale.includes(entry));
160 for (const entry of stale) entry.commit?.();
161 const latest = liveUndos.at(-1);
162 if (!latest) {
163 clearTimeout(expiry);
164 setNotice(null);
165 return;
166 }
167 const group: UndoOptions[] = [];
168 for (let index = liveUndos.length - 1; index >= 0; index--) {
169 const entry = liveUndos[index]!;
170 if (entry.action !== latest.action) break;
171 group.push(entry);
172 }
173 setNotice({
174 action: latest.action,
175 count: group.length,
176 undo: async () => {
177 const current = group.filter((entry) => liveUndos.includes(entry) && entry.claim.isCurrent());
178 liveUndos = liveUndos.filter((entry) => !group.includes(entry));
179 // Claim before awaiting to prevent repeated actions restoring a group twice.
180 for (const entry of current) entry.claim.finish();
181 refreshNotice();
182 let undone = 0;
183 await Promise.all(
184 current.map(async ({ undo, failureTitle }) => {
185 const reportFailure = (error: unknown) => {
186 toastManager.add(
187 stackedThreadToast({
188 type: "error",
189 title: failureTitle,
190 description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")),
191 }),
192 );
193 };
194 try {
195 const result = await undo();
196 if (result._tag === "Success") undone++;
197 else if (!isAtomCommandInterrupted(result)) {
198 reportFailure(squashAtomCommandFailure(result));
199 }
200 } catch (error) {
201 reportFailure(error);
202 }
203 }),
204 );
205 // Failures already raise a toast, so only what was actually restored is spoken.
206 if (undone > 0) {
207 announce(m(UNDONE[latest.action]({ count: undone })));
208 }
209 },
210 });
211}
212
213ThreadUndo.subscribe(refreshNotice);
214
215export function undoLatestThreadAction(): boolean {
216 const notice = useThreadUndoNotice.getState().notice;
217 if (!notice) return false;
218 void notice.undo();
219 return true;
220}
221
222/** Whether mod+z should undo the notice's actions even while a text field is focused. */
223export function threadUndoClaimsShortcut(): boolean {
224 return shortcutClaimed && useThreadUndoNotice.getState().notice !== null;
225}
226
227/** Called on any other keypress or text edit; hands mod+z back to text fields. */
228export function releaseThreadUndoShortcut() {
229 shortcutClaimed = false;
230}
231
232/** Shows one compact confirmation for the currently undoable thread actions. */
233export function showThreadUndoNotice(options: UndoOptions) {
234 if (!options.claim.isCurrent()) return;
235 liveUndos.push(options);
236 shortcutClaimed = true;
237 refreshNotice();
238 clearTimeout(expiry);
239 expiry = setTimeout(() => {
240 const expired = liveUndos;
241 liveUndos = [];
242 for (const { claim, commit } of expired) {
243 claim.finish();
244 commit?.();
245 }
246 refreshNotice();
247 }, 5_000);
248}