# 15 — Novel reader and text-to-speech

Prerequisites: owned content, EPUB/local input, progress and UI shell. [File workbook](../reference/15-files.md).

[chapter-content-start]: #
## How to write this chapter

Turn remote HTML and local EPUB chapters into one owned rich-content reader, with logical anchors shared across scrolling, pagination and speech. Layout changes must not change which text the user was reading.

The 26 assigned entries are integrated below at their implementation steps. Every text listing is complete, including imports, helpers and tests. Create the displayed paths in your new project; dependencies imported from other chapters are linked beside the file. Binary assets have direct downloads.

Read each step’s explanation, write its contracts and implementation, then trace the test assertions. The final application graph has dependencies across chapters: the ordering is a construction plan, and a step is not a promise that the whole app compiles before its referenced contracts exist.

Implementation sequence:

- Step 1: Load owned chapter content and parse rich blocks/links.
- Step 2: Map scroll measurements to stable logical progress.
- Step 3: Paginate measured blocks into text slices and spreads.
- Step 4: Bind ViewModel, route, chrome and persistent reader settings.
- Step 5: Own speech requests and ignore obsolete callbacks.
- Verification: recreate the full test/fixture listings and run the relevant target tasks.
[chapter-content-end]: #


## Step 1: model chapter content

Implement NovelReaderContract and content loading before layout. Remote runtime HTML and local EPUB content enter a common owned loading path. Keep chapter identity, document base URL and referenced resources together so relative links/images resolve correctly. Preserve source headers and cancellation. Clean HTML through the appropriate runtime contract, then parse into rich blocks/spans instead of displaying raw markup as plain text.

Implement NovelHtmlParser, rich content, embedded content and content links. Preserve headings, paragraphs, emphasis, links and supported embedded images/media. External links and internal chapter links need distinct handling. A failed image should not discard the readable text.

[chapter-content-start]: #
### Follow the code

Keep chapter identity, HTML, base URL and headers together through loading and parsing. The parser produces rich text/image/rule blocks that can feed either renderer. Relative image/link resolution uses the chapter document's base rather than an arbitrary app URL. Owned loading guards late responses after navigation; embedded image failure should remain a local block error rather than removing the text.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderContract.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLoading.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelHtmlParser.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContent.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLinks.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContent.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderContract.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderContract.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderContract.kt).

The implementation below defines `NovelReaderState`, `NovelReaderEvent`, `ToggleBookmark`, `ReadingPaused`, `ReadingResumed`, `SaveProgress`, `SetAutoScrollEnabled`, `SetAutoScrollOffset`, `ToggleAutoScrollPlaying`, `StartTts` and 4 further declarations.

The source describes its contract as:

> Loaded chapter content; null until the first load finishes.

Cross-chapter imports used by this file: [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Source`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Source

internal data class NovelReaderState(
    val chapter: Chapter,
    val source: Source?,
    val previousChapter: Chapter? = null,
    val nextChapter: Chapter? = null,
    /** Loaded chapter content; null until the first load finishes. */
    val document: NovelDocument? = null,
    val imageHeaders: Map<String, String> = emptyMap(),
    val loading: Boolean = true,
    /** Extraction failure; [document] then holds the title/chapter description instead. */
    val error: String? = null,
    val tts: NovelTtsUiState = NovelTtsUiState(),
    val autoScrollEnabled: Boolean = false,
    val autoScrollPlaying: Boolean = false,
    val autoScrollOffset: Float = 10f,
)

internal sealed interface NovelReaderEvent {
    data object ToggleBookmark : NovelReaderEvent
    data object ReadingPaused : NovelReaderEvent
    data object ReadingResumed : NovelReaderEvent
    /** Persists [ratio] with the reading time counted since the previous save and pauses the clock. */
    data class SaveProgress(val ratio: Double) : NovelReaderEvent
    data class SetAutoScrollEnabled(val enabled: Boolean) : NovelReaderEvent
    data class SetAutoScrollOffset(val offset: Float) : NovelReaderEvent
    data object ToggleAutoScrollPlaying : NovelReaderEvent
    data class StartTts(val paragraphs: List<String>) : NovelReaderEvent
    data object ToggleTtsPlayback : NovelReaderEvent
    data object SkipNextTts : NovelReaderEvent
    data object SkipPreviousTts : NovelReaderEvent
    data object StopTts : NovelReaderEvent
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLoading.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLoading.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLoading.kt).

The implementation below defines `NovelDocument`, `parse`, `loadNovelDocument`.

The source describes its contract as:

> A chapter's HTML plus the embedded (EPUB) images it references, read while the content owner was live; parsing it needs no further access to the archive.

Cross-chapter imports used by this file: [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Source`](../chapters/02-domain-and-settings-models.md), [`ProfileReaderContent`](../chapters/06-extension-runtimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent

/**
 * A chapter's HTML plus the embedded (EPUB) images it references, read while the content owner was
 * live; parsing it needs no further access to the archive.
 */
internal class NovelDocument(
    val html: String,
    val baseUrl: String = "",
    val embeddedImages: Map<String, ByteArray> = emptyMap(),
) {
    fun parse(onOpenLink: ((String) -> Unit)? = null): NovelRichContent =
        parseNovelRichContent(html, baseUrl, embeddedImages::get, onOpenLink)
}

internal suspend fun loadNovelDocument(
    content: ProfileReaderContent,
    source: Source?,
    name: String,
    chapter: Chapter,
): NovelDocument = content.novelContent(source, name, chapter) { document ->
    NovelDocument(
        html = document.html,
        baseUrl = resolveNovelReference(source?.baseUrl.orEmpty(), chapter.url),
        embeddedImages = document.chapterHref?.let { href ->
            loadNovelEmbeddedImages(document.html) { reference ->
                document.readEmbeddedResource(resolveEpubResourcePath(href, reference))
            }
        }.orEmpty(),
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelHtmlParser.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelHtmlParser.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelHtmlParser.kt).

The implementation below defines `NovelRichContent`, `NovelContentBlock`, `Text`, `Image`, `Rule`, `NovelTextBlockKind`, `NovelImageSource`, `Remote`, `Embedded`, `InlineMarkup` and 14 further declarations.

The source describes its contract as:

> Block elements that also carry an inline style until they close.

Cross-chapter imports used by this file: [`decodeHtmlEntities`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.LinkAnnotation
import androidx.compose.ui.text.LinkInteractionListener
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextLinkStyles
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.BaselineShift
import androidx.compose.ui.text.style.TextDecoration
import eu.friedcutlet.yokan.util.decodeHtmlEntities

internal data class NovelRichContent(
    val blocks: List<NovelContentBlock>,
    val plainText: String,
)

internal sealed interface NovelContentBlock {
    data class Text(
        val text: AnnotatedString,
        val kind: NovelTextBlockKind = NovelTextBlockKind.Paragraph,
    ) : NovelContentBlock

    data class Image(
        val source: NovelImageSource,
        val alt: String,
        val reference: String = "",
    ) : NovelContentBlock

    data object Rule : NovelContentBlock
}

internal enum class NovelTextBlockKind {
    Paragraph,
    Heading1,
    Heading2,
    Heading3,
    Heading4,
    Heading5,
    Heading6,
    BlockQuote,
    Preformatted,
    TableRow,
}

internal sealed interface NovelImageSource {
    data class Remote(val url: String) : NovelImageSource
    class Embedded(val bytes: ByteArray, val cacheKey: String) : NovelImageSource
}

private data class InlineMarkup(
    val tag: String,
    val spanStyle: SpanStyle? = null,
    val link: LinkAnnotation.Url? = null,
)

private val htmlTokenRegex = Regex("<!--[\\s\\S]*?-->|<[^>]+>|[^<]+")
private val htmlAttributeRegex = Regex("([^\\s=/>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?")
private val whitespaceRegex = Regex("\\s+")
private val blockTags = setOf("p", "div", "section", "article", "header", "footer", "aside", "main", "figure", "figcaption")
private val headingTags = setOf("h1", "h2", "h3", "h4", "h5", "h6")
/** Block elements that also carry an inline style until they close. */
private val styledBlockTags = headingTags + setOf("blockquote", "pre")
/** Inline elements whose style is popped on their closing (or self-closing) tag. */
private val inlineTags = setOf("b", "strong", "i", "em", "u", "s", "strike", "del", "code", "mark", "sub", "sup", "span", "a", "th")
private val imageTags = setOf("img", "source")

private val boldStyle = SpanStyle(fontWeight = FontWeight.Bold)
private val italicStyle = SpanStyle(fontStyle = FontStyle.Italic)
private val monospaceStyle = SpanStyle(fontFamily = FontFamily.Monospace)
private val inlineStyles = mapOf(
    "b" to boldStyle,
    "strong" to boldStyle,
    "i" to italicStyle,
    "em" to italicStyle,
    "u" to SpanStyle(textDecoration = TextDecoration.Underline),
    "s" to SpanStyle(textDecoration = TextDecoration.LineThrough),
    "strike" to SpanStyle(textDecoration = TextDecoration.LineThrough),
    "del" to SpanStyle(textDecoration = TextDecoration.LineThrough),
    "code" to SpanStyle(fontFamily = FontFamily.Monospace, background = Color(0x22000000)),
    "mark" to SpanStyle(background = Color(0x66FFF176)),
    "sub" to SpanStyle(baselineShift = BaselineShift.Subscript),
    "sup" to SpanStyle(baselineShift = BaselineShift.Superscript),
)
private val linkStyles = TextLinkStyles(
    style = SpanStyle(color = Color(0xFF1976D2.toInt()), textDecoration = TextDecoration.Underline),
)
private val namedCssColors = mapOf(
    "black" to 0xFF000000,
    "white" to 0xFFFFFFFF,
    "red" to 0xFFF44336,
    "blue" to 0xFF1976D2,
    "green" to 0xFF388E3C,
    "gray" to 0xFF808080,
    "grey" to 0xFF808080,
    "yellow" to 0xFFFFEB3B,
    "transparent" to 0x00000000,
)

internal fun parseNovelRichContent(
    html: String,
    baseUrl: String = "",
    embeddedImage: (String) -> ByteArray? = { null },
    onOpenLink: ((String) -> Unit)? = null,
): NovelRichContent {
    if (!html.contains('<') || !html.contains('>')) {
        val text = decodeHtmlEntities(html)
        return NovelRichContent(
            blocks = listOf(NovelContentBlock.Text(AnnotatedString(text))),
            plainText = text,
        )
    }
    val linkListener = onOpenLink?.let { openLink ->
        LinkInteractionListener { annotation ->
            (annotation as? LinkAnnotation.Url)?.url?.let(openLink)
        }
    }

    val blocks = mutableListOf<NovelContentBlock>()
    var builder = AnnotatedString.Builder()
    val markup = ArrayDeque<InlineMarkup>()
    var kind = NovelTextBlockKind.Paragraph
    var orderedListDepth = 0
    val orderedListIndexes = mutableListOf<Int>()
    var preformatted = false
    var lastTextChar: Char? = null

    fun appendText(value: String) {
        if (value.isEmpty()) return
        builder.append(value)
        lastTextChar = value.last()
    }

    fun appendText(value: Char) {
        builder.append(value)
        lastTextChar = value
    }

    fun push(mark: InlineMarkup) {
        mark.spanStyle?.let(builder::pushStyle)
        mark.link?.let(builder::pushLink)
        markup.addLast(mark)
    }

    fun pop(tag: String) {
        val index = markup.indexOfLast { it.tag == tag }
        if (index < 0) return
        repeat(markup.size - index) {
            markup.removeLast()
            builder.pop()
        }
    }

    fun newBuilder() {
        builder = AnnotatedString.Builder()
        markup.forEach { mark ->
            mark.spanStyle?.let(builder::pushStyle)
            mark.link?.let(builder::pushLink)
        }
        lastTextChar = null
    }

    fun flush() {
        val built = builder.toAnnotatedString().trimmed()
        if (built.length > 0) blocks += NovelContentBlock.Text(built, kind)
        newBuilder()
        kind = NovelTextBlockKind.Paragraph
    }

    htmlTokenRegex.findAll(html)
        .map { it.value }
        .forEach { token ->
            if (!token.startsWith('<')) {
                val decoded = decodeHtmlEntities(token)
                val normalized = if (preformatted) decoded else decoded.replace(whitespaceRegex, " ")
                if (normalized.isNotEmpty()) {
                    if (!preformatted && builder.length > 0 && lastTextChar?.isWhitespace() == false && normalized.first().isWhitespace()) {
                        appendText(' ')
                        appendText(normalized.trimStart())
                    } else if (!preformatted && builder.length == 0) {
                        appendText(normalized.trimStart())
                    } else {
                        appendText(normalized)
                    }
                }
                return@forEach
            }
            if (token.startsWith("<!--")) return@forEach

            val raw = token.removePrefix("<").removeSuffix(">").trim()
            val closing = raw.startsWith('/')
            val selfClosing = raw.endsWith('/')
            val body = raw.removePrefix("/").removeSuffix("/").trim()
            val tagEnd = body.indexOfFirst(Char::isWhitespace).takeIf { it >= 0 } ?: body.length
            val tag = body.substring(0, tagEnd).lowercase().substringAfter(':')

            if (closing) {
                when {
                    tag in blockTags -> flush()
                    tag in styledBlockTags -> {
                        pop(tag)
                        flush()
                        preformatted = false
                    }
                    tag == "tr" -> flush()
                    tag == "li" -> flush()
                    tag == "ol" -> {
                        orderedListDepth = (orderedListDepth - 1).coerceAtLeast(0)
                        if (orderedListIndexes.isNotEmpty()) orderedListIndexes.removeLast()
                    }
                    tag in inlineTags -> pop(tag)
                }
                return@forEach
            }

            val attributes = parseHtmlAttributes(body.substring(tagEnd))
            when {
                tag in blockTags -> flush()
                tag == "br" -> appendText('\n')
                tag == "hr" -> {
                    flush()
                    blocks += NovelContentBlock.Rule
                }
                tag in headingTags -> {
                    flush()
                    kind = NovelTextBlockKind.entries[tag.drop(1).toInt().coerceIn(1, 6)]
                    push(InlineMarkup(tag, boldStyle))
                }
                tag == "blockquote" -> {
                    flush()
                    kind = NovelTextBlockKind.BlockQuote
                    push(InlineMarkup(tag, italicStyle))
                }
                tag == "pre" -> {
                    flush()
                    preformatted = true
                    kind = NovelTextBlockKind.Preformatted
                    push(InlineMarkup(tag, monospaceStyle))
                }
                tag == "ol" -> {
                    orderedListDepth += 1
                    orderedListIndexes += 0
                }
                tag == "li" -> {
                    flush()
                    if (orderedListDepth > 0 && orderedListIndexes.isNotEmpty()) {
                        val next = orderedListIndexes.last() + 1
                        orderedListIndexes[orderedListIndexes.lastIndex] = next
                        appendText("$next. ")
                    } else {
                        appendText("• ")
                    }
                }
                tag == "tr" -> {
                    flush()
                    kind = NovelTextBlockKind.TableRow
                }
                tag == "td" || tag == "th" -> {
                    if (builder.length > 0) appendText("  |  ")
                    if (tag == "th") push(InlineMarkup(tag, boldStyle))
                }
                tag in inlineStyles -> push(InlineMarkup(tag, inlineStyles[tag]))
                tag == "span" -> push(InlineMarkup(tag, parseInlineCss(attributes["style"].orEmpty())))
                tag == "a" -> {
                    val href = resolveNovelReference(baseUrl, attributes["href"].orEmpty())
                    if (href.isNotBlank()) {
                        push(
                            InlineMarkup(
                                tag = tag,
                                link = LinkAnnotation.Url(
                                    url = href,
                                    styles = linkStyles,
                                    linkInteractionListener = linkListener,
                                ),
                            ),
                        )
                    }
                }
                tag in imageTags -> {
                    val src = attributes["src"].orEmpty().ifBlank {
                        attributes["srcset"].orEmpty().substringBefore(',').trim().substringBefore(' ')
                    }
                    if (src.isNotBlank()) {
                        flush()
                        val embedded = embeddedImage(src)
                        val source = if (embedded != null) {
                            NovelImageSource.Embedded(embedded, normalizeArchiveEntry(src))
                        } else {
                            NovelImageSource.Remote(resolveNovelReference(baseUrl, src))
                        }
                        blocks += NovelContentBlock.Image(
                            source = source,
                            reference = src,
                            alt = decodeHtmlEntities(attributes["alt"].orEmpty()).ifBlank { src.substringAfterLast('/') },
                        )
                    }
                }
            }

            if (selfClosing && tag in inlineTags) pop(tag)
        }
    flush()

    val plainText = blocks.mapNotNull { block ->
        when (block) {
            is NovelContentBlock.Text -> block.text.text
            is NovelContentBlock.Image -> block.alt.takeIf(String::isNotBlank)
            NovelContentBlock.Rule -> null
        }
    }.joinToString("\n\n")
    return NovelRichContent(blocks = blocks, plainText = plainText)
}

private fun parseHtmlAttributes(raw: String): Map<String, String> = buildMap {
    htmlAttributeRegex.findAll(raw).forEach { match ->
        val name = match.groupValues[1].lowercase()
        val value = match.groupValues.drop(2).firstOrNull { it.isNotEmpty() }.orEmpty()
        if (name.isNotBlank()) put(name, decodeHtmlEntities(value))
    }
}

private fun parseInlineCss(style: String): SpanStyle? {
    if (style.isBlank()) return null
    val declarations = style.split(';').mapNotNull { declaration ->
        val key = declaration.substringBefore(':', "").trim().lowercase()
        val value = declaration.substringAfter(':', "").trim().lowercase()
        key.takeIf(String::isNotBlank)?.let { it to value }
    }.toMap()
    val weight = declarations["font-weight"]
    val fontStyle = declarations["font-style"]
    val decoration = declarations["text-decoration"]
    val foreground = parseCssColor(declarations["color"])
    val background = parseCssColor(declarations["background-color"] ?: declarations["background"])
    return SpanStyle(
        color = foreground ?: Color.Unspecified,
        background = background ?: Color.Unspecified,
        fontWeight = if (weight == "bold" || weight?.toIntOrNull()?.let { it >= 600 } == true) FontWeight.Bold else null,
        fontStyle = if (fontStyle == "italic" || fontStyle == "oblique") FontStyle.Italic else null,
        textDecoration = when {
            decoration?.contains("line-through") == true -> TextDecoration.LineThrough
            decoration?.contains("underline") == true -> TextDecoration.Underline
            else -> null
        },
    )
}

private fun parseCssColor(value: String?): Color? {
    val text = value?.trim()?.lowercase().orEmpty()
    if (text.isBlank()) return null
    namedCssColors[text]?.let { return Color(it.toInt()) }
    if (!text.startsWith('#')) return null
    val hex = text.drop(1)
    val argb = when (hex.length) {
        3 -> "ff${hex.map { "$it$it" }.joinToString("")}"
        4 -> "${hex[3]}${hex[3]}${hex.take(3).map { "$it$it" }.joinToString("")}"
        6 -> "ff$hex"
        8 -> hex
        else -> return null
    }
    return argb.toLongOrNull(16)?.toInt()?.let(::Color)
}

internal fun resolveNovelReference(base: String, reference: String): String {
    val ref = decodeHtmlEntities(reference).trim()
    if (ref.isBlank() || ref.startsWith("data:") || ref.startsWith("file:") || "://" in ref) return ref
    if (ref.startsWith("//")) return "${base.substringBefore(':', "https")}:$ref"
    if (base.isBlank()) return ref
    val suffixIndex = ref.indexOfFirst { it == '?' || it == '#' }.takeIf { it >= 0 } ?: ref.length
    val refPath = ref.substring(0, suffixIndex)
    val suffix = ref.substring(suffixIndex)
    val schemeIndex = base.indexOf("://")
    if (schemeIndex < 0) return normalizeArchiveEntry(
        if (refPath.startsWith('/')) refPath else "${base.substringBeforeLast('/', "")}/$refPath",
    ) + suffix
    val originEnd = base.indexOf('/', schemeIndex + 3).takeIf { it >= 0 } ?: base.length
    val origin = base.substring(0, originEnd)
    val basePath = base.substring(originEnd).substringBefore('?').substringBefore('#')
    val combined = if (refPath.startsWith('/')) refPath else "${basePath.substringBeforeLast('/', "")}/$refPath"
    return origin + "/" + normalizeArchiveEntry(combined).trimStart('/') + suffix
}

internal fun resolveEpubResourcePath(chapterHref: String, reference: String): String {
    val clean = reference.substringBefore('?').substringBefore('#').replace("%20", " ")
    val combined = if (clean.startsWith('/')) clean else "${chapterHref.substringBeforeLast('/', "")}/$clean"
    return normalizeArchiveEntry(combined)
}

internal fun normalizeArchiveEntry(path: String): String {
    val output = ArrayDeque<String>()
    path.replace('\\', '/').split('/').forEach { part ->
        when (part) {
            "", "." -> Unit
            ".." -> if (output.isNotEmpty()) output.removeLast()
            else -> output.addLast(part)
        }
    }
    return output.joinToString("/")
}

private fun AnnotatedString.trimmed(): AnnotatedString {
    var start = 0
    var end = length
    while (start < end && this[start].isBoundarySpace()) start += 1
    while (end > start && this[end - 1].isBoundarySpace()) end -= 1
    return if (start == 0 && end == length) this else subSequence(start, end)
}

private fun Char.isBoundarySpace(): Boolean = this == ' ' || this == '\t'
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContent.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContent.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContent.kt).

The implementation below defines `NovelRichContentView`, `NovelTextBlock`, `NovelContentImage`, `DbNovelTextAlign.toTextAlign`.

Cross-chapter imports used by this file: [`DbNovelTextAlign`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.relocation.BringIntoViewRequester
import androidx.compose.foundation.relocation.bringIntoViewRequester
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil3.compose.AsyncImage
import coil3.compose.LocalPlatformContext
import coil3.network.NetworkHeaders
import coil3.network.httpHeaders
import coil3.request.ImageRequest
import eu.friedcutlet.yokan.database.DbNovelTextAlign

@Composable
internal fun NovelRichContentView(
    content: NovelRichContent,
    textColor: Color,
    fontSize: Int,
    lineHeight: Double,
    textAlign: DbNovelTextAlign,
    fontFamily: FontFamily,
    imageHeaders: Map<String, String>,
    paragraphSpacing: Dp,
    modifier: Modifier = Modifier,
    ttsState: NovelTtsUiState? = null,
) {
    Column(
        modifier = modifier.fillMaxWidth(),
        verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(paragraphSpacing),
    ) {
        var textIndex = 0
        content.blocks.forEach { block ->
            when (block) {
                is NovelContentBlock.Text -> {
                    val currentTextIndex = textIndex++
                    NovelTextBlock(
                        block = block,
                        textColor = textColor,
                        fontSize = fontSize,
                        lineHeight = lineHeight,
                        textAlign = textAlign.toTextAlign(),
                        fontFamily = fontFamily,
                        ttsActive = ttsState?.paragraphIndex == currentTextIndex &&
                            ttsState.playback != NovelTtsPlaybackState.Stopped,
                        ttsWordStart = ttsState?.wordStart ?: -1,
                        ttsWordEnd = ttsState?.wordEnd ?: -1,
                    )
                }
                is NovelContentBlock.Image -> NovelContentImage(block, imageHeaders)
                NovelContentBlock.Rule -> HorizontalDivider(modifier = Modifier.padding(vertical = 20.dp))
            }
        }
    }
}

@Composable
private fun NovelTextBlock(
    block: NovelContentBlock.Text,
    textColor: Color,
    fontSize: Int,
    lineHeight: Double,
    textAlign: TextAlign,
    fontFamily: FontFamily,
    ttsActive: Boolean,
    ttsWordStart: Int,
    ttsWordEnd: Int,
) {
    val headingScale = novelHeadingScale(block.kind)
    val bringIntoViewRequester = remember { BringIntoViewRequester() }
    LaunchedEffect(ttsActive) {
        if (ttsActive) bringIntoViewRequester.bringIntoView()
    }
    val displayedText = remember(block.text, ttsActive, ttsWordStart, ttsWordEnd) {
        buildAnnotatedString {
            append(block.text)
            val highlightStart = ttsWordStart.coerceIn(0, block.text.length)
            val highlightEnd = ttsWordEnd.coerceIn(highlightStart, block.text.length)
            if (ttsActive && highlightEnd > highlightStart) {
                addStyle(
                    SpanStyle(background = Color(0x66FFD54F)),
                    highlightStart,
                    highlightEnd,
                )
            }
        }
    }
    val blockModifier = when (block.kind) {
        NovelTextBlockKind.BlockQuote -> Modifier
            .fillMaxWidth()
            .border(width = 0.dp, color = Color.Transparent)
            .padding(vertical = 10.dp)
        NovelTextBlockKind.Preformatted -> Modifier
            .fillMaxWidth()
            .clip(RoundedCornerShape(8.dp))
            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f))
            .padding(8.dp)
        NovelTextBlockKind.TableRow -> Modifier
            .fillMaxWidth()
            .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant)
            .padding(8.dp)
        else -> Modifier.fillMaxWidth()
    }.bringIntoViewRequester(bringIntoViewRequester)
    val paragraph = @Composable {
        SelectionContainer {
            Text(
                text = displayedText,
                modifier = blockModifier,
                color = textColor,
                fontSize = (fontSize * headingScale).sp,
                lineHeight = (fontSize * headingScale * lineHeight).sp,
                textAlign = textAlign,
                fontFamily = if (block.kind == NovelTextBlockKind.Preformatted) FontFamily.Monospace else fontFamily,
                fontWeight = if (block.kind.name.startsWith("Heading")) FontWeight.Bold else null,
            )
        }
    }
    if (block.kind == NovelTextBlockKind.BlockQuote) {
        Row(modifier = Modifier.fillMaxWidth().padding(vertical = 10.dp)) {
            Box(
                Modifier
                    .width(4.dp)
                    .heightIn(min = 32.dp)
                    .align(Alignment.CenterVertically)
                    .background(MaterialTheme.colorScheme.outline),
            )
            Box(Modifier.weight(1f).padding(start = 15.dp)) { paragraph() }
        }
    } else {
        paragraph()
    }
}

