-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathadmin.notifications.tsx
More file actions
1459 lines (1351 loc) · 50.9 KB
/
Copy pathadmin.notifications.tsx
File metadata and controls
1459 lines (1351 loc) · 50.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { ChevronRightIcon, TrashIcon, XMarkIcon } from "@heroicons/react/20/solid";
import { useFetcher, useSearchParams } from "@remix-run/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/server-runtime";
import { redirect } from "@remix-run/server-runtime";
import { useEffect, useRef, useState, useLayoutEffect } from "react";
import ReactMarkdown from "react-markdown";
import { typedjson, useTypedLoaderData } from "remix-typedjson";
import { z } from "zod";
import {
Alert,
AlertCancel,
AlertContent,
AlertDescription,
AlertFooter,
AlertHeader,
AlertTitle,
AlertTrigger,
} from "~/components/primitives/Alert";
import { Button } from "~/components/primitives/Buttons";
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
} from "~/components/primitives/Dialog";
import { Header3 } from "~/components/primitives/Headers";
import { Input } from "~/components/primitives/Input";
import { PaginationControls } from "~/components/primitives/Pagination";
import { Paragraph } from "~/components/primitives/Paragraph";
import {
Table,
TableBlankRow,
TableBody,
TableCell,
TableHeader,
TableHeaderCell,
TableRow,
} from "~/components/primitives/Table";
import { prisma } from "~/db.server";
import { logger } from "~/services/logger.server";
import { requireUserId } from "~/services/session.server";
import {
archivePlatformNotification,
createPlatformNotification,
deletePlatformNotification,
getAdminNotificationsList,
publishNowPlatformNotification,
updatePlatformNotification,
} from "~/services/platformNotifications.server";
import { createSearchParams } from "~/utils/searchParams";
import { cn } from "~/utils/cn";
const PAGE_SIZE = 20;
const WEBAPP_TYPES = ["card", "changelog"] as const;
const CLI_TYPES = ["info", "warn", "error", "success"] as const;
const SearchParams = z.object({
page: z.coerce.number().optional(),
hideInactive: z.coerce.boolean().optional(),
});
export const loader = async ({ request }: LoaderFunctionArgs) => {
const userId = await requireUserId(request);
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user?.admin) throw redirect("/");
const searchParams = createSearchParams(request.url, SearchParams);
if (!searchParams.success) throw new Error(searchParams.error);
const { page: rawPage, hideInactive } = searchParams.params.getAll();
const page = rawPage ?? 1;
const data = await getAdminNotificationsList({ page, pageSize: PAGE_SIZE, hideInactive: hideInactive ?? false });
return typedjson({ ...data, userId });
};
export async function action({ request }: ActionFunctionArgs) {
const userId = await requireUserId(request);
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user?.admin) throw redirect("/");
const formData = await request.formData();
const _action = formData.get("_action");
if (_action === "create" || _action === "create-preview") {
return handleCreateAction(formData, userId, _action === "create-preview");
}
if (_action === "archive") {
return handleArchiveAction(formData);
}
if (_action === "delete") {
return handleDeleteAction(formData);
}
if (_action === "publish-now") {
return handlePublishNowAction(formData);
}
if (_action === "edit") {
return handleEditAction(formData);
}
return typedjson({ error: "Unknown action" }, { status: 400 });
}
function parseNotificationFormData(formData: FormData) {
const surface = formData.get("surface") as string;
const payloadType = formData.get("payloadType") as string;
const adminLabel = formData.get("adminLabel") as string;
const title = formData.get("title") as string;
const description = formData.get("description") as string;
const actionUrl = (formData.get("actionUrl") as string) || undefined;
const image = (formData.get("image") as string) || undefined;
const dismissOnAction = formData.get("dismissOnAction") === "true";
const startsAt = formData.get("startsAt") as string;
const endsAt = formData.get("endsAt") as string;
const priority = Number(formData.get("priority") || "0");
const scope = (formData.get("scope") as string) || "GLOBAL";
const scopeUserId = (formData.get("scopeUserId") as string) || undefined;
const scopeOrganizationId = (formData.get("scopeOrganizationId") as string) || undefined;
const scopeProjectId = (formData.get("scopeProjectId") as string) || undefined;
const cliMaxShowCount = formData.get("cliMaxShowCount")
? Number(formData.get("cliMaxShowCount"))
: undefined;
const cliMaxDaysAfterFirstSeen = formData.get("cliMaxDaysAfterFirstSeen")
? Number(formData.get("cliMaxDaysAfterFirstSeen"))
: undefined;
const cliShowEvery = formData.get("cliShowEvery")
? Number(formData.get("cliShowEvery"))
: undefined;
const discoveryFilePatterns = (formData.get("discoveryFilePatterns") as string) || "";
const discoveryContentPattern =
(formData.get("discoveryContentPattern") as string) || undefined;
const discoveryMatchBehavior = (formData.get("discoveryMatchBehavior") as string) || "";
const discovery =
discoveryFilePatterns && discoveryMatchBehavior
? {
filePatterns: discoveryFilePatterns
.split(",")
.map((s) => s.trim())
.filter(Boolean),
...(discoveryContentPattern ? { contentPattern: discoveryContentPattern } : {}),
matchBehavior: discoveryMatchBehavior as "show-if-found" | "show-if-not-found",
}
: undefined;
return {
surface,
payloadType,
adminLabel,
title,
description,
actionUrl,
image,
dismissOnAction,
startsAt,
endsAt,
priority,
scope,
scopeUserId,
scopeOrganizationId,
scopeProjectId,
cliMaxShowCount,
cliMaxDaysAfterFirstSeen,
cliShowEvery,
discovery,
};
}
function buildPayloadInput(fields: ReturnType<typeof parseNotificationFormData>) {
return {
version: "1" as const,
data: {
type: fields.payloadType as "info" | "warn" | "error" | "success" | "card" | "changelog",
title: fields.title,
description: fields.description,
...(fields.actionUrl ? { actionUrl: fields.actionUrl } : {}),
...(fields.image ? { image: fields.image } : {}),
...(fields.dismissOnAction ? { dismissOnAction: true } : {}),
...(fields.discovery ? { discovery: fields.discovery } : {}),
},
};
}
async function handleCreateAction(formData: FormData, userId: string, isPreview: boolean) {
const fields = parseNotificationFormData(formData);
if (!fields.adminLabel || !fields.title || !fields.description || !fields.endsAt || !fields.surface || !fields.payloadType) {
return typedjson({ error: "Missing required fields" }, { status: 400 });
}
const result = await createPlatformNotification({
title: isPreview ? `[Preview] ${fields.adminLabel}` : fields.adminLabel,
payload: buildPayloadInput(fields),
surface: fields.surface as "CLI" | "WEBAPP",
scope: isPreview ? "USER" : (fields.scope as "USER" | "PROJECT" | "ORGANIZATION" | "GLOBAL"),
...(isPreview
? { userId }
: {
...(fields.scope === "USER" && fields.scopeUserId ? { userId: fields.scopeUserId } : {}),
...(fields.scope === "ORGANIZATION" && fields.scopeOrganizationId ? { organizationId: fields.scopeOrganizationId } : {}),
...(fields.scope === "PROJECT" && fields.scopeProjectId ? { projectId: fields.scopeProjectId } : {}),
}),
startsAt: isPreview
? new Date().toISOString()
: fields.startsAt
? new Date(fields.startsAt + "Z").toISOString()
: new Date().toISOString(),
endsAt: isPreview
? new Date(Date.now() + 60 * 60 * 1000).toISOString()
: new Date(fields.endsAt + "Z").toISOString(),
priority: fields.priority,
...(fields.surface === "CLI"
? isPreview
? { cliMaxShowCount: 1 }
: {
cliMaxShowCount: fields.cliMaxShowCount,
cliMaxDaysAfterFirstSeen: fields.cliMaxDaysAfterFirstSeen,
cliShowEvery: fields.cliShowEvery,
}
: {}),
});
if (result.isErr()) {
const err = result.error;
if (err.type === "validation") {
return typedjson(
{ error: err.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") },
{ status: 400 }
);
}
logger.error("Failed to create platform notification", { error: err });
return typedjson({ error: "Something went wrong, please try again." }, { status: 500 });
}
if (isPreview) {
return typedjson({ success: true, previewId: result.value.id });
}
return typedjson({ success: true, id: result.value.id });
}
async function handleArchiveAction(formData: FormData) {
const notificationId = formData.get("notificationId") as string;
if (!notificationId) {
return typedjson({ error: "Missing notificationId" }, { status: 400 });
}
try {
await archivePlatformNotification(notificationId);
return typedjson({ success: true });
} catch (error) {
logger.error("Failed to archive platform notification", { error, notificationId });
return typedjson({ error: "Failed to archive notification, please try again." }, { status: 500 });
}
}
async function handleDeleteAction(formData: FormData) {
const notificationId = formData.get("notificationId") as string;
if (!notificationId) {
return typedjson({ error: "Missing notificationId" }, { status: 400 });
}
try {
await deletePlatformNotification(notificationId);
return typedjson({ success: true });
} catch (error) {
logger.error("Failed to delete platform notification", { error, notificationId });
return typedjson({ error: "Failed to delete notification, please try again." }, { status: 500 });
}
}
async function handlePublishNowAction(formData: FormData) {
const notificationId = formData.get("notificationId") as string;
if (!notificationId) {
return typedjson({ error: "Missing notificationId" }, { status: 400 });
}
try {
await publishNowPlatformNotification(notificationId);
return typedjson({ success: true });
} catch (error) {
logger.error("Failed to publish platform notification", { error, notificationId });
return typedjson({ error: "Failed to publish notification, please try again." }, { status: 500 });
}
}
async function handleEditAction(formData: FormData) {
const notificationId = formData.get("notificationId") as string;
const fields = parseNotificationFormData(formData);
if (!notificationId || !fields.adminLabel || !fields.title || !fields.description || !fields.endsAt || !fields.surface || !fields.payloadType || !fields.startsAt) {
return typedjson({ error: "Missing required fields" }, { status: 400 });
}
const result = await updatePlatformNotification({
id: notificationId,
title: fields.adminLabel,
payload: buildPayloadInput(fields),
surface: fields.surface as "CLI" | "WEBAPP",
scope: fields.scope as "USER" | "PROJECT" | "ORGANIZATION" | "GLOBAL",
...(fields.scope === "USER" && fields.scopeUserId ? { userId: fields.scopeUserId } : {}),
...(fields.scope === "ORGANIZATION" && fields.scopeOrganizationId ? { organizationId: fields.scopeOrganizationId } : {}),
...(fields.scope === "PROJECT" && fields.scopeProjectId ? { projectId: fields.scopeProjectId } : {}),
startsAt: new Date(fields.startsAt + "Z").toISOString(),
endsAt: new Date(fields.endsAt + "Z").toISOString(),
priority: fields.priority,
...(fields.surface === "CLI"
? {
cliMaxShowCount: fields.cliMaxShowCount,
cliMaxDaysAfterFirstSeen: fields.cliMaxDaysAfterFirstSeen,
cliShowEvery: fields.cliShowEvery,
}
: {}),
});
if (result.isErr()) {
const err = result.error;
if (err.type === "validation") {
return typedjson(
{ error: err.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") },
{ status: 400 }
);
}
logger.error("Failed to update platform notification", { error: err });
return typedjson({ error: "Something went wrong, please try again." }, { status: 500 });
}
return typedjson({ success: true, id: result.value.id });
}
export default function AdminNotificationsRoute() {
const { notifications, total, page, pageCount } = useTypedLoaderData<typeof loader>();
const [showCreate, setShowCreate] = useState(false);
const [detailNotification, setDetailNotification] = useState<(typeof notifications)[number] | null>(null);
const [editNotification, setEditNotification] = useState<(typeof notifications)[number] | null>(null);
const [urlSearchParams, setUrlSearchParams] = useSearchParams();
const hideInactive = urlSearchParams.get("hideInactive") === "true";
const toggleHideInactive = () => {
setUrlSearchParams((prev) => {
const next = new URLSearchParams(prev);
if (hideInactive) {
next.delete("hideInactive");
} else {
next.set("hideInactive", "true");
}
next.delete("page");
return next;
});
};
return (
<main className="flex h-full min-w-0 flex-1 flex-col overflow-y-auto px-4 pb-4">
<div className="space-y-4">
<div className="flex items-center justify-end">
<Button variant="primary/small" onClick={() => setShowCreate(true)}>
Create Notification
</Button>
</div>
<Dialog
open={showCreate}
onOpenChange={(open) => { if (!open) setShowCreate(false); }}
>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Create Notification</DialogTitle>
</DialogHeader>
<NotificationForm
key="create"
mode="create"
onClose={() => setShowCreate(false)}
/>
</DialogContent>
</Dialog>
<div className="flex items-center justify-between">
<Paragraph className="text-text-dimmed">
{total} notifications (page {page} of {pageCount || 1})
</Paragraph>
<label className="flex items-center gap-2 text-xs text-text-dimmed">
<input
type="checkbox"
checked={hideInactive}
onChange={toggleHideInactive}
className="rounded border-grid-dimmed bg-charcoal-900"
/>
Hide inactive
</label>
</div>
<Table>
<TableHeader>
<TableRow>
<TableHeaderCell>Title</TableHeaderCell>
<TableHeaderCell>Surface</TableHeaderCell>
<TableHeaderCell>Scope</TableHeaderCell>
<TableHeaderCell>Type</TableHeaderCell>
<TableHeaderCell>Starts (UTC)</TableHeaderCell>
<TableHeaderCell>Ends (UTC)</TableHeaderCell>
<TableHeaderCell>Seen</TableHeaderCell>
<TableHeaderCell>Clicked</TableHeaderCell>
<TableHeaderCell>Dismissed</TableHeaderCell>
<TableHeaderCell>Status</TableHeaderCell>
<TableHeaderCell></TableHeaderCell>
</TableRow>
</TableHeader>
<TableBody>
{notifications.length === 0 ? (
<TableBlankRow colSpan={10}>
<Paragraph>No notifications found</Paragraph>
</TableBlankRow>
) : (
notifications.map((n) => {
const status = getNotificationStatus(n);
const isActive = status === "active";
return (
<TableRow key={n.id} className="group/row">
<TableCell>
<button
type="button"
onClick={() => setDetailNotification(n)}
className="text-sm font-medium text-text-bright hover:text-indigo-400 transition-colors text-left"
>
{n.title}
</button>
</TableCell>
<TableCell>
<Badge color={n.surface === "CLI" ? "amber" : "blue"}>{n.surface}</Badge>
</TableCell>
<TableCell>
<Badge color={n.scope === "GLOBAL" ? "green" : "gray"}>{n.scope}</Badge>
</TableCell>
<TableCell>
<span className="text-xs text-text-dimmed">{n.payloadType ?? "—"}</span>
</TableCell>
<TableCell>
<span className="text-xs text-text-dimmed">{formatDate(n.startsAt)}</span>
</TableCell>
<TableCell>
<span className="text-xs text-text-dimmed">{formatDate(n.endsAt)}</span>
</TableCell>
<TableCell>
<span className="text-xs font-mono">{n.stats.seen}</span>
</TableCell>
<TableCell>
<span className="text-xs font-mono">{n.stats.clicked}</span>
</TableCell>
<TableCell>
<span className="text-xs font-mono">{n.stats.dismissed}</span>
</TableCell>
<TableCell>
<StatusBadge status={status} />
</TableCell>
<TableCell>
<div className="flex items-center justify-end gap-1 opacity-0 group-hover/row:opacity-100 transition-opacity">
{status === "pending" && (
<PublishNowButton notificationId={n.id} />
)}
{(status === "pending" || status === "releasing" || status === "active") && (
<Button
variant="tertiary/small"
onClick={() => setEditNotification(n)}
>
Edit
</Button>
)}
{status !== "archived" && (
<ArchiveButton notificationId={n.id} />
)}
<DeleteConfirmationButton notificationId={n.id} />
</div>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
<PaginationControls currentPage={page} totalPages={pageCount} />
</div>
<Dialog
open={detailNotification !== null}
onOpenChange={(open) => {
if (!open) setDetailNotification(null);
}}
>
<DialogContent className="max-w-lg">
{detailNotification && (
<>
<DialogHeader>
<DialogTitle>{detailNotification.title}</DialogTitle>
</DialogHeader>
<NotificationDetailContent notification={detailNotification} />
</>
)}
</DialogContent>
</Dialog>
<Dialog
open={editNotification !== null}
onOpenChange={(open) => {
if (!open) setEditNotification(null);
}}
>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto">
{editNotification && (
<>
<DialogHeader>
<DialogTitle>Edit Notification</DialogTitle>
</DialogHeader>
<NotificationForm
key={editNotification.id}
mode="edit"
notification={editNotification}
onClose={() => setEditNotification(null)}
/>
</>
)}
</DialogContent>
</Dialog>
</main>
);
}
function ArchiveButton({ notificationId }: { notificationId: string }) {
const fetcher = useFetcher();
return (
<fetcher.Form method="post" className="inline">
<input type="hidden" name="_action" value="archive" />
<input type="hidden" name="notificationId" value={notificationId} />
<Button type="submit" variant="danger/small" disabled={fetcher.state !== "idle"}>
Archive
</Button>
</fetcher.Form>
);
}
function PublishNowButton({ notificationId }: { notificationId: string }) {
const [open, setOpen] = useState(false);
const fetcher = useFetcher();
return (
<Alert open={open} onOpenChange={setOpen}>
<AlertTrigger asChild>
<Button variant="secondary/small">Publish Now</Button>
</AlertTrigger>
<AlertContent>
<AlertHeader>
<AlertTitle>Publish notification now</AlertTitle>
<AlertDescription>
This will make the notification immediately visible to users.
</AlertDescription>
</AlertHeader>
<AlertFooter>
<AlertCancel asChild>
<Button variant="secondary/small">Cancel</Button>
</AlertCancel>
<fetcher.Form method="post" onSubmit={() => setOpen(false)}>
<input type="hidden" name="_action" value="publish-now" />
<input type="hidden" name="notificationId" value={notificationId} />
<Button type="submit" variant="primary/small">
Publish
</Button>
</fetcher.Form>
</AlertFooter>
</AlertContent>
</Alert>
);
}
function DeleteConfirmationButton({ notificationId }: { notificationId: string }) {
const [open, setOpen] = useState(false);
const fetcher = useFetcher();
return (
<Alert open={open} onOpenChange={setOpen}>
<AlertTrigger asChild>
<Button variant="tertiary/small">
<TrashIcon className="size-3.5 text-text-dimmed" />
</Button>
</AlertTrigger>
<AlertContent>
<AlertHeader>
<AlertTitle>Delete notification</AlertTitle>
<AlertDescription>
This will permanently delete this notification and all its interaction data. This
action cannot be undone.
</AlertDescription>
</AlertHeader>
<AlertFooter>
<AlertCancel asChild>
<Button variant="secondary/small">Cancel</Button>
</AlertCancel>
<fetcher.Form method="post" onSubmit={() => setOpen(false)}>
<input type="hidden" name="_action" value="delete" />
<input type="hidden" name="notificationId" value={notificationId} />
<Button type="submit" variant="danger/small">
Delete
</Button>
</fetcher.Form>
</AlertFooter>
</AlertContent>
</Alert>
);
}
type NotificationFormDefaults = {
id?: string;
title?: string;
surface?: string;
scope?: string;
userId?: string | null;
organizationId?: string | null;
projectId?: string | null;
priority?: number;
startsAt?: Date;
endsAt?: Date;
payloadTitle?: string | null;
payloadType?: string | null;
payloadDescription?: string | null;
payloadActionUrl?: string | null;
payloadImage?: string | null;
payloadDismissOnAction?: boolean;
payloadDiscovery?: {
filePatterns: string[];
contentPattern?: string;
matchBehavior: "show-if-found" | "show-if-not-found";
} | null;
cliMaxShowCount?: number | null;
cliMaxDaysAfterFirstSeen?: number | null;
cliShowEvery?: number | null;
};
function NotificationForm({
mode,
notification: n,
onClose,
}: {
mode: "create" | "edit";
notification?: NotificationFormDefaults;
onClose: () => void;
}) {
const fetcher = useFetcher<{ success?: boolean; error?: string; previewId?: string }>();
const [surface, setSurface] = useState<"CLI" | "WEBAPP">((n?.surface as "CLI" | "WEBAPP") ?? "WEBAPP");
const [payloadType, setPayloadType] = useState<string>(n?.payloadType ?? "card");
const [scope, setScope] = useState<string>(n?.scope ?? "GLOBAL");
const [title, setTitle] = useState(n?.payloadTitle ?? "");
const [description, setDescription] = useState(n?.payloadDescription ?? "");
const [actionUrl, setActionUrl] = useState(n?.payloadActionUrl ?? "");
const [image, setImage] = useState(n?.payloadImage ?? "");
const typeOptions = surface === "WEBAPP" ? WEBAPP_TYPES : CLI_TYPES;
const handleSurfaceChange = (newSurface: "CLI" | "WEBAPP") => {
setSurface(newSurface);
const newTypes = newSurface === "WEBAPP" ? WEBAPP_TYPES : CLI_TYPES;
if (!newTypes.includes(payloadType as any)) {
setPayloadType(newTypes[0]);
}
};
useEffect(() => {
if (fetcher.data?.success && !fetcher.data.previewId) {
onClose();
}
}, [fetcher.data, onClose]);
const isEdit = mode === "edit";
return (
<fetcher.Form method="post" className="space-y-3">
{isEdit && (
<>
<input type="hidden" name="_action" value="edit" />
<input type="hidden" name="notificationId" value={n?.id} />
</>
)}
<div className="flex gap-3">
<div className="flex-1">
<label className="text-xs font-medium text-text-dimmed">Admin Label</label>
<Input
name="adminLabel"
variant="medium"
fullWidth
defaultValue={n?.title ?? ""}
placeholder="Internal name for this notification"
className="mt-1"
/>
</div>
<div className="w-28">
<label className="text-xs font-medium text-text-dimmed">Surface</label>
<select
name="surface"
value={surface}
onChange={(e) => handleSurfaceChange(e.target.value as "CLI" | "WEBAPP")}
className="mt-1 block w-full rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright"
>
<option value="WEBAPP">WEBAPP</option>
<option value="CLI">CLI</option>
</select>
</div>
<div className="w-28">
<label className="text-xs font-medium text-text-dimmed">Type</label>
<select
name="payloadType"
value={payloadType}
onChange={(e) => setPayloadType(e.target.value)}
className="mt-1 block w-full rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright"
>
{typeOptions.map((t) => (
<option key={t} value={t}>
{t}
</option>
))}
</select>
</div>
<div className="w-16">
<label className="text-xs font-medium text-text-dimmed">Priority</label>
<Input
name="priority"
variant="medium"
fullWidth
defaultValue={String(n?.priority ?? 0)}
type="number"
className="mt-1"
/>
</div>
</div>
<div className="flex gap-3">
<div className="w-36">
<label className="text-xs font-medium text-text-dimmed">Scope</label>
<select
name="scope"
value={scope}
onChange={(e) => setScope(e.target.value)}
className="mt-1 block w-full rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright"
>
<option value="GLOBAL">GLOBAL</option>
<option value="USER">USER</option>
<option value="ORGANIZATION">ORGANIZATION</option>
<option value="PROJECT">PROJECT</option>
</select>
</div>
{scope === "USER" && (
<div className="flex-1">
<label className="text-xs font-medium text-text-dimmed">User ID</label>
<Input name="scopeUserId" variant="medium" fullWidth defaultValue={n?.userId ?? ""} placeholder="User ID" className="mt-1" />
</div>
)}
{scope === "ORGANIZATION" && (
<div className="flex-1">
<label className="text-xs font-medium text-text-dimmed">Organization ID</label>
<Input name="scopeOrganizationId" variant="medium" fullWidth defaultValue={n?.organizationId ?? ""} placeholder="Organization ID" className="mt-1" />
</div>
)}
{scope === "PROJECT" && (
<div className="flex-1">
<label className="text-xs font-medium text-text-dimmed">Project ID</label>
<Input name="scopeProjectId" variant="medium" fullWidth defaultValue={n?.projectId ?? ""} placeholder="Project ID" className="mt-1" />
</div>
)}
</div>
{/* CLI live preview */}
{surface === "CLI" && (title || description) && (
<div>
<p className="text-[10px] font-medium text-text-dimmed/60 uppercase tracking-wider mb-1">
CLI Preview
</p>
<div className="rounded border border-grid-dimmed bg-charcoal-900 p-3 font-mono text-xs leading-relaxed">
{title && (
<p className="font-bold text-text-bright">
<CliColorMarkup text={title} fallbackClass="text-text-bright" />
</p>
)}
{description && (
<p className="text-text-dimmed">
<CliColorMarkup text={description} fallbackClass="text-text-dimmed" />
</p>
)}
{actionUrl && (
<p className="text-text-dimmed underline">{actionUrl}</p>
)}
</div>
</div>
)}
<div>
<label className="text-xs font-medium text-text-dimmed">Title</label>
<Input
name="title"
variant="medium"
fullWidth
placeholder="Notification title"
value={title}
onChange={(e) => setTitle(e.target.value)}
className="mt-1"
/>
</div>
<div>
<label className="text-xs font-medium text-text-dimmed">
Description{surface === "WEBAPP" ? " (markdown)" : ""}
</label>
{surface === "WEBAPP" ? (
<div className="mt-1 flex gap-3">
<textarea
name="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={6}
placeholder="Supports **bold**, *italic*, `code`, [links](url)..."
className="block min-w-0 flex-1 rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright placeholder:text-text-dimmed/50 font-mono resize-y"
/>
<div className="shrink-0">
<div className="text-[10px] font-medium text-text-dimmed/60 uppercase tracking-wider mb-1">
Preview
</div>
<div className="w-56">
<NotificationPreviewCard
title={title || "Notification title"}
description={description || "Description preview will appear here..."}
actionUrl={actionUrl || undefined}
image={image || undefined}
/>
</div>
</div>
</div>
) : (
<textarea
name="description"
value={description}
onChange={(e) => setDescription(e.target.value)}
rows={6}
placeholder="Plain text description..."
className="mt-1 block w-full rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright placeholder:text-text-dimmed/50 font-mono resize-y"
/>
)}
</div>
{surface === "WEBAPP" ? (
<div className="flex items-end gap-3">
<div className="flex-1">
<label className="text-xs font-medium text-text-dimmed">Action URL (optional)</label>
<Input
name="actionUrl"
variant="medium"
fullWidth
placeholder="https://..."
value={actionUrl}
onChange={(e) => setActionUrl(e.target.value)}
className="mt-1"
/>
</div>
<label className="flex items-center gap-2 pb-1.5 text-xs text-text-dimmed whitespace-nowrap">
<input
type="checkbox"
name="dismissOnAction"
value="true"
defaultChecked={n?.payloadDismissOnAction ?? false}
className="rounded border-grid-dimmed bg-charcoal-900"
/>
Dismiss on action click
</label>
</div>
) : (
<div>
<label className="text-xs font-medium text-text-dimmed">Action URL (optional)</label>
<Input
name="actionUrl"
variant="medium"
fullWidth
placeholder="https://..."
value={actionUrl}
onChange={(e) => setActionUrl(e.target.value)}
className="mt-1"
/>
</div>
)}
{surface === "WEBAPP" && (
<div>
<label className="text-xs font-medium text-text-dimmed">Image URL (optional)</label>
<Input
name="image"
variant="medium"
fullWidth
placeholder="https://example.com/image.png"
value={image}
onChange={(e) => setImage(e.target.value)}
className="mt-1"
/>
</div>
)}
<div className="grid grid-cols-2 gap-3">
<div>
<label className="text-xs font-medium text-text-dimmed">Starts At (UTC)</label>
<input
name="startsAt"
type="datetime-local"
defaultValue={n?.startsAt ? toDatetimeLocalUTC(new Date(n.startsAt)) : defaultStartsAt()}
className="mt-1 block w-full rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright"
/>
</div>
<div>
<label className="text-xs font-medium text-text-dimmed">Ends At (UTC)</label>
<input
name="endsAt"
type="datetime-local"
defaultValue={n?.endsAt ? toDatetimeLocalUTC(new Date(n.endsAt)) : defaultEndsAt()}
className="mt-1 block w-full rounded-sm border border-grid-dimmed bg-charcoal-900 px-2 py-1.5 text-sm text-text-bright"
required
/>
</div>
</div>
{surface === "CLI" && (
<>
<div className="grid grid-cols-3 gap-3 rounded border border-grid-dimmed bg-charcoal-900 p-3">
<div>
<label className="text-xs font-medium text-text-dimmed">Max Show Count</label>
<Input
name="cliMaxShowCount"
variant="medium"
fullWidth
type="number"
defaultValue={n?.cliMaxShowCount != null ? String(n.cliMaxShowCount) : ""}
placeholder="e.g. 5"
className="mt-1"
/>
</div>
<div>
<label className="text-xs font-medium text-text-dimmed">
Max Days After First Seen
</label>
<Input
name="cliMaxDaysAfterFirstSeen"
variant="medium"
fullWidth
type="number"
defaultValue={n?.cliMaxDaysAfterFirstSeen != null ? String(n.cliMaxDaysAfterFirstSeen) : ""}
placeholder="e.g. 7"
className="mt-1"
/>
</div>
<div>
<label className="text-xs font-medium text-text-dimmed">Show Every (Nth)</label>
<Input
name="cliShowEvery"
variant="medium"
fullWidth
type="number"
defaultValue={n?.cliShowEvery != null ? String(n.cliShowEvery) : ""}
placeholder="e.g. 3"
className="mt-1"
/>
</div>
</div>
<div className="rounded border border-grid-dimmed bg-charcoal-900 p-3 space-y-3">
<div className="text-xs font-medium text-text-dimmed">
Discovery (optional) — only show notification if file pattern matches
</div>
<div className="grid grid-cols-3 gap-3">
<div>
<label className="text-xs font-medium text-text-dimmed">File Patterns</label>
<Input
name="discoveryFilePatterns"
variant="medium"
fullWidth
defaultValue={n?.payloadDiscovery?.filePatterns.join(", ") ?? ""}
placeholder="trigger.config.ts, trigger.config.js"
className="mt-1"
/>
<span className="text-[10px] text-text-dimmed/60">Comma-separated</span>
</div>
<div>
<label className="text-xs font-medium text-text-dimmed">Content Pattern</label>
<Input
name="discoveryContentPattern"
variant="medium"