# Avatar

Foto profil bulat dengan tiga ukuran dan inisial nama sebagai fallback saat gambar kosong atau gagal dimuat.

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

## Kapan dipakai

Menampilkan foto atau inisial pengguna di daftar anggota, komentar, dan menu akun.

- Selalu isi name walau src tersedia, agar fallback dan alt tetap bermakna
- Isi alt kosong bila nama sudah tertulis tepat di sebelah avatar
- Blade butuh Alpine.js hanya untuk fallback saat gambar gagal dimuat

## Kode

### Blade

Simpan di `resources/views/components/markas/avatar.blade.php`. Dependensi: 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="Budi Santoso" size="sm" />
<x-markas.avatar name="Siti Aminah" :src="$user->photo_url" />
<x-markas.avatar name="Dewi Lestari" src="/img/dewi.jpg" size="lg" alt="" />
```

Fallback saat gambar gagal dimuat butuh Alpine.js. Livewire 3 dan 4 sudah membawa Alpine. Tanpa `src`, inisial dirender tanpa JavaScript.

### React

Simpan di `src/components/markas/Avatar.tsx`. Tanpa dependensi tambahan.

```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="Budi Santoso" size="sm" />
<Avatar name="Siti Aminah" src={user.photoUrl} />
<Avatar name="Dewi Lestari" src="/img/dewi.jpg" size="lg" alt="" />
```

### Vue

Simpan di `src/components/markas/Avatar.vue`. Tanpa dependensi tambahan.

```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="Budi Santoso" size="sm" />
  <Avatar name="Siti Aminah" :src="user.photoUrl" />
  <Avatar name="Dewi Lestari" src="/img/dewi.jpg" size="lg" alt="" />
</template>
```

### Svelte

Simpan di `src/lib/components/markas/Avatar.svelte`. Tanpa dependensi tambahan.

```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

Simpan di `src/components/markas/Avatar.astro`. Tanpa dependensi tambahan.

```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" />
```

Script kecil yang dibundel mengganti gambar yang gagal dimuat dengan inisial.

### Angular

Simpan di `src/app/markas/avatar.component.ts`. Tanpa dependensi tambahan.

```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

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `name` | `string` | - | Nama orang. Dipakai untuk inisial dan sebagai alt bawaan. |
| `src` | `string` | - | URL gambar. Kalau kosong atau gagal dimuat, inisial yang tampil. |
| `alt` | `string` | name | Teks alternatif. Isi string kosong bila avatar hanya dekorasi di samping nama yang sudah tertulis. |
| `size` | `'sm' \| 'md' \| 'lg'` | md | Ukuran 32, 40, atau 48 piksel. |

## Aksesibilitas

- Gambar selalu punya alt, bawaannya sama dengan name.
- Inisial fallback memakai role img dan aria-label yang sama dengan alt, jadi screen reader membaca nama, bukan huruf.
- Dengan alt kosong, avatar disembunyikan dari screen reader (aria-hidden).

## Catatan

- Inisial diambil dari huruf pertama kata pertama dan terakhir: `Budi Santoso` menjadi `BS`, `ani` menjadi `A`. Fungsi `getInitials` diekspor dari versi React dan Vue.
- Atribut tambahan (`loading`, `width`, `data-*`) jatuh ke `<img>`. Elemen fallback hanya menerima `class`.
- Di Blade, gambar yang sudah gagal sebelum Alpine aktif tetap terdeteksi lewat `x-init` (memeriksa `complete` dan `naturalWidth`).
- Avatar tidak punya teks bawaan. Nama aksesibel berasal dari `name` atau `alt`, jadi isi keduanya dalam Bahasa Indonesia bila perlu, misalnya `alt="Foto Budi"`.