@Composable
internal fun NovelContentImage(
    block: NovelContentBlock.Image,
    headers: Map<String, String>,
    maxHeight: Dp = 720.dp,
    fixedHeight: Dp? = null,
) {
    val context = LocalPlatformContext.current
    var failed by remember(block.source) { mutableIntStateOf(0) }
    val model = remember(context, block.source, headers) {
        when (val source = block.source) {
            is NovelImageSource.Embedded -> ImageRequest.Builder(context)
                .data(source.bytes)
                .memoryCacheKey("epub:${source.cacheKey}:${source.bytes.size}")
                .build()
            is NovelImageSource.Remote -> ImageRequest.Builder(context)
                .data(source.url)
                .apply {
                    if (headers.isNotEmpty()) {
                        httpHeaders(
                            NetworkHeaders.Builder().apply {
                                headers.forEach { (name, value) -> set(name, value) }
                            }.build(),
                        )
                    }
                }
                .build()
        }
    }
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .then(if (fixedHeight == null) Modifier.padding(vertical = 8.dp) else Modifier)
            .then(if (fixedHeight != null) Modifier.height(fixedHeight) else Modifier),
        contentAlignment = Alignment.Center,
    ) {
        if (failed == 0) {
            AsyncImage(
                model = model,
                contentDescription = block.alt,
                contentScale = ContentScale.Fit,
                modifier = Modifier
                    .fillMaxWidth()
                    .then(
                        if (fixedHeight != null) Modifier.height(fixedHeight)
                        else Modifier.heightIn(min = 32.dp, max = maxHeight.coerceAtLeast(32.dp)),
                    ),
                onError = { failed = 1 },
            )
        } else {
            Text(
                text = "Image not loaded: ${block.alt}",
                color = MaterialTheme.colorScheme.error,
                modifier = Modifier
                    .clip(RoundedCornerShape(8.dp))
                    .background(MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.35f))
                    .padding(8.dp)
                    .border(1.dp, MaterialTheme.colorScheme.error, RoundedCornerShape(8.dp))
                    .padding(8.dp),
            )
        }
    }
}

private fun DbNovelTextAlign.toTextAlign(): TextAlign = when (this) {
    DbNovelTextAlign.Left -> TextAlign.Start
    DbNovelTextAlign.Center -> TextAlign.Center
    DbNovelTextAlign.Right -> TextAlign.End
    DbNovelTextAlign.Block -> TextAlign.Justify
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLinks.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLinks.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentLinks.kt).

The implementation below defines `rememberNovelOpenLink`, `NovelContentLinkBinding`, `active`, `close`.

The source describes its contract as:

> Parsed links retain the chapter and screen which created them.

Cross-chapter imports used by this file: [`ProfileReaderContent`](../chapters/06-extension-runtimes.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContent
import kotlinx.coroutines.Job

/** Parsed links retain the chapter and screen which created them. */
@Composable
internal fun rememberNovelOpenLink(
    content: ProfileReaderContent,
    chapterId: Long,
    onOpenLink: (String) -> Unit,
): (String) -> Unit {
    val scope = rememberCoroutineScope()
    val lifecycle = LocalLifecycleOwner.current.lifecycle
    val binding = remember(content, chapterId, lifecycle) {
        NovelContentLinkBinding(content, Job(scope.coroutineContext[Job])) {
            lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)
        }
    }
    val currentOpenLink by rememberUpdatedState(onOpenLink)
    DisposableEffect(binding) { onDispose { binding.close() } }
    return remember(binding) {
        { link -> if (binding.active()) currentOpenLink(link) }
    }
}

internal class NovelContentLinkBinding(
    private val content: ProfileReaderContent,
    private val job: Job,
    private val isScreenActive: () -> Boolean,
) {
    fun active(): Boolean = job.isActive && content.isAvailable && isScreenActive()
    fun close() = job.cancel()
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContent.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContent.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContent.kt).

The implementation below defines `loadNovelEmbeddedImages`.

The source describes its contract as:

> Reads each embedded image \[html\] references once, with backpressure and a per-chapter budget.

```kotlin
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<String, ByteArray> {
    val images = mutableMapOf<String, ByteArray?>()
    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) } }
}
```
[chapter-file-end]: #

### Check your understanding

Load a chapter with relative images and internal/external links, then switch chapters before an image resolves. Verify resolution uses the original base and cannot publish into the replacement chapter.
[chapter-content-end]: #


## Step 2: build scroll mode

Render rich content with font family/size, line spacing, margins, foreground/background and alignment preferences. Convert measured scroll state into stable progress; avoid dividing by zero before content is measured. Restore after font/orientation changes using the reference progress/anchor policy. A layout remeasurement is not a new reading session.

[chapter-content-start]: #
### Follow the code

Scroll coordinates depend on measured content and typography. The progress policy converts them into a persisted/readable representation while guarding unmeasured or zero-size layouts. Follow restoration separately from user scrolling: applying a saved anchor must not immediately overwrite it with a temporary top-of-page measurement. The same reading session continues when font or orientation changes.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelScrollProgress.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelScrollProgress.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelScrollProgress.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelScrollProgress.kt).

The implementation below defines `parseNovelProgressRatio`, `novelProgressRatio`, `novelProgressIsRead`, `novelScrollOffset`, `novelProgressPercent`, `NovelScrollProgressEffects`.

The source describes its contract as:

> Restores the persisted ratio once the scroll extent is measured, then tracks live progress from the pixel offset. \[ScrollState\] reports Int.MAX_VALUE before its first layout.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ScrollState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableDoubleState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import kotlin.math.roundToInt
import kotlinx.coroutines.flow.first

internal fun parseNovelProgressRatio(value: String): Double {
    val normalized = value.trim()
    val ratio = if (normalized.endsWith('%')) {
        normalized.dropLast(1).toDoubleOrNull()?.div(100.0)
    } else {
        normalized.toDoubleOrNull()
    }
    return ratio?.coerceIn(0.0, 1.0) ?: 0.0
}

internal fun novelProgressRatio(offsetPx: Int, maxOffsetPx: Int): Double {
    if (maxOffsetPx <= 0 || maxOffsetPx == Int.MAX_VALUE) return 0.0
    return offsetPx.coerceIn(0, maxOffsetPx).toDouble() / maxOffsetPx
}

internal fun novelProgressIsRead(ratio: Double): Boolean = ratio >= 0.9

internal fun novelScrollOffset(maxOffsetPx: Int, ratio: Double): Int {
    if (maxOffsetPx <= 0 || maxOffsetPx == Int.MAX_VALUE) return 0
    return (maxOffsetPx * ratio.coerceIn(0.0, 1.0)).roundToInt().coerceIn(0, maxOffsetPx)
}

internal fun novelProgressPercent(ratio: Double): Int = (ratio * 100.0).toInt().coerceIn(0, 100)

/**
 * Restores the persisted ratio once the scroll extent is measured, then tracks live progress from
 * the pixel offset. [ScrollState] reports Int.MAX_VALUE before its first layout.
 */
