From b2fc16835c42e5ae0930ccfa71077bdaea7881e7 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 16:48:57 +0800 Subject: [PATCH 1/2] feat(native-overlay): dismiss a collapsed toast stack by swiping toward its edge A collapsed stack, including a single toast, now behaves as one banner: dragging it toward the anchored edge moves every card and dismisses them together, and dragging it away expands a stack of two or more. An expanded stack is a list: cards still swipe sideways one at a time, and pushing the stack toward the edge collapses it. The direction follows the expanded state, which the user changes, instead of the toast count, which changes on its own. - iOS and Android lock the axis when the drag starts and move every card of the stack inside its scaled slot. A group dismissal starts all exits before one layout pass, so back cards keep their depth and faded body and no card is promoted into the front slot while the group leaves. - Toasts shown during a drag wait and enter after release, so a new card never takes the dragged card's slot. A drag whose owner is closed in code ends cleanly instead of deferring later toasts forever. - Web applies the gestures to touch input with the lane's anchored edge as the dismiss direction; mouse and pen keep the horizontal swipe, since hover already expands the stack. - SPEC gains a stack gesture contract and the iOS simulator run. Co-Authored-By: Claude Opus 5.5 --- .../nativeoverlay/NativeOverlayToasterView.kt | 340 +++++++++++++++--- .../NativeOverlayToastCardLayoutTest.kt | 35 +- .../react-native-native-overlay/docs/SPEC.md | 55 ++- .../ios/NativeOverlayToasterView.swift | 299 ++++++++++++--- .../src/__tests__/overlayToast.web.test.ts | 156 +++++++- .../src/toast/toastDomRenderer.web.ts | 322 ++++++++++++++++- .../src/toast/toastStyles.web.ts | 9 +- 7 files changed, 1104 insertions(+), 112 deletions(-) diff --git a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt index 2ebcc87b5..5073f6f87 100644 --- a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt +++ b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToasterView.kt @@ -66,6 +66,14 @@ private object ToasterMetrics { const val SWIPE_FLICK_VELOCITY = 500f const val SWIPE_OPACITY_RANGE = 260f const val SWIPE_MIN_OPACITY = 0.35f + /** Pull away from the top edge that expands a collapsed stack. */ + const val EXPAND_PULL_DISTANCE = 40f + /** Push toward the top edge that collapses an expanded stack. */ + const val COLLAPSE_PUSH_DISTANCE = 50f + const val RUBBER_DIMENSION = 30f + const val EXPAND_RUBBER_DIMENSION = 70f + /** Extra pull per depth while expanding, so back cards fan out under the finger. */ + const val EXPAND_SPREAD_STEP = 0.35f const val FALLBACK_MARGIN = 64f const val FALLBACK_MAX_PAGE_WIDTH = 640f const val LANE_MAX_WIDTH = 360f @@ -181,18 +189,26 @@ private class ToastStageLayout(context: Context) : FrameLayout(context) { } } -/** Hosts one card: forwards presses and horizontal drags to the presenter. */ +/** + * Hosts one card: forwards presses and drags to the presenter. A horizontal + * drag moves this card here; a vertical drag is reported in window pixels and + * the presenter moves every card it involves. + */ @SuppressLint("ViewConstructor") internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) : FrameLayout(context) { var onPressChanged: (() -> Unit)? = null - var onRelease: ((translationX: Float, translationY: Float, velocityX: Float, cancelled: Boolean) -> Unit)? = null + var onDragStart: ((vertical: Boolean, dx: Float, dy: Float) -> Unit)? = null + var onVerticalDrag: ((dy: Float) -> Unit)? = null + var onRelease: ( + (translationX: Float, translationY: Float, velocityX: Float, velocityY: Float, cancelled: Boolean) -> Unit + )? = null var onTap: (() -> Unit)? = null var allowDrag = true set(value) { if (field && !value && dragging) { cancelDrag() moved = true - onRelease?.invoke(0f, 0f, 0f, true) + onRelease?.invoke(0f, 0f, 0f, 0f, true) } field = value } @@ -203,6 +219,9 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) private var windowDragX = 0f var dragging = false private set + /** The locked axis of the current drag. */ + var dragVertical = false + private set private var moved = false private val slop get() = ToasterMetrics.SWIPE_START * resources.displayMetrics.density var hasActivePress = false @@ -218,6 +237,7 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) private fun cancelDrag() { dragging = false + dragVertical = false windowDragX = 0f tracker?.recycle() tracker = null @@ -263,11 +283,20 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) } fun reprojectDrag() { - if (dragging && scaleX > 0f) { + if (dragging && !dragVertical && scaleX > 0f) { card.translationX = windowDragX / scaleX } } + /** Locks the axis once the drag passes the slop. */ + private fun startDragIfNeeded(dx: Float, dy: Float): Boolean { + if (dragging || (abs(dx) <= slop && abs(dy) <= slop)) return false + dragging = true + dragVertical = abs(dy) > abs(dx) + onDragStart?.invoke(dragVertical, dx, dy) + return true + } + override fun onInterceptTouchEvent(event: MotionEvent): Boolean { when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { @@ -283,8 +312,7 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) track(event) val dy = event.rawY - downY val dx = event.rawX - downX - if (!dragging && abs(dx) > slop && abs(dx) > abs(dy)) { - dragging = true + if (startDragIfNeeded(dx, dy)) { parent?.requestDisallowInterceptTouchEvent(true) } } @@ -302,8 +330,10 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) if (abs(dy) > slop || abs(dx) > slop) moved = true if (allowDrag) { track(event) - if (!dragging && abs(dx) > slop && abs(dx) > abs(dy)) dragging = true - if (dragging) { + startDragIfNeeded(dx, dy) + if (dragging && dragVertical) { + onVerticalDrag?.invoke(dy) + } else if (dragging) { windowDragX = dx card.animate().cancel() reprojectDrag() @@ -319,7 +349,10 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL if (dragging) { tracker?.computeCurrentVelocity(1000) - onRelease?.invoke(event.rawX - downX, event.rawY - downY, tracker?.xVelocity ?: 0f, cancelled) + onRelease?.invoke( + event.rawX - downX, event.rawY - downY, + tracker?.xVelocity ?: 0f, tracker?.yVelocity ?: 0f, cancelled, + ) } else if (!cancelled && !moved && abs(event.rawX - downX) <= slop && abs(event.rawY - downY) <= slop ) { @@ -352,11 +385,37 @@ private class ToastEntry(val id: String, var item: ToastItem, val slot: ToastSlo var entered = false var lastActiveIndex = 0 var swipeExitSign = 1f + /** Left with its stack past the top edge rather than off to a side. */ + var swipeExitUp = false + /** The body was faded behind the front card when the dismissal began. */ + var exitBodyHidden = false var lastTargetY = Float.NaN + var lastTargetScale = 1f var lastPaneScale = 1f var dragStart = 0f } +private enum class ToastDragMode { + /** One card, sideways. */ + HORIZONTAL, + /** The collapsed stack toward the top edge, dismissing it. */ + STACK, + /** The collapsed stack away from the top edge, expanding it. */ + EXPAND, + /** The expanded stack toward the top edge, collapsing it. */ + COLLAPSE, + /** Nothing to do in that direction: damped, then settles. */ + RUBBER, +} + +private class ToastDrag(val mode: ToastDragMode, val owner: ToastEntry, val participants: List) + +/** Damped displacement past a limit, as a scroll view's edge bounce. */ +private fun rubberBand(offset: Float, dimension: Float): Float { + val magnitude = dimension * (1f - 1f / (abs(offset) * 0.55f / dimension + 1f)) + return if (offset < 0f) -magnitude else magnitude +} + /** * Draws the message toasts in the activity's `toast` overlay layer: stacking, * timers, swipe and motion all live here, on the main thread. @@ -376,6 +435,9 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { private var config = ToasterConfig() private var expanded = false private var obstructionShift = 0f + private var drag: ToastDrag? = null + /** Toasts first shown during a drag, oldest first; they enter when it ends. */ + private val deferredAdds = mutableListOf() private val motionObserver = object : ContentObserver(handler) { override fun onChange(selfChange: Boolean) { layout(animated = false) @@ -401,6 +463,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { val configChanged = next.cardColor != config.cardColor || next.cardBorderColor != config.cardBorderColor config = next val present = items.map { it.spec.id }.toSet() + deferredAdds.removeAll { it.spec.id !in present } // Cards the list no longer knows leave without ceremony. entries.filter { it.id !in present }.forEach { remove(it, report = false) } // Oldest first, so each new card joins in front of the previous one. @@ -412,7 +475,14 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { entry = null } if (entry == null) { - if (item.visible) add(item) else onEvent?.invoke(item.spec.id, item.generation, "close", "programmatic") + when { + item.visible && drag != null -> deferAdd(item) + item.visible -> add(item) + else -> { + deferredAdds.removeAll { it.spec.id == item.spec.id } + onEvent?.invoke(item.spec.id, item.generation, "close", "programmatic") + } + } continue } if (entry.item.revision != item.revision || configChanged) { @@ -448,10 +518,29 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { entry.slot.card.cancelStatusMotion() entry.slot.card.cancelLoads() } + deferredAdds.clear() + drag = null expanded = false releaseStage() } + private fun deferAdd(item: ToastItem) { + val index = deferredAdds.indexOfFirst { it.spec.id == item.spec.id } + if (index >= 0) deferredAdds[index] = item else deferredAdds.add(item) + } + + /** Draws the toasts that arrived while a card was being dragged. */ + private fun flushDeferredAdds() { + if (drag != null || deferredAdds.isEmpty()) return + val pending = deferredAdds.toList() + deferredAdds.clear() + for (item in pending) { + if (entries.none { it.id == item.spec.id }) add(item) + } + layout(animated = true) + syncTimers() + } + private fun lifetime(spec: ToastSpec): Long? = if (spec.duration >= 0) spec.duration.toLong() else null @@ -547,20 +636,15 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { card.onLink = { link -> if (!entry.leaving) onEvent?.invoke(entry.id, entry.item.generation, "link", link) } card.apply(item.spec, config.cardColor, config.cardBorderColor) slot.onPressChanged = { syncTimers() } - slot.onRelease = { translationX, _, velocityX, cancelled -> - if (!entry.leaving) { - val distance = abs(translationX) / density - val velocity = velocityX / density * (if (translationX >= 0f) 1f else -1f) - val dismissed = !cancelled && - (distance >= ToasterMetrics.SWIPE_DISTANCE || - (distance >= ToasterMetrics.SWIPE_FLICK_DISTANCE && velocity >= ToasterMetrics.SWIPE_FLICK_VELOCITY)) - if (dismissed) { - entry.swipeExitSign = if (translationX >= 0f) 1f else -1f - dismiss(entry, "swipe", report = true) - } else { - settle(card) - } + slot.onDragStart = { vertical, _, dy -> beginDrag(entry, vertical, dy) } + slot.onVerticalDrag = { dy -> drag?.takeIf { it.owner === entry }?.let { applyVerticalDrag(it, dy) } } + slot.onRelease = { translationX, translationY, velocityX, velocityY, cancelled -> + val current = drag?.takeIf { it.owner === entry } + drag = null + if (current != null) { + finishDrag(current, translationX, translationY, velocityX, velocityY, cancelled) } + flushDeferredAdds() } val press = { if (!entry.leaving) { @@ -595,38 +679,190 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { resetDrag(card) return } - card.animate().translationX(0f).alpha(1f).setDuration(ToasterMetrics.SPRING_MS) + card.animate().translationX(0f).translationY(0f).alpha(1f).setDuration(ToasterMetrics.SPRING_MS) .setInterpolator(toastSpringInterpolator).start() } private fun resetDrag(card: View) { card.translationX = 0f + card.translationY = 0f card.alpha = 1f } - private fun dismiss(entry: ToastEntry, reason: String, report: Boolean) { + // region Drag + + private fun beginDrag(entry: ToastEntry, vertical: Boolean, dy: Float) { + if (entry.leaving || drag != null) return + val active = activeEntries + val mode: ToastDragMode + val participants: List + when { + !vertical -> { + mode = ToastDragMode.HORIZONTAL + participants = listOf(entry) + } + dy < 0f -> { + mode = if (expanded) ToastDragMode.COLLAPSE else ToastDragMode.STACK + participants = active + } + !expanded && active.size > 1 -> { + mode = ToastDragMode.EXPAND + participants = active + } + else -> { + mode = ToastDragMode.RUBBER + participants = listOf(entry) + } + } + participants.forEach { it.slot.card.animate().cancel() } + val next = ToastDrag(mode, entry, participants) + drag = next + if (vertical) applyVerticalDrag(next, dy) + } + + /** [dy] is the drag in window pixels. */ + private fun applyVerticalDrag(drag: ToastDrag, dy: Float) { + val rubber = ToasterMetrics.RUBBER_DIMENSION * density + when (drag.mode) { + ToastDragMode.HORIZONTAL -> Unit + ToastDragMode.STACK -> { + val offset = if (dy < 0f) dy else rubberBand(dy, rubber) + drag.participants.forEach { setDragOffset(it, offset) } + } + ToastDragMode.EXPAND -> { + val offset = if (dy > 0f) rubberBand(dy, ToasterMetrics.EXPAND_RUBBER_DIMENSION * density) else rubberBand(dy, rubber) + drag.participants.forEachIndexed { index, participant -> + setDragOffset(participant, offset * (1f + min(index, 2) * ToasterMetrics.EXPAND_SPREAD_STEP)) + } + } + ToastDragMode.COLLAPSE -> { + val offset = if (dy < 0f) dy * 0.5f else rubberBand(dy, rubber) + drag.participants.forEach { setDragOffset(it, offset) } + } + ToastDragMode.RUBBER -> setDragOffset(drag.owner, rubberBand(dy, rubber)) + } + } + + /** Offsets a card inside its slot; the slot carries the depth and pane scale. */ + private fun setDragOffset(entry: ToastEntry, offset: Float) { if (entry.leaving) return - entry.collapsedBackExit = !expanded && entry.lastActiveIndex > 0 && reason != "swipe" - entry.leaving = true - entry.slot.onPressChanged = null - entry.slot.clearTouch() - entry.slot.card.cancelStatusMotion() - entry.reason = reason - cancelTimer(entry) - if (report) onEvent?.invoke(entry.id, entry.item.generation, "dismiss", reason) + val scale = entry.slot.scaleY.takeIf { it > 0.01f } ?: 1f + entry.slot.card.translationY = offset / scale + } + + /** + * Ends a drag whose owner left or went away without a release, settling the + * other cards it moved and letting deferred toasts in. + */ + private fun abandonDrag(owner: ToastEntry) { + val current = drag?.takeIf { it.owner === owner } ?: return + drag = null + current.participants.filter { it !== owner && !it.leaving }.forEach { settle(it.slot.card) } + handler.post { flushDeferredAdds() } + } + + private fun passesSwipe(distanceDp: Float, speedDp: Float): Boolean = + distanceDp >= ToasterMetrics.SWIPE_DISTANCE || + (distanceDp >= ToasterMetrics.SWIPE_FLICK_DISTANCE && speedDp >= ToasterMetrics.SWIPE_FLICK_VELOCITY) + + private fun finishDrag( + drag: ToastDrag, + translationX: Float, + translationY: Float, + velocityX: Float, + velocityY: Float, + cancelled: Boolean, + ) { + val remaining = drag.participants.filter { !it.leaving } + if (cancelled) { + remaining.forEach { settle(it.slot.card) } + return + } + val dyDp = translationY / density + val vyDp = velocityY / density + when (drag.mode) { + ToastDragMode.HORIZONTAL -> { + val entry = drag.owner + if (entry.leaving) return + val speed = velocityX / density * (if (translationX >= 0f) 1f else -1f) + if (passesSwipe(abs(translationX) / density, speed)) { + entry.swipeExitSign = if (translationX >= 0f) 1f else -1f + entry.swipeExitUp = false + dismiss(entry, "swipe", report = true) + } else { + settle(entry.slot.card) + } + } + ToastDragMode.STACK -> { + if (passesSwipe(-dyDp, -vyDp)) { + remaining.forEach { it.swipeExitUp = true } + dismiss(remaining, "swipe", report = true) + } else { + remaining.forEach { settle(it.slot.card) } + } + } + ToastDragMode.EXPAND -> { + remaining.forEach { settle(it.slot.card) } + val pulled = dyDp >= ToasterMetrics.EXPAND_PULL_DISTANCE || vyDp >= ToasterMetrics.SWIPE_FLICK_VELOCITY + if (pulled && !expanded && activeEntries.size > 1) { + expanded = true + layout(animated = true) + syncTimers() + } + } + ToastDragMode.COLLAPSE -> { + remaining.forEach { settle(it.slot.card) } + val pushed = -dyDp >= ToasterMetrics.COLLAPSE_PUSH_DISTANCE || -vyDp >= ToasterMetrics.SWIPE_FLICK_VELOCITY + if (pushed && expanded) { + expanded = false + layout(animated = true) + syncTimers() + } + } + ToastDragMode.RUBBER -> remaining.forEach { settle(it.slot.card) } + } + } + + // endregion + + private fun dismiss(entry: ToastEntry, reason: String, report: Boolean) { + dismiss(listOf(entry), reason, report) + } + + /** + * Starts every exit before laying out once, so a group leaves together and + * no survivor is promoted between two of its cards. + */ + private fun dismiss(group: List, reason: String, report: Boolean) { + val leaving = group.filter { !it.leaving } + if (leaving.isEmpty()) return + for (entry in leaving) { + abandonDrag(entry) + entry.collapsedBackExit = !expanded && entry.lastActiveIndex > 0 && reason != "swipe" + entry.exitBodyHidden = !expanded && entry.lastActiveIndex > 0 + entry.leaving = true + entry.slot.onPressChanged = null + entry.slot.clearTouch() + entry.slot.card.cancelStatusMotion() + entry.reason = reason + cancelTimer(entry) + if (report) onEvent?.invoke(entry.id, entry.item.generation, "dismiss", reason) + } if (reduceMotion) { - remove(entry, report = true) + leaving.forEach { remove(it, report = true) } layout(animated = false) syncTimers() return } - val removal = Runnable { - remove(entry, report = true) - layout(animated = true) - syncTimers() + for (entry in leaving) { + val removal = Runnable { + remove(entry, report = true) + layout(animated = true) + syncTimers() + } + entry.removal = removal + handler.postDelayed(removal, ToasterMetrics.REMOVE_DELAY_MS) } - entry.removal = removal - handler.postDelayed(removal, ToasterMetrics.REMOVE_DELAY_MS) if (activeEntries.size <= 1) { expanded = false } @@ -635,6 +871,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { } private fun remove(entry: ToastEntry, report: Boolean) { + abandonDrag(entry) entries.remove(entry) cancelTimer(entry) entry.removal?.let(handler::removeCallbacks) @@ -785,12 +1022,20 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { val swipeExit = entry.leaving && entry.reason == "swipe" val cardPaneScale = if (entry.leaving) entry.lastPaneScale else paneScale var swipeExitTranslationX: Float? = null + var swipeExitTranslationY: Float? = null if (entry.leaving) { displayHeight = card.currentDisplayHeightPx.takeIf { it > 0 } ?: naturalHeight val collapsedBackExit = entry.collapsedBackExit val baseY = if (entry.lastTargetY.isNaN()) top.toFloat() else entry.lastTargetY - if (swipeExit) { + if (swipeExit && entry.swipeExitUp) { + // Leaves with its stack: depth scale kept, travel measured in the + // slot's scaled space so every card clears the top edge. + targetY = baseY + targetScale = entry.lastTargetScale + val travel = baseY + obstructionShift + displayHeight + dp(ToasterMetrics.SWIPE_EXIT_MARGIN) + swipeExitTranslationY = -travel / max(targetScale * cardPaneScale, 0.01f) + } else if (swipeExit) { targetY = baseY targetScale = ToasterMetrics.SWIPE_EXIT_SCALE val cardWidthPx = slot.measuredWidth.takeIf { it > 0 }?.toFloat() ?: dp(ToasterMetrics.LANE_MAX_WIDTH).toFloat() @@ -807,7 +1052,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { targetScale = ToasterMetrics.AUTO_EXIT_SCALE } targetAlpha = 0f - hideBody = collapsedBackExit + hideBody = collapsedBackExit || (swipeExit && entry.swipeExitUp && entry.exitBodyHidden) interactive = false allowDrag = false } else { @@ -830,6 +1075,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { allowDrag = isVisible } entry.lastTargetY = targetY + entry.lastTargetScale = targetScale entry.lastPaneScale = cardPaneScale if (isVisible) { expandedOffset += naturalHeight + gutterPx @@ -887,6 +1133,11 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { .setDuration(ToasterMetrics.EXIT_MS) .setInterpolator(toastExitInterpolator) .start() + } else if (swipeExitTranslationY != null) { + card.animate().translationY(swipeExitTranslationY) + .setDuration(ToasterMetrics.EXIT_MS) + .setInterpolator(toastExitInterpolator) + .start() } if (slot.alpha != targetAlpha || entry.alphaAnimator?.isRunning == true) { entry.alphaAnimator?.cancel() @@ -902,9 +1153,12 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { entry.alphaAnimator?.cancel() entry.alphaAnimator = null slot.translationY = targetY + val held = slot.dragging || drag?.participants?.contains(entry) == true if (swipeExitTranslationX != null) { card.translationX = swipeExitTranslationX - } else if (!entry.leaving && !slot.dragging) { + } else if (swipeExitTranslationY != null) { + card.translationY = swipeExitTranslationY + } else if (!entry.leaving && !held) { resetDrag(card) } slot.alpha = targetAlpha diff --git a/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastCardLayoutTest.kt b/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastCardLayoutTest.kt index b3ddee68f..1bd618c98 100644 --- a/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastCardLayoutTest.kt +++ b/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastCardLayoutTest.kt @@ -51,7 +51,7 @@ class NativeOverlayToastCardLayoutTest { val density = slot.resources.displayMetrics.density var releaseX = 0f var releaseVelocity = 0f - slot.onRelease = { x, _, velocity, cancelled -> + slot.onRelease = { x, _, velocity, _, cancelled -> assertTrue(!cancelled) releaseX = x / density releaseVelocity = velocity / density @@ -86,14 +86,43 @@ class NativeOverlayToastCardLayoutTest { slot.clearTouch() } + @Test + fun verticalDragLocksItsAxisAndLeavesTheCardToThePresenter() { + val slot = toastSlot() + val density = slot.resources.displayMetrics.density + var startedVertical: Boolean? = null + var lastDy = 0f + var releaseY = 0f + var releaseVelocityY = 0f + slot.onDragStart = { vertical, _, _ -> startedVertical = vertical } + slot.onVerticalDrag = { dy -> lastDy = dy / density } + slot.onRelease = { _, y, _, velocityY, cancelled -> + assertTrue(!cancelled) + releaseY = y / density + releaseVelocityY = velocityY / density + } + sendTouch(slot, MotionEvent.ACTION_DOWN, 0L, 250f, 70f) + sendTouch(slot, MotionEvent.ACTION_MOVE, 40L, 252f, 56f) + sendTouch(slot, MotionEvent.ACTION_MOVE, 80L, 254f, 30f) + + assertEquals(true, startedVertical) + assertEquals(-40f, lastDy, 0.01f) + // The presenter moves cards on a vertical drag; the slot leaves X alone. + assertEquals(0f, slot.card.translationX, 0f) + + sendTouch(slot, MotionEvent.ACTION_UP, 100L, 254f, 20f) + assertEquals(-50f, releaseY, 0.01f) + assertTrue(releaseVelocityY < -300f) + } + private fun toastSlot(): ToastSlot { val context = RuntimeEnvironment.getApplication() return ToastSlot(context, NativeOverlayToastCardView(context)) } - private fun sendTouch(slot: ToastSlot, action: Int, time: Long, xDp: Float) { + private fun sendTouch(slot: ToastSlot, action: Int, time: Long, xDp: Float, yDp: Float = 70f) { val density = slot.resources.displayMetrics.density - val event = MotionEvent.obtain(1000L, 1000L + time, action, xDp * density, 70f * density, 0) + val event = MotionEvent.obtain(1000L, 1000L + time, action, xDp * density, yDp * density, 0) val windowToSlot = Matrix().apply { setTranslate(-100f * density, -40f * density) postScale(1f / slot.scaleX, 1f / slot.scaleY) diff --git a/native-views/react-native-native-overlay/docs/SPEC.md b/native-views/react-native-native-overlay/docs/SPEC.md index 3a513f3a2..15785f6bd 100644 --- a/native-views/react-native-native-overlay/docs/SPEC.md +++ b/native-views/react-native-native-overlay/docs/SPEC.md @@ -1473,14 +1473,53 @@ non-interactive exit `190 ms` `cubic-bezier(0.2, 0, 0, 1)`). | Position | Per toast or toaster; default bottom-right. At viewport widths up to `600 px`, every position uses a horizontally centered lane with equal insets of at least `16 px`, enlarged equally to respect horizontal safe areas. The top or bottom anchor still applies. | Always top-centre | | Stack | Newest in front, 3 visible, `10 px` gap, depth scale `1 - 0.05 * i` with back bodies faded. Hover or tap to expand multiple cards. An outside press clears tap expansion. | Newest in front, 3 visible, `10 pt/dp` peek, depth scale `1 - 0.05 * i` with collapsed back heights matched to front card and back bodies faded (`240 ms`). Tap stack to expand; an outside tap passes through and collapses the stack. | | Card | Fills the available lane up to `356 px` at every viewport width, `10 px` padding, `21 px` concentric radius + `1 px` outer ring (`box-shadow`) + layered shadow, corner close button revealed by mouse/pen hover or keyboard focus | Content box from `contentWidth` plus `10 pt/dp` padding. Caps outer width at `596 pt/dp` and fits the available area with at least `16 pt/dp` side insets in standard window sizes. Uses a `21 pt/dp` continuous radius + `1 px` hairline ring (`0.06` light / `0.09` dark), subtle shadow | -| Enter / exit | Unit-mass spring (`460/36`) with `0.96 -> 1` scale + `220 ms` ease-out opacity; swipe exit slides horizontally off-side (`200 ms` `cubic-bezier(0.32, 0.72, 0, 1)`, scale `0.98`, opacity `0`); non-interactive exit (`timeout`, `programmatic`, `close`) dissolves gently (`190 ms` `cubic-bezier(0.2, 0, 0, 1)`: front/expanded drifts `16 px` toward the anchored edge and scales to `0.95`; collapsed back drifts `12 px` and scales to `0.90`) | Unit-mass spring (`460/36`) with `0.96 -> 1` scale + `220 ms` ease-out opacity; swipe exit slides horizontally off-side (`200 ms` `cubic-bezier(0.32, 0.72, 0, 1)`, scale `0.98`, opacity `0`); non-interactive exit (`timeout`, `programmatic`) dissolves gently (`190 ms` `cubic-bezier(0.2, 0, 0, 1)`: front/expanded drifts `-16 pt/dp` and scales to `0.95`; collapsed back drifts `-12 pt/dp` and scales to `0.90`) | +| Enter / exit | Unit-mass spring (`460/36`) with `0.96 -> 1` scale + `220 ms` ease-out opacity; horizontal swipe exit slides off-side (`200 ms` `cubic-bezier(0.32, 0.72, 0, 1)`, scale `0.98`, opacity `0`); a touch stack dismissal leaves past the anchored edge with the same curve (see stack gestures); non-interactive exit (`timeout`, `programmatic`, `close`) dissolves gently (`190 ms` `cubic-bezier(0.2, 0, 0, 1)`: front/expanded drifts `16 px` toward the anchored edge and scales to `0.95`; collapsed back drifts `12 px` and scales to `0.90`) | Unit-mass spring (`460/36`) with `0.96 -> 1` scale + `220 ms` ease-out opacity; horizontal swipe exit slides off-side (`200 ms` `cubic-bezier(0.32, 0.72, 0, 1)`, scale `0.98`, opacity `0`); a stack dismissal leaves past the top edge with the same curve (see stack gestures); non-interactive exit (`timeout`, `programmatic`) dissolves gently (`190 ms` `cubic-bezier(0.2, 0, 0, 1)`: front/expanded drifts `-16 pt/dp` and scales to `0.95`; collapsed back drifts `-12 pt/dp` and scales to `0.90`) | | Message status entrance & settle | Tile at `110 ms` (`620/50` spring), glyph pop at `155 ms` (`920/40` spring), `180 ms` stroke draw at `210 ms` (~`390 ms` total); settle crossfades text/actions over `160 ms` `cubic-bezier(0.2, 0, 0, 1)` (`translateY 3 -> 0`) | Same spring parameters, stroke draw, tile bump/tint, and `160 ms` content crossfade (`CASpringAnimation` on iOS, analytical spring step response on Android) | | `close` reported | `200 ms` after the exit starts, or immediately with reduced motion | `220 ms` after the exit starts, or immediately with reduced motion | | Timer pause | While the stack is hovered, expanded, or has an active press. When the pause ends, timers restart with the full lifetime. | While a card is pressed or the stack is expanded; resuming continues the remaining time | -| Swipe | Horizontal (left or right) across all viewports (desktop and small screen). Once a horizontal swipe starts (`|dx| > |dy|`), only horizontal displacement counts and opacity attenuates down to `0.35`. Release dismisses at `64 px`, or `20 px` at `0.5 px/ms`, exiting to the dragged side while remaining cards promote vertically on the card spring. | Horizontal (left or right) on front card (collapsed) or any visible card (expanded); `64 pt/dp`, or `20 pt/dp` at `500 pt/dp/s`; card follows 1:1 on X with opacity attenuating down to `0.35`; exits to the dragged side (`200 ms`) while remaining cards promote vertically on the card spring; settle-back uses the card spring | +| Swipe | Mouse and pen: horizontal (left or right) across all viewports. Once a horizontal swipe starts (`|dx| > |dy|`), only horizontal displacement counts and opacity attenuates down to `0.35`. Release dismisses at `64 px`, or `20 px` at `0.5 px/ms`, exiting to the dragged side while remaining cards promote vertically on the card spring. Touch: the stack gestures below, with the anchored edge of the card's lane (top or bottom) as the dismiss direction. | The stack gestures below, with the top edge as the dismiss direction. Horizontal: front card (collapsed) or any visible card (expanded); `64 pt/dp`, or `20 pt/dp` at `500 pt/dp/s`; card follows 1:1 on X with opacity attenuating down to `0.35`; exits to the dragged side (`200 ms`) while remaining cards promote vertically on the card spring; settle-back uses the card spring | | Top obstruction | Top groups animate the inset in 220 ms | Cards translate within the full-window touch stage, 220 ms | | Reduced motion | Transitions off (media query) | Every animation is instant | +#### Stack gestures (Implemented; iOS runtime verified; Android and Web touch device runs pending) + +A banner moves off toward the edge it is anchored to, and a list item moves +off sideways. A collapsed stack, including a single toast, is handled as one +banner. An expanded stack is a list. The direction therefore follows the +expanded state, which the user changes, and never the number of toasts, +which changes on its own. These gestures apply to iOS, Android and touch input +on Web. Web mouse and pen input keeps the horizontal swipe only, since hovering +expands a stack before it can be dragged. + +The axis locks once the drag passes the start threshold, by the larger of +`|dx|` and `|dy|`. The direction toward the anchored edge is the "dismiss +direction" (up for a top anchor, down for a bottom anchor). + +| Stack state | Toward the anchored edge | Away from the anchored edge | Horizontal | +| --- | --- | --- | --- | +| Collapsed, one or more toasts | Every active card in the stack follows 1:1. Release dismisses all of them at `64`, or `20` at `500 /s` moving toward the edge. | Rubber band (`1 - 1/(d·0.55/dim + 1)`, `dim 70`), back cards spreading `35%` more per depth (up to two). Release at `40`, or at `500 /s` away from the edge, expands a stack of two or more cards. A single toast settles back. | Front card only, as before | +| Expanded | Every visible card follows at half the drag distance. Release at `50`, or at `500 /s`, collapses the stack. | Rubber band (`dim 30`), settles back | The dragged card, as before | + +- A stack dismissal reports `dismiss('swipe')`, then `close('swipe')`, for + every card that was active when the drag began, newest first. Cards shown + during the drag are not part of it. +- Each dismissed card keeps its depth scale and, for collapsed back cards, + its faded body, and moves past the anchored edge using the swipe exit curve + (`200 ms` `cubic-bezier(0.32, 0.72, 0, 1)`, opacity to `0`). The group + leaves together, so no card moves into the front slot during the exit. +- Movement against the locked direction is damped with the same rubber band + (`dim 30`) and never dismisses. +- While a card is being dragged, toasts shown for the first time wait. They + enter once the drag ends, after any dismissal it caused, so a new card + never takes the dragged card's slot mid-gesture. Updates, redraws and + dismissals of cards already on screen still apply at once. A deferred + toast hidden before the drag ends reports `close('programmatic')` without + being drawn. +- Lifetimes stay paused during the drag because the card is pressed. +- Only cards that accept swipes start a drag: the front card of a collapsed + stack and every visible card of an expanded stack. A touch on a collapsed + back card still only expands the stack. + In a browser viewport that reports two segments along an axis, a left or right anchor chooses the matching side and a centered anchor chooses the leading segment in the document's current computed text direction. Top and bottom @@ -1565,6 +1604,18 @@ Divergences from the renderers replaced: ### Verification +- Stack gestures (2026-11-26): built into app-monorepo and run on an iPhone + 17 Pro simulator (iOS 26.0) with injected swipes and toasts shown through + `$Toast` over Metro's inspector. Verified: a single toast dismissed by an + upward swipe; pulling a collapsed stack of three down expanded it; a + horizontal swipe on the expanded middle card closed only that card; pushing + the expanded stack up collapsed it without closing any card; a slow 30 pt + push settled back; an upward swipe on a collapsed stack closed every card + together; a toast shown 0.8 s into that swipe entered after release and + stayed. Web touch cases are covered by `overlayToast.web.test.ts`; Android + axis locking by `NativeOverlayToastCardLayoutTest`. Not exercised yet: an + Android device or emulator, a touch browser, VoiceOver/TalkBack, reduced + motion, iPad and the top obstruction shift. - The shared toast geometry was checked with the same specs in Chromium, in a UIKit harness on iPhone 16 (iOS 26.0), and through the Fabric toaster host on Pixel 7 (Android API 35). The cases cover light and dark card diff --git a/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift b/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift index f2846d0a5..8dbc7eb4d 100644 --- a/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift +++ b/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift @@ -28,6 +28,14 @@ private enum ToasterMetrics { static let swipeFlickVelocity: CGFloat = 500 static let swipeOpacityRange: CGFloat = 260 static let swipeMinOpacity: CGFloat = 0.35 + /// Pull away from the top edge that expands a collapsed stack. + static let expandPullDistance: CGFloat = 40 + /// Push toward the top edge that collapses an expanded stack. + static let collapsePushDistance: CGFloat = 50 + static let rubberDimension: CGFloat = 30 + static let expandRubberDimension: CGFloat = 70 + /// Extra pull per depth while expanding, so back cards fan out under the finger. + static let expandSpreadStep: CGFloat = 0.35 static let fallbackMargin: CGFloat = 64 static let fallbackMaxPageWidth: CGFloat = 640 static let minSideInset: CGFloat = 16 @@ -61,6 +69,12 @@ private func toastAutoExitAnimator() -> UIViewPropertyAnimator { ) } +/// Damped displacement past a limit, as UIScrollView's edge bounce. +private func rubberBand(_ offset: CGFloat, dimension: CGFloat) -> CGFloat { + let magnitude = dimension * (1 - 1 / (abs(offset) * 0.55 / dimension + 1)) + return offset < 0 ? -magnitude : magnitude +} + /// Lets touches that miss every card fall through to the windows below. private final class ToastPassthroughView: UIView { var onOutsideTouch: (() -> Void)? @@ -114,7 +128,12 @@ private final class ToastEntry { var pan: UIPanGestureRecognizer? var dragStart: CGFloat = 0 var swipeExitSign: CGFloat = 1 + /// Left with its stack past the top edge rather than off to a side. + var swipeExitUp = false + /// The body was faded behind the front card when the dismissal began. + var exitBodyHidden = false var lastTargetY: CGFloat? + var lastTargetScale: CGFloat = 1 var dragged = false var isPressed = false var entered = false @@ -128,6 +147,25 @@ private final class ToastEntry { } } +private enum ToastDragMode { + /// One card, sideways. + case horizontal + /// The collapsed stack toward the top edge, dismissing it. + case stack + /// The collapsed stack away from the top edge, expanding it. + case expand + /// The expanded stack toward the top edge, collapsing it. + case collapse + /// Nothing to do in that direction: damped, then settles. + case rubber +} + +private struct ToastDrag { + let mode: ToastDragMode + let owner: ToastEntry + let participants: [ToastEntry] +} + /// Draws the message toasts in the `toast` overlay level: stacking, timers, /// swipe and motion all live here, on the main thread. final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIGestureRecognizerDelegate { @@ -142,6 +180,9 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG private var config = NativeOverlayToasterConfig() private var expanded = false private var obstructionShift: CGFloat = 0 + private var drag: ToastDrag? + /// Toasts first shown during a drag, oldest first; they enter when it ends. + private var deferredAdds: [NativeOverlayToastItem] = [] private var activeEntries: [ToastEntry] { entries.filter { !$0.leaving } @@ -192,6 +233,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG || next.cardColor != config.cardColor || next.cardBorderColor != config.cardBorderColor config = next let present = Set(items.map(\.spec.id)) + deferredAdds.removeAll { !present.contains($0.spec.id) } // Cards the list no longer knows leave without ceremony. for entry in entries where !present.contains(entry.id) { remove(entry, report: false) @@ -205,9 +247,12 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG entry = nil } guard let entry else { - if item.visible { + if item.visible && drag != nil { + deferAdd(item) + } else if item.visible { add(item) } else { + deferredAdds.removeAll { $0.spec.id == item.spec.id } onEvent?(item.spec.id, item.generation, "close", "programmatic") } continue @@ -252,10 +297,32 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG entry.slot.removeFromSuperview() } entries = [] + deferredAdds = [] + drag = nil expanded = false releaseWindow() } + private func deferAdd(_ item: NativeOverlayToastItem) { + if let index = deferredAdds.firstIndex(where: { $0.spec.id == item.spec.id }) { + deferredAdds[index] = item + } else { + deferredAdds.append(item) + } + } + + /// Draws the toasts that arrived while a card was being dragged. + private func flushDeferredAdds() { + guard drag == nil, !deferredAdds.isEmpty else { return } + let pending = deferredAdds + deferredAdds = [] + for item in pending where !entries.contains(where: { $0.id == item.spec.id }) { + add(item) + } + layout(animated: true) + syncTimers() + } + private func lifetime(of spec: NativeOverlayToastSpec) -> TimeInterval? { spec.duration >= 0 ? spec.duration / 1000 : nil } @@ -350,29 +417,42 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG } private func dismiss(_ entry: ToastEntry, reason: String, report: Bool) { - guard !entry.leaving else { return } - entry.collapsedBackExit = !expanded && entry.lastActiveIndex > 0 && reason != "swipe" - entry.leaving = true - entry.card.cancelStatusMotion() - entry.reason = reason - entry.timer?.invalidate() - entry.timer = nil - if report { - onEvent?(entry.id, entry.item.generation, "dismiss", reason) + dismiss([entry], reason: reason, report: report) + } + + /// Starts every exit before laying out once, so a group leaves together + /// and no survivor is promoted between two of its cards. + private func dismiss(_ group: [ToastEntry], reason: String, report: Bool) { + let leaving = group.filter { !$0.leaving } + guard !leaving.isEmpty else { return } + for entry in leaving { + abandonDrag(entry) + entry.collapsedBackExit = !expanded && entry.lastActiveIndex > 0 && reason != "swipe" + entry.exitBodyHidden = !expanded && entry.lastActiveIndex > 0 + entry.leaving = true + entry.card.cancelStatusMotion() + entry.reason = reason + entry.timer?.invalidate() + entry.timer = nil + if report { + onEvent?(entry.id, entry.item.generation, "dismiss", reason) + } } if reduceMotion { - remove(entry, report: true) + leaving.forEach { remove($0, report: true) } layout(animated: false) syncTimers() return } - entry.removal = Timer.scheduledTimer( - withTimeInterval: ToasterMetrics.removeDelay, repeats: false - ) { [weak self, weak entry] _ in - guard let self, let entry else { return } - self.remove(entry, report: true) - self.layout(animated: true) - self.syncTimers() + for entry in leaving { + entry.removal = Timer.scheduledTimer( + withTimeInterval: ToasterMetrics.removeDelay, repeats: false + ) { [weak self, weak entry] _ in + guard let self, let entry else { return } + self.remove(entry, report: true) + self.layout(animated: true) + self.syncTimers() + } } if activeEntries.count <= 1 { expanded = false @@ -382,6 +462,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG } private func remove(_ entry: ToastEntry, report: Bool) { + abandonDrag(entry) entry.timer?.invalidate() entry.removal?.invalidate() entry.card.cancelStatusMotion() @@ -485,7 +566,16 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG displayHeight = entry.card.bounds.height > 0 ? entry.card.bounds.height : naturalSize.height let collapsedBackExit = entry.collapsedBackExit let baseY = entry.lastTargetY ?? top - if swipeExit { + if swipeExit && entry.swipeExitUp { + // Leaves with its stack: depth scale kept, travel measured in the + // slot's scaled space so every card clears the top edge. + targetY = baseY + targetScale = entry.lastTargetScale + let travel = baseY + obstructionShift + displayHeight + ToasterMetrics.swipeExitMargin + targetCardTransform = CGAffineTransform( + translationX: 0, y: -travel / max(targetScale, 0.01) + ) + } else if swipeExit { targetY = baseY targetScale = ToasterMetrics.swipeExitScale let exitDistance = max( @@ -503,7 +593,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG targetScale = ToasterMetrics.autoExitScale } targetAlpha = 0 - hideBody = collapsedBackExit + hideBody = collapsedBackExit || (swipeExit && entry.swipeExitUp && entry.exitBodyHidden) interactive = false } else { let index = activeIndex @@ -522,6 +612,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG hideBody = false } entry.lastTargetY = targetY + entry.lastTargetScale = targetScale if isVisible { expandedOffset += naturalSize.height + ToasterMetrics.gutter } @@ -636,11 +727,8 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG // MARK: Gestures func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { - if let pan = gestureRecognizer as? UIPanGestureRecognizer { - let velocity = pan.velocity(in: stage) - return abs(velocity.x) > abs(velocity.y) - } - return true + // Both axes start a drag; `handlePan` picks the mode when it begins. + true } func gestureRecognizer( @@ -691,43 +779,158 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG } @objc private func handlePan(_ gesture: UIPanGestureRecognizer) { - guard let entry = entry(for: gesture), !entry.leaving else { return } - let active = activeEntries - if !expanded && active.count > 1 && entry !== active.first { return } - let card = entry.card + guard let entry = entry(for: gesture) else { return } let translation = gesture.translation(in: stage) + let velocity = gesture.velocity(in: stage) switch gesture.state { case .began: - card.layer.removeAllAnimations() - entry.dragStart = card.transform.tx - entry.dragged = true + beginDrag(entry, translation: translation, velocity: velocity) case .changed: - let dragX = entry.dragStart + translation.x + guard let drag, drag.owner === entry else { return } + applyDrag(drag, translation: translation) + case .ended: + guard let drag, drag.owner === entry else { return } + self.drag = nil + finishDrag(drag, translation: translation, velocity: velocity) + DispatchQueue.main.async { entry.dragged = false } + flushDeferredAdds() + case .cancelled, .failed: + guard let drag, drag.owner === entry else { return } + self.drag = nil + drag.participants.filter { !$0.leaving }.forEach { settle($0.card) } + entry.dragged = false + flushDeferredAdds() + default: + break + } + } + + private func beginDrag(_ entry: ToastEntry, translation: CGPoint, velocity: CGPoint) { + guard !entry.leaving, drag == nil else { return } + let active = activeEntries + if !expanded && active.count > 1 && entry !== active.first { return } + let horizontal = translation == .zero + ? abs(velocity.x) > abs(velocity.y) + : abs(translation.x) > abs(translation.y) + let towardTop = (translation.y != 0 ? translation.y : velocity.y) < 0 + let mode: ToastDragMode + let participants: [ToastEntry] + if horizontal { + mode = .horizontal + participants = [entry] + } else if towardTop { + mode = expanded ? .collapse : .stack + participants = active + } else if !expanded && active.count > 1 { + mode = .expand + participants = active + } else { + mode = .rubber + participants = [entry] + } + participants.forEach { $0.card.layer.removeAllAnimations() } + entry.dragStart = mode == .horizontal ? entry.card.transform.tx : 0 + entry.dragged = true + let next = ToastDrag(mode: mode, owner: entry, participants: participants) + drag = next + applyDrag(next, translation: translation) + } + + private func applyDrag(_ drag: ToastDrag, translation: CGPoint) { + let dy = translation.y + switch drag.mode { + case .horizontal: + let card = drag.owner.card + let dragX = drag.owner.dragStart + translation.x card.transform = CGAffineTransform(translationX: dragX, y: 0) card.alpha = max( ToasterMetrics.swipeMinOpacity, 1 - abs(dragX) / ToasterMetrics.swipeOpacityRange ) - case .ended: + case .stack: + let offset = dy < 0 ? dy : rubberBand(dy, dimension: ToasterMetrics.rubberDimension) + drag.participants.forEach { setDragOffset($0, offset) } + case .expand: + let offset = dy > 0 + ? rubberBand(dy, dimension: ToasterMetrics.expandRubberDimension) + : rubberBand(dy, dimension: ToasterMetrics.rubberDimension) + for (index, participant) in drag.participants.enumerated() { + let spread = 1 + CGFloat(min(index, 2)) * ToasterMetrics.expandSpreadStep + setDragOffset(participant, offset * spread) + } + case .collapse: + let offset = dy < 0 ? dy * 0.5 : rubberBand(dy, dimension: ToasterMetrics.rubberDimension) + drag.participants.forEach { setDragOffset($0, offset) } + case .rubber: + setDragOffset(drag.owner, rubberBand(dy, dimension: ToasterMetrics.rubberDimension)) + } + } + + /// Offsets a card inside its slot; the slot carries the depth scale. + private func setDragOffset(_ entry: ToastEntry, _ offset: CGFloat) { + guard !entry.leaving else { return } + entry.card.transform = CGAffineTransform( + translationX: 0, y: offset / max(entry.lastTargetScale, 0.01) + ) + } + + /// Ends a drag whose owner left or went away before its gesture finished, + /// settling the other cards it moved and letting deferred toasts in. + private func abandonDrag(_ owner: ToastEntry) { + guard let current = drag, current.owner === owner else { return } + drag = nil + current.participants.filter { $0 !== owner && !$0.leaving }.forEach { settle($0.card) } + DispatchQueue.main.async { [weak self] in self?.flushDeferredAdds() } + } + + private func passesSwipe(distance: CGFloat, speed: CGFloat) -> Bool { + distance >= ToasterMetrics.swipeDistance + || (distance >= ToasterMetrics.swipeFlickDistance + && speed >= ToasterMetrics.swipeFlickVelocity) + } + + private func finishDrag(_ drag: ToastDrag, translation: CGPoint, velocity: CGPoint) { + let remaining = drag.participants.filter { !$0.leaving } + switch drag.mode { + case .horizontal: + let entry = drag.owner + guard !entry.leaving else { return } let totalX = entry.dragStart + translation.x - let distance = abs(totalX) - let velocity = gesture.velocity(in: stage).x * (totalX >= 0 ? 1 : -1) - let dismissed = - distance >= ToasterMetrics.swipeDistance - || (distance >= ToasterMetrics.swipeFlickDistance - && velocity >= ToasterMetrics.swipeFlickVelocity) - if dismissed { + let speed = velocity.x * (totalX >= 0 ? 1 : -1) + if passesSwipe(distance: abs(totalX), speed: speed) { entry.swipeExitSign = totalX >= 0 ? 1 : -1 + entry.swipeExitUp = false dismiss(entry, reason: "swipe", report: true) } else { - settle(card) + settle(entry.card) } - DispatchQueue.main.async { entry.dragged = false } - case .cancelled, .failed: - settle(card) - entry.dragged = false - default: - break + case .stack: + if passesSwipe(distance: -translation.y, speed: -velocity.y) { + remaining.forEach { $0.swipeExitUp = true } + dismiss(remaining, reason: "swipe", report: true) + } else { + remaining.forEach { settle($0.card) } + } + case .expand: + remaining.forEach { settle($0.card) } + let pulled = translation.y >= ToasterMetrics.expandPullDistance + || velocity.y >= ToasterMetrics.swipeFlickVelocity + if pulled && !expanded && activeEntries.count > 1 { + expanded = true + layout(animated: true) + syncTimers() + } + case .collapse: + remaining.forEach { settle($0.card) } + let pushed = -translation.y >= ToasterMetrics.collapsePushDistance + || -velocity.y >= ToasterMetrics.swipeFlickVelocity + if pushed && expanded { + expanded = false + layout(animated: true) + syncTimers() + } + case .rubber: + remaining.forEach { settle($0.card) } } } diff --git a/native-views/react-native-native-overlay/src/__tests__/overlayToast.web.test.ts b/native-views/react-native-native-overlay/src/__tests__/overlayToast.web.test.ts index 3c7a9f628..ab632c6fd 100644 --- a/native-views/react-native-native-overlay/src/__tests__/overlayToast.web.test.ts +++ b/native-views/react-native-native-overlay/src/__tests__/overlayToast.web.test.ts @@ -603,7 +603,7 @@ test('dragging out of a toast and releasing clears hover after resetting data-sw expect(onClose).toHaveBeenCalledWith('timeout'); }); -test('horizontal swipe dismisses left or right on wide and narrow positions while vertical drags do not', () => { +test('horizontal swipe dismisses left or right on wide and narrow positions while mouse vertical drags do not', () => { const onWideClose = jest.fn(); store.configure({ position: 'bottom-right' }); store.show(message('wide', { duration: 5000 }), { onClose: onWideClose }); @@ -658,25 +658,32 @@ test('horizontal swipe dismisses left or right on wide and narrow positions whil }); expect(narrowFront.getAttribute('data-expanded')).toBe('false'); - // Vertical upward drag on top-center does not move or dismiss. + // A short touch push toward the top edge moves the stack, then settles back. dispatchPointer(narrowFront, 'pointerdown', { pointerType: 'touch', clientX: 180, clientY: 90, + timeStamp: 0, }); dispatchPointer(narrowFront, 'pointermove', { pointerType: 'touch', clientX: 180, - clientY: 20, + clientY: 78, + timeStamp: 100, }); expect(narrowFront.style.getPropertyValue('--swipe-amount')).toBe('0px'); + expect(narrowFront.getAttribute('data-stack-drag')).toBe('true'); + expect(narrowFront.style.getPropertyValue('--drag-y')).toBe('-12px'); dispatchPointer(narrowFront, 'pointerup', { pointerType: 'touch', clientX: 180, - clientY: 20, + clientY: 78, + timeStamp: 200, }); expect(narrowFront.getAttribute('data-removed')).toBe('false'); expect(narrowFront.getAttribute('data-expanded')).toBe('false'); + expect(narrowFront.hasAttribute('data-stack-drag')).toBe(false); + expect(narrowFront.style.getPropertyValue('--drag-y')).toBe(''); // Horizontal swipe left dismisses to the left. dispatchPointer(narrowFront, 'pointerdown', { @@ -702,6 +709,147 @@ test('horizontal swipe dismisses left or right on wide and narrow positions whil expect(onNarrowClose).toHaveBeenCalledWith('swipe'); }); +function dispatchTouch( + target: EventTarget, + type: string, + clientY: number, + timeStamp: number +) { + dispatchPointer(target, type, { + pointerType: 'touch', + clientX: 180, + clientY, + timeStamp, + }); +} + +test('touch stack gestures follow the expanded state, not the toast count', () => { + const closes: Record = {}; + store.configure({ position: 'top-center' }); + ['s-1', 's-2', 's-3'].forEach((id) => + store.show(message(id, { duration: 1000 }), { + onClose: (reason) => { + closes[id] = reason; + }, + }) + ); + const front = cards()[0]!; + const back = cards()[1]!; + + // Mouse keeps the horizontal swipe only. + dispatchPointer(front, 'pointerdown', { clientX: 180, clientY: 90 }); + dispatchPointer(front, 'pointermove', { clientX: 180, clientY: 10 }); + expect(front.hasAttribute('data-stack-drag')).toBe(false); + dispatchPointer(front, 'pointerup', { clientX: 180, clientY: 10 }); + expect(front.getAttribute('data-removed')).toBe('false'); + // The mouse leaves, so hover no longer expands the stack. + dispatchPointer( + document.querySelector('[data-onekey-toast-toaster]')!, + 'pointerleave' + ); + expect(front.getAttribute('data-expanded')).toBe('false'); + + // Pulling a collapsed stack away from the top edge fans it out and expands it. + dispatchTouch(front, 'pointerdown', 60, 1000); + dispatchTouch(front, 'pointermove', 140, 1100); + const frontPull = parseFloat(front.style.getPropertyValue('--drag-y')); + const backPull = parseFloat(back.style.getPropertyValue('--drag-y')); + expect(frontPull).toBeGreaterThan(0); + expect(frontPull).toBeLessThan(80); + expect(backPull).toBeGreaterThan(frontPull); + dispatchTouch(front, 'pointerup', 140, 1300); + expect(front.getAttribute('data-expanded')).toBe('true'); + expect(front.hasAttribute('data-stack-drag')).toBe(false); + + // Pushing an expanded stack toward the top edge collapses it. + dispatchTouch(front, 'pointerdown', 60, 2000); + dispatchTouch(front, 'pointermove', -20, 2100); + expect(front.style.getPropertyValue('--drag-y')).toBe('-40px'); + dispatchTouch(front, 'pointerup', -20, 2300); + expect(front.getAttribute('data-expanded')).toBe('false'); + expect( + cards().every((card) => card.getAttribute('data-removed') === 'false') + ).toBe(true); + + // A toast shown mid-drag waits; the drag dismisses only the cards it began with. + dispatchTouch(front, 'pointerdown', 60, 3000); + dispatchTouch(front, 'pointermove', 40, 3100); + store.show(message('s-4', { duration: 1000 })); + expect(cards()).toHaveLength(3); + dispatchTouch(front, 'pointermove', -30, 3150); + expect(back.style.getPropertyValue('--drag-y')).toBe('-90px'); + dispatchTouch(front, 'pointerup', -30, 3400); + ['s-1', 's-2', 's-3'].forEach((id) => { + const card = cards().find((entry) => + entry.textContent?.includes(`Title ${id}`) + ); + expect(card?.getAttribute('data-removed')).toBe('true'); + expect(card?.getAttribute('data-swipe-axis')).toBe('y'); + expect( + parseFloat(card?.style.getPropertyValue('--stack-exit-y') ?? '0') + ).toBeLessThan(-90); + }); + // Back cards keep their depth and hidden body while they leave. + expect(back.getAttribute('data-front')).toBe('false'); + expect(back.getAttribute('data-expanded')).toBe('false'); + const added = cards().find((entry) => + entry.textContent?.includes('Title s-4') + ); + expect(added?.getAttribute('data-removed')).toBe('false'); + expect( + events + .filter((event) => event.type === 'dismiss') + .map((event) => [event.id, event.type === 'dismiss' && event.reason]) + ).toEqual([ + ['s-3', 'swipe'], + ['s-2', 'swipe'], + ['s-1', 'swipe'], + ]); + jest.advanceTimersByTime(200); + expect(closes).toEqual({ 's-1': 'swipe', 's-2': 'swipe', 's-3': 'swipe' }); +}); + +test('a single touch toast dismisses upward and a pull away from the edge settles back', () => { + const onClose = jest.fn(); + store.configure({ position: 'top-center' }); + store.show(message('only', { duration: 1000 }), { onClose }); + const card = cards()[0]!; + + dispatchTouch(card, 'pointerdown', 60, 0); + dispatchTouch(card, 'pointermove', 120, 100); + expect(parseFloat(card.style.getPropertyValue('--drag-y'))).toBeLessThan(30); + dispatchTouch(card, 'pointerup', 120, 400); + expect(card.getAttribute('data-removed')).toBe('false'); + expect(card.getAttribute('data-expanded')).toBe('false'); + + // A short flick toward the edge is enough. + dispatchTouch(card, 'pointerdown', 60, 1000); + dispatchTouch(card, 'pointermove', 48, 1010); + dispatchTouch(card, 'pointermove', 36, 1020); + dispatchTouch(card, 'pointerup', 36, 1030); + expect(card.getAttribute('data-removed')).toBe('true'); + jest.advanceTimersByTime(200); + expect(onClose).toHaveBeenCalledWith('swipe'); +}); + +test('a bottom lane dismisses its touch stack downward', () => { + store.configure({ position: 'bottom-center' }); + store.show(message('b-1', { duration: 1000 })); + store.show(message('b-2', { duration: 1000 })); + const front = cards()[0]!; + + dispatchTouch(front, 'pointerdown', 500, 0); + dispatchTouch(front, 'pointermove', 580, 100); + expect(front.style.getPropertyValue('--drag-y')).toBe('80px'); + dispatchTouch(front, 'pointerup', 580, 300); + expect( + cards().every((card) => card.getAttribute('data-removed') === 'true') + ).toBe(true); + expect( + parseFloat(front.style.getPropertyValue('--stack-exit-y')) + ).toBeGreaterThan(80); +}); + test('only the last tracked press can resume timers', () => { const onClose = jest.fn(); store.show(message('held', { duration: 1000 }), { onClose }); diff --git a/native-views/react-native-native-overlay/src/toast/toastDomRenderer.web.ts b/native-views/react-native-native-overlay/src/toast/toastDomRenderer.web.ts index a271a2383..81caf95b0 100644 --- a/native-views/react-native-native-overlay/src/toast/toastDomRenderer.web.ts +++ b/native-views/react-native-native-overlay/src/toast/toastDomRenderer.web.ts @@ -26,6 +26,15 @@ const SWIPE_FLICK_VELOCITY = 0.5; // px per ms (500 px/s) const SWIPE_VELOCITY_WINDOW_MS = 80; const SWIPE_OPACITY_RANGE = 260; const SWIPE_MIN_OPACITY = 0.35; +/** Pull away from the anchored edge that expands a collapsed touch stack. */ +const EXPAND_PULL_DISTANCE = 40; +/** Push toward the anchored edge that collapses an expanded touch stack. */ +const COLLAPSE_PUSH_DISTANCE = 50; +const RUBBER_DIMENSION = 30; +const EXPAND_RUBBER_DIMENSION = 70; +/** Extra pull per depth while expanding, so back cards fan out under the finger. */ +const EXPAND_SPREAD_STEP = 0.35; +const SWIPE_EXIT_MARGIN = 48; const TOUCH_START_THRESHOLD = 10; const POINTER_START_THRESHOLD = 2; const TIME_BEFORE_UNMOUNT = TOAST_MOTION.cardExitMs; @@ -70,7 +79,21 @@ interface IToastPress { x: number; y: number; moved: boolean; - samples: { x: number; t: number }[]; + samples: { x: number; y: number; t: number }[]; +} + +type IStackDragMode = 'stack' | 'expand' | 'collapse' | 'rubber'; + +/** A touch drag on the vertical axis, which moves the whole stack. */ +interface IStackDrag { + pointerId: number; + mode: IStackDragMode; + owner: IToastNode; + group: IToastGroup; + /** Newest first. */ + participants: IToastNode[]; + /** -1 when the lane is anchored to the top edge, 1 for the bottom edge. */ + edgeSign: number; } interface IToastGroup { @@ -83,6 +106,13 @@ interface IToastGroup { paneScale: number; } +/** Damped displacement past a limit, as a scroll view's edge bounce. */ +function rubberBand(offset: number, dimension: number): number { + const magnitude = + dimension * (1 - 1 / ((Math.abs(offset) * 0.55) / dimension + 1)); + return offset < 0 ? -magnitude : magnitude; +} + function getDocumentDirection(): 'ltr' | 'rtl' { const root = document.documentElement; const direction = globalThis.getComputedStyle(root).direction; @@ -146,6 +176,9 @@ export function createToastDomRenderer( let section: HTMLElement | null = null; let keyboardExpanded = false; let touchExpandedGroup: IToastGroup | undefined; + let stackDrag: IStackDrag | undefined; + /** Toasts first shown during a drag, oldest first; they mount when it ends. */ + let deferredItems: IOverlayToastItem[] = []; let destroyed = false; let documentDirection = getDocumentDirection(); let itemOrder = new Map(); @@ -379,7 +412,8 @@ export function createToastDomRenderer( function deleteToast( node: IToastNode, reason: IOverlayToastDismissReason, - notify: boolean + notify: boolean, + exitLayout?: IToastNode['exitLayout'] ) { if (node.removed) { return; @@ -394,8 +428,11 @@ export function createToastDomRenderer( if (statusTile) { stopStatusTile(statusTile); } + if (stackDrag?.owner === node) { + abandonStackDrag(); + } if (group) { - node.exitLayout = { + node.exitLayout = exitLayout ?? { index: Math.max( 0, group.heights.findIndex((entry) => entry.id === node.id) @@ -444,6 +481,9 @@ export function createToastDomRenderer( function clearPress(pointerId: number, { node }: IToastPress) { presses.delete(pointerId); + if (stackDrag?.pointerId === pointerId) { + abandonStackDrag(); + } clearSwipe(node, pointerId); } @@ -479,8 +519,13 @@ export function createToastDomRenderer( return isExpanded() || index === 0; } - function recordSwipeSample(press: IToastPress, x: number, now: number) { - press.samples.push({ x, t: now }); + function recordSwipeSample( + press: IToastPress, + x: number, + y: number, + now: number + ) { + press.samples.push({ x, y, t: now }); while ( press.samples.length > 1 && now - press.samples[0]!.t > SWIPE_VELOCITY_WINDOW_MS @@ -489,7 +534,12 @@ export function createToastDomRenderer( } } - function swipeVelocity(press: IToastPress, x: number, now: number): number { + function swipeVelocity( + press: IToastPress, + axis: 'x' | 'y', + value: number, + now: number + ): number { const oldest = press.samples.find( (sample) => now - sample.t <= SWIPE_VELOCITY_WINDOW_MS ); @@ -497,7 +547,204 @@ export function createToastDomRenderer( return 0; } const dt = Math.max(1, now - oldest.t); - return (x - oldest.x) / dt; + return (value - oldest[axis]) / dt; + } + + function isDragging(): boolean { + return ( + stackDrag !== undefined || + [...nodes.values()].some((node) => node.swiping) + ); + } + + function deferItem(item: IOverlayToastItem) { + const index = deferredItems.findIndex( + (entry) => entry.spec.id === item.spec.id + ); + if (index >= 0) { + deferredItems[index] = item; + } else { + deferredItems.push(item); + } + } + + /** Mounts the toasts that arrived while a card was being dragged. */ + function flushDeferredItems() { + if (destroyed || isDragging() || deferredItems.length === 0) { + return; + } + const pending = deferredItems; + deferredItems = []; + pending.forEach((item) => { + if (!nodes.has(item.spec.id)) { + mountNode(createNode(item)); + } + }); + } + + function setStackDragOffset(node: IToastNode, offset: number) { + if (node.removed) { + return; + } + node.li.setAttribute('data-stack-drag', 'true'); + node.li.style.setProperty('--drag-y', `${offset}px`); + } + + function settleStackDrag(node: IToastNode) { + if (node.removed) { + return; + } + node.li.removeAttribute('data-stack-drag'); + node.li.style.removeProperty('--drag-y'); + } + + function beginStackDrag( + node: IToastNode, + pointerId: number, + dy: number + ): IStackDrag | undefined { + const group = groups.get(node.position); + if (!group || stackDrag) { + return undefined; + } + const edgeSign = group.position.startsWith('top') ? -1 : 1; + const active = group.toasts.filter((entry) => !entry.removed); + const expanded = isExpanded(); + let mode: IStackDragMode; + let participants: IToastNode[]; + if (dy * edgeSign > 0) { + mode = expanded ? 'collapse' : 'stack'; + participants = active; + } else if (!expanded && active.length > 1) { + mode = 'expand'; + participants = active; + } else { + mode = 'rubber'; + participants = [node]; + } + node.li.setPointerCapture?.(pointerId); + stackDrag = { pointerId, mode, owner: node, group, participants, edgeSign }; + return stackDrag; + } + + function applyStackDrag(drag: IStackDrag, dy: number) { + const toward = dy * drag.edgeSign > 0; + switch (drag.mode) { + case 'stack': { + const offset = toward ? dy : rubberBand(dy, RUBBER_DIMENSION); + drag.participants.forEach((node) => setStackDragOffset(node, offset)); + break; + } + case 'expand': { + const offset = rubberBand( + dy, + toward ? RUBBER_DIMENSION : EXPAND_RUBBER_DIMENSION + ); + drag.participants.forEach((node, index) => + setStackDragOffset( + node, + offset * (1 + Math.min(index, 2) * EXPAND_SPREAD_STEP) + ) + ); + break; + } + case 'collapse': { + const offset = toward ? dy * 0.5 : rubberBand(dy, RUBBER_DIMENSION); + drag.participants.forEach((node) => setStackDragOffset(node, offset)); + break; + } + default: + setStackDragOffset(drag.owner, rubberBand(dy, RUBBER_DIMENSION)); + } + } + + /** Ends a stack drag whose owner left before the pointer was released. */ + function abandonStackDrag() { + const drag = stackDrag; + if (!drag) { + return; + } + stackDrag = undefined; + drag.participants.forEach(settleStackDrag); + queueMicrotask(flushDeferredItems); + } + + function dismissStack(drag: IStackDrag) { + const { group, edgeSign } = drag; + const leaving = drag.participants.filter((node) => !node.removed); + const expanded = isExpanded(); + // Capture every card's place first so back cards keep their depth while + // the cards in front of them are removed. + const layouts = leaving.map((node) => ({ + node, + layout: { + index: Math.max( + 0, + group.heights.findIndex((entry) => entry.id === node.id) + ), + offset: offsetOf(group, node) * group.paneScale, + expanded, + paneScale: group.paneScale, + }, + })); + leaving.forEach((node) => { + const rect = node.li.getBoundingClientRect(); + const current = + Number.parseFloat(node.li.style.getPropertyValue('--drag-y')) || 0; + const travel = + edgeSign < 0 + ? rect.bottom + SWIPE_EXIT_MARGIN + : globalThis.innerHeight - rect.top + SWIPE_EXIT_MARGIN; + node.li.style.setProperty( + '--stack-exit-y', + `${current + edgeSign * travel}px` + ); + node.li.setAttribute('data-swipe-axis', 'y'); + node.swipeOut = true; + }); + layouts.forEach(({ node, layout }) => + deleteToast(node, 'swipe', true, layout) + ); + } + + function finishStackDrag( + drag: IStackDrag, + dy: number, + velocityY: number, + cancelled: boolean + ) { + const toward = dy * drag.edgeSign; + const towardSpeed = velocityY * drag.edgeSign; + const remaining = drag.participants.filter((node) => !node.removed); + if ( + !cancelled && + drag.mode === 'stack' && + (toward >= SWIPE_DISTANCE || + (toward >= SWIPE_FLICK_DISTANCE && towardSpeed >= SWIPE_FLICK_VELOCITY)) + ) { + dismissStack(drag); + return; + } + remaining.forEach(settleStackDrag); + if (cancelled) { + update(); + return; + } + if ( + drag.mode === 'expand' && + (-toward >= EXPAND_PULL_DISTANCE || + -towardSpeed >= SWIPE_FLICK_VELOCITY) && + remaining.length > 1 + ) { + touchExpandedGroup = drag.group; + } else if ( + drag.mode === 'collapse' && + (toward >= COLLAPSE_PUSH_DISTANCE || towardSpeed >= SWIPE_FLICK_VELOCITY) + ) { + touchExpandedGroup = undefined; + keyboardExpanded = false; + } + update(); } function onGlobalPointerMove(event: PointerEvent) { @@ -517,12 +764,33 @@ export function createToastDomRenderer( if (node.swipePointerId !== event.pointerId) { return; } + const dy = event.clientY - press.y; if (!canSwipeNode(node)) { + if (stackDrag?.pointerId === event.pointerId) { + abandonStackDrag(); + } clearSwipe(node, event.pointerId); return; } - recordSwipeSample(press, event.clientX, event.timeStamp); + recordSwipeSample(press, event.clientX, event.clientY, event.timeStamp); + if (stackDrag?.pointerId === event.pointerId) { + applyStackDrag(stackDrag, dy); + return; + } if (!node.swiping) { + // Touch follows the stack gestures once the vertical axis wins; mouse + // and pen keep the horizontal swipe only. + if ( + event.pointerType === 'touch' && + absDy > threshold && + absDy >= absDx + ) { + const drag = beginStackDrag(node, event.pointerId, dy); + if (drag) { + applyStackDrag(drag, dy); + } + return; + } if (absDx <= threshold || absDx <= absDy) { return; } @@ -550,13 +818,36 @@ export function createToastDomRenderer( Math.abs(event.clientX - press.x), Math.abs(event.clientY - press.y) ) > threshold; + const stack = stackDrag?.pointerId === pointerId ? stackDrag : undefined; + if (stack) { + stackDrag = undefined; + const dy = event.clientY - press.y; + const velocityY = released + ? swipeVelocity(press, 'y', event.clientY, event.timeStamp) + : 0; + clearPress(pointerId, press); + if (released) { + node.suppressNotificationClick = true; + if (node.suppressClickTimer !== undefined) { + clearTimeout(node.suppressClickTimer); + } + node.suppressClickTimer = setTimeout(() => { + node.suppressClickTimer = undefined; + node.suppressNotificationClick = false; + }, 0); + } + finishStackDrag(stack, released ? dy : 0, velocityY, !released); + flushDeferredItems(); + return; + } const rawDx = event.clientX - press.x; const swiped = released && node.swipePointerId === pointerId && node.swiping; const amount = swiped ? rawDx : 0; const absAmount = Math.abs(amount); const velocity = swiped - ? swipeVelocity(press, event.clientX, event.timeStamp) * Math.sign(amount) + ? swipeVelocity(press, 'x', event.clientX, event.timeStamp) * + Math.sign(amount) : 0; const dismissed = swiped && @@ -612,6 +903,7 @@ export function createToastDomRenderer( } else { update(); } + flushDeferredItems(); } function attachPointerHandlers(node: IToastNode) { @@ -667,7 +959,7 @@ export function createToastDomRenderer( x: event.clientX, y: event.clientY, moved: false, - samples: [{ x: event.clientX, t: event.timeStamp }], + samples: [{ x: event.clientX, y: event.clientY, t: event.timeStamp }], }); update(); }); @@ -1178,6 +1470,7 @@ export function createToastDomRenderer( } itemOrder = new Map(items.map((item, index) => [item.spec.id, index])); const present = new Set(items.map((item) => item.spec.id)); + deferredItems = deferredItems.filter((item) => present.has(item.spec.id)); [...nodes.values()].forEach((node) => { if (!present.has(node.id)) { unmount(node, 'programmatic'); @@ -1191,9 +1484,14 @@ export function createToastDomRenderer( node = undefined; } if (!node) { - if (item.visible) { + if (item.visible && isDragging()) { + deferItem(item); + } else if (item.visible) { mountNode(createNode(item)); } else { + deferredItems = deferredItems.filter( + (entry) => entry.spec.id !== item.spec.id + ); onEvent({ id: item.spec.id, generation: item.generation, @@ -1260,6 +1558,8 @@ export function createToastDomRenderer( globalThis.removeEventListener('resize', onResize); globalThis.removeEventListener('blur', onWindowBlur); presses.forEach((press, pointerId) => clearPress(pointerId, press)); + stackDrag = undefined; + deferredItems = []; hoveredGroups.clear(); nodes.forEach((node) => { clearCloseTimer(node); diff --git a/native-views/react-native-native-overlay/src/toast/toastStyles.web.ts b/native-views/react-native-native-overlay/src/toast/toastStyles.web.ts index e0838dea8..51bd25fe1 100644 --- a/native-views/react-native-native-overlay/src/toast/toastStyles.web.ts +++ b/native-views/react-native-native-overlay/src/toast/toastStyles.web.ts @@ -66,7 +66,7 @@ function buildOverlayToastCss(): string { width:100%; inset-inline:0; opacity:0; - transform:var(--y) scale(var(--toast-pane-scale,1)); + transform:translateY(var(--drag-y,0px)) var(--y) scale(var(--toast-pane-scale,1)); touch-action:none; transition:transform var(--okt-card-spring-duration) var(--okt-card-spring-ease),opacity 220ms ease-out,height var(--okt-card-spring-duration) var(--okt-card-spring-ease); box-sizing:border-box; @@ -99,6 +99,13 @@ function buildOverlayToastCss(): string { :where([data-onekey-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)} [data-onekey-toast][data-swiping="true"]{transform:translateX(var(--swipe-amount,0px)) var(--y) scale(var(--toast-pane-scale,1));opacity:var(--swipe-opacity,1);transition:none} [data-onekey-toast][data-swipe-out="true"][data-y-position="bottom"],[data-onekey-toast][data-swipe-out="true"][data-y-position="top"]{animation:onekey-toast-swipe-out ${TOAST_MOTION.cardExitMs}ms ${cardExitEase} forwards} +/* A touch stack drag moves every card of the stack with the finger; a stack dismissal leaves past the anchored edge. */ +[data-onekey-toast][data-stack-drag="true"]{transition:none} +[data-onekey-toast][data-removed="true"][data-swipe-out="true"][data-swipe-axis="y"]{animation:onekey-toast-stack-swipe-out ${TOAST_MOTION.cardExitMs}ms ${cardExitEase} forwards} +@keyframes onekey-toast-stack-swipe-out{ + 0%{transform:translateY(var(--drag-y,0px)) var(--y) scale(var(--toast-pane-scale,1));opacity:1} + to{transform:translateY(var(--stack-exit-y,0px)) var(--y) scale(var(--toast-pane-scale,1));opacity:0} +} @keyframes onekey-toast-swipe-out{ 0%{transform:translateY(calc(var(--lift) * var(--offset))) translateX(var(--swipe-amount,0px)) scale(var(--toast-pane-scale,1));opacity:var(--swipe-opacity,1)} to{transform:translateY(calc(var(--lift) * var(--offset))) translateX(var(--swipe-exit-x)) scale(calc(var(--toast-pane-scale,1) * ${TOAST_MOTION.swipeExitScale}));opacity:0} From 785e871bf52e49e17e7f019d33dbd30163d8c88c Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:13:56 +0800 Subject: [PATCH 2/2] docs(native-overlay): record the Android run of the toast stack gestures Co-Authored-By: Claude Opus 5.5 --- .../react-native-native-overlay/docs/SPEC.md | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/native-views/react-native-native-overlay/docs/SPEC.md b/native-views/react-native-native-overlay/docs/SPEC.md index 15785f6bd..c8c0e4f65 100644 --- a/native-views/react-native-native-overlay/docs/SPEC.md +++ b/native-views/react-native-native-overlay/docs/SPEC.md @@ -1481,7 +1481,7 @@ non-interactive exit `190 ms` `cubic-bezier(0.2, 0, 0, 1)`). | Top obstruction | Top groups animate the inset in 220 ms | Cards translate within the full-window touch stage, 220 ms | | Reduced motion | Transitions off (media query) | Every animation is instant | -#### Stack gestures (Implemented; iOS runtime verified; Android and Web touch device runs pending) +#### Stack gestures (Implemented; iOS and Android runtime verified; Web touch device run pending) A banner moves off toward the edge it is anchored to, and a list item moves off sideways. A collapsed stack, including a single toast, is handled as one @@ -1612,10 +1612,13 @@ Divergences from the renderers replaced: the expanded stack up collapsed it without closing any card; a slow 30 pt push settled back; an upward swipe on a collapsed stack closed every card together; a toast shown 0.8 s into that swipe entered after release and - stayed. Web touch cases are covered by `overlayToast.web.test.ts`; Android - axis locking by `NativeOverlayToastCardLayoutTest`. Not exercised yet: an - Android device or emulator, a touch browser, VoiceOver/TalkBack, reduced - motion, iPad and the top obstruction shift. + stayed. The same seven cases passed in app-monorepo on a Pixel 7 emulator + (Android API 35, 420 dpi) with `adb shell input swipe`; the APK's dex was + checked for the new drag classes first. Web touch cases are covered by + `overlayToast.web.test.ts`; Android axis locking by + `NativeOverlayToastCardLayoutTest`. Not exercised yet: a touch browser, + physical devices, VoiceOver/TalkBack, reduced motion, iPad, tablets and + foldables, and the top obstruction shift. - The shared toast geometry was checked with the same specs in Chromium, in a UIKit harness on iPhone 16 (iOS 26.0), and through the Fabric toaster host on Pixel 7 (Android API 35). The cases cover light and dark card