@@ -32,19 +32,67 @@ function AvatarImage({
3232 ) ;
3333}
3434
35+ /**
36+ * Simple hash function to generate a number from a string
37+ */
38+ function hashString ( str : string ) : number {
39+ let hash = 0 ;
40+ for ( let i = 0 ; i < str . length ; i ++ ) {
41+ hash = ( hash << 5 ) - hash + str . charCodeAt ( i ) ;
42+ hash = hash & hash ;
43+ }
44+ return Math . abs ( hash ) ;
45+ }
46+
47+ const colorClasses = [
48+ "bg-[color:var(--avatar-0)]" ,
49+ "bg-[color:var(--avatar-1)]" ,
50+ "bg-[color:var(--avatar-2)]" ,
51+ "bg-[color:var(--avatar-3)]" ,
52+ "bg-[color:var(--avatar-4)]" ,
53+ "bg-[color:var(--avatar-5)]" ,
54+ "bg-[color:var(--avatar-6)]" ,
55+ "bg-[color:var(--avatar-7)]" ,
56+ "bg-[color:var(--avatar-8)]" ,
57+ "bg-[color:var(--avatar-9)]" ,
58+ ] ;
59+
60+ function getAvatarColorClass ( children : React . ReactNode ) : string {
61+ // Extract text content from children
62+ let childText : string | undefined ;
63+ if ( typeof children === "string" ) {
64+ childText = children ;
65+ } else if ( Array . isArray ( children ) ) {
66+ // Handle array of children (e.g., multiple text nodes)
67+ childText = children . filter ( ( child ) => typeof child === "string" ) . join ( "" ) ;
68+ } else if (
69+ React . isValidElement ( children ) &&
70+ typeof ( children . props as any ) . children === "string"
71+ ) {
72+ childText = ( children . props as any ) . children ;
73+ }
74+ if ( ! childText ) return "bg-muted text-muted-foreground" ;
75+
76+ return colorClasses [ hashString ( childText ) % colorClasses . length ] ;
77+ }
78+
3579function AvatarFallback ( {
3680 className,
81+ children,
3782 ...props
3883} : React . ComponentProps < typeof AvatarPrimitive . Fallback > ) {
3984 return (
4085 < AvatarPrimitive . Fallback
4186 data-slot = "avatar-fallback"
4287 className = { cn (
43- "bg-muted flex size-full items-center justify-center rounded-full" ,
88+ "flex size-full items-center justify-center rounded-full" ,
4489 className ,
90+ getAvatarColorClass ( children ) ,
4591 ) }
4692 { ...props }
47- />
93+ >
94+ { children }
95+ </ AvatarPrimitive . Fallback >
4896 ) ;
4997}
5098
0 commit comments