package eu.friedcutlet.yokan.ui.screens.reader import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.update /** * Byte-level download progress for images loaded through Coil, keyed by URL. * * Mangayomi surfaces `ImageChunkEvent.cumulativeBytesLoaded / expectedTotalBytes` * on every reader page placeholder; Coil has no progress API, so the shared * [eu.friedcutlet.yokan.ui.image.ProfileImageHttpClient] taps Ktor's `onDownload` callback instead and this * registry fans the ratio out to the composables that render the placeholder. */ object ReaderPageDownloadProgress { private const val MAX_TRACKED = 128 private val state = MutableStateFlow>(emptyMap()) val progress: StateFlow> get() = state fun forUrl(url: String): Flow = state.map { it[url] }.distinctUntilChanged() fun report(url: String, receivedBytes: Long, totalBytes: Long?) { if (totalBytes == null || totalBytes <= 0L) return val ratio = (receivedBytes.toFloat() / totalBytes.toFloat()).coerceIn(0f, 1f) state.update { current -> if (ratio >= 1f) { return@update if (url in current) current - url else current } // Check before copying: most chunks leave the displayed percent unchanged. val previous = current[url] if (previous != null && (previous * 100).toInt() == (ratio * 100).toInt()) return@update current buildMap { putAll(current) put(url, ratio) if (size > MAX_TRACKED) keys.take(size - MAX_TRACKED).forEach(::remove) } } } fun clear(url: String) { state.update { current -> if (url in current) current - url else current } } fun clearAll() { state.update { emptyMap() } } }