Skip to content

Commit

Permalink
refactor: extract more javascripts
Browse files Browse the repository at this point in the history
  • Loading branch information
plateaukao committed Oct 18, 2024
1 parent 7af1a8c commit a1ace1e
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 124 deletions.
20 changes: 20 additions & 0 deletions app/src/main/assets/remove_text_highlight.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
function removeHighlightFromSelection() {
const selection = window.getSelection();
// 檢查是否有選取範圍
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const container = range.commonAncestorContainer;
// 確保範圍是在一個元素內部
const parentElement = container.nodeType === 3 ? container.parentNode : container;

// 查找所有的 highlight divs
const highlights = parentElement.parentNode.querySelectorAll('div.highlight_underline, div.highlight_yellow, div.highlight_green, div.highlight_blue, div.highlight_pink');

// 移除每個 highlight div 的外部 HTML
highlights.forEach(highlight => {
highlight.outerHTML = highlight.innerHTML;
});
}

// 綁定一個按鈕來觸發這個函數
removeHighlightFromSelection();
2 changes: 0 additions & 2 deletions app/src/main/assets/text_node_monitor.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
//const bridge = window.android = new androidApp(context, webView);

function myCallback(elementId, responseString) {
//console.log("Element ID:", elementId, "Response string:", responseString);
node = document.getElementById(elementId).nextElementSibling;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1231,11 +1231,11 @@ open class BrowserActivity : FragmentActivity(), BrowserController {
translateApi: TRANSLATE_API,
webView: NinjaWebView = ninjaWebView,
) {
if (config.enableInplaceParagraphTranslate) {
translateByParagraphInPlace(translateApi, webView)
} else {
translateByParagraphInReaderMode(translateApi)
}
translateByParagraphInPlace(translateApi, webView)
// if (config.enableInplaceParagraphTranslate) {
// } else {
// translateByParagraphInReaderMode(translateApi)
// }
}

private fun translateByParagraphInPlace(
Expand All @@ -1251,41 +1251,41 @@ open class BrowserActivity : FragmentActivity(), BrowserController {
}
}

private fun translateByParagraphInReaderMode(translateApi: TRANSLATE_API) {
lifecycleScope.launch {
val currentUrl = ninjaWebView.url

// assume it's current one
val translateModeWebView = if (ninjaWebView.isTranslatePage) {
ninjaWebView
} else {
// get html from original WebView
val htmlCache = ninjaWebView.getRawReaderHtml()
// create a new WebView
addAlbum("", "")
// set it to translate mode
ninjaWebView.isTranslatePage = true
ninjaWebView.translateApi = translateApi
// set its raw html to be the same as original WebView
ninjaWebView.rawHtmlCache = htmlCache
// show the language label
languageLabelView?.visibility = VISIBLE
ninjaWebView
}

val translatedHtml = translationViewModel
.translateByParagraph(translateModeWebView.rawHtmlCache ?: return@launch)
if (translateModeWebView.isAttachedToWindow) {
translateModeWebView.loadDataWithBaseURL(
if (!ninjaWebView.isPlainText) currentUrl else null,
translatedHtml,
"text/html",
"utf-8",
null
)
}
}
}
// private fun translateByParagraphInReaderMode(translateApi: TRANSLATE_API) {
// lifecycleScope.launch {
// val currentUrl = ninjaWebView.url
//
// // assume it's current one
// val translateModeWebView = if (ninjaWebView.isTranslatePage) {
// ninjaWebView
// } else {
// // get html from original WebView
// val htmlCache = ninjaWebView.getRawReaderHtml()
// // create a new WebView
// addAlbum("", "")
// // set it to translate mode
// ninjaWebView.isTranslatePage = true
// ninjaWebView.translateApi = translateApi
// // set its raw html to be the same as original WebView
// ninjaWebView.rawHtmlCache = htmlCache
// // show the language label
// languageLabelView?.visibility = VISIBLE
// ninjaWebView
// }
//
// val translatedHtml = translationViewModel
// .translateByParagraph(translateModeWebView.rawHtmlCache ?: return@launch)
// if (translateModeWebView.isAttachedToWindow) {
// translateModeWebView.loadDataWithBaseURL(
// if (!ninjaWebView.isPlainText) currentUrl else null,
// translatedHtml,
// "text/html",
// "utf-8",
// null
// )
// }
// }
// }

private fun isTwoPaneControllerInitialized(): Boolean = ::twoPaneController.isInitialized

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -846,12 +846,12 @@ class SettingActivity : FragmentActivity() {
).show()
},
DividerSettingItem(),
BooleanSettingItem(
R.string.setting_title_enable_inplace_translate,
0,
R.string.setting_summary_enable_inplace_translate,
config::enableInplaceParagraphTranslate
),
// BooleanSettingItem(
// R.string.setting_title_enable_inplace_translate,
// 0,
// R.string.setting_summary_enable_inplace_translate,
// config::enableInplaceParagraphTranslate
// ),
ValueSettingItem(
R.string.setting_title_translated_langs,
0,
Expand Down
57 changes: 2 additions & 55 deletions app/src/main/java/info/plateaukao/einkbro/view/NinjaWebView.kt
Original file line number Diff line number Diff line change
Expand Up @@ -800,7 +800,7 @@ open class NinjaWebView(
}

if (highlightStyle == HighlightStyle.BACKGROUND_NONE) {
evaluateJavascript(removeHighlightJs, null)
evaluateJsFile("remove_text_highlight.js")
} else {
val className = when (highlightStyle) {
HighlightStyle.UNDERLINE -> "highlight_underline"
Expand Down Expand Up @@ -1109,10 +1109,6 @@ open class NinjaWebView(
}
"""

const val textNodesMonitorJs = """
"""


private const val readabilityOptions =
"{classesToPreserve: preservedClasses, overwriteImgSrc: true}"

Expand Down Expand Up @@ -1145,30 +1141,6 @@ open class NinjaWebView(
return article.title + ', ' + article.textContent;
})()
"""
private const val stripHeaderElementsJs = """
javascript:(function() {
var r = document.getElementsByTagName('script');
for (var i = (r.length-1); i >= 0; i--) {
if(r[i].getAttribute('id') != 'a'){
r[i].parentNode.removeChild(r[i]);
}
}
})()
"""

private const val oldFacebookHideSponsoredPostsJs = """
javascript:(function() {
var posts = [].filter.call(document.getElementsByTagName('article'), el => el.attributes['data-store'].value.indexOf('is_sponsored.1') >= 0);
while(posts.length > 0) { posts.pop().style.display = "none"; }
var qcleanObserver = new window.MutationObserver(function(mutation, observer){
var posts = [].filter.call(document.getElementsByTagName('article'), el => el.attributes['data-store'].value.indexOf('is_sponsored.1') >= 0);
while(posts.length > 0) { posts.pop().style.display = "none"; }
});
qcleanObserver.observe(document, { subtree: true, childList: true });
})()
"""

private const val verticalLayoutCss = "body {\n" +
"-webkit-writing-mode: vertical-rl;\n" +
Expand Down Expand Up @@ -1282,31 +1254,6 @@ input[type=button]: focus,input[type=submit]: focus,input[type=reset]: focus,inp
"\tfont-weight:value !important;\n" +
"}\n"

private const val removeHighlightJs = """
javascript:(function() {
function removeHighlightFromSelection() {
const selection = window.getSelection();
// 檢查是否有選取範圍
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const container = range.commonAncestorContainer;
// 確保範圍是在一個元素內部
const parentElement = container.nodeType === 3 ? container.parentNode : container;
// 查找所有的 highlight divs
const highlights = parentElement.parentNode.querySelectorAll('div.highlight_underline, div.highlight_yellow, div.highlight_green, div.highlight_blue, div.highlight_pink');
// 移除每個 highlight div 的外部 HTML
highlights.forEach(highlight => {
highlight.outerHTML = highlight.innerHTML;
});
}
// 綁定一個按鈕來觸發這個函數
removeHighlightFromSelection();
})()
"""

private val clearTranslationElementsJs = """
javascript:(function() {
document.body.innerHTML = document.originalInnerHTML;
Expand All @@ -1323,4 +1270,4 @@ removeHighlightFromSelection();
val fontCss = boldFontCss.replace("value", config.fontBoldness.toString())
injectCss(fontCss.toByteArray())
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,13 @@ import info.plateaukao.einkbro.unit.BrowserUnit
import info.plateaukao.einkbro.unit.HelperUnit
import info.plateaukao.einkbro.unit.ViewUnit
import info.plateaukao.einkbro.util.TranslationLanguage
import info.plateaukao.einkbro.view.NinjaWebView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import org.apache.commons.text.StringEscapeUtils
import org.jsoup.Jsoup
import org.jsoup.nodes.DataNode
import org.jsoup.nodes.Element
import org.jsoup.nodes.TextNode
import org.koin.core.component.KoinComponent
Expand Down Expand Up @@ -405,25 +403,25 @@ class TranslationViewModel : ViewModel(), KoinComponent {
return Pair(promptPrefix, selectedText)
}

fun translateByParagraph(html: String): String {
val parsedHtml = Jsoup.parse(html)
val nodesWithText = fetchNodesWithText(parsedHtml)
nodesWithText.forEachIndexed { index, node ->
// for monitoring visibility
node.addClass("to-translate")
// for locating element's position
node.id(index.toString())
// for later inserting translated text
node.after(Element("p"))
}
// add observer
val script: Element = parsedHtml.createElement("script")
script.attr("type", "text/javascript")
script.appendChild(DataNode(NinjaWebView.textNodesMonitorJs))
parsedHtml.body().appendChild(script)

return parsedHtml.toString()
}
// fun translateByParagraph(html: String): String {
// val parsedHtml = Jsoup.parse(html)
// val nodesWithText = fetchNodesWithText(parsedHtml)
// nodesWithText.forEachIndexed { index, node ->
// // for monitoring visibility
// node.addClass("to-translate")
// // for locating element's position
// node.id(index.toString())
// // for later inserting translated text
// node.after(Element("p"))
// }
// // add observer
// val script: Element = parsedHtml.createElement("script")
// script.attr("type", "text/javascript")
// script.appendChild(DataNode(NinjaWebView.textNodesMonitorJs))
// parsedHtml.body().appendChild(script)
//
// return parsedHtml.toString()
// }

private fun fetchNodesWithText(
element: Element,
Expand Down

0 comments on commit a1ace1e

Please sign in to comment.