package eu.friedcutlet.yokan.ui.screens.novel import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive /** Reads each embedded image [html] references once, with backpressure and a per-chapter budget. */ internal suspend fun loadNovelEmbeddedImages( html: String, embeddedImage: suspend (String) -> ByteArray?, ): Map { val images = mutableMapOf() var remaining = 32L * 1024 * 1024 parseNovelRichContent(html).blocks.forEach { block -> currentCoroutineContext().ensureActive() val reference = (block as? NovelContentBlock.Image)?.reference.orEmpty() // External/data images retain the remote-image behavior. if (reference.isBlank() || reference in images || reference.startsWith("//") || reference.substringBefore('/').contains(':')) { return@forEach } val loaded = if (remaining > 0) embeddedImage(reference) else null currentCoroutineContext().ensureActive() images[reference] = loaded?.takeIf { it.size <= remaining }?.also { remaining -= it.size } } return buildMap { images.forEach { (reference, bytes) -> if (bytes != null) put(reference, bytes) } } }