Skip to content
237 linesCodeBlameRaw
1/**
2 * Settings → Notifications: what you hear when chat moves and Do not
3 * disturb (identity keeps the sounds, notify your presence), what pops up
4 * and is pushed (notify), what you are also emailed for, how you watch
5 * repositories you create, and the repositories you watch other than the
6 * default way. The events service keeps those three (`inbox_settings`,
7 * `inbox_watched`); the notifications themselves are at /notifications.
8 */
9import { Eye, EyeOff } from "lucide-react";
10import { Form, Link, data, useNavigation } from "react-router";
11
12import type { DigestCadence, WatchLevel } from "@g1t/contracts";
13
14import type { Route } from "./+types/notifications";
15import { ErrorText, SubmitButton } from "../../components/ui";
16import { Card } from "../../components/ui/card";
17import { CheckboxOption } from "../../components/ui/checkbox";
18import { SwitchCard } from "../../components/ui/switch";
19import { RadioGroup, RadioOption } from "../../components/ui/radio-group";
20import { EMAIL_REASONS, SECURITY_DIGEST_CHOICES, WATCH_CHOICES, WATCH_EVENT_LABEL, emailReasonsFromForm, securityDigestFromForm } from "../../lib/inbox";
21import { page } from "../../lib/meta";
22import { identity, inbox } from "../../lib/services.server";
23import { assertSameOrigin, requireUser } from "../../lib/session.server";
24// Live notifications: pop-ups and browser notifications (services/notify).
25import { LiveNotificationSettings } from "../../components/notifications/settings";
26// Sounds, Do not disturb and desktop notifications (identity, notify).
27import { SoundSettingsSection } from "../../components/notifications/sounds";
28
29export function meta(args: Route.MetaArgs) {
30 return page(args, { title: "Notifications · Settings · g1t" });
31}
32
33export async function loader({ request, context }: Route.LoaderArgs) {
34 const user = requireUser(context, request);
35 const [settings, watched, sounds] = await Promise.all([
36 inbox.settings(user.username).catch(() => null),
37 inbox.watched(user.username).catch(() => null),
38 identity.soundSettings(user).catch(() => null),
39 ]);
40 return { settings, watched, sounds, workspaces: user.workspaces ?? [] };
41}
42
43export async function action({ request, context }: Route.ActionArgs) {
44 assertSameOrigin(request);
45 const user = requireUser(context, request);
46 const form = await request.formData();
47 const intent = String(form.get("intent") ?? "");
48 // One shape for every answer: what was said, beside the form that asked.
49 const answer = (saved: string | null, error: string | null = null) => ({ intent, saved, error });
50 try {
51 switch (intent) {
52 case "email":
53 await inbox.updateSettings(user.username, { email: emailReasonsFromForm(form) });
54 return answer("Saved. You'll be emailed for what is checked.");
55 case "security": {
56 const cadence: DigestCadence | null = securityDigestFromForm(form);
57 if (!cadence) return data(answer(null, "Choose when the rest of the security alerts reach you."), { status: 400 });
58 await inbox.updateSettings(user.username, { securityAlerts: form.get("security_alerts") === "on", securityDigest: cadence });
59 return answer("Saved. Critical and high alerts on repositories you look after still reach you at once.");
60 }
61 case "default_watch": {
62 const level = String(form.get("default_watch") ?? "");
63 if (level !== "participating" && level !== "all") return data(answer(null, "Choose one."), { status: 400 });
64 await inbox.updateSettings(user.username, { defaultWatch: level });
65 return answer("Saved. It applies to repositories you create from now on.");
66 }
67 case "unwatch": {
68 const repoId = String(form.get("repo_id") ?? "");
69 if (!repoId) return data(answer(null, "Nothing to do."), { status: 400 });
70 await inbox.watch(user.username, repoId, String(form.get("repo") ?? ""), null);
71 return answer(null);
72 }
73 default:
74 return data(answer(null, "Nothing to do."), { status: 400 });
75 }
76 } catch {
77 return data(answer(null, "That did not save. Try again in a moment."), { status: 503 });
78 }
79}
80
81const LEVEL_LABEL: Record<WatchLevel, string> = Object.fromEntries(WATCH_CHOICES.map((choice) => [choice.level, choice.label])) as Record<
82 WatchLevel,
83 string
84>;
85
86export default function NotificationSettings({ loaderData, actionData }: Route.ComponentProps) {
87 const { settings, watched, sounds, workspaces } = loaderData;
88 const navigation = useNavigation();
89 const said = (intent: string) => (actionData?.intent === intent && navigation.state === "idle" ? actionData : null);
90 if (!settings) {
91 return <p className="rounded-lg border border-line px-4 py-6 text-sm text-muted">Your notification settings could not be loaded. Try again in a moment.</p>;
92 }
93 return (
94 <div className="space-y-10">
95 <SoundSettingsSection initial={sounds} />
96 <LiveNotificationSettings workspaces={workspaces} />
97 <section aria-labelledby="email-heading">
98 <h2 id="email-heading" className="text-sm font-semibold">
99 Email
100 </h2>
101 <p className="mt-1 text-sm text-muted">
102 Besides your <Link to="/notifications" className="text-fg underline underline-offset-4">notifications</Link>, email me at my primary address when:
103 </p>
104 <Form method="post" className="mt-4 space-y-3">
105 <input type="hidden" name="intent" value="email" />
106 {EMAIL_REASONS.map((entry) => (
107 <CheckboxOption
108 key={entry.reason}
109 name="email"
110 value={entry.reason}
111 defaultChecked={settings.email.includes(entry.reason)}
112 label={entry.label}
113 description={entry.detail}
114 />
115 ))}
116 <div className="flex items-center gap-3 pt-2">
117 <SubmitButton variant="outline" match={{ intent: "email" }} pending="Saving…">
118 Save email settings
119 </SubmitButton>
120 {said("email")?.saved && <p className="text-xs text-success">{said("email")?.saved}</p>}
121 </div>
122 <ErrorText>{said("email")?.error}</ErrorText>
123 </Form>
124 <p className="mt-3 text-xs text-faint">Email goes only to a confirmed address, and only about repositories you can still read.</p>
125 </section>
126
127 <section aria-labelledby="security-heading">
128 <h2 id="security-heading" className="text-sm font-semibold">
129 Security
130 </h2>
131 <p className="mt-1 text-sm text-muted">
132 Each scan of a repository is one item, brought up to date by the next scan. Critical and high alerts, a push of yours that push protection refused
133 and a vulnerability report reach you at once; the rest, as you choose here. The workspaces you own, or manage security for, tell you of their
134 urgent alerts whatever you choose.
135 </p>
136 <Form method="post" className="mt-4 space-y-4">
137 <input type="hidden" name="intent" value="security" />
138 <SwitchCard name="security_alerts" title="Critical and high alerts at once" defaultChecked={settings.securityAlerts}>
139 On repositories you watch for security alerts. Off, you hear of them only in the repositories you own or manage security for.
140 </SwitchCard>
141 <div>
142 <p className="mb-2 text-sm font-medium">Medium and low alerts</p>
143 <RadioGroup name="security_digest" defaultValue={settings.securityDigest}>
144 {SECURITY_DIGEST_CHOICES.map((choice) => (
145 <RadioOption key={choice.cadence} value={choice.cadence} label={choice.label} description={choice.detail} />
146 ))}
147 </RadioGroup>
148 </div>
149 <div className="flex items-center gap-3">
150 <SubmitButton variant="outline" match={{ intent: "security" }} pending="Saving…">
151 Save security settings
152 </SubmitButton>
153 {said("security")?.saved && <p className="text-xs text-success">{said("security")?.saved}</p>}
154 </div>
155 <ErrorText>{said("security")?.error}</ErrorText>
156 </Form>
157 <p className="mt-3 text-xs text-faint">Email for security alerts follows the Email section above: on by default.</p>
158 </section>
159
160 <section aria-labelledby="watching-heading">
161 <h2 id="watching-heading" className="text-sm font-semibold">
162 Repositories you create
163 </h2>
164 <p className="mt-1 text-sm text-muted">How you watch a repository when you make it. Change any one from its Watch menu.</p>
165 <Form method="post" className="mt-4">
166 <input type="hidden" name="intent" value="default_watch" />
167 <RadioGroup name="default_watch" defaultValue={settings.defaultWatch === "participating" ? "participating" : "all"}>
168 {WATCH_CHOICES.filter((choice) => choice.level === "all" || choice.level === "participating").map((choice) => (
169 <RadioOption key={choice.level} value={choice.level} label={choice.label} description={choice.detail} />
170 ))}
171 </RadioGroup>
172 <div className="mt-4 flex items-center gap-3">
173 <SubmitButton variant="outline" match={{ intent: "default_watch" }} pending="Saving…">
174 Save
175 </SubmitButton>
176 {said("default_watch")?.saved && <p className="text-xs text-success">{said("default_watch")?.saved}</p>}
177 </div>
178 <ErrorText>{said("default_watch")?.error}</ErrorText>
179 </Form>
180 </section>
181
182 <section aria-labelledby="watched-heading">
183 <h2 id="watched-heading" className="text-sm font-semibold">
184 Repositories you watch
185 </h2>
186 <p className="mt-1 text-sm text-muted">Those you watch other than the default way, which is only what you take part in.</p>
187 {watched == null ? (
188 <p className="mt-4 text-sm text-muted">This list could not be loaded. Try again in a moment.</p>
189 ) : watched.length === 0 ? (
190 <Card asChild tone="plain" radius="lg" className="mt-4 border-dashed px-4 py-6 text-center text-sm text-muted">
191 <p>
192 You watch every repository the default way.
193 </p>
194 </Card>
195 ) : (
196 <ul className="mt-4 divide-y divide-line rounded-md border border-line">
197 {watched.map((watching) => (
198 <li key={watching.repoId} className="flex items-center gap-3 px-4 py-3">
199 {watching.level === "ignore" ? (
200 <EyeOff size={15} className="shrink-0 text-faint" aria-hidden="true" />
201 ) : (
202 <Eye size={15} className="shrink-0 text-faint" aria-hidden="true" />
203 )}
204 <div className="min-w-0 grow">
205 {watching.repo ? (
206 <Link to={`/${watching.repo}`} className="block truncate font-mono text-sm hover:underline">
207 {watching.repo}
208 </Link>
209 ) : (
210 <span className="block truncate font-mono text-sm text-muted">{watching.repoId}</span>
211 )}
212 <p className="truncate text-xs text-muted">
213 {LEVEL_LABEL[watching.level]}
214 {watching.level === "custom" && watching.events.length > 0 && `: ${watching.events.map((kind) => WATCH_EVENT_LABEL[kind]).join(", ")}`}
215 </p>
216 </div>
217 <Form method="post" className="shrink-0">
218 <input type="hidden" name="intent" value="unwatch" />
219 <input type="hidden" name="repo_id" value={watching.repoId} />
220 <input type="hidden" name="repo" value={watching.repo ?? ""} />
221 <SubmitButton
222 variant="outline"
223 match={{ intent: "unwatch", repo_id: watching.repoId }}
224 pending="…"
225 className="rounded-md border border-line px-2.5 py-1 text-xs text-muted transition-colors hover:border-line-strong hover:text-fg disabled:opacity-60"
226 >
227 {watching.level === "ignore" ? "Stop ignoring" : "Stop watching"}
228 </SubmitButton>
229 </Form>
230 </li>
231 ))}
232 </ul>
233 )}
234 </section>
235 </div>
236 );
237}