Files
multica/packages/views/common/avatar-upload-control.tsx
Naiyuan Qing f4de0948a2 refactor(ui): unify ActorAvatar size tiers + round all avatars & cropper (MUL-4277, MUL-4184) (#5133)
* refactor(ui): converge ActorAvatar size to semantic tiers (MUL-4277)

Replace the free-form numeric `size` on ActorAvatar with a constrained
`AvatarSize` union (xs/sm/md/lg/xl/2xl) so avatar dimensions are chosen by
role instead of ad-hoc pixels. This eliminates the magic-number drift where
the same role rendered at different sizes across pages.

- Add `@multica/ui/lib/avatar-size` (AvatarSize union + AVATAR_SIZE_PX map +
  default tier).
- Base `ActorAvatar` (packages/ui) and business `ActorAvatar`/`AgentStatusDot`
  (packages/views) now take `AvatarSize`; internal font/icon math and the
  presence-dot threshold read px from the map.
- Migrate all web/desktop call sites (packages/ui + packages/views) from
  numeric sizes to tiers using the role table
  (12,14->xs 16,18,20->sm 22,24,28->md 30,32,34->lg 40,44->xl 56,64->2xl).
- Token-ise the derived consumers `AgentAvatarStack` and
  `IssueAgentActivityIndicator` (px looked up internally for overlap/+N math).

Out of scope (per plan): ui/avatar.tsx primitive, account-tab/AvatarPicker,
mobile, and component-name disambiguation.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(ui): unify all avatars and the upload cropper to round (MUL-4277, MUL-4184)

main's avatar-shape decision rendered non-human actors (agent, squad,
system) and the workspace logo as rounded squares, and the upload cropper
mirrored that with a square crop window. Per the updated decision
(avatars_and_cropper_round_required), every avatar and the crop UI are now
circular; the square path is removed rather than left as dead config.

- Base ActorAvatar: always rounded-full (drop the isHuman/rounded-md split).
- avatar-crop-dialog: remove the AvatarCropShape/square path; crop window is
  always cropShape="round".
- avatar-upload-control: drop VARIANT_SHAPE; the control is always round and
  no longer threads a shape to the dialog (variant still drives the fallback).
- Strip rounded-md/rounded-none square overrides from agent/squad/member
  ActorAvatar call sites; round the read-only agent/squad static wrappers.
- WorkspaceAvatar: round the org logo so it matches the (now round) workspace
  upload/crop and the shared avatar shape.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(ui): make round avatar shape a hard invariant (MUL-4277)

Close the two remaining square squad-avatar paths flagged in review and
prevent call sites from re-squaring the avatar:

- base ActorAvatar: keep `rounded-full` as the last class in cn() so a
  call-site `className` can no longer override the circle.
- SquadHeaderAvatar: drop `className="rounded"` (was overriding the base
  circle into a small rounded square).
- SquadsPage no-avatar fallback: route through the shared ActorAvatarBase
  (`isSquad size="lg"`) instead of a hand-written rounded-md tile, so the
  fallback matches the image path — one shape source of truth.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(views): round the agent/squad avatar loading skeletons (MUL-4277)

The avatar placeholder skeletons on the agent/squad list, detail, and
profile-card loading states were still rounded squares (rounded-md/lg) from
the pre-round era, so the avatar visibly popped from square to circle on
load — inconsistent with the round avatars and with the member/inbox/issue
skeletons that already use rounded-full.

Round all five: agents-page, agent-detail-page, squads-page,
squad-detail-page, squad-profile-card.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-07-10 08:31:40 +08:00

213 lines
6.4 KiB
TypeScript

