Yokan / rebuild
Course 1 8624561

NovelRichContent.kt

composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelRichContent.kt

implementation234 lines
1package eu.friedcutlet.yokan.ui.screens.novel23import androidx.compose.foundation.background4import androidx.compose.foundation.border5import androidx.compose.foundation.layout.Box6import androidx.compose.foundation.layout.Column7import androidx.compose.foundation.layout.Row8import androidx.compose.foundation.layout.fillMaxWidth9import androidx.compose.foundation.layout.heightIn10import androidx.compose.foundation.layout.height11import androidx.compose.foundation.layout.padding12import androidx.compose.foundation.layout.width13import androidx.compose.foundation.relocation.BringIntoViewRequester14import androidx.compose.foundation.relocation.bringIntoViewRequester15import androidx.compose.foundation.shape.RoundedCornerShape16import androidx.compose.foundation.text.selection.SelectionContainer17import androidx.compose.material3.HorizontalDivider18import androidx.compose.material3.MaterialTheme19import androidx.compose.material3.Text20import androidx.compose.runtime.Composable21import androidx.compose.runtime.LaunchedEffect22import androidx.compose.runtime.getValue23import androidx.compose.runtime.mutableIntStateOf24import androidx.compose.runtime.remember25import androidx.compose.runtime.setValue26import androidx.compose.ui.Alignment27import androidx.compose.ui.Modifier28import androidx.compose.ui.draw.clip29import androidx.compose.ui.graphics.Color30import androidx.compose.ui.layout.ContentScale31import androidx.compose.ui.text.SpanStyle32import androidx.compose.ui.text.buildAnnotatedString33import androidx.compose.ui.text.font.FontFamily34import androidx.compose.ui.text.font.FontWeight35import androidx.compose.ui.text.style.TextAlign36import androidx.compose.ui.unit.Dp37import androidx.compose.ui.unit.dp38import androidx.compose.ui.unit.sp39import coil3.compose.AsyncImage40import coil3.compose.LocalPlatformContext41import coil3.network.NetworkHeaders42import coil3.network.httpHeaders43import coil3.request.ImageRequest44import eu.friedcutlet.yokan.database.DbNovelTextAlign4546@Composable47internal fun NovelRichContentView(48    content: NovelRichContent,49    textColor: Color,50    fontSize: Int,51    lineHeight: Double,52    textAlign: DbNovelTextAlign,53    fontFamily: FontFamily,54    imageHeaders: Map<String, String>,55    paragraphSpacing: Dp,56    modifier: Modifier = Modifier,57    ttsState: NovelTtsUiState? = null,58) {59    Column(60        modifier = modifier.fillMaxWidth(),61        verticalArrangement = androidx.compose.foundation.layout.Arrangement.spacedBy(paragraphSpacing),62    ) {63        var textIndex = 064        content.blocks.forEach { block ->65            when (block) {66                is NovelContentBlock.Text -> {67                    val currentTextIndex = textIndex++68                    NovelTextBlock(69                        block = block,70                        textColor = textColor,71                        fontSize = fontSize,72                        lineHeight = lineHeight,73                        textAlign = textAlign.toTextAlign(),74                        fontFamily = fontFamily,75                        ttsActive = ttsState?.paragraphIndex == currentTextIndex &&76                            ttsState.playback != NovelTtsPlaybackState.Stopped,77                        ttsWordStart = ttsState?.wordStart ?: -1,78                        ttsWordEnd = ttsState?.wordEnd ?: -1,79                    )80                }81                is NovelContentBlock.Image -> NovelContentImage(block, imageHeaders)82                NovelContentBlock.Rule -> HorizontalDivider(modifier = Modifier.padding(vertical = 20.dp))83            }84        }85    }86}8788@Composable89private fun NovelTextBlock(90    block: NovelContentBlock.Text,91    textColor: Color,92    fontSize: Int,93    lineHeight: Double,94    textAlign: TextAlign,95    fontFamily: FontFamily,96    ttsActive: Boolean,97    ttsWordStart: Int,98    ttsWordEnd: Int,99) {100    val headingScale = novelHeadingScale(block.kind)101    val bringIntoViewRequester = remember { BringIntoViewRequester() }102    LaunchedEffect(ttsActive) {103        if (ttsActive) bringIntoViewRequester.bringIntoView()104    }105    val displayedText = remember(block.text, ttsActive, ttsWordStart, ttsWordEnd) {106        buildAnnotatedString {107            append(block.text)108            val highlightStart = ttsWordStart.coerceIn(0, block.text.length)109            val highlightEnd = ttsWordEnd.coerceIn(highlightStart, block.text.length)110            if (ttsActive && highlightEnd > highlightStart) {111                addStyle(112                    SpanStyle(background = Color(0x66FFD54F)),113                    highlightStart,114                    highlightEnd,115                )116            }117        }118    }119    val blockModifier = when (block.kind) {120        NovelTextBlockKind.BlockQuote -> Modifier121            .fillMaxWidth()122            .border(width = 0.dp, color = Color.Transparent)123            .padding(vertical = 10.dp)124        NovelTextBlockKind.Preformatted -> Modifier125            .fillMaxWidth()126            .clip(RoundedCornerShape(8.dp))127            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.45f))128            .padding(8.dp)129        NovelTextBlockKind.TableRow -> Modifier130            .fillMaxWidth()131            .border(0.5.dp, MaterialTheme.colorScheme.outlineVariant)132            .padding(8.dp)133        else -> Modifier.fillMaxWidth()134    }.bringIntoViewRequester(bringIntoViewRequester)135    val paragraph = @Composable {136        SelectionContainer {137            Text(138                text = displayedText,139                modifier = blockModifier,140                color = textColor,141                fontSize = (fontSize * headingScale).sp,142                lineHeight = (fontSize * headingScale * lineHeight).sp,143                textAlign = textAlign,144                fontFamily = if (block.kind == NovelTextBlockKind.Preformatted) FontFamily.Monospace else fontFamily,145                fontWeight = if (block.kind.name.startsWith("Heading")) FontWeight.Bold else null,146            )147        }148    }149    if (block.kind == NovelTextBlockKind.BlockQuote) {150        Row(modifier = Modifier.fillMaxWidth().padding(vertical = 10.dp)) {151            Box(152                Modifier153                    .width(4.dp)154                    .heightIn(min = 32.dp)155                    .align(Alignment.CenterVertically)156                    .background(MaterialTheme.colorScheme.outline),157            )158            Box(Modifier.weight(1f).padding(start = 15.dp)) { paragraph() }159        }160    } else {161        paragraph()162    }163}164165@Composable166internal fun NovelContentImage(167    block: NovelContentBlock.Image,168    headers: Map<String, String>,169    maxHeight: Dp = 720.dp,170    fixedHeight: Dp? = null,171) {172    val context = LocalPlatformContext.current173    var failed by remember(block.source) { mutableIntStateOf(0) }174    val model = remember(context, block.source, headers) {175        when (val source = block.source) {176            is NovelImageSource.Embedded -> ImageRequest.Builder(context)177                .data(source.bytes)178                .memoryCacheKey("epub:${source.cacheKey}:${source.bytes.size}")179                .build()180            is NovelImageSource.Remote -> ImageRequest.Builder(context)181                .data(source.url)182                .apply {183                    if (headers.isNotEmpty()) {184                        httpHeaders(185                            NetworkHeaders.Builder().apply {186                                headers.forEach { (name, value) -> set(name, value) }187                            }.build(),188                        )189                    }190                }191                .build()192        }193    }194    Box(195        modifier = Modifier196            .fillMaxWidth()197            .then(if (fixedHeight == null) Modifier.padding(vertical = 8.dp) else Modifier)198            .then(if (fixedHeight != null) Modifier.height(fixedHeight) else Modifier),199        contentAlignment = Alignment.Center,200    ) {201        if (failed == 0) {202            AsyncImage(203                model = model,204                contentDescription = block.alt,205                contentScale = ContentScale.Fit,206                modifier = Modifier207                    .fillMaxWidth()208                    .then(209                        if (fixedHeight != null) Modifier.height(fixedHeight)210                        else Modifier.heightIn(min = 32.dp, max = maxHeight.coerceAtLeast(32.dp)),211                    ),212                onError = { failed = 1 },213            )214        } else {215            Text(216                text = "Image not loaded: ${block.alt}",217                color = MaterialTheme.colorScheme.error,218                modifier = Modifier219                    .clip(RoundedCornerShape(8.dp))220                    .background(MaterialTheme.colorScheme.errorContainer.copy(alpha = 0.35f))221                    .padding(8.dp)222                    .border(1.dp, MaterialTheme.colorScheme.error, RoundedCornerShape(8.dp))223                    .padding(8.dp),224            )225        }226    }227}228229private fun DbNovelTextAlign.toTextAlign(): TextAlign = when (this) {230    DbNovelTextAlign.Left -> TextAlign.Start231    DbNovelTextAlign.Center -> TextAlign.Center232    DbNovelTextAlign.Right -> TextAlign.End233    DbNovelTextAlign.Block -> TextAlign.Justify234}235

Search chapters, reference and source filenames.