@Composable
internal fun NovelScrollProgressEffects(
    chapterId: Long,
    content: NovelRichContent?,
    loading: Boolean,
    scrollMode: Boolean,
    paged: Boolean,
    pagedLayoutMessage: Boolean,
    initialRatio: Double,
    restored: Boolean,
    scrollState: ScrollState,
    savedRatio: MutableDoubleState,
    onRestored: () -> Unit,
    onProgress: (percent: Int) -> Unit,
) {
    val currentScrollMode by rememberUpdatedState(scrollMode)
    val currentRestored by rememberUpdatedState(restored)
    LaunchedEffect(chapterId, content, loading, initialRatio, paged) {
        if (loading || restored) return@LaunchedEffect
        if (paged) {
            onRestored()
            return@LaunchedEffect
        }
        if (initialRatio <= 0.0) {
            onProgress(0)
            onRestored()
            return@LaunchedEffect
        }
        val maxOffset = snapshotFlow { scrollState.maxValue }.first { it != Int.MAX_VALUE }
        if (maxOffset > 0) {
            scrollState.animateScrollTo(
                value = novelScrollOffset(maxOffset, initialRatio),
                animationSpec = tween(durationMillis = 1_000, easing = FastOutSlowInEasing),
            )
        }
        val restoredRatio = novelProgressRatio(scrollState.value, maxOffset)
        onProgress(novelProgressPercent(restoredRatio))
        savedRatio.doubleValue = restoredRatio
        onRestored()
    }

    // Live UI progress comes from the actual pixel offset/max extent.
    LaunchedEffect(scrollState) {
        snapshotFlow { scrollState.value to scrollState.maxValue }
            .collect { (offset, maxOffset) ->
                if (currentRestored && maxOffset != Int.MAX_VALUE && currentScrollMode) {
                    val currentRatio = novelProgressRatio(offset, maxOffset)
                    onProgress(novelProgressPercent(currentRatio))
                    savedRatio.doubleValue = currentRatio
                }
            }
    }

    LaunchedEffect(paged, restored) {
        if (restored && !paged) {
            val maxOffset = scrollState.maxValue
            if (maxOffset != Int.MAX_VALUE) scrollState.scrollTo(novelScrollOffset(maxOffset, savedRatio.doubleValue))
        }
    }

    LaunchedEffect(pagedLayoutMessage, paged) {
        if (pagedLayoutMessage && paged) {
            val maxOffset = snapshotFlow { scrollState.maxValue }.first { it != Int.MAX_VALUE }
            scrollState.scrollTo(novelScrollOffset(maxOffset, savedRatio.doubleValue))
        }
    }
}
```
[chapter-file-end]: #

### Check your understanding

Restore into a chapter before its images have measured, then change font size. Check that progress converges to the same logical text rather than resetting to zero.
[chapter-content-end]: #


## Step 3: build paged mode

Implement NovelPagination and measured paged reader. Pagination depends on actual available width/height and typography. Cache/recompute against those inputs; preserve the logical reading position when page counts change. Handle oversized blocks, embedded content and empty chapters. Do not assume each HTML paragraph fits one visual page.

[chapter-content-start]: #
### Follow the code

paginateNovelBlocks receives measurement functions, keeping layout policy testable without a live renderer. Text blocks can span pages through slices with start/end offsets; image/rule blocks are atomic. Every iteration must advance a cursor or finish a nonempty page. Invalid dimensions or a measurement that cannot make progress return null instead of looping. Logical NovelAnchor values let the new page set locate the previous reading position after reflow.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagination.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReader.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagination.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagination.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagination.kt).

Text pages store slices rather than copying rendered strings. The measureText callback must advance endExclusive and fit available height. Atomic images/rules must fit a page; invalid measurements return null. pageIndexForNovelAnchor then maps a logical position into the reflowed page list.

The implementation below defines `NovelAnchor`, `NovelPageSlice`, `NovelPage`, `NovelTextFit`, `paginateNovelBlocks`, `BuildingPage`, `finishPage`, `availableFor`, `pageIndexForNovelAnchor`, `compare` and 2 further declarations.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

internal data class NovelAnchor(val blockIndex: Int, val offset: Int = 0)

internal data class NovelPageSlice(
    val blockIndex: Int,
    val start: Int = 0,
    val endExclusive: Int = 0,
)

internal data class NovelPage(
    val slices: List<NovelPageSlice>,
    val start: NovelAnchor,
    val end: NovelAnchor,
)

internal data class NovelTextFit(val endExclusive: Int, val heightPx: Int)

internal fun paginateNovelBlocks(
    blocks: List<NovelContentBlock>,
    pageHeightPx: Int,
    spacingPx: Int,
    measureText: (NovelContentBlock.Text, start: Int, availableHeightPx: Int) -> NovelTextFit?,
    measureAtomicHeight: (NovelContentBlock) -> Int,
): List<NovelPage>? {
    if (pageHeightPx <= 0 || spacingPx < 0) return null
    if (blocks.isEmpty()) return listOf(NovelPage(emptyList(), NovelAnchor(0), NovelAnchor(0)))

    data class BuildingPage(
        val slices: MutableList<NovelPageSlice> = mutableListOf(),
        var usedHeight: Int = 0,
        var lastBlockIndex: Int? = null,
        var start: NovelAnchor? = null,
        var end: NovelAnchor? = null,
    )

    val pages = mutableListOf<NovelPage>()
    var page = BuildingPage()

    fun finishPage() {
        val start = page.start ?: return
        val end = page.end ?: return
        pages += NovelPage(page.slices.toList(), start, end)
        page = BuildingPage()
    }

    fun availableFor(blockIndex: Int): Int {
        val spacing = if (page.lastBlockIndex != null && page.lastBlockIndex != blockIndex) spacingPx else 0
        return (pageHeightPx.toLong() - page.usedHeight - spacing).coerceAtLeast(0).toInt()
    }

    blocks.forEachIndexed { blockIndex, block ->
        when (block) {
            is NovelContentBlock.Text -> {
                var cursor = 0
                while (cursor < block.text.length) {
                    val available = availableFor(blockIndex)
                    if (available <= 0) {
                        if (page.slices.isEmpty()) return null
                        finishPage()
                        continue
                    }
                    val fit = measureText(block, cursor, available)
                    if (fit == null) {
                        if (page.slices.isEmpty()) return null
                        finishPage()
                        continue
                    }
                    if (fit.endExclusive <= cursor || fit.endExclusive > block.text.length ||
                        fit.heightPx <= 0 || fit.heightPx > available
                    ) return null

                    val spacing = if (page.lastBlockIndex != null && page.lastBlockIndex != blockIndex) spacingPx else 0
                    page.usedHeight += spacing + fit.heightPx
                    page.slices += NovelPageSlice(blockIndex, cursor, fit.endExclusive)
                    if (page.start == null) page.start = NovelAnchor(blockIndex, cursor)
                    page.end = if (fit.endExclusive == block.text.length) {
                        NovelAnchor(blockIndex + 1)
                    } else {
                        NovelAnchor(blockIndex, fit.endExclusive)
                    }
                    page.lastBlockIndex = blockIndex
                    cursor = fit.endExclusive
                    if (cursor < block.text.length) finishPage()
                }
                if (block.text.isEmpty()) {
                    // Empty text contributes no rendered content or page slice.
                }
            }
            is NovelContentBlock.Image, NovelContentBlock.Rule -> {
                val height = measureAtomicHeight(block)
                if (height <= 0 || height > pageHeightPx) return null
                val spacing = if (page.lastBlockIndex != null && page.lastBlockIndex != blockIndex) spacingPx else 0
                if (height.toLong() + spacing > pageHeightPx - page.usedHeight) {
                    if (page.slices.isEmpty()) return null
                    finishPage()
                }
                val actualSpacing = if (page.lastBlockIndex != null && page.lastBlockIndex != blockIndex) spacingPx else 0
                page.usedHeight += actualSpacing + height
                page.slices += NovelPageSlice(blockIndex)
                if (page.start == null) page.start = NovelAnchor(blockIndex)
                page.end = NovelAnchor(blockIndex + 1)
                page.lastBlockIndex = blockIndex
            }
        }
    }
    finishPage()
    return pages
}

internal fun pageIndexForNovelAnchor(pages: List<NovelPage>, anchor: NovelAnchor): Int {
    if (pages.isEmpty()) return 0
    fun compare(left: NovelAnchor, right: NovelAnchor): Int =
        compareValuesBy(left, right, NovelAnchor::blockIndex, NovelAnchor::offset)

    return pages.indexOfFirst { compare(anchor, it.start) >= 0 && compare(anchor, it.end) < 0 }
        .takeIf { it >= 0 }
        ?: if (compare(anchor, pages.first().start) < 0) 0 else pages.lastIndex
}

internal fun novelSpreadCount(pageCount: Int, panes: Int): Int {
    if (pageCount <= 0 || panes <= 0) return 0
    return (pageCount - 1) / panes + 1
}

internal fun novelSpreadForPage(pageIndex: Int, panes: Int): Int {
    if (pageIndex < 0 || panes <= 0) return 0
    return pageIndex / panes
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReader.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReader.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReader.kt).

The implementation below defines `NovelPagedReader`, `BoxWithReaderSize`, `NovelPagedPage`, `novelBlockStyle`, `measureNovelTextFit`, `measureNovelBlankLine`, `renderNovelTextFragment`, `isNovelLineBreakAt`, `novelLineBreakLengthAt`, `novelLineBreakEnd` and 2 further declarations.

Cross-chapter imports used by this file: [`DbNovelPageMode`](../chapters/02-domain-and-settings-models.md), [`DbNovelTextAlign`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.NavigateBefore
import androidx.compose.material.icons.automirrored.filled.NavigateNext
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalDensity
import eu.friedcutlet.yokan.database.DbNovelPageMode
import eu.friedcutlet.yokan.database.DbNovelTextAlign
import kotlin.math.ceil
import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

private const val MIN_PANE_WIDTH_DP = 360
private val PAGE_FOOTER_HEIGHT = 48.dp

@Composable
internal fun NovelPagedReader(
    content: NovelRichContent,
    pageMode: DbNovelPageMode,
    reverseLayout: Boolean = false,
    requestedPageRatio: Double,
    sourceAnchor: NovelAnchor?,
    fontSize: Int,
    lineHeight: Double,
    textAlign: DbNovelTextAlign,
    fontFamily: FontFamily,
    textColor: androidx.compose.ui.graphics.Color,
    imageHeaders: Map<String, String>,
    ttsState: NovelTtsUiState? = null,
    paragraphSpacing: androidx.compose.ui.unit.Dp,
    padding: androidx.compose.ui.unit.Dp,
    onPageChanged: (NovelAnchor, Double) -> Unit,
    onComplete: (NovelAnchor, Double) -> Unit,
    onInvalidLayout: () -> Unit,
    onPagesReady: (List<NovelPage>) -> Unit = {},
    modifier: Modifier = Modifier,
) {
    BoxWithReaderSize(modifier) { widthPx, heightPx ->
        val density = LocalDensity.current
        val widthDp = with(density) { widthPx.toDp() }
        val panes = when (pageMode) {
            DbNovelPageMode.Single -> 1
            DbNovelPageMode.Double -> if (widthDp >= (MIN_PANE_WIDTH_DP * 2).dp) 2 else 1
            DbNovelPageMode.Auto -> if (widthDp >= (MIN_PANE_WIDTH_DP * 2).dp) 2 else 1
        }
        val paneWidthPx = (widthPx - with(density) { padding.toPx() * 2 } -
            with(density) { if (panes == 2) paragraphSpacing.toPx() else 0f }).toInt() / panes
        val pageHeightPx = (heightPx - with(density) { padding.toPx() * 2 + PAGE_FOOTER_HEIGHT.toPx() }).toInt()
        val textMeasurer = rememberTextMeasurer()
        val spacingPx = with(density) { paragraphSpacing.roundToPx() }
        val themeBodyStyle = MaterialTheme.typography.bodyLarge
        val bodyStyle = remember(fontSize, lineHeight, textAlign, fontFamily, textColor, themeBodyStyle) {
            themeBodyStyle.merge(TextStyle(
                color = textColor,
                fontSize = fontSize.sp,
                lineHeight = (fontSize * lineHeight).sp,
                textAlign = when (textAlign) {
                    DbNovelTextAlign.Left -> TextAlign.Start
                    DbNovelTextAlign.Center -> TextAlign.Center
                    DbNovelTextAlign.Right -> TextAlign.End
                    DbNovelTextAlign.Block -> TextAlign.Justify
                },
                fontFamily = fontFamily,
            ))
        }
        val atomicHeight = with(density) { 220.dp.roundToPx() }.coerceAtMost((pageHeightPx * 0.45f).toInt().coerceAtLeast(32))
        val pages = remember(
            content.blocks, paneWidthPx, pageHeightPx, spacingPx, fontSize, lineHeight,
            textAlign, fontFamily, textColor, atomicHeight,
        ) {
            if (paneWidthPx <= 0 || pageHeightPx <= 0) null else paginateNovelBlocks(
                content.blocks,
                pageHeightPx,
                spacingPx,
                measureText = { block, start, available ->
                    val style = novelBlockStyle(block, bodyStyle, fontSize, lineHeight)
                    measureNovelTextFit(textMeasurer, block, start, available, paneWidthPx, style)
                },
                measureAtomicHeight = { block ->
                    when (block) {
                        is NovelContentBlock.Image -> atomicHeight
                        NovelContentBlock.Rule -> with(density) { 24.dp.roundToPx() }
                        is NovelContentBlock.Text -> 0
                    }
                },
            )
        }

        if (pages == null || pages.isEmpty()) {
            LaunchedEffect(pages == null) { onInvalidLayout() }
            return@BoxWithReaderSize
        }
        LaunchedEffect(pages) { onPagesReady(pages) }
        val spreadCount = novelSpreadCount(pages.size, panes)
        val initialPage = remember(pages, requestedPageRatio, sourceAnchor, panes) {
            val wantedPage = sourceAnchor?.let { pageIndexForNovelAnchor(pages, it) }
                ?: (requestedPageRatio.coerceIn(0.0, 1.0) * pages.size).toInt().coerceAtMost(pages.lastIndex)
            novelSpreadForPage(wantedPage, panes).coerceIn(0, (spreadCount - 1).coerceAtLeast(0))
        }
        val pagerState = rememberPagerState(initialPage = initialPage, pageCount = { spreadCount })
        val scope = rememberCoroutineScope()
        LaunchedEffect(pages, pagerState, sourceAnchor, panes, requestedPageRatio) {
            val targetPage = sourceAnchor?.let { pageIndexForNovelAnchor(pages, it) }
                ?: (requestedPageRatio.coerceIn(0.0, 1.0) * pages.size).toInt().coerceAtMost(pages.lastIndex)
            pagerState.scrollToPage(novelSpreadForPage(targetPage.coerceIn(0, pages.lastIndex), panes))
        }
        LaunchedEffect(pages, pagerState, panes) {
            snapshotFlow { pagerState.currentPage }
                .drop(1)
                .collect { spread ->
                    val pageIndex = (spread * panes).coerceAtMost(pages.lastIndex)
                    onPageChanged(pages[pageIndex].start, (pageIndex + 1.0) / pages.size.coerceAtLeast(1))
                }
        }
        HorizontalPager(
            state = pagerState,
            modifier = Modifier.fillMaxSize().padding(padding).padding(bottom = PAGE_FOOTER_HEIGHT),
            reverseLayout = reverseLayout,
            key = { it },
        ) { spread ->
            Row(
                modifier = Modifier.fillMaxSize(),
                horizontalArrangement = Arrangement.spacedBy(paragraphSpacing),
            ) {
                repeat(panes) { pane ->
                    val pageIndex = spread * panes + pane
                    if (pageIndex < pages.size) {
                        NovelPagedPage(
                            page = pages[pageIndex],
                            blocks = content.blocks,
                            widthPx = paneWidthPx,
                            fontSize = fontSize,
                            lineHeight = lineHeight,
                            bodyStyle = bodyStyle,
                            textAlign = textAlign,
                            fontFamily = fontFamily,
                            textColor = textColor,
                            imageHeaders = imageHeaders,
                            ttsState = ttsState,
                            paragraphSpacing = paragraphSpacing,
                            imageMaxHeight = with(density) { atomicHeight.toDp() },
                            modifier = Modifier.weight(1f).fillMaxHeight(),
                        )
                    } else {
                        Spacer(Modifier.weight(1f).fillMaxHeight())
                    }
                }
            }
        }
        val eink = eu.friedcutlet.yokan.ui.theme.LocalEinkMode.current
        Row(
            modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 4.dp),
            verticalAlignment = Alignment.CenterVertically,
        ) {
            IconButton(
                enabled = pagerState.currentPage > 0,
                onClick = { scope.launch { if (eink) pagerState.scrollToPage(pagerState.currentPage - 1) else pagerState.animateScrollToPage(pagerState.currentPage - 1) } },
            ) {
                Icon(Icons.AutoMirrored.Filled.NavigateBefore, contentDescription = "Previous page")
            }
            Text(
                text = "${(pagerState.currentPage * panes + 1).coerceAtMost(pages.size)}–${((pagerState.currentPage + 1) * panes).coerceAtMost(pages.size)} / ${pages.size}",
                style = MaterialTheme.typography.labelSmall,
                color = textColor.copy(alpha = 0.72f),
            )
            IconButton(
                enabled = pagerState.currentPage < spreadCount - 1 || requestedPageRatio < 1.0,
                onClick = {
                    if (pagerState.currentPage < spreadCount - 1) {
                        scope.launch { if (eink) pagerState.scrollToPage(pagerState.currentPage + 1) else pagerState.animateScrollToPage(pagerState.currentPage + 1) }
                    } else {
                        onComplete(pages.last().end, 1.0)
                    }
                },
            ) {
                Icon(
                    Icons.AutoMirrored.Filled.NavigateNext,
                    contentDescription = if (pagerState.currentPage < spreadCount - 1) "Next page" else "Mark chapter read",
                )
            }
        }
    }
}

@Composable
private fun BoxWithReaderSize(
    modifier: Modifier,
    content: @Composable androidx.compose.foundation.layout.BoxWithConstraintsScope.(Int, Int) -> Unit,
) {
    androidx.compose.foundation.layout.BoxWithConstraints(modifier = modifier.fillMaxSize()) {
        val density = LocalDensity.current
        val width = with(density) { maxWidth.roundToPx() }
        val height = with(density) { maxHeight.roundToPx() }
        content(width, height)
    }
}

@Composable
private fun NovelPagedPage(
    page: NovelPage,
    blocks: List<NovelContentBlock>,
    widthPx: Int,
    fontSize: Int,
    lineHeight: Double,
    bodyStyle: TextStyle,
    textAlign: DbNovelTextAlign,
    fontFamily: FontFamily,
    textColor: androidx.compose.ui.graphics.Color,
    imageHeaders: Map<String, String>,
    ttsState: NovelTtsUiState?,
    paragraphSpacing: androidx.compose.ui.unit.Dp,
    imageMaxHeight: androidx.compose.ui.unit.Dp,
    modifier: Modifier = Modifier,
) {
    Column(
        modifier = modifier,
        verticalArrangement = Arrangement.spacedBy(paragraphSpacing),
    ) {
        page.slices.forEach { slice ->
            when (val block = blocks.getOrNull(slice.blockIndex)) {
                is NovelContentBlock.Text -> {
                    val fragment = block.copy(text = renderNovelTextFragment(block.text, slice.start, slice.endExclusive))
                    val textIndex = blocks.take(slice.blockIndex).count { it is NovelContentBlock.Text }
                    val displayText = remember(fragment.text, textIndex, ttsState) {
                        buildAnnotatedString {
                            append(fragment.text)
                            if (ttsState?.playback != NovelTtsPlaybackState.Stopped && ttsState?.paragraphIndex == textIndex) {
                                val start = (ttsState.wordStart - slice.start).coerceIn(0, fragment.text.length)
                                val end = (ttsState.wordEnd - slice.start).coerceIn(start, fragment.text.length)
                                if (end > start) addStyle(SpanStyle(background = androidx.compose.ui.graphics.Color(0x66FFD54F)), start, end)
                            }
                        }
                    }
                    androidx.compose.material3.Text(
                        text = displayText,
                        style = novelBlockStyle(block, bodyStyle, fontSize, lineHeight),
                        modifier = Modifier.fillMaxWidth().then(
                            when (block.kind) {
                                NovelTextBlockKind.Preformatted -> Modifier
                                    .clip(RoundedCornerShape(8.dp))
                                    .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f))
                                NovelTextBlockKind.TableRow -> Modifier.border(0.5.dp, MaterialTheme.colorScheme.outlineVariant)
                                else -> Modifier
                            },
                        ),
                    )
                }
                is NovelContentBlock.Image -> NovelContentImage(block, imageHeaders, imageMaxHeight, imageMaxHeight)
                NovelContentBlock.Rule -> Box(
                    modifier = Modifier.fillMaxWidth().height(24.dp),
                    contentAlignment = Alignment.Center,
                ) { androidx.compose.material3.HorizontalDivider() }
                null -> Unit
            }
        }
    }
}

private fun novelBlockStyle(block: NovelContentBlock.Text, base: TextStyle, fontSize: Int, lineHeight: Double) =
    base.copy(
        fontSize = (fontSize * novelHeadingScale(block.kind)).sp,
        lineHeight = (fontSize * novelHeadingScale(block.kind) * lineHeight).sp,
        fontFamily = if (block.kind == NovelTextBlockKind.Preformatted) FontFamily.Monospace else base.fontFamily,
        fontWeight = if (block.kind.name.startsWith("Heading")) FontWeight.Bold else null,
    )

internal fun measureNovelTextFit(
    textMeasurer: TextMeasurer,
    block: NovelContentBlock.Text,
    start: Int,
    availableHeightPx: Int,
    widthPx: Int,
    style: TextStyle,
): NovelTextFit? {
    if (start !in 0 until block.text.length || availableHeightPx <= 0 || widthPx <= 0) return null
    var visibleStart = start
    var isPageDelimiter = false
    if (isNovelLineBreakAt(block.text, start)) {
        val breakEnd = novelLineBreakEnd(block.text, start)
        isPageDelimiter = start > 0 && !isNovelLineBreakAt(block.text, start - 1) && breakEnd < block.text.length
        if (isPageDelimiter) {
            if (isNovelLineBreakAt(block.text, breakEnd)) {
                val blankEnd = novelLineBreakEnd(block.text, breakEnd)
                val blankHeight = measureNovelBlankLine(textMeasurer, style, widthPx)
                return NovelTextFit(blankEnd, blankHeight).takeIf { blankHeight in 1..availableHeightPx }
            }
            visibleStart = breakEnd
        } else {
            val blankHeight = measureNovelBlankLine(textMeasurer, style, widthPx)
            return NovelTextFit(breakEnd, blankHeight).takeIf { blankHeight in 1..availableHeightPx }
        }
    }
    if (visibleStart >= block.text.length) return null
    val remaining = block.text.subSequence(visibleStart, block.text.length)
    val fullLayout = textMeasurer.measure(remaining, style, constraints = Constraints(maxWidth = widthPx))
    for (line in fullLayout.lineCount - 1 downTo 0) {
        if (ceil(fullLayout.getLineBottom(line)).toInt() > availableHeightPx) continue
        val candidateEnds = listOf(
            fullLayout.getLineEnd(line, visibleEnd = false),
            fullLayout.getLineEnd(line, visibleEnd = true),
        ).distinct().sortedDescending()
        for (candidate in candidateEnds) {
            var logicalEnd = visibleStart + candidate
            if (logicalEnd > start && logicalEnd < block.text.length &&
                block.text[logicalEnd - 1] == '\r' && block.text[logicalEnd] == '\n'
            ) logicalEnd++
            if (logicalEnd <= start) continue
            if (isPageDelimiter && logicalEnd <= visibleStart) continue
            val exactFragment = renderNovelTextFragment(block.text, start, logicalEnd)
            val exactLayout = textMeasurer.measure(exactFragment, style, constraints = Constraints(maxWidth = widthPx))
            val exactHeight = if (exactLayout.lineCount == 0) 0
            else ceil(exactLayout.getLineBottom(exactLayout.lineCount - 1)).toInt()
            if (exactHeight in 1..availableHeightPx) return NovelTextFit(logicalEnd, exactHeight)
        }
    }
    return null
}

private fun measureNovelBlankLine(textMeasurer: TextMeasurer, style: TextStyle, widthPx: Int): Int =
    textMeasurer.measure(AnnotatedString("\u00A0"), style, constraints = Constraints(maxWidth = widthPx))
        .let { ceil(it.getLineBottom(0)).toInt() }

internal fun renderNovelTextFragment(text: AnnotatedString, start: Int, end: Int): AnnotatedString {
    require(start in 0..text.length && end in start..text.length)
    var visibleStart = start
    var visibleEnd = end

    if (isNovelLineBreakAt(text, visibleStart)) {
        val breakEnd = novelLineBreakEnd(text, visibleStart)
        val hasPriorVisibleLine = start > 0 && !isNovelLineBreakAt(text, start - 1)
        if (hasPriorVisibleLine && breakEnd < text.length) visibleStart = breakEnd
        else if (visibleEnd <= breakEnd) return AnnotatedString("\u00A0")
    }
    val contentBeforeTrailingBreak = text.subSequence(visibleStart, visibleEnd)
    if (contentBeforeTrailingBreak.text.isNotEmpty() && contentBeforeTrailingBreak.text.all { it == '\n' || it == '\r' }) {
        val blanks = novelLineBreakCount(contentBeforeTrailingBreak.text).coerceAtLeast(1)
        return AnnotatedString(List(blanks) { "\u00A0" }.joinToString("\n"))
    }
    if (visibleEnd < text.length && visibleEnd > visibleStart && isNovelLineBreakAt(text, visibleEnd - 1)) {
        val breakEndIndex = visibleEnd - 1
        val breakLength = if (text[breakEndIndex] == '\n' && breakEndIndex > 0 && text[breakEndIndex - 1] == '\r') 2
        else novelLineBreakLengthAt(text, breakEndIndex)
        visibleEnd -= breakLength
    }
    if (visibleEnd <= visibleStart) return AnnotatedString("")
    return text.subSequence(visibleStart, visibleEnd)
}

private fun isNovelLineBreakAt(text: AnnotatedString, index: Int): Boolean =
    index in 0 until text.length && (text[index] == '\n' || text[index] == '\r')

private fun novelLineBreakLengthAt(text: AnnotatedString, index: Int): Int =
    if (text[index] == '\r' && index + 1 < text.length && text[index + 1] == '\n') 2 else 1

private fun novelLineBreakEnd(text: AnnotatedString, index: Int): Int = index + novelLineBreakLengthAt(text, index)

private fun novelLineBreakCount(text: String): Int {
    var count = 0
    var index = 0
    while (index < text.length) {
        if (text[index] == '\r' && index + 1 < text.length && text[index + 1] == '\n') index++
        count++
        index++
    }
    return count
}

internal fun novelHeadingScale(kind: NovelTextBlockKind): Float = when (kind) {
    NovelTextBlockKind.Heading1 -> 1.8f
    NovelTextBlockKind.Heading2 -> 1.6f
    NovelTextBlockKind.Heading3 -> 1.4f
    NovelTextBlockKind.Heading4 -> 1.25f
    NovelTextBlockKind.Heading5 -> 1.12f
    else -> 1f
}
```
[chapter-file-end]: #

### Check your understanding

Use a text block longer than one page and an image near the boundary. Verify every character appears once, anchors are ordered, and a nonadvancing measurement is rejected.
[chapter-content-end]: #


## Step 4: implement ViewModel and reader chrome

Connect loading/error/retry, chapter navigation, current page/progress, settings and visibility. Use NovelReaderRoute to bind the profile and finalizer. Reuse reading-time/history/completion policy with novel-specific units. Add reader settings content/screen and persist media defaults/per-title overrides according to the original contract.

[chapter-content-start]: #
### Follow the code

