diff --git a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingBoxTriggerView.kt b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingBoxTriggerView.kt index 5fca1e1..01fbf44 100644 --- a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingBoxTriggerView.kt +++ b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingBoxTriggerView.kt @@ -53,7 +53,8 @@ internal class PoltioFloatingBoxTriggerView( /** Docked on the left screen edge: every edge-facing detail is mirrored, like web's `box.ts`, * so the square side sits against the edge and the rounded side faces the screen. */ private val isLeftDocked = widget.overlayOptions.isLeftDocked - private val dockedEdgeGravity = if (isLeftDocked) Gravity.START else Gravity.END + /** Absolute, like the overlay manager's, so a right-to-left locale doesn't flip the tab. */ + private val dockedEdgeGravity = if (isLeftDocked) Gravity.LEFT else Gravity.RIGHT private val collapsedWidthPx get() = context.dp(42f * scale) private val collapsedHeightPx get() = context.dp(140f * scale) diff --git a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingCardTriggerView.kt b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingCardTriggerView.kt index 781f309..c0e544c 100644 --- a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingCardTriggerView.kt +++ b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioFloatingCardTriggerView.kt @@ -60,7 +60,8 @@ internal class PoltioFloatingCardTriggerView( /** Docked on the left screen edge: the edge tab and every edge-facing detail are mirrored, so * the square side sits against the edge and the rounded side faces the screen. */ private val isLeftDocked = widget.overlayOptions.isLeftDocked - private val dockedEdgeGravity = if (isLeftDocked) Gravity.START else Gravity.END + /** Absolute, like the overlay manager's, so a right-to-left locale doesn't flip the tab. */ + private val dockedEdgeGravity = if (isLeftDocked) Gravity.LEFT else Gravity.RIGHT private val collapsedWidthPx = context.dp(Constants.COLLAPSED_WIDTH_DP) private val collapsedHeightPx = context.dp(Constants.COLLAPSED_HEIGHT_DP) diff --git a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioOverlayManager.kt b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioOverlayManager.kt index 73d09c4..1df8dd0 100644 --- a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioOverlayManager.kt +++ b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioOverlayManager.kt @@ -27,9 +27,6 @@ import java.lang.ref.WeakReference * `window.decorView` / root `FrameLayout` rather than a system-alert-window overlay. */ internal object PoltioOverlayManager { - private const val MAX_SHOW_RETRIES = 10 - private const val RETRY_DELAY_MS = 200L - /** * Default bottom inset for the box trigger — unlike pill/card (70dp), the box trigger's * collapsed tab is tall (140dp) and sits low by design, but 24dp put it directly behind most @@ -49,8 +46,29 @@ internal object PoltioOverlayManager { private var triggerSlideOffsetDp = 80f private var currentPublicId: String? = null private var currentTriggerType: String? = null - private var showTriggerRetryCount = 0 - private var pendingShowRunnable: Runnable? = null + /** Widgets can share content and trigger type yet differ in copy, colors and position, so the + * trigger on screen is only the incoming one when its widget id matches too. */ + private var currentWidgetId: Int? = null + + /** A widget waiting for a host Activity to resume, shown from `onActivityResumed`: one that + * resolved while no host was resumed (the app still starting or in the background, or the + * widget sheet up over a host that a rotation rebuilt behind it), or the trigger a host was + * showing when a configuration change destroyed it. */ + private var pendingTrigger: TriggerRequest? = null + /** What the trigger on screen was built from, so a configuration change can carry it over. */ + private var shownTrigger: TriggerRequest? = null + /** Whether the widget sheet is up, from its creation until it's destroyed for good (a rotation + * rebuilding it doesn't count). No trigger shows meanwhile: the host under the sheet is paused, + * or, rebuilt behind it by a rotation, resumed for only a moment. */ + private var isSheetOpen = false + + /** [reportView] is false for a trigger carried over a configuration change: it was already + * counted before the rotation, and a host that re-tracks its screen counts it again anyway. */ + private class TriggerRequest(val widget: PoltioWidgetResponse, val puid: String?, val reportView: Boolean = true) + + /** Reports a trigger view; swapped in tests to count them. */ + @androidx.annotation.VisibleForTesting + internal var ctaViewReporter: (PoltioWidgetResponse) -> Unit = { PoltioSDK.reportCtaView(it) } /** Registers activity-lifecycle tracking; safe to call more than once with the same instance. */ fun attach(app: Application) { @@ -58,7 +76,11 @@ internal object PoltioOverlayManager { application = app app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityResumed(activity: Activity) { + // The widget sheet never hosts a trigger: while it's up, the trigger belongs to the + // host behind it, which resumes again once the sheet closes. + if (activity is PoltioWebViewActivity) return resumedActivity = WeakReference(activity) + showPendingTriggerIfPossible() } override fun onActivityPaused(activity: Activity) { @@ -66,13 +88,25 @@ internal object PoltioOverlayManager { } override fun onActivityDestroyed(activity: Activity) { + if (activity is PoltioWebViewActivity && !activity.isChangingConfigurations) { + // The sheet is closed for good; the host may have resumed under it already. + isSheetOpen = false + showPendingTriggerIfPossible() + return + } if (resumedActivity?.get() === activity) resumedActivity = null if (overlayContainer?.let { it.context === activity } == true) { + // A configuration change (e.g. rotation) rebuilds the host: carry its trigger + // over to the new one instead of leaving it bare until the next screen view. + val carriedOver = shownTrigger.takeIf { activity.isChangingConfigurations } teardownOverlaySynchronously() + if (carriedOver != null) pendingTrigger = TriggerRequest(carriedOver.widget, carriedOver.puid, reportView = false) } } - override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit + override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { + if (activity is PoltioWebViewActivity) isSheetOpen = true + } override fun onActivityStarted(activity: Activity) = Unit override fun onActivityStopped(activity: Activity) = Unit override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit @@ -106,9 +140,22 @@ internal object PoltioOverlayManager { PoltioExecutors.runOnMain { hideTriggerOnMain() } } - private fun showTriggerOnMain(widget: PoltioWidgetResponse, puid: String?) { - pendingShowRunnable?.let { PoltioExecutors.main.removeCallbacks(it) } - pendingShowRunnable = null + /** Shows the kept trigger once nothing stands in its way: a host resumed and the sheet closed, + * in whichever order those happen. */ + private fun showPendingTriggerIfPossible() { + val request = pendingTrigger ?: return + if (isSheetOpen || resumedActivity?.get() == null) return + pendingTrigger = null + showTriggerOnMain(request.widget, request.puid, request.reportView) + } + + /** Whether [widget] is the one the current trigger was built for: same content and same widget. */ + private fun isCurrent(widget: PoltioWidgetResponse): Boolean = + currentPublicId == widget.publicId && currentWidgetId == widget.widgetId + + private fun showTriggerOnMain(widget: PoltioWidgetResponse, puid: String?, reportView: Boolean = true) { + // A newer request supersedes one still waiting for a host to resume. + pendingTrigger = null val options = widget.overlayOptions if (!(options.isBoxTrigger || options.isPillTrigger || options.isCardTrigger)) { @@ -133,7 +180,7 @@ internal object PoltioOverlayManager { val targetTriggerType = options.triggerType ?: "" - if (currentPublicId == widget.publicId && + if (isCurrent(widget) && currentTriggerType == targetTriggerType && activeTriggerView != null && activeTriggerView?.parent != null && @@ -146,45 +193,33 @@ internal object PoltioOverlayManager { // The `context === activity` check matters because the trigger is attached to the // current Activity's content view: without it, navigating to a *new* Activity (which // only backstacks the old one rather than destroying it) that resolves the same widget - // would match on publicId/triggerType alone and return here — leaving the trigger + // would match on widget and trigger type alone and return here — leaving the trigger // attached to the paused, off-screen Activity underneath instead of the one actually // visible now. - PoltioSDK.reportCtaView(widget) + if (reportView) ctaViewReporter(widget) return } - val isRetryForSameWidget = currentPublicId == widget.publicId teardownOverlaySynchronously() - if (!isRetryForSameWidget) showTriggerRetryCount = 0 - currentPublicId = widget.publicId - currentTriggerType = targetTriggerType - if (activity == null) { - if (showTriggerRetryCount >= MAX_SHOW_RETRIES) { - PoltioLogger.warning { "No resumed Activity available after $MAX_SHOW_RETRIES retries; giving up on showing trigger for widget '${widget.publicId}'." } - showTriggerRetryCount = 0 - currentPublicId = null - currentTriggerType = null - return - } - showTriggerRetryCount++ - PoltioLogger.debug { "No resumed Activity yet, retrying showTrigger ($showTriggerRetryCount/$MAX_SHOW_RETRIES) after ${RETRY_DELAY_MS}ms..." } - val runnable = Runnable { - if (currentPublicId == widget.publicId) showTriggerOnMain(widget, puid) - } - pendingShowRunnable = runnable - PoltioExecutors.main.postDelayed(runnable, RETRY_DELAY_MS) + if (activity == null || isSheetOpen) { + // Keep it rather than give up after a few tries: a host sitting paused under the widget + // sheet after a rotation resumes only once the sheet closes, however long that takes. + PoltioLogger.debug { "No resumed Activity or widget sheet up; showing the trigger for widget '${widget.publicId}' once a host resumes with the sheet closed." } + pendingTrigger = TriggerRequest(widget, puid, reportView) return } - showTriggerRetryCount = 0 + currentPublicId = widget.publicId + currentTriggerType = targetTriggerType + currentWidgetId = widget.widgetId val contentRoot = activity.findViewById(android.R.id.content) ?: return // The trigger is now guaranteed to actually render below — report the impression once - // here rather than at the top of the method, so retries while waiting for a resumed - // Activity (which re-enter this same method) don't double-report. - PoltioSDK.reportCtaView(widget) + // here rather than at the top of the method, so a widget kept for a host to resume isn't + // reported until it actually shows. + if (reportView) ctaViewReporter(widget) val container = FrameLayout(activity).apply { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) clipChildren = false @@ -228,19 +263,23 @@ internal object PoltioOverlayManager { } activeTriggerView = triggerView + shownTrigger = TriggerRequest(widget, puid) PoltioLogger.info { "Attached floating trigger overlay for widget '${widget.publicId}' (type: ${options.triggerType ?: "unknown"})." } animateTriggerIn(triggerView) } + /** Slides the trigger in from beyond its edge to its resting place, which is always an + * untranslated X: reading the current translation instead would, on a trigger still mid-way + * through an earlier entrance, settle it off-screen. */ private fun animateTriggerIn(view: android.view.View) { - val restingX = view.translationX + view.animate().cancel() view.alpha = 0f - view.translationX = restingX + view.context.dp(triggerSlideOffsetDp) + view.translationX = view.context.dp(triggerSlideOffsetDp).toFloat() view.animate() .alpha(1f) - .translationX(restingX) + .translationX(0f) .setStartDelay(50) .setDuration(400) .setInterpolator(android.view.animation.OvershootInterpolator(0.9f)) @@ -248,10 +287,11 @@ internal object PoltioOverlayManager { } private fun hideTriggerOnMain() { - pendingShowRunnable?.let { PoltioExecutors.main.removeCallbacks(it) } - pendingShowRunnable = null + pendingTrigger = null + shownTrigger = null currentPublicId = null currentTriggerType = null + currentWidgetId = null val container = overlayContainer val view = activeTriggerView @@ -272,10 +312,10 @@ internal object PoltioOverlayManager { /** Synchronously tears down any existing overlay container/view (no animation). */ private fun teardownOverlaySynchronously() { - pendingShowRunnable?.let { PoltioExecutors.main.removeCallbacks(it) } - pendingShowRunnable = null + shownTrigger = null currentPublicId = null currentTriggerType = null + currentWidgetId = null activeTriggerView = null overlayContainer?.let { (it.parent as? ViewGroup)?.removeView(it) } overlayContainer = null @@ -315,7 +355,9 @@ internal object PoltioOverlayManager { val params = view.layoutParams as? FrameLayout.LayoutParams ?: FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT) - val horizontalGravity = if (horizontal == "left") Gravity.START else Gravity.END + // Absolute LEFT/RIGHT, not START/END: `floating-position` names a physical side and the + // triggers draw their rounded corners for it, so a right-to-left locale mustn't flip it. + val horizontalGravity = if (horizontal == "left") Gravity.LEFT else Gravity.RIGHT val verticalGravity = when (vertical) { "top" -> Gravity.TOP "center" -> Gravity.CENTER_VERTICAL @@ -380,6 +422,9 @@ internal object PoltioOverlayManager { internal fun onWidgetWebViewDismissed() { PoltioExecutors.runOnMain { val container = overlayContainer ?: return@runOnMain + // Only a trigger the sheet hid comes back here. One shown as the sheet went away (kept + // across a rotation and shown once the sheet closed) is already on screen, entering. + if (container.visibility == android.view.View.VISIBLE) return@runOnMain val trigger = activeTriggerView as? PoltioTriggerPresentable trigger?.resetToCollapsed(animated = false) diff --git a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioWebViewActivity.kt b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioWebViewActivity.kt index 0e3514e..c42d4ee 100644 --- a/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioWebViewActivity.kt +++ b/android/poltio-sdk/src/main/java/com/poltio/sdk/ui/PoltioWebViewActivity.kt @@ -323,7 +323,8 @@ internal class PoltioWebViewActivity : Activity() { addView(disc, FrameLayout.LayoutParams(dp(30f), dp(30f), Gravity.CENTER)) addView(PoltioCloseGlyphView(context, Color.WHITE), FrameLayout.LayoutParams(dp(28f), dp(28f), Gravity.CENTER)) } - sheet.addView(closeButton, FrameLayout.LayoutParams(dp(48f), dp(48f), Gravity.TOP or Gravity.END).apply { + // Top-right in every locale, like the SDK's other physically placed chrome. + sheet.addView(closeButton, FrameLayout.LayoutParams(dp(48f), dp(48f), Gravity.TOP or Gravity.RIGHT).apply { topMargin = dp(4f) rightMargin = dp(4f) }) diff --git a/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioEdgeTabTriggerTest.kt b/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioEdgeTabTriggerTest.kt index 75c534f..138c63f 100644 --- a/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioEdgeTabTriggerTest.kt +++ b/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioEdgeTabTriggerTest.kt @@ -31,6 +31,7 @@ class PoltioEdgeTabTriggerTest { ), ) + /** The horizontal gravity, keeping the relative flag so START/END can't pass for LEFT/RIGHT. */ private fun edgeGravity(view: View) = (view.layoutParams as FrameLayout.LayoutParams).gravity and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK private fun cornerRadii(view: View) = (view.background as GradientDrawable).cornerRadii @@ -61,8 +62,8 @@ class PoltioEdgeTabTriggerTest { val r = context.dp(14f).toFloat() assertArrayEquals(label, edgeTabCornerRadii(r, left), cornerRadii(tab), 0f) - assertEquals(label, if (left) Gravity.START else Gravity.END, edgeGravity(tab)) - assertEquals(label, if (left) Gravity.START else Gravity.END, edgeGravity(expanded)) + assertEquals(label, if (left) Gravity.LEFT else Gravity.RIGHT, edgeGravity(tab)) + assertEquals(label, if (left) Gravity.LEFT else Gravity.RIGHT, edgeGravity(expanded)) assertEquals(label, if (left) 90f else -90f, (tab as FrameLayout).getChildAt(0).rotation, 0f) } } @@ -79,8 +80,8 @@ class PoltioEdgeTabTriggerTest { val expandedParams = expanded.layoutParams as FrameLayout.LayoutParams assertArrayEquals(label, edgeTabCornerRadii(r, left), cornerRadii(tab), 0f) - assertEquals(label, if (left) Gravity.START else Gravity.END, edgeGravity(tab)) - assertEquals(label, if (left) Gravity.START else Gravity.END, edgeGravity(expanded)) + assertEquals(label, if (left) Gravity.LEFT else Gravity.RIGHT, edgeGravity(tab)) + assertEquals(label, if (left) Gravity.LEFT else Gravity.RIGHT, edgeGravity(expanded)) assertEquals(label, if (left) margin else 0, expandedParams.leftMargin) assertEquals(label, if (left) 0 else margin, expandedParams.rightMargin) } diff --git a/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioOverlayManagerTest.kt b/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioOverlayManagerTest.kt index f69787d..1389765 100644 --- a/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioOverlayManagerTest.kt +++ b/android/poltio-sdk/src/test/java/com/poltio/sdk/ui/PoltioOverlayManagerTest.kt @@ -3,11 +3,19 @@ package com.poltio.sdk.ui import android.app.Activity import android.app.Application import android.os.Looper +import android.view.View +import android.view.ViewGroup import android.widget.FrameLayout import androidx.test.core.app.ApplicationProvider import com.poltio.sdk.PoltioOverlayOptions import com.poltio.sdk.PoltioWidgetResponse +import java.util.concurrent.TimeUnit import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNotSame +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith @@ -24,6 +32,185 @@ class PoltioOverlayManagerTest { private fun idleMain() = shadowOf(Looper.getMainLooper()).idle() + private fun boxWidget(position: String) = PoltioWidgetResponse( + publicId = "box_widget", + overlayOptions = PoltioOverlayOptions.fromJson(JSONObject("""{"trigger-type":"box","floating-position":"$position"}""")), + widgetId = 7, + ) + + /** The trigger the overlay manager attached to [activity], if any. */ + private fun shownTrigger(activity: Activity): View? { + val contentRoot = activity.findViewById(android.R.id.content) + val container = (0 until contentRoot.childCount).map(contentRoot::getChildAt).lastOrNull() as? ViewGroup ?: return null + return (0 until container.childCount).map(container::getChildAt).firstOrNull { it is PoltioTriggerPresentable } + } + + @Test + fun `triggers keep their physical side in a right-to-left layout`() { + val application = ApplicationProvider.getApplicationContext() + PoltioOverlayManager.attach(application) + val controller = Robolectric.buildActivity(Activity::class.java).create().start().resume() + val activity = controller.get() + + for ((position, onLeft) in listOf("bottom-left" to true, "bottom-right" to false)) { + PoltioOverlayManager.showTrigger(boxWidget(position), puid = null) + idleMain() + val trigger = shownTrigger(activity)!! + val container = trigger.parent as ViewGroup + container.layoutDirection = View.LAYOUT_DIRECTION_RTL + container.measure(View.MeasureSpec.makeMeasureSpec(1080, View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(1920, View.MeasureSpec.EXACTLY)) + container.layout(0, 0, 1080, 1920) + + if (onLeft) assertEquals(position, 0, trigger.left) else assertEquals(position, 1080, trigger.right) + PoltioOverlayManager.hideTrigger() + idleMain() + } + controller.destroy() + } + + @Test + fun `the widget sheet never hosts the trigger, which waits for the host to resume`() { + val application = ApplicationProvider.getApplicationContext() + PoltioOverlayManager.attach(application) + val host = Robolectric.buildActivity(Activity::class.java).create().start().resume() + + // The host is paused under the widget sheet, as after a rotation rebuilds it behind the sheet. + host.pause() + val sheetIntent = PoltioWebViewActivity.newIntent(application, "box_widget", 7, null, null) + val sheet = Robolectric.buildActivity(PoltioWebViewActivity::class.java, sheetIntent).setup() + + PoltioOverlayManager.showTrigger(boxWidget("bottom-left"), puid = null) + idleMain() + assertNull("The sheet must not host the trigger", shownTrigger(sheet.get())) + assertNull("The paused host can't show it yet", shownTrigger(host.get())) + + // Closing the sheet resumes the host, which then shows the widget it was kept for. + sheet.pause().stop().destroy() + host.resume() + idleMain() + assertNotNull("The trigger must show once the host resumes", shownTrigger(host.get())) + + PoltioOverlayManager.hideTrigger() + idleMain() + host.destroy() + } + + /** Runs [block] with trigger views counted into a list of widget ids, then restores the reporter. + * Inline so a failing assertion inside [block] reports its own line. */ + private inline fun countingViews(block: (reported: List) -> Unit) { + val original = PoltioOverlayManager.ctaViewReporter + val reported = mutableListOf() + PoltioOverlayManager.ctaViewReporter = { reported += it.widgetId } + try { + block(reported) + } finally { + PoltioOverlayManager.ctaViewReporter = original + } + } + + @Test + fun `rebuilding the host behind the widget sheet brings the trigger back visible once the sheet closes`() = countingViews { reported -> + val application = ApplicationProvider.getApplicationContext() + PoltioOverlayManager.attach(application) + val host = Robolectric.buildActivity(Activity::class.java).create().start().resume() + PoltioOverlayManager.showTrigger(boxWidget("bottom-left"), puid = null) + idleMain() + + // Opening the widget hides the trigger, and the translucent sheet covers the paused host. + PoltioOverlayManager.presentWidgetWebView("box_widget", 7, puid = null) + idleMain() + host.pause() + val sheetIntent = PoltioWebViewActivity.newIntent(application, "box_widget", 7, null, null) + val sheet = Robolectric.buildActivity(PoltioWebViewActivity::class.java, sheetIntent).setup() + + // A rotation rebuilds the host behind the sheet: it resumes for a moment and pauses again. + host.recreate() + idleMain() + assertNull("Nothing may attach under the sheet", shownTrigger(host.get())) + + // Closing the sheet resumes the host, and only then is the finished sheet destroyed. + sheet.pause() + host.resume() + idleMain() + sheet.stop().destroy() + shadowOf(Looper.getMainLooper()).idleFor(1, TimeUnit.SECONDS) + + val trigger = shownTrigger(host.get()) + assertNotNull("The trigger must come back", trigger) + assertEquals("It must settle on screen, not beside it", 0f, trigger!!.translationX, 0f) + assertEquals(1f, trigger.alpha, 0f) + assertEquals("Counted once, before the rotation", listOf(7), reported) + + PoltioOverlayManager.hideTrigger() + idleMain() + host.destroy() + } + + @Test + fun `a rotation keeps the trigger without counting it again`() = countingViews { reported -> + val application = ApplicationProvider.getApplicationContext() + PoltioOverlayManager.attach(application) + val host = Robolectric.buildActivity(Activity::class.java).create().start().resume() + PoltioOverlayManager.showTrigger(boxWidget("bottom-left"), puid = null) + idleMain() + + host.recreate() + idleMain() + val carriedOver = shownTrigger(host.get()) + assertNotNull("The rebuilt host gets the trigger back", carriedOver) + assertEquals("The rotation itself isn't a new view", listOf(7), reported) + + // A host that tracks its screen again after rotating still counts that one view, as before. + PoltioOverlayManager.showTrigger(boxWidget("bottom-left"), puid = null) + idleMain() + assertSame(carriedOver, shownTrigger(host.get())) + assertEquals(listOf(7, 7), reported) + + PoltioOverlayManager.hideTrigger() + idleMain() + host.destroy() + } + + /** A card widget on the shared content; [widgetId] tells two such widgets apart. */ + private fun cardWidget(widgetId: Int) = PoltioWidgetResponse( + publicId = "shared_widget", + overlayOptions = PoltioOverlayOptions.fromJson(JSONObject("""{"trigger-type":"card"}""")), + widgetId = widgetId, + ) + + @Test + fun `a different widget on the same content and trigger type replaces the trigger`() { + val application = ApplicationProvider.getApplicationContext() + PoltioOverlayManager.attach(application) + val controller = Robolectric.buildActivity(Activity::class.java).create().start().resume() + val contentRoot = controller.get().findViewById(android.R.id.content) + fun shownCard(): PoltioFloatingCardTriggerView? { + val container = contentRoot.getChildAt(contentRoot.childCount - 1) as? ViewGroup ?: return null + return (0 until container.childCount).map(container::getChildAt).filterIsInstance().singleOrNull() + } + + PoltioOverlayManager.showTrigger(cardWidget(widgetId = 1), puid = null) + idleMain() + val first = shownCard() + assertNotNull(first) + + // The same widget again (a revisit, or one widget on two screens) keeps the trigger as it is. + PoltioOverlayManager.showTrigger(cardWidget(widgetId = 1), puid = null) + idleMain() + assertSame(first, shownCard()) + + // Another widget showing the same content as a card has its own copy, colors and position. + PoltioOverlayManager.showTrigger(cardWidget(widgetId = 2), puid = null) + idleMain() + val second = shownCard() + assertNotNull(second) + assertNotSame(first, second) + + PoltioOverlayManager.hideTrigger() + idleMain() + controller.destroy() + } + @Test fun `showTrigger reattaches to a newly resumed Activity instead of reusing a backstacked one`() { val application = ApplicationProvider.getApplicationContext() diff --git a/ios/Sources/PoltioSDK/UI/PoltioBrandingMarkView.swift b/ios/Sources/PoltioSDK/UI/PoltioBrandingMarkView.swift index c11e8bb..5f6aa21 100644 --- a/ios/Sources/PoltioSDK/UI/PoltioBrandingMarkView.swift +++ b/ios/Sources/PoltioSDK/UI/PoltioBrandingMarkView.swift @@ -52,9 +52,22 @@ } /// Applies the widget's custom font family, if any, so the branding mark matches the rest - /// of the card trigger instead of always using the system font. + /// of the card trigger instead of always using the system font, and a wordmark color that + /// reads on the card's own background (`.secondaryLabel` follows the system appearance, not + /// the card, and all but disappears on a dark one). func configure(with options: PoltioOverlayOptions) { label.font = options.resolvedFont(size: Constants.fontSize, weight: .semibold) + label.textColor = Self.wordmarkColor(on: options.resolvedBgColor) + } + + /// Light text on a dark background, dark text on a light one. + static func wordmarkColor(on background: UIColor) -> UIColor { + var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0 + guard background.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else { + return .secondaryLabel + } + let brightness = 0.299 * red + 0.587 * green + 0.114 * blue + return brightness < 0.6 ? UIColor(white: 1, alpha: 0.75) : UIColor(white: 0, alpha: 0.5) } } #endif diff --git a/ios/Sources/PoltioSDK/UI/PoltioFloatingBoxTriggerView.swift b/ios/Sources/PoltioSDK/UI/PoltioFloatingBoxTriggerView.swift index 4967968..ff6782b 100644 --- a/ios/Sources/PoltioSDK/UI/PoltioFloatingBoxTriggerView.swift +++ b/ios/Sources/PoltioSDK/UI/PoltioFloatingBoxTriggerView.swift @@ -351,11 +351,12 @@ } } - /// Holds `container` against the docked edge, so it stays put while the trigger resizes. + /// Holds `container` against the docked edge, so it stays put while the trigger resizes. Physical + /// anchors, like the overlay manager's, so a right-to-left language doesn't flip it. private func pinToDockedEdge(_ container: UIView) -> NSLayoutConstraint { isLeftDocked - ? container.leadingAnchor.constraint(equalTo: leadingAnchor) - : container.trailingAnchor.constraint(equalTo: trailingAnchor) + ? container.leftAnchor.constraint(equalTo: leftAnchor) + : container.rightAnchor.constraint(equalTo: rightAnchor) } /// Default layout: header text, a fixed-height banner strip, footer text. diff --git a/ios/Sources/PoltioSDK/UI/PoltioFloatingCardTriggerView.swift b/ios/Sources/PoltioSDK/UI/PoltioFloatingCardTriggerView.swift index 61777db..71096a9 100644 --- a/ios/Sources/PoltioSDK/UI/PoltioFloatingCardTriggerView.swift +++ b/ios/Sources/PoltioSDK/UI/PoltioFloatingCardTriggerView.swift @@ -386,10 +386,11 @@ } /// Holds `container` `inset` points off the docked edge, so it stays put while the trigger resizes. + /// Physical anchors, like the overlay manager's, so a right-to-left language doesn't flip it. private func pinToDockedEdge(_ container: UIView, inset: CGFloat = 0) -> NSLayoutConstraint { isLeftDocked - ? container.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset) - : container.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset) + ? container.leftAnchor.constraint(equalTo: leftAnchor, constant: inset) + : container.rightAnchor.constraint(equalTo: rightAnchor, constant: -inset) } /// Matches web's card (`core.ts`'s `first` → `second` transition): reveals the collapsed diff --git a/ios/Sources/PoltioSDK/UI/PoltioOverlayManager.swift b/ios/Sources/PoltioSDK/UI/PoltioOverlayManager.swift index e59c915..b6a1d8a 100644 --- a/ios/Sources/PoltioSDK/UI/PoltioOverlayManager.swift +++ b/ios/Sources/PoltioSDK/UI/PoltioOverlayManager.swift @@ -35,6 +35,15 @@ override var shouldAutorotate: Bool { true } + + override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { + super.viewWillTransition(to: size, with: coordinator) + // A rotation can change the host tab bar's height: measure it again once both windows + // have laid out at the new size. + coordinator.animate(alongsideTransition: nil) { _ in + PoltioOverlayManager.shared.refreshTabBarClearance() + } + } } /// Manages attaching, presenting, and dismissing native Poltio floating triggers and interactive webviews. @@ -51,8 +60,15 @@ private var activeTriggerView: (UIView & PoltioTriggerPresentable)? /// How far the active trigger slides in from, and out to, beyond its docked edge. private var triggerSlideOffsetX: CGFloat = 80 + /// The active trigger's bottom constraint when it's bottom-docked, and its own inset above the + /// safe area, kept so its clearance over the host tab bar can follow the bar after it's built. + private var triggerBottomConstraint: NSLayoutConstraint? + private var triggerBottomInset: CGFloat = 0 private var currentPublicId: String? private var currentTriggerType: String? + /// Widgets can share content and trigger type yet differ in copy, colors and position, so the + /// trigger on screen is only the incoming one when its widget id matches too. + private var currentWidgetId: Int? private var pendingShowWorkItem: DispatchWorkItem? private var showTriggerRetryCount = 0 @@ -92,7 +108,7 @@ let targetTriggerType = widget.overlayOptions.triggerType ?? "" - if currentPublicId == widget.publicId, + if isCurrent(widget), currentTriggerType == targetTriggerType, let activeView = activeTriggerView, activeView.superview != nil, @@ -107,16 +123,19 @@ // The scene check matters on iPadOS multi-window setups: without it, switching // focus to a different scene of the same app while this widget's trigger is // still attached (but inactive) in the first scene would match on - // publicId/triggerType alone and return here, leaving the trigger invisible in + // widget and trigger type alone and return here, leaving the trigger invisible in // the scene actually on screen instead of reattaching to it. PoltioSDK.shared.reportCtaView(widget: widget) + // The screen tracked may have hidden or shown the host tab bar (a push with + // `hidesBottomBarWhenPushed`), so the kept trigger measures it again. + refreshTabBarClearance() return } // A retry (scheduled by this same method below) re-enters here for the same widget while // it's still waiting on a UIWindowScene. Only reset the retry counter for a genuinely new // widget — otherwise it gets zeroed on every retry and the cap below never trips. - let isRetryForSameWidget = currentPublicId == widget.publicId + let isRetryForSameWidget = isCurrent(widget) // Clean up previous overlay and update state immediately teardownOverlaySynchronously() @@ -125,6 +144,7 @@ } currentPublicId = widget.publicId currentTriggerType = targetTriggerType + currentWidgetId = widget.widgetId guard let windowScene = findActiveWindowScene() else { guard showTriggerRetryCount < Self.maxShowTriggerRetries else { @@ -132,12 +152,13 @@ showTriggerRetryCount = 0 currentPublicId = nil currentTriggerType = nil + currentWidgetId = nil return } showTriggerRetryCount += 1 PoltioLogger.debug("UIWindowScene not ready yet, retrying showTrigger (\(showTriggerRetryCount)/\(Self.maxShowTriggerRetries)) after 0.2s...") let workItem = DispatchWorkItem { [weak self] in - guard let self, currentPublicId == widget.publicId else { return } + guard let self, isCurrent(widget) else { return } showTrigger(widget: widget, puid: puid) } pendingShowWorkItem = workItem @@ -181,7 +202,10 @@ let vertical = widget.overlayOptions.verticalPosition let isLeftDocked = widget.overlayOptions.isLeftDocked + let bottomObstruction = vertical == "bottom" ? hostTabBarOverlap() : 0 let triggerView: UIView & PoltioTriggerPresentable + let bottomConstraint: NSLayoutConstraint? + let bottomInset: CGFloat if widget.overlayOptions.isPillTrigger { let pillView = PoltioFloatingPillTriggerView( @@ -191,9 +215,11 @@ ) pillView.translatesAutoresizingMaskIntoConstraints = false rootVC.view.addSubview(pillView) - pinTrigger( + bottomInset = 70 + bottomConstraint = Self.pinTrigger( pillView, in: rootVC.view, vertical: vertical, isLeftDocked: isLeftDocked, - horizontalInset: 16, verticalInset: 70, hugsRawEdgeHorizontally: false + horizontalInset: 16, verticalInset: bottomInset, hugsRawEdgeHorizontally: false, + bottomObstruction: bottomObstruction ) triggerView = pillView } else if widget.overlayOptions.isCardTrigger { @@ -203,9 +229,11 @@ ) cardView.translatesAutoresizingMaskIntoConstraints = false rootVC.view.addSubview(cardView) - pinTrigger( + bottomInset = 70 + bottomConstraint = Self.pinTrigger( cardView, in: rootVC.view, vertical: vertical, isLeftDocked: isLeftDocked, - horizontalInset: 0, verticalInset: 70, hugsRawEdgeHorizontally: true + horizontalInset: 0, verticalInset: bottomInset, hugsRawEdgeHorizontally: true, + bottomObstruction: bottomObstruction ) triggerView = cardView } else { @@ -216,14 +244,18 @@ ) boxView.translatesAutoresizingMaskIntoConstraints = false rootVC.view.addSubview(boxView) - pinTrigger( + bottomInset = 24 + bottomConstraint = Self.pinTrigger( boxView, in: rootVC.view, vertical: vertical, isLeftDocked: isLeftDocked, - horizontalInset: 0, verticalInset: 24, hugsRawEdgeHorizontally: true + horizontalInset: 0, verticalInset: bottomInset, hugsRawEdgeHorizontally: true, + bottomObstruction: bottomObstruction ) triggerView = boxView } activeTriggerView = triggerView + triggerBottomConstraint = bottomConstraint + triggerBottomInset = bottomInset triggerSlideOffsetX = isLeftDocked ? -80 : 80 overlayWindow = window window.isHidden = false @@ -248,6 +280,11 @@ } } + /// Whether `widget` is the one the current trigger was built for: same content and same widget. + private func isCurrent(_ widget: PoltioWidgetResponse) -> Bool { + currentPublicId == widget.publicId && currentWidgetId == widget.widgetId + } + /// Hides and removes any currently displayed floating trigger view and its overlay window with animation. func hideTrigger() { DispatchQueue.main.async { [weak self] in @@ -256,12 +293,14 @@ pendingShowWorkItem = nil currentPublicId = nil currentTriggerType = nil + currentWidgetId = nil let windowToClose = overlayWindow let viewToClose = activeTriggerView let slideOffsetX = triggerSlideOffsetX overlayWindow = nil activeTriggerView = nil + triggerBottomConstraint = nil guard let view = viewToClose, let window = windowToClose else { return } @@ -281,8 +320,10 @@ pendingShowWorkItem = nil currentPublicId = nil currentTriggerType = nil + currentWidgetId = nil activeTriggerView?.removeFromSuperview() activeTriggerView = nil + triggerBottomConstraint = nil overlayWindow?.isHidden = true overlayWindow = nil } @@ -290,24 +331,34 @@ /// Pins `view` within `container` according to the parsed `floatingPosition` (`vertical`, left or right), /// generalizing what used to be three hardcoded per-trigger constraint blocks. `hugsRawEdgeHorizontally` /// preserves each trigger's pre-existing horizontal-anchoring convention (card/box hug the raw view - /// edge so their collapsed tabs bleed off-screen; pill insets from the safe area). - private func pinTrigger( + /// edge so their collapsed tabs bleed off-screen; pill insets from the safe area). `bottomObstruction` + /// lifts a bottom-docked trigger over host chrome the overlay window's safe area can't see. + /// + /// Anchors are physical (`left`/`right`), not `leading`/`trailing`: `floating-position` names a + /// physical side, and the triggers draw their rounded corners for it, so a right-to-left app + /// language must not flip the trigger onto the other edge. + /// + /// Returns the bottom constraint of a bottom-docked trigger, for `updateBottomClearance`. + @discardableResult + static func pinTrigger( _ view: UIView, in container: UIView, vertical: String, isLeftDocked: Bool, horizontalInset: CGFloat, verticalInset: CGFloat, - hugsRawEdgeHorizontally: Bool - ) { + hugsRawEdgeHorizontally: Bool, + bottomObstruction: CGFloat = 0 + ) -> NSLayoutConstraint? { var constraints: [NSLayoutConstraint] = [] + var bottomConstraint: NSLayoutConstraint? if isLeftDocked { - let anchor = hugsRawEdgeHorizontally ? container.leadingAnchor : container.safeAreaLayoutGuide.leadingAnchor - constraints.append(view.leadingAnchor.constraint(equalTo: anchor, constant: horizontalInset)) + let anchor = hugsRawEdgeHorizontally ? container.leftAnchor : container.safeAreaLayoutGuide.leftAnchor + constraints.append(view.leftAnchor.constraint(equalTo: anchor, constant: horizontalInset)) } else { - let anchor = hugsRawEdgeHorizontally ? container.trailingAnchor : container.safeAreaLayoutGuide.trailingAnchor - constraints.append(view.trailingAnchor.constraint(equalTo: anchor, constant: -horizontalInset)) + let anchor = hugsRawEdgeHorizontally ? container.rightAnchor : container.safeAreaLayoutGuide.rightAnchor + constraints.append(view.rightAnchor.constraint(equalTo: anchor, constant: -horizontalInset)) } switch vertical { @@ -316,10 +367,112 @@ case "center": constraints.append(view.centerYAnchor.constraint(equalTo: container.centerYAnchor, constant: -verticalInset)) default: // "bottom" - constraints.append(view.bottomAnchor.constraint(equalTo: container.safeAreaLayoutGuide.bottomAnchor, constant: -verticalInset)) + let bottom = view.bottomAnchor.constraint(equalTo: container.safeAreaLayoutGuide.bottomAnchor) + updateBottomClearance(bottom, inset: verticalInset, overlap: bottomObstruction) + constraints.append(bottom) + bottomConstraint = bottom } NSLayoutConstraint.activate(constraints) + return bottomConstraint + } + + /// Points a bottom-docked trigger's bottom `constraint` `inset` above the safe area plus the + /// `overlap` of host tab bar. Returns whether it moved. + @discardableResult + static func updateBottomClearance(_ constraint: NSLayoutConstraint, inset: CGFloat, overlap: CGFloat) -> Bool { + let constant = -(inset + overlap) + guard constraint.constant != constant else { return false } + constraint.constant = constant + // A new constant alone doesn't always flag the layout as stale; the next pass must move it. + (constraint.firstItem as? UIView)?.superview?.setNeedsLayout() + return true + } + + // MARK: - Host Tab Bar + + /// How far the host app's visible tab bar reaches above the bottom safe area. The trigger has + /// its own window, whose safe area knows nothing of the host's bars, so a bottom-docked trigger + /// would otherwise sit over the tab bar and take the taps meant for it. + private func hostTabBarOverlap() -> CGFloat { + guard let hostWindow = findHostKeyWindow(), + let tabBar = Self.visibleTabBar(under: hostWindow.rootViewController) + else { return 0 } + return Self.tabBarOverlap( + tabBarTop: tabBar.convert(tabBar.bounds, to: hostWindow).minY, + windowHeight: hostWindow.bounds.height, + safeAreaBottom: hostWindow.safeAreaInsets.bottom + ) + } + + /// Measures the host tab bar again and moves a bottom-docked trigger to keep clear of it: the + /// bar can hide (`hidesBottomBarWhenPushed`), come back, or change height on rotation while the + /// same trigger stays up. A host transition still running (a push hiding the bar) finishes first. + func refreshTabBarClearance() { + DispatchQueue.main.async { [weak self] in + guard let self, triggerBottomConstraint != nil else { return } + if let coordinator = Self.transitionInFlight(under: findHostKeyWindow()?.rootViewController) { + coordinator.animate(alongsideTransition: nil) { [weak self] _ in + self?.applyTabBarClearance() + } + } else { + applyTabBarClearance() + } + } + } + + private func applyTabBarClearance() { + guard let constraint = triggerBottomConstraint, + let trigger = activeTriggerView, + Self.updateBottomClearance(constraint, inset: triggerBottomInset, overlap: hostTabBarOverlap()) + else { return } + UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseInOut, .allowUserInteraction]) { + trigger.superview?.layoutIfNeeded() + } + } + + /// A view controller transition running anywhere under `root` (a push, a presentation), if any. + private static func transitionInFlight(under root: UIViewController?) -> UIViewControllerTransitionCoordinator? { + guard let root else { return nil } + if let coordinator = root.transitionCoordinator { + return coordinator + } + for child in root.children { + if let coordinator = transitionInFlight(under: child) { + return coordinator + } + } + return transitionInFlight(under: root.presentedViewController) + } + + /// The tab bar on screen under `root`, if any: searched from the topmost presented controller + /// (a modal over a tab bar controller hides its bar), through child controllers, which is where + /// SwiftUI's `TabView` keeps its `UITabBarController`. + static func visibleTabBar(under root: UIViewController?) -> UITabBar? { + var top = root + while let presented = top?.presentedViewController, !presented.isBeingDismissed { + top = presented + } + return firstVisibleTabBar(in: top) + } + + private static func firstVisibleTabBar(in viewController: UIViewController?) -> UITabBar? { + guard let viewController else { return nil } + if let tabBarController = viewController as? UITabBarController { + let tabBar = tabBarController.tabBar + return !tabBar.isHidden && tabBar.window != nil ? tabBar : nil + } + for child in viewController.children { + if let tabBar = firstVisibleTabBar(in: child) { + return tabBar + } + } + return nil + } + + /// The part of a tab bar starting at `tabBarTop` that lies above the bottom safe area. + static func tabBarOverlap(tabBarTop: CGFloat, windowHeight: CGFloat, safeAreaBottom: CGFloat) -> CGFloat { + max(0, windowHeight - safeAreaBottom - tabBarTop) } /// Presents the interactive widget modal WebView on top of the active view controller. @@ -345,6 +498,8 @@ // Reset to collapsed tab after user interacted with webview trigger.resetToCollapsed(animated: false) + // The host may have rotated or changed screens while the sheet covered it. + self.refreshTabBarClearance() window.isHidden = false trigger.alpha = 0 diff --git a/ios/Sources/PoltioSDK/UI/PoltioWebViewController.swift b/ios/Sources/PoltioSDK/UI/PoltioWebViewController.swift index 1da9af0..b7f73a6 100644 --- a/ios/Sources/PoltioSDK/UI/PoltioWebViewController.swift +++ b/ios/Sources/PoltioSDK/UI/PoltioWebViewController.swift @@ -131,9 +131,10 @@ activityIndicator.centerXAnchor.constraint(equalTo: view.centerXAnchor), activityIndicator.centerYAnchor.constraint(equalTo: view.centerYAnchor), - // A 44pt tap target around the smaller visible disc. + // A 44pt tap target around the smaller visible disc, top-right in every language like + // the rest of the SDK's physically placed chrome. closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 6), - closeButton.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -6), + closeButton.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor, constant: -6), closeButton.widthAnchor.constraint(equalToConstant: 44), closeButton.heightAnchor.constraint(equalToConstant: 44), diff --git a/ios/Tests/PoltioSDKTests/PoltioSDKTests.swift b/ios/Tests/PoltioSDKTests/PoltioSDKTests.swift index 181bfe8..290ead4 100644 --- a/ios/Tests/PoltioSDKTests/PoltioSDKTests.swift +++ b/ios/Tests/PoltioSDKTests/PoltioSDKTests.swift @@ -1922,6 +1922,115 @@ final class PoltioSDKTests: XCTestCase { } } + func testTriggersKeepTheirPhysicalSideInRightToLeftLayouts() { + for isLeftDocked in [true, false] { + let container = UIView(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) + container.semanticContentAttribute = .forceRightToLeft + // Pinned to `leading`, the control lands on the right: the layout really is right-to-left. + let control = UIView() + let trigger = UIView() + for view in [control, trigger] { + view.translatesAutoresizingMaskIntoConstraints = false + view.semanticContentAttribute = .forceRightToLeft + container.addSubview(view) + NSLayoutConstraint.activate([ + view.widthAnchor.constraint(equalToConstant: 42), + view.heightAnchor.constraint(equalToConstant: 140), + ]) + } + NSLayoutConstraint.activate([ + control.leadingAnchor.constraint(equalTo: container.leadingAnchor), + control.topAnchor.constraint(equalTo: container.topAnchor), + ]) + PoltioOverlayManager.pinTrigger( + trigger, in: container, vertical: "bottom", isLeftDocked: isLeftDocked, + horizontalInset: 0, verticalInset: 24, hugsRawEdgeHorizontally: true, + bottomObstruction: 50 + ) + container.layoutIfNeeded() + + XCTAssertEqual(control.frame.maxX, 402) + if isLeftDocked { + XCTAssertEqual(trigger.frame.minX, 0) + } else { + XCTAssertEqual(trigger.frame.maxX, 402) + } + // Lifted by its own bottom inset plus the host tab bar the overlay window can't see. + XCTAssertEqual(trigger.frame.maxY, 874 - 24 - 50) + } + } + + func testBottomTriggersClearTheHostTabBar() { + XCTAssertEqual(PoltioOverlayManager.tabBarOverlap(tabBarTop: 790, windowHeight: 874, safeAreaBottom: 34), 50) + XCTAssertEqual(PoltioOverlayManager.tabBarOverlap(tabBarTop: 874, windowHeight: 874, safeAreaBottom: 34), 0) + + let window = UIWindow(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) + let tabs = UITabBarController() + tabs.viewControllers = [UIViewController()] + // Embedded as a child, the way SwiftUI's TabView hosts its UITabBarController. + let root = UIViewController() + root.addChild(tabs) + root.view.addSubview(tabs.view) + tabs.didMove(toParent: root) + window.rootViewController = root + window.isHidden = false + + XCTAssertTrue(PoltioOverlayManager.visibleTabBar(under: root) === tabs.tabBar) + tabs.tabBar.isHidden = true + XCTAssertNil(PoltioOverlayManager.visibleTabBar(under: root)) + XCTAssertNil(PoltioOverlayManager.visibleTabBar(under: UIViewController())) + } + + func testBottomTriggerFollowsTheTabBarAfterItIsBuilt() throws { + let container = UIView(frame: CGRect(x: 0, y: 0, width: 402, height: 874)) + func addTrigger() -> UIView { + let trigger = UIView() + trigger.translatesAutoresizingMaskIntoConstraints = false + container.addSubview(trigger) + NSLayoutConstraint.activate([ + trigger.widthAnchor.constraint(equalToConstant: 42), + trigger.heightAnchor.constraint(equalToConstant: 140), + ]) + return trigger + } + + let trigger = addTrigger() + let bottom = try XCTUnwrap(PoltioOverlayManager.pinTrigger( + trigger, in: container, vertical: "bottom", isLeftDocked: false, + horizontalInset: 0, verticalInset: 24, hugsRawEdgeHorizontally: true, + bottomObstruction: 50 + )) + container.layoutIfNeeded() + XCTAssertEqual(trigger.frame.maxY, 874 - 24 - 50) + + // The tab bar hides: the trigger drops back to its own inset. + XCTAssertTrue(PoltioOverlayManager.updateBottomClearance(bottom, inset: 24, overlap: 0)) + container.layoutIfNeeded() + XCTAssertEqual(trigger.frame.maxY, 874 - 24) + + // Measured again with nothing changed, it stays put. + XCTAssertFalse(PoltioOverlayManager.updateBottomClearance(bottom, inset: 24, overlap: 0)) + + // Only a bottom-docked trigger has a clearance to follow. + for vertical in ["top", "center"] { + XCTAssertNil(PoltioOverlayManager.pinTrigger( + addTrigger(), in: container, vertical: vertical, isLeftDocked: false, + horizontalInset: 0, verticalInset: 24, hugsRawEdgeHorizontally: true + ), vertical) + } + } + + func testPoltioWordmarkContrastsWithTheCardBackground() { + func isLight(_ color: UIColor) -> Bool { + var white: CGFloat = 0, alpha: CGFloat = 0 + color.getWhite(&white, alpha: &alpha) + return white > 0.5 + } + XCTAssertTrue(isLight(PoltioBrandingMarkView.wordmarkColor(on: UIColor(red: 0.12, green: 0.24, blue: 0.33, alpha: 1))), "navy card") + XCTAssertTrue(isLight(PoltioBrandingMarkView.wordmarkColor(on: UIColor(red: 0, green: 0.62, blue: 0.93, alpha: 1))), "default blue card") + XCTAssertFalse(isLight(PoltioBrandingMarkView.wordmarkColor(on: .white)), "white card") + } + func testOverlayManagerCardTriggerPresentation() { let options = PoltioOverlayOptions( floatingTitle: "TV Finder",