# Avatar

Round profile photo in three sizes, with name initials as a fallback when the image is empty or fails to load.

- Category: Data
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/avatar.json
- CLI: `npx markasui@latest add avatar`

## When to use

Showing a user's photo or initials in member lists, comments, and account menus.

- Always set name even when src is set, so the fallback and alt stay meaningful
- Set an empty alt when the name is written right next to the avatar
- Blade needs Alpine.js only for the fallback when the image fails to load

## Code

### Blade

Save at `resources/views/components/markas/avatar.blade.php`. Dependencies: alpinejs.

```blade
@props([
    'name' => '',
    'src' => null,
    'alt' => null,
    'size' => 'md',
])

@php
    $base = 'inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full align-middle';
    $image = 'object-cover';
    $fallback = 'bg-primary-soft font-medium text-primary select-none';
    $sizes = [
        'sm' => 'size-8 text-xs',
        'md' => 'size-10 text-sm',
        'lg' => 'size-12 text-base',
    ];

    // Huruf pertama kata pertama dan terakhir, sama dengan getInitials() di versi React dan Vue.
    $words = preg_split('/\s+/u', trim((string) $name), -1, PREG_SPLIT_NO_EMPTY) ?: [];
    $pick = count($words) > 1 ? [$words[0], end($words)] : $words;
    $initials = mb_strtoupper(implode('', array_map(fn ($word) => mb_substr($word, 0, 1), $pick)));

    $label = $alt ?? $name;
    // Fallback hanya menerima class user. Atribut lain milik elemen img.
    $fallbackAttributes = new \Illuminate\View\ComponentAttributeBag(array_filter([
        'class' => $attributes->get('class'),
        'role' => $label === '' ? null : 'img',
        'aria-label' => $label === '' ? null : $label,
        'aria-hidden' => $label === '' ? 'true' : null,
    ]));
@endphp

@if ($src)
    <span class="contents" x-data="{ failed: false }"><img
            src="{{ $src }}"
            alt="{{ $label }}"
            x-show="!failed"
            x-init="failed = $el.complete && $el.naturalWidth === 0"
            x-on:error="failed = true"
            {{ $attributes->class([$base, $image, $sizes[$size]]) }}
        /><span
            style="display: none"
            x-show="failed"
            {{ $fallbackAttributes->class([$base, $fallback, $sizes[$size]]) }}
        >{{ $initials }}</span></span>
@else
    <span {{ $fallbackAttributes->class([$base, $fallback, $sizes[$size]]) }}>{{ $initials }}</span>
@endif
```

```blade
<x-markas.avatar name="John Carter" size="sm" />
<x-markas.avatar name="Sarah Miller" :src="$user->photo_url" />
<x-markas.avatar name="Emma Wilson" src="/img/emma.jpg" size="lg" alt="" />
```

The fallback for an image that fails to load needs Alpine.js. Livewire 3 and 4 already ship it. Without `src`, the initials render with no JavaScript.

### React

Save at `src/components/markas/Avatar.tsx`. No extra dependencies.

```tsx
"use client";

import { useState, type ComponentProps } from "react";

const base =
  "inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full align-middle";
const image = "object-cover";
const fallback = "bg-primary-soft font-medium text-primary select-none";
const sizes = {
  sm: "size-8 text-xs",
  md: "size-10 text-sm",
  lg: "size-12 text-base",
};
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

/** Huruf pertama kata pertama dan terakhir, sama dengan versi Blade dan Vue. */
export function getInitials(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean);
  const picked = words.length > 1 ? [words[0], words[words.length - 1]] : words;
  return picked
    .map((word) => Array.from(word ?? "")[0] ?? "")
    .join("")
    .toUpperCase();
}

export type AvatarProps = Omit<ComponentProps<"img">, "src" | "alt"> & {
  name: string;
  src?: string | null;
  alt?: string;
  size?: keyof typeof sizes;
};

export function Avatar({
  name,
  src,
  alt,
  size = "md",
  className,
  onError,
  ...props
}: AvatarProps) {
  const [failedSrc, setFailedSrc] = useState<string | null>(null);
  const label = alt ?? name;

  if (!src || failedSrc === src) {
    return (
      <span
        role={label ? "img" : undefined}
        aria-label={label || undefined}
        aria-hidden={label ? undefined : true}
        className={cx(base, fallback, sizes[size], className)}
      >
        {getInitials(name)}
      </span>
    );
  }

  return (
    <img
      src={src}
      alt={label}
      className={cx(base, image, sizes[size], className)}
      onError={(event) => {
        setFailedSrc(src);
        onError?.(event);
      }}
      {...props}
    />
  );
}
```

