shoelace/src/components/avatar/avatar.ts

75 wiersze
2.1 KiB
TypeScript
Czysty Zwykły widok Historia

import { LitElement, html, unsafeCSS } from 'lit';
2021-05-27 21:00:43 +00:00
import { customElement, property, state } from 'lit/decorators.js';
2021-03-06 17:01:39 +00:00
import { classMap } from 'lit-html/directives/class-map';
2021-02-26 14:09:13 +00:00
import styles from 'sass:./avatar.scss';
/**
* @since 2.0
* @status stable
*
* @dependency sl-icon
*
2021-06-25 20:25:46 +00:00
* @slot icon - The default icon to use when no image or initials are present.
2021-02-26 14:09:13 +00:00
*
2021-06-25 20:25:46 +00:00
* @csspart base - The component's base wrapper.
* @csspart icon - The container that wraps the avatar icon.
* @csspart initials - The container that wraps the avatar initials.
* @csspart image - The avatar image.
*
2021-06-25 20:25:46 +00:00
* @cssproperty --size - The size of the avatar.
2021-02-26 14:09:13 +00:00
*/
2021-03-18 13:04:23 +00:00
@customElement('sl-avatar')
2021-03-09 00:14:32 +00:00
export default class SlAvatar extends LitElement {
2021-03-06 17:01:39 +00:00
static styles = unsafeCSS(styles);
2021-02-26 14:09:13 +00:00
@state() private hasError = false;
2021-02-26 14:09:13 +00:00
/** The image source to use for the avatar. */
2021-04-02 11:47:25 +00:00
@property() image: string;
2021-02-26 14:09:13 +00:00
/** Alternative text for the image. */
2021-04-02 11:47:25 +00:00
@property() alt: string;
2021-02-26 14:09:13 +00:00
/** Initials to use as a fallback when no image is available (1-2 characters max recommended). */
2021-04-02 11:47:25 +00:00
@property() initials: string;
2021-02-26 14:09:13 +00:00
/** The shape of the avatar. */
2021-03-06 17:01:39 +00:00
@property({ reflect: true }) shape: 'circle' | 'square' | 'rounded' = 'circle';
2021-02-26 14:09:13 +00:00
render() {
return html`
<div
part="base"
class=${classMap({
avatar: true,
'avatar--circle': this.shape === 'circle',
'avatar--rounded': this.shape === 'rounded',
'avatar--square': this.shape === 'square'
})}
aria-label=${this.alt}
>
${this.initials
? html` <div part="initials" class="avatar__initials">${this.initials}</div> `
: html`
<div part="icon" class="avatar__icon">
<slot name="icon">
<sl-icon name="person-fill" library="system"></sl-icon>
2021-02-26 14:09:13 +00:00
</slot>
</div>
`}
${this.image && !this.hasError
? html`
2021-03-06 17:01:39 +00:00
<img part="image" class="avatar__image" src="${this.image}" @error="${() => (this.hasError = true)}" />
2021-02-26 14:09:13 +00:00
`
: ''}
</div>
`;
}
}
2021-03-12 14:09:08 +00:00
declare global {
interface HTMLElementTagNameMap {
'sl-avatar': SlAvatar;
}
}