# Avatar

显示一张图片，并在加载中或失败时给出回退内容。

用 Avatar 表示一个人或一个团队，比如在评论、成员列表或账户菜单里。它在图片加载完成前显示姓名首字母或一个图标，图片加载失败时也继续显示。

```ts title="basic.ts"
import "@ui-sdk/web/avatar"

const person = {
  name: "shadcn",
  src: "https://github.com/shadcn.png",
}

function mount(root: HTMLElement) {
  root.innerHTML = `
    <div data-slot="row">
      <ui-avatar>
        <img src="${person.src}" alt="${person.name}" />
        <ui-avatar-fallback><span aria-hidden="true">CN</span><span data-slot="visually-hidden">shadcn</span></ui-avatar-fallback>
      </ui-avatar>
    </div>
  `
}

export { mount }
```

图片加载完成后会替换首字母。无论哪种状态，屏幕阅读器都能读出这个人的名字。

## 安装
```bash
npm install @ui-sdk/web @ui-sdk/core
```

导入这个组件会定义它的元素。在服务器上，导入什么也不做。

```ts
import "@ui-sdk/web/avatar"
```

## 组合
用下面的组合构建一个 `ui-avatar`：

```text
ui-avatar
├── img
└── ui-avatar-fallback
```

- `ui-avatar` 把图片的加载状态共享给它的各个部件。
- 直接子元素 `img` 提供图片。没有用于图片的自定义元素。
- 没有图片加载时，`ui-avatar-fallback` 会显示。

图片是真正的 `img`，服务端标记里也一样。浏览器可以在元素升级之前就开始获取它。回退内容会一直可见，直到图片加载完成；如果加载失败，回退内容会保留。

## 用法
导入各个部件并把它们组合起来：

```html
<script type="module">
  import "@ui-sdk/web/avatar"
</script>

<ui-avatar>
  <img src="/ada.png" alt="Ada Lovelace" />
  <ui-avatar-fallback>AL</ui-avatar-fallback>
</ui-avatar>
```

## 自己构建
`@ui-sdk/web/avatar` 自带现成的 `ui-avatar` 元素。如果你想用自己起的元素名构建一个，从 `@ui-sdk/core` 里的 `avatar` 原语（primitive）开始：

```ts title="user-photo-elements.ts"
import { avatar } from "@ui-sdk/core/avatar"
import { createParts } from "@ui-sdk/web"

createParts(avatar, {
  root: {
    tag: "user-photo",
    children: { image: (el) => el.querySelector(":scope > img") },
    optionalChildren: ["image"],
  },
  fallback: "user-photo-initials",
})
```

```html
<user-photo>
  <img src="https://github.com/shadcn.png" alt="shadcn" />
  <user-photo-initials>CN</user-photo-initials>
</user-photo>
```

