2023-01-16 21:36:23 +05:30
|
|
|
package com.github.libretube.util
|
|
|
|
|
|
|
|
import android.text.Editable
|
|
|
|
import android.text.Spanned
|
|
|
|
import android.text.TextPaint
|
|
|
|
import android.text.style.ClickableSpan
|
|
|
|
import android.view.View
|
|
|
|
import org.xml.sax.Attributes
|
|
|
|
|
2023-01-18 21:43:22 +05:30
|
|
|
class LinkHandler(private val clickCallback: ((String) -> Unit)?) {
|
2023-01-16 21:36:23 +05:30
|
|
|
private var linkTagStartIndex = -1
|
|
|
|
private var link: String? = null
|
2023-01-18 21:43:22 +05:30
|
|
|
fun handleTag(
|
2023-01-17 00:20:33 +05:30
|
|
|
opening: Boolean,
|
|
|
|
tag: String?,
|
|
|
|
output: Editable?,
|
2023-01-18 22:02:08 +05:30
|
|
|
attributes: Attributes?,
|
2023-01-17 00:20:33 +05:30
|
|
|
): Boolean {
|
2023-01-18 21:43:22 +05:30
|
|
|
// if the tag is not an anchor link, ignore for the default handler
|
|
|
|
if (output == null || "a" != tag) {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
if (opening) {
|
|
|
|
if (attributes != null) {
|
|
|
|
linkTagStartIndex = output.length
|
|
|
|
link = attributes.getValue("href")
|
2023-01-16 21:36:23 +05:30
|
|
|
}
|
2023-01-18 21:43:22 +05:30
|
|
|
} else {
|
2023-01-18 22:02:08 +05:30
|
|
|
if (linkTagStartIndex >= 0 && link != null) {
|
|
|
|
setLinkSpans(output, linkTagStartIndex, output.length, link!!)
|
|
|
|
|
|
|
|
linkTagStartIndex = -1
|
|
|
|
link = null
|
|
|
|
}
|
2023-01-16 21:36:23 +05:30
|
|
|
}
|
2023-01-18 21:43:22 +05:30
|
|
|
return true
|
2023-01-16 21:36:23 +05:30
|
|
|
}
|
|
|
|
|
2023-01-18 22:02:08 +05:30
|
|
|
private fun setLinkSpans(output: Editable, start: Int, end: Int, link: String) {
|
2023-01-17 00:20:33 +05:30
|
|
|
output.setSpan(
|
|
|
|
object : ClickableSpan() {
|
|
|
|
override fun onClick(widget: View) {
|
2023-01-18 22:02:08 +05:30
|
|
|
clickCallback?.invoke(link)
|
2023-01-16 21:36:23 +05:30
|
|
|
}
|
|
|
|
|
2023-01-17 00:20:33 +05:30
|
|
|
override fun updateDrawState(ds: TextPaint) {
|
|
|
|
super.updateDrawState(ds)
|
|
|
|
ds.isUnderlineText = false
|
|
|
|
}
|
|
|
|
},
|
|
|
|
start,
|
|
|
|
end,
|
|
|
|
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
|
|
|
|
)
|
2023-01-16 21:36:23 +05:30
|
|
|
}
|
2023-01-17 00:20:33 +05:30
|
|
|
}
|