The ViewModel coordinates loading, chapter sequence, saved progress and current settings; the route captures the owner and registers awaited finalization. The screen chooses scroll or paged rendering from the same logical state. Settings update typography/layout and can trigger reflow, but should not recreate chapter identity or reading time. Final progress/history goes through the repository with novel-specific units and incognito policy.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModel.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderRoute.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderScreen.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderChrome.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsContent.kt`
- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsScreen.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModel.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModel.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModel.kt).

The implementation below defines `NovelReaderViewModel`, `onCleared`, `onEvent`, `load`, `toggleBookmark`, `saveProgress`, `DbSettings.ttsRequest`.

The source describes its contract as:

> One novel chapter: library reads/writes, content loading, reading time, auto-scroll preferences and text-to-speech. Scroll position and layout stay in the screen.

Cross-chapter imports used by this file: [`LibraryIndexStore`](../chapters/09-repository-and-library.md), [`SettingsStore`](../chapters/09-repository-and-library.md), [`YokanRepository`](../chapters/09-repository-and-library.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.data.YokanRepository
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.database.isIncognitoFor
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.catchingNonCancellation
import eu.friedcutlet.yokan.services.extensions.webViewUserAgent
import eu.friedcutlet.yokan.services.library.readingChapterSequence
import eu.friedcutlet.yokan.services.tts.ProfileSpeechService
import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest
import eu.friedcutlet.yokan.ui.screens.ReadingSessionClock
import eu.friedcutlet.yokan.ui.screens.reader.autoScrollSettings
import eu.friedcutlet.yokan.ui.screens.reader.withAutoScrollSettings
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * One novel chapter: library reads/writes, content loading, reading time, auto-scroll preferences
 * and text-to-speech. Scroll position and layout stay in the screen.
 */
internal class NovelReaderViewModel(
    private val manga: Manga,
    chapter: Chapter,
    private val repository: YokanRepository,
    private val settings: SettingsStore,
    libraryIndex: LibraryIndexStore,
    speech: ProfileSpeechService,
    loadHeaders: suspend (Source) -> Map<String, String>,
    loadDocument: suspend (Source?, Chapter) -> NovelDocument,
    private val workDispatcher: CoroutineDispatcher = Dispatchers.Default,
) : ViewModel() {

    private val _state = MutableStateFlow(
        settings.db.value.autoScrollSettings(manga.id).let { autoScroll ->
            NovelReaderState(
                chapter = chapter,
                source = manga.sourceId?.let(repository::source),
                autoScrollEnabled = autoScroll.autoScroll,
                autoScrollPlaying = autoScroll.autoScroll,
                autoScrollOffset = autoScroll.pageOffset.toFloat(),
            )
        },
    )
    val state: StateFlow<NovelReaderState> = _state.asStateFlow()

    private val clock = ReadingSessionClock()
    private val speechReader = speech.reader()
    private val tts = NovelTtsController(speechReader, viewModelScope) { speechReader.isAvailable }

    init {
        repository.chapterOpened(chapter.id)
        viewModelScope.launch {
            combine(libraryIndex.index, settings.db) { index, db ->
                readingChapterSequence(manga, chapter.id, index.chapters(manga.id), db, index.downloadedChapterIds)
            }
                .flowOn(workDispatcher)
                .collect { all ->
                    val position = all.indexOfFirst { it.id == chapter.id }
                    _state.update {
                        it.copy(
                            previousChapter = if (position > 0) all[position - 1] else null,
                            nextChapter = if (position >= 0) all.getOrNull(position + 1) else null,
                        )
                    }
                }
        }
        viewModelScope.launch { load(loadHeaders, loadDocument) }
        viewModelScope.launch { tts.state.collect { speech -> _state.update { it.copy(tts = speech) } } }
        // Voice/rate changes apply to the utterance in progress.
        viewModelScope.launch {
            settings.db.map { it.ttsRequest() }.distinctUntilChanged().collect { request ->
                if (tts.state.value.playback != NovelTtsPlaybackState.Stopped) tts.updateRequest(request)
            }
        }
    }

    override fun onCleared() {
        tts.retire()
        speechReader.retire()
        repository.chapterClosed(state.value.chapter.id)
        super.onCleared()
    }

    fun onEvent(event: NovelReaderEvent) {
        when (event) {
            NovelReaderEvent.ToggleBookmark -> toggleBookmark()
            NovelReaderEvent.ReadingPaused -> clock.pause()
            NovelReaderEvent.ReadingResumed -> clock.resume()
            is NovelReaderEvent.SaveProgress -> {
                clock.pause()
                saveProgress(event.ratio, clock.takeSeconds())
            }
            is NovelReaderEvent.SetAutoScrollEnabled -> {
                _state.update { it.copy(autoScrollEnabled = event.enabled, autoScrollPlaying = event.enabled) }
                val offset = state.value.autoScrollOffset.toDouble()
                settings.updateDb { it.withAutoScrollSettings(manga.id, event.enabled, offset) }
            }
            is NovelReaderEvent.SetAutoScrollOffset -> {
                _state.update { it.copy(autoScrollOffset = event.offset) }
                settings.updateDb { it.withAutoScrollSettings(manga.id, true, event.offset.toDouble()) }
            }
            NovelReaderEvent.ToggleAutoScrollPlaying -> _state.update { it.copy(autoScrollPlaying = !it.autoScrollPlaying) }
            is NovelReaderEvent.StartTts -> viewModelScope.launch {
                tts.start(event.paragraphs, settings.db.value.ttsRequest())
            }
            NovelReaderEvent.ToggleTtsPlayback -> viewModelScope.launch {
                if (tts.state.value.playback == NovelTtsPlaybackState.Playing) tts.pause() else tts.resume()
            }
            NovelReaderEvent.SkipNextTts -> viewModelScope.launch { tts.skipNext() }
            NovelReaderEvent.SkipPreviousTts -> viewModelScope.launch { tts.skipPrevious() }
            NovelReaderEvent.StopTts -> viewModelScope.launch { tts.stop() }
        }
    }

    private suspend fun load(
        loadHeaders: suspend (Source) -> Map<String, String>,
        loadDocument: suspend (Source?, Chapter) -> NovelDocument,
    ) {
        val chapter = state.value.chapter
        val source = state.value.source
        val headers = source?.let { current ->
            val loaded = catchingNonCancellation { withContext(workDispatcher) { loadHeaders(current) } }
                .getOrDefault(emptyMap())
            val userAgent = settings.db.value.webViewUserAgent(current)
            if (userAgent.isBlank() || loaded.keys.any { it.equals("User-Agent", ignoreCase = true) }) loaded
            else loaded + ("User-Agent" to userAgent)
        }.orEmpty()
        var error: String? = null
        val document = catchingNonCancellation { withContext(workDispatcher) { loadDocument(source, chapter) } }
            .getOrElse { throwable ->
                error = throwable.message.orEmpty().ifBlank { throwable::class.simpleName.orEmpty() }
                NovelDocument(chapter.description ?: manga.description)
            }
        _state.update { it.copy(document = document, imageHeaders = headers, loading = false, error = error) }
    }

    private fun toggleBookmark() {
        val chapter = state.value.chapter
        repository.setChaptersBookmarked(setOf(chapter.id), !chapter.isBookmarked)
        _state.update { it.copy(chapter = it.chapter.copy(isBookmarked = !chapter.isBookmarked)) }
    }

    /** Saves the scroll ratio; incognito sessions leave no trace. */
    private fun saveProgress(ratio: Double, readingTimeSeconds: Int) {
        if (settings.db.value.isIncognitoFor(manga.sourceId)) return
        val chapterId = state.value.chapter.id
        repository.setChaptersRead(
            chapterIds = setOf(chapterId),
            isRead = novelProgressIsRead(ratio),
            lastPageRead = ratio.toString(),
            readingTimeSeconds = readingTimeSeconds,
        )
        if (novelProgressIsRead(ratio)) repository.recordChapterConsumption(setOf(chapterId))
    }
}

private fun DbSettings.ttsRequest() = TextToSpeechRequest(
    language = ttsLanguage,
    voice = ttsVoice,
    speechRate = ttsSpeechRate,
    pitch = ttsPitch,
)
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderRoute.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderRoute.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderRoute.kt).

The implementation below defines `NovelReaderRoute`.

The source describes its contract as:

> Route boundary for the novel reader: resolves \[NovelReaderViewModel\] and wires navigation.

Cross-chapter imports used by this file: [`ProfileSession`](../chapters/04-profiles-and-lifetimes.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md), [`Navigator`](../chapters/10-navigation-and-design-system.md), [`Route`](../chapters/10-navigation-and-design-system.md), [`TogetherProgressSync`](../chapters/22-together.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import eu.friedcutlet.yokan.app.profiles.ProfileSession
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.services.extensions.webViewUserAgent
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.navigation.Route
import eu.friedcutlet.yokan.ui.screens.together.TogetherProgressSync
import eu.friedcutlet.yokan.ui.screens.together.rememberOpenRoomMedia

/** Route boundary for the novel reader: resolves [NovelReaderViewModel] and wires navigation. */
@Composable
internal fun NovelReaderRoute(manga: Manga, chapter: Chapter, nav: Navigator, owner: ProfileSession) {
    val readerContent = remember(owner) { owner.readerContent }
    val viewModel = viewModel {
        NovelReaderViewModel(
            manga = manga,
            chapter = chapter,
            repository = owner.repository,
            settings = owner.settings,
            libraryIndex = owner.libraryIndex,
            speech = owner.services.textToSpeech,
            loadHeaders = readerContent::headers,
            loadDocument = { source, target -> loadNovelDocument(readerContent, source, manga.name, target) },
        )
    }
    val state by viewModel.state.collectAsStateWithLifecycle()
    val settings by owner.settings.db.collectAsStateWithLifecycle()
    val together = remember(owner) { owner.together }
    val onOpenRoomMedia = rememberOpenRoomMedia(owner, nav)
    val openWebView = { url: String ->
        val userAgent = settings.webViewUserAgent(state.source)
        if (url.isNotBlank()) nav.navigate(Route.InAppWebView(url, state.chapter.name, userAgent.takeIf { it.isNotBlank() }))
    }
    LifecycleEventEffect(Lifecycle.Event.ON_PAUSE) { viewModel.onEvent(NovelReaderEvent.ReadingPaused) }
    LifecycleEventEffect(Lifecycle.Event.ON_RESUME) { viewModel.onEvent(NovelReaderEvent.ReadingResumed) }
    NovelReaderScreen(
        manga = manga,
        state = state,
        settings = settings,
        onEvent = viewModel::onEvent,
        onBack = nav::back,
        onUpdateSettings = owner.settings::updateDb,
        onOpenChapter = { target -> nav.navigate(Route.Reader(target.mangaId, target.id)) },
        onOpenWebView = { openWebView(state.chapter.url) },
        onOpenLink = rememberNovelOpenLink(readerContent, chapter.id, openWebView),
        progressSync = { progress, onFollow ->
            TogetherProgressSync(together, manga, state.chapter, progress, onOpenRoomMedia, onFollow)
        },
    )
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderScreen.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderScreen.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderScreen.kt).

The implementation below defines `NovelReaderScreen`, `NovelReaderSettingsSheet`, `parseHexColor`.

The source describes its contract as:

> Opens the chapter's own URL in the in-app web view.

Cross-chapter imports used by this file: [`DbNovelReadingMode`](../chapters/02-domain-and-settings-models.md), [`DbReaderMode`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`Chapter`](../chapters/02-domain-and-settings-models.md), [`Manga`](../chapters/02-domain-and-settings-models.md), [`ApplyReaderSystemUi`](../chapters/14-manga-reader.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableDoubleStateOf
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbNovelReadingMode
import eu.friedcutlet.yokan.database.DbReaderMode
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Manga
import eu.friedcutlet.yokan.ui.components.compactSheetWidth
import eu.friedcutlet.yokan.ui.screens.reader.ApplyReaderSystemUi
import eu.friedcutlet.yokan.ui.screens.reader.DriveAutoScroll
import eu.friedcutlet.yokan.ui.screens.reader.ReaderAutoScrollFab
import eu.friedcutlet.yokan.ui.theme.LocalYokanScaffoldColor
import eu.friedcutlet.yokan.ui.theme.resolveNovelFontFamily
import eu.friedcutlet.yokan.ui.theme.YokanScaffold as Scaffold
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch

@Composable
internal fun NovelReaderScreen(
    manga: Manga,
    state: NovelReaderState,
    settings: DbSettings,
    onEvent: (NovelReaderEvent) -> Unit,
    onBack: () -> Unit,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    onOpenChapter: (Chapter) -> Unit,
    /** Opens the chapter's own URL in the in-app web view. */
    onOpenWebView: () -> Unit,
    /** Opens a link tapped inside the chapter text. */
    onOpenLink: (String) -> Unit,
    /** Shares/follows the scroll percentage in a Together room. */
    progressSync: @Composable (progressPercent: Int, onFollow: suspend (Double) -> Unit) -> Unit,
) {
    val chapter = state.chapter
    val richContent = remember(state.document, onOpenLink) { state.document?.parse(onOpenLink) }
    val initialProgressRatio = remember(chapter.id, chapter.lastPageRead) {
        parseNovelProgressRatio(chapter.lastPageRead)
    }
    var progress by remember(chapter.id) { mutableIntStateOf(novelProgressPercent(initialProgressRatio)) }
    var restoredProgress by remember(chapter.id) { mutableStateOf(false) }
    val savedProgressRatio = remember(chapter.id) { mutableDoubleStateOf(initialProgressRatio) }
    var pagedSourceAnchor by remember(chapter.id) { mutableStateOf<NovelAnchor?>(null) }
    var pagedLayoutMessage by remember(chapter.id) { mutableStateOf(false) }
    var chromeVisible by remember(chapter.id) { mutableStateOf(false) }
    var settingsSheetOpen by remember { mutableStateOf(false) }
    val scope = rememberCoroutineScope()
    val novelScrollState = rememberScrollState()
    val paged = settings.novelReadingMode == DbNovelReadingMode.Paged
    // Paged mode falls back to scrolling when the page is too small to paginate.
    val scrollMode = !paged || pagedLayoutMessage
    progressSync(progress) { ratio ->
        novelScrollState.scrollTo((ratio * novelScrollState.maxValue).toInt())
    }

    ApplyReaderSystemUi(
        fullscreen = settings.fullScreenReader,
        keepScreenOn = settings.keepScreenOnReader,
        chromeVisible = chromeVisible,
    )

    DriveAutoScroll(
        state = novelScrollState,
        isPlaying = state.autoScrollPlaying && !settingsSheetOpen && restoredProgress && scrollMode,
        pageOffset = state.autoScrollOffset,
    )

    NovelScrollProgressEffects(
        chapterId = chapter.id,
        content = richContent,
        loading = state.loading,
        scrollMode = scrollMode,
        paged = paged,
        pagedLayoutMessage = pagedLayoutMessage,
        initialRatio = initialProgressRatio,
        restored = restoredProgress,
        scrollState = novelScrollState,
        savedRatio = savedProgressRatio,
        onRestored = { restoredProgress = true },
        onProgress = { progress = it },
    )

    LaunchedEffect(novelScrollState, chromeVisible) {
        if (!chromeVisible) return@LaunchedEffect
        val initialOffset = novelScrollState.value
        snapshotFlow { novelScrollState.value }.first { it != initialOffset }
        chromeVisible = false
    }

    // Saves once when the chapter's screen closes (Mangayomi does not persist every frame) and
    // silences speech the reader can no longer show.
    val currentOnEvent by rememberUpdatedState(onEvent)
    DisposableEffect(chapter.id) {
        onDispose {
            currentOnEvent(NovelReaderEvent.SaveProgress(savedProgressRatio.doubleValue))
            currentOnEvent(NovelReaderEvent.StopTts)
        }
    }

    if (settingsSheetOpen) {
        NovelReaderSettingsSheet(
            mangaId = manga.id,
            settings = settings,
            state = state,
            onEvent = onEvent,
            onUpdateSettings = onUpdateSettings,
            onLayoutChange = { pagedLayoutMessage = false },
            onDismiss = { settingsSheetOpen = false },
        )
    }

    // E-ink: black text on white and no chrome motion, regardless of the stored reader theme.
    val eink = settings.einkMode
    val ttsBottomPadding by animateDpAsState(
        targetValue = if (chromeVisible) 140.dp else 0.dp,
        animationSpec = tween(if (eink) 0 else 300, easing = FastOutSlowInEasing),
        label = "Novel TTS chrome offset",
    )
    val textColor = (if (eink) Color.Black else parseHexColor(settings.novelReaderTextColor))
        ?: MaterialTheme.colorScheme.onBackground
    val fontFamily = resolveNovelFontFamily(settings.novelFontFamily, settings.appFontFamily)
    val paragraphSpacing = if (settings.novelRemoveExtraParagraphSpacing) 4.dp else 12.dp
    val shownContent = richContent ?: remember { parseNovelRichContent("No text content loaded.") }

    Scaffold(
        topBar = {
            NovelReaderTopBar(
                visible = chromeVisible,
                eink = eink,
                title = manga.name,
                chapter = chapter,
                onBack = onBack,
                onToggleBookmark = { onEvent(NovelReaderEvent.ToggleBookmark) },
                onOpenWebView = onOpenWebView,
            )
        },
        bottomBar = {
            NovelReaderBottomBar(
                visible = chromeVisible,
                eink = eink,
                progress = progress,
                ttsEnabled = richContent?.blocks?.isNotEmpty() == true,
                onPreviousChapter = { state.previousChapter?.let(onOpenChapter) },
                onNextChapter = { state.nextChapter?.let(onOpenChapter) },
                onSeek = { ratio ->
                    progress = (ratio * 100).toInt().coerceIn(0, 100)
                    savedProgressRatio.doubleValue = ratio.toDouble()
                    if (!scrollMode) {
                        pagedSourceAnchor = null
                    } else {
                        val maxOffset = novelScrollState.maxValue
                        if (maxOffset != Int.MAX_VALUE) {
                            scope.launch { novelScrollState.scrollTo(novelScrollOffset(maxOffset, ratio.toDouble())) }
                        }
                    }
                },
                onChangeFontSize = { delta ->
                    onUpdateSettings { it.copy(novelFontSize = (it.novelFontSize + delta).coerceIn(4, 40)) }
                },
                onStartTts = {
                    onEvent(NovelReaderEvent.StartTts(richContent?.let(::novelTtsParagraphs).orEmpty()))
                },
                onOpenSettings = { settingsSheetOpen = true },
            )
        },
    ) { _ ->
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    (if (eink) Color.White else parseHexColor(settings.novelReaderTheme))
                        ?: LocalYokanScaffoldColor.current,
                ),
        ) {
            if (!scrollMode) {
                NovelPagedReader(
                    content = shownContent,
                    pageMode = settings.novelPageMode,
                    reverseLayout = settings.defaultReaderMode == DbReaderMode.Rtl ||
                        settings.defaultReaderMode == DbReaderMode.HorizontalContinuousRtl,
                    requestedPageRatio = savedProgressRatio.doubleValue,
                    sourceAnchor = pagedSourceAnchor,
                    fontSize = settings.novelFontSize,
                    lineHeight = settings.novelReaderLineHeight,
                    textAlign = settings.novelTextAlign,
                    fontFamily = fontFamily,
                    textColor = textColor,
                    imageHeaders = state.imageHeaders,
                    ttsState = state.tts,
                    paragraphSpacing = paragraphSpacing,
                    padding = settings.novelReaderPadding.dp,
                    onPageChanged = { anchor, ratio ->
                        pagedSourceAnchor = anchor
                        savedProgressRatio.doubleValue = ratio
                        progress = novelProgressPercent(ratio)
                        restoredProgress = true
                    },
                    onComplete = { anchor, ratio ->
                        pagedSourceAnchor = anchor
                        savedProgressRatio.doubleValue = ratio
                        progress = 100
                        restoredProgress = true
                    },
                    onInvalidLayout = { pagedLayoutMessage = true },
                )
            } else {
                if (paged) {
                    Surface(
                        modifier = Modifier.align(Alignment.TopCenter).padding(8.dp),
                        color = MaterialTheme.colorScheme.tertiaryContainer,
                        shape = RoundedCornerShape(12.dp),
                    ) {
                        Text("This page is too small for paged reading. Showing scroll mode.", modifier = Modifier.padding(12.dp))
                    }
                }
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .verticalScroll(novelScrollState)
                        .padding(settings.novelReaderPadding.dp),
                    verticalArrangement = Arrangement.spacedBy(paragraphSpacing),
                ) {
                    if (state.loading) LinearProgressIndicator(modifier = Modifier.fillMaxWidth())
                    state.error?.takeIf(String::isNotBlank)?.let { Text(it, color = MaterialTheme.colorScheme.error) }
                    NovelRichContentView(
                        content = shownContent,
                        textColor = textColor,
                        fontSize = settings.novelFontSize,
                        lineHeight = settings.novelReaderLineHeight,
                        textAlign = settings.novelTextAlign,
                        fontFamily = fontFamily,
                        paragraphSpacing = paragraphSpacing,
                        imageHeaders = state.imageHeaders,
                        ttsState = state.tts,
                    )
                }
            }
            if (settings.novelShowScrollPercentage) NovelProgressPill(progress, Modifier.align(Alignment.CenterStart))
            if (scrollMode) {
                NovelTapZones(
                    scrollState = novelScrollState,
                    tapToScroll = settings.novelTapToScroll,
                    eink = eink,
                    onToggleChrome = { chromeVisible = !chromeVisible },
                )
                ReaderAutoScrollFab(
                    visible = state.autoScrollEnabled && !chromeVisible,
                    isPlaying = state.autoScrollPlaying,
                    onToggle = { onEvent(NovelReaderEvent.ToggleAutoScrollPlaying) },
                    bottomPadding = 8.dp,
                )
            }
            if (state.tts.playback != NovelTtsPlaybackState.Stopped) {
                NovelTtsBar(
                    tts = state.tts,
                    bottomPadding = ttsBottomPadding,
                    onEvent = onEvent,
                    modifier = Modifier.align(Alignment.BottomCenter),
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun NovelReaderSettingsSheet(
    mangaId: Long,
    settings: DbSettings,
    state: NovelReaderState,
    onEvent: (NovelReaderEvent) -> Unit,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    /** A reading/page mode change retries paged layout. */
    onLayoutChange: () -> Unit,
    onDismiss: () -> Unit,
) {
    ModalBottomSheet(onDismissRequest = onDismiss, modifier = Modifier.compactSheetWidth()) {
        NovelReaderSettingsContent(
            settings = settings,
            onUpdateSettings = onUpdateSettings,
            mangaId = mangaId,
            autoScrollEnabled = state.autoScrollEnabled,
            autoScrollSpeed = state.autoScrollOffset,
            onAutoScrollEnabledChange = { onEvent(NovelReaderEvent.SetAutoScrollEnabled(it)) },
            onAutoScrollSpeedChange = { onEvent(NovelReaderEvent.SetAutoScrollOffset(it)) },
            onReadingModeChange = { mode ->
                onLayoutChange()
                onUpdateSettings { it.copy(novelReadingMode = mode) }
            },
            onPageModeChange = { mode ->
                onLayoutChange()
                onUpdateSettings { it.copy(novelPageMode = mode) }
            },
        )
    }
}

internal fun parseHexColor(value: String): Color? = value.removePrefix("#").takeIf { it.length == 6 || it.length == 8 }?.let { hex ->
    runCatching {
        val argb = if (hex.length == 6) "FF$hex" else hex
        Color(argb.toLong(16).toInt())
    }.getOrNull()
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderChrome.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderChrome.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderChrome.kt).

The implementation below defines `NovelChromeVisibility`, `NovelReaderTopBar`, `NovelReaderBottomBar`, `NovelTapZones`, `scrollOrToggle`, `Modifier.zone`, `NovelProgressPill`, `NovelTtsBar`.

The source describes its contract as:

> Slides the reader chrome in from \[fromTop\] or the bottom edge; e-ink shows it without motion.

Cross-chapter imports used by this file: [`Chapter`](../chapters/02-domain-and-settings-models.md), [`GlobalStatusAccessButton`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.EnterTransition
import androidx.compose.animation.ExitTransition
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.animateScrollBy
import androidx.compose.foundation.gestures.scrollBy
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Bookmark
import androidx.compose.material.icons.filled.BookmarkBorder
import androidx.compose.material.icons.filled.GraphicEq
import androidx.compose.material.icons.filled.Pause
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Public
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.icons.filled.SkipNext
import androidx.compose.material.icons.filled.SkipPrevious
import androidx.compose.material.icons.filled.Stop
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.ui.status.GlobalStatusAccessButton
import kotlin.math.sign
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource
import yokan.composeapp.generated.resources.Res
import yokan.composeapp.generated.resources.action_back
import yokan.composeapp.generated.resources.tts_stop
import yokan.composeapp.generated.resources.ui_tts

private val chapterNumberRegex = Regex("(\\d+(?:\\.\\d+)?)")

/** Slides the reader chrome in from [fromTop] or the bottom edge; e-ink shows it without motion. */
@Composable
private fun NovelChromeVisibility(visible: Boolean, eink: Boolean, fromTop: Boolean, content: @Composable () -> Unit) {
    val direction = if (fromTop) -1 else 1
    AnimatedVisibility(
        visible = visible,
        enter = if (eink) EnterTransition.None else slideInVertically(
            initialOffsetY = { direction * it },
            animationSpec = tween(300, easing = FastOutSlowInEasing),
        ) + fadeIn(tween(300)),
        exit = if (eink) ExitTransition.None else slideOutVertically(
            targetOffsetY = { direction * it },
            animationSpec = tween(300, easing = FastOutSlowInEasing),
        ) + fadeOut(tween(300)),
    ) { content() }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun NovelReaderTopBar(
    visible: Boolean,
    eink: Boolean,
    title: String,
    chapter: Chapter,
    onBack: () -> Unit,
    onToggleBookmark: () -> Unit,
    onOpenWebView: () -> Unit,
) {
    NovelChromeVisibility(visible, eink, fromTop = true) {
        TopAppBar(
            title = {
                Column {
                    Text(
                        title,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        style = MaterialTheme.typography.titleMedium,
                    )
                    Text(
                        // The chapter number prefix of the name when present.
                        "Ch ${chapterNumberRegex.find(chapter.name)?.value ?: "?"} - ${chapter.name}",
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            },
            navigationIcon = {
                IconButton(onClick = onBack) {
                    Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.action_back))
                }
            },
            actions = {
                GlobalStatusAccessButton()
                IconButton(onClick = onToggleBookmark) {
                    Icon(
                        if (chapter.isBookmarked) Icons.Filled.Bookmark else Icons.Filled.BookmarkBorder,
                        contentDescription = "Bookmark",
                    )
                }
                IconButton(onClick = onOpenWebView) {
                    Icon(Icons.Filled.Public, contentDescription = "Open in web view")
                }
            },
        )
    }
}

@Composable
internal fun NovelReaderBottomBar(
    visible: Boolean,
    eink: Boolean,
    progress: Int,
    ttsEnabled: Boolean,
    onPreviousChapter: () -> Unit,
    onNextChapter: () -> Unit,
    onSeek: (Float) -> Unit,
    onChangeFontSize: (delta: Int) -> Unit,
    onStartTts: () -> Unit,
    onOpenSettings: () -> Unit,
) {
    NovelChromeVisibility(visible, eink, fromTop = false) {
        Surface(
            tonalElevation = 2.dp,
            color = MaterialTheme.colorScheme.surface,
        ) {
            Column(
                Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
                verticalArrangement = Arrangement.spacedBy(6.dp),
            ) {
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                ) {
                    IconButton(onClick = onPreviousChapter) {
                        Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous chapter")
                    }
                    Slider(
                        value = progress / 100f,
                        onValueChange = onSeek,
                        modifier = Modifier.weight(1f),
                    )
                    IconButton(onClick = onNextChapter) {
                        Icon(Icons.Filled.SkipNext, contentDescription = "Next chapter")
                    }
                }
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp),
                ) {
                    Surface(
                        shape = RoundedCornerShape(50),
                        tonalElevation = 1.dp,
                        color = MaterialTheme.colorScheme.surfaceVariant,
                    ) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            IconButton(onClick = { onChangeFontSize(-1) }) {
                                Icon(Icons.Filled.Remove, contentDescription = "Smaller text")
                            }
                            Text(
                                "Aa",
                                style = MaterialTheme.typography.labelLarge,
                                modifier = Modifier.padding(horizontal = 4.dp),
                            )
                            IconButton(onClick = { onChangeFontSize(1) }) {
                                Icon(Icons.Filled.Add, contentDescription = "Larger text")
                            }
                        }
                    }
                    Spacer(Modifier.weight(1f))
                    IconButton(enabled = ttsEnabled, onClick = onStartTts) {
                        Icon(Icons.Filled.GraphicEq, contentDescription = stringResource(Res.string.ui_tts))
                    }
                    IconButton(onClick = onOpenSettings) {
                        Icon(Icons.Filled.Settings, contentDescription = "Settings")
                    }
                }
            }
        }
    }
}

/**
 * Mangayomi tap-zone geometry: top/bottom bands (2:5:2) page by ±100 logical px; the middle row
 * splits into thirds where the center always toggles chrome. With tap-to-scroll off, every zone
 * toggles chrome (novel_reader_view.dart _gestureRightLeft/_gestureTopBottom).
 */
@Composable
internal fun NovelTapZones(
    scrollState: ScrollState,
    tapToScroll: Boolean,
    eink: Boolean,
    onToggleChrome: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val scope = rememberCoroutineScope()
    val interactionSource = remember { MutableInteractionSource() }
    val tapStep = with(LocalDensity.current) { 100.dp.toPx() }
    fun scrollOrToggle(delta: Float): () -> Unit = {
        if (!tapToScroll) onToggleChrome() else scope.launch {
            if (eink) {
                // Whole-screen jumps: smooth 100 px steps ghost on e-paper.
                scrollState.scrollBy(sign(delta) * scrollState.viewportSize * 0.9f)
            } else {
                scrollState.animateScrollBy(delta, tween(durationMillis = 100, easing = LinearEasing))
            }
        }
    }
    fun Modifier.zone(onTap: () -> Unit): Modifier =
        clickable(interactionSource = interactionSource, indication = null, onClick = onTap)
    val back = scrollOrToggle(-tapStep)
    val forward = scrollOrToggle(tapStep)
    Column(modifier = modifier.fillMaxSize()) {
        Box(Modifier.fillMaxWidth().weight(2f).zone(back))
        Row(Modifier.fillMaxWidth().weight(5f)) {
            Box(Modifier.fillMaxHeight().weight(1f).zone(back))
            Box(Modifier.fillMaxHeight().weight(1f).zone(onToggleChrome))
            Box(Modifier.fillMaxHeight().weight(1f).zone(forward))
        }
        Box(Modifier.fillMaxWidth().weight(2f).zone(forward))
    }
}

@Composable
internal fun NovelProgressPill(progress: Int, modifier: Modifier = Modifier) {
    Surface(
        modifier = modifier.padding(start = 4.dp),
        color = MaterialTheme.colorScheme.surface.copy(alpha = 0.7f),
        shape = RoundedCornerShape(topEnd = 8.dp, bottomEnd = 8.dp),
    ) {
        Text(
            "$progress%",
            modifier = Modifier.padding(horizontal = 6.dp, vertical = 4.dp),
            style = MaterialTheme.typography.labelSmall,
            color = MaterialTheme.colorScheme.onSurface,
        )
    }
}

@Composable
internal fun NovelTtsBar(
    tts: NovelTtsUiState,
    bottomPadding: Dp,
    onEvent: (NovelReaderEvent) -> Unit,
    modifier: Modifier = Modifier,
) {
    val playing = tts.playback == NovelTtsPlaybackState.Playing
    Surface(
        modifier = modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp, vertical = 8.dp)
            .padding(bottom = bottomPadding),
        color = MaterialTheme.colorScheme.surfaceVariant,
        shape = RoundedCornerShape(16.dp),
        shadowElevation = 8.dp,
    ) {
        Column {
            LinearProgressIndicator(
                progress = { tts.progress },
                modifier = Modifier.fillMaxWidth().height(3.dp),
            )
            Row(
                modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(4.dp),
            ) {
                Icon(Icons.Filled.GraphicEq, contentDescription = null)
                Text(
                    "Paragraph ${tts.paragraphIndex + 1} of ${tts.paragraphCount}",
                    modifier = Modifier.weight(1f),
                    style = MaterialTheme.typography.bodySmall,
                    maxLines = 1,
                    overflow = TextOverflow.Ellipsis,
                )
                IconButton(
                    enabled = tts.paragraphIndex > 0,
                    onClick = { onEvent(NovelReaderEvent.SkipPreviousTts) },
                ) {
                    Icon(Icons.Filled.SkipPrevious, contentDescription = "Previous paragraph")
                }
                IconButton(onClick = { onEvent(NovelReaderEvent.ToggleTtsPlayback) }) {
                    Icon(
                        if (playing) Icons.Filled.Pause else Icons.Filled.PlayArrow,
                        contentDescription = if (playing) "Pause TTS" else "Resume TTS",
                    )
                }
                IconButton(
                    enabled = tts.paragraphIndex < tts.paragraphCount - 1,
                    onClick = { onEvent(NovelReaderEvent.SkipNextTts) },
                ) {
                    Icon(Icons.Filled.SkipNext, contentDescription = "Next paragraph")
                }
                IconButton(onClick = { onEvent(NovelReaderEvent.StopTts) }) {
                    Icon(Icons.Filled.Stop, contentDescription = stringResource(Res.string.tts_stop))
                }
            }
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsContent.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsContent.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsContent.kt).

The implementation below defines `NovelReaderSettingsContent`, `SettingToggle`.

The source describes its contract as:

> Shared live controls for the reader sheet and the global settings destination.

Cross-chapter imports used by this file: [`DbNovelPageMode`](../chapters/02-domain-and-settings-models.md), [`DbNovelReadingMode`](../chapters/02-domain-and-settings-models.md), [`DbNovelTextAlign`](../chapters/02-domain-and-settings-models.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`formatDecimal`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.FormatAlignLeft
import androidx.compose.material.icons.automirrored.filled.FormatAlignRight
import androidx.compose.material.icons.filled.FormatAlignCenter
import androidx.compose.material.icons.filled.FormatAlignJustify
import androidx.compose.material3.FilterChip
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SecondaryTabRow
import androidx.compose.material3.Slider
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Tab
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import eu.friedcutlet.yokan.database.DbNovelPageMode
import eu.friedcutlet.yokan.database.DbNovelReadingMode
import eu.friedcutlet.yokan.database.DbNovelTextAlign
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.formatDecimal

/** Shared live controls for the reader sheet and the global settings destination. */
@Composable
fun NovelReaderSettingsContent(
    settings: DbSettings,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    mangaId: Long? = null,
    autoScrollEnabled: Boolean = false,
    autoScrollSpeed: Float = 10f,
    onAutoScrollEnabledChange: (Boolean) -> Unit = {},
    onAutoScrollSpeedChange: (Float) -> Unit = {},
    onReadingModeChange: (DbNovelReadingMode) -> Unit = { mode ->
        onUpdateSettings { it.copy(novelReadingMode = mode) }
    },
    onPageModeChange: (DbNovelPageMode) -> Unit = { mode ->
        onUpdateSettings { it.copy(novelPageMode = mode) }
    },
    modifier: Modifier = Modifier,
) {
    var tab by remember { mutableIntStateOf(0) }
    Column(modifier.fillMaxWidth()) {
        SecondaryTabRow(selectedTabIndex = tab) {
            Tab(tab == 0, { tab = 0 }, text = { Text("Reader") })
            Tab(tab == 1, { tab = 1 }, text = { Text("General") })
            Tab(tab == 2, { tab = 2 }, text = { Text("TTS") })
        }
        Column(
            Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp).verticalScroll(rememberScrollState()),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            when (tab) {
                0 -> {
                    Text("Reading mode", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        DbNovelReadingMode.entries.forEach { mode ->
                            FilterChip(settings.novelReadingMode == mode, { onReadingModeChange(mode) }, { Text(mode.name) })
                        }
                    }
                    Text("Page layout", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        DbNovelPageMode.entries.forEach { mode ->
                            FilterChip(settings.novelPageMode == mode, { onPageModeChange(mode) }, { Text(mode.name) })
                        }
                    }
                    Text("Novel font", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        listOf("Default", "OpenDyslexic", "Lexend", "Atkinson").forEach { font ->
                            FilterChip(settings.novelFontFamily == font, {
                                onUpdateSettings { it.copy(novelFontFamily = font) }
                            }, { Text(font) })
                        }
                    }
                    Text("Theme", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    val themes = listOf(
                        Triple("Dark", "#292832", "#CCCCCC"),
                        Triple("Light", "#FFFFFF", "#000000"),
                        Triple("Black", "#000000", "#FFFFFF"),
                        Triple("Sepia", "#F5E6D3", "#5F4B32"),
                    )
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        themes.forEach { (label, bg, fg) ->
                            val selected = settings.novelReaderTheme.equals(bg, ignoreCase = true)
                            Surface(
                                shape = RoundedCornerShape(10.dp),
                                color = parseHexColor(bg) ?: Color.Transparent,
                                border = BorderStroke(
                                    width = if (selected) 3.dp else 1.dp,
                                    color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
                                ),
                                modifier = Modifier.clickable {
                                    onUpdateSettings { it.copy(novelReaderTheme = bg, novelReaderTextColor = fg) }
                                },
                            ) {
                                Text(
                                    label,
                                    modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
                                    color = parseHexColor(fg) ?: MaterialTheme.colorScheme.onSurface,
                                    style = MaterialTheme.typography.labelLarge,
                                )
                            }
                        }
                    }
                    val palette = listOf(
                        "#FFFFFF", "#000000", "#292832", "#F5E6D3", "#5F4B32", "#CCCCCC",
                        "#424242", "#E0E0E0", "#D7CCC8", "#BBDEFB", "#C8E6C9", "#FFECB3",
                    )
                    Text("Background", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        palette.forEach { hex ->
                            val selected = settings.novelReaderTheme.equals(hex, ignoreCase = true)
                            Box(
                                Modifier.size(36.dp)
                                    .clip(RoundedCornerShape(8.dp))
                                    .background(parseHexColor(hex) ?: Color.Transparent, RoundedCornerShape(8.dp))
                                    .then(Modifier.border(
                                        if (selected) 2.dp else 1.dp,
                                        if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
                                        RoundedCornerShape(8.dp),
                                    ))
                                    .clickable { onUpdateSettings { it.copy(novelReaderTheme = hex) } },
                            )
                        }
                    }
                    Text("Text color", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        palette.forEach { hex ->
                            val selected = settings.novelReaderTextColor.equals(hex, ignoreCase = true)
                            Box(
                                Modifier.size(36.dp)
                                    .clip(RoundedCornerShape(8.dp))
                                    .background(parseHexColor(hex) ?: Color.Transparent, RoundedCornerShape(8.dp))
                                    .then(Modifier.border(
                                        if (selected) 2.dp else 1.dp,
                                        if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline,
                                        RoundedCornerShape(8.dp),
                                    ))
                                    .clickable { onUpdateSettings { it.copy(novelReaderTextColor = hex) } },
                            )
                        }
                    }
                    Text("Text align", style = MaterialTheme.typography.titleSmall, fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold)
                    Row(horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier.fillMaxWidth()) {
                        DbNovelTextAlign.entries.forEach { align ->
                            val selected = settings.novelTextAlign == align
                            IconButton(
                                onClick = { onUpdateSettings { it.copy(novelTextAlign = align) } },
                                colors = IconButtonDefaults.iconButtonColors(
                                    containerColor = if (selected) MaterialTheme.colorScheme.primaryContainer else Color.Transparent,
                                    contentColor = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant,
                                ),
                            ) {
                                Icon(
                                    when (align) {
                                        DbNovelTextAlign.Left -> Icons.AutoMirrored.Filled.FormatAlignLeft
                                        DbNovelTextAlign.Center -> Icons.Filled.FormatAlignCenter
                                        DbNovelTextAlign.Right -> Icons.AutoMirrored.Filled.FormatAlignRight
                                        DbNovelTextAlign.Block -> Icons.Filled.FormatAlignJustify
                                    },
                                    contentDescription = align.name,
                                )
                            }
                        }
                    }
                    Text("Padding: ${settings.novelReaderPadding}px", style = MaterialTheme.typography.labelLarge)
                    Slider(settings.novelReaderPadding.toFloat(), { v -> onUpdateSettings { it.copy(novelReaderPadding = v.toInt().coerceIn(0, 50)) } }, valueRange = 0f..50f, steps = 49)
                    Text("Line height: ${formatDecimal(settings.novelReaderLineHeight, 1)}", style = MaterialTheme.typography.labelLarge)
                    Slider(settings.novelReaderLineHeight.toFloat(), { v -> onUpdateSettings { it.copy(novelReaderLineHeight = v.toDouble()) } }, valueRange = 1f..3f, steps = 19)
                }
                1 -> {
                    if (mangaId != null) {
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Text("Auto-scroll", Modifier.weight(1f))
                            Switch(autoScrollEnabled, onAutoScrollEnabledChange)
                        }
                        if (autoScrollEnabled) {
                            Text("Auto-scroll speed: ${formatDecimal(autoScrollSpeed.toDouble(), 1)}", style = MaterialTheme.typography.labelLarge)
                            Slider(autoScrollSpeed, onAutoScrollSpeedChange, valueRange = 2f..30f, steps = 27)
                        }
                    }
                    SettingToggle("Keep screen on", settings.keepScreenOnReader) {
                        onUpdateSettings { it.copy(keepScreenOnReader = !it.keepScreenOnReader) }
                    }
                    SettingToggle("Show scroll percentage", settings.novelShowScrollPercentage) {
                        onUpdateSettings { it.copy(novelShowScrollPercentage = !it.novelShowScrollPercentage) }
                    }
                    SettingToggle("Remove extra paragraph spacing", settings.novelRemoveExtraParagraphSpacing) {
                        onUpdateSettings { it.copy(novelRemoveExtraParagraphSpacing = !it.novelRemoveExtraParagraphSpacing) }
                    }
                    SettingToggle("Use page tap zones", settings.novelTapToScroll) {
                        onUpdateSettings { it.copy(novelTapToScroll = !it.novelTapToScroll) }
                    }
                }
                else -> {
                    Text("Speech rate: ${formatDecimal(settings.ttsSpeechRate, 2)}", style = MaterialTheme.typography.labelLarge)
                    Slider(settings.ttsSpeechRate.toFloat(), { v -> onUpdateSettings { it.copy(ttsSpeechRate = v.toDouble()) } }, valueRange = 0.1f..2.0f)
                    Text("Pitch: ${formatDecimal(settings.ttsPitch, 2)}", style = MaterialTheme.typography.labelLarge)
                    Slider(settings.ttsPitch.toFloat(), { v -> onUpdateSettings { it.copy(ttsPitch = v.toDouble()) } }, valueRange = 0.5f..2.0f)
                    Text("Language", style = MaterialTheme.typography.labelLarge)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                        listOf(null, "en", "en-US", "ja", "de", "fr", "es").forEach { language ->
                            FilterChip(settings.ttsLanguage == language, {
                                onUpdateSettings { it.copy(ttsLanguage = language) }
                            }, { Text(language ?: "Auto") })
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun SettingToggle(label: String, checked: Boolean, onToggle: () -> Unit) {
    Row(verticalAlignment = Alignment.CenterVertically) {
        Text(label, Modifier.weight(1f))
        Switch(checked, onCheckedChange = { onToggle() })
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsScreen.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsScreen.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderSettingsScreen.kt).

The implementation below defines `NovelReaderSettingsRoute`, `NovelReaderSettingsScreen`.

Cross-chapter imports used by this file: [`YokanRuntime`](../chapters/04-profiles-and-lifetimes.md), [`DbSettings`](../chapters/02-domain-and-settings-models.md), [`YokanTopBar`](../chapters/10-navigation-and-design-system.md), [`Navigator`](../chapters/10-navigation-and-design-system.md), [`YokanScaffold`](../chapters/10-navigation-and-design-system.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import eu.friedcutlet.yokan.app.YokanRuntime
import eu.friedcutlet.yokan.database.DbSettings
import eu.friedcutlet.yokan.ui.components.YokanTopBar
import eu.friedcutlet.yokan.ui.navigation.Navigator
import eu.friedcutlet.yokan.ui.theme.YokanScaffold

@Composable
internal fun NovelReaderSettingsRoute(title: String, nav: Navigator) {
    val settings by YokanRuntime.settings.db.collectAsStateWithLifecycle()
    NovelReaderSettingsScreen(title, settings, onUpdateSettings = YokanRuntime.settings::updateDb, onBack = nav::back)
}

@Composable
fun NovelReaderSettingsScreen(
    title: String,
    settings: DbSettings,
    onUpdateSettings: ((DbSettings) -> DbSettings) -> Unit,
    onBack: () -> Unit,
) {
    YokanScaffold(topBar = { YokanTopBar(title = title, onBack = onBack) }) { padding ->
        NovelReaderSettingsContent(
            settings = settings,
            onUpdateSettings = onUpdateSettings,
            mangaId = null,
            modifier = Modifier.padding(padding),
        )
    }
}
```
[chapter-file-end]: #

