diff --git a/app/src/main/assets/layout_fix.js b/app/src/main/assets/layout_fix.js new file mode 100644 index 0000000..a9aecd4 --- /dev/null +++ b/app/src/main/assets/layout_fix.js @@ -0,0 +1,127 @@ +// Layout fix: comment reaction chips overlapping following content. +// +// On the lightweight mobile Facebook layout, the small reaction summary chip +// of a comment (reaction icons + count, e.g. "49 👍") is absolutely +// positioned. When the comment container is taller/shorter than FB expects +// (larger system font, a "View previous replies" row below, nested replies) +// the chip no longer lines up with its own comment and is drawn on top of the +// next comment or the "Show previous replies" text. +// +// The fix is deliberately DOM-agnostic (FB class names are obfuscated and +// change): we look for small, absolutely positioned elements that consist of +// a short count text plus an icon, displaced from the normal flow, and only touch those that really overlap +// text/images that do not belong to the chip's own container. A chip that is +// moved back into normal flow takes up its own space, so it can no longer +// overlap anything by construction. +(function () { + if (window.__layout_fix_done) return; + window.__layout_fix_done = true; + + var COUNT_RE = /^\s*\d[\d.,\s]*\s*[^\s\d]{0,8}\.?\s*$/; // "49", "1,2 K", "1,2 хиљ." + var timer = null; + + function isChipShape(el) { + var txt = el.textContent || ''; + if (txt.length > 14) return false; + if (el.children.length > 6) return false; + if (!el.querySelector('img,svg,[role="img"],i')) return false; + // count may be missing when the chip is icons-only; require either a + // count or at least 1 icon and a tiny box (checked via rect below) + return txt.trim() === '' || COUNT_RE.test(txt); + } + + function displacedAncestor(el) { + // The chip may be displaced by absolute positioning, a negative margin + // or a transform, on itself or on a wrapper (<=2 levels up). + var cur = el; + for (var i = 0; i < 3 && cur && cur !== document.body; i++) { + var cs = getComputedStyle(cur); + if (cs.position === 'fixed' || cs.position === 'sticky') return null; + if (cs.position === 'absolute' || + parseFloat(cs.marginTop) < 0 || parseFloat(cs.marginBottom) < 0 || + (cs.transform && cs.transform !== 'none')) return cur; + cur = cur.parentElement; + } + return null; + } + + function inChrome(el) { + return !!el.closest('[role="banner"],[role="navigation"],[role="tablist"],header,nav'); + } + + function overlapsForeignContent(chip) { + var r = chip.getBoundingClientRect(); + if (r.width < 6 || r.height < 6 || r.width > 220 || r.height > 60) return false; + var own = chip.parentElement || chip; + var pts = [ + [r.left + r.width * 0.2, r.top + r.height * 0.5], + [r.left + r.width * 0.5, r.top + r.height * 0.5], + [r.left + r.width * 0.8, r.top + r.height * 0.5], + [r.left + r.width * 0.5, r.top + r.height * 0.15], + [r.left + r.width * 0.5, r.top + r.height * 0.85] + ]; + for (var i = 0; i < pts.length; i++) { + var x = pts[i][0], y = pts[i][1]; + if (x < 0 || y < 0 || x > innerWidth || y > innerHeight) continue; + var stack = document.elementsFromPoint(x, y); + for (var k = 0; k < stack.length; k++) { + var e = stack[k]; + if (e === chip || chip.contains(e) || e.contains(chip) || own.contains(e)) continue; + if (e === document.body || e === document.documentElement) continue; + // only content that actually paints something readable + var hasText = (e.children.length === 0 && (e.textContent || '').trim().length > 0); + if (hasText || e.tagName === 'IMG' || e.tagName === 'SVG') return true; + } + } + return false; + } + + function fix(chip) { + chip.setAttribute('data-chip-fixed', '1'); + var s = chip.style; + s.setProperty('position', 'relative', 'important'); + s.setProperty('top', 'auto', 'important'); + s.setProperty('bottom', 'auto', 'important'); + s.setProperty('left', 'auto', 'important'); + s.setProperty('right', 'auto', 'important'); + s.setProperty('transform', 'none', 'important'); + s.setProperty('margin-top', '2px', 'important'); + s.setProperty('margin-bottom', '4px', 'important'); + s.setProperty('display', 'flex', 'important'); + s.setProperty('align-items', 'center', 'important'); + s.setProperty('width', 'fit-content', 'important'); + console.log('LAYOUT_FIX:chip-fixed:' + (chip.textContent || '').trim().slice(0, 12)); + } + + function scan() { + timer = null; + if (/messenger\.com|\/messages/.test(location.href)) return; + var band0 = -innerHeight, band1 = innerHeight * 2; + var nodes = document.querySelectorAll('div,span'); + var budget = 400; // hard cap on candidates examined per pass + for (var i = 0; i < nodes.length && budget > 0; i++) { + var el = nodes[i]; + if (el.hasAttribute('data-chip-fixed')) continue; + if ((el.textContent || '').length > 14) continue; // cheap reject + if (!el.firstElementChild && (el.textContent || '').trim() === '') continue; + var r = el.getBoundingClientRect(); + if (r.bottom < band0 || r.top > band1 || r.width === 0) continue; + budget--; + if (!isChipShape(el)) continue; + var abs = displacedAncestor(el); + if (!abs || abs.hasAttribute('data-chip-fixed') || inChrome(abs)) continue; + if (!overlapsForeignContent(abs)) continue; + fix(abs); + } + } + + function schedule() { + if (timer) return; + timer = setTimeout(scan, 350); + } + + window.addEventListener('scroll', schedule, { passive: true, capture: true }); + window.addEventListener('resize', schedule); + new MutationObserver(schedule).observe(document.documentElement, { childList: true, subtree: true }); + schedule(); +})(); diff --git a/app/src/main/java/uk/org/retallack/slimbook/AuthorDatabase.kt b/app/src/main/java/uk/org/retallack/slimbook/AuthorDatabase.kt index 114dae6..bd42cca 100644 --- a/app/src/main/java/uk/org/retallack/slimbook/AuthorDatabase.kt +++ b/app/src/main/java/uk/org/retallack/slimbook/AuthorDatabase.kt @@ -81,4 +81,35 @@ class AuthorDatabase(context: Context) { fun setRemoteFilterEnabled(enabled: Boolean) { settingsPrefs.edit().putBoolean("remote_filter", enabled).apply() } + + // Floating overlay positions (stats badge / Messenger button), stored as + // translation in px relative to the default layout position. + fun getOverlayOffset(name: String): Pair? { + if (!settingsPrefs.contains("overlay_${name}_dx")) return null + return settingsPrefs.getFloat("overlay_${name}_dx", 0f) to + settingsPrefs.getFloat("overlay_${name}_dy", 0f) + } + + fun setOverlayOffset(name: String, dx: Float, dy: Float) { + settingsPrefs.edit() + .putFloat("overlay_${name}_dx", dx) + .putFloat("overlay_${name}_dy", dy) + .apply() + } + + fun resetOverlayOffsets() { + settingsPrefs.edit().apply { + for (n in listOf("badge", "messenger")) { + remove("overlay_${n}_dx"); remove("overlay_${n}_dy") + } + }.apply() + } + + fun isMessengerButtonEnabled(): Boolean { + return settingsPrefs.getBoolean("messenger_button", true) + } + + fun setMessengerButtonEnabled(enabled: Boolean) { + settingsPrefs.edit().putBoolean("messenger_button", enabled).apply() + } } diff --git a/app/src/main/java/uk/org/retallack/slimbook/DragHelper.kt b/app/src/main/java/uk/org/retallack/slimbook/DragHelper.kt new file mode 100644 index 0000000..5367eb8 --- /dev/null +++ b/app/src/main/java/uk/org/retallack/slimbook/DragHelper.kt @@ -0,0 +1,94 @@ +package uk.org.retallack.slimbook + +import android.annotation.SuppressLint +import android.view.MotionEvent +import android.view.View +import android.view.ViewConfiguration +import android.view.ViewGroup + +/** + * Makes a floating overlay (stats badge, Messenger button) draggable so the + * user can move it away from whatever it covers (e.g. the comment composer + * icons). The position is stored as a translation relative to the view's + * layout position and clamped to the parent's bounds, so it survives rotation + * and different screen sizes. + * + * Taps and long-presses still reach the view's own click listeners: the touch + * listener only consumes the gesture once the finger moved past touch slop. + */ +object DragHelper { + + @SuppressLint("ClickableViewAccessibility") + fun attach( + view: View, + initial: Pair?, + onMoved: (dx: Float, dy: Float) -> Unit + ) { + val parent = view.parent as? ViewGroup ?: return + val slop = ViewConfiguration.get(view.context).scaledTouchSlop + + fun clampAndApply(dx: Float, dy: Float) { + if (parent.width == 0 || view.width == 0) return + view.translationX = dx.coerceIn(-view.left.toFloat(), (parent.width - view.right).toFloat()) + view.translationY = dy.coerceIn(-view.top.toFloat(), (parent.height - view.bottom).toFloat()) + } + + // Re-apply (and re-clamp) whenever the layout changes (rotation, IME). + var wantedX = initial?.first ?: 0f + var wantedY = initial?.second ?: 0f + parent.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ -> + clampAndApply(wantedX, wantedY) + } + view.post { clampAndApply(wantedX, wantedY) } + + var downRawX = 0f + var downRawY = 0f + var startTx = 0f + var startTy = 0f + var dragging = false + + view.setOnTouchListener { v, ev -> + when (ev.actionMasked) { + MotionEvent.ACTION_DOWN -> { + downRawX = ev.rawX + downRawY = ev.rawY + startTx = v.translationX + startTy = v.translationY + dragging = false + false + } + MotionEvent.ACTION_MOVE -> { + val mx = ev.rawX - downRawX + val my = ev.rawY - downRawY + if (!dragging && (Math.abs(mx) > slop || Math.abs(my) > slop)) { + dragging = true + v.cancelLongPress() + v.isPressed = false + v.parent?.requestDisallowInterceptTouchEvent(true) + } + if (dragging) { + wantedX = startTx + mx + wantedY = startTy + my + clampAndApply(wantedX, wantedY) + true + } else false + } + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { + if (dragging) { + dragging = false + wantedX = v.translationX + wantedY = v.translationY + onMoved(wantedX, wantedY) + true + } else false + } + else -> false + } + } + } + + fun reset(view: View) { + view.translationX = 0f + view.translationY = 0f + } +} diff --git a/app/src/main/java/uk/org/retallack/slimbook/MainActivity.kt b/app/src/main/java/uk/org/retallack/slimbook/MainActivity.kt index 6d0682a..4fd1a81 100644 --- a/app/src/main/java/uk/org/retallack/slimbook/MainActivity.kt +++ b/app/src/main/java/uk/org/retallack/slimbook/MainActivity.kt @@ -15,8 +15,10 @@ import android.os.Bundle import android.util.Log import android.view.View import android.webkit.* +import android.widget.ImageView import android.widget.TextView import android.widget.Toast +import androidx.activity.OnBackPressedCallback import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat @@ -47,6 +49,26 @@ class MainActivity : AppCompatActivity() { "download messenger", "mobile browsers", "use the messenger app", "open in the messenger", "blocked", "unavailable", ) + // Clicks Facebook's own in-page back arrow (the control that always + // worked). Matches the aria-label in common UI languages first; as a + // last resort an icon-only button in the very top-left corner. + private const val PAGE_BACK_JS = """(function(){ + var re=/^(back|go back|назад|nazad|zurück|atrás|retour|indietro|voltar|geri|wstecz|zpět|înapoi|vissza|tillbaka|terug|tilbage|takaisin|nazad)$/i; + var els=document.querySelectorAll('[aria-label]'); + for(var i=0;i=0&&r.top<100&&r.left>=0&&r.left<100&&r.width>=20&&r.width<=90&&r.height>=20&&r.height<=90 + &&(c[j].textContent||'').trim()===''&&c[j].querySelector('svg,img,i')){ + c[j].click();return true; + } + } + return false; + })()""" private const val IMAGE_SAVE_CHANNEL_ID = "image_saves" private const val IMAGE_SAVE_NOTIF_ID = 2000 } @@ -54,10 +76,12 @@ class MainActivity : AppCompatActivity() { private lateinit var webView: WebView private lateinit var swipeRefresh: SwipeRefreshLayout private lateinit var statsBadge: TextView + private lateinit var messengerButton: ImageView private lateinit var filterManager: FilterManager private lateinit var authorDb: AuthorDatabase private var filterJs: String = "" + private var layoutFixJs: String = "" private var highlightMode = false private var isMessengerMode = false private var isComposerFocused = false @@ -95,6 +119,7 @@ class MainActivity : AppCompatActivity() { webView = findViewById(R.id.webView) swipeRefresh = findViewById(R.id.swipeRefresh) statsBadge = findViewById(R.id.statsBadge) + messengerButton = findViewById(R.id.messengerButton) filterManager = FilterManager(this) authorDb = AuthorDatabase(this) @@ -102,6 +127,8 @@ class MainActivity : AppCompatActivity() { setupWebView() setupSwipeRefresh() setupStatsBadge() + setupMessengerButton() + setupBackHandling() requestNotificationPermission() NotificationService.createChannel(this) createImageSaveChannel() @@ -111,7 +138,10 @@ class MainActivity : AppCompatActivity() { scheduleNotificationWorker() if (savedInstanceState != null) { webView.restoreState(savedInstanceState) - CoroutineScope(Dispatchers.IO).launch { filterJs = filterManager.getFilterJs() } + CoroutineScope(Dispatchers.IO).launch { + filterJs = filterManager.getFilterJs() + layoutFixJs = loadLayoutFixJs() + } } else { loadFilter() } @@ -178,7 +208,7 @@ class MainActivity : AppCompatActivity() { */ private fun applyMessengerMode() { if (::swipeRefresh.isInitialized) swipeRefresh.isEnabled = false - if (::statsBadge.isInitialized) statsBadge.visibility = View.GONE + updateBadgeVisibility() // hides badge + Messenger button in chat if (::webView.isInitialized) { webView.settings.useWideViewPort = true webView.settings.loadWithOverviewMode = true @@ -357,7 +387,7 @@ class MainActivity : AppCompatActivity() { return true } // Redirect fb-messenger:// and messages URLs to the desktop - // chat stack (like SlimSocial). + // chat stack. if (scheme == "fb-messenger" || scheme == "fb" || isMessagesUrl(url)) { redirectToMessenger(view) return true @@ -723,6 +753,14 @@ class MainActivity : AppCompatActivity() { isMessengerMode -> View.GONE else -> View.VISIBLE } + if (::messengerButton.isInitialized) { + messengerButton.visibility = when { + !authorDb.isMessengerButtonEnabled() -> View.GONE + isComposerFocused -> View.GONE + isMessengerMode -> View.GONE + else -> View.VISIBLE + } + } } private fun setupSwipeRefresh() { @@ -735,11 +773,40 @@ class MainActivity : AppCompatActivity() { showDebugMenu() true } + // Issue #9: the badge used to sit on top of the comment composer + // icons (GIF / emoji). Let the user drag it out of the way. + DragHelper.attach(statsBadge, authorDb.getOverlayOffset("badge")) { dx, dy -> + authorDb.setOverlayOffset("badge", dx, dy) + } + } + + /** + * Issue #14: persistent Messenger shortcut. The web "Messenger" icon only + * exists in the header at the very top of the feed, so reaching it from a + * long feed or a comment thread meant scrolling all the way up. This + * native button is always on screen in feed mode and uses the same + * desktop-UA redirect as the in-page Messages tab. + */ + private fun setupMessengerButton() { + messengerButton.visibility = + if (authorDb.isMessengerButtonEnabled()) View.VISIBLE else View.GONE + messengerButton.setOnClickListener { redirectToMessenger(webView) } + DragHelper.attach(messengerButton, authorDb.getOverlayOffset("messenger")) { dx, dy -> + authorDb.setOverlayOffset("messenger", dx, dy) + } + } + + private fun loadLayoutFixJs(): String = try { + assets.open("layout_fix.js").bufferedReader().use { it.readText() } + } catch (e: Exception) { + Log.e("SlimBook", "layout_fix.js missing", e) + "" } private fun loadFilter() { CoroutineScope(Dispatchers.IO).launch { filterJs = filterManager.getFilterJs() + layoutFixJs = loadLayoutFixJs() withContext(Dispatchers.Main) { webView.loadUrl(FB_URL) } @@ -923,6 +990,11 @@ class MainActivity : AppCompatActivity() { if (filterJs.isNotEmpty()) { webView.evaluateJavascript(filterJs, null) } + // Issue #9: stop comment reaction chips overlapping the next comment + // / "Show previous replies" row. + if (layoutFixJs.isNotEmpty()) { + webView.evaluateJavascript(layoutFixJs, null) + } webView.evaluateJavascript(""" (function() { if (window.__sb_composer_hooked) return; @@ -1056,7 +1128,9 @@ class MainActivity : AppCompatActivity() { "Remote filter (${if (authorDb.isRemoteFilterEnabled()) "on" else "off"})", "View log (${logMessages.size} entries)", "Dump DOM", - "Re-run filter" + "Re-run filter", + if (authorDb.isMessengerButtonEnabled()) "Hide Messenger button" else "Show Messenger button", + "Reset button/badge positions" ) AlertDialog.Builder(this) .setTitle("SlimBook Debug") @@ -1071,6 +1145,15 @@ class MainActivity : AppCompatActivity() { 6 -> showLog() 7 -> webView.evaluateJavascript("window.__slimbook_dump()", null) 8 -> injectFilter() + 9 -> { + authorDb.setMessengerButtonEnabled(!authorDb.isMessengerButtonEnabled()) + updateBadgeVisibility() + } + 10 -> { + authorDb.resetOverlayOffsets() + DragHelper.reset(statsBadge) + DragHelper.reset(messengerButton) + } } } .show() @@ -1249,8 +1332,43 @@ class MainActivity : AppCompatActivity() { return host.endsWith("facebook.com") || host.endsWith("fbcdn.net") || host.endsWith("fb.com") || host.endsWith("messenger.com") } - @Deprecated("Use OnBackPressedCallback") - override fun onBackPressed() { + // ---- Back navigation (system back button AND back gesture) ---------- + // + // Registered through OnBackPressedDispatcher instead of the deprecated + // onBackPressed() override: this is what the system back gesture / + // predictive back dispatches to (and the only thing that still works once + // targetSdk is 36). Facebook's single-page app also pushes history + // entries that WebView.goBack() "consumes" without changing anything on + // screen, which made the gesture look dead inside a post while the + // in-page back arrow worked, so every goBack() is verified and falls back + // to the in-page back button. + + private val backCallback = object : OnBackPressedCallback(true) { + override fun handleOnBackPressed() { + handleBack() + } + } + + private fun setupBackHandling() { + onBackPressedDispatcher.addCallback(this, backCallback) + } + + private fun isFeedRoot(url: String?): Boolean { + if (url == null) return true + val path = Uri.parse(url).path ?: "" + return path.isEmpty() || path == "/" || path.startsWith("/home") + } + + private fun exitApp() { + // Disable our callback so the dispatcher runs the system default + // (finish / return to launcher), then re-arm it for the next launch + // of this activity instance. + backCallback.isEnabled = false + onBackPressedDispatcher.onBackPressed() + backCallback.isEnabled = true + } + + private fun handleBack() { val url = webView.url ?: "" if (isChatUrl(url)) { // Leave chat - go back to feed with mobile UA @@ -1258,11 +1376,58 @@ class MainActivity : AppCompatActivity() { messengerRedirectPending = false webView.settings.userAgentString = MOBILE_UA applyFeedMode() + updateBadgeVisibility() webView.loadUrl(FB_URL) - } else if (webView.canGoBack()) { - webView.goBack() - } else { - super.onBackPressed() + return + } + if (isFeedRoot(url)) { + if (webView.canGoBack()) webView.goBack() else exitApp() + return + } + goBackVerified() + } + + // Cheap page fingerprint: URL + element count + scroll. If it is unchanged + // after goBack(), the back press was swallowed by the SPA. + private val pageSignatureJs = + "(function(){return location.href+'|'+document.getElementsByTagName('*').length+'|'+Math.round(window.scrollY);})()" + + private fun goBackVerified() { + webView.evaluateJavascript(pageSignatureJs) { before -> + if (webView.canGoBack()) { + webView.goBack() + } else { + clickPageBackButtonOrExit() + return@evaluateJavascript + } + webView.postDelayed({ + if (isFinishing || isDestroyed) return@postDelayed + webView.evaluateJavascript(pageSignatureJs) { after -> + if (before != null && before == after) { + Log.d("SlimBook", "BACK: goBack() had no visible effect, using page back button") + clickPageBackButtonOrExit() + } + } + }, 450) + } + } + + private fun loadFeed() { + isMessengerMode = false + messengerRedirectPending = false + webView.settings.userAgentString = MOBILE_UA + applyFeedMode() + updateBadgeVisibility() + webView.loadUrl(FB_URL) + } + + // Facebook often replaces the history entry instead of pushing one, so a + // post can have no history to step back through. Back must still go + // somewhere: the feed. Only a press made on the feed itself leaves the app. + private fun clickPageBackButtonOrExit() { + webView.evaluateJavascript(PAGE_BACK_JS) { result -> + if (result == "true") return@evaluateJavascript + if (!isFeedRoot(webView.url)) loadFeed() else exitApp() } } diff --git a/app/src/main/res/drawable/bg_messenger_button.xml b/app/src/main/res/drawable/bg_messenger_button.xml new file mode 100644 index 0000000..d94f71f --- /dev/null +++ b/app/src/main/res/drawable/bg_messenger_button.xml @@ -0,0 +1,5 @@ + + + + diff --git a/app/src/main/res/drawable/ic_messenger.xml b/app/src/main/res/drawable/ic_messenger.xml new file mode 100644 index 0000000..103f85f --- /dev/null +++ b/app/src/main/res/drawable/ic_messenger.xml @@ -0,0 +1,15 @@ + + + + + + + diff --git a/app/src/main/res/layout/activity_main.xml b/app/src/main/res/layout/activity_main.xml index 2cc2f9d..dd77897 100644 --- a/app/src/main/res/layout/activity_main.xml +++ b/app/src/main/res/layout/activity_main.xml @@ -20,7 +20,8 @@ android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" - android:layout_margin="12dp" + android:layout_marginEnd="12dp" + android:layout_marginBottom="84dp" android:background="#CC000000" android:focusable="false" android:focusableInTouchMode="false" @@ -30,4 +31,21 @@ android:visibility="gone" android:text="🛡 0" /> + + +