```tsx
import { Avatar } from "@/components/markas/Avatar";

<Avatar name="John Carter" size="sm" />
<Avatar name="Sarah Miller" src={user.photoUrl} />
<Avatar name="Emma Wilson" src="/img/emma.jpg" size="lg" alt="" />
```

### Vue

Save at `src/components/markas/Avatar.vue`. No extra dependencies.

```vue
<script lang="ts">
/** Huruf pertama kata pertama dan terakhir, sama dengan versi Blade dan React. */
export function getInitials(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean);
  const picked = words.length > 1 ? [words[0], words[words.length - 1]] : words;
  return picked
    .map((word) => Array.from(word ?? "")[0] ?? "")
    .join("")
    .toUpperCase();
}
</script>

<script setup lang="ts">
import { computed, ref } from "vue";

defineOptions({ inheritAttrs: false });

const props = withDefaults(
  defineProps<{
    name: string;
    src?: string | null;
    alt?: string;
    size?: "sm" | "md" | "lg";
  }>(),
  { src: null, alt: undefined, size: "md" },
);

const base =
  "inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full align-middle";
const image = "object-cover";
const fallback = "bg-primary-soft font-medium text-primary select-none";
const sizes = {
  sm: "size-8 text-xs",
  md: "size-10 text-sm",
  lg: "size-12 text-base",
};

const failedSrc = ref<string | null>(null);
const label = computed(() => props.alt ?? props.name);
const showFallback = computed(
  () => !props.src || failedSrc.value === props.src,
);
const initials = computed(() => getInitials(props.name));
</script>

<template>
  <span
    v-if="showFallback"
    :role="label ? 'img' : undefined"
    :aria-label="label || undefined"
    :aria-hidden="label ? undefined : 'true'"
    :class="[base, fallback, sizes[props.size], $attrs.class]"
    >{{ initials }}</span
  >
  <img
    v-else
    :src="props.src ?? undefined"
    :alt="label"
    :class="[base, image, sizes[props.size]]"
    v-bind="$attrs"
    @error="failedSrc = props.src"
  />
</template>
```

```vue
<script setup lang="ts">
import Avatar from "@/components/markas/Avatar.vue";
</script>

<template>
  <Avatar name="John Carter" size="sm" />
  <Avatar name="Sarah Miller" :src="user.photoUrl" />
  <Avatar name="Emma Wilson" src="/img/emma.jpg" size="lg" alt="" />
</template>
```

### Svelte

Save at `src/lib/components/markas/Avatar.svelte`. No extra dependencies.