### Check your understanding

Navigate away during loading and while a final progress save is pending. No old content should appear later, and the departing owner's save must finish before its resources close.
[chapter-content-end]: #


## Step 5: implement speech ownership

Build NovelTtsController around TextToSpeechService/ProfileSpeechService. Define speak/pause/stop, voice/rate and chapter/text cursor behavior. Track which chapter owns the speech request. Text changes, chapter navigation and retirement must stop or replace the correct session and ignore stale callbacks. Join outstanding speech work when the reader closes; an old callback must not advance a new chapter or profile.

[chapter-content-start]: #
### Follow the code

The TTS controller turns readable content into speech work associated with a chapter/text cursor. ProfileSpeechService in chapter 24 supplies an owned platform delegate. Pause/stop/replacement and reader teardown must target that exact request. A completion callback received after chapter/profile replacement cannot advance the new reader. Treat speech lifetime separately from visible page layout so a remeasurement does not start a second utterance.

Write these files in this order:

- `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsController.kt`

[chapter-file-start]: #composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsController.kt
### Write `composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsController.kt`

Create this path in your reconstruction project. Source set: **commonMain**. [Exact file download](../reference/source/composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsController.kt).

A speech callback is meaningful only for its captured text/chapter request. Retain request identity and cancellation around callbacks rather than using whichever chapter is current when the platform calls back.

