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, 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, 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 }