Skip to content

Commit

Permalink
Fall back to initials avatar when image avatar doesn't work
Browse files Browse the repository at this point in the history
Initially I had it implemented such that it would only fallback on
error, but actually it's nice to have also while loading if it takes
a while to load the avatar.
  • Loading branch information
SpiritCroc committed Apr 7, 2024
1 parent a46ff73 commit f704cca
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
1 change: 1 addition & 0 deletions changelog.d/2667.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fall back to name-based generated avatars when image avatars don't load.
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
Expand All @@ -32,12 +33,13 @@ import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import coil.compose.AsyncImagePainter
import coil.compose.SubcomposeAsyncImage
import coil.compose.SubcomposeAsyncImageContent
import io.element.android.compound.theme.ElementTheme
import io.element.android.libraries.designsystem.colors.AvatarColorsProvider
import io.element.android.libraries.designsystem.preview.ElementThemedPreview
import io.element.android.libraries.designsystem.preview.PreviewGroup
import io.element.android.libraries.designsystem.preview.debugPlaceholderAvatar
import io.element.android.libraries.designsystem.text.toSp
import io.element.android.libraries.designsystem.theme.components.Text
import timber.log.Timber
Expand Down Expand Up @@ -71,16 +73,23 @@ private fun ImageAvatar(
modifier: Modifier = Modifier,
contentDescription: String? = null,
) {
AsyncImage(
SubcomposeAsyncImage(
model = avatarData,
onError = {
Timber.e(it.result.throwable, "Error loading avatar $it\n${it.result}")
},
contentDescription = contentDescription,
contentScale = ContentScale.Crop,
placeholder = debugPlaceholderAvatar(),
modifier = modifier
)
) {
when (val state = painter.state) {
is AsyncImagePainter.State.Success -> SubcomposeAsyncImageContent()
is AsyncImagePainter.State.Error -> {
SideEffect {
Timber.e(state.result.throwable, "Error loading avatar $state\n${state.result}")
}
InitialsAvatar(avatarData = avatarData)
}
else -> InitialsAvatar(avatarData = avatarData)
}
}
}

@Composable
Expand Down

0 comments on commit f704cca

Please sign in to comment.