NovelHtmlParser.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/ui/screens/novel/NovelHtmlParser.kt
1package eu.friedcutlet.yokan.ui.screens.novel23import androidx.compose.ui.graphics.Color4import androidx.compose.ui.text.AnnotatedString5import androidx.compose.ui.text.LinkAnnotation6import androidx.compose.ui.text.LinkInteractionListener7import androidx.compose.ui.text.SpanStyle8import androidx.compose.ui.text.TextLinkStyles9import androidx.compose.ui.text.font.FontFamily10import androidx.compose.ui.text.font.FontStyle11import androidx.compose.ui.text.font.FontWeight12import androidx.compose.ui.text.style.BaselineShift13import androidx.compose.ui.text.style.TextDecoration14import eu.friedcutlet.yokan.util.decodeHtmlEntities1516internal data class NovelRichContent(17 val blocks: List<NovelContentBlock>,18 val plainText: String,19)2021internal sealed interface NovelContentBlock {22 data class Text(23 val text: AnnotatedString,24 val kind: NovelTextBlockKind = NovelTextBlockKind.Paragraph,25 ) : NovelContentBlock2627 data class Image(28 val source: NovelImageSource,29 val alt: String,30 val reference: String = "",31 ) : NovelContentBlock3233 data object Rule : NovelContentBlock34}3536internal enum class NovelTextBlockKind {37 Paragraph,38 Heading1,39 Heading2,40 Heading3,41 Heading4,42 Heading5,43 Heading6,44 BlockQuote,45 Preformatted,46 TableRow,47}4849internal sealed interface NovelImageSource {50 data class Remote(val url: String) : NovelImageSource51 class Embedded(val bytes: ByteArray, val cacheKey: String) : NovelImageSource52}5354private data class InlineMarkup(55 val tag: String,56 val spanStyle: SpanStyle? = null,57 val link: LinkAnnotation.Url? = null,58)5960private val htmlTokenRegex = Regex("<!--[\\s\\S]*?-->|<[^>]+>|[^<]+")61private val htmlAttributeRegex = Regex("([^\\s=/>]+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\s>]+)))?")62private val whitespaceRegex = Regex("\\s+")63private val blockTags = setOf("p", "div", "section", "article", "header", "footer", "aside", "main", "figure", "figcaption")64private val headingTags = setOf("h1", "h2", "h3", "h4", "h5", "h6")65/** Block elements that also carry an inline style until they close. */66private val styledBlockTags = headingTags + setOf("blockquote", "pre")67/** Inline elements whose style is popped on their closing (or self-closing) tag. */68private val inlineTags = setOf("b", "strong", "i", "em", "u", "s", "strike", "del", "code", "mark", "sub", "sup", "span", "a", "th")69private val imageTags = setOf("img", "source")7071private val boldStyle = SpanStyle(fontWeight = FontWeight.Bold)72private val italicStyle = SpanStyle(fontStyle = FontStyle.Italic)73private val monospaceStyle = SpanStyle(fontFamily = FontFamily.Monospace)74private val inlineStyles = mapOf(75 "b" to boldStyle,76 "strong" to boldStyle,77 "i" to italicStyle,78 "em" to italicStyle,79 "u" to SpanStyle(textDecoration = TextDecoration.Underline),80 "s" to SpanStyle(textDecoration = TextDecoration.LineThrough),81 "strike" to SpanStyle(textDecoration = TextDecoration.LineThrough),82 "del" to SpanStyle(textDecoration = TextDecoration.LineThrough),83 "code" to SpanStyle(fontFamily = FontFamily.Monospace, background = Color(0x22000000)),84 "mark" to SpanStyle(background = Color(0x66FFF176)),85 "sub" to SpanStyle(baselineShift = BaselineShift.Subscript),86 "sup" to SpanStyle(baselineShift = BaselineShift.Superscript),87)88private val linkStyles = TextLinkStyles(89 style = SpanStyle(color = Color(0xFF1976D2.toInt()), textDecoration = TextDecoration.Underline),90)91private val namedCssColors = mapOf(92 "black" to 0xFF000000,93 "white" to 0xFFFFFFFF,94 "red" to 0xFFF44336,95 "blue" to 0xFF1976D2,96 "green" to 0xFF388E3C,97 "gray" to 0xFF808080,98 "grey" to 0xFF808080,99 "yellow" to 0xFFFFEB3B,100 "transparent" to 0x00000000,101)102103internal fun parseNovelRichContent(104 html: String,105 baseUrl: String = "",106 embeddedImage: (String) -> ByteArray? = { null },107 onOpenLink: ((String) -> Unit)? = null,108): NovelRichContent {109 if (!html.contains('<') || !html.contains('>')) {110 val text = decodeHtmlEntities(html)111 return NovelRichContent(112 blocks = listOf(NovelContentBlock.Text(AnnotatedString(text))),113 plainText = text,114 )115 }116 val linkListener = onOpenLink?.let { openLink ->117 LinkInteractionListener { annotation ->118 (annotation as? LinkAnnotation.Url)?.url?.let(openLink)119 }120 }121122 val blocks = mutableListOf<NovelContentBlock>()123 var builder = AnnotatedString.Builder()124 val markup = ArrayDeque<InlineMarkup>()125 var kind = NovelTextBlockKind.Paragraph126 var orderedListDepth = 0127 val orderedListIndexes = mutableListOf<Int>()128 var preformatted = false129 var lastTextChar: Char? = null130131 fun appendText(value: String) {132 if (value.isEmpty()) return133 builder.append(value)134 lastTextChar = value.last()135 }136137 fun appendText(value: Char) {138 builder.append(value)139 lastTextChar = value140 }141142 fun push(mark: InlineMarkup) {143 mark.spanStyle?.let(builder::pushStyle)144 mark.link?.let(builder::pushLink)145 markup.addLast(mark)146 }147148 fun pop(tag: String) {149 val index = markup.indexOfLast { it.tag == tag }150 if (index < 0) return151 repeat(markup.size - index) {152 markup.removeLast()153 builder.pop()154 }155 }156157 fun newBuilder() {158 builder = AnnotatedString.Builder()159 markup.forEach { mark ->160 mark.spanStyle?.let(builder::pushStyle)161 mark.link?.let(builder::pushLink)162 }163 lastTextChar = null164 }165166 fun flush() {167 val built = builder.toAnnotatedString().trimmed()168 if (built.length > 0) blocks += NovelContentBlock.Text(built, kind)169 newBuilder()170 kind = NovelTextBlockKind.Paragraph171 }172173 htmlTokenRegex.findAll(html)174 .map { it.value }175 .forEach { token ->176 if (!token.startsWith('<')) {177 val decoded = decodeHtmlEntities(token)178 val normalized = if (preformatted) decoded else decoded.replace(whitespaceRegex, " ")179 if (normalized.isNotEmpty()) {180 if (!preformatted && builder.length > 0 && lastTextChar?.isWhitespace() == false && normalized.first().isWhitespace()) {181 appendText(' ')182 appendText(normalized.trimStart())183 } else if (!preformatted && builder.length == 0) {184 appendText(normalized.trimStart())185 } else {186 appendText(normalized)187 }188 }189 return@forEach190 }191 if (token.startsWith("<!--")) return@forEach192193 val raw = token.removePrefix("<").removeSuffix(">").trim()194 val closing = raw.startsWith('/')195 val selfClosing = raw.endsWith('/')196 val body = raw.removePrefix("/").removeSuffix("/").trim()197 val tagEnd = body.indexOfFirst(Char::isWhitespace).takeIf { it >= 0 } ?: body.length198 val tag = body.substring(0, tagEnd).lowercase().substringAfter(':')199200 if (closing) {201 when {202 tag in blockTags -> flush()203 tag in styledBlockTags -> {204 pop(tag)205 flush()206 preformatted = false207 }208 tag == "tr" -> flush()209 tag == "li" -> flush()210 tag == "ol" -> {211 orderedListDepth = (orderedListDepth - 1).coerceAtLeast(0)212 if (orderedListIndexes.isNotEmpty()) orderedListIndexes.removeLast()213 }214 tag in inlineTags -> pop(tag)215 }216 return@forEach217 }218219 val attributes = parseHtmlAttributes(body.substring(tagEnd))220 when {221 tag in blockTags -> flush()222 tag == "br" -> appendText('\n')223 tag == "hr" -> {224 flush()225 blocks += NovelContentBlock.Rule226 }227 tag in headingTags -> {228 flush()229 kind = NovelTextBlockKind.entries[tag.drop(1).toInt().coerceIn(1, 6)]230 push(InlineMarkup(tag, boldStyle))231 }232 tag == "blockquote" -> {233 flush()234 kind = NovelTextBlockKind.BlockQuote235 push(InlineMarkup(tag, italicStyle))236 }237 tag == "pre" -> {238 flush()239 preformatted = true240 kind = NovelTextBlockKind.Preformatted241 push(InlineMarkup(tag, monospaceStyle))242 }243 tag == "ol" -> {244 orderedListDepth += 1245 orderedListIndexes += 0246 }247 tag == "li" -> {248 flush()249 if (orderedListDepth > 0 && orderedListIndexes.isNotEmpty()) {250 val next = orderedListIndexes.last() + 1251 orderedListIndexes[orderedListIndexes.lastIndex] = next252 appendText("$next. ")253 } else {254 appendText("• ")255 }256 }257 tag == "tr" -> {258 flush()259 kind = NovelTextBlockKind.TableRow260 }261 tag == "td" || tag == "th" -> {262 if (builder.length > 0) appendText(" | ")263 if (tag == "th") push(InlineMarkup(tag, boldStyle))264 }265 tag in inlineStyles -> push(InlineMarkup(tag, inlineStyles[tag]))266 tag == "span" -> push(InlineMarkup(tag, parseInlineCss(attributes["style"].orEmpty())))267 tag == "a" -> {268 val href = resolveNovelReference(baseUrl, attributes["href"].orEmpty())269 if (href.isNotBlank()) {270 push(271 InlineMarkup(272 tag = tag,273 link = LinkAnnotation.Url(274 url = href,275 styles = linkStyles,276 linkInteractionListener = linkListener,277 ),278 ),279 )280 }281 }282 tag in imageTags -> {283 val src = attributes["src"].orEmpty().ifBlank {284 attributes["srcset"].orEmpty().substringBefore(',').trim().substringBefore(' ')285 }286 if (src.isNotBlank()) {287 flush()288 val embedded = embeddedImage(src)289 val source = if (embedded != null) {290 NovelImageSource.Embedded(embedded, normalizeArchiveEntry(src))291 } else {292 NovelImageSource.Remote(resolveNovelReference(baseUrl, src))293 }294 blocks += NovelContentBlock.Image(295 source = source,296 reference = src,297 alt = decodeHtmlEntities(attributes["alt"].orEmpty()).ifBlank { src.substringAfterLast('/') },298 )299 }300 }301 }302303 if (selfClosing && tag in inlineTags) pop(tag)304 }305 flush()306307 val plainText = blocks.mapNotNull { block ->308 when (block) {309 is NovelContentBlock.Text -> block.text.text310 is NovelContentBlock.Image -> block.alt.takeIf(String::isNotBlank)311 NovelContentBlock.Rule -> null312 }313 }.joinToString("\n\n")314 return NovelRichContent(blocks = blocks, plainText = plainText)315}316317private fun parseHtmlAttributes(raw: String): Map<String, String> = buildMap {318 htmlAttributeRegex.findAll(raw).forEach { match ->319 val name = match.groupValues[1].lowercase()320 val value = match.groupValues.drop(2).firstOrNull { it.isNotEmpty() }.orEmpty()321 if (name.isNotBlank()) put(name, decodeHtmlEntities(value))322 }323}324325private fun parseInlineCss(style: String): SpanStyle? {326 if (style.isBlank()) return null327 val declarations = style.split(';').mapNotNull { declaration ->328 val key = declaration.substringBefore(':', "").trim().lowercase()329 val value = declaration.substringAfter(':', "").trim().lowercase()330 key.takeIf(String::isNotBlank)?.let { it to value }331 }.toMap()332 val weight = declarations["font-weight"]333 val fontStyle = declarations["font-style"]334 val decoration = declarations["text-decoration"]335 val foreground = parseCssColor(declarations["color"])336 val background = parseCssColor(declarations["background-color"] ?: declarations["background"])337 return SpanStyle(338 color = foreground ?: Color.Unspecified,339 background = background ?: Color.Unspecified,340 fontWeight = if (weight == "bold" || weight?.toIntOrNull()?.let { it >= 600 } == true) FontWeight.Bold else null,341 fontStyle = if (fontStyle == "italic" || fontStyle == "oblique") FontStyle.Italic else null,342 textDecoration = when {343 decoration?.contains("line-through") == true -> TextDecoration.LineThrough344 decoration?.contains("underline") == true -> TextDecoration.Underline345 else -> null346 },347 )348}349350private fun parseCssColor(value: String?): Color? {351 val text = value?.trim()?.lowercase().orEmpty()352 if (text.isBlank()) return null353 namedCssColors[text]?.let { return Color(it.toInt()) }354 if (!text.startsWith('#')) return null355 val hex = text.drop(1)356 val argb = when (hex.length) {357 3 -> "ff${hex.map { "$it$it" }.joinToString("")}"358 4 -> "${hex[3]}${hex[3]}${hex.take(3).map { "$it$it" }.joinToString("")}"359 6 -> "ff$hex"360 8 -> hex361 else -> return null362 }363 return argb.toLongOrNull(16)?.toInt()?.let(::Color)364}365366internal fun resolveNovelReference(base: String, reference: String): String {367 val ref = decodeHtmlEntities(reference).trim()368 if (ref.isBlank() || ref.startsWith("data:") || ref.startsWith("file:") || "://" in ref) return ref369 if (ref.startsWith("//")) return "${base.substringBefore(':', "https")}:$ref"370 if (base.isBlank()) return ref371 val suffixIndex = ref.indexOfFirst { it == '?' || it == '#' }.takeIf { it >= 0 } ?: ref.length372 val refPath = ref.substring(0, suffixIndex)373 val suffix = ref.substring(suffixIndex)374 val schemeIndex = base.indexOf("://")375 if (schemeIndex < 0) return normalizeArchiveEntry(376 if (refPath.startsWith('/')) refPath else "${base.substringBeforeLast('/', "")}/$refPath",377 ) + suffix378 val originEnd = base.indexOf('/', schemeIndex + 3).takeIf { it >= 0 } ?: base.length379 val origin = base.substring(0, originEnd)380 val basePath = base.substring(originEnd).substringBefore('?').substringBefore('#')381 val combined = if (refPath.startsWith('/')) refPath else "${basePath.substringBeforeLast('/', "")}/$refPath"382 return origin + "/" + normalizeArchiveEntry(combined).trimStart('/') + suffix383}384385internal fun resolveEpubResourcePath(chapterHref: String, reference: String): String {386 val clean = reference.substringBefore('?').substringBefore('#').replace("%20", " ")387 val combined = if (clean.startsWith('/')) clean else "${chapterHref.substringBeforeLast('/', "")}/$clean"388 return normalizeArchiveEntry(combined)389}390391internal fun normalizeArchiveEntry(path: String): String {392 val output = ArrayDeque<String>()393 path.replace('\\', '/').split('/').forEach { part ->394 when (part) {395 "", "." -> Unit396 ".." -> if (output.isNotEmpty()) output.removeLast()397 else -> output.addLast(part)398 }399 }400 return output.joinToString("/")401}402403private fun AnnotatedString.trimmed(): AnnotatedString {404 var start = 0405 var end = length406 while (start < end && this[start].isBoundarySpace()) start += 1407 while (end > start && this[end - 1].isBoundarySpace()) end -= 1408 return if (start == 0 && end == length) this else subSequence(start, end)409}410411private fun Char.isBoundarySpace(): Boolean = this == ' ' || this == '\t'412