Skip to content

Commit

Permalink
#2078: Send event if image load fails, update changelog closes (#2123)
Browse files Browse the repository at this point in the history
* AVATAR-EVENT: Send event if image load fails, update changelog

* AVATAR-EVENT: rename handler method

* AVATAR-EVENT: Add test
  • Loading branch information
yringler authored Jul 29, 2024
1 parent 1cf340b commit 03adb45
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
1 change: 1 addition & 0 deletions docs/pages/resources/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ New versions of Shoelace are released as-needed and generally occur when a criti
- Fixed a bug in the submenu controller that prevented submenus from rendering in RTL without explicitly setting `dir` on the parent menu item [#1992]
- Fixed a bug where `<sl-relative-time>` would announce the full time instead of the relative time in screen readers
- When calling `customElements.define` we no longer register with anonymous classes by default [#2079]
- When avatar image load fails, send error event [#2122]

## 2.15.1

Expand Down
10 changes: 9 additions & 1 deletion src/components/avatar/avatar.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ import type { CSSResultGroup } from 'lit';
* @since 2.0
*
* @dependency sl-icon
*
* @event sl-error - The image could not be loaded. This may because of an invalid URL, a temporary network condition, or some
* unknown cause.
*
* @slot icon - The default icon to use when no image or initials are present. Works best with `<sl-icon>`.
*
Expand Down Expand Up @@ -54,6 +57,11 @@ export default class SlAvatar extends ShoelaceElement {
this.hasError = false;
}

private handleImageLoadError() {
this.hasError = true;
this.emit('sl-error');
}

render() {
const avatarWithImage = html`
<img
Expand All @@ -62,7 +70,7 @@ export default class SlAvatar extends ShoelaceElement {
src="${this.image}"
loading="${this.loading}"
alt=""
@error="${() => (this.hasError = true)}"
@error="${this.handleImageLoadError}"
/>
`;

Expand Down
6 changes: 6 additions & 0 deletions src/components/avatar/avatar.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,16 @@ describe('<sl-avatar>', () => {
el = await fixture<SlAvatar>(html`<sl-avatar></sl-avatar>`);
el.image = 'bad_image';

let wasEventCalled = false;
el.addEventListener('sl-error', () => {
wasEventCalled = true;
});

await aTimeout(0);

await waitUntil(() => el.shadowRoot!.querySelector('img') === null);
expect(el.shadowRoot!.querySelector('img')).to.be.null;
expect(wasEventCalled).to.be.ok;
});

it('should show a valid image after being passed an invalid image initially', async () => {
Expand Down

0 comments on commit 03adb45

Please sign in to comment.