Expose avatar background for a given content id from ElementColors (#209)

This commit is contained in:
ismailgulek 2022-09-23 17:12:28 +03:00 committed by GitHub
parent 74cab0fc0b
commit e9a272c120
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 3 deletions

View File

@ -58,6 +58,11 @@ public struct ElementColors {
public var systemGray5: Color { Color(.systemGray5) }
public var systemGray6: Color { Color(.systemGray6) }
public func avatarBackground(for contentId: String) -> Color {
let colorIndex = Int(contentId.hashCode % Int32(contentAndAvatars.count))
return contentAndAvatars[colorIndex % contentAndAvatars.count]
}
// MARK: - Temp
private var tempActionBlack: UIColor { UIColor(red: 20 / 255, green: 20 / 255, blue: 20 / 255, alpha: 1.0) }
@ -120,6 +125,11 @@ public extension UIColor {
public var systemGray5: UIColor { .systemGray5 }
public var systemGray6: UIColor { .systemGray6 }
public func avatarBackground(for contentId: String) -> UIColor {
let colorIndex = Int(contentId.hashCode % Int32(contentAndAvatars.count))
return contentAndAvatars[colorIndex % contentAndAvatars.count]
}
// MARK: - Temp
private var tempActionBlack: UIColor { UIColor(red: 20 / 255, green: 20 / 255, blue: 20 / 255, alpha: 1.0) }
@ -139,3 +149,17 @@ public extension UIColor {
public var tempActionBackgroundTint: UIColor { tempActionBackground.withAlphaComponent(0.2) }
public var tempActionForegroundTint: UIColor { tempActionForeground.withAlphaComponent(0.2) }
}
private extension String {
/// Calculates a numeric hash same as Element Web
/// See original function here https://github.com/matrix-org/matrix-react-sdk/blob/321dd49db4fbe360fc2ff109ac117305c955b061/src/utils/FormattingUtils.js#L47
var hashCode: Int32 {
var hash: Int32 = 0
for character in self {
let shiftedHash = hash << 5
hash = shiftedHash.subtractingReportingOverflow(hash).partialValue + Int32(character.unicodeScalars[character.unicodeScalars.startIndex].value)
}
return abs(hash)
}
}

View File

@ -42,9 +42,7 @@ struct PlaceholderAvatarImage: View {
return .element.accent
}
let colors = Color.element.contentAndAvatars
let colorIndex = Int(contentId.hashCode % Int32(colors.count))
return Color.element.contentAndAvatars[colorIndex % colors.count]
return .element.avatarBackground(for: contentId)
}
}