AMMSNH

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/avatar.ts
    import type { Component } from "@effect/ui"
    import type { Html } from "@effect/ui/html"
    import type { Avatar } from "@effect/ui-kit"
    import { cn } from "#lib/cn"
    
    type AvatarParts = Component.Headless.Parts<typeof Avatar>
    
    const sizes = {
      xs: "size-6 text-[10px]",
      sm: "size-8 text-xs",
      md: "size-10 text-sm",
      lg: "size-12 text-base",
      xl: "size-16 text-xl"
    } as const
    
    const shapes = {
      circle: "rounded-full",
      rounded: "rounded-md",
      square: "rounded-none"
    } as const
    
    const variants = {
      default: "bg-muted text-muted-foreground",
      brand: "bg-brand-soft text-brand-soft-foreground [&>[data-slot=fallback]]:border-transparent"
    } as const
    
    const statuses = {
      online: "bg-success",
      away: "bg-warning",
      offline: "bg-muted-foreground"
    } as const
    
    export type AvatarSize = keyof typeof sizes
    export type AvatarShape = keyof typeof shapes
    export type AvatarVariant = keyof typeof variants
    export type AvatarStatusValue = keyof typeof statuses
    
    interface ClassOption {
      readonly class?: string | undefined
    }
    
    /** The classes of the avatar's root, for an element that should look like one, such as a "+3" counter. */
    export const avatarVariants = (
      options: ClassOption & {
        readonly size?: AvatarSize | undefined
        readonly shape?: AvatarShape | undefined
        readonly variant?: AvatarVariant | undefined
      } = {}
    ): string =>
      cn(
        "relative inline-flex shrink-0 align-middle leading-none font-medium select-none",
        sizes[options.size ?? "md"],
        shapes[options.shape ?? "circle"],
        variants[options.variant ?? "default"],
        options.class
      )
    
    const fallbackClass = "flex size-full items-center justify-center rounded-[inherit] border [&_svg]:size-[55%]"
    
    /** The `<span>` that holds the image and the fallback. It doesn't clip, so a status dot can overhang it. */
    export const AvatarRoot = <Msg>(
      h: Html.H<Msg>,
      avatar: AvatarParts,
      options: Parameters<typeof avatarVariants>[0] = {}
    ) => avatar.root(h.span.class(avatarVariants(options)))
    
    /** The picture. `undefined` until it has loaded. */
    export const AvatarImage = <Msg>(
      h: Html.H<Msg>,
      avatar: AvatarParts,
      options: ClassOption & { readonly alt: string }
    ) =>
      avatar.image(
        h.img.class(cn("block size-full rounded-[inherit] object-cover", options.class)).attr("alt", options.alt)
      )
    
    /** The initials or icon shown while the picture isn't loaded. `undefined` otherwise, so chain with `?.children(...)`. */
    export const AvatarFallback = <Msg>(h: Html.H<Msg>, avatar: AvatarParts, options: ClassOption = {}) =>
      avatar.fallback(h.span.class(cn(fallbackClass, options.class)).attr("data-slot", "fallback"))
    
    /** A counter that sits in a group as one more avatar: `AvatarCount(h, { count: 3 })` draws "+3". */
    export const AvatarCount = <Msg>(
      h: Html.H<Msg>,
      options: Parameters<typeof avatarVariants>[0] & { readonly count: number }
    ) =>
      h.span.class(avatarVariants(options)).children(
        h.span.class(fallbackClass).attrs({ "data-slot": "fallback", "aria-label": `${options.count} more` })
          .children(`+${options.count}`)
      )
    
    /** A dot on the avatar's corner. Place it inside the root, after the image and the fallback. */
    export const AvatarStatus = <Msg>(
      h: Html.H<Msg>,
      options: ClassOption & { readonly status: AvatarStatusValue }
    ) =>
      h.span
        .class(cn(
          "absolute right-0 bottom-0 size-[28%] min-h-2 min-w-2 rounded-full ring-2 ring-background",
          statuses[options.status],
          options.class
        ))
        .attrs({ role: "img", "aria-label": options.status })
    
    /** A stack in which each avatar overlaps the one before it. */
    export const AvatarGroup = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
      h.div.class(cn("flex items-center *:ring-2 *:ring-background [&>*+*]:-ml-2.5", options.class))
    
  3. Import it

    import { avatarVariants, AvatarRoot, AvatarImage, AvatarFallback, AvatarCount, AvatarStatus, AvatarGroup } from "#ui/avatar"
    

Usage

Image.ts
import { Html } from "@effect/ui/html"
import { Avatar } from "@effect/ui-kit"
import { Schema } from "effect"
import { AvatarFallback, AvatarImage, AvatarRoot } from "#ui/avatar"

export const AvatarBasic = Html.component({
  name: "AvatarBasic",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    h.div.class("flex items-center gap-3").children(
      Avatar(h, {
        key: "loaded",
        props: { src: "/avatars/ada.svg" },
        view: (avatar) =>
          AvatarRoot(h, avatar).children(
            AvatarImage(h, avatar, { alt: "Ada Moreau" }),
            AvatarFallback(h, avatar)?.children("AM")
          )
      }),
      // The picture can't load, so the fallback stays.
      Avatar(h, {
        key: "broken",
        props: { src: "/avatars/missing.svg" },
        view: (avatar) =>
          AvatarRoot(h, avatar).children(
            AvatarImage(h, avatar, { alt: "Mira Santos" }),
            AvatarFallback(h, avatar)?.children("MS")
          )
      }),
      Avatar(h, {
        key: "none",
        view: (avatar) => AvatarRoot(h, avatar).children(AvatarFallback(h, avatar)?.children("NH"))
      })
    )
})

Examples

Fallback

Initials, a brand fill, an icon, and a fallback that waits out fallbackDelay.

MNKT

Sizes

Five sizes from the root's size option.

AMAMAMAMAM
AMAMAMAMAM

Shapes

The image and the fallback inherit the root's radius, set by the shape option.

LVLV

circle

LVLV

rounded

LVLV

square

Group

A stack that shows four members and counts the rest.

AMLVGOMS+2

6 of 7 members

With a status dot

AvatarStatus is an extra element in the root, coloured by its status.

AMMSNH

In a list

An avatar beside a name and an email, as in a list of members.

  • Ada Moreau

    ada@example.com

  • Mira Santos

    mira@example.com

  • Theo Lang

    theo@example.com

Anatomy

The parts the view closure receives. Apply each one to an element of your own.

PartDescription
rootThe <span> that holds the image and the fallback.
imageThe <img>, returned once the current source has loaded and undefined before.
fallbackThe <span> returned after the delay while the image isn't loaded, undefined otherwise.
imageLoadingStatus"loading", "loaded" or "error", for markup that depends on it.

API reference

Props

PropTypeDescription
srcstringThe picture. Without a src or a srcSet the status is "error" at once.
srcSet, sizesstringAs the <img> attributes of the same names.
crossOrigin"anonymous" | "use-credentials"The request's CORS mode.
referrerPolicystringThe request's referrer policy.
fallbackDelaynumberMilliseconds the fallback waits before it shows, so a fast image doesn't flash it. 0 by default.

Data attributes

AttributeDescription
(none)The avatar sets no data attributes: a part is either in the page or not.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.