Skip to content

Commit

Permalink
fallback to initials if the image is not loaded (#40) (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
danielbprice authored May 25, 2020
1 parent 73a14f6 commit 39d5371
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
12 changes: 12 additions & 0 deletions documentation/_getting-started.pug
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,18 @@ a(href='https://github.com/eliep/vue-avatar')
initials="AS"
:size="100">
</avatar>
tr
td
avatar(username='Luke Skywalker', src='./static/luke-skywalker.png', :size='100')
td
pre
code.language-html.
<!-- fallback to initials if image doesn't load -->
<avatar
src="./static/luke-skywalker.png"
username="Luke Skywalker"
:size="100">
</avatar>

h2 Default color
p
Expand Down
11 changes: 9 additions & 2 deletions src/Avatar.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
<template>
<div class="vue-avatar--wrapper" :style="[style, customStyle]" aria-hidden="true">
<!-- this img is not displayed; it is used to detect failure-to-load of div background image -->
<img v-if="this.isImage" style="display: none" :src="this.src" @error="onImgError"></img>
<span v-show="!this.isImage">{{ userInitial }}</span>
</div>
</template>
Expand Down Expand Up @@ -49,7 +51,8 @@ export default {
'#F44336', '#FF4081', '#9C27B0', '#673AB7',
'#3F51B5', '#2196F3', '#03A9F4', '#00BCD4', '#009688',
'#4CAF50', '#8BC34A', '#CDDC39', /* '#FFEB3B' , */ '#FFC107',
'#FF9800', '#FF5722', '#795548', '#9E9E9E', '#607D8B']
'#FF9800', '#FF5722', '#795548', '#9E9E9E', '#607D8B'],
imgError: false
}
},
Expand All @@ -73,7 +76,7 @@ export default {
},
isImage () {
return Boolean(this.src)
return !this.imgError && Boolean(this.src)
},
style () {
Expand Down Expand Up @@ -136,6 +139,10 @@ export default {
return initials
},
onImgError (evt) {
this.imgError = true
},
randomBackgroundColor (seed, colors) {
return colors[seed % (colors.length)]
},
Expand Down
13 changes: 13 additions & 0 deletions test/unit/specs/Avatar.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,18 @@ describe('Avatar.vue', function () {

var backgroundImage = wrapper.element.style.backgroundImage
expect(backgroundImage).to.contain('path/to/img')
expect(wrapper.element.querySelector('.vue-avatar--wrapper > span').textContent).not.to.contain('HF')
})

it('should render initials if the \'src\' does not load', function () {
var username = 'Hubert-Félix'

const wrapper = mount(Avatar, { propsData: {
username: username,
src: 'path/to/img'
} })
wrapper.setData({ imgError: true })

expect(wrapper.element.querySelector('.vue-avatar--wrapper > span').textContent).to.contain('HF')
})
})

0 comments on commit 39d5371

Please sign in to comment.