feat(user-avatar): add support for uploading, cropping, and displaying user avatars

This commit is contained in:
yiling
2026-06-03 19:56:07 +08:00
parent ee2a7d3281
commit e65b3edbee
19 changed files with 638 additions and 54 deletions
+25 -22
View File
@@ -2,6 +2,7 @@ import { Hono } from 'hono'
import { zValidator } from '@hono/zod-validator'
import { agentService } from '@shumai/core/src/agent/agent'
import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz'
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import {
createAgentRequestSchema,
updateAgentRequestSchema,
@@ -27,26 +28,28 @@ const route = new Hono<{ Variables: { user: User } }>()
const agents = await agentService.listAgents({ teamId })
const res: AgentInfo[] = agents.map((agent) => {
const config = agent.config as unknown as PrismaJson.AgentConfig
return {
id: agent.id,
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: agent.user.image || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({
id: s.id,
skillId: s.skillId,
skill: s.skill,
})),
}
})
const res: AgentInfo[] = await Promise.all(
agents.map(async (agent) => {
const config = agent.config as unknown as PrismaJson.AgentConfig
return {
id: agent.id,
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
systemPrompt: config.systemPrompt,
soul: agent.soul || undefined,
skills: agent.skills.map((s) => ({
id: s.id,
skillId: s.skillId,
skill: s.skill,
})),
}
}),
)
return c.json(res, 200)
})
@@ -75,7 +78,7 @@ const route = new Hono<{ Variables: { user: User } }>()
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: agent.user.image || undefined,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
@@ -113,7 +116,7 @@ const route = new Hono<{ Variables: { user: User } }>()
name: agent.user.name,
type: agent.type as AgentType,
enabled: agent.enabled,
avatar: agent.user.image || undefined,
avatar: (await getAvatarUrl(agent.user.image)) || undefined,
providerId: agent.providerId || undefined,
modelId: agent.modelId || undefined,
thinkingLevel: config.thinkingLevel || '',
+27
View File
@@ -43,6 +43,7 @@ describe('team api', () => {
let mockCreateNotification: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockGetSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateSandboxSettings: any // eslint-disable-line @typescript-eslint/no-explicit-any
let mockUpdateMe: any // eslint-disable-line @typescript-eslint/no-explicit-any
beforeEach(() => {
mockCreateTeam = vi.spyOn(teamService, 'createTeam')
@@ -57,6 +58,7 @@ describe('team api', () => {
mockCreateNotification = vi.spyOn(notificationService, 'create').mockResolvedValue()
mockGetSandboxSettings = vi.spyOn(teamService, 'getSandboxSettings')
mockUpdateSandboxSettings = vi.spyOn(teamService, 'updateSandboxSettings')
mockUpdateMe = vi.spyOn(teamService, 'updateMe')
vi.mocked(authzService.hasPermission).mockResolvedValue(undefined)
})
@@ -133,6 +135,31 @@ describe('team api', () => {
expect(mockGetMe).toHaveBeenCalledWith({ teamId: 't1', user: expect.any(Object) })
})
it('PATCH /teams/:teamId/me updates user info', async () => {
mockUpdateMe.mockResolvedValue(undefined)
const res = await app.request('/teams/t1/me', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'New Name', imageKey: 'avatar-s3-key' }),
})
expect(res.status).toBe(200)
const data = await res.json()
expect(data.success).toBe(true)
expect(authzService.hasPermission).toHaveBeenCalledWith(
expect.objectContaining({
type: ResourceType.Team,
id: 't1',
permission: Permission.Read,
}),
)
expect(mockUpdateMe).toHaveBeenCalledWith('user1', {
name: 'New Name',
imageKey: 'avatar-s3-key',
})
})
it('GET /teams/:teamId/members returns members', async () => {
mockGetTeamMembers.mockResolvedValue([{ id: 'user1', name: 'Test User', role: 'owner' }])
+16
View File
@@ -11,6 +11,7 @@ import {
updateTeamSettingsRequestSchema,
listMembersQuerySchema,
updateSandboxSettingsRequestSchema,
updateMeRequestSchema,
} from '@shumai/dtos'
import { updateUserMetadataRequestSchema } from '@shumai/dtos'
import type { Prisma } from '@shumai/db'
@@ -77,6 +78,21 @@ const route = new Hono<{ Variables: { user: User } }>()
return c.json(me)
})
.patch('/teams/:teamId/me', zValidator('json', updateMeRequestSchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
const req = c.req.valid('json')
await authzService.hasPermission({
user,
permission: Permission.Read,
type: ResourceType.Team,
id: teamId,
})
await teamService.updateMe(user.id, req)
return c.json({ success: true })
})
.get('/teams/:teamId/members', zValidator('query', listMembersQuerySchema), async (c) => {
const user = c.get('user')
const teamId = c.req.param('teamId')
+27 -4
View File
@@ -22,6 +22,7 @@ import { logger } from '@shumai/core/src/logger'
import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination'
import { s3Service } from '@shumai/core/src/s3/s3'
import { generateKeyBetween } from 'jittered-fractional-indexing'
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
type AssetWithIncludes = Prisma.AssetGetPayload<{
include: {
@@ -1459,7 +1460,13 @@ export class AssetService {
id: v.id,
name: v.name,
previewUrl: preview?.thumbnailUrl || null,
creator: v.creator ? { id: v.creator.id, name: v.creator.name } : null,
creator: v.creator
? {
id: v.creator.id,
name: v.creator.name,
image: await getAvatarUrl(v.creator.image),
}
: null,
}
}),
),
@@ -1504,7 +1511,11 @@ export class AssetService {
const preview = await this.toPreviewInfo(latestVersion as Asset)
const creator = latestVersion.creator
? { id: latestVersion.creator.id, name: latestVersion.creator.name }
? {
id: latestVersion.creator.id,
name: latestVersion.creator.name,
image: await getAvatarUrl(latestVersion.creator.image),
}
: null
const fieldValues: FieldValueInfo[] = []
@@ -1599,7 +1610,13 @@ export class AssetService {
version: versions.length - i,
name: v.name,
previewUrl: preview?.thumbnailUrl || null,
creator: v.creator ? { id: v.creator.id, name: v.creator.name } : null,
creator: v.creator
? {
id: v.creator.id,
name: v.creator.name,
image: await getAvatarUrl(v.creator.image),
}
: null,
}
}),
)
@@ -1678,7 +1695,11 @@ export class AssetService {
where: { id: { in: userIds } },
})
for (const u of users) {
mentions.push({ id: u.id, name: u.name })
mentions.push({
id: u.id,
name: u.name,
image: await getAvatarUrl(u.image),
})
}
}
@@ -1686,9 +1707,11 @@ export class AssetService {
if (c.sessionId) {
creator.id = c.creatorId || ''
creator.name = c.creator?.name || 'Ai Bot'
creator.image = await getAvatarUrl(c.creator?.image)
} else if (c.creator) {
creator.id = c.creator.id
creator.name = c.creator.name
creator.image = await getAvatarUrl(c.creator.image)
}
return {
+1
View File
@@ -15,6 +15,7 @@ export * from './skill/skill'
export * from './team/team'
export * from './upload/upload'
export * from './user-metadata/user-metadata'
export * from './user/avatar'
export * from './versionStack/versionStack'
export * from './hyrumtoken'
export * from './pagination'
+11 -7
View File
@@ -2,6 +2,7 @@ import { prisma } from '@shumai/db'
import { Prisma } from '@shumai/db'
import { s3Service } from '@shumai/core/src/s3/s3'
import { paginateQuery, PaginatedData } from '@shumai/core/src/pagination'
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import {
ServiceCreateProjectRequest,
ServiceUpdateProjectRequest,
@@ -215,13 +216,16 @@ export class ProjectService {
},
})
return members
.filter((pm) => pm.teamMember && pm.teamMember.user)
.map((pm) => ({
id: pm.teamMember.user.id,
name: pm.teamMember.user.name,
role: pm.role,
}))
return Promise.all(
members
.filter((pm) => pm.teamMember && pm.teamMember.user)
.map(async (pm) => ({
id: pm.teamMember.user.id,
name: pm.teamMember.user.name,
role: pm.role,
image: await getAvatarUrl(pm.teamMember.user.image),
})),
)
}
async deleteProject(projectId: string): Promise<void> {
+16
View File
@@ -92,6 +92,22 @@ describe('TeamService', () => {
expect(me.role).toBe('owner')
})
it('should update me', async () => {
const user = await prisma.user.create({
data: { name: 'Old Name', email: `test-${Date.now()}@example.com`, password: 'pw' },
})
await teamService.updateMe(user.id, {
name: 'New Name',
imageKey: 'avatar-s3-key',
})
const updatedUser = await prisma.user.findUnique({
where: { id: user.id },
})
expect(updatedUser?.name).toBe('New Name')
expect(updatedUser?.image).toBe('avatar-s3-key')
})
it('should get team members', async () => {
const user1 = await prisma.user.create({
data: { name: 'Test User 1', email: `test1-${Date.now()}@example.com`, password: 'pw' },
+30 -10
View File
@@ -3,6 +3,7 @@ import { Prisma } from '@shumai/db'
import { PaginatedData, paginateQuery } from '@shumai/core/src/pagination'
import { ProviderService, providerService } from '@shumai/core/src/provider/provider'
import { notificationService } from '@shumai/core/src/notification/notification'
import { getAvatarUrl } from '@shumai/core/src/user/avatar'
import {
ServiceCreateTeamRequest,
ServiceGetUserTeamsRequest,
@@ -136,6 +137,7 @@ export class TeamService {
userId: req.user.id,
},
},
include: { user: true },
})
if (!member) throw new Error('user is not a team member')
@@ -146,14 +148,29 @@ export class TeamService {
)
return {
id: req.user.id,
name: req.user.name,
email: undefined,
id: member.user.id,
name: member.user.name,
email: member.user.email || undefined,
role: member.role,
image: await getAvatarUrl(member.user.image),
unreadNotificationCount,
}
}
async updateMe(userId: string, req: { name?: string; imageKey?: string | null }): Promise<void> {
const data: Prisma.UserUpdateInput = {}
if (req.name !== undefined) {
data.name = req.name
}
if (req.imageKey !== undefined) {
data.image = req.imageKey
}
await prisma.user.update({
where: { id: userId },
data,
})
}
async getTeamMembers(req: ServiceGetTeamMembersRequest): Promise<UserInfo[]> {
const members = await prisma.teamMember.findMany({
where: {
@@ -178,13 +195,16 @@ export class TeamService {
include: { user: true },
})
return members.map((m) => ({
id: m.user.id,
name: m.user.name,
email: undefined,
role: m.role,
type: m.user.type || undefined,
}))
return Promise.all(
members.map(async (m) => ({
id: m.user.id,
name: m.user.name,
email: undefined,
role: m.role,
type: m.user.type || undefined,
image: await getAvatarUrl(m.user.image),
})),
)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
+21
View File
@@ -0,0 +1,21 @@
import { s3Service } from '@shumai/core/src/s3/s3'
/**
* Returns the signed avatar URL if the image is an S3 key,
* or returns it directly if it's already an external URL (e.g. OAuth avatar).
*/
export async function getAvatarUrl(
imageKeyOrUrl: string | null | undefined,
): Promise<string | undefined> {
if (!imageKeyOrUrl) return undefined
if (imageKeyOrUrl.startsWith('http://') || imageKeyOrUrl.startsWith('https://')) {
return imageKeyOrUrl
}
try {
const bucket = process.env.S3_BUCKET || 'shumai'
return await s3Service.presign(bucket, imageKeyOrUrl, 'GET')
} catch (e) {
console.error(`Failed to presign avatar URL for key ${imageKeyOrUrl}:`, e)
return undefined
}
}
+1
View File
@@ -25,6 +25,7 @@ export type ChildPreview = z.infer<typeof childPreviewSchema>
export const assetUserInfoSchema = z.object({
id: z.string(),
name: z.string(),
image: z.string().optional(),
})
export type AssetUserInfo = z.infer<typeof assetUserInfoSchema>
+1
View File
@@ -47,6 +47,7 @@ export const projectUserInfoSchema = z.object({
id: z.string(),
name: z.string(),
role: z.string(),
image: z.string().optional(),
})
export type ProjectUserInfo = z.infer<typeof projectUserInfoSchema>
+8
View File
@@ -34,16 +34,24 @@ export const getMeResponseSchema = z.object({
name: z.string(),
email: z.string().optional(),
role: z.string(),
image: z.string().optional(),
unreadNotificationCount: z.number().optional(),
})
export type GetMeResponse = z.infer<typeof getMeResponseSchema>
export const updateMeRequestSchema = z.object({
name: z.string().optional(),
imageKey: z.string().nullable().optional(),
})
export type UpdateMeRequest = z.infer<typeof updateMeRequestSchema>
export const userInfoSchema = z.object({
id: z.string(),
name: z.string(),
role: z.string(),
email: z.string().optional(),
type: z.enum(['human', 'agent']).optional(),
image: z.string().optional(),
})
export type UserInfo = z.infer<typeof userInfoSchema>
@@ -15,7 +15,7 @@ import { useQuery } from '@tanstack/react-query'
import { Download, File, Terminal } from 'lucide-react'
import React from 'react'
import Markdown from 'react-markdown'
import { Avatar, AvatarFallback } from '../ui/avatar'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
import { DrawAnnotation } from '../ui/icons'
import { Skeleton } from '../ui/skeleton'
import { formatTimestamp } from '../viewers/utils'
@@ -147,6 +147,9 @@ export const MessageCard: React.FC<MessageCardProps> = ({
)}
<Avatar className="z-10 relative">
{creator?.image && (
<AvatarImage src={creator.image} alt={creator.name || ''} className="object-cover" />
)}
<AvatarFallback className="bg-rose-400 text-black">
{creator?.name?.[0]?.toUpperCase() || 'U'}
</AvatarFallback>
@@ -13,7 +13,7 @@ import { MembersDialog } from '../members-dialog'
import { FilterPanel } from '../search/filter-panel'
import { SearchFilterDialog } from '../search/search-filter-dialog'
import { SortControl } from '../search/sort-control'
import { Avatar, AvatarFallback } from '../ui/avatar'
import { Avatar, AvatarFallback, AvatarImage } from '../ui/avatar'
import { Button } from '../ui/button'
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover'
import { Separator } from '../ui/separator'
@@ -280,6 +280,9 @@ export function FileBrowserToolbar({
>
{members?.slice(0, 3).map((member) => (
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
{member.image && (
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
)}
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
</Avatar>
))}
+5 -1
View File
@@ -1,4 +1,4 @@
import { Avatar, AvatarFallback } from '@/ui/components/ui/avatar'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Button } from '@/ui/components/ui/button'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/ui/components/ui/dialog'
import {
@@ -17,6 +17,7 @@ export interface Member {
id?: string
name?: string
role?: string
image?: string
}
interface MembersDialogProps {
@@ -99,6 +100,9 @@ export function MembersDialog({
>
<div className="flex items-center gap-3">
<Avatar>
{member.image && (
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
)}
<AvatarFallback>{getInitials(member.name)}</AvatarFallback>
</Avatar>
<div className="flex flex-col">
@@ -0,0 +1,226 @@
import React, { useState, useRef, useEffect } from 'react'
import {
Dialog,
DialogContent,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/ui/components/ui/dialog'
import { Button } from '@/ui/components/ui/button'
import { Move, ZoomIn, ZoomOut, Loader2 } from 'lucide-react'
interface AvatarCropDialogProps {
isOpen: boolean
onClose: () => void
imageSrc: string | null
onConfirm: (croppedBlob: Blob) => Promise<void>
}
export function AvatarCropDialog({ isOpen, onClose, imageSrc, onConfirm }: AvatarCropDialogProps) {
const [zoom, setZoom] = useState(1.0)
const [offset, setOffset] = useState({ x: 0, y: 0 })
const [isDragging, setIsDragging] = useState(false)
const [isSaving, setIsSaving] = useState(false)
const dragStart = useRef({ x: 0, y: 0 })
const imageRef = useRef<HTMLImageElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
// Layout parameters
const VIEWPORT_SIZE = 250 // Diameter of the circle crop in pixels
// Reset parameters when a new image is loaded
useEffect(() => {
if (isOpen) {
setZoom(1.0)
setOffset({ x: 0, y: 0 })
setIsSaving(false)
}
}, [isOpen, imageSrc])
const handleMouseDown = (e: React.MouseEvent) => {
e.preventDefault()
setIsDragging(true)
dragStart.current = { x: e.clientX - offset.x, y: e.clientY - offset.y }
}
const handleMouseMove = (e: React.MouseEvent) => {
if (!isDragging) return
setOffset({
x: e.clientX - dragStart.current.x,
y: e.clientY - dragStart.current.y,
})
}
const handleMouseUp = () => {
setIsDragging(false)
}
// Touch support for mobile devices
const handleTouchStart = (e: React.TouchEvent) => {
if (e.touches.length !== 1) return
setIsDragging(true)
const touch = e.touches[0]
dragStart.current = { x: touch.clientX - offset.x, y: touch.clientY - offset.y }
}
const handleTouchMove = (e: React.TouchEvent) => {
if (!isDragging || e.touches.length !== 1) return
const touch = e.touches[0]
setOffset({
x: touch.clientX - dragStart.current.x,
y: touch.clientY - dragStart.current.y,
})
}
const handleConfirm = async () => {
const img = imageRef.current
const container = containerRef.current
if (!img || !container) return
setIsSaving(true)
try {
// Natural dimensions of the image vs rendered dimensions
const rect = img.getBoundingClientRect()
// Canvas dimensions (high quality cropped resolution)
const CROP_RESOLUTION = 512
const canvas = document.createElement('canvas')
canvas.width = CROP_RESOLUTION
canvas.height = CROP_RESOLUTION
const ctx = canvas.getContext('2d')
if (ctx) {
// Clear canvas
ctx.clearRect(0, 0, CROP_RESOLUTION, CROP_RESOLUTION)
// Draw a circular clipping path
ctx.beginPath()
ctx.arc(CROP_RESOLUTION / 2, CROP_RESOLUTION / 2, CROP_RESOLUTION / 2, 0, Math.PI * 2)
ctx.clip()
// Calculate translation and scaling factors
// Rendered image center in container coordinates:
// center_x = container_width / 2 + offset.x
// center_y = container_height / 2 + offset.y
// Image rendered width = rect.width, height = rect.height
// We map these container coordinate space values to the canvas coordinate space:
// Scale factor between canvas and UI container viewport (e.g. 512 / 250)
const scaleToCanvas = CROP_RESOLUTION / VIEWPORT_SIZE
// Rendered width/height at zoom 1.0 (before scaling)
const baseWidth = rect.width / zoom
const baseHeight = rect.height / zoom
// Calculate centered offset in canvas coordinates
const canvasX = CROP_RESOLUTION / 2 + offset.x * scaleToCanvas
const canvasY = CROP_RESOLUTION / 2 + offset.y * scaleToCanvas
// Draw the image scaled and panned
ctx.translate(canvasX, canvasY)
ctx.scale(zoom * scaleToCanvas, zoom * scaleToCanvas)
ctx.drawImage(img, -baseWidth / 2, -baseHeight / 2, baseWidth, baseHeight)
// Export canvas as blob
const blob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob((b) => resolve(b), 'image/jpeg', 0.9)
})
if (blob) {
await onConfirm(blob)
}
}
} catch (err) {
console.error('Failed to crop image', err)
} finally {
setIsSaving(false)
}
}
return (
<Dialog open={isOpen} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="sm:max-w-[420px] rounded-2xl border border-border bg-background/95 backdrop-blur-md shadow-2xl p-0 overflow-hidden gap-0">
<DialogHeader className="p-6 border-b border-border/40 bg-gradient-to-br from-primary/5 to-transparent">
<DialogTitle className="text-xl font-bold flex items-center gap-2">
<Move className="w-5 h-5 text-primary" />
Position and resize
</DialogTitle>
</DialogHeader>
<div className="p-6 flex flex-col items-center gap-6">
{/* Viewport Container */}
<div
ref={containerRef}
className="relative overflow-hidden bg-muted select-none border border-border/40 rounded-xl cursor-move shadow-inner"
style={{ width: VIEWPORT_SIZE, height: VIEWPORT_SIZE }}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onTouchStart={handleTouchStart}
onTouchMove={handleTouchMove}
onTouchEnd={handleMouseUp}
>
{imageSrc && (
<img
ref={imageRef}
src={imageSrc}
alt="Avatar Source"
className="absolute origin-center max-w-none pointer-events-none transition-transform duration-75 select-none"
style={{
top: '50%',
left: '50%',
transform: `translate(-50%, -50%) translate(${offset.x}px, ${offset.y}px) scale(${zoom})`,
maxHeight: '100%',
}}
/>
)}
{/* Circular Mask Overlay */}
<div className="absolute inset-0 pointer-events-none border-[3px] border-primary/90 rounded-full" />
<div
className="absolute inset-0 pointer-events-none bg-black/40"
style={{
clipPath: 'polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%)',
maskImage: 'radial-gradient(circle, transparent 122px, black 123px)',
webkitMaskImage: 'radial-gradient(circle, transparent 122px, black 123px)',
}}
/>
</div>
{/* Zoom Slider */}
<div className="w-full flex items-center gap-3 px-2">
<ZoomOut className="w-4 h-4 text-muted-foreground" />
<input
type="range"
min="1.0"
max="3.0"
step="0.01"
value={zoom}
onChange={(e) => setZoom(parseFloat(e.target.value))}
className="flex-1 h-1.5 bg-muted rounded-lg appearance-none cursor-pointer accent-primary focus:outline-none"
/>
<ZoomIn className="w-4 h-4 text-muted-foreground" />
</div>
</div>
<DialogFooter className="p-6 border-t border-border/40 bg-muted/20 flex flex-row justify-end gap-3">
<Button variant="outline" onClick={onClose} disabled={isSaving}>
Cancel
</Button>
<Button onClick={handleConfirm} disabled={isSaving || !imageSrc} className="min-w-[80px]">
{isSaving ? (
<>
<Loader2 className="w-4 h-4 animate-spin mr-2" />
Saving
</>
) : (
'Save'
)}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
+8 -1
View File
@@ -1,5 +1,5 @@
import { client } from '@/ui/api/client'
import { Avatar, AvatarFallback } from '@/ui/components/ui/avatar'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import {
DropdownMenu,
DropdownMenuContent,
@@ -57,6 +57,13 @@ export function UserMenu() {
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Avatar className="rounded-lg w-10 h-10">
{me?.image && (
<AvatarImage
src={me.image}
alt={me.name}
className="object-cover rounded-lg w-10 h-10"
/>
)}
<AvatarFallback className="rounded-lg bg-primary/40 text-foreground">
{getInitials(me?.name)}
</AvatarFallback>
@@ -13,7 +13,7 @@ import {
AlertDialogHeader,
AlertDialogTitle,
} from '@/ui/components/ui/alert-dialog'
import { Avatar, AvatarFallback } from '@/ui/components/ui/avatar'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Button } from '@/ui/components/ui/button'
import {
DropdownMenu,
@@ -238,6 +238,9 @@ function TeamPage() {
>
{safeMembers.slice(0, 3).map((member) => (
<Avatar key={member.id} className="border-2 border-background w-8 h-8">
{member.image && (
<AvatarImage src={member.image} alt={member.name} className="object-cover" />
)}
<AvatarFallback className="text-[10px]">{getInitials(member.name)}</AvatarFallback>
</Avatar>
))}
@@ -10,7 +10,12 @@ import { cn } from '@/ui/lib/utils'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
import { Bot, Cpu, Film, Loader2, Puzzle, Shield, User, Bell } from 'lucide-react'
import { useState } from 'react'
import { useState, useRef, useEffect } from 'react'
import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar'
import { Input } from '@/ui/components/ui/input'
import { Button } from '@/ui/components/ui/button'
import { AvatarCropDialog } from '@/ui/components/settings/AvatarCropDialog'
import { toast } from 'sonner'
type SettingsTab =
| 'general'
@@ -25,6 +30,11 @@ function TeamSettingsPage() {
const { teamId } = Route.useParams()
const queryClient = useQueryClient()
const [activeTab, setActiveTab] = useState<SettingsTab>('general')
const [profileName, setProfileName] = useState('')
const [isCropOpen, setIsCropOpen] = useState(false)
const [cropImageSrc, setCropImageSrc] = useState<string | null>(null)
const fileInputRef = useRef<HTMLInputElement>(null)
const [isUpdatingProfile, setIsUpdatingProfile] = useState(false)
const {
data: settings,
@@ -53,6 +63,102 @@ function TeamSettingsPage() {
enabled: !!teamId,
})
useEffect(() => {
if (me?.name) {
setProfileName(me.name)
}
}, [me])
const getInitials = (name?: string) => {
if (!name) return 'U'
const names = name.split(' ')
if (names.length > 1) {
return `${names[0][0]}${names[names.length - 1][0]}`.toUpperCase()
}
return name.substring(0, 2).toUpperCase()
}
const handleAvatarFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0]
if (file) {
const reader = new FileReader()
reader.onload = () => {
setCropImageSrc(reader.result as string)
setIsCropOpen(true)
}
reader.readAsDataURL(file)
e.target.value = ''
}
}
const handleConfirmCrop = async (blob: Blob) => {
setIsUpdatingProfile(true)
try {
const fileToUpload = new File([blob], 'avatar.jpg', { type: 'image/jpeg' })
const uploadRes = await client.api.teams[':teamId'].files.$post({
param: { teamId },
form: { file: fileToUpload },
})
if (!uploadRes.ok) throw new Error('Failed to upload avatar')
const uploadData = await uploadRes.json()
const key = (uploadData as { key: string }).key
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { imageKey: key },
})
if (!patchRes.ok) throw new Error('Failed to save profile')
toast.success('Avatar updated successfully')
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
setIsCropOpen(false)
} catch (err) {
console.error(err)
toast.error('Failed to update avatar')
} finally {
setIsUpdatingProfile(false)
}
}
const handleRemoveAvatar = async () => {
setIsUpdatingProfile(true)
try {
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { imageKey: null },
})
if (!patchRes.ok) throw new Error('Failed to remove avatar')
toast.success('Avatar removed successfully')
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
} catch (err) {
console.error(err)
toast.error('Failed to remove avatar')
} finally {
setIsUpdatingProfile(false)
}
}
const handleUpdateProfile = async () => {
if (!profileName.trim()) return
setIsUpdatingProfile(true)
try {
const patchRes = await client.api.teams[':teamId'].me.$patch({
param: { teamId },
json: { name: profileName.trim() },
})
if (!patchRes.ok) throw new Error('Failed to update name')
toast.success('Profile updated successfully')
queryClient.invalidateQueries({ queryKey: ['teams', teamId, 'me'] })
} catch (err) {
console.error(err)
toast.error('Failed to update profile')
} finally {
setIsUpdatingProfile(false)
}
}
const { mutate: updateSettings } = useMutation({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mutationFn: async (data: { teamId: string; data: { key: string; value: any } }) => {
@@ -265,15 +371,106 @@ function TeamSettingsPage() {
<Card>
<CardHeader>
<CardTitle>Personal Info</CardTitle>
<CardDescription>View your personal information.</CardDescription>
<CardDescription>Manage your profile name and avatar image.</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-col space-y-2">
<span className="text-sm font-medium text-muted-foreground">Name</span>
<span className="text-lg">{me?.name}</span>
<CardContent className="space-y-6">
<div className="flex flex-col md:flex-row gap-8 items-start">
{/* Avatar Column */}
<div className="flex flex-col items-center gap-3">
<span className="text-sm font-medium text-muted-foreground">Avatar</span>
<div
className="group relative cursor-pointer overflow-hidden rounded-full w-24 h-24 border border-border/60 shadow-md transition-all hover:opacity-90"
onClick={() => fileInputRef.current?.click()}
>
<Avatar className="w-24 h-24">
{me?.image && (
<AvatarImage
src={me.image}
alt={me.name}
className="object-cover w-24 h-24"
/>
)}
<AvatarFallback className="text-2xl bg-primary/40 text-foreground">
{getInitials(me?.name)}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 bg-black/40 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity">
<span className="text-white text-xs font-semibold">Change</span>
</div>
</div>
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
>
Upload
</Button>
{me?.image && (
<Button
variant="ghost"
size="sm"
className="text-red-500 hover:text-red-600"
onClick={handleRemoveAvatar}
>
Remove
</Button>
)}
</div>
<input
type="file"
ref={fileInputRef}
className="hidden"
accept="image/*"
onChange={handleAvatarFileChange}
/>
</div>
{/* Details Column */}
<div className="flex-1 space-y-4 w-full">
<div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">
Name
</label>
<Input
value={profileName}
onChange={(e) => setProfileName(e.target.value)}
placeholder="Enter your name"
className="max-w-md"
/>
</div>
<div className="space-y-2">
<label className="text-sm font-medium text-muted-foreground">
Email
</label>
<Input
value={me?.email || ''}
disabled
className="max-w-md bg-muted/50 cursor-not-allowed"
/>
<p className="text-xs text-muted-foreground">
Email address is managed by authentication provider.
</p>
</div>
<Button
onClick={handleUpdateProfile}
disabled={isUpdatingProfile || !profileName.trim()}
className="mt-2"
>
{isUpdatingProfile && <Loader2 className="w-4 h-4 animate-spin mr-2" />}
Save Changes
</Button>
</div>
</div>
</CardContent>
</Card>
<AvatarCropDialog
isOpen={isCropOpen}
onClose={() => setIsCropOpen(false)}
imageSrc={cropImageSrc}
onConfirm={handleConfirmCrop}
/>
</div>
)}