HtmlEntities.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/util/HtmlEntities.kt
1package eu.friedcutlet.yokan.util23private val htmlEntityRegex = Regex("&(#[xX]?[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);")45private val namedHtmlEntities = mapOf(6 "nbsp" to " ",7 "amp" to "&",8 "lt" to "<",9 "gt" to ">",10 "quot" to "\"",11 "apos" to "'",12 "copy" to "©",13 "reg" to "®",14 "mdash" to "—",15 "ndash" to "–",16 "hellip" to "…",17 "rsquo" to "’",18 "lsquo" to "‘",19 "ldquo" to "“",20 "rdquo" to "”",21 "trade" to "™",22)2324/**25 * Decodes numeric (`'`, `'`) and common named HTML entities in one pass, so `&quot;`26 * stays `"`. Unknown or out-of-range entities are kept verbatim; ` ` becomes a plain space.27 */28internal fun decodeHtmlEntities(value: String): String {29 if ('&' !in value) return value30 return value.replace(htmlEntityRegex) { match ->31 val entity = match.groupValues[1]32 if (!entity.startsWith('#')) return@replace namedHtmlEntities[entity.lowercase()] ?: match.value33 val code = if (entity.startsWith("#x", ignoreCase = true)) entity.drop(2).toIntOrNull(16) else entity.drop(1).toIntOrNull()34 when {35 code == null || code !in 0..0x10FFFF -> match.value36 code <= Char.MAX_VALUE.code -> code.toChar().toString()37 else -> {38 val shifted = code - 0x1000039 "${(0xD800 + (shifted shr 10)).toChar()}${(0xDC00 + (shifted and 0x3FF)).toChar()}"40 }41 }42 }43}44