2.6 KiB · text History 263b40b
//! Default "letter" avatars — the user's first initial over a deterministic
//! abstract background, rendered as a self-contained SVG. Used whenever a user
//! has not uploaded an image.

/// DaisyUI semantic color names; the default avatar picks one deterministically
/// so it always matches the active theme (the classes resolve to theme vars).
const THEME_COLORS: [&str; 8] = [
    "primary", "secondary", "accent", "neutral", "info", "success", "warning", "error",
];

/// Pick a theme color name for `name`, used as `bg-{c} text-{c}-content`.
pub fn avatar_color(name: &str) -> &'static str {
    THEME_COLORS[(hash(name) % THEME_COLORS.len() as u64) as usize]
}

/// FNV-1a hash, so a given name always yields the same colors.
fn hash(s: &str) -> u64 {
    let mut h: u64 = 0xcbf29ce484222325;
    for b in s.bytes() {
        h ^= b as u64;
        h = h.wrapping_mul(0x100000001b3);
    }
    h
}

/// Generate an SVG avatar for `name`: its first alphanumeric initial centered
/// over a two-tone gradient with a couple of translucent blobs for texture.
pub fn letter_avatar_svg(name: &str) -> String {
    let initial = name
        .chars()
        .find(|c| c.is_alphanumeric())
        .map(|c| c.to_uppercase().next().unwrap_or(c))
        .unwrap_or('?');

    let h = hash(name);
    let h1 = h % 360;
    let h2 = (h / 360 + 150) % 360;
    // Blob placement also derived from the hash so each avatar differs.
    let bx = 15 + (h / 11 % 30) as i64;
    let by = 60 + (h / 7 % 30) as i64;

    format!(
        r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="100" height="100" role="img">
<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="hsl({h1},62%,52%)"/>
<stop offset="1" stop-color="hsl({h2},58%,42%)"/>
</linearGradient></defs>
<rect width="100" height="100" fill="url(#g)"/>
<circle cx="{bx}" cy="{by}" r="34" fill="hsl({h2},70%,62%)" opacity="0.30"/>
<circle cx="78" cy="24" r="26" fill="hsl({h1},75%,70%)" opacity="0.28"/>
<text x="50" y="50" dy=".35em" text-anchor="middle" fill="#fff" font-weight="700" font-size="46"
 font-family="-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif">{initial}</text>
</svg>"##
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deterministic_and_contains_initial() {
        let a = letter_avatar_svg("Alice");
        let b = letter_avatar_svg("Alice");
        assert_eq!(a, b);
        assert!(a.contains(">A</text>"));
        assert!(a.starts_with("<svg"));
    }

    #[test]
    fn non_alnum_name_falls_back() {
        assert!(letter_avatar_svg("***").contains(">?</text>"));
    }
}