teleposter/app/src/main/java/telegra/ph/Viewer.kt

57 lines
1.6 KiB
Kotlin
Raw Normal View History

2018-02-12 18:36:19 +00:00
package telegra.ph
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.View
2019-02-05 21:18:51 +00:00
import android.webkit.JavascriptInterface
2018-02-12 18:36:19 +00:00
import im.delight.android.webview.AdvancedWebView
2019-02-05 21:18:51 +00:00
class Viewer @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : AdvancedWebView(context, attrs, defStyleAttr) {
2018-02-12 18:36:19 +00:00
2019-02-05 21:18:51 +00:00
init {
prepare()
2018-02-12 18:36:19 +00:00
}
@SuppressLint("SetJavaScriptEnabled", "AddJavascriptInterface")
2019-02-05 21:18:51 +00:00
fun prepare() {
settings.javaScriptEnabled = true
settings.loadWithOverviewMode = true
settings.useWideViewPort = true
2018-02-12 18:36:19 +00:00
overScrollMode = View.OVER_SCROLL_NEVER
setMixedContentAllowed(true)
2019-02-05 21:18:51 +00:00
loadDataWithBaseURL("https://telegra.ph", context.assets.open("viewer.html").bufferedReader().readText(), "text/html", "utf-8", null)
}
fun showPage(page: TelegraphApi.Page) {
clearHistory()
setArticleTitle(page.title)
setAuthor(page.authorName, page.authorUrl)
setViews(page.views)
if (page.content == null) setDescription(page.description)
else setContent(page.content)
2018-02-12 18:36:19 +00:00
}
2019-02-05 21:18:51 +00:00
private fun setArticleTitle(title: String) {
2018-02-12 18:36:19 +00:00
this.loadUrl("javascript:setTitle('$title');")
}
2019-02-05 21:18:51 +00:00
private fun setAuthor(author: String?, url: String?) {
2018-02-12 18:36:19 +00:00
this.loadUrl("javascript:setAuthor('$author','$url');")
}
2019-02-05 21:18:51 +00:00
private fun setViews(views: Int) {
2018-02-12 18:36:19 +00:00
this.loadUrl("javascript:setViews('$views');")
}
2019-02-05 21:18:51 +00:00
private fun setDescription(description: String) {
2018-02-12 18:36:19 +00:00
this.loadUrl("javascript:setDescription('${description.replace("\n", "<br>")}');")
}
2019-02-05 21:18:51 +00:00
private fun setContent(content: String?) {
2018-02-12 18:36:19 +00:00
this.loadUrl("javascript:setContent('${content?.replace("'", "\\'")}');")
}
}