HtmlSelectorMatcher.kt
composeApp/src/commonMain/kotlin/eu/friedcutlet/yokan/services/extensions/js/HtmlSelectorMatcher.kt
1package eu.friedcutlet.yokan.services.extensions.js23import eu.friedcutlet.yokan.services.files.BoundedCache45private val ChildCombinator = Regex("\\s*>\\s*")6private val AttributeConstraint = Regex("\\[(.+?)(?:=\"([^\"]*)\")?]")7private val IdConstraint = Regex("#([\\w-]+)")8private val ClassConstraint = Regex("\\.([\\w-]+)")9private val TagName = Regex("^([a-zA-Z][\\w-]*)")1011/**12 * Minimal CSS selector evaluator. Supports a single tag/class/id/attribute selector and returns the13 * inner HTML of each match. This intentionally covers the lowest-common-denominator selectors used by14 * source extensions (e.g. `.title`, `#description`, `img[src]`, `a.link`) without taking a full DOM15 * dependency.16 */17internal object HtmlSelectorMatcher {18 // ponytail: fixed LRU of compiled selectors; extensions reuse a handful per source, raise if they churn.19 private val compiledSelectors = BoundedCache<String, Compiled>(maxEntries = 64, maxWeight = 64) { 1 }2021 fun match(html: String, selector: String): List<String> {22 if (html.isBlank() || selector.isBlank()) return emptyList()23 val matchers = selector24 .split(',')25 .map { it.trim() }26 .filter { it.isNotEmpty() }27 .map { compiledSelectors[it] ?: compile(it).also { compiled -> compiledSelectors[it] = compiled } }28 if (matchers.isEmpty()) return emptyList()29 val results = mutableListOf<String>()30 matchers.forEach { matcher ->31 // Every match needs the literal closing tag; skip the per-candidate scan when it is absent.32 if (matcher.closingTag != null && matcher.closingTag !in html) return@forEach33 matcher.element.findAll(html).forEach { match ->34 val inner = match.groups["inner"]?.value35 if (!inner.isNullOrBlank()) results += inner.trim()36 }37 }38 return results.distinct()39 }4041 private fun compile(selector: String): Compiled {42 // Strip pseudo classes / descendants we can't handle and keep the last simple selector.43 val cleaned = selector.replace(ChildCombinator, " ").substringAfterLast(' ').trim()44 val attributes = AttributeConstraint.findAll(cleaned).map { it.groupValues[1] to it.groupValues[2] }.toList()45 val bare = cleaned.replace(AttributeConstraint, "")46 val id = IdConstraint.find(bare)?.groupValues?.getOrNull(1)47 val classes = ClassConstraint.findAll(bare).map { it.groupValues[1] }.toList()48 val tag = TagName.find(bare)?.groupValues?.getOrNull(1)49 val tagPattern = tag ?: "[a-zA-Z][a-zA-Z0-9-]*"50 val classConstraints = classes.joinToString("") { "(?=[^>]*class=[\"'][^\"']*\\b$it\\b[^\"']*[\"'])" }51 val idConstraint = id?.let { "(?=[^>]*id=[\"']$it[\"'])" }.orEmpty()52 val attrConstraints = attributes.joinToString("") { (name, value) ->53 if (value.isEmpty()) "(?=[^>]*\\b${Regex.escape(name)}\\b)" else "(?=[^>]*\\b${Regex.escape(name)}=[\"']${Regex.escape(value)}[\"'])"54 }55 return Compiled(56 element = Regex("<$tagPattern\\b$idConstraint$classConstraints$attrConstraints[^>]*>(?<inner>[\\s\\S]*?)</$tagPattern>"),57 closingTag = tag?.let { "</$it>" },58 )59 }6061 private class Compiled(val element: Regex, val closingTag: String?)62}63