-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathroute.tsx
More file actions
763 lines (712 loc) · 27.2 KB
/
route.tsx
File metadata and controls
763 lines (712 loc) · 27.2 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
import { ArrowUpCircleIcon, PlusIcon, TrashIcon } from "@heroicons/react/20/solid";
import { DialogClose } from "@radix-ui/react-dialog";
import { type ActionFunctionArgs, type LoaderFunctionArgs } from "@remix-run/node";
import { Form, useNavigation } from "@remix-run/react";
import { IconChartHistogram, IconEdit, IconTypography } from "@tabler/icons-react";
import { useCallback, useEffect, useState } from "react";
import { typedjson, useTypedLoaderData } from "remix-typedjson";
import { z } from "zod";
import { defaultChartConfig } from "~/components/code/ChartConfigPanel";
import { Feedback } from "~/components/Feedback";
import { MainCenteredContainer, PageBody, PageContainer } from "~/components/layout/AppLayout";
import { Button, LinkButton } from "~/components/primitives/Buttons";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTrigger,
} from "~/components/primitives/Dialog";
import { FormButtons } from "~/components/primitives/FormButtons";
import { Header3 } from "~/components/primitives/Headers";
import { InfoPanel } from "~/components/primitives/InfoPanel";
import { Input } from "~/components/primitives/Input";
import { InputGroup } from "~/components/primitives/InputGroup";
import { Label } from "~/components/primitives/Label";
import { NavBar, PageAccessories, PageTitle } from "~/components/primitives/PageHeader";
import { Paragraph } from "~/components/primitives/Paragraph";
import {
Popover,
PopoverContent,
PopoverVerticalEllipseTrigger,
} from "~/components/primitives/Popover";
import { Sheet, SheetContent } from "~/components/primitives/SheetV3";
import { useToast } from "~/components/primitives/Toast";
import { SimpleTooltip } from "~/components/primitives/Tooltip";
import { QueryEditor, type QueryEditorSaveData } from "~/components/query/QueryEditor";
import { prisma } from "~/db.server";
import { env } from "~/env.server";
import { useDashboardEditor } from "~/hooks/useDashboardEditor";
import { useEnvironment } from "~/hooks/useEnvironment";
import { useOrganization, useWidgetLimitPerDashboard } from "~/hooks/useOrganizations";
import { useProject } from "~/hooks/useProject";
import { redirectWithSuccessMessage } from "~/models/message.server";
import { findProjectBySlug } from "~/models/project.server";
import { findEnvironmentBySlug } from "~/models/runtimeEnvironment.server";
import { getTaskIdentifiers } from "~/models/task.server";
import { MetricDashboardPresenter } from "~/presenters/v3/MetricDashboardPresenter.server";
import { QueryPresenter } from "~/presenters/v3/QueryPresenter.server";
import { requireUser, requireUserId } from "~/services/session.server";
import {
EnvironmentParamSchema,
queryPath,
v3BillingPath,
v3BuiltInDashboardPath,
} from "~/utils/pathBuilder";
import { MetricDashboard } from "../_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboards.$dashboardKey/route";
import { useCurrentPlan } from "../_app.orgs.$organizationSlug/route";
import { Type } from "lucide-react";
const ParamSchema = EnvironmentParamSchema.extend({
dashboardId: z.string(),
});
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const user = await requireUser(request);
const { projectParam, organizationSlug, envParam, dashboardId } = ParamSchema.parse(params);
const project = await findProjectBySlug(organizationSlug, projectParam, user.id);
if (!project) {
throw new Response(undefined, {
status: 404,
statusText: "Project not found",
});
}
const environment = await findEnvironmentBySlug(project.id, envParam, user.id);
if (!environment) {
throw new Response(undefined, {
status: 404,
statusText: "Environment not found",
});
}
const dashboardPresenter = new MetricDashboardPresenter();
const queryPresenter = new QueryPresenter();
const [dashboard, { defaultQuery, history }, possibleTasks] = await Promise.all([
dashboardPresenter.customDashboard({
friendlyId: dashboardId,
organizationId: project.organizationId,
}),
queryPresenter.call({
organizationId: project.organizationId,
}),
getTaskIdentifiers(environment.id),
]);
// Admins and impersonating users can use EXPLAIN
const isAdmin = user.admin || user.isImpersonating;
// Compute widget count from dashboard layout
const widgetCount = Object.keys(dashboard.layout.widgets).length;
return typedjson({
...dashboard,
// Query editor data
queryDefaultQuery: defaultQuery,
queryHistory: history,
isAdmin,
maxRows: env.QUERY_CLICKHOUSE_MAX_RETURNED_ROWS,
possibleTasks,
widgetCount,
});
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const userId = await requireUserId(request);
const { projectParam, organizationSlug, envParam, dashboardId } = ParamSchema.parse(params);
const project = await findProjectBySlug(organizationSlug, projectParam, userId);
if (!project) {
throw new Response("Project not found", { status: 404 });
}
// Load the dashboard
const dashboard = await prisma.metricsDashboard.findFirst({
where: {
friendlyId: dashboardId,
organizationId: project.organizationId,
},
});
if (!dashboard) {
throw new Response("Dashboard not found", { status: 404 });
}
const formData = await request.formData();
const action = formData.get("action");
switch (action) {
case "delete": {
await prisma.metricsDashboard.delete({
where: { id: dashboard.id },
});
return redirectWithSuccessMessage(
v3BuiltInDashboardPath(
{ slug: organizationSlug },
{ slug: projectParam },
{ slug: envParam },
"overview"
),
request,
`Deleted "${dashboard.title}" dashboard`
);
}
case "rename": {
const newTitle = formData.get("title");
if (typeof newTitle !== "string" || newTitle.trim().length === 0) {
throw new Response("Title is required", { status: 400 });
}
await prisma.metricsDashboard.update({
where: { id: dashboard.id },
data: { title: newTitle.trim() },
});
return typedjson({ success: true });
}
default: {
throw new Response("Invalid action", { status: 400 });
}
}
};
export default function Page() {
const {
friendlyId,
title,
layout: dashboardLayout,
defaultPeriod,
queryDefaultQuery,
queryHistory,
isAdmin,
maxRows,
possibleTasks,
widgetCount: initialWidgetCount,
} = useTypedLoaderData<typeof loader>();
const organization = useOrganization();
const project = useProject();
const environment = useEnvironment();
const plan = useCurrentPlan();
const maxPeriodDays = plan?.v3Subscription?.plan?.limits?.queryPeriodDays?.number;
// Widget limits
const widgetLimitPerDashboard = useWidgetLimitPerDashboard();
const planLimits = (plan?.v3Subscription?.plan?.limits as any)?.metricWidgetsPerDashboard;
const canExceedWidgets = typeof planLimits === "object" && planLimits.canExceed === true;
// Build the action URLs - both use the resource route to avoid full page renders on POST
const widgetActionUrl = `/resources/orgs/${organization.slug}/projects/${project.slug}/env/${environment.slug}/dashboards/${friendlyId}/widgets`;
const layoutActionUrl = widgetActionUrl;
const toast = useToast();
const handleSyncError = useCallback((error: Error, action: string) => {
const actionMessages: Record<string, string> = {
add: "Failed to add widget",
update: "Failed to update widget",
delete: "Failed to delete widget",
duplicate: "Failed to duplicate widget",
layout: "Failed to save layout",
};
const message = actionMessages[action] || "Failed to save changes";
toast.error(`${message}. Your changes may not be saved.`, { title: "Sync Error" });
}, [toast]);
// Add title dialog state
const [showAddTitleDialog, setShowAddTitleDialog] = useState(false);
const [newTitleValue, setNewTitleValue] = useState("");
// Widget limit dialog state (triggered when hook blocks add/duplicate)
const [showWidgetLimitDialog, setShowWidgetLimitDialog] = useState(false);
const handleWidgetLimitReached = useCallback(() => {
setShowWidgetLimitDialog(true);
}, []);
// Use the dashboard editor hook for all state management
const { state, actions } = useDashboardEditor({
initialData: dashboardLayout,
widgetActionUrl,
layoutActionUrl,
widgetLimit: canExceedWidgets ? undefined : widgetLimitPerDashboard,
onSyncError: handleSyncError,
onWidgetLimitReached: handleWidgetLimitReached,
});
// Reactive widget count from editor state (title widgets don't count against limits)
const currentWidgetCount = Object.values(state.widgets).filter(
(w) => w.display.type !== "title"
).length;
const totalWidgetCount = Object.keys(state.widgets).length;
const widgetLimits = { used: currentWidgetCount, limit: widgetLimitPerDashboard };
const widgetIsAtLimit = currentWidgetCount >= widgetLimitPerDashboard;
const widgetLimitRatio =
widgetLimits.limit > 0 ? widgetLimits.used / widgetLimits.limit : widgetLimits.used > 0 ? 1 : 0;
const widgetLimitPercent = Math.min(100, Math.max(0, Math.round(widgetLimitRatio * 100)));
const widgetCanUpgrade = plan?.v3Subscription?.plan && !canExceedWidgets;
// Build the query action URL for the editor
const queryActionUrl = queryPath(
{ slug: organization.slug },
{ slug: project.slug },
{ slug: environment.slug }
);
// Handle save from the QueryEditor
const handleSave = useCallback(
(data: QueryEditorSaveData) => {
if (state.editorMode?.type === "add") {
actions.addWidget(data.title, data.query, data.config);
} else if (state.editorMode?.type === "edit") {
actions.updateWidget(state.editorMode.widgetId, data.title, data.query, data.config);
}
},
[state.editorMode, actions]
);
// Render save button for the QueryEditor
const renderSaveForm = useCallback(
(data: QueryEditorSaveData) => {
const isAdd = state.editorMode?.type === "add";
return (
<Button
type="button"
variant="primary/small"
disabled={!data.query}
onClick={() => handleSave(data)}
>
{isAdd ? "Add to dashboard" : "Save changes"}
</Button>
);
},
[state.editorMode, handleSave]
);
// Prepare editor props when in editor mode
const editorProps = state.editorMode
? (() => {
const mode =
state.editorMode.type === "add"
? { type: "dashboard-add" as const, dashboardId: friendlyId, dashboardName: title }
: {
type: "dashboard-edit" as const,
dashboardId: friendlyId,
dashboardName: title,
widgetId: state.editorMode.widgetId,
widgetName: state.editorMode.widget.title,
};
// For edit mode, use the widget's existing values as defaults
const editorDefaultQuery =
state.editorMode.type === "edit" ? state.editorMode.widget.query : queryDefaultQuery;
const editorDefaultChartConfig =
state.editorMode.type === "edit" && state.editorMode.widget.display.type === "chart"
? {
chartType: state.editorMode.widget.display.chartType,
xAxisColumn: state.editorMode.widget.display.xAxisColumn,
yAxisColumns: state.editorMode.widget.display.yAxisColumns,
groupByColumn: state.editorMode.widget.display.groupByColumn,
stacked: state.editorMode.widget.display.stacked,
sortByColumn: state.editorMode.widget.display.sortByColumn,
sortDirection: state.editorMode.widget.display.sortDirection,
aggregation: state.editorMode.widget.display.aggregation,
seriesColors: state.editorMode.widget.display.seriesColors,
}
: defaultChartConfig;
const editorDefaultBigNumberConfig =
state.editorMode.type === "edit" && state.editorMode.widget.display.type === "bignumber"
? {
column: state.editorMode.widget.display.column,
aggregation: state.editorMode.widget.display.aggregation,
sortDirection: state.editorMode.widget.display.sortDirection,
abbreviate: state.editorMode.widget.display.abbreviate,
prefix: state.editorMode.widget.display.prefix,
suffix: state.editorMode.widget.display.suffix,
}
: undefined;
const editorDefaultResultsView =
state.editorMode.type === "edit" ? state.editorMode.widget.display.type : "table";
// Pass the existing result data when editing
const editorDefaultData =
state.editorMode.type === "edit" ? state.editorMode.widget.resultData : undefined;
return {
mode,
editorDefaultQuery,
editorDefaultChartConfig,
editorDefaultBigNumberConfig,
editorDefaultResultsView,
editorDefaultData,
};
})()
: null;
return (
<PageContainer>
<NavBar>
<PageTitle title={title} />
<PageAccessories>
{totalWidgetCount > 0 &&
(widgetIsAtLimit ? (
<>
<Dialog>
<DialogTrigger asChild>
<Button variant="primary/small" LeadingIcon={PlusIcon}>
Add chart
</Button>
</DialogTrigger>
<DialogContent>
<DialogHeader>You've exceeded your widget limit</DialogHeader>
<DialogDescription>
You've used {widgetLimits.used}/{widgetLimits.limit} widgets on this
dashboard.
</DialogDescription>
<DialogFooter>
{widgetCanUpgrade ? (
<LinkButton variant="primary/small" to={v3BillingPath(organization)}>
Upgrade
</LinkButton>
) : (
<Feedback
button={<Button variant="primary/small">Request more</Button>}
defaultValue="help"
/>
)}
</DialogFooter>
</DialogContent>
</Dialog>
<Button
variant="secondary/small"
LeadingIcon={Type}
className="pl-1.5"
iconSpacing="gap-x-1"
onClick={() => {
setNewTitleValue("");
setShowAddTitleDialog(true);
}}
>
Add title
</Button>
</>
) : (
<>
<Button
variant="primary/small"
LeadingIcon={IconChartHistogram}
className="pl-1.5"
iconSpacing="gap-x-1.5"
onClick={actions.openAddEditor}
>
Add chart
</Button>
<Button
variant="secondary/small"
LeadingIcon={Type}
className="pl-1.5"
iconSpacing="gap-x-1"
onClick={() => {
setNewTitleValue("");
setShowAddTitleDialog(true);
}}
>
Add title
</Button>
</>
))}
<Popover>
<PopoverVerticalEllipseTrigger variant="secondary" />
<PopoverContent className="w-fit min-w-[10rem] p-1" align="end">
<div className="flex flex-col gap-1">
<RenameDashboardDialog title={title} />
<DeleteDashboardDialog title={title} />
</div>
</PopoverContent>
</Popover>
</PageAccessories>
</NavBar>
<PageBody scrollable={false}>
<div className="flex h-full flex-col">
<div className="min-h-0 flex-1">
{totalWidgetCount === 0 ? (
<MainCenteredContainer className="max-w-md">
<InfoPanel
icon={IconChartHistogram}
iconClassName="text-metrics"
panelClassName="max-full"
title="Add your first chart"
accessory={
<Button
variant="primary/small"
LeadingIcon={PlusIcon}
onClick={actions.openAddEditor}
>
Add chart
</Button>
}
>
<Paragraph variant="small">
Charts let you visualize your task metrics. Write a query to pull data from your
runs, then choose how to display it on this dashboard.
</Paragraph>
</InfoPanel>
</MainCenteredContainer>
) : (
<MetricDashboard
key={friendlyId}
layout={state.layout}
widgets={state.widgets}
defaultPeriod={defaultPeriod}
editable={true}
possibleTasks={possibleTasks}
onLayoutChange={actions.updateLayout}
onEditWidget={actions.openEditEditor}
onRenameWidget={actions.renameWidget}
onDeleteWidget={actions.deleteWidget}
onDuplicateWidget={actions.duplicateWidget}
/>
)}
</div>
<div className="flex w-full items-start justify-between">
<div className="flex h-fit w-full items-center gap-4 border-t border-grid-bright bg-background-bright p-[0.86rem] pl-4">
<SimpleTooltip
button={
<div className="size-6">
<svg className="h-full w-full -rotate-90 overflow-visible">
<circle
className="fill-none stroke-grid-bright"
strokeWidth="4"
r="10"
cx="12"
cy="12"
/>
<circle
className={`fill-none ${
widgetIsAtLimit ? "stroke-error" : "stroke-success"
}`}
strokeWidth="4"
r="10"
cx="12"
cy="12"
strokeDasharray={`${widgetLimitRatio * 62.8} 62.8`}
strokeDashoffset="0"
strokeLinecap="round"
/>
</svg>
</div>
}
content={`${widgetLimitPercent}%`}
/>
<div className="flex w-full items-center justify-between gap-6">
{widgetIsAtLimit ? (
<Header3 className="text-error">
You've used all {widgetLimits.limit} of your available widgets. Upgrade your
plan to enable more.
</Header3>
) : (
<Header3>
You've used {widgetLimits.used}/{widgetLimits.limit} of your charts
</Header3>
)}
{widgetCanUpgrade ? (
<LinkButton
to={v3BillingPath(organization)}
variant="secondary/small"
LeadingIcon={ArrowUpCircleIcon}
leadingIconClassName="text-indigo-500"
>
Upgrade
</LinkButton>
) : (
<Feedback
button={<Button variant="secondary/small">Request more…</Button>}
defaultValue="help"
/>
)}
</div>
</div>
</div>
</div>
</PageBody>
{/* Query Editor Sheet - opens on top of the dashboard */}
<Sheet open={!!state.editorMode} onOpenChange={(open) => !open && actions.closeEditor()}>
<SheetContent
side="right"
className="w-[90vw] max-w-none rounded-l-lg border-l border-grid-dimmed p-0 sm:max-w-none"
>
{editorProps && (
<QueryEditor
defaultQuery={editorProps.editorDefaultQuery}
defaultScope="environment"
defaultPeriod={defaultPeriod}
defaultResultsView={
editorProps.editorDefaultResultsView === "chart"
? "graph"
: editorProps.editorDefaultResultsView === "bignumber"
? "bignumber"
: "table"
}
defaultChartConfig={editorProps.editorDefaultChartConfig}
defaultBigNumberConfig={editorProps.editorDefaultBigNumberConfig}
defaultData={editorProps.editorDefaultData}
history={queryHistory}
isAdmin={isAdmin}
maxRows={maxRows}
queryActionUrl={queryActionUrl}
mode={editorProps.mode}
maxPeriodDays={maxPeriodDays}
save={renderSaveForm}
onClose={actions.closeEditor}
/>
)}
</SheetContent>
</Sheet>
{/* Add title dialog */}
<Dialog open={showAddTitleDialog} onOpenChange={setShowAddTitleDialog}>
<DialogContent className="sm:max-w-md">
<DialogHeader>Add title</DialogHeader>
<form
className="space-y-4 pt-3"
onSubmit={(e) => {
e.preventDefault();
if (newTitleValue.trim()) {
actions.addTitleWidget(newTitleValue.trim());
setShowAddTitleDialog(false);
}
}}
>
<InputGroup>
<Label>Title</Label>
<Input
value={newTitleValue}
onChange={(e) => setNewTitleValue(e.target.value)}
placeholder="Section title"
autoFocus
/>
</InputGroup>
<DialogFooter>
<DialogClose asChild>
<Button variant="tertiary/medium">Cancel</Button>
</DialogClose>
<Button type="submit" variant="primary/medium" disabled={!newTitleValue.trim()}>
Add
</Button>
</DialogFooter>
</form>
</DialogContent>
</Dialog>
{/* Widget limit dialog - triggered by hook when add/duplicate is blocked */}
<Dialog open={showWidgetLimitDialog} onOpenChange={setShowWidgetLimitDialog}>
<DialogContent>
<DialogHeader>You've exceeded your widget limit</DialogHeader>
<DialogDescription>
You've used {widgetLimits.used}/{widgetLimits.limit} widgets on this dashboard.
</DialogDescription>
<DialogFooter>
{widgetCanUpgrade ? (
<LinkButton variant="primary/small" to={v3BillingPath(organization)}>
Upgrade
</LinkButton>
) : (
<Feedback
button={<Button variant="primary/small">Request more</Button>}
defaultValue="help"
/>
)}
</DialogFooter>
</DialogContent>
</Dialog>
</PageContainer>
);
}
function RenameDashboardDialog({ title }: { title: string }) {
const navigation = useNavigation();
const [isOpen, setIsOpen] = useState(false);
const [newTitle, setNewTitle] = useState(title);
const isRenaming =
navigation.state !== "idle" &&
navigation.formMethod === "post" &&
navigation.formData?.get("action") === "rename";
// Close dialog when navigation completes
useEffect(() => {
if (navigation.state === "idle") {
setIsOpen(false);
}
}, [navigation.state]);
// Sync newTitle state when title changes (after successful rename)
useEffect(() => {
setNewTitle(title);
}, [title]);
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>
<Button
variant="small-menu-item"
LeadingIcon={IconEdit}
fullWidth
textAlignLeft
className="pl-0.5 pr-3"
leadingIconClassName="gap-x-0"
>
Rename dashboard
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-sm">
<DialogHeader>Rename dashboard</DialogHeader>
<Form method="post" className="space-y-4">
<input type="hidden" name="action" value="rename" />
<InputGroup>
<Label>Title</Label>
<Input
name="title"
value={newTitle}
onChange={(e) => setNewTitle(e.target.value)}
placeholder="Dashboard title"
required
autoFocus
/>
</InputGroup>
<FormButtons
confirmButton={
<Button
type="submit"
variant="primary/medium"
disabled={isRenaming || !newTitle.trim()}
>
{isRenaming ? "Saving…" : "Save"}
</Button>
}
cancelButton={
<DialogClose asChild>
<Button variant="tertiary/medium">Cancel</Button>
</DialogClose>
}
/>
</Form>
</DialogContent>
</Dialog>
);
}
function DeleteDashboardDialog({ title }: { title: string }) {
const navigation = useNavigation();
const [isOpen, setIsOpen] = useState(false);
const isDeleting =
navigation.state !== "idle" &&
navigation.formMethod === "post" &&
navigation.formData?.get("action") === "delete";
// Close dialog when navigation completes
useEffect(() => {
if (navigation.state === "idle") {
setIsOpen(false);
}
}, [navigation.state]);
return (
<Dialog open={isOpen} onOpenChange={setIsOpen}>
<DialogTrigger asChild>
<Button
variant="small-menu-item"
LeadingIcon={TrashIcon}
leadingIconClassName="text-rose-500"
fullWidth
textAlignLeft
>
Delete dashboard
</Button>
</DialogTrigger>
<DialogContent className="sm:max-w-md">
<DialogHeader>Delete dashboard</DialogHeader>
<div className="mb-2 mt-4 flex flex-col gap-2">
<Paragraph>
Are you sure you want to delete <strong>"{title}"</strong>? This action cannot be undone
and all widgets on this dashboard will be permanently removed.
</Paragraph>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="secondary/medium">Cancel</Button>
</DialogClose>
<Form method="post">
<Button
type="submit"
name="action"
value="delete"
variant="danger/medium"
LeadingIcon={TrashIcon}
disabled={isDeleting}
>
{isDeleting ? "Deleting…" : "Delete"}
</Button>
</Form>
</DialogFooter>
</DialogContent>
</Dialog>
);
}