Skip to content

A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search

perf(web): reduce admin user list rendering overhead (#3184)

Mohamed Bassem62a0642a050e
diff --git a/apps/web/components/admin/ResetPasswordDialog.tsx b/apps/web/components/admin/ResetPasswordDialog.tsx
index f195395a..c78c15e6 100644
--- a/apps/web/components/admin/ResetPasswordDialog.tsx
+++ b/apps/web/components/admin/ResetPasswordDialog.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import { ActionButton } from "@/components/ui/action-button";
import { Button } from "@/components/ui/button";
import {
@@ -8,7 +8,6 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
- DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
@@ -32,17 +31,20 @@ import { resetPasswordSchema } from "@karakeep/shared/types/admin";
interface ResetPasswordDialogProps {
userId: string;
- children?: React.ReactNode;
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ onCloseAutoFocus?: (e: Event) => void;
}
type ResetPasswordSchema = z.infer<typeof resetPasswordSchema>;
export default function ResetPasswordDialog({
- children,
userId,
+ open: isOpen,
+ setOpen: onOpenChange,
+ onCloseAutoFocus,
}: ResetPasswordDialogProps) {
const api = useTRPC();
- const [isOpen, onOpenChange] = useState(false);
const form = useForm<ResetPasswordSchema>({
resolver: zodResolver(resetPasswordSchema),
defaultValues: {
@@ -83,8 +85,7 @@ export default function ResetPasswordDialog({
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
- <DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent>
+ <DialogContent onCloseAutoFocus={onCloseAutoFocus}>
<DialogHeader>
<DialogTitle>Reset Password</DialogTitle>
</DialogHeader>
diff --git a/apps/web/components/admin/UpdateUserDialog.tsx b/apps/web/components/admin/UpdateUserDialog.tsx
index 95ccb6fd..233c1f32 100644
--- a/apps/web/components/admin/UpdateUserDialog.tsx
+++ b/apps/web/components/admin/UpdateUserDialog.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useState } from "react";
+import { useEffect } from "react";
import { ActionButton } from "@/components/ui/action-button";
import { Button } from "@/components/ui/button";
import {
@@ -8,7 +8,6 @@ import {
DialogFooter,
DialogHeader,
DialogTitle,
- DialogTrigger,
} from "@/components/ui/dialog";
import {
Form,
@@ -43,18 +42,21 @@ interface UpdateUserDialogProps {
currentRole: "user" | "admin";
currentQuota: number | null;
currentStorageQuota: number | null;
- children?: React.ReactNode;
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ onCloseAutoFocus?: (e: Event) => void;
}
export default function UpdateUserDialog({
userId,
currentRole,
currentQuota,
currentStorageQuota,
- children,
+ open: isOpen,
+ setOpen: onOpenChange,
+ onCloseAutoFocus,
}: UpdateUserDialogProps) {
const api = useTRPC();
const queryClient = useQueryClient();
- const [isOpen, onOpenChange] = useState(false);
const defaultValues = {
userId,
role: currentRole,
@@ -98,9 +100,7 @@ export default function UpdateUserDialog({
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
- <DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent>
- <DialogTrigger asChild></DialogTrigger>
+ <DialogContent onCloseAutoFocus={onCloseAutoFocus}>
<DialogHeader>
<DialogTitle>Edit User</DialogTitle>
</DialogHeader>
diff --git a/apps/web/components/admin/UserList.tsx b/apps/web/components/admin/UserList.tsx
index 1bdd9d52..e23179ee 100644
--- a/apps/web/components/admin/UserList.tsx
+++ b/apps/web/components/admin/UserList.tsx
@@ -1,5 +1,6 @@
"use client";
+import { memo, useCallback, useRef, useState } from "react";
import { ActionButton } from "@/components/ui/action-button";
import { ButtonWithTooltip } from "@/components/ui/button";
import { toast } from "@/components/ui/sonner";
@@ -18,9 +19,12 @@ import {
useQueryClient,
useSuspenseQuery,
} from "@tanstack/react-query";
+import { TFunction } from "i18next";
import { KeyRound, Pencil, Trash, UserPlus } from "lucide-react";
+import { z } from "zod";
import { useTRPC } from "@karakeep/shared-react/trpc";
+import { zAdminUserSchema } from "@karakeep/shared/types/admin";
import ActionConfirmingDialog from "../ui/action-confirming-dialog";
import AddUserDialog from "./AddUserDialog";
@@ -35,6 +39,78 @@ function toHumanReadableSize(size: number) {
return (size / Math.pow(1024, i)).toFixed(2) + " " + sizes[i];
}
+type AdminUser = z.infer<typeof zAdminUserSchema>;
+type UserDialog = "delete" | "resetPassword" | "edit";
+
+// Rows are memoized and don't own any dialogs/forms/mutations. With thousands
+// of users, mounting those per row makes the page extremely heavy.
+const UserRow = memo(function UserRow({
+ user: u,
+ stats,
+ isSelf,
+ t,
+ openDialog,
+}: {
+ user: AdminUser;
+ stats: { numBookmarks: number; assetSizes: number };
+ isSelf: boolean;
+ t: TFunction;
+ openDialog: (
+ dialog: UserDialog,
+ user: AdminUser,
+ trigger: HTMLElement,
+ ) => void;
+}) {
+ return (
+ <TableRow>
+ <TableCell className="py-1">{u.name}</TableCell>
+ <TableCell className="py-1">{u.email}</TableCell>
+ <TableCell className="py-1">
+ {stats.numBookmarks} /{" "}
+ {u.bookmarkQuota ?? t("admin.users_list.unlimited")}
+ </TableCell>
+ <TableCell className="py-1">
+ {toHumanReadableSize(stats.assetSizes)} /{" "}
+ {u.storageQuota
+ ? toHumanReadableSize(u.storageQuota)
+ : t("admin.users_list.unlimited")}
+ </TableCell>
+ <TableCell className="py-1">
+ {u.role && t(`common.roles.${u.role}`)}
+ </TableCell>
+ <TableCell className="flex gap-1 py-1">
+ <ButtonWithTooltip
+ tooltip={t("admin.users_list.delete_user")}
+ variant="outline"
+ disabled={isSelf}
+ aria-haspopup="dialog"
+ onClick={(e) => openDialog("delete", u, e.currentTarget)}
+ >
+ <Trash size={16} color="red" />
+ </ButtonWithTooltip>
+ <ButtonWithTooltip
+ tooltip={t("admin.users_list.reset_password")}
+ variant="outline"
+ disabled={isSelf}
+ aria-haspopup="dialog"
+ onClick={(e) => openDialog("resetPassword", u, e.currentTarget)}
+ >
+ <KeyRound size={16} color="red" />
+ </ButtonWithTooltip>
+ <ButtonWithTooltip
+ tooltip="Edit User"
+ variant="outline"
+ disabled={isSelf}
+ aria-haspopup="dialog"
+ onClick={(e) => openDialog("edit", u, e.currentTarget)}
+ >
+ <Pencil size={16} color="red" />
+ </ButtonWithTooltip>
+ </TableCell>
+ </TableRow>
+ );
+});
+
export default function UsersSection() {
const api = useTRPC();
const queryClient = useQueryClient();
@@ -46,6 +122,40 @@ export default function UsersSection() {
const { data: userStats } = useSuspenseQuery(
api.admin.userStats.queryOptions(),
);
+ // The selected user is kept around after the dialog closes so that the
+ // closing animation still has content to render.
+ const [selectedUser, setSelectedUser] = useState<AdminUser | null>(null);
+ const [activeDialog, setActiveDialog] = useState<{
+ type: UserDialog;
+ userId: string;
+ } | null>(null);
+ // The dialogs aren't rendered with a trigger, so focus has to be returned
+ // to the row button manually when they close.
+ const triggerRef = useRef<HTMLElement | null>(null);
+ const openDialog = useCallback(
+ (dialog: UserDialog, user: AdminUser, trigger: HTMLElement) => {
+ triggerRef.current = trigger;
+ setSelectedUser(user);
+ setActiveDialog({ type: dialog, userId: user.id });
+ },
+ [],
+ );
+ // Mutations can resolve after the admin moved on to another dialog, so only
+ // close the dialog if it's still the one this callback was created for.
+ const setDialogOpen =
+ (dialog: UserDialog, userId: string) => (open: boolean) =>
+ setActiveDialog((cur) =>
+ open
+ ? { type: dialog, userId }
+ : cur?.type === dialog && cur.userId === userId
+ ? null
+ : cur,
+ );
+ const restoreFocus = useCallback((e: Event) => {
+ e.preventDefault();
+ triggerRef.current?.focus();
+ }, []);
+
const { mutateAsync: deleteUser, isPending: isDeletionPending } = useMutation(
api.users.delete.mutationOptions({
onSuccess: () => {
@@ -88,81 +198,60 @@ export default function UsersSection() {
</TableHeader>
<TableBody>
{users.map((u) => (
- <TableRow key={u.id}>
- <TableCell className="py-1">{u.name}</TableCell>
- <TableCell className="py-1">{u.email}</TableCell>
- <TableCell className="py-1">
- {userStats[u.id].numBookmarks} /{" "}
- {u.bookmarkQuota ?? t("admin.users_list.unlimited")}
- </TableCell>
- <TableCell className="py-1">
- {toHumanReadableSize(userStats[u.id].assetSizes)} /{" "}
- {u.storageQuota
- ? toHumanReadableSize(u.storageQuota)
- : t("admin.users_list.unlimited")}
- </TableCell>
- <TableCell className="py-1">
- {u.role && t(`common.roles.${u.role}`)}
- </TableCell>
- <TableCell className="flex gap-1 py-1">
- <ActionConfirmingDialog
- title={t("admin.users_list.delete_user")}
- description={t(
- "admin.users_list.delete_user_confirm_description",
- {
- name: u.name ?? "this user",
- },
- )}
- actionButton={(setDialogOpen) => (
- <ActionButton
- variant="destructive"
- loading={isDeletionPending}
- onClick={async () => {
- await deleteUser({ userId: u.id });
- setDialogOpen(false);
- }}
- >
- Delete
- </ActionButton>
- )}
- >
- <ButtonWithTooltip
- tooltip={t("admin.users_list.delete_user")}
- variant="outline"
- disabled={session!.user.id == u.id}
- >
- <Trash size={16} color="red" />
- </ButtonWithTooltip>
- </ActionConfirmingDialog>
- <ResetPasswordDialog userId={u.id}>
- <ButtonWithTooltip
- tooltip={t("admin.users_list.reset_password")}
- variant="outline"
- disabled={session!.user.id == u.id}
- >
- <KeyRound size={16} color="red" />
- </ButtonWithTooltip>
- </ResetPasswordDialog>
- <UpdateUserDialog
- userId={u.id}
- currentRole={u.role!}
- currentQuota={u.bookmarkQuota}
- currentStorageQuota={u.storageQuota}
- >
- <ButtonWithTooltip
- tooltip="Edit User"
- variant="outline"
- disabled={session!.user.id == u.id}
- >
- <Pencil size={16} color="red" />
- </ButtonWithTooltip>
- </UpdateUserDialog>
- </TableCell>
- </TableRow>
+ <UserRow
+ key={u.id}
+ user={u}
+ stats={userStats[u.id]}
+ isSelf={session!.user.id == u.id}
+ t={t}
+ openDialog={openDialog}
+ />
))}
</TableBody>
</Table>
</div>
+ {selectedUser && (
+ <>
+ <ActionConfirmingDialog
+ open={activeDialog?.type === "delete"}
+ setOpen={setDialogOpen("delete", selectedUser.id)}
+ onCloseAutoFocus={restoreFocus}
+ title={t("admin.users_list.delete_user")}
+ description={t("admin.users_list.delete_user_confirm_description", {
+ name: selectedUser.name ?? "this user",
+ })}
+ actionButton={(setOpen) => (
+ <ActionButton
+ variant="destructive"
+ loading={isDeletionPending}
+ onClick={async () => {
+ await deleteUser({ userId: selectedUser.id });
+ setOpen(false);
+ }}
+ >
+ Delete
+ </ActionButton>
+ )}
+ />
+ <ResetPasswordDialog
+ key={`reset-${selectedUser.id}`}
+ userId={selectedUser.id}
+ open={activeDialog?.type === "resetPassword"}
+ setOpen={setDialogOpen("resetPassword", selectedUser.id)}
+ onCloseAutoFocus={restoreFocus}
+ />
+ <UpdateUserDialog
+ key={`edit-${selectedUser.id}`}
+ userId={selectedUser.id}
+ currentRole={selectedUser.role!}
+ currentQuota={selectedUser.bookmarkQuota}
+ currentStorageQuota={selectedUser.storageQuota}
+ open={activeDialog?.type === "edit"}
+ setOpen={setDialogOpen("edit", selectedUser.id)}
+ onCloseAutoFocus={restoreFocus}
+ />
+ </>
+ )}
</AdminCard>
);
}
diff --git a/apps/web/components/ui/action-confirming-dialog.tsx b/apps/web/components/ui/action-confirming-dialog.tsx
index e624d287..381820e7 100644
--- a/apps/web/components/ui/action-confirming-dialog.tsx
+++ b/apps/web/components/ui/action-confirming-dialog.tsx
@@ -17,6 +17,7 @@ export default function ActionConfirmingDialog({
description,
actionButton,
children,
+ onCloseAutoFocus,
open: userIsOpen,
setOpen: userSetOpen,
}: {
@@ -26,6 +27,7 @@ export default function ActionConfirmingDialog({
description: React.ReactNode;
actionButton: (setDialogOpen: (open: boolean) => void) => React.ReactNode;
children?: React.ReactNode;
+ onCloseAutoFocus?: (e: Event) => void;
}) {
const { t } = useTranslation();
const [customIsOpen, setCustomIsOpen] = useState(false);
@@ -36,7 +38,7 @@ export default function ActionConfirmingDialog({
return (
<Dialog open={isDialogOpen} onOpenChange={setDialogOpen}>
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
- <DialogContent>
+ <DialogContent onCloseAutoFocus={onCloseAutoFocus}>
<DialogHeader>
<DialogTitle>{title}</DialogTitle>
</DialogHeader>