Open History to see the last commit
1import { type EnvironmentId, SourceControlProviderKind } from "@t3tools/contracts";
2import { runAtomCommand } from "@t3tools/client-runtime/state/runtime";
3import * as Schema from "effect/Schema";
4import { msg } from "gt-react";
5import { StarIcon } from "lucide-react";
6
7import { m } from "../i18n/messages";
8import { getLocalStorageItem, setLocalStorageItem } from "../hooks/useLocalStorage";
9import { readLocalApi } from "../localApi";
10import { appAtomRegistry } from "../rpc/atomRegistry";
11import { sourceControlEnvironment } from "../state/sourceControl";
12import { toastManager } from "./ui/toast";
13
14// Separate keys so a count written by another tab can never undo a dismissal.
15const SENT_KEY = "t3code:github-star-prompt:sent";
16const DISMISSED_KEY = "t3code:github-star-prompt:dismissed";
17const REPOSITORY = "pingdotgg/t3code";
18const PROMPTS_BEFORE_ASKING = 5;
19const IDLE_MS = 30_000;
20// User-driven actions (send, navigate, type, scroll) start with one of these; touch fires pointerdown.
21const ACTIVITY_EVENTS = ["pointerdown", "keydown", "wheel", "focus"] as const;
22
23let shownThisSession = false;
24
25function dismiss() {
26 try {
27 setLocalStorageItem(DISMISSED_KEY, true, Schema.Boolean);
28 } catch {}
29}
30
31// Every close path, including both buttons, runs `onClose`, which saves the dismissal.
32function showStarPrompt(environmentId: EnvironmentId) {
33 const close = () => toastManager.close(id);
34 const openInBrowser = () => {
35 close();
36 void readLocalApi()
37 ?.shell.openExternal(`https://github.com/${REPOSITORY}`)
38 .catch(() => undefined);
39 };
40 const starInPlace = async () => {
41 toastManager.update(id, { actionProps: { children: m(msg("Starring…")), disabled: true } });
42 if (await starRepository(environmentId)) {
43 // Thank them in place: a closing and opening toast would slide under the confetti.
44 dismiss();
45 toastManager.update(id, {
46 type: "success",
47 title: m(msg("Thanks for the star!")),
48 description: m(msg("It really helps T3 Code grow.")),
49 timeout: 5_000,
50 actionProps: undefined,
51 data: {},
52 });
53 celebrate();
54 return;
55 }
56 // Browsers block new tabs once the click's activation expires; desktop opens through its bridge.
57 if (window.desktopBridge || navigator.userActivation?.isActive !== false)
58 return openInBrowser();
59 toastManager.update(id, {
60 actionProps: { children: m(msg("Open GitHub")), onClick: openInBrowser },
61 });
62 };
63 const id = toastManager.add({
64 title: m(msg("Enjoying T3 Code?")),
65 description: m(msg("Give us a star on GitHub to let us know!")),
66 timeout: 0,
67 onClose: dismiss,
68 actionProps: { children: m(msg("Star on GitHub")), onClick: () => void starInPlace() },
69 data: {
70 actionLayout: "stacked-end",
71 leadingIcon: <StarIcon aria-hidden className="size-4 text-warning-foreground" />,
72 secondaryActionProps: { children: m(msg("Dismiss")), onClick: close },
73 secondaryActionVariant: "ghost",
74 },
75 });
76}
77
78// One burst out of the toast. The library loads only here, and its canvas stops when done.
79function celebrate() {
80 void import("canvas-confetti")
81 .then(({ default: confetti }) =>
82 confetti({
83 particleCount: 160,
84 spread: 360,
85 startVelocity: 38,
86 gravity: 1.6,
87 ticks: 140,
88 origin: { x: 0.83, y: 0.15 },
89 disableForReducedMotion: true,
90 }),
91 )
92 .catch(() => undefined);
93}
94
95// Resolves after IDLE_MS without input while this window has focus.
96function waitForIdle() {
97 return new Promise<void>((resolve) => {
98 let timer: ReturnType<typeof setTimeout> | undefined;
99 const restart = () => {
100 clearTimeout(timer);
101 timer = setTimeout(() => {
102 // Input inside another app or an embedded frame never reaches us; the next focus restarts.
103 if (!document.hasFocus() || document.activeElement?.matches("iframe, webview")) return;
104 for (const type of ACTIVITY_EVENTS) window.removeEventListener(type, restart, true);
105 resolve();
106 }, IDLE_MS);
107 };
108 for (const type of ACTIVITY_EVENTS) {
109 window.addEventListener(type, restart, { capture: true, passive: true });
110 }
111 restart();
112 });
113}
114
115// The server's GitHub account stands in for the user's; it may not be theirs on a shared server.
116const starInput = (environmentId: EnvironmentId) => ({
117 environmentId,
118 input: {
119 provider: SourceControlProviderKind.make("github"),
120 host: "github.com",
121 repository: REPOSITORY,
122 },
123});
124
125async function alreadyStarred(environmentId: EnvironmentId) {
126 const result = await runAtomCommand(
127 appAtomRegistry,
128 sourceControlEnvironment.checkStarred,
129 starInput(environmentId),
130 { label: "check GitHub star", reportFailure: false, reportDefect: false },
131 );
132 return result._tag === "Success" ? result.value : undefined;
133}
134
135async function starRepository(environmentId: EnvironmentId) {
136 const result = await runAtomCommand(
137 appAtomRegistry,
138 sourceControlEnvironment.star,
139 starInput(environmentId),
140 { label: "star on GitHub", reportFailure: false, reportDefect: false },
141 );
142 return result._tag === "Success" && result.value;
143}
144
145/**
146 * Counts a sent prompt. After more than five, asks once per session for a star until dismissed,
147 * unless the environment's GitHub account already starred the repo. Waits until the user is idle.
148 */
149export async function recordPromptSent(environmentId: EnvironmentId): Promise<void> {
150 if (shownThisSession) return;
151 try {
152 if (getLocalStorageItem(DISMISSED_KEY, Schema.Boolean)) return;
153 const sent = (getLocalStorageItem(SENT_KEY, Schema.Number) ?? 0) + 1;
154 setLocalStorageItem(SENT_KEY, sent, Schema.Number);
155 if (sent <= PROMPTS_BEFORE_ASKING) return;
156 } catch {
157 // Storage that cannot be read or written could not keep a dismissal, so never ask.
158 return;
159 }
160 shownThisSession = true;
161 const starred = await alreadyStarred(environmentId);
162 if (starred === undefined) return;
163 if (starred) return dismiss();
164 await waitForIdle();
165 try {
166 // Another tab can dismiss while the check or the idle wait runs.
167 if (getLocalStorageItem(DISMISSED_KEY, Schema.Boolean)) return;
168 } catch {
169 return;
170 }
171 showStarPrompt(environmentId);
172}