Skip to content
Merged
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -49,30 +46,67 @@ 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) {
if (application === app) return
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) {
if (resumedActivity?.get() === activity) resumedActivity = null
}

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
Expand Down Expand Up @@ -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)) {
Expand All @@ -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 &&
Expand All @@ -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<ViewGroup>(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
Expand Down Expand Up @@ -228,30 +263,35 @@ 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))
.start()
}

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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
}
Expand All @@ -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)
}
Expand Down
Loading
Loading