FaviconInitials.kt

2.6 KB · raw

1package com.peachpasswords.ui.components23import androidx.compose.foundation.layout.Box4import androidx.compose.foundation.layout.size5import androidx.compose.foundation.shape.RoundedCornerShape6import androidx.compose.material3.Text7import androidx.compose.runtime.Composable8import androidx.compose.ui.Alignment9import androidx.compose.ui.Modifier10import androidx.compose.ui.draw.clip11import androidx.compose.ui.graphics.Color12import androidx.compose.ui.draw.drawBehind13import androidx.compose.ui.unit.Dp14import androidx.compose.ui.unit.dp15import androidx.compose.ui.unit.sp16import com.peachpasswords.ui.theme.PeachColors17import com.peachpasswords.ui.theme.PeachType1819/**20 * Initials chip used in place of a network favicon (offline-first). Ports the21 * browser titleInitials + titleBackground (deterministic HSL 32%/26%).22 */23@Composable24fun FaviconInitials(source: String, modifier: Modifier = Modifier, size: Dp = 36.dp) {25    val bg = titleBackground(source)26    Box(27        modifier = modifier28            .size(size)29            .clip(RoundedCornerShape(10.dp))30            .drawBehind { drawRect(bg) },31        contentAlignment = Alignment.Center,32    ) {33        Text(34            text = titleInitials(source),35            color = PeachColors.T0,36            fontFamily = PeachType.Mono,37            fontSize = (size.value * 0.34f).sp,38        )39    }40}4142fun titleInitials(source: String): String {43    val cleaned = source.replace(Regex("^https?://"), "").removePrefix("www.").trim()44    if (cleaned.isEmpty()) return "·"45    val words = cleaned.split(Regex("[\\s.\\-_/]+")).filter { it.isNotEmpty() }46    if (words.size >= 2 && words[0].isNotEmpty() && words[1].isNotEmpty()) {47        return (words[0][0].toString() + words[1][0].toString()).uppercase()48    }49    val single = words.firstOrNull() ?: cleaned50    return single.take(2).uppercase()51}5253/** Deterministic muted HSL(hue, 32%, 26%) background, matching the browser. */54fun titleBackground(source: String): Color {55    var hash = 056    for (ch in source) hash = ((hash shl 5) - hash + ch.code)57    val hue = (((hash % 360) + 360) % 360).toFloat()58    return hsl(hue, 0.32f, 0.26f)59}6061private fun hsl(h: Float, s: Float, l: Float): Color {62    val c = (1f - kotlin.math.abs(2 * l - 1f)) * s63    val x = c * (1f - kotlin.math.abs((h / 60f) % 2f - 1f))64    val m = l - c / 2f65    val (r, g, b) = when {66        h < 60 -> Triple(c, x, 0f)67        h < 120 -> Triple(x, c, 0f)68        h < 180 -> Triple(0f, c, x)69        h < 240 -> Triple(0f, x, c)70        h < 300 -> Triple(x, 0f, c)71        else -> Triple(c, 0f, x)72    }73    return Color(r + m, g + m, b + m)74}