"use client";
import { useRef, useState } from "react";
import { Bot, Camera, Loader2, Users, X } from "lucide-react";
import { toast } from "sonner";
import { api } from "@multica/core/api";
import { useFileUpload } from "@multica/core/hooks/use-file-upload";
import { resolvePublicFileUrl } from "@multica/core/workspace/avatar-url";
import { cn } from "@multica/ui/lib/utils";
import { useT } from "../i18n";
import { AvatarCropDialog } from "./avatar-crop-dialog";
export type AvatarUploadVariant = "user" | "agent" | "squad" | "workspace";
interface AvatarUploadControlProps {
/** Current avatar URL, raw (unresolved). `null` renders the empty state. */
value: string | null;
/** Drives the empty-state fallback icon/initials. */
variant: AvatarUploadVariant;
/** Name used for initials / first-letter fallback and the image alt. */
name?: string;
/** Pixel diameter of the circle. Defaults to 64. */
size?: number;
disabled?: boolean;
/**
* Fires with the uploaded file URL after a successful crop + upload. The
* parent persists it (updateMe / updateWorkspace / updateAgent /
* updateSquad, or stashing it for a create call). The crop dialog stays in
* its busy state until this resolves, then closes.
*/
onUploaded: (url: string) => void | Promise<unknown>;
/**
* When provided, shows a small clear affordance. Used by create flows to
* drop a not-yet-persisted choice; edit flows omit it (removing a saved
* avatar is out of scope).
*/
onClear?: () => void;
className?: string;
ariaLabel?: string;
}
function initialsOf(name: string): string {
return name
.split(" ")
.map((word) => word[0])
.join("")
.toUpperCase()
.slice(0, 2);
}
function AvatarFallback({
variant,
name,
size,
}: {
variant: AvatarUploadVariant;
name: string;
size: number;
}) {
if (variant === "agent") {
return <Bot style={{ width: size * 0.5, height: size * 0.5 }} />;
}
if (variant === "squad") {
return <Users style={{ width: size * 0.5, height: size * 0.5 }} />;
}
const text =
variant === "workspace"
? name.charAt(0).toUpperCase()
: initialsOf(name);
return (
<span className="font-semibold" style={{ fontSize: size * 0.4 }}>
{text}
</span>
);
}
/**
* Shared click-to-upload avatar control for web/desktop. Renders the current
* avatar with a hover "change" affordance; on pick it opens {@link
* AvatarCropDialog} for reposition/zoom, then uploads the cropped image
* through the existing `/api/upload-file` chain and hands the URL back via
* `onUploaded`. Business persistence stays with the caller.
*/
export function AvatarUploadControl({
value,
variant,
name = "",
size = 64,
disabled = false,
onUploaded,
onClear,
className,
ariaLabel,
}: AvatarUploadControlProps) {
const { t } = useT("common");
const { upload } = useFileUpload(api);
const fileInputRef = useRef<HTMLInputElement>(null);
const [pickedFile, setPickedFile] = useState<File | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [previewError, setPreviewError] = useState(false);
const resolved = value ? resolvePublicFileUrl(value) : null;
const hasImage = !!resolved && !previewError;
const handlePick = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
e.target.value = ""; // allow re-selecting the same file
if (!file) return;
if (!file.type.startsWith("image/")) {
toast.error(t(($) => $.avatar_upload.select_image));
return;
}
setPreviewError(false);
setPickedFile(file);
setDialogOpen(true);
};
const handleCropped = async (cropped: File) => {
setBusy(true);
try {
const result = await upload(cropped);
if (!result) return;
await onUploaded(result.link);
setDialogOpen(false);
setPickedFile(null);
toast.success(t(($) => $.avatar_upload.updated));
} catch (err) {
toast.error(
err instanceof Error ? err.message : t(($) => $.avatar_upload.failed),
);
} finally {
setBusy(false);
}
};
return (
<div className="relative shrink-0" style={{ width: size, height: size }}>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={disabled || busy}
aria-label={ariaLabel ?? t(($) => $.avatar_upload.change)}
className={cn(
"group relative h-full w-full overflow-hidden bg-muted text-muted-foreground outline-none",
"flex items-center justify-center",
"focus-visible:ring-2 focus-visible:ring-ring",
"disabled:cursor-not-allowed disabled:opacity-60",
"rounded-full",
className,
)}
style={{ width: size, height: size }}
>
{hasImage ? (
<img
src={resolved ?? undefined}
alt={name}
className="h-full w-full object-cover"
onError={() => setPreviewError(true)}
/>
) : (
<AvatarFallback variant={variant} name={name} size={size} />
)}
{!disabled && (
<div className="absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 transition-opacity group-hover:opacity-100">
{busy ? (
<Loader2 className="h-5 w-5 animate-spin text-white" />
) : (
<Camera className="h-5 w-5 text-white" />
)}
</div>
)}
</button>
{onClear && hasImage && !busy && !disabled && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
setPreviewError(false);
onClear();
}}
className="absolute -right-1.5 -top-1.5 flex h-5 w-5 items-center justify-center rounded-full border bg-background text-muted-foreground shadow-sm transition-colors hover:bg-muted hover:text-foreground"
aria-label={t(($) => $.avatar_upload.remove)}
>
<X className="h-3 w-3" />
</button>
)}
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={handlePick}
/>
<AvatarCropDialog
file={pickedFile}
open={dialogOpen}
busy={busy}
onOpenChange={(next) => {
if (busy) return;
setDialogOpen(next);
if (!next) setPickedFile(null);
}}
onCropped={handleCropped}
/>
</div>
);
}