All files / src/shared/utils babyAvatarColor.ts

100% Statements 11/11
100% Branches 2/2
100% Functions 3/3
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 3928x                         1140x 1140x 28116x   1140x                     1149x 9x   1140x 1140x       1064x    
const PALETTE = [
  { bg: 'bg-emerald-600', text: 'text-white' },
  { bg: 'bg-amber-500', text: 'text-white' },
  { bg: 'bg-rose-500', text: 'text-white' },
  { bg: 'bg-violet-500', text: 'text-white' },
] as const
 
/**
 * Deterministic fallback for babies without a user-chosen `avatarColor` (e.g.
 * created before that field existed), so the same baby still always gets the
 * same color across renders/sessions.
 */
export function babyAvatarPalette(babyId: string): { bg: string; text: string } {
  let hash = 0
  for (let i = 0; i < babyId.length; i++) {
    hash = (hash * 31 + babyId.charCodeAt(i)) >>> 0
  }
  return PALETTE[hash % PALETTE.length]!
}
 
export interface BabyAvatarAppearance {
  className: string
  style?: { backgroundColor: string }
}
 
// Prefers the color the user picked for the baby's avatar; falls back to the
// id-derived palette only when no avatarColor is set.
export function babyAvatarAppearance(babyId: string, avatarColor: string | null | undefined): BabyAvatarAppearance {
  if (avatarColor) {
    return { className: 'text-white', style: { backgroundColor: avatarColor } }
  }
  const palette = babyAvatarPalette(babyId)
  return { className: `${palette.bg} ${palette.text}` }
}
 
export function babyInitials(name: string): string {
  return name.trim().slice(0, 1).toUpperCase()
}