The implementation below defines `NovelTtsPlaybackState`, `NovelTtsUiState`, `novelTtsParagraphs`, `NovelTtsController`, `ensureCurrent`, `command`, `start`, `pause`, `resume`, `skipNext` and 9 further declarations.

Cross-chapter imports used by this file: [`TextToSpeechRequest`](../chapters/24-settings-and-integrations.md), [`TextToSpeechService`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest
import eu.friedcutlet.yokan.services.tts.TextToSpeechService
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.NonCancellable
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.flow.updateAndGet
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext

internal enum class NovelTtsPlaybackState { Stopped, Playing, Paused }

internal data class NovelTtsUiState(
    val playback: NovelTtsPlaybackState = NovelTtsPlaybackState.Stopped,
    val paragraphIndex: Int = 0,
    val paragraphCount: Int = 0,
    val wordStart: Int = -1,
    val wordEnd: Int = -1,
) {
    val progress: Float
        get() = if (paragraphCount == 0) 0f else (paragraphIndex + 1f) / paragraphCount
}

internal fun novelTtsParagraphs(content: NovelRichContent): List<String> = content.blocks
    .mapNotNull { (it as? NovelContentBlock.Text)?.text?.text?.trim()?.takeIf(String::isNotEmpty) }

internal class NovelTtsController(
    private val service: TextToSpeechService,
    ownerScope: CoroutineScope,
    private val isOwnerOpen: () -> Boolean = { true },
) {
    private val parentJob = requireNotNull(ownerScope.coroutineContext[Job])
    private val job = SupervisorJob(parentJob)
    private val scope = CoroutineScope(ownerScope.coroutineContext + job)
    private val operations = Mutex()
    private val mutableState = MutableStateFlow(NovelTtsUiState())
    val state: StateFlow<NovelTtsUiState> = mutableState.asStateFlow()

    private var paragraphs: List<String> = emptyList()
    private var request = TextToSpeechRequest()
    private var resumeOffset = 0
    private var playbackJob: Job? = null
    private val generation = MutableStateFlow(0L)

    private fun ensureCurrent(call: Job) {
        call.ensureActive()
        parentJob.ensureActive()
        job.ensureActive()
        if (!isOwnerOpen()) throw CancellationException("Reader speech owner is retired.")
    }

    private suspend fun command(action: suspend () -> Unit) {
        val caller = requireNotNull(currentCoroutineContext()[Job])
        ensureCurrent(caller)
        val work = scope.async {
            operations.withLock {
                caller.ensureActive()
                ensureCurrent(requireNotNull(currentCoroutineContext()[Job]))
                action()
                ensureCurrent(requireNotNull(currentCoroutineContext()[Job]))
            }
        }
        try { work.await() }
        finally {
            withContext(NonCancellable) { work.cancelAndJoin() }
            ensureCurrent(caller)
        }
    }

    suspend fun start(paragraphs: List<String>, request: TextToSpeechRequest, startIndex: Int = 0) = command {
        haltCurrent()
        this.paragraphs = paragraphs.filter(String::isNotBlank)
        this.request = request
        resumeOffset = 0
        mutableState.update {
            if (this.paragraphs.isEmpty()) NovelTtsUiState() else NovelTtsUiState(
                playback = NovelTtsPlaybackState.Playing,
                paragraphIndex = startIndex.coerceIn(this.paragraphs.indices),
                paragraphCount = this.paragraphs.size,
            )
        }
        if (this.paragraphs.isNotEmpty()) launchPlayback()
    }

    suspend fun pause() = command {
        val current = mutableState.value
        if (current.playback == NovelTtsPlaybackState.Playing) {
            resumeOffset = current.wordStart.takeIf { it >= 0 } ?: resumeOffset
            haltCurrent()
            mutableState.update { current.copy(playback = NovelTtsPlaybackState.Paused) }
        }
    }

    suspend fun resume() = command {
        if (mutableState.value.playback == NovelTtsPlaybackState.Paused && paragraphs.isNotEmpty()) {
            mutableState.update { it.copy(playback = NovelTtsPlaybackState.Playing) }
            launchPlayback()
        }
    }

    suspend fun skipNext() = command { jumpTo((mutableState.value.paragraphIndex + 1).coerceAtMost(paragraphs.lastIndex)) }
    suspend fun skipPrevious() = command { jumpTo((mutableState.value.paragraphIndex - 1).coerceAtLeast(0)) }

    private suspend fun jumpTo(index: Int) {
        if (index !in paragraphs.indices) return
        val wasPlaying = mutableState.value.playback == NovelTtsPlaybackState.Playing
        haltCurrent()
        resumeOffset = 0
        mutableState.update { it.copy(
            playback = if (wasPlaying) NovelTtsPlaybackState.Playing else NovelTtsPlaybackState.Paused,
            paragraphIndex = index, wordStart = -1, wordEnd = -1,
        ) }
        if (wasPlaying) launchPlayback()
    }

    suspend fun updateRequest(request: TextToSpeechRequest) = command {
        this.request = request
        val current = mutableState.value
        if (current.playback == NovelTtsPlaybackState.Playing) {
            resumeOffset = current.wordStart.takeIf { it >= 0 } ?: resumeOffset
            haltCurrent()
            mutableState.update { current.copy(playback = NovelTtsPlaybackState.Playing) }
            launchPlayback()
        }
    }

    suspend fun stop() = command {
        haltCurrent()
        paragraphs = emptyList()
        resumeOffset = 0
        mutableState.update { NovelTtsUiState() }
    }

    internal fun retire() {
        generation.update { it + 1 }
        job.cancel()
        mutableState.update { NovelTtsUiState() }
    }

    internal suspend fun closeAndJoin() {
        retire()
        withContext(NonCancellable) { job.join() }
    }

    private fun launchPlayback() {
        val token = generation.updateAndGet { it + 1 }
        playbackJob = scope.launch {
            val call = requireNotNull(currentCoroutineContext()[Job])
            fun admitted() = call.isActive && job.isActive && parentJob.isActive && isOwnerOpen() && token == generation.value
            try {
                while (admitted() && mutableState.value.playback == NovelTtsPlaybackState.Playing) {
                    val paragraphIndex = mutableState.value.paragraphIndex
                    val paragraph = paragraphs.getOrNull(paragraphIndex) ?: break
                    val offset = resumeOffset.coerceIn(0, paragraph.length)
                    if (offset < paragraph.length) {
                        service.speak(paragraph.substring(offset), request) { start, end ->
                            if (admitted()) mutableState.update { current ->
                                if (admitted() && current.playback == NovelTtsPlaybackState.Playing) current.copy(
                                    wordStart = (offset + start).coerceIn(0, paragraph.length),
                                    wordEnd = (offset + end).coerceIn(0, paragraph.length),
                                ) else current
                            }
                        }
                    }
                    ensureCurrent(call)
                    if (!admitted() || mutableState.value.playback != NovelTtsPlaybackState.Playing) break
                    if (paragraphIndex >= paragraphs.lastIndex) {
                        mutableState.update { it.copy(playback = NovelTtsPlaybackState.Stopped, wordStart = -1, wordEnd = -1) }
                        break
                    }
                    resumeOffset = 0
                    mutableState.update { it.copy(paragraphIndex = paragraphIndex + 1, wordStart = -1, wordEnd = -1) }
                }
            } catch (cancelled: CancellationException) {
                throw cancelled
            } catch (_: Throwable) {
                if (admitted()) mutableState.update {
                    it.copy(playback = NovelTtsPlaybackState.Stopped, wordStart = -1, wordEnd = -1)
                }
            }
        }
    }

    private suspend fun haltCurrent() {
        generation.update { it + 1 }
        val previous = playbackJob
        previous?.cancel()
        withContext(NonCancellable) {
            previous?.join()
            service.stop()
        }
        playbackJob = null
        ensureCurrent(requireNotNull(currentCoroutineContext()[Job]))
    }
}
```
[chapter-file-end]: #

### Check your understanding

Start speech, switch chapters, then deliver the old completion callback. It must not advance or resume speech in the new chapter.
[chapter-content-end]: #


[chapter-content-start]: #
## Recreate the tests and verify the chapter

Recreate rich-content/link, scroll/progress, pagination and TTS ownership fixtures. Run pure pagination cases on the desktop test target, plus measured Compose pagination tests. Repeat real speech/voice behavior on each supported platform after the chapter-24 TTS actuals are connected.

These are source tests to reproduce and run in your reconstruction. Their inclusion here is not a claim that application/native/device tests were executed while writing the guide.

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContentTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContentTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelEmbeddedContentTest.kt).

The implementation below defines `NovelEmbeddedContentTest`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `embeddedImagesDeduplicateAndKeepExternalImagesAndLinks`
- `cancellationWhileAwaitingAnImageStopsBeforeTheNextResource`

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.yield
import kotlin.test.*

class NovelEmbeddedContentTest {
    @Test fun embeddedImagesDeduplicateAndKeepExternalImagesAndLinks() = runTest {
        val reads = mutableListOf<String>()
        val bytes = byteArrayOf(1, 2, 3)
        val html = "<p>Before</p><img src='../Images/a.png'><img src='../Images/a.png'><img src='https://img.test/a'><p>After</p>"
        val images = loadNovelEmbeddedImages(html) { reads += it; yield(); bytes }
        val parsed = NovelDocument(html, embeddedImages = images).parse()

        assertEquals(listOf("../Images/a.png"), reads)
        val blocks = parsed.blocks.filterIsInstance<NovelContentBlock.Image>()
        assertContentEquals(bytes, assertIs<NovelImageSource.Embedded>(blocks[0].source).bytes)
        assertSame(assertIs<NovelImageSource.Embedded>(blocks[0].source).bytes, assertIs<NovelImageSource.Embedded>(blocks[1].source).bytes)
        assertEquals("https://img.test/a", assertIs<NovelImageSource.Remote>(blocks[2].source).url)
        assertTrue(parsed.plainText.startsWith("Before"))
        assertTrue(parsed.plainText.endsWith("After"))
    }

    @Test fun cancellationWhileAwaitingAnImageStopsBeforeTheNextResource() = runTest {
        val entered = CompletableDeferred<Unit>()
        val reads = mutableListOf<String>()
        var delivered = false
        val work = async {
            loadNovelEmbeddedImages("<img src='one.png'><img src='two.png'>") {
                reads += it; entered.complete(Unit); awaitCancellation()
            }
            delivered = true
        }
        entered.await()
        work.cancelAndJoin()
        assertEquals(listOf("one.png"), reads)
        assertFalse(delivered)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPaginationTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPaginationTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPaginationTest.kt).

The implementation below defines `NovelPaginationTest`, `splitsLongTextWithoutLosingOrDuplicatingCharacters`, `paginatesTextAndAtomicBlocksWithSpacingOnlyBetweenBlocks`, `rejectsImpossibleContentAndInvalidViewport`, `exactFitAndBoundaryAnchorBelongToFollowingPage`, `anchorBeforeFirstPageClampsToFirstPageAcrossSkippedEmptyBlock`, `countsOddFinalSpread`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `splitsLongTextWithoutLosingOrDuplicatingCharacters`
- `paginatesTextAndAtomicBlocksWithSpacingOnlyBetweenBlocks`
- `rejectsImpossibleContentAndInvalidViewport`
- `exactFitAndBoundaryAnchorBelongToFollowingPage`
- `anchorBeforeFirstPageClampsToFirstPageAcrossSkippedEmptyBlock`
- `countsOddFinalSpread`

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.ui.text.AnnotatedString
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class NovelPaginationTest {
    @Test
    fun splitsLongTextWithoutLosingOrDuplicatingCharacters() {
        val text = "abcdefghij"
        val pages = paginateNovelBlocks(
            listOf(NovelContentBlock.Text(AnnotatedString(text))),
            pageHeightPx = 3,
            spacingPx = 2,
            measureText = { block, start, available ->
                val count = minOf(available, 3, block.text.length - start)
                NovelTextFit(start + count, count)
            },
            measureAtomicHeight = { 1 },
        )

        assertEquals(listOf("abc", "def", "ghi", "j"), pages!!.map { page ->
            page.slices.joinToString("") { slice -> text.substring(slice.start, slice.endExclusive) }
        })
        assertEquals(text, pages.flatMap { it.slices }.joinToString("") {
            text.substring(it.start, it.endExclusive)
        })
    }

    @Test
    fun paginatesTextAndAtomicBlocksWithSpacingOnlyBetweenBlocks() {
        val blocks = listOf(
            NovelContentBlock.Text(AnnotatedString("ab")),
            NovelContentBlock.Image(NovelImageSource.Remote("image"), "image"),
            NovelContentBlock.Rule,
        )
        val pages = paginateNovelBlocks(
            blocks,
            pageHeightPx = 5,
            spacingPx = 1,
            measureText = { block, start, available ->
                val count = minOf(2, available, block.text.length - start)
                NovelTextFit(start + count, count)
            },
            measureAtomicHeight = { 2 },
        )!!

        assertEquals(listOf(listOf(0, 1), listOf(2)), pages.map { page -> page.slices.map { it.blockIndex } })
        assertEquals(3, pages.sumOf { it.slices.size })
        assertEquals(listOf(0, 1, 2), pages.flatMap { it.slices }.map { it.blockIndex })
        assertEquals(NovelPageSlice(1), pages[0].slices[1])
        assertEquals(NovelPageSlice(2), pages[1].slices[0])
    }

    @Test
    fun rejectsImpossibleContentAndInvalidViewport() {
        val text = listOf(NovelContentBlock.Text(AnnotatedString("x")))
        assertNull(paginateNovelBlocks(text, 0, 0, { _, _, _ -> NovelTextFit(1, 1) }, { 1 }))
        assertNull(paginateNovelBlocks(text, 2, -1, { _, _, _ -> NovelTextFit(1, 1) }, { 1 }))
        assertNull(paginateNovelBlocks(text, 1, 0, { _, _, _ -> null }, { 1 }))
        assertNull(paginateNovelBlocks(text, 1, 0, { _, _, _ -> NovelTextFit(1, 2) }, { 1 }))
    }

    @Test
    fun exactFitAndBoundaryAnchorBelongToFollowingPage() {
        val blocks = listOf(NovelContentBlock.Text(AnnotatedString("abcd")))
        val pages = paginateNovelBlocks(
            blocks,
            pageHeightPx = 2,
            spacingPx = 0,
            measureText = { block, start, available ->
                val end = minOf(start + available, block.text.length)
                NovelTextFit(end, end - start)
            },
            measureAtomicHeight = { 1 },
        )!!

        assertEquals(2, pages.size)
        assertEquals(2, pages[0].slices.single().endExclusive)
        assertEquals(1, pageIndexForNovelAnchor(pages, NovelAnchor(0, 2)))
        assertEquals(0, pageIndexForNovelAnchor(pages, NovelAnchor(0, 1)))
        assertEquals(1, pageIndexForNovelAnchor(pages, NovelAnchor(99)))
    }

    @Test
    fun anchorBeforeFirstPageClampsToFirstPageAcrossSkippedEmptyBlock() {
        val pages = paginateNovelBlocks(
            listOf(
                NovelContentBlock.Text(AnnotatedString("")),
                NovelContentBlock.Text(AnnotatedString("abcd")),
            ),
            pageHeightPx = 2,
            spacingPx = 0,
            measureText = { block, start, available ->
                val end = minOf(start + available, block.text.length)
                NovelTextFit(end, end - start)
            },
            measureAtomicHeight = { 1 },
        )!!

        assertEquals(0, pageIndexForNovelAnchor(pages, NovelAnchor(0)))
    }

    @Test
    fun countsOddFinalSpread() {
        assertEquals(2, novelSpreadCount(pageCount = 3, panes = 2))
        assertEquals(1_073_741_824, novelSpreadCount(pageCount = Int.MAX_VALUE, panes = 2))
        assertEquals(1, novelSpreadForPage(pageIndex = 2, panes = 2))
        assertEquals(listOf(NovelPage(emptyList(), NovelAnchor(0), NovelAnchor(0))), paginateNovelBlocks(emptyList(), 10, 0, { _, _, _ -> null }, { 1 }))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderColorTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderColorTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderColorTest.kt).

The implementation below defines `NovelReaderColorTest`, `sixDigitReaderColorUsesSrgbArgbPacking`, `eightDigitReaderColorPreservesAlpha`, `invalidReaderColorIsRejected`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `sixDigitReaderColorUsesSrgbArgbPacking`
- `eightDigitReaderColorPreservesAlpha`
- `invalidReaderColorIsRejected`

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.ui.graphics.toArgb
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class NovelReaderColorTest {
    @Test
    fun sixDigitReaderColorUsesSrgbArgbPacking() {
        assertEquals(0xFF292832.toInt(), parseHexColor("#292832")?.toArgb())
    }

    @Test
    fun eightDigitReaderColorPreservesAlpha() {
        assertEquals(0x80292832.toInt(), parseHexColor("80292832")?.toArgb())
    }

    @Test
    fun invalidReaderColorIsRejected() {
        assertNull(parseHexColor("not-a-color"))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderProgressTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderProgressTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderProgressTest.kt).

The implementation below defines `NovelReaderProgressTest`, `persistedProgressAcceptsAuthorityRatiosAndMigratesLegacyPercentages`, `progressAndSeekUseMeasuredPixelExtent`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `persistedProgressAcceptsAuthorityRatiosAndMigratesLegacyPercentages`
- `progressAndSeekUseMeasuredPixelExtent`

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue

class NovelReaderProgressTest {
    @Test
    fun persistedProgressAcceptsAuthorityRatiosAndMigratesLegacyPercentages() {
        assertEquals(0.42, parseNovelProgressRatio("0.42"))
        assertEquals(0.42, parseNovelProgressRatio("42%"))
        assertEquals(1.0, parseNovelProgressRatio("120%"))
        assertEquals(0.0, parseNovelProgressRatio("invalid"))
    }

    @Test
    fun progressAndSeekUseMeasuredPixelExtent() {
        assertEquals(0.5, novelProgressRatio(offsetPx = 450, maxOffsetPx = 900))
        assertEquals(225, novelScrollOffset(maxOffsetPx = 900, ratio = 0.25))
        assertEquals(0.0, novelProgressRatio(offsetPx = 1, maxOffsetPx = Int.MAX_VALUE))
        assertEquals(0.0, novelProgressRatio(offsetPx = 1, maxOffsetPx = 0))
        assertFalse(novelProgressIsRead(0.899))
        assertTrue(novelProgressIsRead(0.9))
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModelTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModelTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelReaderViewModelTest.kt).

The implementation below defines `NovelReaderViewModelTest`, `tearDown`, `TestScope.viewModel`, `loadsDocumentAndAddsTheWebViewUserAgentToImageHeaders`, `failedExtractionShowsTheErrorOverTheTitleDescription`, `savingProgressMarksTheChapterReadPastNinetyPercent`, `autoScrollTogglePersistsPerTitle`, `speechFollowsEventsAndRestartsWithChangedVoiceSettings`, `clearingTheViewModelSilencesSpeechAndRejectsLaterCommands`, `Native` and 3 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `loadsDocumentAndAddsTheWebViewUserAgentToImageHeaders`
- `failedExtractionShowsTheErrorOverTheTitleDescription`
- `savingProgressMarksTheChapterReadPastNinetyPercent`
- `autoScrollTogglePersistsPerTitle`
- `speechFollowsEventsAndRestartsWithChangedVoiceSettings`
- `clearingTheViewModelSilencesSpeechAndRejectsLaterCommands`

Cross-chapter imports used by this file: [`DefaultYokanRepository`](../chapters/09-repository-and-library.md), [`LibraryIndexStore`](../chapters/09-repository-and-library.md), [`SettingsStore`](../chapters/09-repository-and-library.md), [`DbChapter`](../chapters/02-domain-and-settings-models.md), [`DbItemType`](../chapters/02-domain-and-settings-models.md), [`DbManga`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.lifecycle.ViewModelStore
import eu.friedcutlet.yokan.data.DefaultYokanRepository
import eu.friedcutlet.yokan.data.LibraryIndexStore
import eu.friedcutlet.yokan.data.SettingsStore
import eu.friedcutlet.yokan.database.DbChapter
import eu.friedcutlet.yokan.database.DbItemType
import eu.friedcutlet.yokan.database.DbManga
import eu.friedcutlet.yokan.database.DbSource
import eu.friedcutlet.yokan.database.InMemoryYokanDatabase
import eu.friedcutlet.yokan.database.seedDatabaseSnapshot
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.domain.Source
import eu.friedcutlet.yokan.services.tts.ProfileSpeechService
import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest
import eu.friedcutlet.yokan.services.tts.TextToSpeechService
import eu.friedcutlet.yokan.ui.ViewModelTestHost
import eu.friedcutlet.yokan.ui.screens.reader.autoScrollSettings
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

@OptIn(ExperimentalCoroutinesApi::class)
class NovelReaderViewModelTest {
    private val database = InMemoryYokanDatabase(
        seedDatabaseSnapshot().copy(
            sources = listOf(DbSource(id = 1, name = "Web", lang = "en", itemType = DbItemType.Novel, isAdded = true)),
            mangas = listOf(
                DbManga(id = 1, name = "Book", link = "/book", description = "Blurb", source = "Web", sourceId = 1, itemType = DbItemType.Novel, favorite = true),
            ),
            chapters = listOf(DbChapter(id = 10, mangaId = 1, name = "Ch 1", url = "/1")),
        ),
    )
    private val repository = DefaultYokanRepository(database)
    private val host = ViewModelTestHost()
    private val dispatcher = host.dispatcher
    private val native = Native()
    private val speechJob = SupervisorJob()
    private val speech = ProfileSpeechService(native, CoroutineScope(speechJob + dispatcher))

    @AfterTest
    fun tearDown() = host.close()

    private fun TestScope.viewModel(
        store: ViewModelStore? = null,
        loadHeaders: suspend (Source) -> Map<String, String> = { emptyMap() },
        loadDocument: suspend (Source?, Chapter) -> NovelDocument = { _, _ -> NovelDocument("<p>One</p><p>Two</p>") },
    ): Pair<NovelReaderViewModel, SettingsStore> {
        val settings = SettingsStore(repository, backgroundScope, onSchedulingChanged = {})
        val manga = requireNotNull(repository.manga(1))
        val chapter = repository.chapters(1).single()
        val create = {
            NovelReaderViewModel(
                manga, chapter, repository, settings, LibraryIndexStore(repository, backgroundScope, dispatcher), speech,
                loadHeaders, loadDocument, workDispatcher = dispatcher,
            )
        }
        val vm = if (store == null) host.create(create) else create().also { store.put("novel", it) }
        return vm to settings
    }

    @Test
    fun loadsDocumentAndAddsTheWebViewUserAgentToImageHeaders() = runTest {
        repository.updateDbSettings { it.copy(userAgent = "Agent") }
        val (vm, _) = viewModel(loadHeaders = { mapOf("Referer" to "https://web.test") })
        runCurrent()

        val state = vm.state.value
        assertEquals(false, state.loading)
        assertNull(state.error)
        assertEquals("<p>One</p><p>Two</p>", state.document?.html)
        assertEquals(mapOf("Referer" to "https://web.test", "User-Agent" to "Agent"), state.imageHeaders)
    }

    @Test
    fun failedExtractionShowsTheErrorOverTheTitleDescription() = runTest {
        val (vm, _) = viewModel(loadDocument = { _, _ -> error("Source offline") })
        runCurrent()

        assertEquals("Source offline", vm.state.value.error)
        assertEquals("Blurb", vm.state.value.document?.html)
    }

    @Test
    fun savingProgressMarksTheChapterReadPastNinetyPercent() = runTest {
        val (vm, _) = viewModel()

        vm.onEvent(NovelReaderEvent.SaveProgress(0.95))

        val chapter = repository.chapters(1).single()
        assertTrue(chapter.isRead)
        assertEquals("0.95", chapter.lastPageRead)
    }

    @Test
    fun autoScrollTogglePersistsPerTitle() = runTest {
        val (vm, settings) = viewModel()

        vm.onEvent(NovelReaderEvent.SetAutoScrollOffset(12f))
        vm.onEvent(NovelReaderEvent.SetAutoScrollEnabled(false))

        assertEquals(false, vm.state.value.autoScrollPlaying)
        val stored = settings.db.value.autoScrollSettings(1)
        assertEquals(false, stored.autoScroll)
        assertEquals(12.0, stored.pageOffset)
    }

    @Test
    fun speechFollowsEventsAndRestartsWithChangedVoiceSettings() = runTest {
        val (vm, settings) = viewModel()
        runCurrent()

        vm.onEvent(NovelReaderEvent.StartTts(listOf("One", "Two")))
        runCurrent()
        assertEquals(NovelTtsPlaybackState.Playing, vm.state.value.tts.playback)
        settings.updateDb { it.copy(ttsPitch = 1.5) }
        runCurrent()
        vm.onEvent(NovelReaderEvent.SkipNextTts)
        runCurrent()

        assertEquals(listOf("One" to 1.0, "One" to 1.5, "Two" to 1.5), native.spoken)
        assertEquals(1, vm.state.value.tts.paragraphIndex)
        vm.onEvent(NovelReaderEvent.StopTts)
        runCurrent()
        assertEquals(NovelTtsPlaybackState.Stopped, vm.state.value.tts.playback)
    }

    @Test
    fun clearingTheViewModelSilencesSpeechAndRejectsLaterCommands() = runTest {
        val store = ViewModelStore()
        val (vm, _) = viewModel(store)
        vm.onEvent(NovelReaderEvent.StartTts(listOf("One")))
        runCurrent()
        val stopsBefore = native.stops

        store.clear()
        runCurrent()
        vm.onEvent(NovelReaderEvent.StartTts(listOf("Late")))
        runCurrent()

        assertTrue(native.stops > stopsBefore)
        assertEquals(listOf("One" to 1.0), native.spoken)
        speech.closeAndJoin()
        speechJob.cancelAndJoin()
    }

    private class Native : TextToSpeechService {
        val spoken = mutableListOf<Pair<String, Double>>()
        var stops = 0
        override suspend fun voices(language: String?): List<String> = emptyList()
        override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) {
            spoken += text to request.pitch
            awaitCancellation()
        }
        override suspend fun stop() { stops++ }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContentTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContentTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContentTest.kt).

The implementation below defines `NovelRichContentTest`, `parsesStructuralBlocksLinksAndImages`, `resolvesEmbeddedEpubImageAgainstChapterPath`, `resolvesRootRelativeProtocolRelativeAndArchivePaths`, `preservesExplicitBreaksAtBlockBoundariesAndInStandaloneBlocks`, `trimsIncidentalBoundarySpacesAndKeepsLinkAcrossBreaks`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `parsesStructuralBlocksLinksAndImages`
- `resolvesEmbeddedEpubImageAgainstChapterPath`
- `resolvesRootRelativeProtocolRelativeAndArchivePaths`
- `preservesExplicitBreaksAtBlockBoundariesAndInStandaloneBlocks`
- `trimsIncidentalBoundarySpacesAndKeepsLinkAcrossBreaks`

Cross-chapter imports used by this file: [`Chapter`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.ui.text.LinkAnnotation
import eu.friedcutlet.yokan.domain.Chapter
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
import kotlin.test.assertIs
import kotlin.test.assertTrue

class NovelRichContentTest {
    @Test
    fun parsesStructuralBlocksLinksAndImages() {
        val html = """
            <h2>Chapter &amp; Two</h2>
            <p>Hello <strong>bold</strong> and <a href="../next.html">next</a>.</p>
            <blockquote>Quoted <em>text</em></blockquote>
            <pre>val x = 1\nprint(x)</pre>
            <table><tr><th>Name</th><td>Value</td></tr></table>
            <img src="../images/panel.png" alt="Panel">
            <hr>
        """.trimIndent()

        var openedLink: String? = null
        val content = parseNovelRichContent(
            html = html,
            baseUrl = "https://example.test/books/chapter/current.html",
            onOpenLink = { openedLink = it },
        )

        assertEquals(NovelTextBlockKind.Heading2, assertIs<NovelContentBlock.Text>(content.blocks[0]).kind)
        assertEquals("Chapter & Two", assertIs<NovelContentBlock.Text>(content.blocks[0]).text.text)
        val paragraph = assertIs<NovelContentBlock.Text>(content.blocks[1])
        val link = assertIs<LinkAnnotation.Url>(paragraph.text.getLinkAnnotations(0, paragraph.text.length).single().item)
        assertEquals("https://example.test/books/next.html", link.url)
        link.linkInteractionListener?.onClick(link)
        assertEquals(link.url, openedLink)
        assertEquals(NovelTextBlockKind.BlockQuote, assertIs<NovelContentBlock.Text>(content.blocks[2]).kind)
        assertEquals(NovelTextBlockKind.Preformatted, assertIs<NovelContentBlock.Text>(content.blocks[3]).kind)
        assertEquals(NovelTextBlockKind.TableRow, assertIs<NovelContentBlock.Text>(content.blocks[4]).kind)
        assertEquals("Name  |  Value", assertIs<NovelContentBlock.Text>(content.blocks[4]).text.text)
        val image = assertIs<NovelContentBlock.Image>(content.blocks[5])
        assertEquals("Panel", image.alt)
        assertEquals(
            "https://example.test/books/images/panel.png",
            assertIs<NovelImageSource.Remote>(image.source).url,
        )
        assertIs<NovelContentBlock.Rule>(content.blocks[6])
        assertTrue(content.plainText.contains("Quoted text"))
    }

    @Test
    fun resolvesEmbeddedEpubImageAgainstChapterPath() {
        val expected = byteArrayOf(1, 2, 3, 4)
        val chapterHref = "OEBPS/Text/chapter-1.xhtml"
        val content = parseNovelRichContent(
            html = "<p>Before</p><img src=\"../Images/cover%20art.jpg\"><p>After</p>",
            embeddedImage = { reference ->
                if (resolveEpubResourcePath(chapterHref, reference) == "OEBPS/Images/cover art.jpg") expected else null
            },
        )

        val image = assertIs<NovelContentBlock.Image>(content.blocks[1])
        assertContentEquals(expected, assertIs<NovelImageSource.Embedded>(image.source).bytes)
        assertEquals("OEBPS/Images/cover art.jpg", resolveEpubResourcePath(chapterHref, "../Images/cover%20art.jpg"))
    }

    @Test
    fun resolvesRootRelativeProtocolRelativeAndArchivePaths() {
        assertEquals(
            "https://cdn.example.test/a.jpg",
            resolveNovelReference("https://example.test/book/chapter", "//cdn.example.test/a.jpg"),
        )
        assertEquals(
            "https://example.test/images/a.jpg?size=2",
            resolveNovelReference("https://example.test/book/chapter", "/images/a.jpg?size=2"),
        )
        assertEquals("Images/a.jpg", normalizeArchiveEntry("OEBPS/Text/../../Images/a.jpg"))
    }

    @Test
    fun preservesExplicitBreaksAtBlockBoundariesAndInStandaloneBlocks() {
        val leading = parseNovelRichContent("<p><br><br>A</p>")
        assertEquals(listOf("\n\nA"), leading.blocks.map { assertIs<NovelContentBlock.Text>(it).text.text })
        assertEquals("\n\nA", leading.plainText)

        val trailing = parseNovelRichContent("<p>A<br><br></p>")
        assertEquals(listOf("A\n\n"), trailing.blocks.map { assertIs<NovelContentBlock.Text>(it).text.text })
        assertEquals("A\n\n", trailing.plainText)

        val standalone = parseNovelRichContent("<br><p>B</p>")
        assertEquals(listOf("\n", "B"), standalone.blocks.map { assertIs<NovelContentBlock.Text>(it).text.text })
        assertEquals("\n\n\nB", standalone.plainText)
    }

    @Test
    fun trimsIncidentalBoundarySpacesAndKeepsLinkAcrossBreaks() {
        val spaced = parseNovelRichContent("<p> \t A \t </p>")
        assertEquals("A", assertIs<NovelContentBlock.Text>(spaced.blocks.single()).text.text)

        val content = parseNovelRichContent("<p><a href=\"/next\">A<br><br>B</a></p>")
        val text = assertIs<NovelContentBlock.Text>(content.blocks.single()).text
        assertEquals("A\n\nB", text.text)
        val link = assertIs<LinkAnnotation.Url>(text.getLinkAnnotations(0, text.length).single().item)
        assertEquals("/next", link.url)
        assertEquals(0, text.getLinkAnnotations(0, text.length).single().start)
        assertEquals(text.length, text.getLinkAnnotations(0, text.length).single().end)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsControllerTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsControllerTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsControllerTest.kt).

The implementation below defines `NovelTtsControllerTest`, `extractsReadableTextBlocksInDocumentOrder`, `speaksParagraphsInOrderAndReportsProgress`, `pauseAndResumeRestartsAtCurrentWord`, `skipAndLiveSettingsRestartTheSelectedParagraph`, `ControlledTextToSpeechService`, `voices`, `speak`, `stop`, `reportProgress` and 1 further declarations.

Read the setup, action and assertions in these cases before implementing their production paths:

- `extractsReadableTextBlocksInDocumentOrder`
- `speaksParagraphsInOrderAndReportsProgress`
- `pauseAndResumeRestartsAtCurrentWord`
- `skipAndLiveSettingsRestartTheSelectedParagraph`

Cross-chapter imports used by this file: [`TextToSpeechRequest`](../chapters/24-settings-and-integrations.md), [`TextToSpeechService`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest
import eu.friedcutlet.yokan.services.tts.TextToSpeechService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)
class NovelTtsControllerTest {
    @Test
    fun extractsReadableTextBlocksInDocumentOrder() {
        val content = parseNovelRichContent(
            "<h2>Heading</h2><p>First <strong>paragraph</strong></p><img src=\"cover.jpg\"><blockquote>Quote</blockquote>",
        )

        assertEquals(
            listOf("Heading", "First paragraph", "Quote"),
            novelTtsParagraphs(content),
        )
    }

    @Test
    fun speaksParagraphsInOrderAndReportsProgress() = runTest {
        val service = ControlledTextToSpeechService()
        val controller = NovelTtsController(service, backgroundScope)

        controller.start(
            paragraphs = listOf("First paragraph", "Second paragraph"),
            request = TextToSpeechRequest(speechRate = 0.8, pitch = 1.2),
        )
        runCurrent()

        assertEquals(listOf("First paragraph"), service.spokenTexts)
        assertEquals(NovelTtsPlaybackState.Playing, controller.state.value.playback)
        assertEquals(0, controller.state.value.paragraphIndex)
        service.reportProgress(0, 5)
        assertEquals(0, controller.state.value.wordStart)
        assertEquals(5, controller.state.value.wordEnd)

        service.completeCurrent()
        runCurrent()
        assertEquals(listOf("First paragraph", "Second paragraph"), service.spokenTexts)
        assertEquals(1, controller.state.value.paragraphIndex)
        assertEquals(1f, controller.state.value.progress)

        service.completeCurrent()
        runCurrent()
        assertEquals(NovelTtsPlaybackState.Stopped, controller.state.value.playback)
    }

    @Test
    fun pauseAndResumeRestartsAtCurrentWord() = runTest {
        val service = ControlledTextToSpeechService()
        val controller = NovelTtsController(service, backgroundScope)

        controller.start(listOf("Read this sentence"), TextToSpeechRequest())
        runCurrent()
        service.reportProgress(5, 9)

        val stopsBeforePause = service.stopCount
        controller.pause()
        assertEquals(NovelTtsPlaybackState.Paused, controller.state.value.playback)
        controller.resume()
        runCurrent()

        assertEquals(listOf("Read this sentence", "this sentence"), service.spokenTexts)
        assertEquals(stopsBeforePause + 1, service.stopCount)
    }

    @Test
    fun skipAndLiveSettingsRestartTheSelectedParagraph() = runTest {
        val service = ControlledTextToSpeechService()
        val controller = NovelTtsController(service, backgroundScope)
        controller.start(listOf("One", "Two", "Three"), TextToSpeechRequest())
        runCurrent()

        controller.skipNext()
        runCurrent()
        assertEquals(1, controller.state.value.paragraphIndex)
        assertEquals("Two", service.spokenTexts.last())

        controller.updateRequest(TextToSpeechRequest(speechRate = 1.4, pitch = 0.8))
        runCurrent()
        assertEquals("Two", service.spokenTexts.last())
        assertEquals(1.4, service.requests.last().speechRate)
        assertEquals(0.8, service.requests.last().pitch)

        controller.skipPrevious()
        runCurrent()
        assertEquals(0, controller.state.value.paragraphIndex)
        assertEquals("One", service.spokenTexts.last())
    }
}

private class ControlledTextToSpeechService : TextToSpeechService {
    val spokenTexts = mutableListOf<String>()
    val requests = mutableListOf<TextToSpeechRequest>()
    var stopCount = 0
    private val completions = Channel<Unit>(Channel.UNLIMITED)
    private var progress: ((Int, Int) -> Unit)? = null

    override suspend fun voices(language: String?): List<String> = emptyList()

    override suspend fun speak(
        text: String,
        request: TextToSpeechRequest,
        onProgress: (startOffset: Int, endOffset: Int) -> Unit,
    ) {
        spokenTexts += text
        requests += request
        progress = onProgress
        completions.receive()
    }

    override suspend fun stop() {
        stopCount += 1
    }

    fun reportProgress(start: Int, end: Int) {
        progress?.invoke(start, end)
    }

    fun completeCurrent() {
        completions.trySend(Unit)
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsOwnershipTest.kt
### Write `composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsOwnershipTest.kt`

Create this path in your reconstruction project. Source set: **commonTest**. [Exact file download](../reference/source/composeApp/src/commonTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelTtsOwnershipTest.kt).

The implementation below defines `NovelTtsOwnershipTest`, `Fixture`, `close`, `Native`, `voices`, `speak`, `stop`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `pausedAndSupersededUtterancesCannotUpdateHighlight`
- `retainedCommandsCannotRestartRetiredController`
- `retirementDuringRestartCleanupCannotStartReplacementParagraph`
- `canceledQueuedCommandCannotStartPlaybackAfterCleanup`

Cross-chapter imports used by this file: [`ProfileSpeechService`](../chapters/24-settings-and-integrations.md), [`TextToSpeechRequest`](../chapters/24-settings-and-integrations.md), [`TextToSpeechService`](../chapters/24-settings-and-integrations.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)

package eu.friedcutlet.yokan.ui.screens.novel

import eu.friedcutlet.yokan.services.tts.ProfileSpeechService
import eu.friedcutlet.yokan.services.tts.TextToSpeechRequest
import eu.friedcutlet.yokan.services.tts.TextToSpeechService
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitCancellation
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

class NovelTtsOwnershipTest {
    @Test fun pausedAndSupersededUtterancesCannotUpdateHighlight() = runTest {
        val f = Fixture(this)
        try {
            f.controller.start(listOf("First paragraph", "Second paragraph"), TextToSpeechRequest())
            runCurrent()
            val first = f.native.progress.single()
            first(0, 5)
            f.controller.pause()
            val paused = f.controller.state.value
            first(7, 9)
            assertEquals(paused, f.controller.state.value)
            f.controller.resume()
            runCurrent()
            val resumed = f.native.progress.last()
            f.controller.skipNext()
            runCurrent()
            first(1, 2); resumed(3, 4)
            assertEquals(1, f.controller.state.value.paragraphIndex)
            assertEquals(-1, f.controller.state.value.wordStart)
            f.native.progress.last()(0, 6)
            assertEquals(6, f.controller.state.value.wordEnd)
        } finally { f.close() }
    }

    @Test fun retainedCommandsCannotRestartRetiredController() = runTest {
        val f = Fixture(this)
        try {
            f.controller.start(listOf("First", "Second"), TextToSpeechRequest())
            runCurrent()
            val old = f.native.progress.single()
            f.controller.closeAndJoin()
            old(0, 4)
            assertEquals(NovelTtsUiState(), f.controller.state.value)
            assertFailsWith<CancellationException> { f.controller.start(listOf("Late"), TextToSpeechRequest()) }
            assertFailsWith<CancellationException> { f.controller.resume() }
            assertFailsWith<CancellationException> { f.controller.pause() }
            assertFailsWith<CancellationException> { f.controller.skipNext() }
            assertFailsWith<CancellationException> { f.controller.skipPrevious() }
            assertFailsWith<CancellationException> { f.controller.updateRequest(TextToSpeechRequest(pitch = 1.5)) }
            assertFailsWith<CancellationException> { f.controller.stop() }
            assertEquals(listOf("First"), f.native.spoken)
        } finally { f.close() }
    }

    @Test fun retirementDuringRestartCleanupCannotStartReplacementParagraph() = runTest {
        val f = Fixture(this)
        val release = CompletableDeferred<Unit>()
        f.native.stopping = { release.await() }
        try {
            f.controller.start(listOf("First", "Second"), TextToSpeechRequest())
            runCurrent()
            val restart = async { f.controller.skipNext() }
            runCurrent()
            assertFalse(restart.isCompleted)
            f.controller.retire()
            val close = async { f.controller.closeAndJoin() }
            runCurrent()
            assertFalse(close.isCompleted)
            release.complete(Unit)
            close.await()
            restart.join()
            assertEquals(listOf("First"), f.native.spoken)
            assertEquals(NovelTtsUiState(), f.controller.state.value)
        } finally { release.complete(Unit); f.close() }
    }

    @Test fun canceledQueuedCommandCannotStartPlaybackAfterCleanup() = runTest {
        val f = Fixture(this)
        val release = CompletableDeferred<Unit>()
        f.native.stopping = { release.await() }
        try {
            f.controller.start(listOf("First"), TextToSpeechRequest())
            runCurrent()
            val stopping = async { f.controller.stop() }
            runCurrent()
            val queued = async { f.controller.start(listOf("Late"), TextToSpeechRequest()) }
            runCurrent()
            queued.cancel()
            runCurrent()
            release.complete(Unit)
            stopping.await()
            queued.join()
            runCurrent()
            assertEquals(listOf("First"), f.native.spoken)
            assertEquals(NovelTtsUiState(), f.controller.state.value)
        } finally { release.complete(Unit); f.close() }
    }

    private class Fixture(test: TestScope) {
        val owner = SupervisorJob()
        val scope = CoroutineScope(owner + StandardTestDispatcher(test.testScheduler))
        val native = Native()
        val speech = ProfileSpeechService(native, scope)
        val reader = speech.reader()
        val controller = NovelTtsController(reader, scope) { reader.isAvailable }
        suspend fun close() { controller.closeAndJoin(); speech.closeAndJoin(); owner.cancelAndJoin() }
    }
    private class Native : TextToSpeechService {
        val spoken = mutableListOf<String>()
        val progress = mutableListOf<(Int, Int) -> Unit>()
        var stopping: suspend () -> Unit = { }
        override suspend fun voices(language: String?): List<String> = emptyList()
        override suspend fun speak(text: String, request: TextToSpeechRequest, onProgress: (Int, Int) -> Unit) {
            spoken += text; progress += onProgress
            awaitCancellation()
        }
        override suspend fun stop() { stopping() }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentOwnershipTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentOwnershipTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelContentOwnershipTest.kt).

The implementation below defines `NovelContentOwnershipTest`, `TestScope.blockedReadIsJoined`, `UiFixture`, `click`, `show`, `pump`, `ui`, `finish`, `onUi`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `disposedParsedLinkCannotNavigateAndRemountGetsANewLink`
- `chapterReplacementRejectsThePreviousChaptersLink`
- `ownerReplacementWithTheSameChapterCannotRetargetARetainedLink`
- `backgroundLifecycleRejectsLinksImmediatelyAndResumePreservesCurrentContent`
- `replacingTheLifecycleOwnerExpiresPreviousLinksAndPublishesCurrentLinks`
- `retirementAdmissionRejectsLinksBeforeJobCancellationAndSameScreenUsesLatestAction`
- `callerCancellationJoinsABlockedLocalReadWithoutDeliveringParsedContent`
- `ownerRetirementJoinsABlockedLocalReadWithoutDeliveringParsedContent`

Cross-chapter imports used by this file: [`Chapter`](../chapters/02-domain-and-settings-models.md), [`ProfileReaderContentTest`](../chapters/06-extension-runtimes.md). Keep those contracts available as you connect this step.

```kotlin
@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class, androidx.compose.ui.ExperimentalComposeUiApi::class)

