Avatar

Photo Fallback

A photo with initials behind it: a broken link leaves no hole and needs no JavaScript.

  • avatar
  • fallback
  • image
  • no-js

Preview

1440pxHost theme

Use it with AI

  1. 1. Copy the link.
  2. 2. Write to your agent in your own words and drop the link into the sentence.
  3. 3. The agent opens the link and installs the component from the registry.

put this in the header: https://vibeui.ru/c/avatar-002?lang=en

Anna Petrova
Show the full instructions

What the link says, spelled out. Use it when your agent cannot open links — paste this text instead.

# Install and place "avatar-002" (Photo Fallback) from VibeUI

## 1. Install first — do not skip, do not recreate
Run this exact command before writing any code:
npx shadcn@latest add https://vibeui.ru/r/avatar-002.json

Registry item: https://vibeui.ru/r/avatar-002.json
Installs to: components/vibeui/avatar-002.tsx (the exact path follows this project's components.json aliases).
npm dependencies: none.
Registry dependencies: none.

Install it from the registry. Do not recreate it from the description,
do not substitute a similar component from another library, and do not
rewrite it to match the project's existing style.

## 2. What it is
A photo with initials behind it: a broken link leaves no hole and needs no JavaScript.

An avatar with a photo and initials underneath: the initials are a backdrop, so a broken link never breaks the layout. The backdrop hue comes from the name. Zero dependencies, one file, no client JS.

## 3. How to use it
import { Avatar002 } from "@/components/vibeui/avatar-002"

<Avatar002 name="Anna Petrova" src="/people/anna.jpg" size="lg" />

Read the installed file for the full prop list.

## 4. Where to place it
This is a small inline component. Put it exactly where the user asked,
inside the existing markup. Do not create a new page, section or
wrapper for it. If a similar control already sits in that spot,
replace it instead of adding a second one.

Placement: ___
(The user fills this line in. If it is still blank, ask where to put it
instead of guessing.)

## 5. Keep exactly as installed
- the local --vibeui-avatar-002-* palette — do not swap it for your theme tokens
- initials as a backdrop instead of onError: an error handler would make this a client component for one edge case
- the empty alt on the photo — with a 404 the browser would print the name over the initials
- the visually hidden name: a screen reader reads initials as loose letters
- the single size variable: an avatar must scale without touching the markup
- object-fit: cover — a portrait would otherwise stretch inside the circle

## 6. You may change
- name and src
- size — sm, md or lg
- the backdrop hue if you have your own palette
- the shape: a squircle instead of a circle is one property

## 7. Rules
- The component never checks whether the photo loaded: it is built so that checking is unnecessary.
- In grids and lists set the size through the variable, not with width on the element.
- Initials come from the first two words: a single-word name yields one letter, which is fine.
- Do not lift the CSS variables into globals.css: the component has to stay a single file.

## 8. Verify
- it renders with no console errors;
- it looks like the preview on the VibeUI page you copied this from;
- if it does not, you changed something listed in section 5 — put it back.

For developers

npx shadcn@latest add https://vibeui.ru/r/avatar-002.json
https://vibeui.ru/r/avatar-002.json

Компонент самодостаточен: один файл, без зависимостей, собственная палитра в локальных переменных --vibeui-avatar-002-*. Серверный: хуков нет. Инициалы лежат абсолютной подложкой, фотография — слоем поверх с alt="", поэтому при неудачной загрузке остаётся подложка, а не значок сломанной картинки. Имя вынесено скрытой строкой для скринридера. Размер задаётся одной переменной --vibeui-avatar-002-size, три готовых значения — атрибутом data-size.

Component source

The same file your agent installs. Here in case you would rather copy it by hand.

import type { ComponentPropsWithoutRef, CSSProperties } from "react"

export type Avatar002Props = Omit<
  ComponentPropsWithoutRef<"span">,
  "children"
> & {
  name?: string
  src?: string
  size?: "sm" | "md" | "lg"
}

// Идея компонента: фотография с запасным вариантом без JS. Инициалы лежат
// подложкой, фотография — слоем поверх, и у неё alt="" — иначе при битой
// ссылке браузер нарисует поверх инициалов значок сломанной картинки и
// прочитает имя дважды. Имя отдаётся скринридеру отдельной скрытой строкой.
const STYLES = `
:where([data-vibeui-block="avatar-002"]){
--vibeui-avatar-002-size:3rem;
--vibeui-avatar-002-hue:250;
--vibeui-avatar-002-bg:oklch(0.92 0.05 var(--vibeui-avatar-002-hue));
--vibeui-avatar-002-fg:oklch(0.38 0.09 var(--vibeui-avatar-002-hue));
--vibeui-avatar-002-ring:oklch(1 0 0 / 65%);
--vibeui-avatar-002-font:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
}
[data-vibeui-block="avatar-002"]{
position:relative;display:inline-flex;flex:none;vertical-align:middle;
width:var(--vibeui-avatar-002-size);height:var(--vibeui-avatar-002-size);
}
[data-vibeui-block="avatar-002"][data-size="sm"]{--vibeui-avatar-002-size:2.25rem}
[data-vibeui-block="avatar-002"][data-size="lg"]{--vibeui-avatar-002-size:4rem}
/* Инициалы — подложка: если фотография не загрузится, останутся они. */
[data-vibeui-block="avatar-002"] [data-part="fallback"]{
position:absolute;inset:0;display:flex;align-items:center;justify-content:center;
border-radius:9999px;background:var(--vibeui-avatar-002-bg);color:var(--vibeui-avatar-002-fg);
font-family:var(--vibeui-avatar-002-font);
font-size:calc(var(--vibeui-avatar-002-size) * 0.34);font-weight:650;line-height:1;
user-select:none;
}
[data-vibeui-block="avatar-002"] img{
position:relative;width:100%;height:100%;display:block;object-fit:cover;
border-radius:9999px;box-shadow:inset 0 0 0 1px var(--vibeui-avatar-002-ring);
}
[data-vibeui-block="avatar-002"] [data-part="name"]{
position:absolute;width:1px;height:1px;overflow:hidden;
clip-path:inset(50%);white-space:nowrap;
}
@media (prefers-reduced-motion:reduce){[data-vibeui-block="avatar-002"] *{animation:none!important;transition:none!important}}
`

// Оттенок из имени: FNV-1a, разложенный по двенадцати ступеням круга.
// Сумма кодов символов не годится — кириллические имена ложатся в один
// розовый сектор; ступени в 30° дают заведомо различимые цвета.
function hue(name: string) {
  let hash = 2166136261

  for (const symbol of name) {
    hash ^= symbol.codePointAt(0)!
    hash = Math.imul(hash, 16777619)
  }

  return ((hash >>> 0) % 12) * 30
}

function initials(name: string) {
  return name
    .split(" ")
    .slice(0, 2)
    .map((part) => part[0]?.toUpperCase() ?? "")
    .join("")
}

/**
 * Фотография с запасными инициалами: битая ссылка не оставляет пустоты.
 * Один файл, ноль зависимостей, собственная палитра.
 */
export function Avatar002({
  name = "Анна Петрова",
  src = "",
  size = "md",
  className,
  style,
  ...props
}: Avatar002Props) {
  const palette = {
    "--vibeui-avatar-002-hue": hue(name),
    ...style,
  } as CSSProperties

  return (
    <>
      <style href="vibeui-avatar-002" precedence="medium">
        {STYLES}
      </style>
      <span
        {...props}
        data-vibeui-block="avatar-002"
        data-size={size}
        className={className}
        style={palette}
      >
        <span data-part="fallback" aria-hidden="true">
          {initials(name)}
        </span>
        {src ? <img src={src} alt="" loading="lazy" decoding="async" /> : null}
        <span data-part="name">{name}</span>
      </span>
    </>
  )
}