它们和现成元素由同一批部件组成，只是用了你的名字。更多内容见[渲染原语](/docs/web-components/rendering)和[自定义渲染](https://ui-sdk.cn/docs/web-components/components/avatar#custom-rendering)。

## 回退延迟
<span id="behavior-and-options" />

在回退内容上设置 `delay`，让它在显示前等待一段时间。这样可以避免图片加载很快时首字母一闪而过。不设置延迟时，回退内容会立即出现，在服务端也是如此。

```html
<ui-avatar>
  <img src="https://github.com/shadcn.png" alt="shadcn" />
  <ui-avatar-fallback delay="600">CN</ui-avatar-fallback>
</ui-avatar>
```

## 图片属性
把 `srcset`、`crossorigin` 和 `referrerpolicy` 这类图片属性传给图片。它们作用在浏览器加载的同一个 `img` 上。对于页面靠下的头像，使用 `loading="lazy"`。

```html
<ui-avatar>
  <img
    src="https://github.com/shadcn.png"
    srcset="
      https://github.com/shadcn.png?size=80  1x,
      https://github.com/shadcn.png?size=160 2x
    "
    alt="shadcn"
    crossorigin="anonymous"
    referrerpolicy="no-referrer"
    loading="lazy"
  />
  <ui-avatar-fallback>CN</ui-avatar-fallback>
</ui-avatar>
```

<span id="render-functions" />

## 可交互的头像
点击头像会执行某个动作时，改用按钮。给它一个无障碍名称，这个名称在图片加载期间也要一直可用。

```html
<button type="button" aria-label="shadcn">
  <ui-avatar>
    <img src="https://github.com/shadcn.png" alt="" />
    <ui-avatar-fallback aria-hidden="true">CN</ui-avatar-fallback>
  </ui-avatar>
</button>
```

`img` 必须保持为 `ui-avatar` 的直接子元素，所以要把头像放进按钮里，而不是用 `as-child` 绑定按钮。

## 加载状态
在 `ui-avatar` 上监听 `loadingstatuschange`。事件 detail 里的 `value` 是新状态，变更详情在它旁边。可能的状态有 `loading`、`loaded`、`error` 和 `idle`。

```ts
const avatar = document.querySelector("ui-avatar")!

avatar.addEventListener("loadingstatuschange", (event) => {
  if (event.detail.value === "error") reportBrokenImage(event.detail.reason)
})
```

替换已经加载的图片时，浏览器会让旧图保持可见，直到新来源加载完成。替换失败时会显示回退内容。变更详情说明状态为什么变化；见[原因](https://ui-sdk.cn/docs/web-components/components/avatar#reasons)。

## 自定义渲染
用[部件与组合](/docs/web-components/parts-and-composition)选择部件绑定的元素。每个部件都会显示加载状态，`ui-avatar` 会报告每次变化，所以图片加载失败时，回退内容可以显示不同的文字：

```ts
const avatar = document.querySelector("ui-avatar")!
const fallback = avatar.querySelector("ui-avatar-fallback")!

avatar.addEventListener("loadingstatuschange", (event) => {
  fallback.textContent = event.detail.value === "error" ? "?" : user.initials
})
```

## 样式
设置根元素的大小，让图片和回退内容填满它。图片在加载完成前会管理自己的隐藏样式；更换它的元素时，保留这些样式。

每个部件都有一个 `data-slot`，比如 `avatar-fallback`，并通过[数据属性](https://ui-sdk.cn/docs/web-components/components/avatar#data-attributes)下列出的属性显示加载状态。

## 数据属性
### `<ui-avatar>`
`[data-slot="avatar"]`

- `data-loading-status` (`idle`, `loading`, `loaded`, `error`): Where the image is: no image yet, loading, loaded, or failed.

### `<img>`
`[data-slot="avatar-image"]`

- `data-loading-status` (`idle`, `loading`, `loaded`, `error`): Where the image is: no image yet, loading, loaded, or failed.

### `<ui-avatar-fallback>`
`[data-slot="avatar-fallback"]`

- `data-loading-status` (`idle`, `loading`, `loaded`, `error`): Where the image is: no image yet, loading, loaded, or failed.

## API 参考
属性（props）采用 kebab 命名（kebab case），比如 `<ui-avatar-fallback>` 上的 `delay`。回调是 DOM 事件。

### Avatar
- `loadingstatuschange event`: Runs when the image's loading status changes: `"loading"` when it gets a source, `"loaded"`, `"error"`, and `"idle"` when it leaves the page. `details.reason` says why, and `details.event` is the image's `load` or `error` event, or undefined when the status was known at once, like for a cached image.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### AvatarImage
图片。它是 `ui-avatar` 的直接子元素，是一个真正的 `img`，所以浏览器可以在元素升级之前获取它，并带有自己的属性，比如 `srcset`、`crossorigin` 和 `referrerpolicy`。

### AvatarFallback
- `delay?` (`number`): How long to wait, in milliseconds, before showing the fallback, so a fast image appears without the fallback flashing first. Without one, the fallback shows at once, server markup included.

### 状态
相同的状态会作为数据属性出现在每个元素上。

- `loadingStatus` (`AvatarLoadingStatus`): Where the image is: `"idle"`, `"loading"`, `"loaded"` or `"error"`.

### 原因
`event.detail.reason` 说明状态为什么变化。

- `image-load` (`Event | undefined`): An image loaded. No event when it was already in the browser's cache.
- `image-error` (`Event | undefined`): An image failed to load, or has no source. No event when that was known at once.
- `src-change` (`none`): An image got a new source, or left the page, so its status starts over.

### 事件
事件在各自的元素上触发，不会冒泡，状态在 `event.detail.value` 里，`reason` 和 `event` 在它旁边。

| 成员                        | 所属                 | 说明                                               |
| --------------------------- | -------------------- | -------------------------------------------------- |
| `loadingstatuschange` event | `ui-avatar`          | `detail: { value, reason, event }`，状态变化时触发 |
| `delay` attribute           | `ui-avatar-fallback` | 显示回退内容前等待的时间，以毫秒计                 |
| `debug` attribute           | `ui-avatar`          | 记录每次状态变化及其原因                           |

## 无障碍
给图片有意义的 `alt` 文本。回退内容里也要包含这个人的名字；如果你只想显示首字母，可以使用视觉上隐藏的文字。

头像旁边可见的名字已经能表明这个人是谁时，用空的 `alt`，并对屏幕阅读器隐藏装饰性的回退内容。

- An image that loads replaces the fallback.
- An image that fails keeps the fallback.
- An avatar without an image shows its fallback.
- A fallback with a delay waits before showing.
- The image's loading status is reported.
- Removing the image brings the fallback back.
- A new source shows its image once it loads.
- The image is fetched with its own referrer policy.
- A cached image doesn't flash the fallback when the avatar mounts again.
- A new source keeps showing the previous image until it loads.
- The image is fetched once, even when it can't be cached.

Runs in React、Vue 和 web components.