package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.text.LinkAnnotation
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import androidx.lifecycle.compose.LocalLifecycleOwner
import eu.friedcutlet.yokan.domain.Chapter
import eu.friedcutlet.yokan.services.extensions.ProfileReaderContentTest
import java.util.concurrent.CountDownLatch
import java.util.concurrent.FutureTask
import java.util.concurrent.TimeUnit
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertNotSame
import kotlin.test.assertTrue
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.cancelAndJoin
import kotlinx.coroutines.test.TestScope
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest

class NovelContentOwnershipTest {
    @Test fun disposedParsedLinkCannotNavigateAndRemountGetsANewLink() = runTest {
        val f = UiFixture(this)
        try {
            f.click(f.link)
            assertEquals(listOf("A"), f.opened)
            val old = f.link
            f.show(false)
            f.click(old)
            assertEquals(listOf("A"), f.opened)
            assertTrue(f.a.owner.isActive)
            f.show(true)
            assertNotSame(old, f.link)
            f.click(old); f.click(f.link)
            assertEquals(listOf("A", "A"), f.opened)
        } finally { f.finish() }
    }

    @Test fun chapterReplacementRejectsThePreviousChaptersLink() = runTest {
        val f = UiFixture(this)
        try {
            val old = f.link
            f.ui { f.chapter.value = 11 }; f.pump()
            f.click(old); f.click(f.link)
            assertEquals(listOf("A"), f.opened)
        } finally { f.finish() }
    }

