Skip to content
191 linesCodeBlameRaw
1/**
2 * Settings → Notifications: what you are also emailed for, how you watch
3 * repositories you create, and the repositories you watch other than the
4 * default way. The events service keeps all three (`inbox_settings`,
5 * `inbox_watched`); the notifications themselves are at /notifications.
6 */
7import { Eye, EyeOff } from "lucide-react";
8import { Form, Link, data, useNavigation } from "react-router";
9
10import type { WatchLevel } from "@g1t/contracts";
11
12import type { Route } from "./+types/notifications";
13import { ErrorText, SubmitButton } from "../../components/ui";
14import { Card } from "../../components/ui/card";
15import { CheckboxOption } from "../../components/ui/checkbox";
16import { RadioGroup, RadioOption } from "../../components/ui/radio-group";
17import { EMAIL_REASONS, WATCH_CHOICES, WATCH_EVENT_LABEL, emailReasonsFromForm } from "../../lib/inbox";
18import { page } from "../../lib/meta";
19import { inbox } from "../../lib/services.server";
20import { assertSameOrigin, requireUser } from "../../lib/session.server";
21// Live notifications: pop-ups, browser notifications, sound (services/notify).
22import { LiveNotificationSettings } from "../../components/notifications/settings";
23
24export function meta(args: Route.MetaArgs) {
25 return page(args, { title: "Notifications · Settings · g1t" });
26}
27
28export async function loader({ request, context }: Route.LoaderArgs) {
29 const user = requireUser(context, request);
30 const [settings, watched] = await Promise.all([
31 inbox.settings(user.username).catch(() => null),
32 inbox.watched(user.username).catch(() => null),
33 ]);
34 return { settings, watched, workspaces: user.workspaces ?? [] };
35}
36
37export async function action({ request, context }: Route.ActionArgs) {
38 assertSameOrigin(request);
39 const user = requireUser(context, request);
40 const form = await request.formData();
41 const intent = String(form.get("intent") ?? "");
42 // One shape for every answer: what was said, beside the form that asked.
43 const answer = (saved: string | null, error: string | null = null) => ({ intent, saved, error });
44 try {
45 switch (intent) {
46 case "email":
47 await inbox.updateSettings(user.username, { email: emailReasonsFromForm(form) });
48 return answer("Saved. You'll be emailed for what is checked.");
49 case "default_watch": {
50 const level = String(form.get("default_watch") ?? "");
51 if (level !== "participating" && level !== "all") return data(answer(null, "Choose one."), { status: 400 });
52 await inbox.updateSettings(user.username, { defaultWatch: level });
53 return answer("Saved. It applies to repositories you create from now on.");
54 }
55 case "unwatch": {
56 const repoId = String(form.get("repo_id") ?? "");
57 if (!repoId) return data(answer(null, "Nothing to do."), { status: 400 });
58 await inbox.watch(user.username, repoId, String(form.get("repo") ?? ""), null);
59 return answer(null);
60 }
61 default:
62 return data(answer(null, "Nothing to do."), { status: 400 });
63 }
64 } catch {
65 return data(answer(null, "That did not save. Try again in a moment."), { status: 503 });
66 }
67}
68
69const LEVEL_LABEL: Record<WatchLevel, string> = Object.fromEntries(WATCH_CHOICES.map((choice) => [choice.level, choice.label])) as Record<
70 WatchLevel,
71 string
72>;
73
74export default function NotificationSettings({ loaderData, actionData }: Route.ComponentProps) {
75 const { settings, watched, workspaces } = loaderData;
76 const navigation = useNavigation();
77 const said = (intent: string) => (actionData?.intent === intent && navigation.state === "idle" ? actionData : null);
78 if (!settings) {
79 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>;
80 }
81 return (
82 <div className="space-y-10">
83 <LiveNotificationSettings workspaces={workspaces} />
84 <section aria-labelledby="email-heading">
85 <h2 id="email-heading" className="text-sm font-semibold">
86 Email
87 </h2>
88 <p className="mt-1 text-sm text-muted">
89 Besides your <Link to="/notifications" className="text-fg underline underline-offset-4">notifications</Link>, email me at my primary address when:
90 </p>
91 <Form method="post" className="mt-4 space-y-3">
92 <input type="hidden" name="intent" value="email" />
93 {EMAIL_REASONS.map((entry) => (
94 <CheckboxOption
95 key={entry.reason}
96 name="email"
97 value={entry.reason}
98 defaultChecked={settings.email.includes(entry.reason)}
99 label={entry.label}
100 description={entry.detail}
101 />
102 ))}
103 <div className="flex items-center gap-3 pt-2">
104 <SubmitButton variant="outline" match={{ intent: "email" }} pending="Saving…">
105 Save email settings
106 </SubmitButton>
107 {said("email")?.saved && <p className="text-xs text-success">{said("email")?.saved}</p>}
108 </div>
109 <ErrorText>{said("email")?.error}</ErrorText>
110 </Form>
111 <p className="mt-3 text-xs text-faint">Email goes only to a confirmed address, and only about repositories you can still read.</p>
112 </section>
113
114 <section aria-labelledby="watching-heading">
115 <h2 id="watching-heading" className="text-sm font-semibold">
116 Repositories you create
117 </h2>
118 <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>
119 <Form method="post" className="mt-4">
120 <input type="hidden" name="intent" value="default_watch" />
121 <RadioGroup name="default_watch" defaultValue={settings.defaultWatch === "participating" ? "participating" : "all"}>
122 {WATCH_CHOICES.filter((choice) => choice.level === "all" || choice.level === "participating").map((choice) => (
123 <RadioOption key={choice.level} value={choice.level} label={choice.label} description={choice.detail} />
124 ))}
125 </RadioGroup>
126 <div className="mt-4 flex items-center gap-3">
127 <SubmitButton variant="outline" match={{ intent: "default_watch" }} pending="Saving…">
128 Save
129 </SubmitButton>
130 {said("default_watch")?.saved && <p className="text-xs text-success">{said("default_watch")?.saved}</p>}
131 </div>
132 <ErrorText>{said("default_watch")?.error}</ErrorText>
133 </Form>
134 </section>
135
136 <section aria-labelledby="watched-heading">
137 <h2 id="watched-heading" className="text-sm font-semibold">
138 Repositories you watch
139 </h2>
140 <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>
141 {watched == null ? (
142 <p className="mt-4 text-sm text-muted">This list could not be loaded. Try again in a moment.</p>
143 ) : watched.length === 0 ? (
144 <Card asChild tone="plain" radius="lg" className="mt-4 border-dashed px-4 py-6 text-center text-sm text-muted">
145 <p>
146 You watch every repository the default way.
147 </p>
148 </Card>
149 ) : (
150 <ul className="mt-4 divide-y divide-line rounded-md border border-line">
151 {watched.map((watching) => (
152 <li key={watching.repoId} className="flex items-center gap-3 px-4 py-3">
153 {watching.level === "ignore" ? (
154 <EyeOff size={15} className="shrink-0 text-faint" aria-hidden="true" />
155 ) : (
156 <Eye size={15} className="shrink-0 text-faint" aria-hidden="true" />
157 )}
158 <div className="min-w-0 grow">
159 {watching.repo ? (
160 <Link to={`/${watching.repo}`} className="block truncate font-mono text-sm hover:underline">
161 {watching.repo}
162 </Link>
163 ) : (
164 <span className="block truncate font-mono text-sm text-muted">{watching.repoId}</span>
165 )}
166 <p className="truncate text-xs text-muted">
167 {LEVEL_LABEL[watching.level]}
168 {watching.level === "custom" && watching.events.length > 0 && `: ${watching.events.map((kind) => WATCH_EVENT_LABEL[kind]).join(", ")}`}
169 </p>
170 </div>
171 <Form method="post" className="shrink-0">
172 <input type="hidden" name="intent" value="unwatch" />
173 <input type="hidden" name="repo_id" value={watching.repoId} />
174 <input type="hidden" name="repo" value={watching.repo ?? ""} />
175 <SubmitButton
176 variant="outline"
177 match={{ intent: "unwatch", repo_id: watching.repoId }}
178 pending="…"
179 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"
180 >
181 {watching.level === "ignore" ? "Stop ignoring" : "Stop watching"}
182 </SubmitButton>
183 </Form>
184 </li>
185 ))}
186 </ul>
187 )}
188 </section>
189 </div>
190 );
191}