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, 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("|<[^>]+>|[^<]+") 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() var builder = AnnotatedString.Builder() val markup = ArrayDeque() var kind = NovelTextBlockKind.Paragraph var orderedListDepth = 0 val orderedListIndexes = mutableListOf() 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("