Skip to content

Open source CapCut alternative.

TypeScript

feat(site): open a profile from the Cut account menu

David Lefc2b094cf40e
diff --git a/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx b/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx
index 5165299c..6f534f1f 100644
--- a/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx
+++ b/site/src/app/cut/app/(home)/settings/SettingsHeader.tsx
@@ -20,6 +20,11 @@ const SECTIONS = [
description: "Early features you can turn on for your account.",
pinned: true,
},
+ {
+ suffix: "/settings/profile",
+ title: "Profile",
+ pinned: true,
+ },
{
suffix: "/settings",
title: "Billing",
@@ -40,7 +45,9 @@ export function SettingsHeader() {
)}
>
<h1 className="text-lg font-semibold tracking-tight">{section.title}</h1>
- <p className="mt-1 text-sm text-muted-foreground">{section.description}</p>
+ {section.description && (
+ <p className="mt-1 text-sm text-muted-foreground">{section.description}</p>
+ )}
</div>
);
}
diff --git a/site/src/app/cut/app/(home)/settings/profile/AvatarDialog.tsx b/site/src/app/cut/app/(home)/settings/profile/AvatarDialog.tsx
new file mode 100644
index 00000000..86462a7d
--- /dev/null
+++ b/site/src/app/cut/app/(home)/settings/profile/AvatarDialog.tsx
@@ -0,0 +1,283 @@
+"use client";
+
+import {
+ useCallback,
+ useRef,
+ useState,
+ type PointerEvent as ReactPointerEvent,
+} from "react";
+import { ImageUp } from "lucide-react";
+
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Slider } from "@/components/ui/slider";
+import { useRemoveAvatar, useUpdateAvatar } from "@/queries/accountProfile";
+
+// The square that gets stored. Avatars are only ever drawn small, so 256px is
+// generous and keeps the encoded file tiny. The frame on screen is measured
+// instead — it spans the dialog — and the crop math runs in its pixels.
+const OUTPUT = 256;
+// Zoom 1 is "cover": the picture exactly fills the frame. Below that it shrinks
+// inside the frame, which is how a logo or a full photo gets to sit whole in
+// the avatar, with the rest of the square left transparent.
+const MIN_ZOOM = 0.2;
+const MAX_ZOOM = 3;
+// WebP at this quality lands a 256px square around 15KB, well under the
+// route's cap, and every browser that runs the editor can encode it.
+const OUTPUT_TYPE = "image/webp";
+const OUTPUT_QUALITY = 0.85;
+
+type Picked = { url: string; width: number; height: number };
+
+// Pick a picture, then frame it: drag to move, slide to zoom. The crop is
+// applied for real on save — the stored square is exactly what the box shows —
+// so nothing downstream has to know how it was positioned.
+export function AvatarDialog({
+ open,
+ onOpenChange,
+ hasCustomImage,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ hasCustomImage: boolean;
+}) {
+ const fileInput = useRef<HTMLInputElement>(null);
+ const [picked, setPicked] = useState<Picked | null>(null);
+ const [zoom, setZoom] = useState(1);
+ const [offset, setOffset] = useState({ x: 0, y: 0 });
+ const [error, setError] = useState<string | null>(null);
+ const drag = useRef<{ x: number; y: number } | null>(null);
+ // The frame spans the dialog, so its size comes from layout rather than a
+ // constant. offsetWidth, not a rect: the dialog opens on a scale animation,
+ // and a measured rect would come back mid-zoom.
+ const [frame, setFrame] = useState(320);
+ const frameRef = useCallback((el: HTMLDivElement | null) => {
+ if (el) setFrame(el.offsetWidth);
+ }, []);
+
+ const update = useUpdateAvatar();
+ const remove = useRemoveAvatar();
+ const busy = update.isPending || remove.isPending;
+
+ const close = () => {
+ if (picked) URL.revokeObjectURL(picked.url);
+ setPicked(null);
+ setZoom(1);
+ setOffset({ x: 0, y: 0 });
+ setError(null);
+ onOpenChange(false);
+ };
+
+ const pick = (file: File | undefined) => {
+ if (!file) return;
+ setError(null);
+ const url = URL.createObjectURL(file);
+ const img = new Image();
+ img.onload = () => {
+ if (picked) URL.revokeObjectURL(picked.url);
+ setPicked({ height: img.naturalHeight, url, width: img.naturalWidth });
+ setZoom(1);
+ setOffset({ x: 0, y: 0 });
+ };
+ img.onerror = () => {
+ URL.revokeObjectURL(url);
+ setError("That file isn't an image we can read.");
+ };
+ img.src = url;
+ };
+
+ // Scale that makes the picture cover the frame at zoom 1.
+ const cover = picked ? frame / Math.min(picked.width, picked.height) : 1;
+ const scale = cover * zoom;
+ const drawn = picked
+ ? { height: picked.height * scale, width: picked.width * scale }
+ : { height: 0, width: 0 };
+ // How far the picture may travel: overhang while it's larger than the frame,
+ // the leftover room while it's smaller — either way it can't leave the frame.
+ const limit = {
+ x: Math.abs(drawn.width - frame) / 2,
+ y: Math.abs(drawn.height - frame) / 2,
+ };
+ const clamp = (value: number, max: number) => Math.min(max, Math.max(-max, value));
+ const position = {
+ left: (frame - drawn.width) / 2 + clamp(offset.x, limit.x),
+ top: (frame - drawn.height) / 2 + clamp(offset.y, limit.y),
+ };
+
+ // Zooming out shrinks how far the picture can travel, so the stored offset
+ // comes back inside the new limits with it — otherwise the next drag starts
+ // from a position the frame is no longer showing.
+ const applyZoom = (next: number) => {
+ setZoom(next);
+ if (!picked) return;
+ const nextScale = cover * next;
+ setOffset((cur) => ({
+ x: clamp(cur.x, Math.abs(picked.width * nextScale - frame) / 2),
+ y: clamp(cur.y, Math.abs(picked.height * nextScale - frame) / 2),
+ }));
+ };
+
+ const onPointerDown = (e: ReactPointerEvent<HTMLDivElement>) => {
+ if (!picked) return;
+ drag.current = { x: e.clientX - offset.x, y: e.clientY - offset.y };
+ e.currentTarget.setPointerCapture(e.pointerId);
+ };
+ const onPointerMove = (e: ReactPointerEvent<HTMLDivElement>) => {
+ const start = drag.current;
+ if (!start) return;
+ setOffset({
+ x: clamp(e.clientX - start.x, limit.x),
+ y: clamp(e.clientY - start.y, limit.y),
+ });
+ };
+ const onPointerUp = (e: ReactPointerEvent<HTMLDivElement>) => {
+ drag.current = null;
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ };
+
+ const save = async () => {
+ if (!picked) return;
+ setError(null);
+
+ // The frame window, mapped back onto the source pixels it is showing. Once
+ // zoomed out past cover the window runs off the picture; canvas clips the
+ // overhang on both rectangles, so those edges come out transparent.
+ const source = {
+ height: frame / scale,
+ width: frame / scale,
+ x: -position.left / scale,
+ y: -position.top / scale,
+ };
+ const canvas = document.createElement("canvas");
+ canvas.width = OUTPUT;
+ canvas.height = OUTPUT;
+ const ctx = canvas.getContext("2d");
+ const image = new Image();
+ image.src = picked.url;
+ await image.decode();
+ if (!ctx) {
+ setError("Couldn't prepare that image — try again.");
+ return;
+ }
+ ctx.drawImage(
+ image,
+ source.x,
+ source.y,
+ source.width,
+ source.height,
+ 0,
+ 0,
+ OUTPUT,
+ OUTPUT,
+ );
+
+ const blob = await new Promise<Blob | null>((resolve) => {
+ canvas.toBlob(resolve, OUTPUT_TYPE, OUTPUT_QUALITY);
+ });
+ if (!blob) {
+ setError("Couldn't prepare that image — try again.");
+ return;
+ }
+ update.mutate(blob, {
+ onError: () => setError("Couldn't save that picture — try again."),
+ onSuccess: close,
+ });
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(next) => (next ? onOpenChange(true) : close())}>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Profile picture</DialogTitle>
+ </DialogHeader>
+
+ <div className="flex flex-col items-center gap-4">
+ <div
+ ref={frameRef}
+ className="relative aspect-square w-full overflow-hidden rounded-xl bg-muted"
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={onPointerUp}
+ onPointerCancel={onPointerUp}
+ >
+ {picked ? (
+ <img
+ src={picked.url}
+ alt=""
+ draggable={false}
+ className="absolute max-w-none cursor-grab select-none active:cursor-grabbing"
+ style={{
+ height: drawn.height,
+ left: position.left,
+ top: position.top,
+ width: drawn.width,
+ }}
+ />
+ ) : (
+ <button
+ type="button"
+ onClick={() => fileInput.current?.click()}
+ className="flex size-full cursor-pointer flex-col items-center justify-center gap-2 text-sm text-muted-foreground"
+ >
+ <ImageUp className="size-6" />
+ Choose an image
+ </button>
+ )}
+ </div>
+
+ {picked && (
+ <div className="flex w-full items-center gap-3">
+ <span className="text-sm text-muted-foreground">Zoom</span>
+ <Slider
+ aria-label="Zoom"
+ min={MIN_ZOOM}
+ max={MAX_ZOOM}
+ step={0.01}
+ value={zoom}
+ onValueChange={(value) => applyZoom(Array.isArray(value) ? value[0] : value)}
+ />
+ </div>
+ )}
+
+ <input
+ ref={fileInput}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ onChange={(e) => {
+ pick(e.target.files?.[0]);
+ e.target.value = "";
+ }}
+ />
+ {error && <p className="text-sm text-red-600">{error}</p>}
+ </div>
+
+ <DialogFooter className="sm:justify-between">
+ <div className="flex gap-2">
+ <Button variant="outline" onClick={() => fileInput.current?.click()}>
+ {picked ? "Replace" : "Choose"}
+ </Button>
+ {hasCustomImage && !picked && (
+ <Button
+ variant="outline"
+ disabled={busy}
+ onClick={() => remove.mutate(undefined, { onSuccess: close })}
+ >
+ Remove
+ </Button>
+ )}
+ </div>
+ <Button disabled={!picked || busy} onClick={() => void save()}>
+ Save
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/site/src/app/cut/app/(home)/settings/profile/page.tsx b/site/src/app/cut/app/(home)/settings/profile/page.tsx
new file mode 100644
index 00000000..ee29df0b
--- /dev/null
+++ b/site/src/app/cut/app/(home)/settings/profile/page.tsx
@@ -0,0 +1,107 @@
+"use client";
+
+import { useState } from "react";
+import { Pencil } from "lucide-react";
+
+import { AvatarDialog } from "@/app/cut/app/(home)/settings/profile/AvatarDialog";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { UserAvatar } from "@/cut/components/UserAvatar";
+import {
+ useAccountProfile,
+ useUpdateDisplayName,
+ visibleName,
+} from "@/queries/accountProfile";
+
+// The account's own page: who you're signed in as, and the one thing about it
+// you can change. The display name is the product's; the Google account keeps
+// the name and email it signed in with.
+export default function CutProfilePage() {
+ const { data: profile, isPending, isError } = useAccountProfile();
+ const update = useUpdateDisplayName();
+ // Null means "not edited yet", so the field follows the saved value until
+ // the user types and again once a save lands.
+ const [draft, setDraft] = useState<string | null>(null);
+ const [editingAvatar, setEditingAvatar] = useState(false);
+
+ if (isPending) {
+ return <p className="text-sm text-muted-foreground">Loading…</p>;
+ }
+ if (isError || !profile) {
+ return <p className="text-sm text-red-600">Couldn&apos;t load your profile.</p>;
+ }
+
+ const value = draft ?? profile.displayName ?? "";
+ const dirty = value.trim() !== (profile.displayName ?? "");
+
+ const save = () => {
+ update.mutate(value.trim() || null, { onSuccess: () => setDraft(null) });
+ };
+
+ return (
+ <div className="max-w-2xl space-y-6 pb-9">
+ <div className="rounded-xl border bg-card p-5">
+ <div className="flex items-center gap-3">
+ {/* The picture is the way into its own editor — pick, frame, save. */}
+ <button
+ type="button"
+ aria-label="Change profile picture"
+ onClick={() => setEditingAvatar(true)}
+ className="group relative cursor-pointer rounded-lg"
+ >
+ <UserAvatar
+ name={visibleName(profile, profile.name)}
+ image={profile.image}
+ className="size-[3.6rem]"
+ initialClassName="text-lg"
+ />
+ <span className="absolute inset-0 rounded-lg bg-black/40 opacity-0 transition-opacity group-hover:opacity-100" />
+ {/* Pinned to the corner rather than shown on hover, so the picture
+ reads as editable before anyone points at it. */}
+ <span className="absolute -right-1 -bottom-1 grid size-5 place-items-center rounded-full bg-background text-muted-foreground ring-1 ring-border">
+ <Pencil className="size-3" />
+ </span>
+ </button>
+ <div className="min-w-0">
+ <div className="truncate text-sm font-medium">
+ {visibleName(profile, profile.name)}
+ </div>
+ <div className="truncate text-sm text-muted-foreground">{profile.email}</div>
+ </div>
+ </div>
+
+ <div className="mt-5 border-t pt-5">
+ <Label htmlFor="display-name">Display name</Label>
+ <div className="mt-3 flex items-center gap-2">
+ <Input
+ id="display-name"
+ className="max-w-xs"
+ maxLength={60}
+ placeholder={profile.name}
+ value={value}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && dirty) save();
+ }}
+ />
+ <Button disabled={!dirty || update.isPending} onClick={save}>
+ Save
+ </Button>
+ </div>
+ {update.isError && (
+ <p className="mt-2 text-sm text-red-600">
+ Couldn&apos;t save that name — try again.
+ </p>
+ )}
+ </div>
+ </div>
+
+ <AvatarDialog
+ open={editingAvatar}
+ onOpenChange={setEditingAvatar}
+ hasCustomImage={profile.image?.startsWith("/api/account/avatar") === true}
+ />
+ </div>
+ );
+}
diff --git a/site/src/components/ui/avatar.tsx b/site/src/components/ui/avatar.tsx
new file mode 100644
index 00000000..9f3ad25d
--- /dev/null
+++ b/site/src/components/ui/avatar.tsx
@@ -0,0 +1,41 @@
+import { Avatar as AvatarPrimitive } from "@base-ui/react/avatar"
+
+import { cn } from "@/lib/utils"
+
+function Avatar({ className, ...props }: AvatarPrimitive.Root.Props) {
+ return (
+ <AvatarPrimitive.Root
+ data-slot="avatar"
+ className={cn(
+ "relative flex size-8 shrink-0 overflow-hidden rounded-lg select-none",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+function AvatarImage({ className, ...props }: AvatarPrimitive.Image.Props) {
+ return (
+ <AvatarPrimitive.Image
+ data-slot="avatar-image"
+ className={cn("size-full object-cover", className)}
+ {...props}
+ />
+ )
+}
+
+function AvatarFallback({ className, ...props }: AvatarPrimitive.Fallback.Props) {
+ return (
+ <AvatarPrimitive.Fallback
+ data-slot="avatar-fallback"
+ className={cn(
+ "flex size-full items-center justify-center rounded-[inherit] bg-muted text-sm font-semibold text-muted-foreground",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+
+export { Avatar, AvatarFallback, AvatarImage }
diff --git a/site/src/cut/components/NavUser.tsx b/site/src/cut/components/NavUser.tsx
index b2ee300e..843f6721 100644
--- a/site/src/cut/components/NavUser.tsx
+++ b/site/src/cut/components/NavUser.tsx
@@ -3,6 +3,7 @@
import { useRouter } from "next/navigation";
import {
ChartColumn,
+ ChevronRight,
CreditCard,
EllipsisVertical,
Flag,
@@ -14,24 +15,14 @@ import {
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuItem,
- DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
+import { UserAvatar } from "@/cut/components/UserAvatar";
import { cutInstallHref } from "@/cut/lib/install";
import { useCutBase } from "@/cut/lib/nav";
import { authClient } from "@/lib/auth-client";
-
-function Avatar({ name, image }: { name: string; image: string | null | undefined }) {
- if (image) {
- return <img src={image} alt="" className="size-8 shrink-0 rounded-lg object-cover" />;
- }
- return (
- <span className="grid size-8 shrink-0 place-items-center rounded-lg bg-muted text-sm font-semibold text-muted-foreground">
- {(name.trim()[0] ?? "?").toUpperCase()}
- </span>
- );
-}
+import { useAccountProfile, visibleName } from "@/queries/accountProfile";
// Signed-in user row pinned to the sidebar bottom; the whole row opens the
// account menu. Hidden while signed out — the editor itself needs no account,
@@ -40,9 +31,14 @@ export function NavUser() {
const router = useRouter();
const base = useCutBase();
const { data: session } = authClient.useSession();
+ // Mounted above the session check so the hook order is stable; it stays idle
+ // until there's a session to read a profile for.
+ const { data: profile } = useAccountProfile({ enabled: Boolean(session) });
if (!session) return null;
- const { name, email, image } = session.user;
+ // The name the user chose wins over the one the provider gave us.
+ const name = visibleName(profile, session.user.name);
+ const image = profile?.image ?? session.user.image;
const root = base.replace(/\/app$/, "");
const signOut = () => {
@@ -62,24 +58,23 @@ export function NavUser() {
return (
<DropdownMenu>
- <DropdownMenuTrigger className="mt-auto flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-muted data-[popup-open]:bg-muted">
- <Avatar name={name} image={image} />
- <span className="min-w-0 flex-1 leading-tight">
- <span className="block truncate text-sm font-medium">{name}</span>
- <span className="block truncate text-xs text-muted-foreground">{email}</span>
- </span>
+ <DropdownMenuTrigger className="flex w-full items-center gap-2.5 rounded-lg px-2 py-1.5 text-left transition-colors hover:bg-muted data-[popup-open]:bg-muted">
+ <UserAvatar name={name} image={image} />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{name}</span>
<EllipsisVertical className="size-4 shrink-0 text-muted-foreground" />
</DropdownMenuTrigger>
<DropdownMenuContent side="top" align="start" className="w-56">
- {/* GroupLabel must live inside a Group in this menu kit. */}
+ {/* The identity row is the way into the profile, where the account's
+ details live and the display name is edited. */}
<DropdownMenuGroup>
- <DropdownMenuLabel className="flex items-center gap-2.5 font-normal">
- <Avatar name={name} image={image} />
- <span className="min-w-0 flex-1 leading-tight">
- <span className="block truncate text-sm font-medium">{name}</span>
- <span className="block truncate text-xs text-muted-foreground">{email}</span>
- </span>
- </DropdownMenuLabel>
+ <DropdownMenuItem
+ className="gap-2.5 py-2"
+ onClick={() => router.push(`${base}/settings/profile`)}
+ >
+ <UserAvatar name={name} image={image} />
+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{name}</span>
+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" />
+ </DropdownMenuItem>
</DropdownMenuGroup>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => router.push(`${base}/settings`)}>
diff --git a/site/src/cut/components/UserAvatar.tsx b/site/src/cut/components/UserAvatar.tsx
new file mode 100644
index 00000000..17e3609c
--- /dev/null
+++ b/site/src/cut/components/UserAvatar.tsx
@@ -0,0 +1,29 @@
+import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
+import { cn } from "@/lib/utils";
+
+// The signed-in user's picture, or the first letter of the name they go by.
+//
+// Provider avatars are hotlinked from the identity provider, so they fail for
+// reasons this app can't fix — an expired URL, a provider that turns away
+// requests carrying our referrer, an offline machine. The initial stands in
+// whenever the image doesn't arrive, so a row never shows a broken icon.
+export function UserAvatar({
+ name,
+ image,
+ className,
+ initialClassName,
+}: {
+ name: string;
+ image?: string | null;
+ className?: string;
+ initialClassName?: string;
+}) {
+ return (
+ <Avatar className={className}>
+ {image && <AvatarImage src={image} alt="" referrerPolicy="no-referrer" />}
+ <AvatarFallback className={cn(initialClassName)}>
+ {(name.trim()[0] ?? "?").toUpperCase()}
+ </AvatarFallback>
+ </Avatar>
+ );
+}