```svelte
<script lang="ts" module>
  /** First letter of the first and last word, same as the Blade, React, and Vue versions. */
  export function getInitials(name: string): string {
    const words = name.trim().split(/\s+/).filter(Boolean);
    const picked =
      words.length > 1 ? [words[0], words[words.length - 1]] : words;
    return picked
      .map((word) => Array.from(word ?? "")[0] ?? "")
      .join("")
      .toUpperCase();
  }
</script>

<script lang="ts">
  import type { HTMLImgAttributes } from "svelte/elements";

  const base =
    "inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full align-middle";
  const image = "object-cover";
  const fallback = "bg-primary-soft font-medium text-primary select-none";
  const sizes = {
    sm: "size-8 text-xs",
    md: "size-10 text-sm",
    lg: "size-12 text-base",
  };

  type Props = Omit<HTMLImgAttributes, "src" | "alt"> & {
    name: string;
    src?: string | null;
    alt?: string;
    size?: keyof typeof sizes;
  };

  let {
    name,
    src,
    alt,
    size = "md",
    class: className,
    onerror,
    ...rest
  }: Props = $props();

  let failedSrc = $state<string | null>(null);
  const label = $derived(alt ?? name);

  function handleError(
    event: Event & { currentTarget: EventTarget & Element },
  ) {
    failedSrc = src ?? null;
    onerror?.(event);
  }
</script>

{#if !src || failedSrc === src}
  <span
    role={label ? "img" : undefined}
    aria-label={label || undefined}
    aria-hidden={label ? undefined : true}
    class={[base, fallback, sizes[size], className]}>{getInitials(name)}</span
  >
{:else}
  <img
    {src}
    alt={label}
    class={[base, image, sizes[size], className]}
    onerror={handleError}
    {...rest}
  />
{/if}
```

```svelte
<script lang="ts">
  import Avatar from "$lib/components/markas/Avatar.svelte";
</script>

<Avatar name="Dewi Lestari" src="/avatars/dewi.jpg" size="lg" />
<Avatar name="Budi Santoso" />
```

### Astro

Save at `src/components/markas/Avatar.astro`. No extra dependencies.

```astro
---
import type { HTMLAttributes } from "astro/types";

const base =
  "inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full align-middle";
const image = "object-cover";
const fallback = "bg-primary-soft font-medium text-primary select-none";
const sizes = {
  sm: "size-8 text-xs",
  md: "size-10 text-sm",
  lg: "size-12 text-base",
};

type Props = Omit<HTMLAttributes<"img">, "src" | "alt"> & {
  name: string;
  src?: string | null;
  alt?: string;
  size?: keyof typeof sizes;
};

const { name, src, alt, size = "md", class: className, ...rest } = Astro.props;

// First letter of the first and last word, same as getInitials() in the other versions.
const words = name.trim().split(/\s+/).filter(Boolean);
const picked = words.length > 1 ? [words[0], words[words.length - 1]] : words;
const initials = picked
  .map((word) => Array.from(word ?? "")[0] ?? "")
  .join("")
  .toUpperCase();
const label = alt ?? name;
---

{
  src && (
    <img
      src={src}
      alt={label}
      data-markas-avatar
      class:list={[base, image, sizes[size], className]}
      {...rest}
    />
  )
}
<span
  role={label ? "img" : undefined}
  aria-label={label || undefined}
  aria-hidden={label ? undefined : "true"}
  hidden={Boolean(src)}
  class:list={[base, fallback, sizes[size], className]}>{initials}</span
>

<script>
  // The fallback right after a broken image takes its place. One listener per page serves
  // every avatar; error does not bubble, so it is caught in the capture phase.
  const isAvatar = (node: EventTarget | null): node is HTMLImageElement =>
    node instanceof HTMLImageElement && node.hasAttribute("data-markas-avatar");

  const showFallback = (img: HTMLImageElement) => {
    img.hidden = true;
    const fallback = img.nextElementSibling;
    if (fallback instanceof HTMLElement) fallback.hidden = false;
  };

  document.addEventListener(
    "error",
    (event) => {
      if (isAvatar(event.target)) showFallback(event.target);
    },
    true,
  );

  // Images that already failed before this script ran.
  document
    .querySelectorAll<HTMLImageElement>("img[data-markas-avatar]")
    .forEach((img) => {
      if (img.complete && img.naturalWidth === 0) showFallback(img);
    });
</script>
```

```astro
---
import Avatar from "@/components/markas/Avatar.astro";
---

<Avatar name="Dewi Lestari" src="/avatars/dewi.jpg" size="lg" />
<Avatar name="Budi Santoso" />
```

