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

showThreadUndoNotice.ts

150 lines5.1 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 { shortcutLabelForCommand } from "../keybindings";
10import { announce, cancelAnnouncement } from "../lib/announce";
11import { appAtomRegistry } from "../rpc/atomRegistry";
12import { primaryServerKeybindingsAtom } from "../state/server";
13import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
14​
15type UndoOptions = {
16 action: "Settled" | "Snoozed" | "Unpinned" | "Archived" | "Discarded";
17 undo: () => Promise<AtomCommandResult<unknown, unknown>>;
18 failureTitle: string;
19 claim: ReturnType<typeof ThreadUndo.begin>;
20 commit?: () => void;
21};
22​
23type UndoNotice = {
24 action: UndoOptions["action"];
25 count: number;
26 undo: () => Promise<void>;
27};
28​
29export const useThreadUndoNotice = create<{ notice: UndoNotice | null }>(() => ({ notice: null }));
30​
31export function threadUndoNoticeSummary(notice: Pick<UndoNotice, "action" | "count">): string {
32 const noun = notice.action === "Discarded" ? "draft" : "thread";
33 return `${notice.action} ${notice.count} ${noun}${notice.count === 1 ? "" : "s"}`;
35​
36export function threadUndoLabel(keybindings: Parameters<typeof shortcutLabelForCommand>[0]) {
37 const shortcut = shortcutLabelForCommand(keybindings, "thread.undo");
38 return shortcut ? `${shortcut} to undo` : "Undo";
40​
41let announcedSummary: string | null = null;
42​
43// A live region that mounts already filled is skipped by screen readers, and settling
44// usually moves focus to the next thread at the same moment, so the notice is announced
45// separately from the alert that shows it.
46function setNotice(notice: UndoNotice | null) {
47 useThreadUndoNotice.setState({ notice });
48 const summary = notice ? threadUndoNoticeSummary(notice) : null;
49 if (summary === announcedSummary) return;
50 announcedSummary = summary;
51 if (summary) {
52 const label = threadUndoLabel(appAtomRegistry.get(primaryServerKeybindingsAtom));
53 announce(`${summary}, ${label}`, "thread-undo-notice");
54 } else {
55 cancelAnnouncement("thread-undo-notice");
56 }
58​
59let liveUndos: UndoOptions[] = [];
60let expiry: ReturnType<typeof setTimeout> | undefined;
61// A new notice owns mod+z even inside a text field, until the user presses
62// another key or edits text. After that, mod+z is the field's own undo again.
63let shortcutClaimed = false;
64​
65function refreshNotice() {
66 const stale = liveUndos.filter(({ claim }) => !claim.isCurrent());
67 liveUndos = liveUndos.filter((entry) => !stale.includes(entry));
68 for (const entry of stale) entry.commit?.();
69 const latest = liveUndos.at(-1);
70 if (!latest) {
71 clearTimeout(expiry);
72 setNotice(null);
73 return;
74 }
75 const group: UndoOptions[] = [];
76 for (let index = liveUndos.length - 1; index >= 0; index--) {
77 const entry = liveUndos[index]!;
78 if (entry.action !== latest.action) break;
79 group.push(entry);
80 }
81 setNotice({
82 action: latest.action,
83 count: group.length,
84 undo: async () => {
85 const current = group.filter((entry) => liveUndos.includes(entry) && entry.claim.isCurrent());
86 liveUndos = liveUndos.filter((entry) => !group.includes(entry));
87 // Claim before awaiting to prevent repeated actions restoring a group twice.
88 for (const entry of current) entry.claim.finish();
89 refreshNotice();
90 await Promise.all(
91 current.map(async ({ undo, failureTitle }) => {
92 const reportFailure = (error: unknown) => {
93 toastManager.add(
94 stackedThreadToast({
95 type: "error",
96 title: failureTitle,
97 description: error instanceof Error ? error.message : "An error occurred.",
98 }),
99 );
100 };
101 try {
102 const result = await undo();
103 if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
104 reportFailure(squashAtomCommandFailure(result));
105 }
106 } catch (error) {
107 reportFailure(error);
108 }
109 }),
110 );
111 },
112 });
114​
115ThreadUndo.subscribe(refreshNotice);
116​
117export function undoLatestThreadAction(): boolean {
118 const notice = useThreadUndoNotice.getState().notice;
119 if (!notice) return false;
120 void notice.undo();
121 return true;
123​
124/** Whether mod+z should undo the notice's actions even while a text field is focused. */
125export function threadUndoClaimsShortcut(): boolean {
126 return shortcutClaimed && useThreadUndoNotice.getState().notice !== null;
128​
129/** Called on any other keypress or text edit; hands mod+z back to text fields. */
130export function releaseThreadUndoShortcut() {
131 shortcutClaimed = false;
133​
134/** Shows one compact confirmation for the currently undoable thread actions. */
135export function showThreadUndoNotice(options: UndoOptions) {
136 if (!options.claim.isCurrent()) return;
137 liveUndos.push(options);
138 shortcutClaimed = true;
139 refreshNotice();
140 clearTimeout(expiry);
141 expiry = setTimeout(() => {
142 const expired = liveUndos;
143 liveUndos = [];
144 for (const { claim, commit } of expired) {
145 claim.finish();
146 commit?.();
147 }
148 refreshNotice();
149 }, 5_000);