| 1 | <script lang="ts"> |
| 2 | import { mediaUrl } from './api'; |
| 3 | import { initialsOf, senderHue } from './format'; |
| 4 | import EmojiText from './EmojiText.svelte'; |
| 5 | |
| 6 | export let mxc: string | null; |
| 7 | export let label: string; |
| 8 | export let size = 34; |
| 9 | /** 'circle' for people, 'rounded' for rooms/spaces */ |
| 10 | export let shape: 'circle' | 'rounded' = 'circle'; |
| 11 | export let seed: string | null = null; |
| 12 | |
| 13 | const density = typeof window === 'undefined' ? 1 : Math.min(window.devicePixelRatio || 1, 3); |
| 14 | // rounding up to a 32px step keeps the number of cached variants per avatar small |
| 15 | $: src = mediaUrl(mxc, Math.ceil((size * density) / 32) * 32); |
| 16 | |
| 17 | let failed = false; |
| 18 | $: if (mxc) failed = false; |
| 19 | $: px = `${size}px`; |
| 20 | $: fontPx = `${Math.max(10, Math.round(size * 0.36))}px`; |
| 21 | $: hue = senderHue(seed ?? label ?? '#'); |
| 22 | </script> |
| 23 | |
| 24 | {#if src && !failed} |
| 25 | <img |
| 26 | {src} |
| 27 | alt="" |
| 28 | aria-hidden="true" |
| 29 | width={size} |
| 30 | height={size} |
| 31 | loading="lazy" |
| 32 | class="mxc-avatar" |
| 33 | class:circle={shape === 'circle'} |
| 34 | style={`width:${px};height:${px};`} |
| 35 | on:error={() => (failed = true)} |
| 36 | /> |
| 37 | {:else} |
| 38 | <span class="mxc-fallback" class:circle={shape === 'circle'} aria-hidden="true" style={`width:${px};height:${px};font-size:${fontPx};background:hsl(${hue} 32% 30%);`}> |
| 39 | <span><EmojiText text={initialsOf(label || '#')} /></span> |
| 40 | </span> |
| 41 | {/if} |
| 42 | |
| 43 | <style> |
| 44 | .mxc-avatar { |
| 45 | flex: none; |
| 46 | object-fit: cover; |
| 47 | border-radius: var(--r-md); |
| 48 | background: var(--bg-soft); |
| 49 | } |
| 50 | .mxc-avatar.circle { border-radius: 50%; } |
| 51 | .mxc-fallback { |
| 52 | flex: none; |
| 53 | display: inline-grid; |
| 54 | place-items: center; |
| 55 | border-radius: var(--r-md); |
| 56 | color: #fff; |
| 57 | font-weight: 700; |
| 58 | letter-spacing: 0.02em; |
| 59 | } |
| 60 | .mxc-fallback.circle { border-radius: 50%; } |
| 61 | </style> |