Yokan / rebuild
Course 1 8624561

StatisticsScreen.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/settings/statistics/StatisticsScreen.kt

implementation585 lines
1package eu.friedcutlet.yokan.ui.screens.settings.statistics23import androidx.compose.animation.AnimatedContent4import androidx.compose.animation.SizeTransform5import androidx.compose.animation.core.Animatable6import androidx.compose.animation.core.EaseOutQuart7import androidx.compose.animation.core.LinearEasing8import androidx.compose.animation.core.RepeatMode9import androidx.compose.animation.core.animateFloat10import androidx.compose.animation.core.animateFloatAsState11import androidx.compose.animation.core.infiniteRepeatable12import androidx.compose.animation.core.rememberInfiniteTransition13import androidx.compose.animation.core.tween14import androidx.compose.animation.fadeIn15import androidx.compose.animation.fadeOut16import androidx.compose.animation.scaleIn17import androidx.compose.animation.togetherWith18import androidx.compose.foundation.Canvas19import androidx.compose.foundation.background20import androidx.compose.foundation.layout.*21import androidx.compose.foundation.shape.CircleShape22import androidx.compose.material3.*23import androidx.compose.runtime.*24import androidx.compose.ui.Alignment25import androidx.compose.ui.Modifier26import androidx.compose.ui.draw.clip27import androidx.compose.ui.geometry.CornerRadius28import androidx.compose.ui.geometry.Offset29import androidx.compose.ui.geometry.Rect30import androidx.compose.ui.geometry.RoundRect31import androidx.compose.ui.geometry.Size32import androidx.compose.ui.graphics.Brush33import androidx.compose.ui.graphics.Color34import androidx.compose.ui.graphics.Path35import androidx.compose.ui.graphics.StrokeCap36import androidx.compose.ui.graphics.StrokeJoin37import androidx.compose.ui.graphics.drawscope.Stroke38import androidx.compose.ui.graphics.drawscope.clipPath39import androidx.compose.ui.graphics.drawscope.clipRect40import androidx.compose.ui.graphics.drawscope.scale41import androidx.compose.ui.graphics.lerp42import androidx.compose.ui.layout.onVisibilityChanged43import androidx.compose.ui.semantics.clearAndSetSemantics44import androidx.compose.ui.semantics.contentDescription45import androidx.compose.ui.semantics.heading46import androidx.compose.ui.semantics.semantics47import androidx.compose.ui.text.TextStyle48import androidx.compose.ui.text.drawText49import androidx.compose.ui.text.font.FontWeight50import androidx.compose.ui.text.rememberTextMeasurer51import androidx.compose.ui.text.style.TextOverflow52import androidx.compose.ui.unit.Constraints53import androidx.compose.ui.unit.dp54import androidx.lifecycle.compose.collectAsStateWithLifecycle55import androidx.lifecycle.viewmodel.compose.viewModel56import eu.friedcutlet.yokan.app.YokanRuntime57import eu.friedcutlet.yokan.domain.History58import eu.friedcutlet.yokan.domain.ItemType59import eu.friedcutlet.yokan.ui.components.YokanChipTabs60import eu.friedcutlet.yokan.ui.screens.settings.SettingsScaffold61import eu.friedcutlet.yokan.ui.screens.settings.data.formatBytes62import kotlin.math.PI63import kotlin.math.ceil64import kotlin.math.cos65import kotlin.math.roundToInt66import kotlin.math.sin67import org.jetbrains.compose.resources.pluralStringResource68import org.jetbrains.compose.resources.stringResource69import yokan.composeapp.generated.resources.*7071/** One linear clock per chart; each mark eases in on its own slice of it. */72private const val REVEAL_MS = 10007374private fun stage(progress: Float, start: Float, span: Float): Float =75    EaseOutQuart.transform(((progress - start) / span).coerceIn(0f, 1f))7677@Composable78internal fun StatisticsSettingsRoute(title: String, initialItemType: ItemType, onBack: () -> Unit) {79    val model = viewModel {80        StatisticsViewModel(81            initialItemType,82            YokanRuntime.repository,83            YokanRuntime.settings,84            YokanRuntime.libraryIndex,85            YokanRuntime.localFiles,86        )87    }88    val state by model.state.collectAsStateWithLifecycle()89    SettingsScaffold(title, onBack) {90        item(key = "statistics", contentType = "dashboard") {91            StatisticsDashboard(state, onSelect = model::select, onRetry = model::refresh)92        }93    }94}9596@Composable97internal fun StatisticsDashboard(98    state: StatisticsState,99    modifier: Modifier = Modifier,100    onSelect: (ItemType) -> Unit = {},101    onRetry: () -> Unit = {},102) {103    Column(modifier.fillMaxWidth().wrapContentWidth(Alignment.CenterHorizontally).widthIn(max = 1040.dp)104        .padding(horizontal = 20.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(24.dp)) {105        YokanChipTabs(ItemType.entries.map { it.label }, ItemType.entries.indexOf(state.type),106            { onSelect(ItemType.entries[it]) })107        // Fade-through between media types and load phases; same-phase data updates morph in place instead.108        AnimatedContent(109            targetState = state,110            contentKey = { Triple(it.type, it.data != null, it.failed) },111            transitionSpec = {112                (fadeIn(tween(220, delayMillis = 90)) + scaleIn(tween(220, delayMillis = 90), initialScale = 0.98f))113                    .togetherWith(fadeOut(tween(90))).using(SizeTransform(clip = false))114            },115            label = "statistics content",116        ) { shown ->117            val data = shown.data118            when {119                shown.failed -> Column {120                    Text(stringResource(Res.string.stats_error))121                    TextButton(onClick = onRetry) { Text(stringResource(Res.string.stats_retry)) }122                }123                data == null -> {124                    val loading = stringResource(Res.string.stats_loading)125                    Box(Modifier.fillMaxWidth().height(240.dp), contentAlignment = Alignment.Center) {126                        CircularProgressIndicator(Modifier.size(28.dp).semantics { contentDescription = loading }, strokeWidth = 2.5.dp)127                    }128                }129                else -> StatisticsContent(shown, data)130            }131        }132        Spacer(Modifier.height(8.dp))133    }134}135136@Composable137private fun StatisticsContent(state: StatisticsState, data: StatisticsData) {138    val anime = state.type == ItemType.Anime139    val empty = data.titles == 0 && data.activeTitles == 0140    Column(verticalArrangement = Arrangement.spacedBy(32.dp)) {141        Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {142            Text(stringResource(if (anime) Res.string.stats_title_watch else Res.string.stats_title_read),143                style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold,144                modifier = Modifier.semantics { heading() })145            Text(146                if (empty) stringResource(Res.string.stats_empty)147                else pluralStringResource(Res.plurals.stats_subtitle, data.activeTitles, statisticsDuration(data.seconds), data.activeTitles),148                style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant,149            )150        }151        val activity = Panel(1.65f) { ActivityPanel(data.dailyActivity, it) }152        val rows = if (empty) listOf(listOf(activity)) else listOf(153            listOf(activity, Panel { HourPanel(data.hourly, it) }),154            listOfNotNull(data.mostTime.takeIf { it.isNotEmpty() }?.let { top -> Panel { TopTitlesPanel(top, it) } },155                Panel { ChaptersPanel(data, anime, it) }),156            listOfNotNull(Panel { LibraryPanel(data, it) },157                data.genres.takeIf { it.isNotEmpty() }?.let { genres -> Panel { GenresPanel(genres, it) } }),158            listOfNotNull(data.growth.takeIf { it.size >= 2 && it.last() > 0 }?.let { growth -> Panel { GrowthPanel(growth, it) } },159                Panel { CollectionPanel(data, it) }),160            listOf(Panel { StoragePanel(state, it) }),161        )162        PanelRows(rows)163    }164}165166private class Panel(val weight: Float = 1f, val content: @Composable (Modifier) -> Unit)167168@Composable169private fun PanelRows(rows: List<List<Panel>>) {170    BoxWithConstraints(Modifier.fillMaxWidth()) {171        val wide = maxWidth >= 720.dp172        Column(verticalArrangement = Arrangement.spacedBy(40.dp)) {173            if (wide) rows.forEach { row ->174                Row(horizontalArrangement = Arrangement.spacedBy(36.dp)) { row.forEach { it.content(Modifier.weight(it.weight)) } }175            } else rows.flatten().forEach { it.content(Modifier) }176        }177    }178}179180/** Starts the chart's reveal clock the first time a quarter of it is on screen, so off-screen charts still animate. */181@Composable182private fun ChartPanel(183    title: String,184    modifier: Modifier = Modifier,185    trailing: String? = null,186    content: @Composable (reveal: () -> Float) -> Unit,187) {188    val reveal = remember { Animatable(0f) }189    var seen by remember { mutableStateOf(false) }190    LaunchedEffect(seen) { if (seen) reveal.animateTo(1f, tween(REVEAL_MS, easing = LinearEasing)) }191    Column(modifier.fillMaxWidth().onVisibilityChanged(minFractionVisible = 0.25f) { visible -> if (visible) seen = true },192        verticalArrangement = Arrangement.spacedBy(16.dp)) {193        Row(verticalAlignment = Alignment.CenterVertically) {194            Text(title, Modifier.weight(1f).semantics { heading() }, style = MaterialTheme.typography.titleMedium,195                fontWeight = FontWeight.SemiBold)196            if (trailing != null) Text(trailing, style = MaterialTheme.typography.labelLarge,197                color = MaterialTheme.colorScheme.onSurfaceVariant)198        }199        content { reveal.value }200    }201}202203/** Calendar heatmap; the colour washes in as a diagonal wave across the already-drawn grid. */204@Composable205private fun ActivityPanel(days: List<Int>, modifier: Modifier) {206    BoxWithConstraints(modifier.fillMaxWidth()) {207        val gap = 3.dp208        val weeks = (days.size + 6) / 7209        val cols = ((maxWidth + gap) / (11.dp + gap)).toInt().coerceIn(1, weeks)210        val cell = ((maxWidth - gap * (cols - 1)) / cols).coerceAtMost(22.dp)211        val shown = days.drop((weeks - cols) * 7)212        val max = (shown.maxOrNull() ?: 0).coerceAtLeast(1)213        val activeDays = shown.count { it > 0 }214        val track = MaterialTheme.colorScheme.surfaceContainerHighest215        val ink = MaterialTheme.colorScheme.primary216        val description = stringResource(Res.string.stats_activity_description, activeDays, cols)217        ChartPanel(stringResource(Res.string.stats_activity),218            trailing = pluralStringResource(Res.plurals.stats_active_days, activeDays, activeDays)) { reveal ->219            Canvas(Modifier.size(cell * cols + gap * (cols - 1), cell * 7 + gap * 6)220                .clearAndSetSemantics { contentDescription = description }) {221                val c = cell.toPx()222                val g = gap.toPx()223                val radius = CornerRadius(c * 0.28f)224                val p = reveal()225                shown.forEachIndexed { i, value ->226                    val col = i / 7227                    val row = i % 7228                    val topLeft = Offset(col * (c + g), row * (c + g))229                    drawRoundRect(track, topLeft, Size(c, c), radius)230                    val t = if (value > 0) stage(p, (col + row * 0.6f) / (cols + 3.6f) * 0.6f, 0.4f) else 0f231                    if (t > 0f) {232                        val level = ceil(value * 4f / max) / 4f233                        val s = c * (0.4f + 0.6f * t)234                        drawRoundRect(lerp(track, ink, 0.25f + 0.75f * level), topLeft + Offset((c - s) / 2, (c - s) / 2),235                            Size(s, s), CornerRadius(s * 0.28f), alpha = t)236                    }237                    if (i == shown.lastIndex) drawRoundRect(ink, topLeft, Size(c, c), radius, style = Stroke(1.5.dp.toPx()))238                }239            }240        }241    }242}243244/** 24-hour radial bars; rays grow outward, sweeping clockwise from midnight. */245@Composable246private fun HourPanel(hourly: List<Int>, modifier: Modifier) {247    val peak = hourly.indices.maxByOrNull { hourly[it] }?.takeIf { hourly[it] > 0 }248    val peakLabel = peak?.let { "${it.toString().padStart(2, '0')}:00" }249    val description = peakLabel?.let { stringResource(Res.string.stats_peak_description, it) } ?: stringResource(Res.string.stats_no_activity)250    ChartPanel(stringResource(Res.string.stats_time_of_day), modifier) { reveal ->251        val measurer = rememberTextMeasurer()252        val tickStyle = MaterialTheme.typography.labelSmall.copy(color = MaterialTheme.colorScheme.onSurfaceVariant)253        val ink = MaterialTheme.colorScheme.primary254        val track = MaterialTheme.colorScheme.surfaceContainerHighest255        Box(Modifier.fillMaxWidth().clearAndSetSemantics { contentDescription = description }, contentAlignment = Alignment.Center) {256            Canvas(Modifier.widthIn(max = 204.dp).fillMaxWidth().aspectRatio(1f)) {257                val radius = size.minDimension / 2258                val inner = radius * 0.38f259                val outer = radius * 0.8f260                val max = (hourly.maxOrNull() ?: 0).coerceAtLeast(1)261                val stroke = (2 * PI * inner / 24 * 0.55).toFloat()262                val p = reveal()263                fun direction(hour: Int): Offset {264                    val angle = (hour * 15f - 90f) * PI.toFloat() / 180f265                    return Offset(cos(angle), sin(angle))266                }267                hourly.forEachIndexed { hour, value ->268                    val dir = direction(hour)269                    val start = center + dir * inner270                    drawLine(track, start, center + dir * outer, stroke, StrokeCap.Round, alpha = 0.55f)271                    val length = (outer - inner) * value / max * stage(p, hour / 24f * 0.45f, 0.55f)272                    if (length > 0f) drawLine(if (hour == peak) ink else ink.copy(alpha = 0.5f), start, start + dir * length,273                        stroke, StrokeCap.Round)274                }275                listOf(0, 6, 12, 18).forEach { hour ->276                    val layout = measurer.measure(hour.toString(), tickStyle)277                    drawText(layout, topLeft = center + direction(hour) * (radius * 0.93f) -278                        Offset(layout.size.width / 2f, layout.size.height / 2f))279                }280            }281            Text(peakLabel ?: "—", style = MaterialTheme.typography.titleLarge, fontWeight = FontWeight.Bold)282        }283    }284}285286@Composable287private fun TopTitlesPanel(items: List<History>, modifier: Modifier) {288    ChartPanel(stringResource(Res.string.stats_top_titles), modifier) { reveal ->289        val max = items.first().readingTimeSeconds.toFloat().coerceAtLeast(1f)290        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {291            items.forEachIndexed { index, history ->292                val fraction by animateFloatAsState(history.readingTimeSeconds / max, tween(450), label = "title time")293                val color = if (index == 0) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.secondary294                Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {295                    Row(horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically) {296                        Text(history.title.ifBlank { stringResource(Res.string.stats_untitled) }, Modifier.weight(1f),297                            maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium,298                            fontWeight = FontWeight.Medium)299                        Text(statisticsDuration(history.readingTimeSeconds.toLong()), style = MaterialTheme.typography.labelLarge)300                    }301                    Canvas(Modifier.fillMaxWidth().height(10.dp).clearAndSetSemantics { }) {302                        val radius = CornerRadius(size.height / 2)303                        drawRoundRect(color.copy(alpha = 0.12f), cornerRadius = radius)304                        val width = size.width * fraction * stage(reveal(), index * 0.08f, 0.6f)305                        if (width > 0f) drawRoundRect(color, size = Size(width.coerceAtLeast(size.height), size.height), cornerRadius = radius)306                    }307                }308            }309        }310    }311}312313/** 10×10 waffle that fills from the bottom row up, one square per percent. */314@Composable315private fun ChaptersPanel(data: StatisticsData, anime: Boolean, modifier: Modifier) {316    val rate = if (data.chapters > 0) data.read.toFloat() / data.chapters else 0f317    val animatedRate by animateFloatAsState(rate, tween(450), label = "completion")318    val description = stringResource(Res.string.stats_completion_description, data.read, data.chapters)319    ChartPanel(stringResource(if (anime) Res.string.stats_episodes else Res.string.stats_chapters), modifier,320        trailing = stringResource(Res.string.stats_fraction, data.read, data.chapters)) { reveal ->321        val ink = MaterialTheme.colorScheme.primary322        val track = MaterialTheme.colorScheme.surfaceContainerHighest323        Row(horizontalArrangement = Arrangement.spacedBy(24.dp), verticalAlignment = Alignment.CenterVertically) {324            Canvas(Modifier.size(156.dp).clearAndSetSemantics { contentDescription = description }) {325                val g = 3.dp.toPx()326                val c = (size.width - g * 9) / 10327                val radius = CornerRadius(c * 0.25f)328                val filled = (animatedRate * 100).roundToInt()329                val p = reveal()330                for (k in 0 until 100) {331                    val topLeft = Offset(k % 10 * (c + g), (9 - k / 10) * (c + g))332                    drawRoundRect(track, topLeft, Size(c, c), radius)333                    val t = if (k < filled) stage(p, k / 100f * 0.6f, 0.4f) else 0f334                    if (t > 0f) drawRoundRect(ink, topLeft, Size(c, c), radius, alpha = t)335                }336            }337            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {338                if (data.chapters == 0) Text("—", style = MaterialTheme.typography.headlineMedium, fontWeight = FontWeight.Bold)339                else CountUp((rate * 100).roundToInt(), reveal, MaterialTheme.typography.headlineMedium) {340                    stringResource(Res.string.stats_percent, it)341                }342                Legend(stringResource(if (anime) Res.string.stats_seen else Res.string.stats_read), data.read.toString(), ink)343                Legend(stringResource(if (anime) Res.string.stats_unseen else Res.string.stats_unread),344                    (data.chapters - data.read).toString(), MaterialTheme.colorScheme.outline)345            }346        }347    }348}349350/** Segmented donut; one sweep draws the segments in order. */351@Composable352private fun LibraryPanel(data: StatisticsData, modifier: Modifier) {353    val labels = listOf(stringResource(Res.string.stats_caught_up), stringResource(Res.string.stats_in_progress),354        stringResource(Res.string.stats_not_started))355    val values = listOf(data.caughtUp, data.inProgress, data.notStarted)356    val colors = listOf(MaterialTheme.colorScheme.primary, secondTone(), MaterialTheme.colorScheme.outline)357    val fractions = values.mapIndexed { index, value ->358        animateFloatAsState(if (data.titles > 0) value.toFloat() / data.titles else 0f, tween(450), label = "library $index")359    }360    val description = stringResource(Res.string.stats_library_description, data.caughtUp, data.inProgress, data.notStarted)361    ChartPanel(stringResource(Res.string.stats_library), modifier) { reveal ->362        val track = MaterialTheme.colorScheme.surfaceContainerHighest363        Row(horizontalArrangement = Arrangement.spacedBy(24.dp), verticalAlignment = Alignment.CenterVertically) {364            Box(Modifier.size(156.dp).clearAndSetSemantics { contentDescription = description }, contentAlignment = Alignment.Center) {365                Canvas(Modifier.fillMaxSize()) {366                    val stroke = 18.dp.toPx()367                    val topLeft = Offset(stroke / 2, stroke / 2)368                    val arcSize = Size(size.width - stroke, size.height - stroke)369                    drawArc(track, 0f, 360f, false, topLeft, arcSize, style = Stroke(stroke))370                    val drawn = 360f * stage(reveal(), 0f, 0.85f)371                    val gap = if (values.count { it > 0 } > 1) 3f else 0f372                    var start = 0f373                    fractions.forEachIndexed { index, fraction ->374                        val sweep = 360f * fraction.value375                        val visible = (drawn - start).coerceIn(0f, sweep)376                        if (visible > gap) drawArc(colors[index], start - 90f + gap / 2, visible - gap, false, topLeft, arcSize,377                            style = Stroke(stroke))378                        start += sweep379                    }380                }381                Column(horizontalAlignment = Alignment.CenterHorizontally) {382                    CountUp(data.titles, reveal, MaterialTheme.typography.headlineMedium) { it.toString() }383                    Text(pluralStringResource(Res.plurals.stats_titles_unit, data.titles), style = MaterialTheme.typography.labelMedium,384                        color = MaterialTheme.colorScheme.onSurfaceVariant)385                }386            }387            Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {388                labels.forEachIndexed { index, label -> Legend(label, values[index].toString(), colors[index]) }389            }390        }391    }392}393394/** Treemap of the most common genres; cells settle in, largest first. */395@Composable396private fun GenresPanel(genres: List<Pair<String, Int>>, modifier: Modifier) {397    ChartPanel(stringResource(Res.string.stats_genres), modifier) { reveal ->398        val measurer = rememberTextMeasurer()399        val scheme = MaterialTheme.colorScheme400        val palette = listOf(scheme.primaryContainer to scheme.onPrimaryContainer,401            scheme.secondaryContainer to scheme.onSecondaryContainer, scheme.tertiaryContainer to scheme.onTertiaryContainer)402        val nameStyle = MaterialTheme.typography.labelLarge.copy(fontWeight = FontWeight.SemiBold)403        val countStyle = MaterialTheme.typography.labelMedium404        val description = genres.joinToString { "${it.first} ${it.second}" }405        Canvas(Modifier.fillMaxWidth().height(208.dp).clearAndSetSemantics { contentDescription = description }) {406            val gap = 3.dp.toPx()407            val pad = 10.dp.toPx()408            val radius = CornerRadius(10.dp.toPx())409            val p = reveal()410            layoutTreemap(genres.map { it.second }, Rect(Offset.Zero, size)).forEachIndexed { index, bounds ->411                val t = stage(p, index * 0.07f, 0.5f)412                if (t <= 0f) return@forEachIndexed413                val (fill, ink) = if (index == 0) scheme.primary to scheme.onPrimary else palette[(index - 1) % palette.size]414                val cell = bounds.deflate(gap / 2)415                scale(0.9f + 0.1f * t, pivot = cell.center) {416                    drawRoundRect(fill, cell.topLeft, cell.size, radius, alpha = t)417                    val room = (cell.width - pad * 2).toInt().coerceAtLeast(0)418                    val full = measurer.measure(genres[index].first, nameStyle, maxLines = 1)419                    // Only ellipsize when there is room for a readable stem; tiny cells stay unlabeled.420                    if (cell.height > 44.dp.toPx() && (full.size.width <= room || cell.width > 88.dp.toPx())) {421                        val name = if (full.size.width <= room) full else measurer.measure(genres[index].first, nameStyle,422                            TextOverflow.Ellipsis, maxLines = 1, constraints = Constraints(maxWidth = room))423                        drawText(name, ink, Offset(cell.left + pad, cell.top + pad), alpha = t)424                        drawText(measurer.measure(genres[index].second.toString(), countStyle), ink,425                            Offset(cell.left + pad, cell.top + pad + name.size.height), alpha = t * 0.8f)426                    }427                }428            }429        }430    }431}432433/**434 * Binary-split treemap: [values] sorted largest first, each rect's area proportional to its value.435 * ponytail: halves by weight instead of squarifying; fine for ≤8 cells, squarify if more genres are shown.436 */437internal fun layoutTreemap(values: List<Int>, bounds: Rect): List<Rect> {438    val out = arrayOfNulls<Rect>(values.size)439    fun place(from: Int, to: Int, rect: Rect) {440        if (to - from == 1) { out[from] = rect; return }441        val total = (from until to).sumOf { values[it].toLong() }.toFloat().coerceAtLeast(1f)442        var mid = from + 1443        var head = values[from].toFloat()444        while (mid < to - 1 && head + values[mid] <= total / 2) head += values[mid++]445        val f = head / total446        if (rect.width >= rect.height) {447            val x = rect.left + rect.width * f448            place(from, mid, Rect(rect.left, rect.top, x, rect.bottom)); place(mid, to, Rect(x, rect.top, rect.right, rect.bottom))449        } else {450            val y = rect.top + rect.height * f451            place(from, mid, Rect(rect.left, rect.top, rect.right, y)); place(mid, to, Rect(rect.left, y, rect.right, rect.bottom))452        }453    }454    if (values.isNotEmpty()) place(0, values.size, bounds)455    return out.map { checkNotNull(it) }456}457458/** Cumulative library size; the line draws left to right with a dot riding its tip. */459@Composable460private fun GrowthPanel(growth: List<Int>, modifier: Modifier) {461    val description = stringResource(Res.string.stats_growth_description, growth.first(), growth.last(), growth.size)462    ChartPanel(stringResource(Res.string.stats_growth), modifier,463        trailing = stringResource(Res.string.stats_growth_delta, growth.last() - growth.first())) { reveal ->464        val ink = MaterialTheme.colorScheme.primary465        val grid = MaterialTheme.colorScheme.outlineVariant466        val surface = MaterialTheme.colorScheme.surface467        Canvas(Modifier.fillMaxWidth().height(168.dp).clearAndSetSemantics { contentDescription = description }) {468            val max = growth.max().coerceAtLeast(1).toFloat()469            val top = 8.dp.toPx()470            val height = size.height - top471            val step = size.width / (growth.size - 1)472            val points = growth.mapIndexed { i, v -> Offset(i * step, top + height * (1 - v / max)) }473            for (k in 0..2) {474                val y = top + height * k / 2f475                drawLine(grid, Offset(0f, y), Offset(size.width, y), 1.dp.toPx(), alpha = 0.6f)476            }477            val line = Path().apply { moveTo(points[0].x, points[0].y); points.drop(1).forEach { lineTo(it.x, it.y) } }478            val area = Path().apply { addPath(line); lineTo(size.width, size.height); lineTo(0f, size.height); close() }479            val t = stage(reveal(), 0f, 0.85f)480            clipRect(right = size.width * t) {481                drawPath(area, Brush.verticalGradient(listOf(ink.copy(alpha = 0.26f), ink.copy(alpha = 0f)), top, size.height))482                drawPath(line, ink, style = Stroke(2.5.dp.toPx(), cap = StrokeCap.Round, join = StrokeJoin.Round))483            }484            if (t > 0f) {485                val x = size.width * t486                val i = (x / step).toInt().coerceAtMost(points.size - 2)487                val tip = Offset(x, points[i].y + (points[i + 1].y - points[i].y) * ((x - i * step) / step))488                drawCircle(surface, 6.dp.toPx(), tip)489                drawCircle(ink, 4.dp.toPx(), tip)490            }491        }492    }493}494495@Composable496private fun CollectionPanel(data: StatisticsData, modifier: Modifier) {497    val items = listOf(Res.string.stats_downloaded to data.downloadedTitles, Res.string.stats_local to data.localTitles,498        Res.string.stats_tracked to data.trackedTitles)499    val color = MaterialTheme.colorScheme.primary500    ChartPanel(stringResource(Res.string.stats_collection), modifier) { reveal ->501        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {502            items.forEachIndexed { index, (label, count) ->503                val fraction by animateFloatAsState(if (data.titles > 0) count.toFloat() / data.titles else 0f, tween(450),504                    label = "collection $index")505                // One hue: the columns share a denominator (library size), so colour would imply categories that aren't there.506                Column(Modifier.weight(1f).semantics(mergeDescendants = true) { }, horizontalAlignment = Alignment.CenterHorizontally,507                    verticalArrangement = Arrangement.spacedBy(8.dp)) {508                    CountUp(count, reveal, MaterialTheme.typography.titleLarge) { it.toString() }509                    Canvas(Modifier.width(44.dp).height(112.dp)) {510                        val radius = CornerRadius(10.dp.toPx())511                        drawRoundRect(color.copy(alpha = 0.12f), cornerRadius = radius)512                        val height = size.height * fraction * stage(reveal(), index * 0.1f, 0.6f)513                        if (height > 0f) drawRoundRect(color, Offset(0f, size.height - height), Size(size.width, height), radius)514                    }515                    Text(stringResource(label), style = MaterialTheme.typography.labelMedium,516                        color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)517                }518            }519        }520    }521}522523/** Stacked bar of downloads vs local files; pulses while the disk scan runs. */524@Composable525private fun StoragePanel(state: StatisticsState, modifier: Modifier) {526    val downloads = state.downloadBytes527    val local = state.localBytes528    val total = (downloads ?: 0L) + (local ?: 0L)529    val loading = (downloads == null || local == null) && !state.storageFailed530    val downloadShare by animateFloatAsState(if (total > 0) (downloads ?: 0L).toFloat() / total else 0f, tween(600), label = "download share")531    val localShare by animateFloatAsState(if (total > 0) (local ?: 0L).toFloat() / total else 0f, tween(600), label = "local share")532    ChartPanel(stringResource(Res.string.stats_storage), modifier, trailing = if (loading) null else formatBytes(total)) { reveal ->533        val primary = MaterialTheme.colorScheme.primary534        val localTone = secondTone()535        val track = MaterialTheme.colorScheme.surfaceContainerHighest536        val pulse = if (loading) {537            val transition = rememberInfiniteTransition(label = "storage scan")538            transition.animateFloat(0.45f, 1f, infiniteRepeatable(tween(800), RepeatMode.Reverse), label = "storage pulse")539        } else null540        Column(verticalArrangement = Arrangement.spacedBy(14.dp)) {541            Canvas(Modifier.fillMaxWidth().height(16.dp).clearAndSetSemantics { }) {542                val bar = Path().apply { addRoundRect(RoundRect(Rect(Offset.Zero, size), CornerRadius(size.height / 2))) }543                clipPath(bar) {544                    drawRect(track, alpha = pulse?.value ?: 1f)545                    val t = stage(reveal(), 0f, 0.8f)546                    val first = size.width * downloadShare * t547                    drawRect(primary, size = Size(first, size.height))548                    drawRect(localTone, Offset(first, 0f), Size(size.width * localShare * t, size.height))549                }550            }551            FlowRow(horizontalArrangement = Arrangement.spacedBy(28.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {552                Legend(stringResource(Res.string.stats_download_storage), downloads?.let(::formatBytes) ?: "—", primary)553                Legend(stringResource(Res.string.stats_local_storage), local?.let(::formatBytes) ?: "—", localTone)554            }555            if (state.storageFailed) Text(stringResource(Res.string.stats_storage_error), style = MaterialTheme.typography.bodySmall,556                color = MaterialTheme.colorScheme.onSurfaceVariant)557        }558    }559}560561/** Counts up with the chart's reveal; isolated so only this text recomposes per frame. */562@Composable563private fun CountUp(target: Int, reveal: () -> Float, style: TextStyle, format: @Composable (Int) -> String) {564    Text(format((target * stage(reveal(), 0f, 0.8f)).roundToInt()), style = style, fontWeight = FontWeight.Bold)565}566567@Composable568private fun Legend(label: String, value: String, color: Color) {569    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {570        Box(Modifier.size(8.dp).clip(CircleShape).background(color))571        Text(label, style = MaterialTheme.typography.bodyMedium)572        Text(value, style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold)573    }574}575576@Composable577private fun statisticsDuration(seconds: Long): String = when {578    seconds >= 3600 -> stringResource(Res.string.stats_hours_minutes, seconds / 3600, seconds % 3600 / 60)579    seconds >= 60 -> stringResource(Res.string.stats_minutes, seconds / 60)580    else -> stringResource(Res.string.stats_seconds, seconds)581}582583/** A lighter step of primary that stays distinct from it in every Flex scheme, unlike tertiary on blue themes. */584@Composable585private fun secondTone(): Color = lerp(MaterialTheme.colorScheme.primary, MaterialTheme.colorScheme.surfaceContainerHighest, 0.5f)586

Search chapters, reference and source filenames.