mirror of
https://github.com/bitwarden/android.git
synced 2026-06-08 23:16:33 -05:00
BIT-1191: Calculate avatar color when absent (#280)
This commit is contained in:
committed by
Álison Fernandes
parent
912d6b62fe
commit
5864f5376d
@@ -4,6 +4,7 @@ import com.x8bit.bitwarden.data.auth.datasource.disk.model.UserStateJson
|
||||
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
||||
import com.x8bit.bitwarden.data.vault.datasource.network.model.SyncResponseJson
|
||||
import com.x8bit.bitwarden.data.vault.repository.model.VaultState
|
||||
import com.x8bit.bitwarden.ui.platform.base.util.toHexColorRepresentation
|
||||
|
||||
/**
|
||||
* Updates the given [UserStateJson] with the data from the [syncResponse] to return a new
|
||||
@@ -51,8 +52,8 @@ fun UserStateJson.toUserState(
|
||||
userId = accountJson.profile.userId,
|
||||
name = accountJson.profile.name,
|
||||
email = accountJson.profile.email,
|
||||
// TODO Calculate default color (BIT-1191)
|
||||
avatarColorHex = accountJson.profile.avatarColorHex ?: "#00aaaa",
|
||||
avatarColorHex = accountJson.profile.avatarColorHex
|
||||
?: accountJson.profile.userId.toHexColorRepresentation(),
|
||||
isPremium = accountJson.profile.hasPremium == true,
|
||||
isVaultUnlocked = userId in vaultState.unlockedVaultUserIds,
|
||||
)
|
||||
|
||||
@@ -54,3 +54,28 @@ fun String.hexToColor(): Color = if (startsWith("#")) {
|
||||
} else {
|
||||
Color("#$this".toColorInt())
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new [String] that represents a unique color in the hex representation (`"#AARRGGBB"`).
|
||||
* This can be applied to any [String] in order to provide some deterministic color value based on
|
||||
* arbitrary [String] properties.
|
||||
*/
|
||||
@OptIn(ExperimentalStdlibApi::class)
|
||||
@Suppress("MagicNumber")
|
||||
fun String.toHexColorRepresentation(): String {
|
||||
// Produces a string with exactly two hexadecimal digits.
|
||||
// Ex:
|
||||
// 0 -> "00"
|
||||
// 10 -> "0a"
|
||||
// 1000 -> "e8"
|
||||
fun Int.toTwoDigitHexString(): String =
|
||||
this.toHexString().takeLast(2)
|
||||
|
||||
// Calculates separate red, blue, and green values from different positions in the hash and then
|
||||
// combines then into a single color.
|
||||
val hash = this.hashCode()
|
||||
val red = (hash and 0x0000FF).toTwoDigitHexString()
|
||||
val green = ((hash and 0x00FF00) shr 8).toTwoDigitHexString()
|
||||
val blue = ((hash and 0xFF0000) shr 16).toTwoDigitHexString()
|
||||
return "#ff$red$green$blue"
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user