    @Test fun ownerReplacementWithTheSameChapterCannotRetargetARetainedLink() = runTest {
        val f = UiFixture(this)
        try {
            val old = f.link
            f.ui { f.content.value = f.b.content; f.target.value = "B" }; f.pump()
            f.click(old); f.click(f.link)
            assertEquals(listOf("B"), f.opened)
            assertTrue(f.a.owner.isActive)
            assertTrue(f.b.owner.isActive)
        } finally { f.finish() }
    }

    @Test fun backgroundLifecycleRejectsLinksImmediatelyAndResumePreservesCurrentContent() = runTest {
        val f = UiFixture(this)
        try {
            val current = f.link
            f.ui { f.registry.currentState = Lifecycle.State.CREATED }
            // No recomposition frame: the click checks the actual lifecycle.
            f.click(current); assertTrue(f.opened.isEmpty())
            f.ui { f.registry.currentState = Lifecycle.State.RESUMED }
            f.click(current); assertEquals(listOf("A"), f.opened)
        } finally { f.finish() }
    }

    @Test fun replacingTheLifecycleOwnerExpiresPreviousLinksAndPublishesCurrentLinks() = runTest {
        val f = UiFixture(this)
        try {
            val old = f.link
            val replacement = object : LifecycleOwner {
                override val lifecycle = LifecycleRegistry.createUnsafe(this)
            }
            f.ui {
                replacement.lifecycle.currentState = Lifecycle.State.RESUMED
                f.currentLifecycle.value = replacement
            }
            f.pump()
            f.click(old); f.click(f.link)
            assertEquals(listOf("A"), f.opened)
        } finally { f.finish() }
    }

    @Test fun retirementAdmissionRejectsLinksBeforeJobCancellationAndSameScreenUsesLatestAction() = runTest {
        val f = UiFixture(this)
        try {
            val current = f.link
            f.ui { f.target.value = "latest" }; f.pump()
            f.click(current)
            assertEquals(listOf("latest"), f.opened)
            f.a.open = false
            f.click(current)
            assertEquals(listOf("latest"), f.opened)
            assertTrue(f.a.owner.isActive)
        } finally { f.finish() }
    }

    @Test fun callerCancellationJoinsABlockedLocalReadWithoutDeliveringParsedContent() = runTest {
        blockedReadIsJoined(retireOwner = false)
    }

    @Test fun ownerRetirementJoinsABlockedLocalReadWithoutDeliveringParsedContent() = runTest {
        blockedReadIsJoined(retireOwner = true)
    }

    private suspend fun TestScope.blockedReadIsJoined(retireOwner: Boolean) {
        val f = ProfileReaderContentTest.Fixture(this, fileDispatcher = Dispatchers.Default)
        val entered = CompletableDeferred<Unit>()
        val release = CountDownLatch(1)
        var parsed = false
        f.beforeEpubChapterRead = {
            entered.complete(Unit)
            check(release.await(10, TimeUnit.SECONDS)) { "Blocked archive read was not released" }
        }
        val chapter = Chapter(10, 1, "Local", "/chapter", archivePath = "/A/book.epub#0")
        val request = async { f.content.novelContent(f.source, "Book", chapter) { parsed = true } }
        try {
            entered.await()
            val retiring = if (retireOwner) async { f.owner.cancelAndJoin() } else null
            if (!retireOwner) request.cancel()
            runCurrent()
            assertFalse(request.isCompleted, "extraction is still reading the captured archive")
            if (retiring != null) assertFalse(retiring.isCompleted, "retirement joins the blocking file read")
            release.countDown()
            if (retireOwner) {
                retiring?.await()
                assertFailsWith<CancellationException> { request.await() }
            } else request.join()
            assertFalse(parsed)
            assertTrue(f.epubResourceReads.isEmpty())
            assertEquals(!retireOwner, f.owner.isActive)
        } finally { release.countDown(); request.cancelAndJoin(); f.close() }
    }

    private class UiFixture(val test: TestScope) {
        val a = ProfileReaderContentTest.Fixture(test, "A")
        val b = ProfileReaderContentTest.Fixture(test, "B")
        val content = mutableStateOf(a.content)
        val chapter = mutableStateOf(10L)
        val visible = mutableStateOf(true)
        val target = mutableStateOf("A")
        val opened = mutableListOf<String>()
        lateinit var link: LinkAnnotation.Url
        val lifecycleOwner = object : LifecycleOwner {
            override val lifecycle = LifecycleRegistry.createUnsafe(this)
        }
        val registry = lifecycleOwner.lifecycle as LifecycleRegistry
        val currentLifecycle = mutableStateOf<LifecycleOwner>(lifecycleOwner)
        val scene = ui {
            registry.currentState = Lifecycle.State.RESUMED
            ImageComposeScene(100, 100, coroutineContext = UnconfinedTestDispatcher(test.testScheduler)) {
                CompositionLocalProvider(LocalLifecycleOwner provides currentLifecycle.value) {
                    if (visible.value) {
                        val currentTarget = target.value
                        val open = rememberNovelOpenLink(content.value, chapter.value) { opened += currentTarget }
                        val parsed = parseNovelRichContent("<p><a href='https://book.test/next'>Next</a></p>", onOpenLink = open)
                        val text = assertIs<NovelContentBlock.Text>(parsed.blocks.single()).text
                        val annotation = assertIs<LinkAnnotation.Url>(text.getLinkAnnotations(0, text.length).single().item)
                        SideEffect { link = annotation }
                    }
                }
            }
        }
        init { pump() }
        fun click(annotation: LinkAnnotation.Url) = ui { annotation.linkInteractionListener?.onClick(annotation) }
        fun show(value: Boolean) { ui { visible.value = value }; pump() }
        fun pump() = ui { repeat(3) {
            test.testScheduler.runCurrent()
            scene.render(test.testScheduler.currentTime * 1_000_000).close()
            test.testScheduler.runCurrent()
        } }
        fun <T> ui(block: () -> T): T = onUi(block)
        suspend fun finish() { ui { scene.close() }; a.close(); b.close() }
    }

    private companion object {
        fun <T> onUi(block: () -> T): T {
            if (SwingUtilities.isEventDispatchThread()) return block()
            val task = FutureTask(block)
            SwingUtilities.invokeAndWait(task)
            return task.get()
        }
    }
}
```
[chapter-file-end]: #

[chapter-file-start]: #composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReaderMeasureTest.kt
### Write `composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReaderMeasureTest.kt`

Create this path in your reconstruction project. Source set: **desktopTest**. [Exact file download](../reference/source/composeApp/src/desktopTest/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelPagedReaderMeasureTest.kt).

The implementation below defines `NovelPagedReaderMeasureTest`, `realComposeMeasurementPaginatesAndPreservesEverySourceCharacter`, `everyAcceptedFragmentHasMeasuredHeightWithinPageBudget`, `MeasurementProbe`, `String.escapeForTest`, `String.toAnnotatedString`, `onUi`.

Read the setup, action and assertions in these cases before implementing their production paths:

- `realComposeMeasurementPaginatesAndPreservesEverySourceCharacter`
- `everyAcceptedFragmentHasMeasuredHeightWithinPageBudget`

Cross-chapter imports used by this file: [`DbNovelPageMode`](../chapters/02-domain-and-settings-models.md), [`DbNovelTextAlign`](../chapters/02-domain-and-settings-models.md). Keep those contracts available as you connect this step.

```kotlin
package eu.friedcutlet.yokan.ui.screens.novel

import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.ImageComposeScene
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.use
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.graphics.Color
import eu.friedcutlet.yokan.database.DbNovelPageMode
import eu.friedcutlet.yokan.database.DbNovelTextAlign
import java.util.concurrent.FutureTask
import javax.swing.SwingUtilities
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertTrue

class NovelPagedReaderMeasureTest {
    @Test
    fun realComposeMeasurementPaginatesAndPreservesEverySourceCharacter() {
        listOf("A\nB", "A\n", "A\n\nB", "A\r\n\r\nB", "\nA", "\n\nA", "\n", "A\r\n", "one two three four five six seven eight nine ten").forEach { source ->
            val isBreakCase = source.contains('\n') || source.contains('\r')
            val width = if (isBreakCase) 320 else 390
            val height = if (isBreakCase) 80 else 560
            onUi {
                var invalid = false
                var readyPages: List<NovelPage>? = null
                val scene = ImageComposeScene(width, height) {
                    NovelPagedReader(
                        content = NovelRichContent(
                            blocks = listOf(NovelContentBlock.Text(AnnotatedString(source))),
                            plainText = source,
                        ),
                        pageMode = DbNovelPageMode.Single,
                        requestedPageRatio = 0.0,
                        sourceAnchor = null,
                        fontSize = 14,
                        lineHeight = 1.2,
                        textAlign = DbNovelTextAlign.Left,
                        fontFamily = FontFamily.Serif,
                        textColor = Color.Black,
                        imageHeaders = emptyMap(),
                        paragraphSpacing = 12.dp,
                        padding = 0.dp,
                        onPageChanged = { _, _ -> },
                        onComplete = { _, _ -> },
                        onInvalidLayout = { invalid = true },
                        onPagesReady = { readyPages = it },
                    )
                }
                try {
                    repeat(4) { scene.render(it * 16_000_000L).close() }
                    assertFalse(invalid, "source should fit across pages: ${source.escapeForTest()}")
                    val pages = assertNotNull(readyPages, "pagination should produce pages for ${source.escapeForTest()}")
                    assertTrue(pages.isNotEmpty())
                    val slices = pages.flatMap { it.slices }
                    var next = 0
                    slices.forEach { slice ->
                        assertEquals(0, slice.blockIndex)
                        assertEquals(next, slice.start, "source gap or duplicate for ${source.escapeForTest()}")
                        assertTrue(slice.endExclusive > slice.start)
                        next = slice.endExclusive
                    }
                    assertEquals(source.length, next)
                    assertEquals(source, slices.joinToString("") { source.substring(it.start, it.endExclusive) })
                    if (source == "A\nB") assertEquals(2, pages.size, "one-line viewport should split at the newline")
                    val renderedPages = pages.map { page ->
                        page.slices.joinToString("") { slice ->
                            renderNovelTextFragment(source.toAnnotatedString(), slice.start, slice.endExclusive).text
                        }
                    }
                    when (source) {
                        "A\nB" -> assertEquals(listOf("A", "B"), renderedPages)
                        "A\n" -> assertEquals(listOf("A", "\u00A0"), renderedPages)
                        "A\n\nB", "A\r\n\r\nB" -> assertEquals(
                            listOf("A", "\u00A0", "B"),
                            renderedPages,
                            "${source.escapeForTest()} slices=${pages.map { it.slices }}",
                        )
                        "\nA" -> assertEquals(listOf("\u00A0", "A"), renderedPages)
                        "\n\nA" -> assertEquals(listOf("\u00A0", "\u00A0", "A"), renderedPages)
                        "\n" -> assertEquals(listOf("\u00A0"), renderedPages)
                        "A\r\n" -> assertEquals(listOf("A", "\u00A0"), renderedPages)
                    }
                } finally {
                    scene.close()
                }
            }
        }
    }

    @Test
    fun everyAcceptedFragmentHasMeasuredHeightWithinPageBudget() {
        onUi {
            val source = "A\nB\n\nC\n"
            var allFragmentsFit = false
            val scene = ImageComposeScene(320, 80) {
                MeasurementProbe(source) { result -> allFragmentsFit = result }
            }
            try {
                scene.render().close()
                assertTrue(allFragmentsFit, "all source ranges should advance with measured height within the one-line page budget")
            } finally {
                scene.close()
            }
        }
    }

    @Composable
    private fun MeasurementProbe(source: String, onComplete: (Boolean) -> Unit) {
        val density = LocalDensity.current
        val measurer = rememberTextMeasurer()
        val block = NovelContentBlock.Text(AnnotatedString(source))
        val style = MaterialTheme.typography.bodyLarge.merge(
            TextStyle(color = Color.Black, fontSize = 14.sp, lineHeight = 17.sp, fontFamily = FontFamily.Serif),
        )
        val width = with(density) { 280.dp.roundToPx() }
        val pageHeight = with(density) { 32.dp.roundToPx() }
        var cursor = 0
        var valid = true
        var steps = 0
        while (cursor < source.length && steps++ <= source.length) {
            val fit = measureNovelTextFit(measurer, block, cursor, pageHeight, width, style)
            if (fit == null || fit.endExclusive <= cursor || fit.heightPx !in 1..pageHeight) {
                valid = false
                break
            }
            cursor = fit.endExclusive
        }
        onComplete(valid && cursor == source.length)
    }

    private fun String.escapeForTest() = replace("\n", "\\n")

    private fun String.toAnnotatedString() = AnnotatedString(this)

    private fun <T> onUi(block: () -> T): T {
        val task = FutureTask<T> { block() }
        SwingUtilities.invokeAndWait(task)
        return task.get()
    }
}
```
[chapter-file-end]: #

### Completion record

- [ ] Every implementation/configuration and required asset shown above is present at its displayed path.
- [ ] Cross-chapter imports resolve against the intended contracts and platform source sets.
- [ ] The tests for this chapter pass in the rebuilt app; record the command, platform and result.
- [ ] Native, device, browser and live-service checks have evidence or an explicit “not run” entry.
[chapter-content-end]: #


Gate: compare scroll and paged reading on the same chapter, resize/change font, exit/reopen and verify equivalent logical progress. Test embedded resources/links, cancellation during content loading, TTS ownership and profile switch. Use pagination/progress/rich-content/TTS tests and desktop measured-layout tests, then platform speech smoke tests.