A small bundled script swaps a broken image for the initials.

### Angular

Save at `src/app/markas/avatar.component.ts`. No extra dependencies.

```ts
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  linkedSignal,
} from "@angular/core";

const base =
  "inline-flex shrink-0 items-center justify-center overflow-hidden rounded-full align-middle";
const image = "object-cover";
const fallback = "bg-primary-soft font-medium text-primary select-none";
const sizes = {
  sm: "size-8 text-xs",
  md: "size-10 text-sm",
  lg: "size-12 text-base",
};

export type AvatarSize = keyof typeof sizes;

/** First letter of the first and last word, same as the Blade, React, and Vue versions. */
export function getInitials(name: string): string {
  const words = name.trim().split(/\s+/).filter(Boolean);
  const picked = words.length > 1 ? [words[0], words[words.length - 1]] : words;
  return picked
    .map((word) => Array.from(word ?? "")[0] ?? "")
    .join("")
    .toUpperCase();
}

/**
 * Host stays out of layout (display: contents). class moves to the image or the initials,
 * so the host title and class are cleared.
 */
@Component({
  selector: "markas-avatar",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { class: "contents", "[attr.title]": "null" },
  template: `
    @if (src() && !failed()) {
      <img
        [src]="src()"
        [alt]="label()"
        [class]="imageClass()"
        (error)="failed.set(true)"
      />
    } @else {
      <span
        [attr.role]="label() ? 'img' : null"
        [attr.aria-label]="label() || null"
        [attr.aria-hidden]="label() ? null : 'true'"
        [class]="fallbackClass()"
        >{{ initials() }}</span
      >
    }
  `,
})
export class Avatar {
  readonly name = input.required<string>();
  readonly src = input<string | null>();
  readonly alt = input<string>();
  readonly size = input<AvatarSize>("md");
  readonly userClass = input("", { alias: "class" });

  /** Resets whenever src changes, so a new image gets a fresh try. */
  protected readonly failed = linkedSignal({
    source: this.src,
    computation: () => false,
  });
  protected readonly label = computed(() => this.alt() ?? this.name());
  protected readonly initials = computed(() => getInitials(this.name()));
  protected readonly imageClass = computed(() =>
    [base, image, sizes[this.size()], this.userClass()]
      .filter(Boolean)
      .join(" "),
  );
  protected readonly fallbackClass = computed(() =>
    [base, fallback, sizes[this.size()], this.userClass()]
      .filter(Boolean)
      .join(" "),
  );
}
```

```ts
import { Component } from "@angular/core";
import { Avatar } from "./markas/avatar.component";

@Component({
  selector: "app-example",
  imports: [Avatar],
  template: `
    <markas-avatar name="Dewi Lestari" src="/avatars/dewi.jpg" size="lg" />
    <markas-avatar name="Budi Santoso" />
  `,
})
export class Example {}
```

## Props

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | - | Person's name. Used for the initials and as the default alt. |
| `src` | `string` | - | Image URL. When empty or when it fails to load, the initials are shown. |
| `alt` | `string` | name | Alternative text. Pass an empty string when the avatar is decorative next to a name that is already written. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Size of 32, 40, or 48 pixels. |

## Accessibility

- The image always has an alt, which defaults to name.
- The initials fallback uses role img and the same aria-label as alt, so screen readers announce the name, not the letters.
- With an empty alt, the avatar is hidden from screen readers (aria-hidden).

## Notes

- Initials come from the first letter of the first and last word: `John Carter` becomes `JC`, `ann` becomes `A`. The `getInitials` function is exported from the React and Vue versions.
- Extra attributes (`loading`, `width`, `data-*`) land on the `<img>`. The fallback element only receives `class`.
- In Blade, an image that already failed before Alpine starts is still detected through `x-init` (it checks `complete` and `naturalWidth`).
- Avatar has no built-in text. The accessible name comes from `name` or `alt`, so pass them in your site's language.
