From 9b1ee5a449a7946697a1fb2c7163ffc5ee164072 Mon Sep 17 00:00:00 2001 From: huhuanming Date: Thu, 26 Nov 2026 17:38:04 +0800 Subject: [PATCH] revert: restore the previous toast UI --- .../android/build.gradle | 2 - .../NativeOverlayToastCardView.kt | 377 +----- .../nativeoverlay/NativeOverlayToastSpec.kt | 58 +- .../nativeoverlay/NativeOverlayToasterView.kt | 653 ++------- .../nativeoverlay/ToastStatusTileView.kt | 289 ---- .../NativeOverlayToastBoundsTest.kt | 63 - .../NativeOverlayToastCardLayoutTest.kt | 110 -- .../react-native-native-overlay/docs/SPEC.md | 130 +- .../ios/NativeOverlayToastCardView.swift | 373 +----- .../ios/NativeOverlayToastSpec.swift | 55 +- .../ios/NativeOverlayToasterView.swift | 441 ++---- .../ios/ToastStatusTileView.swift | 309 ----- .../src/__tests__/overlayToast.web.test.ts | 355 +---- .../react-native-native-overlay/src/index.ts | 3 - .../src/toast/toastBridge.ts | 17 - .../src/toast/toastDomContent.web.ts | 183 +-- .../src/toast/toastDomRenderer.web.ts | 682 ++-------- .../src/toast/toastMotion.ts | 67 - .../src/toast/toastSquircle.ts | 76 -- .../src/toast/toastStatusGlyph.ts | 70 - .../src/toast/toastStatusTile.web.ts | 131 -- .../src/toast/toastStyles.web.ts | 398 +----- .../src/toast/types.ts | 28 +- .../tests/browser/overlayToast.test.cjs | 1178 +---------------- .../tests/ios/WindowManagerTests.swift | 58 +- .../tests/ios/run.sh | 3 - 26 files changed, 565 insertions(+), 5544 deletions(-) delete mode 100644 native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/ToastStatusTileView.kt delete mode 100644 native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastBoundsTest.kt delete mode 100644 native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastCardLayoutTest.kt delete mode 100644 native-views/react-native-native-overlay/ios/ToastStatusTileView.swift delete mode 100644 native-views/react-native-native-overlay/src/toast/toastMotion.ts delete mode 100644 native-views/react-native-native-overlay/src/toast/toastSquircle.ts delete mode 100644 native-views/react-native-native-overlay/src/toast/toastStatusGlyph.ts delete mode 100644 native-views/react-native-native-overlay/src/toast/toastStatusTile.web.ts diff --git a/native-views/react-native-native-overlay/android/build.gradle b/native-views/react-native-native-overlay/android/build.gradle index c23e55f7e..83b562d38 100644 --- a/native-views/react-native-native-overlay/android/build.gradle +++ b/native-views/react-native-native-overlay/android/build.gradle @@ -77,8 +77,6 @@ dependencies { implementation "com.facebook.react:react-android" implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" implementation "com.google.android.material:material:1.14.0-alpha05" - implementation "androidx.window:window:1.5.1" - implementation "androidx.window:window-java:1.5.1" testImplementation "junit:junit:4.13.2" testImplementation "org.robolectric:robolectric:4.17" } diff --git a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt index a50e5583e..ffcd87cb2 100644 --- a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt +++ b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastCardView.kt @@ -1,9 +1,5 @@ package com.onekey.nativeoverlay -import android.animation.Animator -import android.animation.AnimatorListenerAdapter -import android.animation.TimeInterpolator -import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.content.res.AssetManager @@ -13,7 +9,6 @@ import android.graphics.BitmapFactory import android.graphics.Canvas import android.graphics.Color import android.graphics.ColorFilter -import android.graphics.Outline import android.graphics.Paint import android.graphics.PixelFormat import android.graphics.Rect @@ -41,9 +36,7 @@ import android.util.TypedValue import android.view.MotionEvent import android.view.View import android.view.ViewGroup -import android.view.ViewOutlineProvider import android.view.accessibility.AccessibilityNodeInfo -import android.view.animation.PathInterpolator import android.widget.FrameLayout import android.widget.ImageView import android.widget.ProgressBar @@ -64,29 +57,22 @@ import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt -// RareUI-inspired concentric geometry in dp: cardRadius = tileRadius (11) + padding (10). +// The card geometry of the layouts this replaces, in dp. private object ToastMetrics { - const val CARD_PADDING_HORIZONTAL = 10f - const val CARD_PADDING_VERTICAL = 10f - const val CARD_RADIUS = 21f - const val CARD_ELEVATION = 4f - const val MESSAGE_ICON_GAP = 12f - const val MESSAGE_TEXT_GAP = 2f - const val NO_ICON_PADDING_START = 6f - const val TILE_MIN_HEIGHT = 36f - const val INLINE_ACTION_HEIGHT = 36f - const val INLINE_ACTION_RADIUS = 11f - const val INLINE_TEXT_MIN_WIDTH = 96f - const val INLINE_ACTION_MAX_LABEL = 16 - const val INLINE_ACTION_MAX_MESSAGE = 72 - const val NOTIFICATION_GAP = 10f + const val CARD_PADDING_HORIZONTAL = 16f + const val CARD_PADDING_VERTICAL = 12f + const val CARD_RADIUS = 8f + const val CARD_ELEVATION = 7f + const val MESSAGE_ICON_GAP = 8f + /** The status icon sits this far under the top of its box. */ + const val MESSAGE_ICON_PADDING_TOP = 2f + const val MESSAGE_TEXT_GAP = 4f + const val NOTIFICATION_GAP = 8f const val NOTIFICATION_TEXT_GAP = 2f const val ACTIONS_GAP = 8f - const val ACTIONS_PADDING_TOP = 10f + const val ACTIONS_PADDING_TOP = 12f const val ACTIONS_PADDING_END = 2f const val ACTIONS_PADDING_BOTTOM = 2f - const val CONTENT_SWAP_MS = 160L - const val BODY_FADE_MS = 240L } private const val IMAGE_POOL_THREADS = 4 @@ -252,10 +238,7 @@ private object ToastNamedIcon { } @SuppressLint("ViewConstructor") -internal class ToastIconView(context: Context, icon: ToastIcon) : FrameLayout(context) { - var icon = icon - private set - val statusTile = (icon as? ToastIcon.Status)?.let { ToastStatusTileView(context, it) } +internal class ToastIconView(context: Context, val icon: ToastIcon) : FrameLayout(context) { private val owner = Any() private val imageView = ImageView(context) /** The size the named icon was last drawn at; it renders at its frame. */ @@ -272,9 +255,6 @@ internal class ToastIconView(context: Context, icon: ToastIcon) : FrameLayout(co spinner.indeterminateTintList = ColorStateList.valueOf(icon.color) addView(spinner, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } - is ToastIcon.Status -> { - addView(statusTile, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) - } is ToastIcon.Image -> { imageView.scaleType = ImageView.ScaleType.CENTER_CROP if (icon.radius > 0) { @@ -294,16 +274,10 @@ internal class ToastIconView(context: Context, icon: ToastIcon) : FrameLayout(co } } - fun applyStatus(status: ToastIcon.Status, settle: Boolean) { - icon = status - statusTile?.apply(status, settle) - } - override fun onAttachedToWindow() { super.onAttachedToWindow() - val currentIcon = icon - if (currentIcon is ToastIcon.Image && cancelled.get() && imageView.drawable == null) { - load(currentIcon.uri) + if (icon is ToastIcon.Image && cancelled.get() && imageView.drawable == null) { + load(icon.uri) } requestIcon() } @@ -562,7 +536,6 @@ private class ToastActionButton(context: Context, val action: ToastAction) : Vie private val surface = ToastPillDrawable(if (action.borderWidth > 0) 0.8f else 0f) val label = TextView(context) val iconView = action.icon?.let { ToastIconView(context, it) } - var isInline = false /** Child frames in the card's coordinates; the card lays the button out. */ var frame = Rect() var labelFrame = Rect() @@ -601,14 +574,8 @@ private class ToastActionButton(context: Context, val action: ToastAction) : Vie override fun onTouchEvent(event: MotionEvent): Boolean { if (isEnabled) { when (event.actionMasked) { - MotionEvent.ACTION_DOWN -> { - surface.setColor(action.pressedBackgroundColor ?: action.backgroundColor) - animate().scaleX(0.95f).scaleY(0.95f).setDuration(120L).start() - } - MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - surface.setColor(action.backgroundColor) - animate().scaleX(1f).scaleY(1f).setDuration(120L).start() - } + MotionEvent.ACTION_DOWN -> surface.setColor(action.pressedBackgroundColor ?: action.backgroundColor) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> surface.setColor(action.backgroundColor) } } return super.onTouchEvent(event) @@ -619,8 +586,7 @@ private class ToastActionButton(context: Context, val action: ToastAction) : Vie } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { - val radiusDp = if (isInline) ToastMetrics.INLINE_ACTION_RADIUS else action.borderRadius - surface.radius = minOf(radiusDp * resources.displayMetrics.density, (bottom - top) / 2f) + surface.radius = minOf(action.borderRadius * resources.displayMetrics.density, (bottom - top) / 2f) label.layoutAt(labelFrame, frame.left, frame.top) iconView?.layoutAt(iconFrame, frame.left, frame.top) } @@ -634,12 +600,6 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) var onAction: ((String) -> Unit)? = null var onLink: ((String) -> Unit)? = null var onPress: (() -> Unit)? = null - var canExpandStack = false - set(value) { - if (field == value) return - field = value - updateAccessibilityImportance() - } /** Width of the content box in dp; the card adds its padding around it. */ var contentWidth = 0f /** Tallest the content box grows, in dp; zero leaves it unbounded. */ @@ -649,8 +609,6 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) var originY = 0.0 private val surface = GradientDrawable() - private val contentSwapInterpolator = PathInterpolator(0.2f, 0f, 0f, 1f) - private val bodyFadeInterpolator = PathInterpolator(0f, 0f, 0.58f, 1f) private var iconView: ToastIconView? = null private var badge: View? = null private var imageView: ToastIconView? = null @@ -659,148 +617,34 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) private var buttons: List = emptyList() private val frames = HashMap() private var size = Rect() - private var bodyHidden = false - private var displayHeightPx = -1 - private var targetDisplayHeightPx = -1 - private var heightAnimator: ValueAnimator? = null - - val naturalHeightPx: Int get() = size.height() - val currentDisplayHeightPx: Int - get() = when { - displayHeightPx > 0 -> displayHeightPx - size.height() > 0 -> size.height() - else -> measuredHeight - } init { - setWillNotDraw(false) surface.cornerRadius = context.dp(ToastMetrics.CARD_RADIUS).toFloat() + background = surface elevation = context.dp(ToastMetrics.CARD_ELEVATION).toFloat() - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - outlineAmbientShadowColor = Color.argb(46, 0, 0, 0) - outlineSpotShadowColor = Color.argb(56, 0, 0, 0) - } - outlineProvider = object : ViewOutlineProvider() { - override fun getOutline(view: View, outline: Outline) { - val h = if (displayHeightPx > 0) displayHeightPx else view.height - outline.setRoundRect(0, 0, view.width, max(h, 0), context.dp(ToastMetrics.CARD_RADIUS).toFloat()) - } - } - clipToOutline = true clipChildren = true clipToPadding = true } - override fun onDraw(canvas: Canvas) { - val h = if (displayHeightPx > 0) displayHeightPx else height - surface.setBounds(0, 0, width, max(h, 0)) - surface.draw(canvas) - } - - override fun onDetachedFromWindow() { - heightAnimator?.cancel() - heightAnimator = null - super.onDetachedFromWindow() - } - fun cancelLoads() { - heightAnimator?.cancel() - heightAnimator = null iconView?.cancelLoad() imageView?.cancelLoad() buttons.forEach { it.iconView?.cancelLoad() } } - private fun childRestAlpha(view: View): Float = - if (view is ToastActionButton && view.action.disabled) view.action.disabledOpacity else 1f - - fun setBodyHidden(hidden: Boolean, animated: Boolean) { - if (hidden == bodyHidden) return - bodyHidden = hidden - for (index in 0 until childCount) { - val child = getChildAt(index) - val target = if (hidden) 0f else childRestAlpha(child) - if (animated) { - child.animate().alpha(target).setDuration(ToastMetrics.BODY_FADE_MS) - .setInterpolator(bodyFadeInterpolator).start() - } else { - child.animate().cancel() - child.alpha = target - } - } - } - - fun setDisplayHeight(targetPx: Int, animated: Boolean, durationMs: Long, interpolator: TimeInterpolator) { - val clamped = max(targetPx, 0) - val natural = size.height() - if (clamped == 0 || natural == 0) return - val isNatural = clamped == natural - val current = if (displayHeightPx > 0) displayHeightPx else natural - if (!animated || current == clamped) { - heightAnimator?.cancel() - heightAnimator = null - displayHeightPx = if (isNatural) -1 else clamped - targetDisplayHeightPx = if (isNatural) -1 else clamped - if (measuredHeight < clamped || (isNatural && measuredHeight != natural)) { - requestLayout() - } - invalidateOutline() - invalidate() - return - } - if (targetDisplayHeightPx == clamped && heightAnimator?.isRunning == true) return - heightAnimator?.cancel() - targetDisplayHeightPx = clamped - if (measuredHeight < max(current, clamped)) { - requestLayout() - } - var cancelled = false - heightAnimator = ValueAnimator.ofInt(current, clamped).apply { - duration = durationMs - this.interpolator = interpolator - addUpdateListener { anim -> - displayHeightPx = anim.animatedValue as Int - invalidateOutline() - invalidate() - } - addListener(object : AnimatorListenerAdapter() { - override fun onAnimationCancel(animation: Animator) { - cancelled = true - } - - override fun onAnimationEnd(animation: Animator) { - if (!cancelled && isNatural) { - displayHeightPx = -1 - targetDisplayHeightPx = -1 - if (measuredHeight != size.height()) { - requestLayout() - } - invalidateOutline() - invalidate() - } - } - }) - start() - } - } - - fun apply(spec: ToastSpec, cardColor: Int, cardBorderColor: Int? = null, settleStatus: Boolean = false) { - val nextStatus = spec.icon as? ToastIcon.Status - val retained = iconView?.takeIf { - this.spec?.isNotification == false && !spec.isNotification && - nextStatus != null && it.statusTile != null - } + fun apply(spec: ToastSpec, cardColor: Int) { this.spec = spec surface.setColor(cardColor) - surface.setStroke(max(1, context.dp(1f)), cardBorderColor ?: Color.argb(15, 0, 0, 0)) spec.testID?.let { tag = it } isClickable = spec.pressable isFocusable = spec.pressable - updateAccessibilityImportance() - cancelLoads() - for (index in childCount - 1 downTo 0) { - if (getChildAt(index) !== retained) removeViewAt(index) + importantForAccessibility = if (spec.pressable) { + IMPORTANT_FOR_ACCESSIBILITY_YES + } else { + IMPORTANT_FOR_ACCESSIBILITY_AUTO } + cancelLoads() + removeAllViews() val link: (String) -> Unit = { onLink?.invoke(it) } badge = if (spec.isNotification) { View(context).also { view -> @@ -813,12 +657,7 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) } else { null } - iconView = if (retained != null && nextStatus != null) { - retained.applyStatus(nextStatus, settleStatus) - retained - } else { - spec.icon?.let { ToastIconView(context, it).also(::addView) } - } + iconView = spec.icon?.let { ToastIconView(context, it).also(::addView) } imageView = spec.image?.let { ToastIconView(context, it).also(::addView) } titles = spec.title?.let { text -> text.paragraphs.map { makeParagraph(context, text, it, link).also(::addView) } @@ -832,60 +671,18 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) addView(button) } } - if (bodyHidden) { - for (index in 0 until childCount) { - getChildAt(index).alpha = 0f - } - } else if (settleStatus && retained != null) { - val shiftPx = context.dp(3f).toFloat() - val swapped: List = titles + messages + buttons - for (view in swapped) { - view.alpha = 0f - view.translationY = shiftPx - view.animate() - .alpha(childRestAlpha(view)) - .translationY(0f) - .setDuration(ToastMetrics.CONTENT_SWAP_MS) - .setInterpolator(contentSwapInterpolator) - .start() - } - } requestLayout() - invalidate() - } - - fun animateMessageStatusEntrance() { - if (spec?.isNotification == false) iconView?.statusTile?.enter() - } - - fun animateMessageStatusRing() { - if (spec?.isNotification == false) iconView?.statusTile?.startRing() - } - - fun cancelStatusMotion() { - iconView?.statusTile?.cancelMotion() } /** What TalkBack reads when the card appears. */ val announcement: String get() = (titles + messages).map { it.text.toString() }.filter { it.isNotEmpty() }.joinToString(". ") - private fun updateAccessibilityImportance() { - importantForAccessibility = if (canExpandStack || spec?.pressable == true) { - IMPORTANT_FOR_ACCESSIBILITY_YES - } else { - IMPORTANT_FOR_ACCESSIBILITY_AUTO - } - } - override fun onInitializeAccessibilityNodeInfo(info: AccessibilityNodeInfo) { super.onInitializeAccessibilityNodeInfo(info) - if (canExpandStack || spec?.pressable == true) { + if (spec?.pressable == true) { info.isClickable = true - val click = AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK - info.addAction(if (canExpandStack) { - AccessibilityNodeInfo.AccessibilityAction(click.id, "Expand notifications") - } else click) + info.addAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_CLICK) if (info.contentDescription.isNullOrEmpty()) { info.contentDescription = announcement } @@ -893,7 +690,7 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) } override fun performAccessibilityAction(action: Int, arguments: Bundle?): Boolean { - if (action == AccessibilityNodeInfo.ACTION_CLICK && (canExpandStack || spec?.pressable == true)) { + if (action == AccessibilityNodeInfo.ACTION_CLICK && spec?.pressable == true) { onPress?.invoke() return true } @@ -986,20 +783,8 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) return paddingTop + rowHeight + px(paddingBottom) } - private fun shouldUseInlineAction(spec: ToastSpec): Boolean { - if (buttons.size != 1 || spec.actionsAlignLeft) return false - val action = buttons.first().action - if (action.label.length > ToastMetrics.INLINE_ACTION_MAX_LABEL) return false - if (action.marginHorizontal != 0f || action.marginVertical != 0f) return false - val message = spec.message ?: return true - if (message.paragraphs.size > 1) return false - val length = message.paragraphs.sumOf { runs -> runs.sumOf { it.text.length } } - return length <= ToastMetrics.INLINE_ACTION_MAX_MESSAGE - } - /** Lays the content box out from [content]; returns its height in px. */ private fun placeContent(spec: ToastSpec, content: Node, width: Double): Double { - buttons.forEach { it.isInline = false } if (spec.isNotification) { val badgeSize = px(spec.badgeSize) val badgeNode = content.child(0.0, 0.0) @@ -1027,93 +812,30 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) return maxOf(y, badgeSize, imageSize) } val icon = spec.icon - val iconSize = icon?.let { px(it.size) } ?: 0.0 - val columnX = icon?.let { iconSize + px(ToastMetrics.MESSAGE_ICON_GAP) } ?: px(ToastMetrics.NO_ICON_PADDING_START) - val gap = px(ToastMetrics.MESSAGE_TEXT_GAP) - val measureColumn = content.child(columnX, 0.0) - val textBlocks = listOf(titles, messages).filter { it.isNotEmpty() } - fun measureText(columnWidth: Double): Double { - var height = 0.0 - textBlocks.forEachIndexed { index, block -> - if (index > 0) height += gap - for (view in block) { - val node = measureColumn.child(0.0, height, text = true) - height += textHeight(view, node.width(columnWidth, text = true)) - } - } - return height - } - var inlineAction = false - var inlineWidth = 0.0 - var inlineHeight = 0.0 - if (shouldUseInlineAction(spec)) { - val button = buttons.first() - val action = button.action - val (labelWidth, labelHeight) = button.measureLabel() - val actionIconSize = action.icon?.let { px(it.size) } ?: 0.0 - val iconExtent = if (action.icon != null) actionIconSize + px(action.iconGap) else 0.0 - val insetX = px(max(action.paddingHorizontal, 14f) + action.borderWidth) - val insetY = px(action.paddingVertical + action.borderWidth) - inlineWidth = labelWidth + iconExtent + 2 * insetX - val minTextWidth = if (textBlocks.isEmpty()) 0.0 else px(ToastMetrics.INLINE_TEXT_MIN_WIDTH) - val inlineTextWidth = width - columnX - px(ToastMetrics.MESSAGE_ICON_GAP) - inlineWidth - val fittedHeight = max(labelHeight.toDouble(), actionIconSize) + 2 * insetY - val candidateHeight = max(fittedHeight, px(ToastMetrics.INLINE_ACTION_HEIGHT)) - inlineAction = inlineTextWidth >= minTextWidth - if (!inlineAction && contentMaxHeight > 0f && inlineTextWidth > 0.0) { - val heightCap = px(contentMaxHeight) - val lowerButtonBottom = measureText(max(width - columnX, 0.0)) + gap + - px(ToastMetrics.ACTIONS_PADDING_TOP) + fittedHeight - if (lowerButtonBottom > heightCap) { - val inlineTextHeight = measureText(inlineTextWidth) - inlineAction = maxOf(inlineTextHeight, candidateHeight, iconSize, px(ToastMetrics.TILE_MIN_HEIGHT)) <= heightCap - } - } - button.isInline = inlineAction - if (inlineAction) inlineHeight = candidateHeight - } - val trailing = if (inlineAction) inlineWidth + px(ToastMetrics.MESSAGE_ICON_GAP) else 0.0 - val columnWidth = max(width - columnX - trailing, 0.0) - var textHeight = measureText(columnWidth) - var bottomActionsHeight = 0.0 - if (buttons.isNotEmpty() && !inlineAction) { - if (textBlocks.isNotEmpty()) textHeight += gap - bottomActionsHeight = placeActions( - measureColumn.child(0.0, textHeight), columnWidth, ToastMetrics.ACTIONS_PADDING_END, ToastMetrics.ACTIONS_PADDING_BOTTOM, - ) + val columnX = icon?.let { px(it.size) + px(ToastMetrics.MESSAGE_ICON_GAP) } ?: 0.0 + iconView?.let { view -> + val size = px(view.icon.size) + frames[view] = content.child(0.0, px(ToastMetrics.MESSAGE_ICON_PADDING_TOP)).frame(size, size) } - val rowHeight = maxOf(textHeight + bottomActionsHeight, iconSize, inlineHeight, px(ToastMetrics.TILE_MIN_HEIGHT)) - val textTop = if (bottomActionsHeight > 0.0) 0.0 else (rowHeight - textHeight) / 2.0 - val textColumn = content.child(columnX, textTop) + val columnWidth = max(width - columnX, 0.0) + val column = content.child(columnX, 0.0) + val gap = px(ToastMetrics.MESSAGE_TEXT_GAP) var y = 0.0 - var placedBlock = false + var hasBlock = false for (block in listOf(titles, messages)) { if (block.isEmpty()) continue - if (placedBlock) y += gap - placedBlock = true - y += placeParagraphs(block, textColumn.child(0.0, y), columnWidth) - } - iconView?.let { view -> - frames[view] = content.child(0.0, (rowHeight - iconSize) / 2.0).frame(iconSize, iconSize) - } - if (inlineAction) { - val button = buttons.first() - val action = button.action - val node = content.child(width - inlineWidth, (rowHeight - inlineHeight) / 2.0) - button.frame = node.frame(inlineWidth, inlineHeight) - frames[button] = button.frame - val insetX = px(max(action.paddingHorizontal, 14f) + action.borderWidth) - var labelX = insetX - button.iconView?.let { - val actionIconSize = px(action.icon!!.size) - button.iconFrame = node.child(insetX, (inlineHeight - actionIconSize) / 2.0).frame(actionIconSize, actionIconSize) - labelX += actionIconSize + px(action.iconGap) - } - val labelHeight = button.label.measuredHeight.toDouble() - button.labelFrame = node.child(labelX, (inlineHeight - labelHeight) / 2.0, text = true) - .frame(button.label.measuredWidth.toDouble(), labelHeight, text = true) + if (hasBlock) y += gap + hasBlock = true + y += placeParagraphs(block, column.child(0.0, y), columnWidth) + } + if (buttons.isNotEmpty()) { + if (hasBlock) y += gap + y += placeActions( + column.child(0.0, y), columnWidth, ToastMetrics.ACTIONS_PADDING_END, ToastMetrics.ACTIONS_PADDING_BOTTOM, + ) } - return rowHeight + val iconBox = icon?.let { px(it.size + ToastMetrics.MESSAGE_ICON_PADDING_TOP) } ?: 0.0 + return max(y, iconBox) } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { @@ -1131,8 +853,7 @@ internal class NativeOverlayToastCardView(context: Context) : ViewGroup(context) width + 2 * px(ToastMetrics.CARD_PADDING_HORIZONTAL), height + 2 * px(ToastMetrics.CARD_PADDING_VERTICAL), ) - val measuredH = max(size.height(), max(displayHeightPx, targetDisplayHeightPx)) - setMeasuredDimension(size.width(), measuredH) + setMeasuredDimension(size.width(), size.height()) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { diff --git a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt index 3d73d66b5..8fb10b633 100644 --- a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt +++ b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/NativeOverlayToastSpec.kt @@ -170,14 +170,6 @@ internal sealed class ToastIcon { data class Spinner(val color: Int, override val size: Float) : ToastIcon() - data class Status( - val status: String, - val color: Int, - val backgroundColor: Int, - override val size: Float, - val glyph: ToastStatusGlyph, - ) : ToastIcon() - data class Image(val uri: String, override val size: Float, val radius: Float) : ToastIcon() companion object { @@ -190,16 +182,6 @@ internal sealed class ToastIcon { Named(json.optString("name"), ToastColor.rgba(color), color, size) } "spinner" -> Spinner(ToastColor.parse(json.stringOrNull("color")) ?: Color.GRAY, size) - "status" -> { - val glyph = ToastStatusGlyph.parse(json.optJSONObject("glyph")) ?: return null - Status( - json.optString("status"), - ToastColor.parse(json.stringOrNull("color")) ?: Color.WHITE, - ToastColor.parse(json.stringOrNull("backgroundColor")) ?: Color.TRANSPARENT, - size, - glyph, - ) - } "image" -> Image(json.optString("uri"), size, json.float("borderRadius", 0f)) else -> null } @@ -207,41 +189,6 @@ internal sealed class ToastIcon { } } -internal data class ToastStatusGlyph( - val strokeWidth: Float, - val contours: List>>, - val dot: Dot?, - val ring: Ring?, -) { - data class Dot(val x: Float, val y: Float, val radius: Float) - data class Ring(val radius: Float, val trackOpacity: Float, val arcFraction: Float) - - companion object { - fun parse(json: JSONObject?): ToastStatusGlyph? { - json ?: return null - return runCatching { - val contours = json.getJSONArray("contours") - ToastStatusGlyph( - json.float("strokeWidth", 3f), - List(contours.length()) { i -> - val points = contours.getJSONArray(i) - List(points.length()) { j -> - val point = points.getJSONArray(j) - point.getDouble(0).toFloat() to point.getDouble(1).toFloat() - } - }, - json.optJSONArray("dot")?.let { - Dot(it.getDouble(0).toFloat(), it.getDouble(1).toFloat(), it.getDouble(2).toFloat()) - }, - json.optJSONObject("ring")?.let { - Ring(it.float("radius", 8f), it.float("trackOpacity", 0.25f), it.float("arcFraction", 0.25f)) - }, - ) - }.getOrNull() - } - } -} - internal data class ToastAction( val id: String, val label: String, @@ -314,8 +261,7 @@ internal data class ToastSpec( isNotification = json.optString("layout") == "notification", duration = json.optDouble("duration", 5000.0), testID = json.stringOrNull("testID"), - icon = (if (json.optString("layout") == "notification") null - else ToastIcon.parse(json.optJSONObject("statusIcon"))) ?: ToastIcon.parse(json.optJSONObject("icon")), + icon = ToastIcon.parse(json.optJSONObject("icon")), title = ToastText.parse(json.optJSONObject("title")), message = ToastText.parse(json.optJSONObject("message")), actions = json.optJSONArray("actions").mapObjects(ToastAction::parse), @@ -355,7 +301,6 @@ internal data class ToastItem( internal data class ToasterConfig( val cardColor: Int = Color.WHITE, - val cardBorderColor: Int? = null, /** Width of the card's content box in dp; null derives it from the window. */ val contentWidth: Float? = null, val contentMaxHeight: Float? = null, @@ -370,7 +315,6 @@ internal data class ToasterConfig( val dict = runCatching { JSONObject(json) }.getOrNull() ?: return ToasterConfig() return ToasterConfig( cardColor = ToastColor.parse(dict.stringOrNull("cardColor")) ?: Color.WHITE, - cardBorderColor = ToastColor.parse(dict.stringOrNull("cardBorderColor")), contentWidth = if (dict.has("contentWidth")) dict.float("contentWidth", 0f) else null, contentMaxHeight = if (dict.has("contentMaxHeight")) dict.float("contentMaxHeight", 0f) else null, topObstruction = dict.float("topObstruction", 0f), 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..03d1f7165 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 @@ -1,33 +1,21 @@ package com.onekey.nativeoverlay -import android.animation.ObjectAnimator -import android.animation.TimeInterpolator import android.animation.ValueAnimator import android.annotation.SuppressLint import android.app.Activity import android.content.Context -import android.database.ContentObserver -import android.graphics.Matrix -import android.graphics.Rect import android.os.Build import android.os.Handler import android.os.Looper import android.os.SystemClock -import android.provider.Settings import android.view.MotionEvent import android.view.VelocityTracker import android.view.View import android.view.ViewGroup import android.view.animation.PathInterpolator import android.widget.FrameLayout -import androidx.core.content.ContextCompat -import androidx.core.util.Consumer import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat -import androidx.window.java.layout.WindowInfoTrackerCallbackAdapter -import androidx.window.layout.FoldingFeature -import androidx.window.layout.WindowInfoTracker -import androidx.window.layout.WindowLayoutInfo import com.facebook.react.bridge.Arguments import com.facebook.react.bridge.WritableMap import com.facebook.react.uimanager.ThemedReactContext @@ -37,103 +25,35 @@ import kotlin.math.max import kotlin.math.min import kotlin.math.roundToInt -// RareUI-inspired motion and gesture constants, in dp / ms. +// The motion and gesture constants of the toaster this replaces, in dp / ms. private object ToasterMetrics { /** The first toast sits this far under the top inset. */ const val TOP_OFFSET = 16f - const val GUTTER = 10f - const val VISIBLE_TOASTS = 3 - const val STACK_SCALE_STEP = 0.05f - const val SPRING_MS = 407L - const val ENTER_FADE_MS = 220L - const val EXIT_MS = 200L - const val AUTO_EXIT_MS = 190L + const val GUTTER = 8f + const val ANIMATION_MS = 300L const val OBSTRUCTION_MS = 220L - /** Keep leaving cards mounted long enough for the exit transition and close callback. */ - const val REMOVE_DELAY_MS = 220L - const val ENTER_OVERSHOOT = 32f - const val HIDDEN_SCALE = 0.96f - const val SWIPE_EXIT_SCALE = 0.98f - const val SWIPE_EXIT_MARGIN = 48f - const val AUTO_EXIT_OFFSET = 16f - const val AUTO_EXIT_SCALE = 0.95f - const val COLLAPSED_BACK_EXIT_OFFSET = 12f - const val COLLAPSED_LEAVE_SCALE = 0.90f - const val FALLBACK_HEIGHT = 56f + /** A dismissed card is reported closed when the previous renderer unmounted it. */ + const val REMOVE_DELAY_MS = 1000L + const val ENTER_OVERSHOOT = 50f + const val FALLBACK_HEIGHT = 50f const val SWIPE_START = 10f - const val SWIPE_DISTANCE = 64f - const val SWIPE_FLICK_DISTANCE = 20f - const val SWIPE_FLICK_VELOCITY = 500f - const val SWIPE_OPACITY_RANGE = 260f - const val SWIPE_MIN_OPACITY = 0.35f + const val SWIPE_DISTANCE = 32f + const val SWIPE_FLICK_DISTANCE = 12f + const val SWIPE_FLICK_VELOCITY = 600f + /** Dragging against the dismiss direction moves the card a quarter as far. */ + const val SWIPE_RESISTANCE = 4f const val FALLBACK_MARGIN = 64f const val FALLBACK_MAX_PAGE_WIDTH = 640f const val LANE_MAX_WIDTH = 360f const val LANE_MARGIN = 32.0 - const val CARD_PADDING_HORIZONTAL = 10f - const val MIN_SIDE_INSET = 16f + const val CARD_PADDING_HORIZONTAL = 16f } /** Rounds half up, the way the replaced layout placed a node in its parent. */ private fun snapHalfUp(value: Double): Int = kotlin.math.floor(value + 0.5 + 1e-4).toInt() -/** Spring timing shared with Web and iOS: mass 1, stiffness 460, damping 36. */ -private val toastSpringInterpolator = TimeInterpolator { input -> - if (input >= 1f) 1f else toastSpringProgress(460.0, 36.0, input * ToasterMetrics.SPRING_MS) -} - -/** Smooth ease-out fade for card entrance and visibility transitions. */ -private val toastEnterFadeInterpolator = PathInterpolator(0f, 0f, 0.58f, 1f) - -/** Brisk ease-out curve for interactive swipe exit and obstruction shifts. */ -private val toastExitInterpolator = PathInterpolator(0.32f, 0.72f, 0f, 1f) - -/** Gentle ease-out curve for non-interactive timeout / programmatic exit. */ -private val toastAutoExitInterpolator = PathInterpolator(0.2f, 0f, 0f, 1f) - -/** Chooses a region in stage coordinates from separating, window-relative folds. */ -internal fun toastAvailableBounds( - safeBounds: Rect, - features: List, - windowX: Int, - windowY: Int, - isRtl: Boolean, -): Rect { - val region = Rect(safeBounds) - for (feature in features) { - if (!feature.isSeparating) continue - val fold = Rect(feature.bounds).apply { offset(-windowX, -windowY) } - if (feature.orientation == FoldingFeature.Orientation.VERTICAL && - fold.left > region.left && fold.right < region.right && - fold.top < region.bottom && fold.bottom > region.top - ) { - val leftWidth = fold.left - region.left - val rightWidth = region.right - fold.right - if (rightWidth > leftWidth || (rightWidth == leftWidth && isRtl)) { - region.left = fold.right - } else { - region.right = fold.left - } - } else if (feature.orientation == FoldingFeature.Orientation.HORIZONTAL && - fold.top > region.top && fold.bottom < region.bottom && - fold.left < region.right && fold.right > region.left - ) { - region.bottom = fold.top - } - } - return region -} - -internal fun toastContentWidth(availableDp: Float, requestedDp: Float?): Float { - val maxContent = ToasterMetrics.FALLBACK_MAX_PAGE_WIDTH - ToasterMetrics.FALLBACK_MARGIN - val availableContent = availableDp - - 2 * (ToasterMetrics.MIN_SIDE_INSET + ToasterMetrics.CARD_PADDING_HORIZONTAL) - return (requestedDp?.takeIf { it.isFinite() } ?: (availableDp - ToasterMetrics.FALLBACK_MARGIN)) - .coerceIn(0f, min(maxContent, availableContent).coerceAtLeast(0f)) -} - -internal fun toastStackScale(availablePx: Float, stackHeightPx: Int): Float = - if (stackHeightPx > 0) (availablePx / stackHeightPx).coerceIn(0f, 1f) else 1f +/** Quadratic ease-in-out, the timing curve of the animations this replaces. */ +private val toastInterpolator = PathInterpolator(0.455f, 0.03f, 0.515f, 0.955f) internal class NativeOverlayToastEvent( surfaceId: Int, @@ -160,55 +80,18 @@ internal class NativeOverlayToastEvent( } } -/** Full-window toast stage that passes outside touches through while reporting them to collapse an expanded stack. */ -private class ToastStageLayout(context: Context) : FrameLayout(context) { - var onOutsideTouch: (() -> Unit)? = null - val cards = FrameLayout(context).apply { - clipChildren = false - clipToPadding = false - } - - init { - addView(cards, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) - } - - override fun dispatchTouchEvent(ev: MotionEvent): Boolean { - val handled = super.dispatchTouchEvent(ev) - if (!handled && ev.actionMasked == MotionEvent.ACTION_DOWN) { - onOutsideTouch?.invoke() - } - return handled - } -} - -/** Hosts one card: forwards presses and horizontal drags to the presenter. */ +/** Hosts one card: forwards presses and vertical drags to the presenter. */ @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 +private class ToastSlot(context: Context, val card: NativeOverlayToastCardView) : FrameLayout(context) { + var onPressChanged: ((Boolean) -> Unit)? = null + var onDrag: ((Float) -> Unit)? = null + var onRelease: ((translationY: Float, translationX: 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) - } - field = value - } - var expansionOnly = false private var downX = 0f private var downY = 0f - private var windowDragX = 0f - var dragging = false - private set - private var moved = false - private val slop get() = ToasterMetrics.SWIPE_START * resources.displayMetrics.density - var hasActivePress = false - private set + private var dragging = false private var tracker: VelocityTracker? = null - private val slotToWindow = Matrix() init { clipChildren = false @@ -216,56 +99,17 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) addView(card, LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)) } - private fun cancelDrag() { - dragging = false - windowDragX = 0f - tracker?.recycle() - tracker = null - } - - fun clearTouch() { - resetPress() - cancelDrag() - } - - private fun resetPress() { - if (hasActivePress) { - hasActivePress = false - onPressChanged?.invoke() - } - } - override fun dispatchTouchEvent(event: MotionEvent): Boolean { - if (event.actionMasked == MotionEvent.ACTION_DOWN) { - if (!isEnabled || event.x < card.x || event.x >= card.x + card.width || - event.y < card.y || event.y >= card.y + card.currentDisplayHeightPx - ) return false - hasActivePress = true - onPressChanged?.invoke() + when (event.actionMasked) { + MotionEvent.ACTION_DOWN -> onPressChanged?.invoke(true) + MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> onPressChanged?.invoke(false) } - val handled = isEnabled && super.dispatchTouchEvent(event) - if (event.actionMasked == MotionEvent.ACTION_UP || event.actionMasked == MotionEvent.ACTION_CANCEL || - (event.actionMasked == MotionEvent.ACTION_DOWN && !handled) - ) clearTouch() - return handled + return super.dispatchTouchEvent(event) } private fun track(event: MotionEvent) { val current = tracker ?: VelocityTracker.obtain().also { tracker = it } - // Ancestors only translate. Undo the slot's scale and translation for - // the entire batch so a pane resize cannot introduce a jump in velocity. - slotToWindow.setScale(scaleX, scaleY) - slotToWindow.postTranslate(event.rawX - event.x * scaleX, event.rawY - event.y * scaleY) - val windowEvent = MotionEvent.obtain(event) - windowEvent.transform(slotToWindow) - current.addMovement(windowEvent) - windowEvent.recycle() - } - - fun reprojectDrag() { - if (dragging && scaleX > 0f) { - card.translationX = windowDragX / scaleX - } + current.addMovement(event) } override fun onInterceptTouchEvent(event: MotionEvent): Boolean { @@ -273,17 +117,17 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) MotionEvent.ACTION_DOWN -> { downX = event.rawX downY = event.rawY - moved = false - cancelDrag() - if (expansionOnly) return true - if (allowDrag) track(event) + dragging = false + tracker?.recycle() + tracker = null + track(event) } MotionEvent.ACTION_MOVE -> { - if (!allowDrag) return false track(event) val dy = event.rawY - downY val dx = event.rawX - downX - if (!dragging && abs(dx) > slop && abs(dx) > abs(dy)) { + val slop = ToasterMetrics.SWIPE_START * resources.displayMetrics.density + if (!dragging && abs(dy) > slop && abs(dy) > abs(dx)) { dragging = true parent?.requestDisallowInterceptTouchEvent(true) } @@ -294,38 +138,27 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { - if (!isEnabled) return false when (event.actionMasked) { MotionEvent.ACTION_MOVE -> { + track(event) val dy = event.rawY - downY val dx = event.rawX - downX - 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) { - windowDragX = dx - card.animate().cancel() - reprojectDrag() - card.alpha = max( - ToasterMetrics.SWIPE_MIN_OPACITY, - 1f - abs(dx / resources.displayMetrics.density) / ToasterMetrics.SWIPE_OPACITY_RANGE, - ) - } - } + val slop = ToasterMetrics.SWIPE_START * resources.displayMetrics.density + if (!dragging && abs(dy) > slop && abs(dy) > abs(dx)) dragging = true + if (dragging) onDrag?.invoke(dy) } MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> { - if (allowDrag) track(event) + track(event) val cancelled = event.actionMasked == MotionEvent.ACTION_CANCEL if (dragging) { tracker?.computeCurrentVelocity(1000) - onRelease?.invoke(event.rawX - downX, event.rawY - downY, tracker?.xVelocity ?: 0f, cancelled) - } else if (!cancelled && !moved && - abs(event.rawX - downX) <= slop && abs(event.rawY - downY) <= slop - ) { + onRelease?.invoke(event.rawY - downY, event.rawX - downX, tracker?.yVelocity ?: 0f, cancelled) + } else if (!cancelled) { onTap?.invoke() } - cancelDrag() + dragging = false + tracker?.recycle() + tracker = null } } // Claim the gesture so a press on the card's own surface can become a drag. @@ -341,19 +174,13 @@ internal class ToastSlot(context: Context, val card: NativeOverlayToastCardView) private class ToastEntry(val id: String, var item: ToastItem, val slot: ToastSlot) { var leaving = false - var collapsedBackExit = false var reason = "programmatic" /** Milliseconds of lifetime left, counted while not paused. */ var remaining: Long? = null var startedAt = 0L var timer: Runnable? = null var removal: Runnable? = null - var alphaAnimator: ObjectAnimator? = null var entered = false - var lastActiveIndex = 0 - var swipeExitSign = 1f - var lastTargetY = Float.NaN - var lastPaneScale = 1f var dragStart = 0f } @@ -368,22 +195,11 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { private val context: Context get() = hostView.context private val density: Float get() = context.resources.displayMetrics.density /** Rides under whatever hangs from the top of the window. */ - private var stage: ToastStageLayout? = null - private var stopTrackingFolds: (() -> Unit)? = null - private var foldingFeatures: List = emptyList() - private val windowLocation = IntArray(2) + private var stage: FrameLayout? = null private var entries = mutableListOf() // newest first private var config = ToasterConfig() - private var expanded = false + private var pressed = 0 private var obstructionShift = 0f - private val motionObserver = object : ContentObserver(handler) { - override fun onChange(selfChange: Boolean) { - layout(animated = false) - } - } - - private val activeEntries: List - get() = entries.filter { !it.leaving } private val reduceMotion: Boolean get() = config.respectReducedMotion && @@ -398,7 +214,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { // region Sync fun sync(items: List, next: ToasterConfig) { - val configChanged = next.cardColor != config.cardColor || next.cardBorderColor != config.cardBorderColor + val configChanged = next.cardColor != config.cardColor config = next val present = items.map { it.spec.id }.toSet() // Cards the list no longer knows leave without ceremony. @@ -416,12 +232,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { continue } if (entry.item.revision != item.revision || configChanged) { - entry.slot.card.apply( - item.spec, config.cardColor, config.cardBorderColor, - settleStatus = item.visible && entry.entered && !reduceMotion && - entry.item.generation != item.generation && - (item.spec.icon as? ToastIcon.Status)?.status != "loading", - ) + entry.slot.card.apply(item.spec, config.cardColor) } if (entry.item.generation != item.generation) { // Shown again: the toast starts its lifetime over. @@ -436,19 +247,12 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { } fun invalidate() { - val departing = entries.toList() - entries.clear() - departing.forEach { entry -> + entries.forEach { entry -> cancelTimer(entry) entry.removal?.let(handler::removeCallbacks) - entry.alphaAnimator?.cancel() - entry.alphaAnimator = null - entry.slot.onPressChanged = null - entry.slot.clearTouch() - entry.slot.card.cancelStatusMotion() entry.slot.card.cancelLoads() } - expanded = false + entries.clear() releaseStage() } @@ -459,34 +263,21 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { // region Stage - private fun ensureStage(): ToastStageLayout? { + private fun ensureStage(): FrameLayout? { stage?.let { if (it.parent != null) return it } val activity = activity ?: return null - val layer = stage ?: ToastStageLayout(context).apply { + val layer = stage ?: FrameLayout(context).apply { clipChildren = false clipToPadding = false - onOutsideTouch = { - handler.post { - if (expanded) { - expanded = false - layout(animated = true) - syncTimers() - } - } - } addOnLayoutChangeListener { _, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom -> if (right - left != oldRight - oldLeft || bottom - top != oldBottom - oldTop) { // A new window size moves every card; wait for the layout pass to end. handler.post { layout(animated = false) } } } - context.contentResolver.registerContentObserver( - Settings.Global.getUriFor(Settings.Global.ANIMATOR_DURATION_SCALE), false, motionObserver, - ) } stage = layer NativeOverlayHost.of(activity).attachToastLayer(layer) - trackFolds(activity, layer) ViewCompat.setOnApplyWindowInsetsListener(layer) { _, insets -> handler.post { layout(animated = true) } insets @@ -494,35 +285,13 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { return layer } - @Suppress("DEPRECATION") // Window 1.5 provides a callback adapter for this view-owned listener. - private fun trackFolds(activity: Activity, layer: ToastStageLayout) { - stopTrackingFolds?.invoke() - foldingFeatures = emptyList() - val adapter = WindowInfoTrackerCallbackAdapter(WindowInfoTracker.getOrCreate(activity)) - val consumer = Consumer { info -> - if (stage === layer) { - val next = info.displayFeatures.filterIsInstance() - if (next != foldingFeatures) { - foldingFeatures = next - layout(animated = false) - } - } - } - adapter.addWindowLayoutInfoListener(activity, ContextCompat.getMainExecutor(activity), consumer) - stopTrackingFolds = { adapter.removeWindowLayoutInfoListener(consumer) } - } - private fun releaseStage() { val layer = stage ?: return - stage = null - stopTrackingFolds?.invoke() - stopTrackingFolds = null - foldingFeatures = emptyList() - context.contentResolver.unregisterContentObserver(motionObserver) - layer.cards.removeAllViews() + layer.removeAllViews() activity?.let { NativeOverlayHost.of(it).detachToastLayer(layer) } ?: (layer.parent as? ViewGroup)?.removeView(layer) obstructionShift = 0f + layer.translationY = 0f } /** The host joined a window: draw the toasts that were waiting for one. */ @@ -545,32 +314,31 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { entry.remaining = lifetime(item.spec) card.onAction = { actionId -> if (!entry.leaving) onEvent?.invoke(entry.id, entry.item.generation, "action", actionId) } 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 -> + card.apply(item.spec, config.cardColor) + slot.onPressChanged = { down -> + pressed = if (down) pressed + 1 else max(0, pressed - 1) + syncTimers() + } + slot.onDrag = { translation -> if (!entry.leaving) { - val distance = abs(translationX) / density - val velocity = velocityX / density * (if (translationX >= 0f) 1f else -1f) - val dismissed = !cancelled && + // Toasts land at the top, so the dismiss direction is up. + card.translationY = + if (translation <= 0) translation else translation / ToasterMetrics.SWIPE_RESISTANCE + } + } + slot.onRelease = { translationY, translationX, velocityY, cancelled -> + if (!entry.leaving) { + val distance = -translationY / density + val velocity = -velocityY / density + val dismissed = !cancelled && translationY < 0 && abs(translationY) > abs(translationX) && (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) - } + if (dismissed) dismiss(entry, "swipe", report = true) else settle(card) } } val press = { - if (!entry.leaving) { - if (!expanded && activeEntries.size > 1) { - expanded = true - layout(animated = true) - syncTimers() - } else if (entry.item.spec.pressable) { - onEvent?.invoke(entry.id, entry.item.generation, "press", "") - } + if (!entry.leaving && entry.item.spec.pressable) { + onEvent?.invoke(entry.id, entry.item.generation, "press", "") } } card.onPress = press @@ -579,9 +347,9 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { ensureStage()?.let { attach(entry, it) } } - private fun attach(entry: ToastEntry, layer: ToastStageLayout) { + private fun attach(entry: ToastEntry, layer: FrameLayout) { entry.slot.alpha = 0f - layer.cards.addView( + layer.addView( entry.slot, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT), ) @@ -592,66 +360,38 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { private fun settle(card: View) { if (reduceMotion) { - resetDrag(card) + card.translationY = 0f return } - card.animate().translationX(0f).alpha(1f).setDuration(ToasterMetrics.SPRING_MS) - .setInterpolator(toastSpringInterpolator).start() - } - - private fun resetDrag(card: View) { - card.translationX = 0f - card.alpha = 1f + card.animate().translationY(0f).setDuration(ToasterMetrics.ANIMATION_MS) + .setInterpolator(toastInterpolator).start() } private fun dismiss(entry: ToastEntry, reason: String, report: Boolean) { 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) - if (reduceMotion) { - remove(entry, report = true) - layout(animated = false) - syncTimers() - return - } val removal = Runnable { remove(entry, report = true) layout(animated = true) - syncTimers() } entry.removal = removal handler.postDelayed(removal, ToasterMetrics.REMOVE_DELAY_MS) - if (activeEntries.size <= 1) { - expanded = false - } layout(animated = true) - syncTimers() } private fun remove(entry: ToastEntry, report: Boolean) { - entries.remove(entry) cancelTimer(entry) entry.removal?.let(handler::removeCallbacks) - entry.alphaAnimator?.cancel() - entry.alphaAnimator = null - entry.slot.onPressChanged = null - entry.slot.clearTouch() - entry.slot.card.cancelStatusMotion() entry.slot.card.cancelLoads() entry.slot.animate().cancel() (entry.slot.parent as? ViewGroup)?.removeView(entry.slot) - if (activeEntries.size <= 1) { - expanded = false - } + entries.remove(entry) if (report) onEvent?.invoke(entry.id, entry.item.generation, "close", entry.reason) if (entries.isEmpty()) { - expanded = false + pressed = 0 releaseStage() } } @@ -660,9 +400,10 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { // region Layout - private fun computeObstructionShift(topInset: Int, usableBottom: Int): Float { + private fun computeObstructionShift(layer: View, topInset: Int, bottomInset: Int): Float { if (config.topObstruction <= 0f) return 0f val toastTop = topInset + dp(ToasterMetrics.TOP_OFFSET) + val usableBottom = layer.height - bottomInset val top = min( dp(config.topObstruction + config.topObstructionGap), usableBottom - dp(config.topObstructionRoom), @@ -673,58 +414,47 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { private fun layout(animated: Boolean) { val layer = stage ?: return if (entries.isEmpty() || layer.width == 0) return - val cards = layer.cards val insets = ViewCompat.getRootWindowInsets(layer) val bars = insets?.getInsets( WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.displayCutout(), ) val ime = insets?.getInsets(WindowInsetsCompat.Type.ime()) - layer.getLocationInWindow(windowLocation) - val safeBottom = layer.height - (bars?.bottom ?: 0) - val region = toastAvailableBounds( - Rect( - bars?.left ?: 0, - bars?.top ?: 0, - layer.width - (bars?.right ?: 0), - safeBottom, - ), - foldingFeatures, windowLocation[0], windowLocation[1], - layer.layoutDirection == View.LAYOUT_DIRECTION_RTL, - ) - val usableBottom = min(region.bottom, layer.height - (ime?.bottom ?: 0)) + val topInset = bars?.top ?: 0 + // The keyboard's top edge while it is up, the system bar's otherwise. + val bottomInset = max(bars?.bottom ?: 0, ime?.bottom ?: 0) val animate = animated && !reduceMotion - val shift = computeObstructionShift(region.top, usableBottom) + val shift = computeObstructionShift(layer, topInset, bottomInset) if (shift != obstructionShift) { obstructionShift = shift if (animate) { - cards.animate().translationY(shift).setDuration(ToasterMetrics.OBSTRUCTION_MS) - .setInterpolator(toastExitInterpolator).start() + layer.animate().translationY(shift).setDuration(ToasterMetrics.OBSTRUCTION_MS) + .setInterpolator(toastInterpolator).start() } else { - cards.animate().cancel() - cards.translationY = shift + layer.animate().cancel() + layer.translationY = shift } } - val available = region.width().toDouble() - val contentWidth = toastContentWidth(region.width() / density, config.contentWidth) + val contentWidth = config.contentWidth + ?: (min(layer.width / density, ToasterMetrics.FALLBACK_MAX_PAGE_WIDTH) - ToasterMetrics.FALLBACK_MARGIN) val contentMaxHeight = config.contentMaxHeight ?: 0f - val top = region.top + dp(ToasterMetrics.TOP_OFFSET) - // Keep the existing half-up rounding of the lane and card offsets. + val top = topInset + dp(ToasterMetrics.TOP_OFFSET) + val left = bars?.left ?: 0 + val right = bars?.right ?: 0 + // The replaced toaster centred a lane of at most 360dp and centred the + // card in it; both offsets were rounded on their own. + val available = (layer.width - left - right).toDouble() val lane = min(available / density - ToasterMetrics.LANE_MARGIN, ToasterMetrics.LANE_MAX_WIDTH.toDouble()) val laneLeft = (available - lane * density) / 2 val cardOffset = (lane - (contentWidth + 2 * ToasterMetrics.CARD_PADDING_HORIZONTAL)) * density / 2 - val originX = region.left + laneLeft + cardOffset - val drawnX = region.left + snapHalfUp(laneLeft) + snapHalfUp(cardOffset) - val originY = region.top + (ToasterMetrics.TOP_OFFSET * density).toDouble() - val active = activeEntries - if (active.size <= 1) { - expanded = false - } - val isCollapsed = !expanded && active.size > 1 - - // Measure every card's natural size first so collapsed back cards know frontHeight. - for (entry in entries) { + val originX = left + laneLeft + cardOffset + val drawnX = left + snapHalfUp(laneLeft) + snapHalfUp(cardOffset) + val originY = topInset + (ToasterMetrics.TOP_OFFSET * density).toDouble() + // Oldest at the top, newest under it: a toast keeps its place when a newer + // one arrives and moves up when an older one leaves. + var offset = 0 + for (entry in entries.asReversed()) { val slot = entry.slot val card = slot.card if (card.contentWidth != contentWidth || card.contentMaxHeight != contentMaxHeight || @@ -737,180 +467,25 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { card.requestLayout() } slot.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) - } - - val frontHeight = active.firstOrNull()?.slot?.card?.naturalHeightPx?.takeIf { it > 0 } - ?: dp(ToasterMetrics.FALLBACK_HEIGHT) - - // Keep newest card at the highest z-order (last child of FrameLayout). - val ordered = entries.asReversed() - var zMismatch = cards.childCount != ordered.size - if (!zMismatch) { - for (i in ordered.indices) { - if (cards.getChildAt(i) !== ordered[i].slot) { - zMismatch = true - break - } - } - } - if (zMismatch) { - for (entry in ordered) { - entry.slot.bringToFront() - } - } - - val gutterPx = dp(ToasterMetrics.GUTTER) - val paneScale = if (region.bottom < safeBottom) { - val visible = active.take(ToasterMetrics.VISIBLE_TOASTS) - val height = if (isCollapsed) frontHeight else visible.sumOf { entry -> - entry.slot.card.naturalHeightPx.takeIf { it > 0 } ?: entry.slot.measuredHeight - } - val stackHeight = height + max(0, visible.size - 1) * gutterPx - toastStackScale(usableBottom - top - shift - gutterPx, stackHeight) - } else 1f - var activeIndex = 0 - var expandedOffset = 0 - for (entry in entries) { - val slot = entry.slot - val card = slot.card - val naturalHeight = card.naturalHeightPx.takeIf { it > 0 } ?: slot.measuredHeight - val displayHeight: Int - val targetY: Float - val targetScale: Float - val targetAlpha: Float - val hideBody: Boolean - val interactive: Boolean - val allowDrag: Boolean - - val swipeExit = entry.leaving && entry.reason == "swipe" - val cardPaneScale = if (entry.leaving) entry.lastPaneScale else paneScale - var swipeExitTranslationX: 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) { - targetY = baseY - targetScale = ToasterMetrics.SWIPE_EXIT_SCALE - val cardWidthPx = slot.measuredWidth.takeIf { it > 0 }?.toFloat() ?: dp(ToasterMetrics.LANE_MAX_WIDTH).toFloat() - val exitDistance = max( - cardWidthPx + dp(ToasterMetrics.SWIPE_EXIT_MARGIN), - layer.width * 0.5f + cardWidthPx * 0.5f, - ) - swipeExitTranslationX = entry.swipeExitSign * exitDistance / max(cardPaneScale, 0.01f) - } else if (collapsedBackExit) { - targetY = baseY - dp(ToasterMetrics.COLLAPSED_BACK_EXIT_OFFSET) - targetScale = ToasterMetrics.COLLAPSED_LEAVE_SCALE - } else { - targetY = baseY - dp(ToasterMetrics.AUTO_EXIT_OFFSET) - targetScale = ToasterMetrics.AUTO_EXIT_SCALE - } - targetAlpha = 0f - hideBody = collapsedBackExit - interactive = false - allowDrag = false - } else { - val index = activeIndex - entry.lastActiveIndex = index - activeIndex += 1 - val isVisible = index < ToasterMetrics.VISIBLE_TOASTS - if (isCollapsed) { - displayHeight = if (index == 0) naturalHeight else frontHeight - val clampedIndex = min(index, ToasterMetrics.VISIBLE_TOASTS) - targetY = top + clampedIndex * gutterPx * cardPaneScale - targetScale = max(0.85f, 1f - clampedIndex * ToasterMetrics.STACK_SCALE_STEP) - hideBody = index > 0 - allowDrag = index == 0 - } else { - displayHeight = naturalHeight - targetY = top + expandedOffset * cardPaneScale - targetScale = 1f - hideBody = false - allowDrag = isVisible - } - entry.lastTargetY = targetY - entry.lastPaneScale = cardPaneScale - if (isVisible) { - expandedOffset += naturalHeight + gutterPx - } - targetAlpha = if (isVisible) 1f else 0f - interactive = isVisible && cardPaneScale > 0f - } - + val height = slot.measuredHeight + // Where the card rests before it enters and after it leaves. + val hidden = -(if (height > 0) height else dp(ToasterMetrics.FALLBACK_HEIGHT)) - + topInset - dp(ToasterMetrics.ENTER_OVERSHOOT) + val targetY = (top + if (entry.leaving) hidden else offset).toFloat() + val targetAlpha = if (entry.leaving) 0f else 1f + if (!entry.leaving) offset += height + dp(ToasterMetrics.GUTTER) slot.translationX = drawnX.toFloat() - slot.isEnabled = interactive - slot.allowDrag = allowDrag && interactive - slot.expansionOnly = hideBody - slot.importantForAccessibility = if (interactive && !hideBody) { - View.IMPORTANT_FOR_ACCESSIBILITY_AUTO - } else View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS - card.canExpandStack = isCollapsed && entry === active.firstOrNull() - slot.pivotX = slot.measuredWidth / 2f - slot.pivotY = if (cardPaneScale < 1f) 0f else displayHeight / 2f - val finalScale = targetScale * cardPaneScale - - val wasEntered = entry.entered - if (!wasEntered) { + if (!entry.entered) { entry.entered = true - val hidden = -(if (displayHeight > 0) displayHeight else dp(ToasterMetrics.FALLBACK_HEIGHT)) - - region.top - dp(ToasterMetrics.ENTER_OVERSHOOT) - card.setDisplayHeight(displayHeight, animated = false, durationMs = 0L, interpolator = toastSpringInterpolator) - card.setBodyHidden(hideBody, animated = false) slot.translationY = (top + hidden).toFloat() - slot.scaleX = ToasterMetrics.HIDDEN_SCALE - slot.scaleY = ToasterMetrics.HIDDEN_SCALE - if (animate && !entry.leaving) card.animateMessageStatusEntrance() - } else { - card.setBodyHidden(hideBody, animated = animate) - card.setDisplayHeight( - displayHeight, - animated = animate && !entry.leaving, - durationMs = ToasterMetrics.SPRING_MS, - interpolator = toastSpringInterpolator, - ) } - - if (!entry.leaving && !reduceMotion) card.animateMessageStatusRing() - if (reduceMotion) card.cancelStatusMotion() - if (animate) { - val exitDuration = if (swipeExit) ToasterMetrics.EXIT_MS else ToasterMetrics.AUTO_EXIT_MS - val exitInterpolator = if (swipeExit) toastExitInterpolator else toastAutoExitInterpolator - slot.animate().translationY(targetY).scaleX(finalScale).scaleY(finalScale) - .setDuration(if (entry.leaving) exitDuration else ToasterMetrics.SPRING_MS) - .setInterpolator(if (entry.leaving) exitInterpolator else toastSpringInterpolator) - .setUpdateListener { slot.reprojectDrag() } - .start() - if (swipeExitTranslationX != null) { - card.animate().translationX(swipeExitTranslationX) - .setDuration(ToasterMetrics.EXIT_MS) - .setInterpolator(toastExitInterpolator) - .start() - } - if (slot.alpha != targetAlpha || entry.alphaAnimator?.isRunning == true) { - entry.alphaAnimator?.cancel() - entry.alphaAnimator = ObjectAnimator.ofFloat(slot, View.ALPHA, targetAlpha).apply { - duration = if (entry.leaving) exitDuration else ToasterMetrics.ENTER_FADE_MS - interpolator = if (entry.leaving) exitInterpolator else toastEnterFadeInterpolator - start() - } - } + slot.animate().translationY(targetY).alpha(targetAlpha) + .setDuration(ToasterMetrics.ANIMATION_MS).setInterpolator(toastInterpolator).start() } else { slot.animate().cancel() - card.animate().cancel() - entry.alphaAnimator?.cancel() - entry.alphaAnimator = null slot.translationY = targetY - if (swipeExitTranslationX != null) { - card.translationX = swipeExitTranslationX - } else if (!entry.leaving && !slot.dragging) { - resetDrag(card) - } slot.alpha = targetAlpha - slot.scaleX = finalScale - slot.scaleY = finalScale - slot.reprojectDrag() } } } @@ -925,7 +500,7 @@ internal class NativeOverlayToastPresenter(private val hostView: View) { } private fun syncTimers() { - val paused = expanded || entries.any { !it.leaving && it.slot.hasActivePress } + val paused = pressed > 0 val now = SystemClock.uptimeMillis() for (entry in entries) { if (entry.leaving) continue diff --git a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/ToastStatusTileView.kt b/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/ToastStatusTileView.kt deleted file mode 100644 index 2e4ab4c7b..000000000 --- a/native-views/react-native-native-overlay/android/src/main/java/com/onekey/nativeoverlay/ToastStatusTileView.kt +++ /dev/null @@ -1,289 +0,0 @@ -package com.onekey.nativeoverlay - -import android.animation.Animator -import android.animation.AnimatorListenerAdapter -import android.animation.ArgbEvaluator -import android.animation.ObjectAnimator -import android.animation.ValueAnimator -import android.annotation.SuppressLint -import android.content.Context -import android.graphics.Canvas -import android.graphics.Color -import android.graphics.Paint -import android.graphics.Path -import android.graphics.PathMeasure -import android.graphics.drawable.GradientDrawable -import android.view.View -import android.view.animation.LinearInterpolator -import android.view.animation.PathInterpolator -import android.widget.FrameLayout -import kotlin.math.cos -import kotlin.math.exp -import kotlin.math.roundToInt -import kotlin.math.sin -import kotlin.math.sqrt - -/** Analytical unit-mass spring step response matching Web `springProgressAt` and iOS `CASpringAnimation`. */ -internal fun toastSpringProgress(stiffness: Double, damping: Double, elapsedMs: Float): Float { - if (elapsedMs <= 0f) return 0f - val t = elapsedMs / 1000.0 - val w0 = sqrt(stiffness) - val zeta = damping / (2.0 * w0) - val progress = when { - zeta < 1.0 -> { - val wd = w0 * sqrt(1.0 - zeta * zeta) - 1.0 - exp(-zeta * w0 * t) * (cos(wd * t) + ((zeta * w0) / wd) * sin(wd * t)) - } - zeta == 1.0 -> 1.0 - exp(-w0 * t) * (1.0 + w0 * t) - else -> { - val root = sqrt(zeta * zeta - 1.0) - val r1 = -w0 * (zeta - root) - val r2 = -w0 * (zeta + root) - 1.0 - (r2 * exp(r1 * t) - r1 * exp(r2 * t)) / (r2 - r1) - } - } - return progress.toFloat() -} - -@SuppressLint("ViewConstructor") -internal class ToastStatusTileView(context: Context, private var status: ToastIcon.Status) : FrameLayout(context) { - private val surface = GradientDrawable() - private val colors = ArgbEvaluator() - private val easeOut = PathInterpolator(0f, 0f, .58f, 1f) - private val easeIn = PathInterpolator(.42f, 0f, 1f, 1f) - private val tintEase = PathInterpolator(.4f, 0f, .2f, 1f) - private var glyph = makeGlyph(status) - private var departing: ToastStatusGlyphView? = null - private var animation: ValueAnimator? = null - private var tileColor = status.backgroundColor - private var tinting = false - - init { - importantForAccessibility = IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS - clipToOutline = true - background = surface - applyTileColor(tileColor) - } - - override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { - super.onSizeChanged(w, h, oldw, oldh) - surface.cornerRadius = w * 11f / 36f - } - - private fun makeGlyph(icon: ToastIcon.Status) = ToastStatusGlyphView(context, icon).also { - addView(it, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) - } - - private fun applyTileColor(color: Int) { - tileColor = color - surface.setColor(color) - } - - private fun fade(view: View, opacity: Float, scale: Float) { - view.alpha = opacity.coerceIn(0f, 1f) - view.scaleX = scale - view.scaleY = scale - } - - private fun drawAt(elapsed: Float, popStart: Float) { - // Snappy POP spring: mass 1, stiffness 920, damping 40 (same ~6.4% overshoot, ~35% faster). - val pop = toastSpringProgress(920.0, 40.0, elapsed - popStart) - fade(glyph, pop, mix(.4f, 1f, pop)) - glyph.strokeProgress = easeOut.getInterpolation(progress(elapsed, popStart + 55f, 180f)) - } - - private fun animateFor(duration: Long, frame: (Float) -> Unit) { - animation?.cancel() - frame(0f) - var cancelled = false - animation = ValueAnimator.ofFloat(0f, duration.toFloat()).apply { - this.duration = duration - interpolator = LinearInterpolator() - addUpdateListener { frame(it.animatedValue as Float) } - addListener(object : AnimatorListenerAdapter() { - override fun onAnimationCancel(animator: Animator) { - cancelled = true - } - - override fun onAnimationEnd(animator: Animator) { - if (!cancelled) { - tinting = false - removeDeparting() - fade(this@ToastStatusTileView, 1f, 1f) - fade(glyph, 1f, 1f) - glyph.strokeProgress = 1f - applyTileColor(status.backgroundColor) - } - } - }) - start() - } - } - - fun enter() { - // Tile spring (110 ms, 620/50) + glyph POP spring (155 ms, 920/40) + stroke draw (210..390 ms). - animateFor(510L) { elapsed -> - val tile = toastSpringProgress(620.0, 50.0, elapsed - 110f) - fade(this, tile, mix(.85f, 1f, tile)) - drawAt(elapsed, 155f) - } - } - - fun apply(next: ToastIcon.Status, settle: Boolean) { - val previous = status - status = next - if (previous.status == next.status) { - glyph.color = next.color - if (previous.backgroundColor != next.backgroundColor && !tinting) { - applyTileColor(next.backgroundColor) - } - return - } - - val eligible = settle && previous.status != next.status - val old = glyph - val oldOpacity = old.alpha - val oldScale = old.scaleX - val tileOpacity = alpha - val tileScale = scaleX - val oldColor = tileColor - removeDeparting() - glyph = makeGlyph(next) - val leave = if (eligible && oldOpacity > 0f) 90f else 0f - if (leave > 0f) { - departing = old - } else { - old.stopRing() - removeView(old) - } - if (!eligible) { - cancelMotion() - return - } - - animateFor((leave + 360f).toLong()) { elapsed -> - val leaving = easeIn.getInterpolation(progress(elapsed, 0f, leave.coerceAtLeast(1f))) - departing?.let { - fade(it, mix(oldOpacity, 0f, leaving), mix(oldScale, .5f, leaving)) - if (elapsed >= leave) removeDeparting() - } - val bump = progress(elapsed, leave, 260f) - val bumpScale = if (bump <= .4f) { - mix(tileScale, 1.07f, easeOut.getInterpolation(bump / .4f)) - } else { - mix(1.07f, 1f, easeOut.getInterpolation((bump - .4f) / .6f)) - } - fade(this, mix(tileOpacity, 1f, easeOut.getInterpolation(progress(bump, 0f, .4f))), bumpScale) - val tint = tintEase.getInterpolation(progress(elapsed, 0f, 140f)) - tinting = tint < 1f - applyTileColor(colors.evaluate(tint, oldColor, status.backgroundColor) as Int) - drawAt(elapsed, leave) - } - } - - private fun removeDeparting() { - departing?.let { - it.stopRing() - removeView(it) - } - departing = null - } - - fun cancelMotion() { - animation?.cancel() - animation = null - tinting = false - removeDeparting() - fade(this, 1f, 1f) - fade(glyph, 1f, 1f) - glyph.strokeProgress = 1f - glyph.stopRing() - applyTileColor(status.backgroundColor) - } - - fun startRing() = glyph.startRing() - - override fun onDetachedFromWindow() { - cancelMotion() - super.onDetachedFromWindow() - } - - private fun progress(elapsed: Float, start: Float, duration: Float) = - ((elapsed - start) / duration).coerceIn(0f, 1f) - - private fun mix(from: Float, to: Float, fraction: Float) = from + (to - from) * fraction -} - -@SuppressLint("ViewConstructor") -internal class ToastStatusGlyphView(context: Context, icon: ToastIcon.Status) : View(context) { - private val recipe = icon.glyph - private val contours = recipe.contours.filter { it.size >= 2 }.map { points -> - val path = Path().apply { - moveTo(points.first().first, points.first().second) - points.drop(1).forEach { (x, y) -> lineTo(x, y) } - } - PathMeasure(path, false) - } - private val segment = Path() - private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply { - strokeWidth = recipe.strokeWidth - strokeCap = Paint.Cap.ROUND - strokeJoin = Paint.Join.ROUND - } - private var spin: ObjectAnimator? = null - var color = icon.color - set(value) { - field = value - invalidate() - } - var strokeProgress = 1f - set(value) { - field = value - invalidate() - } - - fun startRing() { - if (recipe.ring == null || spin != null) return - spin = ObjectAnimator.ofFloat(this, ROTATION, 0f, 360f).apply { - duration = 850L - repeatCount = ValueAnimator.INFINITE - interpolator = LinearInterpolator() - start() - } - } - - fun stopRing() { - spin?.cancel() - spin = null - rotation = 0f - } - - override fun onDraw(canvas: Canvas) { - val scale = minOf(width, height) / 48f - canvas.save() - canvas.translate(width / 2f - 12f * scale, height / 2f - 12f * scale) - canvas.scale(scale, scale) - paint.color = color - paint.style = Paint.Style.STROKE - if (strokeProgress > 0) { - contours.forEach { contour -> - segment.rewind() - contour.getSegment(0f, contour.length * strokeProgress, segment, true) - canvas.drawPath(segment, paint) - } - } - recipe.ring?.let { ring -> - paint.alpha = (Color.alpha(color) * ring.trackOpacity).roundToInt() - canvas.drawCircle(12f, 12f, ring.radius, paint) - paint.color = color - val low = 12f - ring.radius - val high = 12f + ring.radius - canvas.drawArc(low, low, high, high, -90f, 360f * ring.arcFraction, false, paint) - } - recipe.dot?.let { dot -> - paint.style = Paint.Style.FILL - canvas.drawCircle(dot.x, dot.y, dot.radius, paint) - } - canvas.restore() - } -} diff --git a/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastBoundsTest.kt b/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastBoundsTest.kt deleted file mode 100644 index 3f5c2af87..000000000 --- a/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastBoundsTest.kt +++ /dev/null @@ -1,63 +0,0 @@ -package com.onekey.nativeoverlay - -import android.graphics.Rect -import androidx.window.layout.FoldingFeature -import org.junit.Assert.assertEquals -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) -class NativeOverlayToastBoundsTest { - @Test - fun separatingVerticalFoldUsesWiderPaneAndBreaksTiesByDirection() { - val safe = Rect(0, 30, 800, 900) - val centeredFold = fold(Rect(380, 0, 420, 900)) - assertEquals(Rect(0, 30, 380, 900), toastAvailableBounds(safe, listOf(centeredFold), 0, 0, false)) - assertEquals(Rect(420, 30, 800, 900), toastAvailableBounds(safe, listOf(centeredFold), 0, 0, true)) - - // Stage is inset 50 window pixels from the left. - assertEquals(Rect(270, 30, 800, 900), toastAvailableBounds(safe, listOf(fold(Rect(300, 0, 320, 900))), 50, 0, false)) - } - - @Test - fun horizontalFoldUsesUpperPaneAndContinuousFoldKeepsWindow() { - val safe = Rect(12, 30, 788, 880) - val horizontal = fold(Rect(0, 430, 800, 460), FoldingFeature.Orientation.HORIZONTAL) - assertEquals(Rect(12, 30, 788, 430), toastAvailableBounds(safe, listOf(horizontal), 0, 0, false)) - assertEquals(safe, toastAvailableBounds(safe, listOf(fold(Rect(400, 0, 400, 900), separates = false)), 0, 0, false)) - } - - @Test - fun requestedAndDefaultWidthsFitPaneAndRespectMaximum() { - assertEquals(576f, toastContentWidth(900f, 900f), 0f) - assertEquals(576f, toastContentWidth(900f, null), 0f) - assertEquals(288f, toastContentWidth(340f, 596f), 0f) - assertEquals(276f, toastContentWidth(340f, null), 0f) - assertEquals(200f, toastContentWidth(340f, 200f), 0f) - } - - @Test - fun stackFitsTheUpperPaneAfterTheObstructionShift() { - val available = 430f - 62f - 96f - 4f - val stackHeight = 128 + 92 + 122 + 2 * 4 - val scale = toastStackScale(available, stackHeight) - assertEquals(available, stackHeight * scale, 0.001f) - assertEquals(1f, toastStackScale(available, 128 + 2 * 4), 0f) - assertEquals(0f, toastStackScale(-4f, stackHeight), 0f) - } - - private fun fold( - rect: Rect, - foldOrientation: FoldingFeature.Orientation = FoldingFeature.Orientation.VERTICAL, - separates: Boolean = true, - ) = object : FoldingFeature { - override val bounds = rect - override val orientation = foldOrientation - override val isSeparating = separates - override val state = FoldingFeature.State.FLAT - override val occlusionType = FoldingFeature.OcclusionType.FULL - } -} 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 deleted file mode 100644 index b3ddee68f..000000000 --- a/native-views/react-native-native-overlay/android/src/test/java/com/onekey/nativeoverlay/NativeOverlayToastCardLayoutTest.kt +++ /dev/null @@ -1,110 +0,0 @@ -package com.onekey.nativeoverlay - -import android.graphics.Color -import android.graphics.Matrix -import android.view.MotionEvent -import android.view.View -import org.json.JSONObject -import org.junit.Assert.assertEquals -import org.junit.Assert.assertTrue -import org.junit.Test -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.RuntimeEnvironment -import org.robolectric.annotation.Config -import kotlin.math.roundToInt - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) -class NativeOverlayToastCardLayoutTest { - @Test - fun eligibleActionRemainsVisibleWhenHeightCapWouldClipLowerRow() { - val card = NativeOverlayToastCardView(RuntimeEnvironment.getApplication()) - val spec = ToastSpec.parse(JSONObject(""" - { - "id": "capped-toast", - "statusIcon": {"kind": "status", "status": "success", "size": 36, "glyph": {"contours": [[[6, 12], [10, 16], [18, 8]]]}}, - "title": {"paragraphs": [[{"text": "Done"}]], "fontSize": 16, "lineHeight": 24}, - "actions": [{"id": "view", "testID": "view", "label": "View", "lineHeight": 20, "paddingVertical": 4}] - } - """.trimIndent())) - card.contentWidth = 180f - card.apply(spec, Color.WHITE) - card.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) - card.layout(0, 0, card.measuredWidth, card.measuredHeight) - val action = checkNotNull(card.findViewWithTag("view")) - val lowerTop = action.top - - card.contentMaxHeight = 36f - card.requestLayout() - card.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED) - card.layout(0, 0, card.measuredWidth, card.measuredHeight) - - val padding = (10f * card.resources.displayMetrics.density).roundToInt() - assertTrue(lowerTop > action.top) - assertTrue(action.top >= padding && action.bottom <= card.height - padding) - } - - @Test - fun shortDragVelocityStaysInWindowCoordinatesAcrossSlotScales() { - val slot = toastSlot() - val density = slot.resources.displayMetrics.density - var releaseX = 0f - var releaseVelocity = 0f - slot.onRelease = { x, _, velocity, cancelled -> - assertTrue(!cancelled) - releaseX = x / density - releaseVelocity = velocity / density - } - sendTouch(slot, MotionEvent.ACTION_DOWN, 0L, 250f) - sendTouch(slot, MotionEvent.ACTION_MOVE, 40L, 262f) - slot.scaleX = 0.5f - slot.scaleY = 0.5f - sendTouch(slot, MotionEvent.ACTION_MOVE, 70L, 271f) - sendTouch(slot, MotionEvent.ACTION_MOVE, 90L, 277f) - sendTouch(slot, MotionEvent.ACTION_UP, 100L, 280f) - - assertEquals(30f, releaseX, 0.01f) - assertEquals(300f, releaseVelocity, 20f) - } - - @Test - fun heldDragKeepsItsPhysicalOffsetAndOpacityWhenTheSlotShrinks() { - val slot = toastSlot() - val density = slot.resources.displayMetrics.density - sendTouch(slot, MotionEvent.ACTION_DOWN, 0L, 250f) - sendTouch(slot, MotionEvent.ACTION_MOVE, 80L, 290f) - val opacity = slot.card.alpha - assertEquals(40f, slot.card.translationX / density, 0.01f) - - slot.scaleX = 0.5f - slot.scaleY = 0.5f - slot.reprojectDrag() - - assertEquals(40f, slot.card.translationX * slot.scaleX / density, 0.01f) - assertEquals(opacity, slot.card.alpha, 0f) - slot.clearTouch() - } - - private fun toastSlot(): ToastSlot { - val context = RuntimeEnvironment.getApplication() - return ToastSlot(context, NativeOverlayToastCardView(context)) - } - - private fun sendTouch(slot: ToastSlot, action: Int, time: Long, xDp: Float) { - val density = slot.resources.displayMetrics.density - val event = MotionEvent.obtain(1000L, 1000L + time, action, xDp * density, 70f * density, 0) - val windowToSlot = Matrix().apply { - setTranslate(-100f * density, -40f * density) - postScale(1f / slot.scaleX, 1f / slot.scaleY) - } - event.transform(windowToSlot) - assertEquals(xDp, event.rawX / density, 0.01f) - if (action == MotionEvent.ACTION_DOWN) { - slot.onInterceptTouchEvent(event) - } else { - slot.onTouchEvent(event) - } - event.recycle() - } -} diff --git a/native-views/react-native-native-overlay/docs/SPEC.md b/native-views/react-native-native-overlay/docs/SPEC.md index 3a513f3a2..60602c7aa 100644 --- a/native-views/react-native-native-overlay/docs/SPEC.md +++ b/native-views/react-native-native-overlay/docs/SPEC.md @@ -1403,33 +1403,6 @@ only React piece is `OverlayToastHost`, which attaches the renderer. Pressing one does not dismiss the toast. - `show` with an id that is on screen updates that card and restarts its lifetime; `update` redraws it (theme or layout change) without restarting. -- A message icon may use `kind: 'status'` with `status` set to `success`, - `error`, `warning`, `info`, or `loading`. The caller supplies `color` - for the glyph, `backgroundColor` for its rounded tile, and `size` for - the tile edge. The centered glyph occupies half the tile edge. The optional - message `statusIcon` takes precedence over `icon`. Callers can supply both - so older renderers still show the fallback `icon`. -- A status tile fades and settles into place near the end of the card - entrance. Its glyph pops independently with a small overshoot. - Success draws one continuous check from the short leg to the long leg. - Error draws two simultaneous diagonals from their upper ends. - Warning and info draw downward stems and reveal their stationary dots - with the glyph pop. Loading rotates a ring with a dimmer track and a - brighter quarter arc. -- Showing success or error under the same id as a message loading status - keeps the card and tile in place. Once the loading glyph is visible, it - fades and shrinks from its current state for about 140 ms. The tile - interpolates its background color and bumps once, and the result glyph - pops and draws after the outgoing glyph's departure. If the loading - glyph has yet to appear, the result appears without waiting for either - departure or the rest of the card entrance. -- A redraw or theme change with the same generation and status preserves - the tile and any in-flight glyph motion. Dismissal cancels status motion. - Reduced motion shows the full resting glyph and tile immediately, with a - static loading ring, following `respectReducedMotion`. Named icons, - custom spinners, images, notification badges, and action icons retain - their existing renderer behavior. A status icon used in a badge or action - uses its resting appearance. - A toast leaves the list when its renderer reports `close`, after the exit. With no renderer attached a dismissal removes it at once. At most 20 toasts are kept; older ones are dropped without animation. @@ -1448,9 +1421,6 @@ with two string props (`toasts`, `config`: JSON) and one direct event level window from `NativeOverlayWindowManager`, Android in a layer at the bottom of the host's `toast` level container, so custom toast entries stay above them. Web has no bridge: the DOM renderer subscribes to the store. -The JSON serializer attaches the shared status glyph recipe to every status -icon. Web and both native renderers use the same 24-unit centerlines, dot, -stroke widths, and loading ring geometry. Named icons come from `@onekeyfe/react-native-image`'s native registry, reached at runtime (Objective-C runtime on iOS, reflection on Android) so this @@ -1462,91 +1432,21 @@ Web draws an SVG `` of the `href` the caller supplies. ### Platform behaviour -All platforms adopt the shared RareUI-inspired concentric geometry (`10` card -padding, `36` status tile, `11` tile/inline-action radius, `21` card radius) -and unified spring motion (`card` stiffness/damping `460/36`, `tile` `620/50`, -`glyph` `920/40`; swipe exit `200 ms` `cubic-bezier(0.32, 0.72, 0, 1)`; -non-interactive exit `190 ms` `cubic-bezier(0.2, 0, 0, 1)`). +Each platform keeps the look and motion of the renderer it replaced. | Behaviour | Web | iOS / Android | | --- | --- | --- | -| 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`) | -| 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 | -| Top obstruction | Top groups animate the inset in 220 ms | Cards translate within the full-window touch stage, 220 ms | +| Position | Per toast or toaster; default bottom-right | Always top-centre | +| Stack | Newest in front, 3 visible. Hover or tap to expand multiple cards. An outside press clears tap expansion. | Oldest at the top, newest under it, 8 pt apart, all visible | +| Card | 356 px wide, 16 px padding, themed surface and border, close button | Content box from `contentWidth` plus 16 / 12 pt padding, 8 pt radius, shadow | +| Enter / exit | 400 ms transform and opacity transition; exit 200 ms | 300 ms quadratic ease-in-out slide from above the top edge, with opacity | +| `close` reported | 200 ms after the exit starts | 1000 ms after the exit starts | +| 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; resuming continues the remaining time | +| Swipe | Away from the anchored edge (down on bottom groups, up on top groups). Once a vertical swipe starts, only vertical displacement counts. Release dismisses at 20 px or above 0.11 px/ms. | Up; 32 pt, or 12 pt at 600 pt/s; dragging down moves a quarter as far | +| Top obstruction | Inline `top` on top groups, 220 ms | The whole stack translates, 220 ms | | Reduced motion | Transitions off (media query) | Every animation is instant | -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 -anchors choose the corresponding row of segments. -Web positions that resolve to the same lane share a stack. Moving a card -between lanes remeasures its content at the destination width. In Android -windows that report a separating display feature, the toaster chooses the -wider side of a vertical fold, using the leading side for ties, and the upper -side of a horizontal fold. The native anchor remains -top-center within that area. iOS and windows with no reported separator use the -available window bounds. Insets, resizing and posture changes recalculate the -placement without restarting toast lifetimes. On Web and Android, a -horizontal fold limits the settled stack to the space between its anchor -(after any obstruction shift) and the hinge-facing edge of its pane. If the -stack exceeds this budget, its cards and gaps scale together so every action -stays in the pane. On Web, cards with no remaining pane space are excluded -from pointer input, keyboard focus and the accessibility tree until space returns. - -A single eligible message action stays inline when its measured width, icon -and spacing leave at least 96 px/pt/dp for the text column. A smaller text -column is allowed when the lower action would be clipped by a configured -content height cap and the measured inline row fits within the cap. Other -eligible actions use the lower row. Inline buttons use an 11-unit radius. -Lower-row buttons use the caller's radius. Disabled actions keep their configured opacity -through settlement. - -Native collapsed back cards accept taps in their visible bounds to expand -the stack. Movement past the drag threshold does not expand a back card. -On all platforms, a swipe is cancelled when the card loses swipe eligibility. The -front card exposes an accessibility action to expand a collapsed stack. On -iOS the expansion control is a separate accessibility element alongside the -front card's visible text, links and action buttons. Its focus frame uses -the visible part of the status icon or badge, or the card's leading inset -if the icon or badge is absent or fully clipped. Removing a toast clears -its press and timer before synchronizing survivors. - -The Web close control stays keyboard- and screen-reader-accessible on -visible toasts on touch browsers. The hidden control is transparent to -pointer input. Cards beyond the display limit are excluded from focus and -the accessibility tree until they become visible. While the stack is -collapsed, the hidden bodies of back cards are also excluded. After the -stack layout updates, focus on a lane that no longer contains active cards -follows its cards to a destination lane. Focus inside a newly collapsed body -moves to its visible shell if focus has stayed with the toast. The shell keeps its -close button accessible. Enabling Reduce Motion -finalizes mounted status animations and keeps loading rings static. On Web -it also completes in-flight exits with their original dismissal reasons. -Restoring motion resumes the loading ring. iOS action buttons use -color-only press feedback while motion reduction is active. - -On Web, the card, tile and glyph springs are generated from the shared -`TOAST_MOTION` spring definitions via `springToCssLinear`. Stroke reveal and -the result tile bump (`[1, 1.07, 1]` over `260 ms`) use -`cubic-bezier(0, 0, 0.58, 1)`, the outgoing glyph uses `90 ms` -`cubic-bezier(0.42, 0, 1, 1)`, and tile/glyph colors transition over `140 ms` -with `cubic-bezier(0.4, 0, 0.2, 1)`. The status loading ring completes one -turn every `850 ms` on every platform. - -On Web, the card captures the pointer after recognizing a swipe. Flick speed -uses input event timestamps from the last 80 ms, including movement before -the swipe locks. Android measures both swipe velocity and displacement in -window coordinates. While an eligible Android card is held during a pane -resize, its visible horizontal displacement continues to match the input. -The short flick must be moving toward its exit side on every platform. -Holding the card still and then moving it slowly below the -distance threshold settles it back in place. Ordinary +On Web, the card captures the pointer after recognizing a swipe. Ordinary clicks and taps activate the pressable row, buttons, or links through their own handlers. Each press ends independently on release or cancellation. Card removal, reuse, or repositioning clears its presses, and window blur @@ -1565,21 +1465,13 @@ Divergences from the renderers replaced: ### Verification -- 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 - styling, inline and lower-row action placement, and the expanded stack. - The native harnesses exercise their respective renderers in isolation - from the OneKey app. - Web: `src/__tests__/overlayToast.web.test.ts` covers the store and the DOM renderer. In app-monorepo, 13 scenarios in three captures (wide dark, narrow dark, wide light) matched the previous renderer's card boxes, text line rects, icon and button boxes and computed styles within 0.5 px. - Web pointer regression: `tests/browser/overlayToast.test.cjs` exercises browser-generated mouse clicks, touch taps, mixed input, and swipes in - Chromium. Status motion checks in the suite cover ordered entrance, stroke - direction, same-id settlement, redraw, cancellation, and reduced motion. - Run from the package with `node --test tests/browser/overlayToast.test.cjs`. + Chromium. Run from the package with `node --test tests/browser/overlayToast.test.cjs`. Make `esbuild` and `playwright-core` available via `NODE_PATH` or the local install, and set `CHROMIUM_EXECUTABLE_PATH` if using a system Chrome. - iOS: built into app-monorepo and run on an iPhone 17 Pro simulator (iOS diff --git a/native-views/react-native-native-overlay/ios/NativeOverlayToastCardView.swift b/native-views/react-native-native-overlay/ios/NativeOverlayToastCardView.swift index 0c2caf374..34a527285 100644 --- a/native-views/react-native-native-overlay/ios/NativeOverlayToastCardView.swift +++ b/native-views/react-native-native-overlay/ios/NativeOverlayToastCardView.swift @@ -1,24 +1,17 @@ import ObjectiveC import UIKit -// RareUI-inspired concentric geometry: cardRadius = tileRadius (11) + padding (10). +// The card geometry of the layouts this replaces. private enum ToastMetrics { - static let cardPaddingHorizontal: CGFloat = 10 - static let cardPaddingVertical: CGFloat = 10 - static let cardRadius: CGFloat = 21 - static let messageIconGap: CGFloat = 12 - static let messageTextGap: CGFloat = 2 - static let noIconPaddingStart: CGFloat = 6 - static let tileMinHeight: CGFloat = 36 - static let inlineActionHeight: CGFloat = 36 - static let inlineActionRadius: CGFloat = 11 - static let inlineTextMinWidth: CGFloat = 96 - static let inlineActionMaxLabel: Int = 16 - static let inlineActionMaxMessage: Int = 72 - static let notificationGap: CGFloat = 10 + static let cardPaddingHorizontal: CGFloat = 16 + static let cardPaddingVertical: CGFloat = 12 + static let cardRadius: CGFloat = 8 + static let messageIconGap: CGFloat = 8 + static let messageTextGap: CGFloat = 4 + static let notificationGap: CGFloat = 8 static let notificationTextGap: CGFloat = 2 static let actionsGap: CGFloat = 8 - static let actionsPaddingTop: CGFloat = 10 + static let actionsPaddingTop: CGFloat = 12 static let actionsPaddingEnd: CGFloat = 2 static let actionsPaddingBottom: CGFloat = 2 } @@ -73,8 +66,7 @@ private final class ToastIconView: UIView { private var spinner: UIActivityIndicatorView? private var task: URLSessionDataTask? private var requested = false - private(set) var icon: NativeOverlayToastIcon - private(set) var statusTile: ToastStatusTileView? + let icon: NativeOverlayToastIcon init(icon: NativeOverlayToastIcon) { self.icon = icon @@ -93,12 +85,6 @@ private final class ToastIconView: UIView { indicator.center = CGPoint(x: bounds.midX, y: bounds.midY) addSubview(indicator) spinner = indicator - case let .status(status): - let tile = ToastStatusTileView(status: status) - tile.frame = bounds - tile.autoresizingMask = [.flexibleWidth, .flexibleHeight] - addSubview(tile) - statusTile = tile case let .image(uri, _, radius): imageView.layer.cornerRadius = radius load(uri) @@ -107,11 +93,6 @@ private final class ToastIconView: UIView { } } - func applyStatus(_ status: NativeOverlayToastStatus, settle: Bool) { - icon = .status(status) - statusTile?.apply(status, settle: settle) - } - @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } @@ -286,17 +267,8 @@ final class ToastTextLabel: UIView { private final class ToastActionButton: UIControl { let action: NativeOverlayToastAction - var isInline = false private let label = UILabel() private var iconView: ToastIconView? - var reduceMotion = false { - didSet { - if reduceMotion && !oldValue { - layer.removeAllAnimations() - transform = .identity - } - } - } init(action: NativeOverlayToastAction) { self.action = action @@ -334,11 +306,6 @@ private final class ToastActionButton: UIControl { backgroundColor = isHighlighted ? (action.pressedBackgroundColor ?? action.backgroundColor) : action.backgroundColor - guard !reduceMotion else { return } - let scale: CGFloat = isHighlighted ? 0.95 : 1 - UIView.animate(withDuration: 0.12) { - self.transform = CGAffineTransform(scaleX: scale, y: scale) - } } } @@ -347,9 +314,8 @@ private final class ToastActionButton: UIControl { /// The button's border box. var fittedSize: CGSize { - let padX = isInline ? max(action.paddingHorizontal, 14) : action.paddingHorizontal - return CGSize( - width: labelWidth + iconExtent + 2 * (padX + action.borderWidth), + CGSize( + width: labelWidth + iconExtent + 2 * (action.paddingHorizontal + action.borderWidth), height: max(action.lineHeight + textBoxSlack, action.icon?.size ?? 0) + 2 * (action.paddingVertical + action.borderWidth) ) @@ -357,10 +323,8 @@ private final class ToastActionButton: UIControl { override func layoutSubviews() { super.layoutSubviews() - let radius = isInline ? ToastMetrics.inlineActionRadius : action.borderRadius - layer.cornerRadius = min(radius, bounds.height / 2) - let padX = isInline ? max(action.paddingHorizontal, 14) : action.paddingHorizontal - var x = padX + action.borderWidth + layer.cornerRadius = min(action.borderRadius, bounds.height / 2) + var x = action.paddingHorizontal + action.borderWidth if let iconView, let icon = action.icon { iconView.frame = CGRect( x: x, y: (bounds.height - icon.size) / 2, width: icon.size, height: icon.size @@ -380,17 +344,8 @@ private final class ToastActionButton: UIControl { } } -private final class ToastStackExpansionElement: UIAccessibilityElement { - var onExpand: (() -> Bool)? - - override func accessibilityActivate() -> Bool { - onExpand?() ?? false - } -} - /// One toast card, drawn with UIKit from a spec. final class NativeOverlayToastCardView: UIView { - static let horizontalPadding = ToastMetrics.cardPaddingHorizontal private(set) var spec: NativeOverlayToastSpec var onAction: ((String) -> Void)? var onLink: ((String) -> Void)? @@ -398,107 +353,35 @@ final class NativeOverlayToastCardView: UIView { private let surface = UIView() private let content = UIView() - private var messageStatusIcon: ToastIconView? - private var layoutBlocks: [(CGFloat, CGFloat?) -> CGFloat] = [] - private weak var stackExpansionAnchor: UIView? - private lazy var stackExpansionElement: ToastStackExpansionElement = { - let element = ToastStackExpansionElement(accessibilityContainer: self) - element.accessibilityLabel = "Expand notifications" - element.accessibilityTraits = .button - element.onExpand = { [weak self] in - guard let self, self.canExpandStack, let onPress = self.onPress else { return false } - onPress() - return true - } - return element - }() - private var bodyHidden = false - var canExpandStack = false { - didSet { - guard canExpandStack != oldValue else { return } - updateAccessibilityActions() - } - } - private(set) var naturalSize: CGSize = .zero + private var layoutBlocks: [(CGFloat) -> CGFloat] = [] - init(spec: NativeOverlayToastSpec, cardColor: UIColor, cardBorderColor: UIColor? = nil) { + init(spec: NativeOverlayToastSpec, cardColor: UIColor) { self.spec = spec super.init(frame: .zero) surface.layer.cornerRadius = ToastMetrics.cardRadius - surface.layer.cornerCurve = .continuous - surface.layer.borderWidth = 1 - surface.layer.shadowColor = UIColor.black.cgColor - surface.layer.shadowOffset = CGSize(width: 0, height: 2) - surface.layer.shadowOpacity = 0.06 - surface.layer.shadowRadius = 4 + surface.layer.shadowColor = UIColor(red: 0x18 / 255, green: 0x18 / 255, blue: 0x21 / 255, alpha: 1).cgColor + surface.layer.shadowOffset = CGSize(width: 0, height: 3) + surface.layer.shadowOpacity = 0.15 + surface.layer.shadowRadius = 4.65 addSubview(surface) content.clipsToBounds = true surface.addSubview(content) - apply(spec: spec, cardColor: cardColor, cardBorderColor: cardBorderColor) + apply(spec: spec, cardColor: cardColor) } @available(*, unavailable) required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - func apply( - spec: NativeOverlayToastSpec, - cardColor: UIColor, - cardBorderColor: UIColor? = nil, - settleStatus: Bool = false - ) { - let retained: ToastIconView? - if spec.layout == .message, case let .status(status)? = spec.icon, let messageStatusIcon { - messageStatusIcon.applyStatus(status, settle: settleStatus) - retained = messageStatusIcon - } else { - cancelStatusMotion() - retained = nil - } - messageStatusIcon = nil - stackExpansionAnchor = nil + func apply(spec: NativeOverlayToastSpec, cardColor: UIColor) { self.spec = spec surface.backgroundColor = cardColor - surface.layer.borderColor = (cardBorderColor ?? UIColor(white: 0, alpha: 0.06)).cgColor accessibilityIdentifier = spec.testID - content.subviews.forEach { view in - if view !== retained { view.removeFromSuperview() } - } + content.subviews.forEach { $0.removeFromSuperview() } layoutBlocks = [] switch spec.layout { - case .message: buildMessage(statusIcon: retained) + case .message: buildMessage() case .notification: buildNotification() } - if settleStatus && retained != nil { - let swapped = content.subviews.filter { $0 !== retained }.map { ($0, $0.alpha) } - swapped.forEach { view, _ in - view.alpha = 0 - view.transform = CGAffineTransform(translationX: 0, y: 3) - } - let animator = UIViewPropertyAnimator( - duration: 0.16, - timingParameters: UICubicTimingParameters( - controlPoint1: CGPoint(x: 0.2, y: 0), controlPoint2: CGPoint(x: 0, y: 1) - ) - ) - animator.addAnimations { - swapped.forEach { view, restingAlpha in - view.alpha = restingAlpha - view.transform = .identity - } - } - animator.startAnimation() - } - updateAccessibilityActions() - } - - private func updateAccessibilityActions() { - if canExpandStack { - let visibleElements: [Any] = content.subviews.filter(\.isAccessibilityElement) - accessibilityElements = visibleElements + [stackExpansionElement] - updateStackExpansionFrame() - } else { - accessibilityElements = nil - } if spec.pressable { accessibilityCustomActions = [ UIAccessibilityCustomAction( @@ -512,67 +395,6 @@ final class NativeOverlayToastCardView: UIView { } } - private func updateStackExpansionFrame() { - guard canExpandStack else { return } - let visibleContent = content.convert(content.bounds, to: self).intersection(bounds) - if let anchor = stackExpansionAnchor { - let frame = anchor.convert(anchor.bounds, to: self).intersection(visibleContent) - if !frame.isEmpty { - stackExpansionElement.accessibilityFrameInContainerSpace = frame - return - } - } - stackExpansionElement.accessibilityFrameInContainerSpace = CGRect( - x: bounds.minX, y: bounds.minY, - width: min(ToastMetrics.cardPaddingHorizontal, bounds.width), height: bounds.height - ) - } - - func setBodyHidden(_ hidden: Bool, animated: Bool) { - guard hidden != bodyHidden else { return } - bodyHidden = hidden - accessibilityElementsHidden = hidden - content.isUserInteractionEnabled = !hidden - let targetAlpha: CGFloat = hidden ? 0 : 1 - if animated { - UIView.animate(withDuration: 0.24, delay: 0, options: [.beginFromCurrentState, .curveEaseOut]) { - self.content.alpha = targetAlpha - } - } else { - content.alpha = targetAlpha - } - } - - func applyDisplayHeight(_ height: CGFloat) { - let clamped = max(height, 0) - let size = CGSize(width: naturalSize.width, height: clamped) - bounds.size = size - surface.frame = CGRect(origin: .zero, size: size) - surface.layer.shadowPath = UIBezierPath( - roundedRect: surface.bounds, cornerRadius: ToastMetrics.cardRadius - ).cgPath - content.frame = CGRect( - x: ToastMetrics.cardPaddingHorizontal, - y: ToastMetrics.cardPaddingVertical, - width: max(size.width - 2 * ToastMetrics.cardPaddingHorizontal, 0), - height: max(clamped - 2 * ToastMetrics.cardPaddingVertical, 0) - ) - updateStackExpansionFrame() - } - - func animateMessageStatusEntrance() { messageStatusIcon?.statusTile?.enter() } - - func animateMessageStatusRing() { messageStatusIcon?.statusTile?.startRing() } - - func cancelStatusMotion() { messageStatusIcon?.statusTile?.cancelMotion() } - - func setReducedMotion(_ reduced: Bool) { - for case let button as ToastActionButton in content.subviews { - button.reduceMotion = reduced - } - if reduced { cancelStatusMotion() } - } - @objc private func handleAccessibilityPressAction() -> Bool { guard spec.pressable, let onPress else { return false } onPress() @@ -643,115 +465,38 @@ final class NativeOverlayToastCardView: UIView { return ToastMetrics.actionsPaddingTop + rowHeight + paddingBottom } - private func shouldUseInlineAction() -> Bool { - guard spec.actions.count == 1, !spec.actionsAlignLeft, let action = spec.actions.first else { - return false - } - if action.label.count > ToastMetrics.inlineActionMaxLabel { return false } - if action.marginHorizontal != 0 || action.marginVertical != 0 { return false } - if let message = spec.message { - if message.paragraphs.count > 1 { return false } - let len = message.paragraphs.reduce(0) { sum, runs in - sum + runs.reduce(0) { $0 + $1.text.count } - } - if len > ToastMetrics.inlineActionMaxMessage { return false } - } - return true - } - - private func buildMessage(statusIcon: ToastIconView?) { - let iconView = statusIcon ?? spec.icon.map(ToastIconView.init(icon:)) - if statusIcon == nil { iconView.map(content.addSubview) } - if iconView?.statusTile != nil { messageStatusIcon = iconView } - stackExpansionAnchor = iconView + private func buildMessage() { + let iconView = spec.icon.map(ToastIconView.init(icon:)) + iconView.map(content.addSubview) let titleLabels = makeLabels(spec.title) let messageLabels = makeLabels(spec.message) let buttons = makeButtons() - let inlineCandidate = shouldUseInlineAction() - let minTextWidth = titleLabels.isEmpty && messageLabels.isEmpty ? 0 : ToastMetrics.inlineTextMinWidth let iconSize = spec.icon?.size ?? 0 - layoutBlocks.append { [weak self] width, heightCap in + layoutBlocks.append { [weak self] width in guard let self else { return 0 } - func measureText(width: CGFloat) -> (height: CGFloat, frames: [(UIView, CGFloat)]) { - var height: CGFloat = 0 - var frames: [(UIView, CGFloat)] = [] - for labels in [titleLabels, messageLabels] where !labels.isEmpty { - if !frames.isEmpty { height += ToastMetrics.messageTextGap } - for label in labels { - let labelHeight = label.fittedHeight(width: width) - frames.append((label, labelHeight)) - height += labelHeight - } - } - return (height, frames) - } - - let startX = iconView == nil ? ToastMetrics.noIconPaddingStart : iconSize + ToastMetrics.messageIconGap - var trailingWidth: CGFloat = 0 - var inlineSize = CGSize.zero - if inlineCandidate, let button = buttons.first { - button.isInline = true - let fitted = button.fittedSize - let requiredWidth = fitted.width + ToastMetrics.messageIconGap - let inlineTextWidth = width - startX - requiredWidth - let inlineHeight = max(fitted.height, ToastMetrics.inlineActionHeight) - var useInline = inlineTextWidth >= minTextWidth - if !useInline, let heightCap, inlineTextWidth > 0 { - let lowerTextHeight = measureText(width: max(0, width - startX)).height - let lowerButtonBottom = lowerTextHeight + ToastMetrics.messageTextGap - + ToastMetrics.actionsPaddingTop + fitted.height - if lowerButtonBottom > heightCap { - let inlineTextHeight = measureText(width: inlineTextWidth).height - useInline = max(inlineTextHeight, inlineHeight, iconSize, ToastMetrics.tileMinHeight) <= heightCap - } - } - button.isInline = useInline - if useInline { - inlineSize = CGSize(width: fitted.width, height: inlineHeight) - trailingWidth = requiredWidth + iconView?.frame = CGRect(x: 0, y: 0, width: iconSize, height: iconSize) + let x = iconView == nil ? 0 : iconSize + ToastMetrics.messageIconGap + let columnWidth = max(width - x, 0) + var y: CGFloat = 0 + var hasBlock = false + for labels in [titleLabels, messageLabels] where !labels.isEmpty { + if hasBlock { y += ToastMetrics.messageTextGap } + hasBlock = true + for label in labels { + let height = label.fittedHeight(width: columnWidth) + label.frame = CGRect(x: x, y: y, width: columnWidth, height: height) + y += height } - button.setNeedsLayout() } - let inlineAction = trailingWidth > 0 - let columnWidth = max(width - startX - trailingWidth, 0) - let measurement = measureText(width: columnWidth) - var textHeight = measurement.height - let frames = measurement.frames - var bottomActionsHeight: CGFloat = 0 - if !buttons.isEmpty && !inlineAction { - if !frames.isEmpty { textHeight += ToastMetrics.messageTextGap } - bottomActionsHeight = self.layoutActions( - buttons, x: startX, y: textHeight, width: columnWidth, + if !buttons.isEmpty { + if hasBlock { y += ToastMetrics.messageTextGap } + y += self.layoutActions( + buttons, x: x, y: y, width: columnWidth, paddingEnd: ToastMetrics.actionsPaddingEnd, paddingBottom: ToastMetrics.actionsPaddingBottom ) } - let columnTotalHeight = textHeight + bottomActionsHeight - let rowHeight = max(columnTotalHeight, iconSize, inlineSize.height, ToastMetrics.tileMinHeight) - let textStartY = bottomActionsHeight > 0 ? 0 : (rowHeight - textHeight) / 2 - var cursorY = textStartY - var previousGroupWasTitle = false - for (index, pair) in frames.enumerated() { - let isMessage = index >= titleLabels.count - if isMessage && previousGroupWasTitle { - cursorY += ToastMetrics.messageTextGap - } - pair.0.frame = CGRect(x: startX, y: cursorY, width: columnWidth, height: pair.1) - cursorY += pair.1 - previousGroupWasTitle = !isMessage - } - if let iconView { - iconView.frame = CGRect(x: 0, y: (rowHeight - iconSize) / 2, width: iconSize, height: iconSize) - } - if inlineAction, let button = buttons.first { - button.frame = CGRect( - x: width - inlineSize.width, - y: (rowHeight - inlineSize.height) / 2, - width: inlineSize.width, - height: inlineSize.height - ) - } - return rowHeight + return max(y, iconSize) } } @@ -761,7 +506,6 @@ final class NativeOverlayToastCardView: UIView { badge.layer.cornerRadius = spec.badgeSize / 2 badge.isUserInteractionEnabled = false content.addSubview(badge) - stackExpansionAnchor = badge let iconView = spec.icon.map(ToastIconView.init(icon:)) iconView.map(badge.addSubview) let titleLabels = makeLabels(spec.title) @@ -772,7 +516,7 @@ final class NativeOverlayToastCardView: UIView { let badgeSize = spec.badgeSize let iconSize = spec.icon?.size ?? 0 let imageSize = spec.image?.size ?? 0 - layoutBlocks.append { [weak self] width, _ in + layoutBlocks.append { [weak self] width in guard let self else { return 0 } badge.frame = CGRect(x: 0, y: 0, width: badgeSize, height: badgeSize) iconView?.frame = CGRect( @@ -803,23 +547,26 @@ final class NativeOverlayToastCardView: UIView { } /// Sizes the card for a content box of `contentWidth` and lays its content - /// out. Returns the card's natural size. Pass `applyBounds: false` when the - /// caller will animate height via `applyDisplayHeight(_:)`. + /// out. Returns the card's size. @discardableResult - func layoutCard(contentWidth: CGFloat, contentMaxHeight: CGFloat?, applyBounds: Bool = true) -> CGSize { - let heightCap = contentMaxHeight.flatMap { $0 > 0 ? $0 : nil } - let naturalHeight = layoutBlocks.reduce(CGFloat(0)) { $0 + $1(contentWidth, heightCap) } - let height = min(naturalHeight, heightCap ?? naturalHeight) + func layoutCard(contentWidth: CGFloat, contentMaxHeight: CGFloat?) -> CGSize { + var height = layoutBlocks.reduce(CGFloat(0)) { $0 + $1(contentWidth) } + if let contentMaxHeight, contentMaxHeight > 0 { + height = min(height, contentMaxHeight) + } let size = CGSize( width: contentWidth + 2 * ToastMetrics.cardPaddingHorizontal, height: height + 2 * ToastMetrics.cardPaddingVertical ) - naturalSize = size - if applyBounds || bounds.size == .zero || bounds.width != size.width { - applyDisplayHeight(size.height) - } else { - updateStackExpansionFrame() - } + bounds.size = size + surface.frame = CGRect(origin: .zero, size: size) + surface.layer.shadowPath = UIBezierPath( + roundedRect: surface.bounds, cornerRadius: ToastMetrics.cardRadius + ).cgPath + content.frame = CGRect( + x: ToastMetrics.cardPaddingHorizontal, y: ToastMetrics.cardPaddingVertical, + width: contentWidth, height: height + ) return size } } diff --git a/native-views/react-native-native-overlay/ios/NativeOverlayToastSpec.swift b/native-views/react-native-native-overlay/ios/NativeOverlayToastSpec.swift index bf040bdcf..d15163bec 100644 --- a/native-views/react-native-native-overlay/ios/NativeOverlayToastSpec.swift +++ b/native-views/react-native-native-overlay/ios/NativeOverlayToastSpec.swift @@ -142,55 +142,9 @@ struct NativeOverlayToastText { } } -struct NativeOverlayToastStatus { - struct Dot { let center: CGPoint; let radius: CGFloat } - struct Ring { let radius: CGFloat; let trackOpacity: Float; let arcFraction: CGFloat } - - let status: String - let color: UIColor - let backgroundColor: UIColor - let size: CGFloat - let strokeWidth: CGFloat - let contours: [[CGPoint]] - let dot: Dot? - let ring: Ring? - - init?(dict: [String: Any], size: CGFloat) { - guard let status = dict["status"] as? String, - let glyph = dict["glyph"] as? [String: Any], - let contours = glyph["contours"] as? [[[NSNumber]]] else { return nil } - self.status = status - self.size = size - color = NativeOverlayToastColor.parse(dict["color"]) ?? .white - backgroundColor = NativeOverlayToastColor.parse(dict["backgroundColor"]) ?? .clear - strokeWidth = toastNumber(glyph["strokeWidth"]) ?? 3 - self.contours = contours.map { contour in - contour.compactMap { point in - guard point.count == 2 else { return nil } - return CGPoint(x: point[0].doubleValue, y: point[1].doubleValue) - } - } - if let dot = glyph["dot"] as? [NSNumber], dot.count == 3 { - self.dot = Dot(center: CGPoint(x: dot[0].doubleValue, y: dot[1].doubleValue), radius: dot[2].doubleValue) - } else { - dot = nil - } - if let ring = glyph["ring"] as? [String: Any] { - self.ring = Ring( - radius: toastNumber(ring["radius"]) ?? 8, - trackOpacity: Float(toastNumber(ring["trackOpacity"]) ?? 0.25), - arcFraction: toastNumber(ring["arcFraction"]) ?? 0.25 - ) - } else { - ring = nil - } - } -} - enum NativeOverlayToastIcon { case named(name: String, colorString: String, color: UIColor, size: CGFloat) case spinner(color: UIColor, size: CGFloat) - case status(NativeOverlayToastStatus) case image(uri: String, size: CGFloat, radius: CGFloat) init?(json: Any?) { @@ -206,9 +160,6 @@ enum NativeOverlayToastIcon { ) case "spinner": self = .spinner(color: NativeOverlayToastColor.parse(dict["color"]) ?? .gray, size: size) - case "status": - guard let status = NativeOverlayToastStatus(dict: dict, size: size) else { return nil } - self = .status(status) case "image": guard let uri = dict["uri"] as? String else { return nil } self = .image(uri: uri, size: size, radius: toastNumber(dict["borderRadius"]) ?? 0) @@ -220,7 +171,6 @@ enum NativeOverlayToastIcon { var size: CGFloat { switch self { case let .named(_, _, _, size), let .spinner(_, size), let .image(_, size, _): return size - case let .status(status): return status.size } } } @@ -301,8 +251,7 @@ struct NativeOverlayToastSpec { layout = Layout(rawValue: dict["layout"] as? String ?? "") ?? .message duration = (dict["duration"] as? NSNumber)?.doubleValue ?? 5000 testID = dict["testID"] as? String - let statusIcon = layout == .message ? NativeOverlayToastIcon(json: dict["statusIcon"]) : nil - icon = statusIcon ?? NativeOverlayToastIcon(json: dict["icon"]) + icon = NativeOverlayToastIcon(json: dict["icon"]) title = NativeOverlayToastText(json: dict["title"]) message = NativeOverlayToastText(json: dict["message"]) actions = ((dict["actions"] as? [Any]) ?? []).compactMap(NativeOverlayToastAction.init(json:)) @@ -341,7 +290,6 @@ struct NativeOverlayToastItem { struct NativeOverlayToasterConfig { var cardColor: UIColor = .systemBackground - var cardBorderColor: UIColor? /// Width of the card's content box; nil derives it from the window. var contentWidth: CGFloat? var contentMaxHeight: CGFloat? @@ -356,7 +304,6 @@ struct NativeOverlayToasterConfig { guard let data = jsonString.data(using: .utf8), let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return } cardColor = NativeOverlayToastColor.parse(dict["cardColor"]) ?? .systemBackground - cardBorderColor = NativeOverlayToastColor.parse(dict["cardBorderColor"]) contentWidth = toastNumber(dict["contentWidth"]) contentMaxHeight = toastNumber(dict["contentMaxHeight"]) topObstruction = toastNumber(dict["topObstruction"]) ?? 0 diff --git a/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift b/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift index f2846d0a5..16f5a2e9a 100644 --- a/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift +++ b/native-views/react-native-native-overlay/ios/NativeOverlayToasterView.swift @@ -1,99 +1,43 @@ import React import UIKit +// The motion and gesture constants of the toaster this replaces. private enum ToasterMetrics { /// The first toast sits this far under the top safe-area inset. static let topOffset: CGFloat = 16 - static let gutter: CGFloat = 10 - static let visibleToasts: Int = 3 - static let stackScaleStep: CGFloat = 0.05 - static let enterFadeDuration: TimeInterval = 0.22 - static let exitDuration: TimeInterval = 0.2 - static let autoExitDuration: TimeInterval = 0.19 + static let gutter: CGFloat = 8 + static let animationDuration: TimeInterval = 0.3 static let obstructionDuration: TimeInterval = 0.22 - /// Keep leaving cards mounted long enough for the exit transition and close callback. - static let removeDelay: TimeInterval = 0.22 - /// Extra travel above the top edge for the resting-out position on enter. - static let enterOvershoot: CGFloat = 32 - static let hiddenScale: CGFloat = 0.96 - static let swipeExitScale: CGFloat = 0.98 - static let swipeExitMargin: CGFloat = 48 - static let autoExitOffset: CGFloat = 16 - static let autoExitScale: CGFloat = 0.95 - static let collapsedBackExitOffset: CGFloat = 12 - static let collapsedLeaveScale: CGFloat = 0.9 - static let fallbackHeight: CGFloat = 56 - static let swipeDistance: CGFloat = 64 - static let swipeFlickDistance: CGFloat = 20 - static let swipeFlickVelocity: CGFloat = 500 - static let swipeOpacityRange: CGFloat = 260 - static let swipeMinOpacity: CGFloat = 0.35 + /// A dismissed card stays in the list this long, so `close` is reported + /// when the previous renderer unmounted the card. + static let removeDelay: TimeInterval = 1 + /// Extra travel above the top edge for the resting-out position. + static let enterOvershoot: CGFloat = 50 + static let fallbackHeight: CGFloat = 50 + static let swipeDistance: CGFloat = 32 + static let swipeFlickDistance: CGFloat = 12 + static let swipeFlickVelocity: CGFloat = 600 + /// Dragging against the dismiss direction moves the card a quarter as far. + static let swipeResistance: CGFloat = 4 static let fallbackMargin: CGFloat = 64 static let fallbackMaxPageWidth: CGFloat = 640 - static let minSideInset: CGFloat = 16 } -/// Spring timing shared with Web and Android: mass 1, stiffness 460, damping 36. -private func toastSpringAnimator() -> UIViewPropertyAnimator { - let timing = UISpringTimingParameters( - mass: 1, stiffness: 460, damping: 36, initialVelocity: .zero - ) - return UIViewPropertyAnimator(duration: 0, timingParameters: timing) -} - -/// Brisk ease-out curve for interactive swipe exit and obstruction shifts. -private func toastExitAnimator(duration: TimeInterval = ToasterMetrics.exitDuration) -> UIViewPropertyAnimator { +/// Quadratic ease-in-out, the timing curve of the animations this replaces. +private func toastAnimator(duration: TimeInterval) -> UIViewPropertyAnimator { UIViewPropertyAnimator( duration: duration, timingParameters: UICubicTimingParameters( - controlPoint1: CGPoint(x: 0.32, y: 0.72), controlPoint2: CGPoint(x: 0, y: 1) - ) - ) -} - -/// Gentle ease-out curve for non-interactive timeout / programmatic exit. -private func toastAutoExitAnimator() -> UIViewPropertyAnimator { - UIViewPropertyAnimator( - duration: ToasterMetrics.autoExitDuration, - timingParameters: UICubicTimingParameters( - controlPoint1: CGPoint(x: 0.2, y: 0), controlPoint2: CGPoint(x: 0, y: 1) + controlPoint1: CGPoint(x: 0.455, y: 0.03), controlPoint2: CGPoint(x: 0.515, y: 0.955) ) ) } /// Lets touches that miss every card fall through to the windows below. private final class ToastPassthroughView: UIView { - var onOutsideTouch: (() -> Void)? - var onGeometryChanged: (() -> Void)? - private var lastLayoutSize: CGSize = .zero - - override func didMoveToSuperview() { - super.didMoveToSuperview() - lastLayoutSize = bounds.size - } - - override func layoutSubviews() { - super.layoutSubviews() - if lastLayoutSize != bounds.size { - lastLayoutSize = bounds.size - onGeometryChanged?() - } - } - - override func safeAreaInsetsDidChange() { - super.safeAreaInsetsDidChange() - onGeometryChanged?() - } - override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { let hit = super.hitTest(point, with: event) - if hit === self { - if event?.type == .touches { - onOutsideTouch?() - } - return nil - } - return hit + return hit === self ? nil : hit } } @@ -104,26 +48,20 @@ private final class ToastEntry { /// Parent of the card: carries the stack position, the card the drag. let slot: UIView = ToastPassthroughView() var leaving = false - var collapsedBackExit = false var reason = "programmatic" /// Seconds of lifetime left, counted while not paused. var remaining: TimeInterval? var startedAt: Date? var timer: Timer? var removal: Timer? - var pan: UIPanGestureRecognizer? var dragStart: CGFloat = 0 - var swipeExitSign: CGFloat = 1 - var lastTargetY: CGFloat? var dragged = false - var isPressed = false var entered = false - var lastActiveIndex = 0 - init(item: NativeOverlayToastItem, cardColor: UIColor, cardBorderColor: UIColor?) { + init(item: NativeOverlayToastItem, cardColor: UIColor) { id = item.spec.id self.item = item - card = NativeOverlayToastCardView(spec: item.spec, cardColor: cardColor, cardBorderColor: cardBorderColor) + card = NativeOverlayToastCardView(spec: item.spec, cardColor: cardColor) slot.addSubview(card) } } @@ -136,36 +74,15 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG private weak var hostView: UIView? private var window: UIWindow? /// Rides under whatever hangs from the top of the window. - private let stage = ToastPassthroughView() - private let cards = ToastPassthroughView() + private let stage: UIView = ToastPassthroughView() private var entries: [ToastEntry] = [] // newest first private var config = NativeOverlayToasterConfig() - private var expanded = false + private var pressedCount = 0 private var obstructionShift: CGFloat = 0 - private var activeEntries: [ToastEntry] { - entries.filter { !$0.leaving } - } - init(hostView: UIView) { self.hostView = hostView super.init() - stage.addSubview(cards) - stage.onGeometryChanged = { [weak self] in - guard let self, self.entries.contains(where: { $0.slot.superview != nil }) else { return } - self.layout(animated: false) - } - NotificationCenter.default.addObserver( - self, selector: #selector(layoutChanged), name: UIAccessibility.reduceMotionStatusDidChangeNotification, object: nil - ) - stage.onOutsideTouch = { [weak self] in - DispatchQueue.main.async { - guard let self, self.expanded else { return } - self.expanded = false - self.layout(animated: true) - self.syncTimers() - } - } NotificationCenter.default.addObserver( self, selector: #selector(layoutChanged), name: NativeOverlayKeyboard.didChange, object: nil ) @@ -189,7 +106,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG func sync(items: [NativeOverlayToastItem], config next: NativeOverlayToasterConfig) { let configChanged = next.contentWidth != config.contentWidth || next.contentMaxHeight != config.contentMaxHeight - || next.cardColor != config.cardColor || next.cardBorderColor != config.cardBorderColor + || next.cardColor != config.cardColor config = next let present = Set(items.map(\.spec.id)) // Cards the list no longer knows leave without ceremony. @@ -213,20 +130,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG continue } if entry.item.revision != item.revision || configChanged { - let settleStatus: Bool - if case let .status(status)? = item.spec.icon { - settleStatus = item.visible && entry.entered && !reduceMotion - && entry.item.generation != item.generation - && status.status != "loading" - } else { - settleStatus = false - } - entry.card.apply( - spec: item.spec, - cardColor: config.cardColor, - cardBorderColor: config.cardBorderColor, - settleStatus: settleStatus - ) + entry.card.apply(spec: item.spec, cardColor: config.cardColor) } if entry.item.generation != item.generation { // Shown again: the toast starts its lifetime over. @@ -248,11 +152,9 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG entries.forEach { entry in entry.timer?.invalidate() entry.removal?.invalidate() - entry.card.cancelStatusMotion() entry.slot.removeFromSuperview() } entries = [] - expanded = false releaseWindow() } @@ -280,8 +182,6 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG window = overlayWindow stage.frame = root.bounds stage.autoresizingMask = [.flexibleWidth, .flexibleHeight] - cards.frame = stage.bounds - cards.autoresizingMask = [.flexibleWidth, .flexibleHeight] root.addSubview(stage) return root } @@ -289,9 +189,6 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG private func releaseWindow() { guard let window else { return } stage.removeFromSuperview() - cards.layer.removeAllAnimations() - cards.transform = .identity - obstructionShift = 0 NativeOverlayWindowManager.shared.entryRemoved(from: window) self.window = nil } @@ -306,7 +203,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG // MARK: Cards private func add(_ item: NativeOverlayToastItem) { - let entry = ToastEntry(item: item, cardColor: config.cardColor, cardBorderColor: config.cardBorderColor) + let entry = ToastEntry(item: item, cardColor: config.cardColor) entry.remaining = lifetime(of: item.spec) entry.card.onAction = { [weak self, weak entry] actionId in guard let entry, !entry.leaving else { return } @@ -317,13 +214,12 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG self?.onEvent?(entry.id, entry.item.generation, "link", link) } entry.card.onPress = { [weak self, weak entry] in - guard let entry else { return } - self?.activate(entry) + guard let entry, !entry.leaving, entry.item.spec.pressable else { return } + self?.onEvent?(entry.id, entry.item.generation, "press", "") } let pan = UIPanGestureRecognizer(target: self, action: #selector(handlePan(_:))) pan.maximumNumberOfTouches = 1 pan.delegate = self - entry.pan = pan entry.card.addGestureRecognizer(pan) // Press and hold pauses every toast's lifetime. let press = UILongPressGestureRecognizer(target: self, action: #selector(handlePress(_:))) @@ -340,8 +236,8 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG private func attach(_ entry: ToastEntry) { guard ensureWindow() != nil else { return } - cards.addSubview(entry.slot) - entry.slot.alpha = 0 + stage.addSubview(entry.slot) + entry.card.alpha = 0 UIAccessibility.post(notification: .announcement, argument: entry.card.announcement) } @@ -351,50 +247,33 @@ 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) } - if reduceMotion { - remove(entry, 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() - } - if activeEntries.count <= 1 { - expanded = false } layout(animated: true) - syncTimers() } private func remove(_ entry: ToastEntry, report: Bool) { entry.timer?.invalidate() entry.removal?.invalidate() - entry.card.cancelStatusMotion() entry.slot.removeFromSuperview() entries.removeAll { $0 === entry } - if activeEntries.count <= 1 { - expanded = false - } if report { onEvent?(entry.id, entry.item.generation, "close", entry.reason) } if entries.isEmpty { - expanded = false + pressedCount = 0 releaseWindow() } } @@ -405,12 +284,9 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG layout(animated: true) } - private func contentWidth(availableWidth: CGFloat) -> CGFloat { - let requested = config.contentWidth.flatMap { $0.isFinite ? $0 : nil } - ?? availableWidth - ToasterMetrics.fallbackMargin - let maximum = ToasterMetrics.fallbackMaxPageWidth - ToasterMetrics.fallbackMargin - let available = availableWidth - 2 * (ToasterMetrics.minSideInset + NativeOverlayToastCardView.horizontalPadding) - return max(0, min(requested, maximum, available)) + private func contentWidth(in root: UIView) -> CGFloat { + config.contentWidth + ?? min(root.bounds.width, ToasterMetrics.fallbackMaxPageWidth) - ToasterMetrics.fallbackMargin } /// How far the whole stack rides down to rest under the top obstruction. @@ -428,18 +304,17 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG private func layout(animated: Bool) { guard let root = window?.rootViewController?.view, !entries.isEmpty else { return } + let width = contentWidth(in: root) let safe = root.safeAreaInsets - let availableWidth = root.bounds.width - safe.left - safe.right - let width = contentWidth(availableWidth: availableWidth) let top = safe.top + ToasterMetrics.topOffset let animate = animated && !reduceMotion let shift = computeObstructionShift(in: root) if shift != obstructionShift { obstructionShift = shift - let apply = { self.cards.transform = CGAffineTransform(translationX: 0, y: shift) } + let apply = { self.stage.transform = CGAffineTransform(translationX: 0, y: shift) } if animate { - let animator = toastExitAnimator(duration: ToasterMetrics.obstructionDuration) + let animator = toastAnimator(duration: ToasterMetrics.obstructionDuration) animator.addAnimations(apply) animator.startAnimation() } else { @@ -447,161 +322,39 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG } } - let active = activeEntries - if active.count <= 1 { - expanded = false - } - let isCollapsed = !expanded && active.count > 1 - - // Measure every card's natural size first so collapsed back cards know frontHeight. - for entry in entries { - entry.card.layoutCard( - contentWidth: width, contentMaxHeight: config.contentMaxHeight, applyBounds: false - ) - } - let frontHeight = active.first?.card.naturalSize.height ?? ToasterMetrics.fallbackHeight - - // Keep newest card at the highest z-order. + // Oldest at the top, newest under it: a toast keeps its place when a + // newer one arrives and moves up when an older one leaves. + var offset: CGFloat = 0 for entry in entries.reversed() { - cards.bringSubviewToFront(entry.slot) - } - - var activeIndex = 0 - var expandedOffset: CGFloat = 0 - for entry in entries { - let naturalSize = entry.card.naturalSize - let x = safe.left + (availableWidth - naturalSize.width) / 2 - let displayHeight: CGFloat - let targetY: CGFloat - let targetScale: CGFloat - let targetAlpha: CGFloat - let hideBody: Bool - let interactive: Bool - - let swipeExit = entry.leaving && entry.reason == "swipe" - var targetCardTransform: CGAffineTransform? - - if entry.leaving { - displayHeight = entry.card.bounds.height > 0 ? entry.card.bounds.height : naturalSize.height - let collapsedBackExit = entry.collapsedBackExit - let baseY = entry.lastTargetY ?? top - if swipeExit { - targetY = baseY - targetScale = ToasterMetrics.swipeExitScale - let exitDistance = max( - naturalSize.width + ToasterMetrics.swipeExitMargin, - root.bounds.width * 0.5 + naturalSize.width * 0.5 - ) - targetCardTransform = CGAffineTransform( - translationX: entry.swipeExitSign * exitDistance, y: 0 - ) - } else if collapsedBackExit { - targetY = baseY - ToasterMetrics.collapsedBackExitOffset - targetScale = ToasterMetrics.collapsedLeaveScale - } else { - targetY = baseY - ToasterMetrics.autoExitOffset - targetScale = ToasterMetrics.autoExitScale - } - targetAlpha = 0 - hideBody = collapsedBackExit - interactive = false - } else { - let index = activeIndex - entry.lastActiveIndex = index - activeIndex += 1 - let isVisible = index < ToasterMetrics.visibleToasts - if isCollapsed { - displayHeight = index == 0 ? naturalSize.height : frontHeight - targetY = top + CGFloat(min(index, ToasterMetrics.visibleToasts)) * ToasterMetrics.gutter - targetScale = max(0.85, 1 - CGFloat(min(index, ToasterMetrics.visibleToasts)) * ToasterMetrics.stackScaleStep) - hideBody = index > 0 - } else { - displayHeight = naturalSize.height - targetY = top + expandedOffset - targetScale = 1 - hideBody = false - } - entry.lastTargetY = targetY - if isVisible { - expandedOffset += naturalSize.height + ToasterMetrics.gutter - } - targetAlpha = isVisible ? 1 : 0 - interactive = isVisible + let size = entry.card.layoutCard( + contentWidth: width, contentMaxHeight: config.contentMaxHeight + ) + let x = safe.left + (root.bounds.width - safe.left - safe.right - size.width) / 2 + // Where the card rests before it enters and after it leaves. + let hidden = -(size.height > 0 ? size.height : ToasterMetrics.fallbackHeight) + - safe.top - ToasterMetrics.enterOvershoot + let targetY = top + (entry.leaving ? hidden : offset) + let targetAlpha: CGFloat = entry.leaving ? 0 : 1 + if !entry.leaving { + offset += size.height + ToasterMetrics.gutter } - - let displaySize = CGSize(width: naturalSize.width, height: displayHeight) - let frame = CGRect(x: x, y: targetY, width: displaySize.width, height: displaySize.height) - let targetTransform = targetScale == 1 - ? CGAffineTransform.identity - : CGAffineTransform(scaleX: targetScale, y: targetScale) - let wasEntered = entry.entered - - if !wasEntered { + let frame = CGRect(x: x, y: targetY, width: size.width, height: size.height) + if !entry.entered { entry.entered = true - let hidden = -(displayHeight > 0 ? displayHeight : ToasterMetrics.fallbackHeight) - - safe.top - ToasterMetrics.enterOvershoot - entry.card.applyDisplayHeight(displayHeight) - entry.card.setBodyHidden(hideBody, animated: false) - entry.slot.transform = .identity - entry.slot.bounds.size = displaySize - entry.card.center = CGPoint(x: displaySize.width / 2, y: displaySize.height / 2) - entry.slot.center = CGPoint(x: x + displaySize.width / 2, y: top + hidden + displaySize.height / 2) - entry.slot.transform = CGAffineTransform( - scaleX: ToasterMetrics.hiddenScale, y: ToasterMetrics.hiddenScale - ) - if animate && !entry.leaving { entry.card.animateMessageStatusEntrance() } - } else { - entry.card.setBodyHidden(hideBody, animated: animate) + entry.slot.frame = CGRect(x: x, y: top + hidden, width: size.width, height: size.height) } - - entry.slot.isUserInteractionEnabled = interactive - entry.slot.accessibilityElementsHidden = !interactive - entry.card.canExpandStack = isCollapsed && entry === active.first - let canSwipe = interactive && !hideBody - if entry.pan?.isEnabled != canSwipe { - if !canSwipe && entry.dragged && !entry.leaving { - settle(entry.card) - entry.dragged = false - } - entry.pan?.isEnabled = canSwipe - } - entry.card.setReducedMotion(reduceMotion) - if !entry.leaving && !reduceMotion { entry.card.animateMessageStatusRing() } - - let applyGeometry = { - entry.slot.center = CGPoint(x: frame.midX, y: frame.midY) - entry.slot.bounds.size = displaySize - entry.slot.transform = targetTransform - entry.card.applyDisplayHeight(displayHeight) - entry.card.center = CGPoint(x: displaySize.width / 2, y: displaySize.height / 2) - if let targetCardTransform { - entry.card.transform = targetCardTransform - } + entry.slot.bounds.size = size + entry.card.center = CGPoint(x: size.width / 2, y: size.height / 2) + let apply = { + entry.slot.frame = frame + entry.card.alpha = targetAlpha } - if animate { - if entry.leaving { - let animator = swipeExit ? toastExitAnimator() : toastAutoExitAnimator() - animator.addAnimations { - applyGeometry() - entry.slot.alpha = targetAlpha - } - animator.startAnimation() - } else { - let spring = toastSpringAnimator() - spring.addAnimations(applyGeometry) - spring.startAnimation() - if entry.slot.alpha != targetAlpha { - let fade = UIViewPropertyAnimator( - duration: ToasterMetrics.enterFadeDuration, curve: .easeOut - ) - fade.addAnimations { entry.slot.alpha = targetAlpha } - fade.startAnimation() - } - } + let animator = toastAnimator(duration: ToasterMetrics.animationDuration) + animator.addAnimations(apply) + animator.startAnimation() } else { - applyGeometry() - entry.slot.alpha = targetAlpha + apply() } } } @@ -609,7 +362,7 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG // MARK: Timers private func syncTimers() { - let paused = expanded || entries.contains { !$0.leaving && $0.isPressed } + let paused = pressedCount > 0 for entry in entries where !entry.leaving { guard let remaining = entry.remaining else { continue } if paused { @@ -635,14 +388,6 @@ 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 - } - func gestureRecognizer( _ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer @@ -652,21 +397,18 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if gestureRecognizer is UITapGestureRecognizer { - guard let entry = entry(for: gestureRecognizer) else { return false } - let canExpand = !expanded && activeEntries.count > 1 - if !canExpand && !entry.item.spec.pressable { return false } + guard let entry = entry(for: gestureRecognizer), entry.item.spec.pressable else { return false } if touch.view is UIControl || touch.view is ToastTextLabel { return false } } return true } @objc private func handlePress(_ gesture: UILongPressGestureRecognizer) { - guard let entry = entry(for: gesture) else { return } switch gesture.state { case .began: - entry.isPressed = true + pressedCount += 1 case .ended, .cancelled, .failed: - entry.isPressed = false + pressedCount = max(0, pressedCount - 1) default: return } @@ -674,50 +416,35 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG } @objc private func handleTap(_ gesture: UITapGestureRecognizer) { - guard let entry = entry(for: gesture), !entry.dragged else { return } - activate(entry) - } - - private func activate(_ entry: ToastEntry) { - guard !entry.leaving else { return } - if !expanded && activeEntries.count > 1 { - expanded = true - layout(animated: true) - syncTimers() - return - } - guard entry.item.spec.pressable else { return } + guard let entry = entry(for: gesture), !entry.leaving, !entry.dragged, + entry.item.spec.pressable else { return } onEvent?(entry.id, entry.item.generation, "press", "") } @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 + // Toasts land at the top, so the dismiss direction is up. let translation = gesture.translation(in: stage) switch gesture.state { case .began: card.layer.removeAllAnimations() - entry.dragStart = card.transform.tx + entry.dragStart = card.transform.ty entry.dragged = true case .changed: - let dragX = entry.dragStart + translation.x - card.transform = CGAffineTransform(translationX: dragX, y: 0) - card.alpha = max( - ToasterMetrics.swipeMinOpacity, - 1 - abs(dragX) / ToasterMetrics.swipeOpacityRange - ) + let drag = translation.y <= 0 + ? entry.dragStart + translation.y + : entry.dragStart + translation.y / ToasterMetrics.swipeResistance + card.transform = CGAffineTransform(translationX: 0, y: drag) case .ended: - let totalX = entry.dragStart + translation.x - let distance = abs(totalX) - let velocity = gesture.velocity(in: stage).x * (totalX >= 0 ? 1 : -1) + let distance = -translation.y + let velocity = -gesture.velocity(in: stage).y let dismissed = - distance >= ToasterMetrics.swipeDistance - || (distance >= ToasterMetrics.swipeFlickDistance - && velocity >= ToasterMetrics.swipeFlickVelocity) + translation.y < 0 && abs(distance) > abs(translation.x) + && (distance >= ToasterMetrics.swipeDistance + || (distance >= ToasterMetrics.swipeFlickDistance + && velocity >= ToasterMetrics.swipeFlickVelocity)) if dismissed { - entry.swipeExitSign = totalX >= 0 ? 1 : -1 dismiss(entry, reason: "swipe", report: true) } else { settle(card) @@ -734,14 +461,10 @@ final class NativeOverlayToastPresenter: NSObject, NativeOverlayWindowOwner, UIG private func settle(_ card: UIView) { guard !reduceMotion else { card.transform = .identity - card.alpha = 1 return } - let animator = toastSpringAnimator() - animator.addAnimations { - card.transform = .identity - card.alpha = 1 - } + let animator = toastAnimator(duration: ToasterMetrics.animationDuration) + animator.addAnimations { card.transform = .identity } animator.startAnimation() } } diff --git a/native-views/react-native-native-overlay/ios/ToastStatusTileView.swift b/native-views/react-native-native-overlay/ios/ToastStatusTileView.swift deleted file mode 100644 index 290f36e1d..000000000 --- a/native-views/react-native-native-overlay/ios/ToastStatusTileView.swift +++ /dev/null @@ -1,309 +0,0 @@ -import UIKit - -private enum ToastStatusMotion { - static let easeOut = CAMediaTimingFunction(name: .easeOut) - static let easeIn = CAMediaTimingFunction(name: .easeIn) - static let tintEase = CAMediaTimingFunction(controlPoints: 0.4, 0, 0.2, 1) - - static func spring( - _ keyPath: String, in layer: CALayer, from: Any, to: Any, - stiffness: CGFloat, damping: CGFloat, delay: TimeInterval = 0 - ) { - let animation = CASpringAnimation(keyPath: keyPath) - animation.mass = 1 - animation.stiffness = stiffness - animation.damping = damping - animation.fromValue = from - animation.toValue = to - animation.duration = animation.settlingDuration - animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) + delay - animation.fillMode = .backwards - layer.add(animation, forKey: keyPath) - } - - static func basic( - _ keyPath: String, in layer: CALayer, from: Any, to: Any, - duration: TimeInterval, delay: TimeInterval = 0, timing: CAMediaTimingFunction - ) { - let animation = CABasicAnimation(keyPath: keyPath) - animation.fromValue = from - animation.toValue = to - animation.duration = duration - animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) + delay - animation.timingFunction = timing - animation.fillMode = .backwards - layer.add(animation, forKey: keyPath) - } - - static func scale( - in layer: CALayer, values: [Double], times: [NSNumber], - duration: TimeInterval, delay: TimeInterval, timings: [CAMediaTimingFunction] - ) { - let animation = CAKeyframeAnimation(keyPath: "transform.scale") - animation.values = values - animation.keyTimes = times - animation.duration = duration - animation.beginTime = layer.convertTime(CACurrentMediaTime(), from: nil) + delay - animation.timingFunctions = timings - animation.fillMode = .backwards - layer.add(animation, forKey: "transform.scale") - } - - static func withoutActions(_ update: () -> Void) { - CATransaction.begin() - CATransaction.setDisableActions(true) - update() - CATransaction.commit() - } -} - -final class ToastStatusTileView: UIView { - private var status: NativeOverlayToastStatus - private var glyph: ToastStatusGlyphView - private var departing: ToastStatusGlyphView? - private var removal: DispatchWorkItem? - private var tintUntil: TimeInterval = 0 - - init(status: NativeOverlayToastStatus) { - self.status = status - glyph = ToastStatusGlyphView(status) - super.init(frame: .zero) - isUserInteractionEnabled = false - clipsToBounds = true - layer.cornerCurve = .continuous - layer.backgroundColor = status.backgroundColor.cgColor - addSubview(glyph) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - - override func layoutSubviews() { - super.layoutSubviews() - ToastStatusMotion.withoutActions { - layer.cornerRadius = bounds.width * 11 / 36 - glyph.frame = bounds - departing?.frame = bounds - } - } - - func enter() { - // Critically damped tile spring: mass 1, stiffness 620, damping 50. - ToastStatusMotion.spring( - "opacity", in: layer, from: 0, to: 1, stiffness: 620, damping: 50, delay: 0.11 - ) - ToastStatusMotion.spring( - "transform.scale", in: layer, from: 0.85, to: 1, stiffness: 620, damping: 50, delay: 0.11 - ) - glyph.pop(after: 0.155) - } - - func apply(_ next: NativeOverlayToastStatus, settle: Bool) { - let previous = status - status = next - if previous.status == next.status { - glyph.setColor(next.color) - if previous.backgroundColor != next.backgroundColor { - tint(over: max(0, tintUntil - CACurrentMediaTime())) - } - return - } - - let old = glyph - let canSettle = settle && previous.status != next.status - let oldAlpha = opacity(of: old.layer) - let oldScale = scale(of: old.layer, initial: 0.4) - let tileAlpha = opacity(of: layer) - let tileScale = scale(of: layer, initial: 0.85) - let delay: TimeInterval = canSettle && oldAlpha > 0 ? 0.09 : 0 - removeDeparting() - glyph = ToastStatusGlyphView(next) - glyph.frame = bounds - addSubview(glyph) - - if delay > 0 { - departing = old - ToastStatusMotion.withoutActions { - old.layer.opacity = 0 - old.layer.transform = CATransform3DMakeScale(0.5, 0.5, 1) - } - ToastStatusMotion.basic( - "opacity", in: old.layer, from: oldAlpha, to: 0, duration: delay, timing: ToastStatusMotion.easeIn - ) - ToastStatusMotion.basic( - "transform.scale", in: old.layer, from: oldScale, to: 0.5, duration: delay, timing: ToastStatusMotion.easeIn - ) - let removal = DispatchWorkItem { [weak self] in self?.removeDeparting() } - self.removal = removal - DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: removal) - } else { - old.stopRing() - old.removeFromSuperview() - } - - guard canSettle else { - cancelMotion() - return - } - tint(over: 0.14) - ToastStatusMotion.basic( - "opacity", in: layer, from: tileAlpha, to: 1, duration: 0.104, delay: delay, timing: ToastStatusMotion.easeOut - ) - ToastStatusMotion.scale( - in: layer, values: [tileScale, 1.07, 1], times: [0, 0.4, 1], duration: 0.26, delay: delay, - timings: [ToastStatusMotion.easeOut, ToastStatusMotion.easeOut] - ) - glyph.pop(after: delay) - } - - private func opacity(of layer: CALayer) -> Float { - layer.presentation()?.opacity ?? (layer.animation(forKey: "opacity") == nil ? layer.opacity : 0) - } - - private func scale(of layer: CALayer, initial: Double) -> Double { - if let presentation = layer.presentation() { - return Double(presentation.transform.m11) - } - return layer.animation(forKey: "transform.scale") == nil ? 1 : initial - } - - private func tint(over duration: TimeInterval) { - let from = layer.presentation()?.backgroundColor ?? layer.backgroundColor - let target = status.backgroundColor.cgColor - ToastStatusMotion.withoutActions { layer.backgroundColor = target } - if duration > 0, let from { - tintUntil = CACurrentMediaTime() + duration - ToastStatusMotion.basic( - "backgroundColor", in: layer, from: from, to: target, duration: duration, timing: ToastStatusMotion.tintEase - ) - } - } - - func startRing() { glyph.startRing() } - - func cancelMotion() { - layer.removeAllAnimations() - removeDeparting() - glyph.cancelMotion() - tintUntil = 0 - tint(over: 0) - } - - private func removeDeparting() { - removal?.cancel() - removal = nil - departing?.stopRing() - departing?.removeFromSuperview() - departing = nil - } -} - -private final class ToastStatusGlyphView: UIView { - private let art = CALayer() - private let unitBounds = CGRect(x: 0, y: 0, width: 24, height: 24) - private var contours: [CAShapeLayer] = [] - private var dot: CAShapeLayer? - private var track: CAShapeLayer? - private var arc: CAShapeLayer? - - init(_ status: NativeOverlayToastStatus) { - super.init(frame: .zero) - art.bounds = unitBounds - layer.addSublayer(art) - for points in status.contours { - guard let first = points.first else { continue } - let path = UIBezierPath() - path.move(to: first) - points.dropFirst().forEach { path.addLine(to: $0) } - contours.append(shape(path.cgPath, width: status.strokeWidth)) - } - if let dot = status.dot { - let box = CGRect( - x: dot.center.x - dot.radius, y: dot.center.y - dot.radius, - width: 2 * dot.radius, height: 2 * dot.radius - ) - self.dot = shape(UIBezierPath(ovalIn: box).cgPath, width: 0) - } - if let ring = status.ring { - let center = CGPoint(x: 12, y: 12) - let path = UIBezierPath( - arcCenter: center, radius: ring.radius, startAngle: -.pi / 2, - endAngle: 3 * .pi / 2, clockwise: true - ) - let track = shape(path.cgPath, width: status.strokeWidth) - track.opacity = ring.trackOpacity - self.track = track - let arc = shape(path.cgPath, width: status.strokeWidth) - arc.strokeEnd = ring.arcFraction - self.arc = arc - } - setColor(status.color) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } - - override func layoutSubviews() { - super.layoutSubviews() - ToastStatusMotion.withoutActions { - let scale = min(bounds.width, bounds.height) / 48 - art.position = CGPoint(x: bounds.midX, y: bounds.midY) - art.setAffineTransform(CGAffineTransform(scaleX: scale, y: scale)) - } - } - - private func shape(_ path: CGPath, width: CGFloat) -> CAShapeLayer { - let shape = CAShapeLayer() - shape.frame = unitBounds - shape.path = path - shape.fillColor = nil - shape.lineWidth = width - shape.lineCap = .round - shape.lineJoin = .round - art.addSublayer(shape) - return shape - } - - func setColor(_ color: UIColor) { - ToastStatusMotion.withoutActions { - contours.forEach { $0.strokeColor = color.cgColor } - dot?.fillColor = color.cgColor - track?.strokeColor = color.cgColor - arc?.strokeColor = color.cgColor - } - } - - func pop(after delay: TimeInterval) { - // Snappy POP spring: mass 1, stiffness 920, damping 40 (same ~6.4% overshoot, ~35% faster). - ToastStatusMotion.spring( - "transform.scale", in: layer, from: 0.4, to: 1, stiffness: 920, damping: 40, delay: delay - ) - ToastStatusMotion.spring( - "opacity", in: layer, from: 0, to: 1, stiffness: 920, damping: 40, delay: delay - ) - contours.forEach { contour in - ToastStatusMotion.basic( - "strokeEnd", in: contour, from: 0, to: 1, duration: 0.18, delay: delay + 0.055, - timing: ToastStatusMotion.easeOut - ) - } - } - - func startRing() { - guard let arc, arc.animation(forKey: "spin") == nil else { return } - let animation = CABasicAnimation(keyPath: "transform.rotation.z") - animation.fromValue = 0 - animation.toValue = 2 * Double.pi - animation.duration = 0.85 - animation.repeatCount = .infinity - arc.add(animation, forKey: "spin") - } - - func stopRing() { arc?.removeAnimation(forKey: "spin") } - - func cancelMotion() { - layer.removeAllAnimations() - contours.forEach { $0.removeAllAnimations() } - stopRing() - } -} 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..1ed8ae090 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 @@ -160,11 +160,11 @@ test('hovering a single toast pauses its timer without fanning out', () => { test('pointercancel clears interaction state and resumes timers without swipe dismissal', () => { store.show(message('a', { duration: 1000 })); const card = cards()[0]!; - dispatchPointer(card, 'pointerdown', { clientX: 200, clientY: 200 }); - dispatchPointer(card, 'pointermove', { clientX: 270, clientY: 200 }); + dispatchPointer(card, 'pointerdown'); + dispatchPointer(card, 'pointermove', { clientY: 40 }); jest.advanceTimersByTime(2000); expect(card.getAttribute('data-removed')).toBe('false'); - dispatchPointer(card, 'pointercancel', { clientX: 270, clientY: 200 }); + dispatchPointer(card, 'pointercancel'); expect(card.getAttribute('data-removed')).toBe('false'); expect(card.getAttribute('data-swiping')).toBe('false'); jest.advanceTimersByTime(999); @@ -316,9 +316,9 @@ test('top toasts rest under a top obstruction', () => { const list = document.querySelector( '[data-onekey-toast-toaster]' ); - expect(list?.style.getPropertyValue('--toast-obstruction-top')).toBe('128px'); + expect(list?.style.top).toBe('128px'); store.configure({ topObstruction: 0 }); - expect(list?.style.getPropertyValue('--toast-obstruction-top')).toBe(''); + expect(list?.style.top).toBe(''); }); test('with no renderer a dismiss removes the toast at once', () => { @@ -557,16 +557,14 @@ function dispatchPointer( type: string, init: Record = {} ) { - const { timeStamp = performance.now(), ...pointer } = init; const event = new Event(type, { bubbles: true, cancelable: true }); - Object.defineProperty(event, 'timeStamp', { value: timeStamp }); Object.assign(event, { pointerId: 1, pointerType: 'mouse', button: 0, clientX: 0, clientY: 0, - ...pointer, + ...init, }); target.dispatchEvent(event); } @@ -589,10 +587,10 @@ test('dragging out of a toast and releasing clears hover after resetting data-sw dispatchPointer(list, 'pointerenter'); dispatchPointer(card, 'pointerdown', { clientX: 200, clientY: 200 }); - dispatchPointer(card, 'pointermove', { clientX: 215, clientY: 200 }); + dispatchPointer(card, 'pointermove', { clientX: 200, clientY: 215 }); expect(card.getAttribute('data-swiping')).toBe('true'); jest.advanceTimersByTime(200); - dispatchPointer(card, 'pointerup', { clientX: 215, clientY: 200 }); + dispatchPointer(card, 'pointerup', { clientX: 200, clientY: 215 }); expect(card.getAttribute('data-swiping')).toBe('false'); expect(card.style.getPropertyValue('--swipe-amount')).toBe('0px'); @@ -603,31 +601,28 @@ 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('single-direction swipe dismisses away from the anchored edge on wide and narrow positions', () => { const onWideClose = jest.fn(); store.configure({ position: 'bottom-right' }); store.show(message('wide', { duration: 5000 }), { onClose: onWideClose }); const wideCard = cards()[0]!; - // Vertical drag on bottom-right does not start a swipe or dismiss. + // Upward drag on bottom-right does not move or dismiss. dispatchPointer(wideCard, 'pointerdown', { clientX: 200, clientY: 200 }); - dispatchPointer(wideCard, 'pointermove', { clientX: 200, clientY: 280 }); + dispatchPointer(wideCard, 'pointermove', { clientX: 200, clientY: 150 }); expect(wideCard.getAttribute('data-swiping')).toBe('false'); - dispatchPointer(wideCard, 'pointerup', { clientX: 200, clientY: 280 }); + dispatchPointer(wideCard, 'pointerup', { clientX: 200, clientY: 150 }); expect(wideCard.getAttribute('data-removed')).toBe('false'); - // Horizontal swipe right after slight vertical jitter dismisses to the right. + // Downward swipe after initial horizontal jitter still dismisses. dispatchPointer(wideCard, 'pointerdown', { clientX: 200, clientY: 200 }); - dispatchPointer(wideCard, 'pointermove', { clientX: 201, clientY: 204 }); + dispatchPointer(wideCard, 'pointermove', { clientX: 196, clientY: 201 }); expect(wideCard.style.getPropertyValue('--swipe-amount')).toBe('0px'); - dispatchPointer(wideCard, 'pointermove', { clientX: 268, clientY: 204 }); - expect(wideCard.style.getPropertyValue('--swipe-amount')).toBe('68px'); - dispatchPointer(wideCard, 'pointermove', { clientX: 272, clientY: 240 }); - expect(wideCard.style.getPropertyValue('--swipe-amount')).toBe('72px'); - dispatchPointer(wideCard, 'pointerup', { clientX: 272, clientY: 240 }); - expect( - parseFloat(wideCard.style.getPropertyValue('--swipe-exit-x')) - ).toBeGreaterThan(0); + dispatchPointer(wideCard, 'pointermove', { clientX: 196, clientY: 228 }); + expect(wideCard.style.getPropertyValue('--swipe-amount')).toBe('28px'); + dispatchPointer(wideCard, 'pointermove', { clientX: 241, clientY: 230 }); + expect(wideCard.style.getPropertyValue('--swipe-amount')).toBe('30px'); + dispatchPointer(wideCard, 'pointerup', { clientX: 241, clientY: 230 }); jest.advanceTimersByTime(200); expect(onWideClose).toHaveBeenCalledWith('swipe'); @@ -658,27 +653,26 @@ 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. + // Downward drag on top-center does not move or dismiss; upward swipe dismisses. dispatchPointer(narrowFront, 'pointerdown', { pointerType: 'touch', clientX: 180, - clientY: 90, + clientY: 40, }); dispatchPointer(narrowFront, 'pointermove', { pointerType: 'touch', clientX: 180, - clientY: 20, + clientY: 90, }); expect(narrowFront.style.getPropertyValue('--swipe-amount')).toBe('0px'); dispatchPointer(narrowFront, 'pointerup', { pointerType: 'touch', clientX: 180, - clientY: 20, + clientY: 90, }); expect(narrowFront.getAttribute('data-removed')).toBe('false'); expect(narrowFront.getAttribute('data-expanded')).toBe('false'); - // Horizontal swipe left dismisses to the left. dispatchPointer(narrowFront, 'pointerdown', { pointerType: 'touch', clientX: 180, @@ -686,18 +680,15 @@ test('horizontal swipe dismisses left or right on wide and narrow positions whil }); dispatchPointer(narrowFront, 'pointermove', { pointerType: 'touch', - clientX: 110, - clientY: 60, + clientX: 180, + clientY: 30, }); - expect(narrowFront.style.getPropertyValue('--swipe-amount')).toBe('-70px'); + expect(narrowFront.style.getPropertyValue('--swipe-amount')).toBe('-30px'); dispatchPointer(narrowFront, 'pointerup', { pointerType: 'touch', - clientX: 110, - clientY: 60, + clientX: 180, + clientY: 30, }); - expect( - parseFloat(narrowFront.style.getPropertyValue('--swipe-exit-x')) - ).toBeLessThan(0); jest.advanceTimersByTime(200); expect(onNarrowClose).toHaveBeenCalledWith('swipe'); }); @@ -736,294 +727,14 @@ test('an unfinished touch drag does not pause a single toast after release', () expect(onClose).toHaveBeenCalledWith('timeout'); }); -test('dragging back within threshold cancels a recognized horizontal swipe', () => { +test('dragging back past the anchor cancels a recognized swipe', () => { store.show(message('a', { position: 'top-center' })); const card = cards()[0]!; - dispatchPointer(card, 'pointerdown', { clientX: 200, clientY: 100 }); - dispatchPointer(card, 'pointermove', { clientX: 160, clientY: 100 }); + dispatchPointer(card, 'pointerdown', { clientY: 100 }); + dispatchPointer(card, 'pointermove', { clientY: 70 }); expect(card.getAttribute('data-swiping')).toBe('true'); - jest.advanceTimersByTime(200); - dispatchPointer(card, 'pointermove', { clientX: 196, clientY: 100 }); - expect(card.style.getPropertyValue('--swipe-amount')).toBe('-4px'); - dispatchPointer(card, 'pointerup', { clientX: 196, clientY: 100 }); - expect(card.getAttribute('data-removed')).toBe('false'); - expect(card.style.getPropertyValue('--swipe-amount')).toBe('0px'); -}); - -test('touch jitter on a collapsed back card still expands the stack and resumes timers', () => { - const onBackClose = jest.fn(); - store.configure({ position: 'top-center' }); - store.show(message('back', { duration: 1000 }), { onClose: onBackClose }); - store.show(message('front', { duration: 1000 })); - const backCard = cards()[1]!; - document.elementFromPoint = jest.fn(() => backCard); - - dispatchPointer(backCard, 'pointerdown', { - pointerType: 'touch', - clientX: 180, - clientY: 60, - }); - dispatchPointer(backCard, 'pointermove', { - pointerType: 'touch', - clientX: 181, - clientY: 60, - }); - dispatchPointer(backCard, 'pointerup', { - pointerType: 'touch', - clientX: 181, - clientY: 60, - }); - - expect(backCard.getAttribute('data-expanded')).toBe('true'); - // Collapse by tapping outside, then confirm timers are not frozen. - dispatchPointer(document.body, 'pointerdown', { - pointerType: 'touch', - clientX: 10, - clientY: 500, - }); - expect(backCard.getAttribute('data-expanded')).toBe('false'); - jest.advanceTimersByTime(1200); - expect(onBackClose).toHaveBeenCalledWith('timeout'); -}); - -test('short horizontal flick dismisses even after a stationary hold', () => { - const onClose = jest.fn(); - store.configure({ position: 'top-center' }); - store.show(message('held-flick', { duration: 5000 }), { onClose }); - const card = cards()[0]!; - - dispatchPointer(card, 'pointerdown', { - pointerType: 'touch', - clientX: 200, - clientY: 60, - }); - jest.advanceTimersByTime(600); - dispatchPointer(card, 'pointermove', { - pointerType: 'touch', - clientX: 222, - clientY: 60, - }); - jest.advanceTimersByTime(15); - dispatchPointer(card, 'pointermove', { - pointerType: 'touch', - clientX: 240, - clientY: 60, - }); - jest.advanceTimersByTime(15); - dispatchPointer(card, 'pointerup', { - pointerType: 'touch', - clientX: 240, - clientY: 60, - }); - - jest.advanceTimersByTime(200); - expect(onClose).toHaveBeenCalledWith('swipe'); -}); - -test.each([ - ['slow events delivered together', 108, 130, 660, false], - ['fast reversal toward the origin', 149, 121, 620, false], - ['fast motion toward the exit', 111, 138, 620, true], -] as const)( - 'short swipe uses event time and signed velocity for %s', - (_, firstX, lastX, lastAt, dismisses) => { - const onDismiss = jest.fn(); - store.show(message('timed-flick', { duration: 5000 }), { onDismiss }); - const card = cards()[0]!; - dispatchPointer(card, 'pointerdown', { clientX: 100, timeStamp: 1 }); - dispatchPointer(card, 'pointermove', { clientX: firstX, timeStamp: 600 }); - dispatchPointer(card, 'pointermove', { clientX: lastX, timeStamp: lastAt }); - dispatchPointer(card, 'pointerup', { - clientX: lastX, - timeStamp: lastAt + 5, - }); - expect(onDismiss.mock.calls).toEqual(dismisses ? [['swipe']] : []); - } -); - -test('a slow short drag after a stationary hold settles without dismissing', () => { - const onDismiss = jest.fn(); - store.show(message('held-slow-drag'), { onDismiss }); - const card = cards()[0]!; - - dispatchPointer(card, 'pointerdown', { - pointerType: 'touch', - clientX: 200, - clientY: 60, - }); - jest.advanceTimersByTime(600); - for (const clientX of [203, 206, 209, 230]) { - jest.advanceTimersByTime(80); - dispatchPointer(card, 'pointermove', { - pointerType: 'touch', - clientX, - clientY: 60, - }); - } - expect(card.dataset.swiping).toBe('true'); - jest.advanceTimersByTime(10); - dispatchPointer(card, 'pointerup', { - pointerType: 'touch', - clientX: 230, - clientY: 60, - }); - - expect(onDismiss).not.toHaveBeenCalled(); - expect(card.dataset.removed).toBe('false'); + dispatchPointer(card, 'pointermove', { clientY: 105 }); expect(card.style.getPropertyValue('--swipe-amount')).toBe('0px'); -}); - -test('mouse drag inside selectable text preserves text selection without swiping the toast away', () => { - const onClose = jest.fn(); - store.configure({ position: 'bottom-right' }); - store.show( - message('selectable-toast', { - duration: 1000, - message: { - ...text('0x71C...89A'), - selectable: true, - }, - }), - { onClose } - ); - const card = cards()[0]!; - const selectable = card.querySelector('[data-okt-selectable]')!; - expect(selectable).toBeTruthy(); - - dispatchPointer(selectable, 'pointerdown', { - pointerType: 'mouse', - clientX: 100, - clientY: 100, - }); - dispatchPointer(selectable, 'pointermove', { - pointerType: 'mouse', - clientX: 190, - clientY: 100, - }); - expect(card.getAttribute('data-swiping')).toBe('false'); - // Press still pauses timer while selecting. - jest.advanceTimersByTime(1500); - expect(card.getAttribute('data-removed')).toBe('false'); - - dispatchPointer(selectable, 'pointerup', { - pointerType: 'mouse', - clientX: 190, - clientY: 100, - }); + dispatchPointer(card, 'pointerup', { clientY: 105 }); expect(card.getAttribute('data-removed')).toBe('false'); - expect(onClose).not.toHaveBeenCalled(); - - // Timers resume once the mouse leaves the toast after releasing selection. - dispatchPointer(card.parentElement!, 'pointerleave', { - pointerType: 'mouse', - }); - jest.advanceTimersByTime(1200); - expect(onClose).toHaveBeenCalledWith('timeout'); -}); - -test('vertical drag on a pressable notification suppresses the synthesized row click', () => { - const onPress = jest.fn(); - store.configure({ position: 'top-center' }); - store.show( - { - id: 'notif-drag', - layout: 'notification', - pressable: true, - duration: 5000, - badgeSize: 36, - badgeColor: '#eee', - icon: { kind: 'icon', name: 'Bell', size: 18, color: '#111' }, - title: text('Transfer received'), - message: text('1.0 ETH'), - }, - { onPress } - ); - const card = cards()[0]!; - const row = card.querySelector('[data-okt-pressable]')!; - - // Vertical drag followed by synthesized click should not trigger onPress. - dispatchPointer(row, 'pointerdown', { - pointerType: 'mouse', - clientX: 200, - clientY: 80, - }); - dispatchPointer(row, 'pointermove', { - pointerType: 'mouse', - clientX: 200, - clientY: 50, - }); - dispatchPointer(row, 'pointerup', { - pointerType: 'mouse', - clientX: 200, - clientY: 50, - }); - row.click(); - expect(onPress).not.toHaveBeenCalled(); - - // A normal click afterwards still triggers onPress. - dispatchPointer(row, 'pointerdown', { - pointerType: 'mouse', - clientX: 200, - clientY: 80, - }); - dispatchPointer(row, 'pointerup', { - pointerType: 'mouse', - clientX: 200, - clientY: 80, - }); - row.click(); - expect(onPress).toHaveBeenCalledTimes(1); -}); - -test('a leaving front card keeps its exit slot while survivors promote immediately', () => { - store.show(message('oldest')); - store.show(message('middle')); - store.show(message('front')); - const [front, middle, oldest] = cards(); - - dispatchPointer(front!, 'pointerdown', { clientX: 120 }); - dispatchPointer(front!, 'pointermove', { clientX: 200 }); - dispatchPointer(front!, 'pointerup', { clientX: 200 }); - - expect(front?.dataset.removed).toBe('true'); - expect(front?.dataset.index).toBe('0'); - expect(middle?.dataset.front).toBe('true'); - expect(middle?.dataset.index).toBe('0'); - expect(oldest?.dataset.index).toBe('1'); - expect(events.map(({ type }) => type)).toEqual(['dismiss']); - - jest.advanceTimersByTime(200); - expect(events.map(({ type }) => type)).toEqual(['dismiss', 'close']); -}); - -test('collapsing during a middle-card drag cancels dismissal on release', () => { - ['oldest', 'middle', 'front'].forEach((id) => store.show(message(id))); - document.dispatchEvent( - new KeyboardEvent('keydown', { altKey: true, code: 'KeyT' }) - ); - - const middle = cards()[1]!; - dispatchPointer(middle, 'pointerdown', { - pointerType: 'touch', - clientX: 120, - }); - dispatchPointer(middle, 'pointermove', { - pointerType: 'touch', - clientX: 200, - }); - expect(middle.dataset.swiping).toBe('true'); - dispatchPointer(document.body, 'pointerdown', { - pointerType: 'touch', - pointerId: 2, - }); - expect(middle.dataset.expanded).toBe('false'); - expect(middle.dataset.swiping).toBe('false'); - dispatchPointer(middle, 'pointerup', { - pointerType: 'touch', - clientX: 200, - }); - - expect(middle.dataset.removed).toBe('false'); - expect(middle.style.getPropertyValue('--swipe-amount')).toBe('0px'); - expect(events).toEqual([]); }); diff --git a/native-views/react-native-native-overlay/src/index.ts b/native-views/react-native-native-overlay/src/index.ts index 4a2c887a4..151a3e30f 100644 --- a/native-views/react-native-native-overlay/src/index.ts +++ b/native-views/react-native-native-overlay/src/index.ts @@ -59,7 +59,6 @@ export { OverlayToastStore, overlayToastStore, } from './toast/OverlayToastStore'; -export { TOAST_GEOMETRY, TOAST_MOTION } from './toast/toastMotion'; export type { IOverlayToastSnapshot } from './toast/OverlayToastStore'; export type { IOverlayMessageToast, @@ -71,8 +70,6 @@ export type { IOverlayToastHandle, IOverlayToastHandlers, IOverlayToastIcon, - IOverlayToastStatus, - IOverlayToastStatusIcon, IOverlayToastItem, IOverlayToastPosition, IOverlayToastSpec, diff --git a/native-views/react-native-native-overlay/src/toast/toastBridge.ts b/native-views/react-native-native-overlay/src/toast/toastBridge.ts index 0d26479e1..8a8952b3b 100644 --- a/native-views/react-native-native-overlay/src/toast/toastBridge.ts +++ b/native-views/react-native-native-overlay/src/toast/toastBridge.ts @@ -1,10 +1,7 @@ -import { TOAST_STATUS_GLYPHS } from './toastStatusGlyph'; - import type { IOverlayToastDismissReason, IOverlayToastEvent, IOverlayToastItem, - IOverlayToastIcon, } from './types'; /** How a toast that never times out crosses the bridge: JSON has no Infinity. */ @@ -17,12 +14,6 @@ const DISMISS_REASONS: readonly IOverlayToastDismissReason[] = [ 'programmatic', ]; -function serializeIcon(icon: IOverlayToastIcon | undefined) { - return icon?.kind === 'status' - ? { ...icon, glyph: TOAST_STATUS_GLYPHS[icon.status] } - : icon; -} - export function serializeToastItems( items: readonly IOverlayToastItem[] ): string { @@ -31,14 +22,6 @@ export function serializeToastItems( ...item, spec: { ...item.spec, - icon: serializeIcon(item.spec.icon), - ...(item.spec.layout === 'message' && { - statusIcon: serializeIcon(item.spec.statusIcon), - }), - actions: item.spec.actions?.map((action) => ({ - ...action, - icon: serializeIcon(action.icon), - })), duration: Number.isFinite(item.spec.duration) ? item.spec.duration : TOAST_DURATION_INFINITE, diff --git a/native-views/react-native-native-overlay/src/toast/toastDomContent.web.ts b/native-views/react-native-native-overlay/src/toast/toastDomContent.web.ts index fe2d23305..2e9800eec 100644 --- a/native-views/react-native-native-overlay/src/toast/toastDomContent.web.ts +++ b/native-views/react-native-native-overlay/src/toast/toastDomContent.web.ts @@ -1,9 +1,5 @@ /* cspell:ignore dasharray dashoffset */ -import { TOAST_GEOMETRY } from './toastMotion'; -import { createStatusTile, updateStatusTile } from './toastStatusTile.web'; - import type { - IOverlayMessageToast, IOverlayToastAction, IOverlayToastIcon, IOverlayToastSpec, @@ -13,15 +9,14 @@ import type { const SVG_NS = 'http://www.w3.org/2000/svg'; -const MESSAGE_ICON_GAP = TOAST_GEOMETRY.contentGap; -const MESSAGE_TEXT_GAP = TOAST_GEOMETRY.textGap; -const NOTIFICATION_GAP = 10; +// The card geometry of the layouts this replaces. +const MESSAGE_ICON_GAP = 8; +const MESSAGE_TEXT_GAP = 4; +const NOTIFICATION_GAP = 8; const NOTIFICATION_TEXT_GAP = 2; -const ACTIONS_PADDING_TOP = 10; +const ACTIONS_PADDING_TOP = 12; const ACTIONS_PADDING_END = 2; const ACTIONS_PADDING_BOTTOM = 2; -const INLINE_ACTION_MAX_LABEL = 16; -const INLINE_ACTION_MAX_MESSAGE = 72; export type IToastContentEvent = | { type: 'action'; actionId: string } @@ -36,41 +31,7 @@ function element(tag: string, marker: string): HTMLElement { return node; } -function textLength(text: IOverlayToastText | undefined): number { - if (!text) { - return 0; - } - return text.paragraphs.reduce( - (sum, runs) => - sum + runs.reduce((runSum, run) => runSum + run.text.length, 0), - 0 - ); -} - -function shouldUseInlineAction(spec: IOverlayMessageToast): boolean { - if (spec.actions?.length !== 1) { - return false; - } - if ((spec.actionsAlign ?? 'right') !== 'right') { - return false; - } - const [action] = spec.actions; - if (!action || action.label.length > INLINE_ACTION_MAX_LABEL) { - return false; - } - if (action.marginHorizontal || action.marginVertical) { - return false; - } - if ((spec.message?.paragraphs.length ?? 0) > 1) { - return false; - } - return textLength(spec.message) <= INLINE_ACTION_MAX_MESSAGE; -} - function createIcon(icon: IOverlayToastIcon): Element { - if (icon.kind === 'status') { - return createStatusTile(icon); - } if (icon.kind === 'image') { const image = document.createElement('img'); image.setAttribute('data-okt-image', ''); @@ -93,6 +54,7 @@ function createIcon(icon: IOverlayToastIcon): Element { svg.setAttribute('focusable', 'false'); svg.style.color = icon.color; if (icon.kind === 'spinner') { + // The indeterminate ring of the activity indicator this replaces. svg.setAttribute('data-okt-spinner', ''); svg.style.color = ''; svg.setAttribute('viewBox', '0 0 32 32'); @@ -250,11 +212,8 @@ function createAction(action: IOverlayToastAction, emit: IEmit): HTMLElement { if (action.fontFamily) { style.fontFamily = action.fontFamily; } - style.setProperty( - '--okt-action-padding', - `${action.paddingVertical}px ${action.paddingHorizontal}px` - ); - style.setProperty('--okt-action-radius', `${action.borderRadius}px`); + style.padding = `${action.paddingVertical}px ${action.paddingHorizontal}px`; + style.borderRadius = `${action.borderRadius}px`; style.borderWidth = `${action.borderWidth ?? 0}px`; if (action.marginHorizontal || action.marginVertical) { style.margin = `${action.marginVertical ?? 0}px ${ @@ -265,6 +224,7 @@ function createAction(action: IOverlayToastAction, emit: IEmit): HTMLElement { style.opacity = String(action.disabledOpacity); } button.addEventListener('click', (event) => { + // A press on an action never reaches the row under it. event.stopPropagation(); if (!action.disabled) { emit({ type: 'action', actionId: action.id }); @@ -289,13 +249,10 @@ function createActions( /** Builds the body of one card. The caller owns the card element. */ export function buildToastContent( spec: IOverlayToastSpec, - emit: IEmit, - previous?: HTMLElement, - statusMotion?: 'enter' | 'settle' + emit: IEmit ): HTMLElement { if (spec.layout === 'notification') { const row = element('div', 'data-okt-row'); - row.setAttribute('data-okt-layout', 'notification'); row.style.flex = '1 1 auto'; row.style.gap = `${NOTIFICATION_GAP}px`; if (spec.pressable) { @@ -362,13 +319,16 @@ export function buildToastContent( return row; } - const icon = spec.statusIcon ?? spec.icon; + const root = element('div', 'data-okt-root'); + const row = element('div', 'data-okt-row'); + if (spec.icon) { + row.style.gap = `${MESSAGE_ICON_GAP}px`; + const box = element('div', 'data-okt-icon-box'); + box.append(createIcon(spec.icon)); + row.append(box); + } const column = element('div', 'data-okt-col'); - column.setAttribute('data-okt-message-col', ''); column.style.gap = `${MESSAGE_TEXT_GAP}px`; - if (!icon) { - column.setAttribute('data-okt-no-icon', ''); - } if (spec.title) { column.append(createParagraphs(spec.title, emit)); } @@ -376,109 +336,16 @@ export function buildToastContent( column.append(createParagraphs(spec.message, emit)); } if (spec.actions?.length) { - const actions = createActions( - spec.actions, - spec.actionsAlign ?? 'right', - `${ACTIONS_PADDING_TOP}px ${ACTIONS_PADDING_END}px ${ACTIONS_PADDING_BOTTOM}px 0`, - emit + column.append( + createActions( + spec.actions, + spec.actionsAlign ?? 'right', + `${ACTIONS_PADDING_TOP}px ${ACTIONS_PADDING_END}px ${ACTIONS_PADDING_BOTTOM}px 0`, + emit + ) ); - const button = actions.firstElementChild; - const [action] = spec.actions; - if ( - action && - shouldUseInlineAction(spec) && - button instanceof HTMLElement - ) { - button.setAttribute('data-okt-inline-candidate', ''); - button.style.setProperty( - '--okt-inline-padding', - `${Math.max(action.paddingHorizontal, 14)}px` - ); - } - column.append(actions); - } - - if (icon?.kind === 'status' && previous?.hasAttribute('data-okt-root')) { - const row = previous.querySelector(':scope > [data-okt-row]'); - const tile = row?.querySelector( - ':scope > [data-okt-icon-box] > [data-okt-status-tile]' - ); - const iconBox = tile?.parentElement; - if (row && tile && iconBox) { - updateStatusTile(tile, icon, statusMotion === 'settle'); - if (statusMotion === 'settle') { - column.setAttribute('data-okt-content-swap', ''); - } - while (iconBox.nextSibling) { - iconBox.nextSibling.remove(); - } - row.style.gap = `${MESSAGE_ICON_GAP}px`; - row.append(column); - return previous; - } - } - const root = element('div', 'data-okt-root'); - const row = element('div', 'data-okt-row'); - row.style.gap = `${MESSAGE_ICON_GAP}px`; - if (icon) { - const box = element('div', 'data-okt-icon-box'); - box.append( - icon.kind === 'status' - ? createStatusTile(icon, statusMotion === 'enter') - : createIcon(icon) - ); - row.append(box); } row.append(column); root.append(row); return root; } - -export function layoutMessageAction(content: HTMLElement, heightCap?: number) { - const button = content.querySelector( - '[data-okt-inline-candidate]' - ); - const row = button?.closest('[data-okt-row]'); - const actions = row?.querySelector('[data-okt-actions]'); - const column = actions?.parentElement; - if (!button || !row || !actions || !column) { - return; - } - const icon = row.querySelector('[data-okt-icon-box]'); - const textStart = icon - ? icon.offsetWidth + MESSAGE_ICON_GAP - : TOAST_GEOMETRY.noIconPaddingStart; - const minTextWidth = column.querySelector('[data-okt-paragraphs]') - ? TOAST_GEOMETRY.inlineTextMinWidth - : 0; - - const focused = document.activeElement === button; - const placeInline = (inline: boolean) => { - button.toggleAttribute('data-okt-inline-action', inline); - const parent = inline ? row : actions; - if (button.parentElement !== parent) { - parent.append(button); - actions.hidden = inline; - } - }; - - button.setAttribute('data-okt-inline-action', ''); - const inlineTextWidth = - row.clientWidth - textStart - MESSAGE_ICON_GAP - button.offsetWidth; - placeInline(inlineTextWidth >= minTextWidth); - if ( - inlineTextWidth > 0 && - inlineTextWidth < minTextWidth && - heightCap !== undefined && - heightCap > 0 && - column.offsetTop + button.offsetTop + button.offsetHeight > heightCap - ) { - placeInline(true); - if (row.offsetHeight > heightCap) { - placeInline(false); - } - } - return focused && document.activeElement === document.body - ? button - : undefined; -} 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..65d9b57d7 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 @@ -1,9 +1,7 @@ /* cspell:ignore dasharray dashoffset */ import { getOverlayLayerRoot, syncOverlayInert } from '../web/overlayLayers'; -import { buildToastContent, layoutMessageAction } from './toastDomContent.web'; -import { TOAST_GEOMETRY, TOAST_MOTION } from './toastMotion'; -import { stopStatusTile } from './toastStatusTile.web'; +import { buildToastContent } from './toastDomContent.web'; import { ensureOverlayToastStyles } from './toastStyles.web'; import type { @@ -16,19 +14,17 @@ import type { IOverlayToasterConfig, } from './types'; +// The chrome constants of the renderer this replaces (sonner 1.4.41). const VISIBLE_TOASTS = 3; const VIEWPORT_OFFSET = 32; const TOAST_WIDTH = 356; -const GAP = TOAST_GEOMETRY.stackGap; -const SWIPE_DISTANCE = 64; -const SWIPE_FLICK_DISTANCE = 20; -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; +const GAP = 14; +const SWIPE_THRESHOLD = 20; +const SWIPE_VELOCITY = 0.11; // px per ms const TOUCH_START_THRESHOLD = 10; const POINTER_START_THRESHOLD = 2; -const TIME_BEFORE_UNMOUNT = TOAST_MOTION.cardExitMs; +// Equal to the exit transition. +const TIME_BEFORE_UNMOUNT = 200; const DEFAULT_POSITION: IOverlayToastPosition = 'bottom-right'; const DEFAULT_OBSTRUCTION_GAP = 8; const DEFAULT_OBSTRUCTION_ROOM = 88; @@ -42,35 +38,24 @@ interface IToastNode { generation: number; position: IOverlayToastPosition; li: HTMLLIElement; - shell: HTMLElement; - surface: HTMLElement; - body: HTMLElement; content: HTMLElement; mounted: boolean; removed: boolean; swiping: boolean; swipeOut: boolean; - exitReason?: IOverlayToastDismissReason; - exitLayout?: { - index: number; - offset: number; - expanded: boolean; - paneScale: number; - }; + offsetBeforeRemove: number; initialHeight: number; closeTimer?: ReturnType; unmountTimer?: ReturnType; swipePointerId?: number; - suppressNotificationClick?: boolean; - suppressClickTimer?: ReturnType; } interface IToastPress { node: IToastNode; x: number; y: number; + startedAt: number; moved: boolean; - samples: { x: number; t: number }[]; } interface IToastGroup { @@ -80,16 +65,17 @@ interface IToastGroup { toasts: IToastNode[]; /** Newest first, without leaving cards. */ heights: { id: string; height: number }[]; - paneScale: number; } function getDocumentDirection(): 'ltr' | 'rtl' { - const root = document.documentElement; - const direction = globalThis.getComputedStyle(root).direction; - if (direction === 'rtl' || direction === 'ltr') { - return direction; - } - return root.dir === 'rtl' ? 'rtl' : 'ltr'; + const attribute = document.documentElement.getAttribute('dir'); + if (attribute === 'rtl' || attribute === 'ltr') { + return attribute; + } + return globalThis.getComputedStyle(document.documentElement).direction === + 'rtl' + ? 'rtl' + : 'ltr'; } function createCloseButton(label: string): HTMLButtonElement { @@ -99,35 +85,45 @@ function createCloseButton(label: string): HTMLButtonElement { button.setAttribute('data-close-button', ''); const svg = document.createElementNS(SVG_NS, 'svg'); const attributes: Record = { - 'width': '10', - 'height': '10', + 'width': '12', + 'height': '12', 'viewBox': '0 0 24 24', 'fill': 'none', 'stroke': 'currentColor', - 'stroke-width': '3', + 'stroke-width': '1.5', 'stroke-linecap': 'round', - 'aria-hidden': 'true', + 'stroke-linejoin': 'round', }; Object.entries(attributes).forEach(([name, value]) => svg.setAttribute(name, value) ); - const path = document.createElementNS(SVG_NS, 'path'); - path.setAttribute('d', 'M7 7l10 10M17 7L7 17'); - svg.append(path); + [ + ['18', '6', '6', '18'], + ['6', '6', '18', '18'], + ].forEach(([x1, y1, x2, y2]) => { + const line = document.createElementNS(SVG_NS, 'line'); + line.setAttribute('x1', x1 ?? ''); + line.setAttribute('y1', y1 ?? ''); + line.setAttribute('x2', x2 ?? ''); + line.setAttribute('y2', y2 ?? ''); + svg.append(line); + }); button.append(svg); return button; } /** * Draws message toasts with plain DOM in the `toast` overlay layer. No React: - * the cards, their ring/shadow chrome, stacking, timers, swipe and spring - * transitions live here. + * the cards, their stacking, timers, swipe and transitions live here, and the + * stylesheet reproduces the previous renderer's chrome rule for rule. */ export function createToastDomRenderer( report: (event: IOverlayToastEvent) => void ): IOverlayToastRenderer { ensureOverlayToastStyles(); + // Events raised while a sync is applying wait for it to finish: the store + // answers an event by syncing again. let syncing = false; const pendingEvents: IOverlayToastEvent[] = []; const onEvent = (event: IOverlayToastEvent) => { @@ -147,45 +143,13 @@ export function createToastDomRenderer( let keyboardExpanded = false; let touchExpandedGroup: IToastGroup | undefined; let destroyed = false; - let documentDirection = getDocumentDirection(); - let itemOrder = new Map(); - const groupResizeObserver = - typeof ResizeObserver === 'function' - ? new ResizeObserver(onResize) - : undefined; const isExpanded = (): boolean => nodes.size > 1 && (keyboardExpanded || !!touchExpandedGroup || hoveredGroups.size > 0); - const narrowViewport = globalThis.matchMedia?.('(max-width: 600px)'); - const splitColumns = globalThis.matchMedia?.( - '(horizontal-viewport-segments: 2)' - ); - const splitRows = globalThis.matchMedia?.('(vertical-viewport-segments: 2)'); - - function positionOf(spec: IOverlayToastSpec): IOverlayToastPosition { - const position = spec.position ?? config.position ?? DEFAULT_POSITION; - const [vertical, horizontal] = position.split('-'); - if (splitColumns?.matches) { - const lane = - horizontal === 'center' - ? documentDirection === 'rtl' - ? 'right' - : 'left' - : horizontal; - return `${vertical}-${lane}` as IOverlayToastPosition; - } - return narrowViewport?.matches - ? (`${vertical}-center` as IOverlayToastPosition) - : position; - } - - const motionPreference = globalThis.matchMedia?.( - '(prefers-reduced-motion: reduce)' - ); - const reduceMotion = () => - config.respectReducedMotion !== false && motionPreference?.matches; + const positionOf = (spec: IOverlayToastSpec): IOverlayToastPosition => + spec.position ?? config.position ?? DEFAULT_POSITION; function ensureSection(): HTMLElement { const root = getOverlayLayerRoot('toast'); @@ -226,7 +190,6 @@ export function createToastDomRenderer( ol, toasts: [], heights: [], - paneScale: 1, }; const hover = (event: PointerEvent) => { if ( @@ -249,14 +212,8 @@ export function createToastDomRenderer( update(); } }); - ol.addEventListener('transitionend', (event) => { - if (event.target === ol && event.propertyName === 'top') { - update(); - } - }); group = nextGroup; groups.set(position, group); - groupResizeObserver?.observe(ol); } if (group.ol.parentElement !== ensureSection()) { ensureSection().append(group.ol); @@ -265,6 +222,8 @@ export function createToastDomRenderer( } function offsetOf(group: IToastGroup, node: IToastNode): number { + // The height index moves before the card list does, so the layout of the + // cards behind a leaving one starts closing at once. const heightIndex = Math.max( group.heights.findIndex((height) => height.id === node.id), 0 @@ -275,42 +234,21 @@ export function createToastDomRenderer( return heightIndex * GAP + heightsBefore; } - function focusAfterLayout( - target: HTMLElement, - expectedFocus: Element | null, - isStillEligible?: () => boolean - ) { - // A focusin listener can synchronously change the toast store. - queueMicrotask(() => { - if ( - !destroyed && - target.isConnected && - !target.closest('[inert]') && - document.activeElement === expectedFocus && - isStillEligible?.() !== false - ) { - target.focus({ preventScroll: true }); - } - }); - } - function measure(node: IToastNode) { const group = groups.get(node.position); if (!group || node.removed) { return; } + // The card's own height: a card further back in the stack is scaled + // and pinned to the front card's height, neither of which is its size. const { style } = node.li; const originalHeight = style.height; + const originalTransform = style.transform; style.height = 'auto'; - const actionToFocus = layoutMessageAction( - node.content, - config.webContentMaxHeight - ); - if (actionToFocus) { - focusAfterLayout(actionToFocus, document.body); - } - const { offsetHeight: height } = node.li; + style.transform = 'none'; + const { height } = node.li.getBoundingClientRect(); style.height = originalHeight; + style.transform = originalTransform; node.initialHeight = height; const existing = group.heights.find((entry) => entry.id === node.id); if (existing) { @@ -339,6 +277,7 @@ export function createToastDomRenderer( return; } if (node.closeTimer === undefined) { + // A resumed toast starts over with its whole lifetime, as before. node.closeTimer = setTimeout(() => { node.closeTimer = undefined; deleteToast(node, 'timeout', true); @@ -349,11 +288,6 @@ export function createToastDomRenderer( function unmount(node: IToastNode, reason: IOverlayToastDismissReason) { clearNodePresses(node); - if (node.suppressClickTimer !== undefined) { - clearTimeout(node.suppressClickTimer); - node.suppressClickTimer = undefined; - } - node.suppressNotificationClick = false; if (node.unmountTimer !== undefined) { clearTimeout(node.unmountTimer); node.unmountTimer = undefined; @@ -387,23 +321,9 @@ export function createToastDomRenderer( clearNodePresses(node); const group = groups.get(node.position); node.removed = true; - node.exitReason = reason; - const statusTile = node.content.querySelector( - ':scope > [data-okt-row] > [data-okt-icon-box] > [data-okt-status-tile]' - ); - if (statusTile) { - stopStatusTile(statusTile); - } + // Keep the offset the card had, for the exit transition. + node.offsetBeforeRemove = group ? offsetOf(group, node) : 0; if (group) { - node.exitLayout = { - index: Math.max( - 0, - group.heights.findIndex((entry) => entry.id === node.id) - ), - offset: offsetOf(group, node) * group.paneScale, - expanded: isExpanded(), - paneScale: group.paneScale, - }; group.heights = group.heights.filter((entry) => entry.id !== node.id); } clearCloseTimer(node); @@ -415,38 +335,27 @@ export function createToastDomRenderer( reason, }); } - if (nodes.get(node.id) !== node) { - return; - } - if (reduceMotion()) { + node.unmountTimer = setTimeout(() => { + node.unmountTimer = undefined; unmount(node, reason); - } else { - node.unmountTimer = setTimeout(() => { - unmount(node, reason); - update(); - }, TIME_BEFORE_UNMOUNT); - } + update(); + }, TIME_BEFORE_UNMOUNT); update(); } - function clearSwipe(node: IToastNode, pointerId: number) { + function clearPress(pointerId: number, { node }: IToastPress) { + presses.delete(pointerId); if (node.swipePointerId === pointerId) { node.swipePointerId = undefined; node.swiping = false; node.li.setAttribute('data-swiping', 'false'); node.li.style.setProperty('--swipe-amount', '0px'); - node.li.style.removeProperty('--swipe-opacity'); if (node.li.hasPointerCapture?.(pointerId)) { node.li.releasePointerCapture(pointerId); } } } - function clearPress(pointerId: number, { node }: IToastPress) { - presses.delete(pointerId); - clearSwipe(node, pointerId); - } - function clearNodePresses(node: IToastNode) { presses.forEach((press, pointerId) => { if (press.node === node) { @@ -456,48 +365,10 @@ export function createToastDomRenderer( }); } - function swipeOpacityFor(deltaX: number): number { - return Math.max( - SWIPE_MIN_OPACITY, - 1 - Math.abs(deltaX) / SWIPE_OPACITY_RANGE - ); - } - - function canSwipeNode(node: IToastNode): boolean { - if (node.removed) { - return false; - } - const group = groups.get(node.position); - if (!group || group.paneScale === 0) { - return false; - } - const active = group.toasts.filter((entry) => !entry.removed); - const index = active.indexOf(node); - if (index < 0 || index >= VISIBLE_TOASTS) { - return false; - } - return isExpanded() || index === 0; - } - - function recordSwipeSample(press: IToastPress, x: number, now: number) { - press.samples.push({ x, t: now }); - while ( - press.samples.length > 1 && - now - press.samples[0]!.t > SWIPE_VELOCITY_WINDOW_MS - ) { - press.samples.shift(); - } - } - - function swipeVelocity(press: IToastPress, x: number, now: number): number { - const oldest = press.samples.find( - (sample) => now - sample.t <= SWIPE_VELOCITY_WINDOW_MS - ); - if (!oldest) { - return 0; - } - const dt = Math.max(1, now - oldest.t); - return (x - oldest.x) / dt; + function swipeAmount(node: IToastNode, deltaY: number): number { + return node.position.startsWith('top') + ? Math.min(0, deltaY) + : Math.max(0, deltaY); } function onGlobalPointerMove(event: PointerEvent) { @@ -506,32 +377,27 @@ export function createToastDomRenderer( return; } const { node } = press; - const dx = event.clientX - press.x; - const absDx = Math.abs(dx); - const absDy = Math.abs(event.clientY - press.y); + const dx = Math.abs(event.clientX - press.x); + const dy = event.clientY - press.y; const threshold = event.pointerType === 'touch' ? TOUCH_START_THRESHOLD : POINTER_START_THRESHOLD; - press.moved ||= Math.max(absDx, absDy) > threshold; + press.moved ||= Math.max(dx, Math.abs(dy)) > threshold; if (node.swipePointerId !== event.pointerId) { return; } - if (!canSwipeNode(node)) { - clearSwipe(node, event.pointerId); - return; - } - recordSwipeSample(press, event.clientX, event.timeStamp); + const amount = swipeAmount(node, dy); if (!node.swiping) { - if (absDx <= threshold || absDx <= absDy) { + if (Math.abs(amount) <= threshold || Math.abs(amount) < dx) { return; } + // Preserve the descendant's native click until an actual swipe starts. node.li.setPointerCapture?.(event.pointerId); node.swiping = true; node.li.setAttribute('data-swiping', 'true'); } - node.li.style.setProperty('--swipe-amount', `${dx}px`); - node.li.style.setProperty('--swipe-opacity', String(swipeOpacityFor(dx))); + node.li.style.setProperty('--swipe-amount', `${amount}px`); } function onGlobalPointerEnd(event: PointerEvent) { @@ -542,39 +408,17 @@ export function createToastDomRenderer( } const { node } = press; const released = event.type === 'pointerup'; - const threshold = - pointerType === 'touch' ? TOUCH_START_THRESHOLD : POINTER_START_THRESHOLD; - const moved = - press.moved || - Math.max( - Math.abs(event.clientX - press.x), - Math.abs(event.clientY - press.y) - ) > threshold; - 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) - : 0; + const amount = + released && node.swipePointerId === pointerId && node.swiping + ? swipeAmount(node, event.clientY - press.y) + : 0; + const velocity = + Math.abs(amount) / Math.max(1, Date.now() - press.startedAt); const dismissed = - swiped && - (absAmount >= SWIPE_DISTANCE || - (absAmount >= SWIPE_FLICK_DISTANCE && - velocity >= SWIPE_FLICK_VELOCITY)); + Math.abs(amount) >= SWIPE_THRESHOLD || velocity > SWIPE_VELOCITY; clearPress(pointerId, press); - if (released && moved && !dismissed) { - node.suppressNotificationClick = true; - if (node.suppressClickTimer !== undefined) { - clearTimeout(node.suppressClickTimer); - } - node.suppressClickTimer = setTimeout(() => { - node.suppressClickTimer = undefined; - node.suppressNotificationClick = false; - }, 0); - } + // The swipe pseudo-element must be gone before checking where we landed. const hit = released ? groupContaining(pointerHit(event)) : undefined; if (pointerType === 'touch') { if ( @@ -598,16 +442,6 @@ export function createToastDomRenderer( if (dismissed) { node.swipeOut = true; node.li.style.setProperty('--swipe-amount', `${amount}px`); - node.li.style.setProperty( - '--swipe-opacity', - String(swipeOpacityFor(amount)) - ); - const { left, right } = node.li.getBoundingClientRect(); - const exitX = - amount >= 0 - ? amount + Math.max(0, globalThis.innerWidth - left) + 48 - : amount - Math.max(0, right) - 48; - node.li.style.setProperty('--swipe-exit-x', `${exitX}px`); deleteToast(node, 'swipe', true); } else { update(); @@ -619,45 +453,13 @@ export function createToastDomRenderer( li.addEventListener('dragstart', (event) => { event.preventDefault(); }); - li.addEventListener( - 'click', - (event) => { - if (!node.suppressNotificationClick) { - return; - } - node.suppressNotificationClick = false; - if (node.suppressClickTimer !== undefined) { - clearTimeout(node.suppressClickTimer); - node.suppressClickTimer = undefined; - } - const target = event.target as HTMLElement | null; - if (target?.closest?.('button, [data-okt-link]')) { - return; - } - if (target?.closest?.('[data-okt-pressable]')) { - event.stopPropagation(); - event.preventDefault(); - } - }, - true - ); li.addEventListener('pointerdown', (event) => { - if (li.inert || event.button !== 0) { + if (node.removed || event.button !== 0) { return; } - node.suppressNotificationClick = false; - if (node.suppressClickTimer !== undefined) { - clearTimeout(node.suppressClickTimer); - node.suppressClickTimer = undefined; - } const target = event.target as HTMLElement | null; - const selectableMousePress = - event.pointerType === 'mouse' && - Boolean(target?.closest?.('[data-okt-selectable]')); if ( node.swipePointerId === undefined && - canSwipeNode(node) && - !selectableMousePress && !target?.closest?.('button, [data-okt-link]') ) { node.swipePointerId = event.pointerId; @@ -666,12 +468,13 @@ export function createToastDomRenderer( node, x: event.clientX, y: event.clientY, + startedAt: Date.now(), moved: false, - samples: [{ x: event.clientX, t: event.timeStamp }], }); update(); }); li.addEventListener('lostpointercapture', (event) => { + // A touch's implicit capture may move from a descendant to the card. if ( event.target === li && node.swipePointerId === event.pointerId && @@ -682,29 +485,22 @@ export function createToastDomRenderer( }); } - function renderContent(node: IToastNode, statusMotion?: 'enter' | 'settle') { - const next = buildToastContent( - node.spec, - (event) => { - if (!node.removed) { - onEvent({ - ...event, - id: node.id, - generation: node.generation, - } as IOverlayToastEvent); - } - }, - node.content, - reduceMotion() ? undefined : statusMotion - ); - if (node.content !== next) { - if (node.content.parentElement === node.body) { - node.content.replaceWith(next); - } else { - node.body.append(next); + function renderContent(node: IToastNode) { + const next = buildToastContent(node.spec, (event) => { + if (!node.removed) { + onEvent({ + ...event, + id: node.id, + generation: node.generation, + } as IOverlayToastEvent); } - node.content = next; + }); + if (node.content.parentElement === node.li) { + node.content.replaceWith(next); + } else { + node.li.append(next); } + node.content = next; if (node.spec.testID) { node.li.setAttribute('data-testid', node.spec.testID); } else { @@ -722,21 +518,10 @@ export function createToastDomRenderer( li.setAttribute('data-styled', 'true'); li.setAttribute('data-dismissible', 'true'); li.setAttribute('data-invert', 'false'); - - const shell = document.createElement('div'); - shell.setAttribute('data-okt-shell', ''); - const surface = document.createElement('div'); - surface.setAttribute('data-okt-surface', ''); - const body = document.createElement('div'); - body.setAttribute('data-okt-body', ''); - surface.append(body); - const closeButton = createCloseButton( config.closeButtonLabel ?? 'Close toast' ); - shell.append(surface, closeButton); - li.append(shell); - + li.append(closeButton); const node: IToastNode = { id: item.spec.id, spec: item.spec, @@ -744,36 +529,20 @@ export function createToastDomRenderer( generation: item.generation, position: positionOf(item.spec), li, - shell, - surface, - body, content: document.createElement('div'), mounted: false, removed: false, swiping: false, swipeOut: false, + offsetBeforeRemove: 0, initialHeight: 0, }; - const revealClose = (event: PointerEvent) => { - if ( - event.buttons === 0 && - (event.pointerType === 'mouse' || event.pointerType === 'pen') - ) { - li.setAttribute('data-okt-close-hover', ''); - } - }; - li.addEventListener('pointerenter', revealClose); - li.addEventListener('pointermove', revealClose); - li.addEventListener('pointerleave', () => - li.removeAttribute('data-okt-close-hover') - ); closeButton.addEventListener('click', () => deleteToast(node, 'close', true) ); li.addEventListener('keydown', (event) => { if ( !node.removed && - !node.body.inert && node.spec.layout === 'notification' && node.spec.pressable && event.target === li && @@ -787,7 +556,7 @@ export function createToastDomRenderer( }); } }); - renderContent(node, 'enter'); + renderContent(node); attachPointerHandlers(node); return node; } @@ -798,6 +567,9 @@ export function createToastDomRenderer( group.ol.prepend(node.li); nodes.set(node.id, node); applyGroup(group); + // Measuring lays the card out in its resting-out state, so switching it + // to mounted right after starts the enter transition from there. No frame + // callback: those do not run while the page is hidden. measure(node); node.mounted = true; update(); @@ -813,46 +585,10 @@ export function createToastDomRenderer( return Math.max(0, Math.min(bottom + gap, globalThis.innerHeight - room)); } - function getPaneScale(group: IToastGroup, expanded: boolean): number { - if (!splitRows?.matches || group.heights.length === 0) { - return 1; - } - const { ol } = group; - const styles = globalThis.getComputedStyle(ol); - const top = group.position.startsWith('top'); - const hinge = Number.parseFloat( - styles.getPropertyValue( - top ? '--toast-segment-bottom' : '--toast-segment-top' - ) - ); - if (!Number.isFinite(hinge)) { - return 1; - } - const currentAnchor = ol.getBoundingClientRect().top; - const room = config.topObstructionRoom ?? DEFAULT_OBSTRUCTION_ROOM; - const anchor = top - ? Math.max(currentAnchor, Math.min(obstructionTop(), hinge - room)) - : currentAnchor; - const visible = group.heights.slice(0, VISIBLE_TOASTS); - const naturalHeight = expanded - ? visible.reduce((sum, { height }) => sum + height, 0) - : visible[0]?.height ?? 0; - const stackHeight = naturalHeight + (visible.length - 1) * GAP; - return stackHeight > 0 - ? Math.min( - 1, - Math.max( - 0, - ((top ? hinge - anchor : anchor - hinge) - GAP) / stackHeight - ) - ) - : 1; - } - function applyGroup(group: IToastGroup) { const { ol } = group; const [yPosition, xPosition] = group.position.split('-'); - ol.dir = documentDirection; + ol.dir = getDocumentDirection(); ol.setAttribute('data-theme', config.theme ?? 'light'); ol.setAttribute('data-y-position', yPosition ?? 'bottom'); ol.setAttribute('data-x-position', xPosition ?? 'right'); @@ -863,16 +599,6 @@ export function createToastDomRenderer( ol.style.setProperty('--offset', `${VIEWPORT_OFFSET}px`); ol.style.setProperty('--width', `${TOAST_WIDTH}px`); ol.style.setProperty('--gap', `${GAP}px`); - if (config.cardColor) { - ol.style.setProperty('--okt-card-bg', config.cardColor); - } else { - ol.style.removeProperty('--okt-card-bg'); - } - if (config.cardBorderColor) { - ol.style.setProperty('--okt-card-border', config.cardBorderColor); - } else { - ol.style.removeProperty('--okt-card-border'); - } if (config.webContentMaxHeight !== undefined) { ol.style.setProperty( '--okt-max-height', @@ -881,67 +607,36 @@ export function createToastDomRenderer( } else { ol.style.removeProperty('--okt-max-height'); } + // Top toasts rest under whatever hangs from the top of the window. An + // inline `top`: the narrow-window rule pins the toaster otherwise. const top = yPosition === 'top' ? obstructionTop() : 0; - ol.setAttribute( - 'data-okt-respect-reduced-motion', - String(config.respectReducedMotion !== false) - ); - ol.style.transition = reduceMotion() + const reducedMotion = + config.respectReducedMotion !== false && + globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + ol.style.transition = reducedMotion ? '' : `top ${OBSTRUCTION_SHIFT_MS}ms ease`; - ol.style.setProperty('--toast-obstruction-top', top > 0 ? `${top}px` : ''); - ol.style.setProperty( - '--toast-obstruction-room', - `${config.topObstructionRoom ?? DEFAULT_OBSTRUCTION_ROOM}px` - ); + ol.style.top = top > 0 ? `${top}px` : ''; - const expanded = isExpanded(); - group.paneScale = getPaneScale(group, expanded); - let activeIndex = 0; - group.toasts.forEach((node, stackIndex) => { - const { li, body, exitLayout } = node; - const index = exitLayout?.index ?? activeIndex++; - const cardExpanded = exitLayout?.expanded ?? expanded; - const paneScale = exitLayout?.paneScale ?? group.paneScale; - const visible = index < VISIBLE_TOASTS && paneScale > 0; - const front = index === 0; - const bodyHidden = !front && !cardExpanded; - if (paneScale === 0) { - clearNodePresses(node); - } - li.inert = !visible || node.removed; - const lastFocus = document.activeElement; - const needsFocusHandoff = - bodyHidden && !body.inert && !li.inert && body.contains(lastFocus); - body.inert = bodyHidden; - if (needsFocusHandoff) { - const currentFocus = document.activeElement; - if (currentFocus === lastFocus || currentFocus === document.body) { - focusAfterLayout(li, currentFocus, () => body.inert); - } - } + group.toasts.forEach((node, index) => { + const { li } = node; li.setAttribute('data-mounted', String(node.mounted)); li.setAttribute('data-removed', String(node.removed)); - li.setAttribute('data-visible', String(visible)); + li.setAttribute('data-visible', String(index + 1 <= VISIBLE_TOASTS)); li.setAttribute('data-y-position', yPosition ?? 'bottom'); li.setAttribute('data-x-position', xPosition ?? 'right'); li.setAttribute('data-index', String(index)); - li.setAttribute('data-front', String(front)); + li.setAttribute('data-front', String(index === 0)); li.setAttribute('data-swiping', String(node.swiping)); li.setAttribute('data-swipe-out', String(node.swipeOut)); - li.setAttribute('data-expanded', String(cardExpanded)); + li.setAttribute('data-expanded', String(isExpanded())); li.style.setProperty('--index', String(index)); li.style.setProperty('--toasts-before', String(index)); - li.style.setProperty( - '--z-index', - String(group.toasts.length - stackIndex) - ); + li.style.setProperty('--z-index', String(group.toasts.length - index)); li.style.setProperty( '--offset', - `${exitLayout?.offset ?? offsetOf(group, node) * paneScale}px` + `${node.removed ? node.offsetBeforeRemove : offsetOf(group, node)}px` ); - li.style.setProperty('--toast-pane-scale', String(paneScale)); - li.toggleAttribute('data-pane-constrained', paneScale < 1); li.style.setProperty('--initial-height', `${node.initialHeight}px`); }); } @@ -950,11 +645,6 @@ export function createToastDomRenderer( if (destroyed) { return; } - const nextDirection = getDocumentDirection(); - if (nextDirection !== documentDirection) { - documentDirection = nextDirection; - reconcilePositions(); - } groups.forEach((group, position) => { if (group.toasts.length === 0) { hoveredGroups.forEach((hoveredGroup, pointerId) => { @@ -965,7 +655,6 @@ export function createToastDomRenderer( if (touchExpandedGroup === group) { touchExpandedGroup = undefined; } - groupResizeObserver?.unobserve(group.ol); group.ol.remove(); groups.delete(position); } @@ -974,11 +663,6 @@ export function createToastDomRenderer( keyboardExpanded = false; touchExpandedGroup = undefined; } - presses.forEach(({ node }, pointerId) => { - if (node.swiping && !canSwipeNode(node)) { - clearSwipe(node, pointerId); - } - }); groups.forEach((group) => { applyGroup(group); }); @@ -1003,29 +687,10 @@ export function createToastDomRenderer( node.position = position; const group = ensureGroup(position); group.toasts.push(node); - const focused = document.activeElement; - const restoreFocus = - focused instanceof HTMLElement && node.li.contains(focused); group.ol.append(node.li); - if ( - touchExpandedGroup === previous && - previous && - previous.toasts.length === 0 - ) { - touchExpandedGroup = group; - } - if (restoreFocus && document.activeElement === document.body) { - focusAfterLayout(focused, document.body); + if (!node.removed) { + group.heights.push({ id: node.id, height: node.initialHeight }); } - if (previous && focused === previous.ol && previous.heights.length === 0) { - focusAfterLayout( - group.ol, - previous.toasts.length > 0 ? previous.ol : document.body, - () => previous.heights.length === 0 - ); - } - applyGroup(group); - measure(node); return group; } @@ -1036,12 +701,7 @@ export function createToastDomRenderer( group.toasts.sort( (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0) ); - group.toasts.forEach((node, index) => { - const child = group.ol.children.item(index); - if (node.li !== child) { - group.ol.insertBefore(node.li, child); - } - }); + group.toasts.forEach((node) => group.ol.append(node.li)); group.heights.sort( (a, b) => (order.get(a.id) ?? 0) - (order.get(b.id) ?? 0) ); @@ -1071,31 +731,13 @@ export function createToastDomRenderer( } } - function reconcilePositions() { - const moved = new Set(); - nodes.forEach((node) => { - if (!node.removed) { - const position = positionOf(node.spec); - if (position !== node.position) { - moved.add(moveNode(node, position)); - } else { - measure(node); - } - } - }); - moved.forEach((group) => reconcileGroupOrder(group, itemOrder)); - } - function onResize() { - documentDirection = getDocumentDirection(); - reconcilePositions(); - update(); + if ((config.topObstruction ?? 0) > 0) { + update(); + } } function onGlobalPointerDown(event: PointerEvent) { - if (event.pointerType === 'touch') { - nodes.forEach(({ li }) => li.removeAttribute('data-okt-close-hover')); - } if ( (touchExpandedGroup || keyboardExpanded) && !groupContaining(event.target as Node | null) @@ -1114,51 +756,11 @@ export function createToastDomRenderer( update(); } - function finalizeReducedMotion() { - if (!reduceMotion()) { - return; - } - for (const node of [...nodes.values()]) { - if (nodes.get(node.id) !== node) { - continue; - } - if (node.exitReason !== undefined) { - unmount(node, node.exitReason); - continue; - } - const { content } = node; - content - .querySelectorAll('[data-okt-status-motion]') - .forEach(stopStatusTile); - content - .querySelector('[data-okt-content-swap]') - ?.removeAttribute('data-okt-content-swap'); - } - } - - function onMotionPreferenceChange() { - finalizeReducedMotion(); - update(); - } - - motionPreference?.addEventListener?.('change', onMotionPreferenceChange); document.addEventListener('keydown', onKeyDown); document.addEventListener('pointerdown', onGlobalPointerDown, true); document.addEventListener('pointermove', onGlobalPointerMove, true); document.addEventListener('pointerup', onGlobalPointerEnd, true); document.addEventListener('pointercancel', onGlobalPointerEnd, true); - const layoutQueries = [narrowViewport, splitColumns, splitRows]; - const directionObserver = new MutationObserver(() => { - if (getDocumentDirection() !== documentDirection) { - update(); - } - }); - directionObserver.observe(document.documentElement, { - attributes: true, - }); - layoutQueries.forEach((query) => - query?.addEventListener?.('change', onResize) - ); globalThis.addEventListener('resize', onResize); globalThis.addEventListener('blur', onWindowBlur); @@ -1168,25 +770,20 @@ export function createToastDomRenderer( return; } syncing = true; - const shouldReduceBeforeSync = reduceMotion(); - const heightCapChanged = - config.webContentMaxHeight !== nextConfig.webContentMaxHeight; config = nextConfig; - documentDirection = getDocumentDirection(); - if (heightCapChanged) { - groups.forEach(applyGroup); - } - itemOrder = new Map(items.map((item, index) => [item.spec.id, index])); const present = new Set(items.map((item) => item.spec.id)); + // Cards the list no longer knows leave without ceremony. [...nodes.values()].forEach((node) => { if (!present.has(node.id)) { unmount(node, 'programmatic'); } }); const movedGroups = new Set(); + // Oldest first, so each new card lands in front of the previous one. [...items].reverse().forEach((item) => { let node = nodes.get(item.spec.id); if (node?.removed && item.visible) { + // Shown again while the previous card was leaving. unmount(node, 'programmatic'); node = undefined; } @@ -1203,39 +800,31 @@ export function createToastDomRenderer( } return; } - const needsRedraw = node.revision !== item.revision; - if (needsRedraw) { - const nextIcon = - item.spec.layout === 'message' - ? item.spec.statusIcon ?? item.spec.icon - : undefined; - const settling = - item.visible && - node.generation !== item.generation && - nextIcon?.kind === 'status' && - nextIcon.status !== 'loading'; + if (node.revision !== item.revision) { node.revision = item.revision; node.spec = item.spec; - renderContent(node, settling ? 'settle' : undefined); + renderContent(node); + measure(node); } if (node.generation !== item.generation) { + // Shown again: the toast starts its lifetime over. clearNodePresses(node); node.generation = item.generation; clearCloseTimer(node); } const position = positionOf(node.spec); - if (!node.removed && position !== node.position) { + if (position !== node.position) { movedGroups.add(moveNode(node, position)); - } else if (needsRedraw || heightCapChanged) { - measure(node); } if (!item.visible) { deleteToast(node, 'programmatic', false); } }); - movedGroups.forEach((group) => reconcileGroupOrder(group, itemOrder)); - if (!shouldReduceBeforeSync && reduceMotion()) { - finalizeReducedMotion(); + if (movedGroups.size > 0) { + const order = new Map( + items.map((item, index) => [item.spec.id, index]) + ); + movedGroups.forEach((group) => reconcileGroupOrder(group, order)); } update(); syncing = false; @@ -1243,20 +832,11 @@ export function createToastDomRenderer( }, destroy() { destroyed = true; - groupResizeObserver?.disconnect(); - directionObserver.disconnect(); - motionPreference?.removeEventListener?.( - 'change', - onMotionPreferenceChange - ); document.removeEventListener('keydown', onKeyDown); document.removeEventListener('pointerdown', onGlobalPointerDown, true); document.removeEventListener('pointermove', onGlobalPointerMove, true); document.removeEventListener('pointerup', onGlobalPointerEnd, true); document.removeEventListener('pointercancel', onGlobalPointerEnd, true); - layoutQueries.forEach((query) => - query?.removeEventListener?.('change', onResize) - ); globalThis.removeEventListener('resize', onResize); globalThis.removeEventListener('blur', onWindowBlur); presses.forEach((press, pointerId) => clearPress(pointerId, press)); diff --git a/native-views/react-native-native-overlay/src/toast/toastMotion.ts b/native-views/react-native-native-overlay/src/toast/toastMotion.ts deleted file mode 100644 index 3ad505d9f..000000000 --- a/native-views/react-native-native-overlay/src/toast/toastMotion.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { springToCssLinear } from '../animation/spring'; - -import type { IOverlaySpring } from '../animation/types'; - -/** - * Shared RareUI-inspired geometry and spring motion parameters for message - * toasts across Web, iOS and Android. - * - * Concentric corner rule: `CARD_RADIUS = TILE_RADIUS + CARD_PADDING` (21 = 11 + 10). - */ -export const TOAST_GEOMETRY = { - inlineTextMinWidth: 96, - cardPadding: 10, - tileSize: 36, - tileRadius: 11, - cardRadius: 21, - stackGap: 10, - contentGap: 12, - textGap: 2, - noIconPaddingStart: 6, - actionHeight: 36, - actionRadius: 11, -} as const; - -export const TOAST_MOTION = { - /** Card entrance, stack expand/collapse and swipe settle-back spring. */ - cardSpring: { mass: 1, stiffness: 460, damping: 36 } as IOverlaySpring, - /** Decisive horizontal swipe-out timing aligned with TIME_BEFORE_UNMOUNT (200 ms). */ - cardExitMs: 200, - cardExitEase: [0.32, 0.72, 0, 1] as const, - swipeExitScale: 0.98, - /** Gentle non-interactive exit (timeout / programmatic / close button). */ - cardAutoExitMs: 190, - cardAutoExitEase: [0.2, 0, 0, 1] as const, - cardAutoExitOffset: 16, - cardAutoExitScale: 0.95, - collapsedBackExitOffset: 12, - collapsedBackExitScale: 0.9, - /** Critically damped tile entrance spring (zeta ~= 1.004, ~40% faster than raw RareUI). */ - tileSpring: { mass: 1, stiffness: 620, damping: 50 } as IOverlaySpring, - /** Snappy glyph pop spring (same zeta ~= 0.659 / 1.0385 overshoot, ~35% faster). */ - glyphSpring: { mass: 1, stiffness: 920, damping: 40 } as IOverlaySpring, - /** Tight icon choreography synchronized with the snappier card landing (~390 ms total). */ - arrivalDelayMs: 155, - tileLeadMs: 45, // tile begins at 110 ms (arrival - 45) - strokeDrawMs: 180, - strokeDelayOffsetMs: 55, // stroke draws 210..390 ms on enter - strokeEase: [0, 0, 0.58, 1] as const, - glyphLeaveMs: 90, - glyphLeaveEase: [0.42, 0, 1, 1] as const, - tileBumpMs: 260, - tileBumpPeakScale: 1.07, - tileBumpPeakFraction: 0.4, - tileBumpEase: [0, 0, 0.58, 1] as const, - tileTintMs: 140, - tileTintEase: [0.4, 0, 0.2, 1] as const, - contentSwapMs: 160, - spinnerPeriodMs: 850, -} as const; - -export function getToastWebSprings() { - return { - card: springToCssLinear(TOAST_MOTION.cardSpring, 48), - tile: springToCssLinear(TOAST_MOTION.tileSpring, 48), - glyph: springToCssLinear(TOAST_MOTION.glyphSpring, 48), - }; -} diff --git a/native-views/react-native-native-overlay/src/toast/toastSquircle.ts b/native-views/react-native-native-overlay/src/toast/toastSquircle.ts deleted file mode 100644 index 9b00d14eb..000000000 --- a/native-views/react-native-native-overlay/src/toast/toastSquircle.ts +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Generates an SVG path string for a continuous-curvature squircle matching - * Figma's `cornerSmoothing` model (the same geometry used by RareUI's toast - * cards and status tiles). - */ -export function getSquirclePath( - width: number, - height: number, - cornerRadius: number, - cornerSmoothing = 1 -): string { - if (width <= 0 || height <= 0) { - return ''; - } - const maxRadius = Math.min(width, height) / 2; - const r = Math.max(0, Math.min(cornerRadius, maxRadius)); - if (r === 0) { - return `M0 0H${width}V${height}H0Z`; - } - const clampedSmoothing = Math.max(0, Math.min(cornerSmoothing, 1)); - const p = Math.min((1 + clampedSmoothing) * r, maxRadius); - const smoothing = p / r - 1; - - const arcMeasure = 90 * (1 - smoothing); - const toRad = (deg: number) => (deg * Math.PI) / 180; - const arcSection = Math.sin(toRad(arcMeasure / 2)) * r * Math.SQRT2; - const angleAlpha = (90 - arcMeasure) / 2; - const p3ToP4 = r * Math.tan(toRad(angleAlpha / 2)); - const angleBeta = 45 * smoothing; - const c = p3ToP4 * Math.cos(toRad(angleBeta)); - const d = c * Math.tan(toRad(angleBeta)); - const b = (p - arcSection - c - d) / 3; - const a = 2 * b; - - const fmt = (value: number) => Number(value.toFixed(3)); - const w = fmt(width); - const h = fmt(height); - const rFmt = fmt(r); - const pFmt = fmt(p); - const aEnd = fmt(p - a); - const abEnd = fmt(p - a - b); - const abcEnd = fmt(p - a - b - c); - const dFmt = fmt(d); - const hasArc = arcSection > 0.001; - - // Top-right, bottom-right, bottom-left, top-left. - return [ - `M${fmt(width - p)} 0`, - `C${fmt(width - aEnd)} 0 ${fmt(width - abEnd)} 0 ${fmt( - width - abcEnd - )} ${dFmt}`, - hasArc ? `A${rFmt} ${rFmt} 0 0 1 ${fmt(width - d)} ${abcEnd}` : '', - `C${w} ${abEnd} ${w} ${aEnd} ${w} ${pFmt}`, - `L${w} ${fmt(height - p)}`, - `C${w} ${fmt(height - aEnd)} ${w} ${fmt(height - abEnd)} ${fmt( - width - d - )} ${fmt(height - abcEnd)}`, - hasArc - ? `A${rFmt} ${rFmt} 0 0 1 ${fmt(width - abcEnd)} ${fmt(height - d)}` - : '', - `C${fmt(width - abEnd)} ${h} ${fmt(width - aEnd)} ${h} ${fmt( - width - p - )} ${h}`, - `L${pFmt} ${h}`, - `C${aEnd} ${h} ${abEnd} ${h} ${abcEnd} ${fmt(height - d)}`, - hasArc ? `A${rFmt} ${rFmt} 0 0 1 ${dFmt} ${fmt(height - abcEnd)}` : '', - `C0 ${fmt(height - abEnd)} 0 ${fmt(height - aEnd)} 0 ${fmt(height - p)}`, - `L0 ${pFmt}`, - `C0 ${aEnd} 0 ${abEnd} ${dFmt} ${abcEnd}`, - hasArc ? `A${rFmt} ${rFmt} 0 0 1 ${abcEnd} ${dFmt}` : '', - `C${abEnd} 0 ${aEnd} 0 ${pFmt} 0`, - 'Z', - ] - .filter(Boolean) - .join(' '); -} diff --git a/native-views/react-native-native-overlay/src/toast/toastStatusGlyph.ts b/native-views/react-native-native-overlay/src/toast/toastStatusGlyph.ts deleted file mode 100644 index 3a2c4d949..000000000 --- a/native-views/react-native-native-overlay/src/toast/toastStatusGlyph.ts +++ /dev/null @@ -1,70 +0,0 @@ -import type { IOverlayToastStatus } from './types'; - -type Point = readonly [number, number]; - -interface IToastStatusGlyph { - strokeWidth: number; - contours: readonly (readonly Point[])[]; - dot?: readonly [number, number, number]; - ring?: { - radius: number; - trackOpacity: number; - arcFraction: number; - }; -} - -// Centerlines in a 24-unit box, in drawing order. Each contour has its own -// progress, so the two error diagonals draw simultaneously. -export const TOAST_STATUS_GLYPHS: Record< - IOverlayToastStatus, - IToastStatusGlyph -> = { - success: { - strokeWidth: 3, - contours: [ - [ - [6, 12.5], - [10, 16.5], - [18, 7.5], - ], - ], - }, - error: { - strokeWidth: 3, - contours: [ - [ - [7.5, 7.5], - [16.5, 16.5], - ], - [ - [16.5, 7.5], - [7.5, 16.5], - ], - ], - }, - warning: { - strokeWidth: 3, - contours: [ - [ - [12, 6], - [12, 13], - ], - ], - dot: [12, 18, 1.6], - }, - info: { - strokeWidth: 3, - contours: [ - [ - [12, 11], - [12, 18], - ], - ], - dot: [12, 6.25, 1.6], - }, - loading: { - strokeWidth: 2.75, - contours: [], - ring: { radius: 8, trackOpacity: 0.25, arcFraction: 0.25 }, - }, -}; diff --git a/native-views/react-native-native-overlay/src/toast/toastStatusTile.web.ts b/native-views/react-native-native-overlay/src/toast/toastStatusTile.web.ts deleted file mode 100644 index 168d5ba44..000000000 --- a/native-views/react-native-native-overlay/src/toast/toastStatusTile.web.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { TOAST_GEOMETRY } from './toastMotion'; -import { getSquirclePath } from './toastSquircle'; -import { TOAST_STATUS_GLYPHS } from './toastStatusGlyph'; - -import type { IOverlayToastStatusIcon } from './types'; - -const SVG_NS = 'http://www.w3.org/2000/svg'; - -function createGlyph(icon: IOverlayToastStatusIcon): HTMLElement { - const glyph = document.createElement('span'); - glyph.setAttribute('data-okt-status-glyph', ''); - const svg = document.createElementNS(SVG_NS, 'svg'); - const recipe = TOAST_STATUS_GLYPHS[icon.status]; - svg.setAttribute('viewBox', '0 0 24 24'); - svg.setAttribute('fill', 'none'); - svg.setAttribute('stroke', 'currentColor'); - svg.setAttribute('stroke-width', String(recipe.strokeWidth)); - svg.setAttribute('stroke-linecap', 'round'); - svg.setAttribute('stroke-linejoin', 'round'); - for (const points of recipe.contours) { - const path = document.createElementNS(SVG_NS, 'path'); - path.setAttribute('data-okt-status-stroke', ''); - path.setAttribute('pathLength', '1'); - path.setAttribute( - 'd', - `M${points.map((point) => point.join(' ')).join('L')}` - ); - svg.append(path); - } - const circle = (x: number, y: number, radius: number) => { - const node = document.createElementNS(SVG_NS, 'circle'); - node.setAttribute('cx', String(x)); - node.setAttribute('cy', String(y)); - node.setAttribute('r', String(radius)); - svg.append(node); - return node; - }; - if (recipe.dot) { - const dot = circle(...recipe.dot); - dot.setAttribute('data-okt-status-dot', ''); - dot.setAttribute('fill', 'currentColor'); - dot.setAttribute('stroke', 'none'); - } - if (recipe.ring) { - const { radius, trackOpacity, arcFraction } = recipe.ring; - const track = circle(12, 12, radius); - track.setAttribute('stroke-opacity', String(trackOpacity)); - const arc = circle(12, 12, radius); - arc.setAttribute('transform', 'rotate(-90 12 12)'); - arc.setAttribute('pathLength', '1'); - arc.setAttribute('stroke-dasharray', `${arcFraction} 1`); - svg.setAttribute('data-okt-status-ring', ''); - } - glyph.append(svg); - return glyph; -} - -export function createStatusTile( - icon: IOverlayToastStatusIcon, - entering = false -): HTMLElement { - const tile = document.createElement('span'); - tile.setAttribute('aria-hidden', 'true'); - tile.setAttribute('data-okt-status-tile', icon.status); - if (entering) { - tile.setAttribute('data-okt-status-motion', 'enter'); - } - updateStatusTile(tile, icon, false); - return tile; -} - -export function updateStatusTile( - tile: HTMLElement, - icon: IOverlayToastStatusIcon, - settle: boolean -) { - const previous = tile.getAttribute('data-okt-status-tile'); - const glyph = tile.querySelector( - '[data-okt-status-glyph]:not([data-okt-status-outgoing])' - ); - if (!glyph || previous !== icon.status) { - tile.querySelector('[data-okt-status-outgoing]')?.remove(); - if (settle && glyph && previous && previous !== icon.status) { - const { transform: tileTransform, opacity: tileOpacity } = - getComputedStyle(tile); - const { transform: glyphTransform, opacity: glyphOpacity } = - getComputedStyle(glyph); - const visible = Number(glyphOpacity) > 0; - tile.style.setProperty('--okt-tile-from-scale', tileTransform); - tile.style.setProperty('--okt-tile-from-opacity', tileOpacity); - tile.setAttribute( - 'data-okt-status-motion', - visible ? 'settle' : 'immediate' - ); - if (visible) { - glyph.getAnimations?.().forEach((animation) => animation.cancel()); - glyph.style.setProperty('--okt-glyph-from-transform', glyphTransform); - glyph.style.setProperty('--okt-glyph-from-opacity', glyphOpacity); - glyph.setAttribute('data-okt-status-outgoing', ''); - glyph.addEventListener('animationend', (event) => { - if (event.animationName === 'onekey-status-leave') { - glyph.remove(); - } - }); - } else { - glyph.remove(); - } - } else if (glyph) { - tile.removeAttribute('data-okt-status-motion'); - glyph.remove(); - } - tile.setAttribute('data-okt-status-tile', icon.status); - tile.append(createGlyph(icon)); - } - const radius = - (icon.size * TOAST_GEOMETRY.tileRadius) / TOAST_GEOMETRY.tileSize; - const squircle = getSquirclePath(icon.size, icon.size, radius, 1); - tile.style.width = `${icon.size}px`; - tile.style.height = `${icon.size}px`; - tile.style.borderRadius = `${radius}px`; - if (squircle) { - tile.style.clipPath = `path('${squircle}')`; - } - tile.style.backgroundColor = icon.backgroundColor; - tile.style.color = icon.color; -} - -export function stopStatusTile(tile: HTMLElement) { - tile.removeAttribute('data-okt-status-motion'); - tile.querySelector('[data-okt-status-outgoing]')?.remove(); -} 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..dc1bcc2ae 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 @@ -1,351 +1,62 @@ /* cspell:ignore Neue Noto */ -import { - getToastWebSprings, - TOAST_GEOMETRY, - TOAST_MOTION, -} from './toastMotion'; - +// The web toaster chrome. These declarations replicate sonner@1.4.41's +// default stylesheet (the renderer this replaces) one for one: same custom +// properties, same values, same transitions and breakpoints, so the migration +// is visually a no-op. Attribute names are ours so nothing else can target the +// old library's nodes. const STYLE_ID = 'onekey-overlay-toast-styles'; -function cubic(tuple: readonly [number, number, number, number]): string { - return `cubic-bezier(${tuple.join(',')})`; -} - -function buildOverlayToastCss(): string { - const springs = getToastWebSprings(); - const tileDelayMs = TOAST_MOTION.arrivalDelayMs - TOAST_MOTION.tileLeadMs; - const glyphDelayMs = TOAST_MOTION.arrivalDelayMs; - const drawDelayMs = - TOAST_MOTION.arrivalDelayMs + TOAST_MOTION.strokeDelayOffsetMs; - const settleDrawDelayMs = - TOAST_MOTION.glyphLeaveMs + TOAST_MOTION.strokeDelayOffsetMs; - const cardExitEase = cubic(TOAST_MOTION.cardExitEase); - const cardAutoExitEase = cubic(TOAST_MOTION.cardAutoExitEase); - const strokeEase = cubic(TOAST_MOTION.strokeEase); - const leaveEase = cubic(TOAST_MOTION.glyphLeaveEase); - const bumpEase = cubic(TOAST_MOTION.tileBumpEase); - const tintEase = cubic(TOAST_MOTION.tileTintEase); - - return ` -:where(html[dir="ltr"]),:where([data-onekey-toast-toaster][dir="ltr"]){--toast-close-button-start:-6px;--toast-close-button-end:unset} -:where(html[dir="rtl"]),:where([data-onekey-toast-toaster][dir="rtl"]){--toast-close-button-start:unset;--toast-close-button-end:-6px} -:where([data-onekey-toast-toaster]){ - position:fixed; - --toast-inset:max(16px,env(safe-area-inset-left),env(safe-area-inset-right)); - --toast-vertical-offset:var(--offset); - --toast-segment-width:100vw; - --toast-segment-top:0px; - --toast-segment-bottom:100vh; - width:min(var(--width),max(0px,calc(var(--toast-segment-width) - var(--toast-inset) * 2))); - font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji; - --okt-card-radius:${TOAST_GEOMETRY.cardRadius}px; - --okt-card-padding:${TOAST_GEOMETRY.cardPadding}px; - --okt-card-spring-duration:${springs.card.durationMs}ms; - --okt-card-spring-ease:cubic-bezier(.22,1,.36,1); - --okt-card-exit-duration:${TOAST_MOTION.cardExitMs}ms; - --okt-card-exit-ease:${cardExitEase}; - --okt-card-auto-exit-duration:${TOAST_MOTION.cardAutoExitMs}ms; - --okt-card-auto-exit-ease:${cardAutoExitEase}; - box-sizing:border-box; - padding:0; - margin:0; - list-style:none; - outline:none; - z-index:0; -} +const CSS = ` +:where(html[dir="ltr"]),:where([data-onekey-toast-toaster][dir="ltr"]){--toast-close-button-start:0;--toast-close-button-end:unset;--toast-close-button-transform:translate(-35%, -35%)} +:where(html[dir="rtl"]),:where([data-onekey-toast-toaster][dir="rtl"]){--toast-close-button-start:unset;--toast-close-button-end:0;--toast-close-button-transform:translate(35%, -35%)} +:where([data-onekey-toast-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1:hsl(0, 0%, 99%);--gray2:hsl(0, 0%, 97.3%);--gray3:hsl(0, 0%, 95.1%);--gray4:hsl(0, 0%, 93%);--gray5:hsl(0, 0%, 90.9%);--gray6:hsl(0, 0%, 88.7%);--gray7:hsl(0, 0%, 85.8%);--gray8:hsl(0, 0%, 78%);--gray9:hsl(0, 0%, 56.1%);--gray10:hsl(0, 0%, 52.3%);--gray11:hsl(0, 0%, 43.5%);--gray12:hsl(0, 0%, 9%);--border-radius:8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:0} :where([data-onekey-toast-toaster][data-x-position="right"]){right:max(var(--offset),env(safe-area-inset-right))} :where([data-onekey-toast-toaster][data-x-position="left"]){left:max(var(--offset),env(safe-area-inset-left))} :where([data-onekey-toast-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)} -:where([data-onekey-toast-toaster][data-y-position="top"]){top:max(var(--toast-obstruction-top,0px),calc(var(--toast-segment-top) + max(var(--toast-vertical-offset),env(safe-area-inset-top))))} -:where([data-onekey-toast-toaster][data-y-position="bottom"]){bottom:calc(100vh - var(--toast-segment-bottom) + max(var(--toast-vertical-offset),env(safe-area-inset-bottom)))} -:where([data-onekey-toast]){ - --y:translateY(calc(100% + 16px)) scale(.96); - --lift-amount:calc(var(--lift) * var(--gap) * var(--toast-pane-scale,1)); - z-index:var(--z-index); - position:absolute; - width:100%; - inset-inline:0; - opacity:0; - transform: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; - outline:none; - overflow-wrap:anywhere; -} -:where([data-onekey-toast][data-y-position="top"]){top:0;--y:translateY(calc(-100% - 16px)) scale(.96);--lift:1} -:where([data-onekey-toast][data-y-position="bottom"]){bottom:0;--y:translateY(calc(100% + 16px)) scale(.96);--lift:-1} -:where([data-onekey-toast][data-pane-constrained][data-y-position="top"]){transform-origin:center top} -:where([data-onekey-toast][data-pane-constrained][data-y-position="bottom"]){transform-origin:center bottom} +:where([data-onekey-toast-toaster][data-y-position="top"]){top:max(var(--offset),env(safe-area-inset-top))} +:where([data-onekey-toast-toaster][data-y-position="bottom"]){bottom:max(var(--offset),env(safe-area-inset-bottom))} +:where([data-onekey-toast]){--y:translateY(100%);--lift-amount:calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere} +:where([data-onekey-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px} +:where([data-onekey-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003} +:where([data-onekey-toast][data-y-position="top"]){top:0;--y:translateY(-100%);--lift:1;--lift-amount:calc(1 * var(--gap))} +:where([data-onekey-toast][data-y-position="bottom"]){bottom:0;--y:translateY(100%);--lift:-1;--lift-amount:calc(var(--lift) * var(--gap))} +:where([data-onekey-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;background:var(--gray1);color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s} +:where([data-onekey-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003} +:where([data-onekey-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)} :where([data-onekey-toast][data-swiping="true"]):before{content:"";position:absolute;left:0;right:0;height:100%;z-index:-1} :where([data-onekey-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)} :where([data-onekey-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)} :where([data-onekey-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)} :where([data-onekey-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%} -:where([data-onekey-toast][data-mounted="true"]){--y:translateY(0) scale(1);opacity:1} -:where([data-onekey-toast][data-expanded="false"][data-front="false"]){ - --scale:calc(1 - var(--toasts-before) * .05); - --y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(var(--scale)); - height:var(--front-toast-height); -} +:where([data-onekey-toast][data-mounted="true"]){--y:translateY(0);opacity:1} +:where([data-onekey-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y:translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)} +:where([data-onekey-toast])>*{transition:opacity .4s} +:where([data-onekey-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0} :where([data-onekey-toast][data-visible="false"]){opacity:0;pointer-events:none} -:where([data-onekey-toast][data-mounted="true"][data-expanded="true"]){--y:translateY(calc(var(--lift) * var(--offset))) scale(1);height:var(--initial-height)} -:where([data-onekey-toast][data-removed="true"][data-swipe-out="false"]){ - transition:transform var(--okt-card-auto-exit-duration) var(--okt-card-auto-exit-ease),opacity var(--okt-card-auto-exit-duration) var(--okt-card-auto-exit-ease),height var(--okt-card-auto-exit-duration) var(--okt-card-auto-exit-ease); -} -:where([data-onekey-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y:translateY(calc(var(--lift) * -${TOAST_MOTION.cardAutoExitOffset}px)) scale(${TOAST_MOTION.cardAutoExitScale});opacity:0} -:where([data-onekey-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -${TOAST_MOTION.cardAutoExitOffset}px)) scale(${TOAST_MOTION.cardAutoExitScale});opacity:0} -:where([data-onekey-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y:translateY(calc(var(--lift-amount) * var(--toasts-before) + var(--lift) * -${TOAST_MOTION.collapsedBackExitOffset}px)) scale(${TOAST_MOTION.collapsedBackExitScale});opacity:0} +:where([data-onekey-toast][data-mounted="true"][data-expanded="true"]){--y:translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)} +:where([data-onekey-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y:translateY(calc(var(--lift) * -100%));opacity:0} +:where([data-onekey-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y:translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0} +:where([data-onekey-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y:translateY(40%);opacity:0;transition:transform .5s,opacity .2s} :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} -@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} -} - -/* Raised concentric card with outer 1px ring + layered box-shadow (no clip-path/filter haze) */ -[data-onekey-toast-toaster][data-theme="light"]{ - --okt-surface-bg:#fff; - --okt-surface-border:rgba(0,0,0,.06); - --okt-surface-text:#111; - --okt-surface-shadow:0 1px 3px rgba(0,0,0,.05),0 4px 10px -4px rgba(0,0,0,.06); - --okt-close-bg:#fff; - --okt-close-text:#868593; - --okt-close-hover-text:#000; - --okt-close-ring:0 0 0 1px rgba(0,0,0,.08); - --okt-focus-ring:rgba(0,0,0,.22); -} -[data-onekey-toast-toaster][data-theme="dark"]{ - --okt-surface-bg:#1c1c1e; - --okt-surface-border:rgba(255,255,255,.09); - --okt-surface-text:#fff; - --okt-surface-shadow:0 4px 12px -2px rgba(0,0,0,.36); - --okt-close-bg:#2c2c2e; - --okt-close-text:#9b9aa7; - --okt-close-hover-text:#fff; - --okt-close-ring:0 0 0 1px rgba(255,255,255,.1); - --okt-focus-ring:rgba(255,255,255,.32); -} -[data-okt-shell]{ - position:relative; - width:100%; - height:100%; - box-sizing:border-box; -} -[data-okt-surface]{ - position:relative; - display:flex; - align-items:center; - width:100%; - height:100%; - padding:var(--okt-card-padding); - border-radius:var(--okt-card-radius); - background:var(--okt-card-bg,var(--okt-surface-bg)); - color:var(--okt-surface-text); - box-shadow:0 0 0 1px var(--okt-card-border,var(--okt-surface-border)),var(--okt-surface-shadow); - box-sizing:border-box; - overflow:hidden; -} -:where([data-onekey-toast]:focus-visible) [data-okt-surface]{ - box-shadow:0 0 0 1px var(--okt-card-border,var(--okt-surface-border)),var(--okt-surface-shadow),0 0 0 2px var(--okt-focus-ring); -} -[data-okt-body]{ - display:flex; - align-items:center; - min-width:0; - flex:1 1 auto; - transition:opacity 300ms ease; -} -:where([data-onekey-toast][data-expanded="false"][data-front="false"]) [data-okt-body]{ - opacity:0; -} - -/* Corner close button outside the squircle clip */ -:where([data-onekey-toast]) :where([data-close-button]){ - position:absolute; - left:var(--toast-close-button-start); - right:var(--toast-close-button-end); - top:-6px; - height:20px; - width:20px; - display:grid; - place-items:center; - padding:0; - border:0; - background:var(--okt-close-bg); - color:var(--okt-close-text); - box-shadow:var(--okt-close-ring); - border-radius:50%; - cursor:pointer; - z-index:2; - pointer-events:none; - opacity:0; - outline:none; - transition:opacity 160ms ease,color 150ms ease,transform 120ms ease; -} -:where([data-onekey-toast][data-okt-close-hover]) :where([data-close-button]){ - pointer-events:auto; - opacity:1; -} -:where([data-onekey-toast]) :where([data-close-button]):focus-visible{ - opacity:1; -} -:where([data-onekey-toast]) :where([data-close-button]):hover{ - color:var(--okt-close-hover-text); -} -:where([data-onekey-toast]) :where([data-close-button]):active{ - transform:scale(.92); -} -:where([data-onekey-toast]) :where([data-close-button]):focus-visible{ - box-shadow:var(--okt-close-ring),0 0 0 2px var(--okt-focus-ring); -} - -@media (max-width:600px){ - [data-onekey-toast-toaster]{--toast-vertical-offset:20px;left:50%;right:auto;transform:translateX(-50%)} -} - -@media (horizontal-viewport-segments:2){ - [data-onekey-toast-toaster]{ - --toast-segment-width:env(viewport-segment-width 0 0); - left:calc(env(viewport-segment-left 0 0) + var(--toast-segment-width) / 2); - right:auto; - transform:translateX(-50%); - } - [data-onekey-toast-toaster]:is([data-x-position="right"],[data-x-position="center"][dir="rtl"]){ - --toast-segment-width:env(viewport-segment-width 1 0); - left:calc(env(viewport-segment-left 1 0) + var(--toast-segment-width) / 2); - } -} - -@media (vertical-viewport-segments:2){ - [data-onekey-toast-toaster][data-y-position="top"]{ - --toast-segment-top:env(viewport-segment-top 0 0); - --toast-segment-bottom:env(viewport-segment-bottom 0 0); - --toast-obstruction-top:0px; - top:max(min(var(--toast-obstruction-top),calc(var(--toast-segment-bottom) - var(--toast-obstruction-room,88px))),calc(var(--toast-segment-top) + max(var(--toast-vertical-offset),env(safe-area-inset-top)))); - } - [data-onekey-toast-toaster][data-y-position="bottom"]{ - --toast-segment-top:env(viewport-segment-top 0 1); - --toast-segment-bottom:env(viewport-segment-bottom 0 1); - } -} +[data-onekey-toast][data-swiping="true"]{transform:var(--y) translateY(var(--swipe-amount,0px));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 .2s ease-out forwards} +@keyframes onekey-toast-swipe-out{0%{transform:translateY(calc(var(--lift) * var(--offset) + var(--swipe-amount)));opacity:1}to{transform:translateY(calc(var(--lift) * var(--offset) + var(--swipe-amount) + var(--lift) * -100%));opacity:0}} +@media (max-width:600px){[data-onekey-toast-toaster]{position:fixed;--mobile-offset:16px;right:var(--mobile-offset);left:var(--mobile-offset);width:100%}[data-onekey-toast-toaster] [data-onekey-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset) * 2)}[data-onekey-toast-toaster][data-x-position="left"]{left:var(--mobile-offset)}[data-onekey-toast-toaster][data-y-position="bottom"]{bottom:20px}[data-onekey-toast-toaster][data-y-position="top"]{top:20px}[data-onekey-toast-toaster][data-x-position="center"]{left:var(--mobile-offset);right:var(--mobile-offset);transform:none}} +[data-onekey-toast-toaster][data-theme="light"]{--normal-bg:#fff;--normal-border:var(--gray4);--normal-text:var(--gray12);--success-bg:hsl(143, 85%, 96%);--success-border:hsl(145, 92%, 91%);--success-text:hsl(140, 100%, 27%);--info-bg:hsl(208, 100%, 97%);--info-border:hsl(221, 91%, 91%);--info-text:hsl(210, 92%, 45%);--warning-bg:hsl(49, 100%, 97%);--warning-border:hsl(49, 91%, 91%);--warning-text:hsl(31, 92%, 45%);--error-bg:hsl(359, 100%, 97%);--error-border:hsl(359, 100%, 94%);--error-text:hsl(360, 100%, 45%)} +[data-onekey-toast-toaster][data-theme="light"] [data-onekey-toast][data-invert="true"]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1)} +[data-onekey-toast-toaster][data-theme="dark"] [data-onekey-toast][data-invert="true"]{--normal-bg:#fff;--normal-border:var(--gray3);--normal-text:var(--gray12)} +[data-onekey-toast-toaster][data-theme="dark"]{--normal-bg:#000;--normal-border:hsl(0, 0%, 20%);--normal-text:var(--gray1);--success-bg:hsl(150, 100%, 6%);--success-border:hsl(147, 100%, 12%);--success-text:hsl(150, 86%, 65%);--info-bg:hsl(215, 100%, 6%);--info-border:hsl(223, 100%, 12%);--info-text:hsl(216, 87%, 65%);--warning-bg:hsl(64, 100%, 6%);--warning-border:hsl(60, 100%, 12%);--warning-text:hsl(46, 87%, 65%);--error-bg:hsl(358, 76%, 10%);--error-border:hsl(357, 89%, 16%);--error-text:hsl(358, 100%, 81%)} +[data-rich-colors="true"] [data-onekey-toast][data-type="success"],[data-rich-colors="true"] [data-onekey-toast][data-type="success"] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)} +[data-rich-colors="true"] [data-onekey-toast][data-type="info"],[data-rich-colors="true"] [data-onekey-toast][data-type="info"] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)} +[data-rich-colors="true"] [data-onekey-toast][data-type="warning"],[data-rich-colors="true"] [data-onekey-toast][data-type="warning"] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)} +[data-rich-colors="true"] [data-onekey-toast][data-type="error"],[data-rich-colors="true"] [data-onekey-toast][data-type="error"] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)} +@media (prefers-reduced-motion){[data-onekey-toast],[data-onekey-toast]>*{transition:none!important;animation:none!important}} [data-onekey-toast-section]{pointer-events:bounding-box} [data-okt-root]{display:flex;flex-direction:column;align-items:stretch;flex:1 1 auto;min-width:0;min-height:0;position:relative;box-sizing:border-box;max-height:var(--okt-max-height,none);overflow:hidden} -[data-okt-row]{display:flex;flex-direction:row;align-items:center;flex-shrink:0;min-width:0;min-height:0;position:relative;box-sizing:border-box} -[data-okt-row][data-okt-layout="notification"]{align-items:flex-start} -[data-okt-col]{display:flex;flex-direction:column;align-items:stretch;justify-content:center;flex:1 1 auto;min-width:0;min-height:0;position:relative;box-sizing:border-box} -[data-okt-col][data-okt-message-col]{min-height:${TOAST_GEOMETRY.tileSize}px} -[data-okt-col][data-okt-no-icon]{padding-inline-start:${TOAST_GEOMETRY.noIconPaddingStart}px} -[data-okt-col][data-okt-content-swap]{animation:onekey-toast-content-swap ${TOAST_MOTION.contentSwapMs}ms cubic-bezier(.2,0,0,1) both} -@keyframes onekey-toast-content-swap{ - from{opacity:0;transform:translateY(3px)} - to{opacity:1;transform:translateY(0)} -} -[data-okt-icon-box]{display:flex;flex-direction:column;align-items:center;justify-content:center;flex-shrink:0;position:relative;box-sizing:border-box} -[data-okt-status-tile]{ - display:block;position:relative;flex-shrink:0;overflow:hidden; - --okt-status-ease-in:${leaveEase}; - --okt-status-ease-out:${strokeEase}; - --okt-status-tint-ease:${tintEase}; -} -[data-okt-status-glyph]{position:absolute;inset:0;display:grid;place-items:center} -[data-okt-status-glyph] svg{display:block;width:50%;height:50%} -[data-okt-status-outgoing]{display:none} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion]{ - --okt-status-pop:${glyphDelayMs}ms;--okt-status-draw:${drawDelayMs}ms; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion="enter"]{ - animation:onekey-status-tile-in ${springs.tile.durationMs}ms ${tileDelayMs}ms linear both; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion="settle"]{ - --okt-status-pop:${TOAST_MOTION.glyphLeaveMs}ms;--okt-status-draw:${settleDrawDelayMs}ms; - transition:background-color ${TOAST_MOTION.tileTintMs}ms var(--okt-status-tint-ease),color ${TOAST_MOTION.tileTintMs}ms var(--okt-status-tint-ease); - animation:onekey-status-tile-bump ${TOAST_MOTION.tileBumpMs}ms ${TOAST_MOTION.glyphLeaveMs}ms ${bumpEase} both; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion="immediate"]{ - --okt-status-pop:0ms;--okt-status-draw:${TOAST_MOTION.strokeDelayOffsetMs}ms; - transition:background-color ${TOAST_MOTION.tileTintMs}ms var(--okt-status-tint-ease),color ${TOAST_MOTION.tileTintMs}ms var(--okt-status-tint-ease); - animation:onekey-status-tile-bump ${TOAST_MOTION.tileBumpMs}ms ${bumpEase} both; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion] [data-okt-status-glyph]:not([data-okt-status-outgoing]){ - animation:onekey-status-pop ${springs.glyph.durationMs}ms var(--okt-status-pop) linear both; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion] [data-okt-status-outgoing]{ - display:grid;animation:onekey-status-leave ${TOAST_MOTION.glyphLeaveMs}ms var(--okt-status-ease-in) both; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion] [data-okt-status-stroke]{ - stroke-dasharray:1 1;animation:onekey-status-draw ${TOAST_MOTION.strokeDrawMs}ms var(--okt-status-draw) var(--okt-status-ease-out) both; -} -[data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-icon-box] [data-okt-status-ring]{ - animation:onekey-toast-spin ${TOAST_MOTION.spinnerPeriodMs}ms linear infinite; -} -/* Fallback keyframes for browsers without CSS linear() easing. */ -@keyframes onekey-status-tile-in{ - from{opacity:0;transform:scale(.85)} - 30%{opacity:.63;transform:scale(.945)} - 60%{opacity:.93;transform:scale(.99)} - to{opacity:1;transform:scale(1)} -} -@keyframes onekey-status-pop{ - from{opacity:0;transform:scale(.4)} - 35%{opacity:1;transform:scale(1.0386)} - 65%{opacity:1;transform:scale(1.007)} - to{opacity:1;transform:scale(1)} -} -@supports (animation-timing-function:linear(0,1)){ - [data-onekey-toast-toaster]{ - --okt-card-spring-ease:${springs.card.easing}; - } - [data-okt-status-tile]{ - --okt-tile-spring:${springs.tile.easing}; - --okt-glyph-spring:${springs.glyph.easing}; - } - [data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion="enter"]{ - animation:onekey-status-tile-scale ${springs.tile.durationMs}ms ${tileDelayMs}ms var(--okt-tile-spring) both, - onekey-status-opacity-in ${springs.tile.durationMs}ms ${tileDelayMs}ms var(--okt-tile-spring) both; - } - [data-onekey-toast][data-mounted="true"][data-removed="false"] [data-okt-status-motion] [data-okt-status-glyph]:not([data-okt-status-outgoing]){ - animation:onekey-status-glyph-scale ${springs.glyph.durationMs}ms var(--okt-status-pop) var(--okt-glyph-spring) both, - onekey-status-opacity-in ${springs.glyph.durationMs}ms var(--okt-status-pop) var(--okt-glyph-spring) both; - } -} -@keyframes onekey-status-tile-scale{ - from{transform:scale(.85)} - to{transform:scale(1)} -} -@keyframes onekey-status-glyph-scale{ - from{transform:scale(.4)} - to{transform:scale(1)} -} -@keyframes onekey-status-opacity-in{ - from{opacity:0} - to{opacity:1} -} -@keyframes onekey-status-draw{ - from{opacity:0;stroke-dashoffset:1} - .01%{opacity:1;stroke-dashoffset:1} - to{opacity:1;stroke-dashoffset:0} -} -@keyframes onekey-status-leave{ - from{opacity:var(--okt-glyph-from-opacity);transform:var(--okt-glyph-from-transform)} - to{opacity:0;transform:scale(.5)} -} -@keyframes onekey-status-tile-bump{ - from{opacity:var(--okt-tile-from-opacity);transform:var(--okt-tile-from-scale)} - 40%{opacity:1;transform:scale(${TOAST_MOTION.tileBumpPeakScale})} - to{opacity:1;transform:scale(1)} -} -@media (prefers-reduced-motion:reduce){ - [data-okt-respect-reduced-motion="true"] [data-onekey-toast], - [data-okt-respect-reduced-motion="true"] [data-onekey-toast] *, - [data-okt-respect-reduced-motion="true"] [data-okt-status-tile], - [data-okt-respect-reduced-motion="true"] [data-okt-status-tile] *{animation:none!important;transition:none!important} - [data-okt-respect-reduced-motion="true"] [data-okt-status-stroke]{stroke-dasharray:none!important} - [data-okt-respect-reduced-motion="true"] [data-okt-status-outgoing]{display:none!important} - [data-okt-respect-reduced-motion="true"] [data-okt-action]:active{transform:none} -} +[data-okt-row]{display:flex;flex-direction:row;align-items:stretch;flex-shrink:0;min-width:0;min-height:0;position:relative;box-sizing:border-box} +[data-okt-col]{display:flex;flex-direction:column;align-items:stretch;flex:1 1 auto;min-width:0;min-height:0;position:relative;box-sizing:border-box} +[data-okt-icon-box]{display:flex;flex-direction:column;align-items:stretch;flex-shrink:0;position:relative;box-sizing:border-box} [data-okt-icon]{display:block;flex-shrink:0} [data-okt-badge]{display:flex;flex-direction:row;align-items:center;justify-content:center;flex-shrink:0;border-radius:9999px;box-sizing:border-box} [data-okt-paragraphs]{display:flex;flex-direction:column;align-items:stretch;flex-shrink:0;min-width:0;position:relative;box-sizing:border-box} @@ -356,33 +67,18 @@ function buildOverlayToastCss(): string { [data-okt-link]{cursor:pointer;text-decoration-line:underline} [data-okt-link]:hover{background-color:var(--okt-link-hover,transparent)} [data-okt-link]:active{background-color:var(--okt-link-active,transparent)} -[data-okt-actions][hidden]{display:none} [data-okt-actions]{display:flex;flex-direction:row;flex-shrink:0;gap:8px;box-sizing:border-box} -[data-okt-action]{ - display:flex;flex-direction:row;align-items:center;justify-content:center;flex-shrink:0; - box-sizing:border-box;margin:0;border:0 solid rgba(170,170,170,0); - cursor:pointer;font:inherit;font-variant-numeric:normal;white-space:nowrap; - outline:none;appearance:none;-webkit-appearance:none; - background-color:var(--okt-action-bg); - padding:var(--okt-action-padding);border-radius:var(--okt-action-radius); - transition:background-color 150ms ease,transform 120ms ease; -} -[data-okt-action][data-okt-inline-action]{ - min-height:${TOAST_GEOMETRY.actionHeight}px; - padding:0 var(--okt-inline-padding); - border-radius:${TOAST_GEOMETRY.actionRadius}px; -} +[data-okt-action]{display:flex;flex-direction:row;align-items:center;justify-content:center;flex-shrink:0;box-sizing:border-box;margin:0;border:0 solid rgba(170,170,170,0);cursor:default;font:inherit;font-variant-numeric:normal;white-space:pre-wrap;outline:none;appearance:none;-webkit-appearance:none;background-color:var(--okt-action-bg);transition:none} [data-okt-action]:hover{background-color:var(--okt-action-hover,var(--okt-action-bg))} -[data-okt-action]:active:not(:disabled){background-color:var(--okt-action-active,var(--okt-action-bg));transform:scale(.95)} +[data-okt-action]:active{background-color:var(--okt-action-active,var(--okt-action-bg))} [data-okt-action]:focus-visible{outline:2px solid var(--okt-action-ring,transparent);outline-offset:2px} -[data-okt-action]:disabled{background-color:var(--okt-action-bg);cursor:default} +[data-okt-action]:disabled{background-color:var(--okt-action-bg)} [data-okt-image]{display:block;flex-shrink:0;object-fit:cover} [data-okt-spinner]{display:block;flex-shrink:0;animation:onekey-toast-spin .75s linear infinite} @keyframes onekey-toast-spin{0%{transform:rotate(0deg)}to{transform:rotate(360deg)}} [data-okt-pressable]{cursor:pointer} @media (prefers-reduced-motion){[data-okt-spinner]{animation:none!important}} `; -} let injected = false; @@ -396,6 +92,6 @@ export function ensureOverlayToastStyles() { } const style = document.createElement('style'); style.id = STYLE_ID; - style.appendChild(document.createTextNode(buildOverlayToastCss())); + style.appendChild(document.createTextNode(CSS)); (document.head ?? document.documentElement).appendChild(style); } diff --git a/native-views/react-native-native-overlay/src/toast/types.ts b/native-views/react-native-native-overlay/src/toast/types.ts index 653faf8af..71ae25456 100644 --- a/native-views/react-native-native-overlay/src/toast/types.ts +++ b/native-views/react-native-native-overlay/src/toast/types.ts @@ -65,22 +65,6 @@ export interface IOverlayToastText { linkPressedColor?: string; } -export type IOverlayToastStatus = - | 'success' - | 'error' - | 'warning' - | 'info' - | 'loading'; - -export interface IOverlayToastStatusIcon { - kind: 'status'; - status: IOverlayToastStatus; - color: string; - backgroundColor: string; - /** Edge of the square tile, including the centered glyph. */ - size: number; -} - export type IOverlayToastIcon = | { kind: 'icon'; @@ -92,8 +76,7 @@ export type IOverlayToastIcon = size: number; } | { kind: 'spinner'; color: string; size: number } - | { kind: 'image'; uri: string; size: number; borderRadius?: number } - | IOverlayToastStatusIcon; + | { kind: 'image'; uri: string; size: number; borderRadius?: number }; export interface IOverlayToastAction { /** Opaque id reported through `onAction`. */ @@ -150,8 +133,6 @@ interface IOverlayToastBase { export interface IOverlayMessageToast extends IOverlayToastBase { layout: 'message'; icon?: IOverlayToastIcon; - /** Takes precedence over icon. Older renderers continue to show icon. */ - statusIcon?: IOverlayToastStatusIcon; title?: IOverlayToastText; message?: IOverlayToastText; actions?: IOverlayToastAction[]; @@ -201,14 +182,11 @@ export interface IOverlayToasterConfig { position?: IOverlayToastPosition; /** Web chrome follows this; native reads `cardColor`. */ theme?: 'light' | 'dark'; - /** Card surface colour on native and web. */ + /** Native card surface. */ cardColor?: string; - /** Subtle inner hairline stroke colour on native and web. */ - cardBorderColor?: string; /** * Native: the width of the card's content box. The card adds its own - * padding around it and constrains the result to the available area and - * a maximum outer width of 596 points or dp. + * padding around it. */ contentWidth?: number; /** Native: the tallest a card's content may grow. */ diff --git a/native-views/react-native-native-overlay/tests/browser/overlayToast.test.cjs b/native-views/react-native-native-overlay/tests/browser/overlayToast.test.cjs index 9e4d23ab3..781a6ff55 100644 --- a/native-views/react-native-native-overlay/tests/browser/overlayToast.test.cjs +++ b/native-views/react-native-native-overlay/tests/browser/overlayToast.test.cjs @@ -29,28 +29,6 @@ before(async () => { lineHeight: 20, fontWeight: '600', }); window.callbacks = []; - const statusSpec = (status, colors = {}) => ({ - id: 'status', layout: 'message', duration: Infinity, - title: text(status), position: 'top-center', - icon: { kind: 'icon', name: 'Fallback', size: 20, color: '#111' }, - statusIcon: { - kind: 'status', status, size: 36, color: status === 'loading' ? '#655' : '#fff', - backgroundColor: status === 'loading' ? '#bbb' : '#2a5', - ...colors, - }, - }); - window.showStatus = (status, extra = {}) => - store.show({ ...statusSpec(status), ...extra }, { - onAction: (id) => window.callbacks.push(id), - }); - window.redrawStatus = (status, colors) => store.update(statusSpec(status, colors)); - window.moveStatus = (id, position) => { - const { spec } = store.getSnapshot().items.find((item) => item.spec.id === id); - store.update({ ...spec, position }); - }; - window.dismissStatus = () => store.dismiss('status'); - window.configure = (config) => store.configure(config); - window.dismissNotification = () => store.dismiss('notification'); window.showToast = (duration, position) => { store.show({ id: 'notification', layout: 'notification', @@ -104,269 +82,6 @@ function callbacks(page) { return page.evaluate(() => window.callbacks); } -async function statusPage(t, reducedMotion = 'no-preference') { - const context = await browser.newContext({ reducedMotion }); - t.after(() => context.close()); - const page = await context.newPage(); - await page.setContent( - '
Page content
' - ); - await page.addScriptTag({ content: bundle }); - return page; -} - -test('status motion stages the tile, pop and directed strokes independently', async (t) => { - const page = await statusPage(t); - const sample = await page.evaluate(() => { - const glyph = '[data-okt-status-glyph]'; - const tile = '[data-okt-status-tile]'; - const stroke = '[data-okt-status-stroke]'; - const style = (selector) => - getComputedStyle(document.querySelector(selector)); - const pointAt = (path, length) => { - const { x, y } = path.getPointAtLength(length); - return { x, y }; - }; - const sampleAt = (ms) => { - document.getAnimations().forEach((animation) => { - animation.pause(); - animation.currentTime = ms; - }); - return { - tileOpacity: Number(style(tile).opacity), - glyphOpacity: Number(style(glyph).opacity), - scale: new DOMMatrix(style(glyph).transform).a, - strokes: Array.from(document.querySelectorAll(stroke), (path) => ({ - offset: parseFloat(getComputedStyle(path).strokeDashoffset), - length: path.getTotalLength(), - start: pointAt(path, 0), - end: pointAt(path, path.getTotalLength()), - })), - }; - }; - window.showStatus('success'); - const entrance = sampleAt(90); - const tileOnly = sampleAt(135); - const glyphPop = sampleAt(195); - const halfDraw = sampleAt(265); - const peak = sampleAt(293); - const result = sampleAt(410); - const tileSize = document.querySelector(tile).offsetWidth; - const glyphSize = Number(style(`${glyph} svg`).width.replace('px', '')); - const tileDurations = style(tile).animationDuration; - const glyphDurations = style(glyph).animationDuration; - const drawEase = style(stroke).animationTimingFunction; - window.dismissStatus(); - window.showStatus('error'); - return { - entrance, - tileOnly, - glyphPop, - halfDraw, - peak, - result, - tileSize, - glyphSize, - tileDurations, - glyphDurations, - drawEase, - error: sampleAt(265), - }; - }); - assert.equal(sample.entrance.tileOpacity, 0); - assert.ok(sample.tileOnly.tileOpacity > 0); - assert.equal(sample.tileOnly.glyphOpacity, 0); - assert.ok(sample.glyphPop.glyphOpacity > 0 && sample.glyphPop.scale < 1); - assert.ok(Math.abs(sample.peak.scale - 1.0385) < 0.001); - assert.equal(sample.glyphPop.strokes[0].offset, 1); - assert.ok( - sample.halfDraw.strokes[0].offset > 0 && - sample.halfDraw.strokes[0].offset < 1 - ); - assert.equal(sample.result.strokes[0].offset, 0); - assert.equal(sample.tileSize, 36); - assert.equal(sample.glyphSize, 18); - assert.equal(sample.tileDurations, '0.376s, 0.376s'); - assert.equal(sample.glyphDurations, '0.342s, 0.342s'); - assert.equal(sample.drawEase, 'cubic-bezier(0, 0, 0.58, 1)'); - assert.equal(sample.result.strokes.length, 1); - assert.equal(sample.result.strokes[0].start.x, 6); - assert.equal(sample.result.strokes[0].end.x, 18); - assert.equal(sample.error.strokes.length, 2); - assert.deepEqual( - sample.error.strokes.map(({ start, end }) => [start.y, end.y]), - [ - [7.5, 16.5], - [7.5, 16.5], - ] - ); - assert.equal(sample.error.strokes[0].offset, sample.error.strokes[1].offset); -}); - -test('loading settles within the same card and tile and keeps motion on redraw', async (t) => { - const page = await statusPage(t); - const sample = await page.evaluate(() => { - const tileSelector = '[data-okt-status-tile]'; - const glyph = '[data-okt-status-glyph]:not([data-okt-status-outgoing])'; - const tile = () => document.querySelector(tileSelector); - const seek = (ms) => { - document - .querySelector('[data-onekey-toast]') - .getAnimations({ subtree: true }) - .forEach((animation) => { - animation.pause(); - animation.currentTime = ms; - }); - }; - window.showStatus('loading'); - const card = document.querySelector('[data-onekey-toast]'); - const originalTile = tile(); - seek(205); - const loading = originalTile.querySelector(glyph); - const expectedOpacity = getComputedStyle(loading).opacity; - const expectedTransform = getComputedStyle(loading).transform; - const spinDuration = getComputedStyle( - loading.querySelector('svg') - ).animationDuration; - window.showStatus('success'); - const outgoing = tile().querySelector('[data-okt-status-outgoing]'); - const startingOpacity = outgoing?.style.getPropertyValue( - '--okt-glyph-from-opacity' - ); - const startingTransform = outgoing?.style.getPropertyValue( - '--okt-glyph-from-transform' - ); - seek(45); - const incoming = tile().querySelector(glyph); - const incomingBeforeDeparture = Number(getComputedStyle(incoming).opacity); - const fadingOpacity = Number(getComputedStyle(outgoing).opacity); - const tint = getComputedStyle(tile()).backgroundColor; - const glyphColor = getComputedStyle(outgoing).color; - const tintEase = getComputedStyle(tile()).transitionTimingFunction; - const leaveEase = getComputedStyle(outgoing).animationTimingFunction; - const bumpEase = getComputedStyle(tile()).animationTimingFunction; - const pop = incoming.getAnimations()[0]; - window.redrawStatus('success', { color: '#ffe' }); - const redrawnColor = tile().style.color; - const keptPop = pop === incoming.getAnimations()[0]; - seek(185); - const drawing = parseFloat( - getComputedStyle(incoming.querySelector('path')).strokeDashoffset - ); - const sameCard = document.querySelector('[data-onekey-toast]') === card; - const sameTile = tile() === originalTile; - window.dismissStatus(); - return { - sameCard, - sameTile, - expectedOpacity, - startingOpacity, - expectedTransform, - startingTransform, - incomingBeforeDeparture, - fadingOpacity, - tint, - glyphColor, - spinDuration, - tintEase, - leaveEase, - bumpEase, - keptPop, - redrawnColor, - drawing, - stopped: - !tile().hasAttribute('data-okt-status-motion') && - !tile().contains(outgoing), - }; - }); - assert.ok( - sample.sameCard && sample.sameTile && sample.keptPop && sample.stopped - ); - assert.equal(sample.redrawnColor, 'rgb(255, 255, 238)'); - assert.equal(sample.startingOpacity, sample.expectedOpacity); - assert.equal(sample.startingTransform, sample.expectedTransform); - assert.equal(sample.incomingBeforeDeparture, 0); - assert.ok( - sample.fadingOpacity > 0 && - sample.fadingOpacity < Number(sample.expectedOpacity) - ); - assert.notEqual(sample.tint, 'rgb(187, 187, 187)'); - assert.notEqual(sample.tint, 'rgb(34, 170, 85)'); - assert.notEqual(sample.glyphColor, 'rgb(102, 85, 85)'); - assert.notEqual(sample.glyphColor, 'rgb(255, 255, 255)'); - assert.equal(sample.spinDuration, '0.85s'); - assert.equal( - sample.tintEase, - 'cubic-bezier(0.4, 0, 0.2, 1), cubic-bezier(0.4, 0, 0.2, 1)' - ); - assert.equal(sample.leaveEase, 'cubic-bezier(0.42, 0, 1, 1)'); - assert.equal(sample.bumpEase, 'cubic-bezier(0, 0, 0.58, 1)'); - assert.ok(sample.drawing > 0 && sample.drawing < 1); -}); - -test('immediate completion skips the unshown loading glyph; reduced motion remains static', async (t) => { - const page = await statusPage(t); - const immediate = await page.evaluate(() => { - window.showStatus('loading'); - const tile = document.querySelector('[data-okt-status-tile]'); - window.showStatus('error'); - return [ - tile === document.querySelector('[data-okt-status-tile]'), - tile.getAttribute('data-okt-status-motion'), - !!tile.querySelector('[data-okt-status-outgoing]'), - ]; - }); - assert.deepEqual(immediate, [true, 'immediate', false]); - const reduced = await statusPage(t, 'reduce'); - const staticGlyphs = await reduced.evaluate(() => { - window.showStatus('loading'); - const tile = document.querySelector('[data-okt-status-tile]'); - const initial = tile.getAnimations({ subtree: true }).length; - window.showStatus('error'); - const strokes = Array.from( - tile.querySelectorAll('path'), - (path) => getComputedStyle(path).strokeDasharray - ); - return [initial, tile.getAnimations({ subtree: true }).length, strokes]; - }); - assert.deepEqual(staticGlyphs, [0, 0, ['none', 'none']]); -}); - -test('warning and info keep their dots static while the stems draw downward', async (t) => { - const page = await statusPage(t, 'reduce'); - const sample = await page.evaluate(() => { - window.configure({ respectReducedMotion: false }); - return ['warning', 'info'].map((status) => { - window.dismissStatus(); - window.showStatus(status); - const tile = document.querySelector('[data-okt-status-tile]'); - const stroke = tile.querySelector('[data-okt-status-stroke]'); - const dot = tile.querySelector('[data-okt-status-dot]'); - const initial = stroke.getPointAtLength(0); - const final = stroke.getPointAtLength(stroke.getTotalLength()); - const dotY = Number(dot.getAttribute('cy')); - return { - stem: [initial.y, final.y], - dotY, - dotAnimations: dot.getAnimations().length, - strokeAnimations: stroke.getAnimations().length, - }; - }); - }); - assert.deepEqual(sample[0], { - stem: [6, 13], - dotY: 18, - dotAnimations: 0, - strokeAnimations: 1, - }); - assert.deepEqual(sample[1], { - stem: [11, 18], - dotY: 6.25, - dotAnimations: 0, - strokeAnimations: 1, - }); -}); - async function touchInput(context, page) { const session = await context.newCDPSession(page); return (type, touchPoints = []) => @@ -391,10 +106,9 @@ test('a touch drag ending within the card resumes its close timer', async (t) => const box = await card.boundingBox(); const x = Math.round(box.x + box.width / 2); const y = Math.round(box.y + 8); - const drag = Math.max(24, Math.round(box.height - 16)); await send('touchStart', [{ x, y }]); - await send('touchMove', [{ x, y: y + drag }]); - assert.ok(y + drag < box.y + box.height); + await send('touchMove', [{ x, y: y + 64 }]); + assert.ok(y + 64 < box.y + box.height); await send('touchEnd'); await card.waitFor({ state: 'detached', timeout: 2000 }); assert.deepEqual(await callbacks(page), ['timeout']); @@ -421,7 +135,7 @@ for (const [position, direction] of [ ['top-center', -1], ['bottom-right', 1], ]) { - test(`a ${position} swipe stays horizontal after vertical drift`, async (t) => { + test(`a ${position} swipe stays vertical after sideways drift`, async (t) => { const { context, page, card } = await showToast(t, { touch: true, position, @@ -431,22 +145,22 @@ for (const [position, direction] of [ const x = Math.round(box.x + box.width / 2); const y = Math.round(box.y + box.height / 2); await send('touchStart', [{ x, y }]); - await send('touchMove', [{ x: x + 48 * direction, y }]); + await send('touchMove', [{ x, y: y + 28 * direction }]); await page.waitForFunction( (amount) => document .querySelector('[data-onekey-toast]') .style.getPropertyValue('--swipe-amount') === amount, - `${48 * direction}px`, + `${28 * direction}px`, { timeout: 1000 } ); - await send('touchMove', [{ x: x + 72 * direction, y: y + 41 }]); + await send('touchMove', [{ x: x + 41, y: y + 30 * direction }]); await page.waitForFunction( (amount) => document .querySelector('[data-onekey-toast]') .style.getPropertyValue('--swipe-amount') === amount, - `${72 * direction}px`, + `${30 * direction}px`, { timeout: 1000 } ); await send('touchEnd'); @@ -454,881 +168,3 @@ for (const [position, direction] of [ assert.deepEqual(await callbacks(page), ['swipe']); }); } - -test('card adopts concentric squircle chrome, a hover close button and an inline right action', async (t) => { - const page = await statusPage(t); - await page.evaluate(() => { - window.configure({ - theme: 'dark', - cardColor: '#1b1b1b', - cardBorderColor: 'rgba(255, 255, 255, 0.1)', - }); - window.showStatus('success', { - actions: [ - { - id: 'view', - label: 'View', - color: '#fff', - backgroundColor: '#2c2c2e', - fontSize: 13, - lineHeight: 18, - fontWeight: '600', - paddingHorizontal: 14, - paddingVertical: 7, - borderRadius: 11, - }, - ], - }); - }); - - const card = page.locator('[data-onekey-toast]'); - const closeButton = page.locator('[data-close-button]'); - const metrics = await page.evaluate(() => { - const surface = document.querySelector('[data-okt-surface]'); - const tile = document.querySelector('[data-okt-status-tile]'); - const action = document.querySelector('[data-okt-inline-action]'); - const close = document.querySelector('[data-close-button]'); - const surfaceStyle = getComputedStyle(surface); - const actionBox = action.getBoundingClientRect(); - const tileBox = tile.getBoundingClientRect(); - return { - padding: surfaceStyle.padding, - radius: surfaceStyle.borderRadius, - boxShadow: surfaceStyle.boxShadow, - tileClip: tile.style.clipPath, - bg: surfaceStyle.backgroundColor, - closeOpacityIdle: Number(getComputedStyle(close).opacity), - actionHeight: action.offsetHeight, - actionRadius: getComputedStyle(action).borderRadius, - alignedVertically: - Math.abs( - tileBox.top + - tileBox.height / 2 - - (actionBox.top + actionBox.height / 2) - ) <= 1, - }; - }); - - assert.equal(metrics.padding, '10px'); - assert.equal(metrics.radius, '21px'); - assert.match(metrics.boxShadow, /0px 0px 0px 1px/); - assert.match(metrics.tileClip, /^path\(["']M/); - assert.equal(metrics.bg, 'rgb(27, 27, 27)'); - assert.equal(metrics.closeOpacityIdle, 0); - assert.equal(metrics.actionHeight, 36); - assert.equal(metrics.actionRadius, '11px'); - assert.equal(metrics.alignedVertically, true); - - await card.hover(); - await page.waitForFunction( - () => - Number( - getComputedStyle(document.querySelector('[data-close-button]')).opacity - ) > 0.9, - null, - { timeout: 1000 } - ); - assert.ok(await closeButton.isVisible()); -}); - -test('a wide icon action falls back on a narrow viewport and returns inline on resize', async (t) => { - const page = await statusPage(t, 'reduce'); - await page.setViewportSize({ width: 320, height: 800 }); - await page.evaluate(() => - window.showStatus('success', { - actions: [ - { - id: 'view', - label: 'MMMMMMMM', - borderRadius: 28, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - fontWeight: '600', - paddingHorizontal: 10, - paddingVertical: 4, - icon: { kind: 'icon', name: 'View', size: 20, color: '#111' }, - iconGap: 4, - }, - ], - }) - ); - const action = page.getByRole('button', { name: 'MMMMMMMM' }); - assert.equal(await action.getAttribute('data-okt-inline-action'), null); - assert.equal( - await action.evaluate((node) => getComputedStyle(node).borderRadius), - '28px' - ); - assert.ok( - await page - .locator('[data-okt-message-col]') - .evaluate((node) => node.clientWidth >= 96) - ); - await page.setViewportSize({ width: 820, height: 800 }); - await page.waitForSelector('[data-okt-inline-action]', { timeout: 2000 }); - assert.equal( - await action.evaluate((node) => getComputedStyle(node).borderRadius), - '11px' - ); -}); - -test('touch browsers keep close available to the keyboard and the idle corner passes through touch', async (t) => { - for (const isMobile of [true, false]) { - const context = await browser.newContext({ - hasTouch: true, - isMobile, - reducedMotion: 'reduce', - }); - t.after(() => context.close()); - const page = await context.newPage(); - await page.setContent( - '' - ); - await page.addScriptTag({ content: bundle }); - await page.evaluate(() => window.showStatus('success')); - const close = page.getByRole('button', { name: 'Close toast' }); - const box = await close.boundingBox(); - assert.ok(box); - assert.equal( - await close.evaluate((node) => getComputedStyle(node).pointerEvents), - 'none' - ); - await page.touchscreen.tap(box.x + 10, box.y + 10); - assert.equal( - await page.locator('[data-onekey-toast]').getAttribute('data-removed'), - 'false' - ); - await page.locator('[data-onekey-toast]').focus(); - await page.keyboard.press('Tab'); - assert.ok(await close.evaluate((node) => node === document.activeElement)); - assert.equal( - await close.evaluate((node) => getComputedStyle(node).opacity), - '1' - ); - await page.keyboard.press('Enter'); - await close.waitFor({ state: 'detached' }); - } -}); - -test('restoring motion resumes the ring without replaying a mounted status animation', async (t) => { - const page = await statusPage(t); - await page.evaluate(() => window.showStatus('loading')); - await page.emulateMedia({ reducedMotion: 'reduce' }); - await page.waitForFunction( - () => !document.querySelector('[data-okt-status-motion]') - ); - const ring = page.locator('[data-okt-status-ring]'); - assert.equal( - await ring.evaluate((node) => getComputedStyle(node).animationName), - 'none' - ); - await page.emulateMedia({ reducedMotion: 'no-preference' }); - await page.waitForFunction( - () => - document.querySelector('[data-okt-status-ring]').getAnimations() - .length === 1 - ); - assert.equal(await page.locator('[data-okt-status-motion]').count(), 0); - await page.evaluate(() => window.showStatus('success')); - await page.waitForSelector('[data-okt-status-outgoing]', { - state: 'attached', - }); - await page.emulateMedia({ reducedMotion: 'reduce' }); - await page.waitForSelector('[data-okt-status-outgoing]', { - state: 'detached', - }); - await page.emulateMedia({ reducedMotion: 'no-preference' }); - assert.equal(await page.locator('[data-okt-status-motion]').count(), 0); -}); - -test('a compact action stays reachable when lowering it would exceed the content height cap', async (t) => { - const page = await statusPage(t, 'reduce'); - await page.setViewportSize({ width: 232, height: 800 }); - await page.evaluate(() => - window.showStatus('success', { - title: { - paragraphs: [[{ text: 'Done' }]], - color: '#111', - fontSize: 16, - lineHeight: 24, - fontWeight: '600', - }, - actions: [ - { - id: 'view', - label: 'View', - borderRadius: 28, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - fontWeight: '600', - paddingHorizontal: 10, - paddingVertical: 4, - }, - ], - }) - ); - const action = page.getByRole('button', { name: 'View', exact: true }); - assert.equal(await action.getAttribute('data-okt-inline-action'), null); - await action.focus(); - - await page.evaluate(() => window.configure({ webContentMaxHeight: 36 })); - assert.equal(await action.getAttribute('data-okt-inline-action'), ''); - const geometry = await action.evaluate((node) => { - const root = node.closest('[data-okt-root]').getBoundingClientRect(); - const button = node.getBoundingClientRect(); - const column = node.parentElement.querySelector('[data-okt-message-col]'); - return { - cap: root.height, - fits: button.top >= root.top && button.bottom <= root.bottom, - textWidth: column.clientWidth, - focused: node === document.activeElement, - }; - }); - assert.equal(geometry.cap, 36); - assert.ok(geometry.fits && geometry.focused); - assert.ok(geometry.textWidth > 0 && geometry.textWidth < 96); - - await page.evaluate(() => window.configure({ webContentMaxHeight: 160 })); - assert.equal(await action.getAttribute('data-okt-inline-action'), null); -}); - -test('toasts beyond the display limit regain keyboard access only when visible', async (t) => { - const context = await browser.newContext({ - hasTouch: true, - isMobile: true, - reducedMotion: 'reduce', - }); - t.after(() => context.close()); - const page = await context.newPage(); - await page.setContent( - '' - ); - await page.addScriptTag({ content: bundle }); - await page.evaluate(() => { - for (let index = 0; index < 4; index += 1) { - window.showStatus('success', { - id: `status-${index}`, - testID: `status-${index}`, - }); - } - }); - - const oldest = page.getByTestId('status-0'); - assert.equal(await oldest.getAttribute('data-visible'), 'false'); - const cdp = await context.newCDPSession(page); - const { nodes } = await cdp.send('Accessibility.getFullAXTree'); - const accessibleCloseButtons = nodes.filter( - (node) => - !node.ignored && - node.role?.value === 'button' && - node.name?.value === 'Close toast' - ); - assert.equal(accessibleCloseButtons.length, 3); - await oldest.locator('[data-close-button]').focus(); - assert.equal( - await oldest.evaluate((node) => node.contains(document.activeElement)), - false - ); - - const frontClose = page - .getByTestId('status-3') - .getByRole('button', { name: 'Close toast' }); - await frontClose.press('Enter'); - await frontClose.waitFor({ state: 'detached', timeout: 2000 }); - const nowVisibleClose = oldest.getByRole('button', { name: 'Close toast' }); - assert.equal(await oldest.getAttribute('data-visible'), 'true'); - await nowVisibleClose.focus(); - assert.equal( - await nowVisibleClose.evaluate((node) => node === document.activeElement), - true - ); -}); - -test('collapsed back toast actions regain keyboard access after expansion or promotion', async (t) => { - const page = await statusPage(t, 'reduce'); - await page.evaluate(() => { - window.showStatus('success', { - id: 'back', - testID: 'back', - actions: [ - { - id: 'view', - label: 'View', - testID: 'view', - borderRadius: 11, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - fontWeight: '600', - paddingHorizontal: 14, - paddingVertical: 4, - }, - ], - }); - window.showStatus('success', { id: 'front', testID: 'front' }); - }); - - const back = page.getByTestId('back'); - const action = back.getByTestId('view'); - const actionHasFocus = () => - action.evaluate((node) => node === document.activeElement); - const backClose = back.getByRole('button', { name: 'Close toast' }); - await backClose.focus(); - assert.ok( - await backClose.evaluate((node) => node === document.activeElement) - ); - await action.focus(); - assert.equal(await actionHasFocus(), false); - - await page.keyboard.press('Alt+t'); - assert.equal(await back.getAttribute('data-expanded'), 'true'); - await action.focus(); - assert.ok(await actionHasFocus()); - await page.keyboard.press('Enter'); - assert.deepEqual(await callbacks(page), ['view']); - - await page.keyboard.press('Escape'); - assert.equal(await back.getAttribute('data-expanded'), 'false'); - assert.ok(await back.evaluate((node) => node === document.activeElement)); - await action.focus(); - assert.equal(await actionHasFocus(), false); - await page.keyboard.press('Enter'); - assert.deepEqual(await callbacks(page), ['view']); - - const frontClose = page - .getByTestId('front') - .getByRole('button', { name: 'Close toast' }); - await frontClose.press('Enter'); - await frontClose.waitFor({ state: 'detached', timeout: 2000 }); - assert.equal(await back.getAttribute('data-front'), 'true'); - await action.focus(); - assert.ok(await actionHasFocus()); - await page.keyboard.press('Enter'); - assert.deepEqual(await callbacks(page), ['view', 'view']); -}); - -test('collapse focus handoff preserves layout when a focus listener shows another toast', async (t) => { - const page = await statusPage(t, 'reduce'); - await page.evaluate(() => { - window.showStatus('success', { - id: 'back', - testID: 'back', - actions: [ - { - id: 'view', - label: 'View', - testID: 'view', - borderRadius: 11, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - fontWeight: '600', - paddingHorizontal: 14, - paddingVertical: 4, - }, - ], - }); - window.showStatus('success', { id: 'front', testID: 'front' }); - - function showOnShellFocus(event) { - if (event.target !== document.querySelector('[data-testid="back"]')) - return; - document.removeEventListener('focusin', showOnShellFocus); - window.showStatus('success', { id: 'new', testID: 'new' }); - } - document.addEventListener('focusin', showOnShellFocus); - }); - - await page.keyboard.press('Alt+t'); - const back = page.getByTestId('back'); - const action = back.getByTestId('view'); - await action.focus(); - await page.keyboard.press('Escape'); - - assert.ok(await back.evaluate((node) => node === document.activeElement)); - assert.deepEqual( - await page - .locator('[data-onekey-toast]') - .evaluateAll((cards) => - cards.map((card) => [ - card.dataset.testid, - card.dataset.index, - card.style.getPropertyValue('--offset'), - ]) - ), - [ - ['new', '0', '0px'], - ['front', '1', '66px'], - ['back', '2', '132px'], - ] - ); - - await page.keyboard.press('Alt+t'); - await action.focus(); - await page.evaluate(() => { - const outside = document.createElement('button'); - outside.id = 'outside-focus'; - document.body.append(outside); - document.activeElement.dispatchEvent( - new KeyboardEvent('keydown', { - code: 'Escape', - key: 'Escape', - bubbles: true, - }) - ); - outside.focus(); - }); - assert.equal(await back.getAttribute('data-expanded'), 'false'); - assert.equal( - await page.evaluate(() => document.activeElement.id), - 'outside-focus' - ); -}); - -test('narrow toast lanes and all three cards share the viewport center', async (t) => { - const page = await statusPage(t, 'reduce'); - for (const width of [320, 390, 600]) { - await page.setViewportSize({ width, height: 800 }); - for (const direction of ['ltr', 'rtl']) { - await page.evaluate((dir) => { - document.documentElement.dir = dir; - }, direction); - for (const position of ['top-left', 'top-center', 'bottom-right']) { - await page.evaluate((anchor) => { - for (const id of ['back', 'middle', 'front']) { - window.showStatus('success', { id, position: anchor }); - } - }, position); - - const lane = page.locator('[data-onekey-toast-toaster]'); - const laneBox = await lane.boundingBox(); - const label = `${width}px ${direction} ${position}`; - const expectedWidth = Math.min(356, width - 32); - assert.equal(laneBox.x, (width - expectedWidth) / 2, label); - assert.equal(laneBox.width, expectedWidth, label); - - const cards = lane.locator('[data-onekey-toast]'); - const assertCardCenters = async () => { - const centers = await cards.evaluateAll((nodes) => - nodes.map((node) => { - const { left, right } = node.getBoundingClientRect(); - return (left + right) / 2; - }) - ); - assert.equal(centers.length, 3, label); - for (const center of centers) { - assert.ok(Math.abs(center - width / 2) < 0.1, label); - } - }; - await assertCardCenters(); - await page.keyboard.press('Alt+t'); - assert.equal(await cards.first().getAttribute('data-expanded'), 'true'); - await assertCardCenters(); - await page.keyboard.press('Escape'); - assert.equal( - await cards.first().getAttribute('data-expanded'), - 'false' - ); - } - } - } - - await page.setViewportSize({ width: 601, height: 800 }); - const desktopLane = await page - .locator('[data-onekey-toast-toaster][data-x-position="right"]') - .boundingBox(); - assert.equal(desktopLane.width, 356); - assert.equal(601 - desktopLane.x - desktopLane.width, 32); -}); - -async function foldablePage(t) { - const page = await statusPage(t, 'reduce'); - await page.setViewportSize({ width: 740, height: 800 }); - const client = await page.context().newCDPSession(page); - const fold = (displayFeature) => - client.send('Emulation.setDeviceMetricsOverride', { - width: 740, - height: 800, - screenWidth: 740, - screenHeight: 800, - deviceScaleFactor: 1, - mobile: true, - displayFeature, - }); - return { page, fold, client }; -} - -test('a separating fold keeps a toast stack centered inside its selected pane', async (t) => { - const { page, fold } = await foldablePage(t); - await fold({ orientation: 'vertical', offset: 340, maskLength: 30 }); - - const lane = page.locator('[data-onekey-toast-toaster]'); - const showStack = (position, dir = 'ltr') => - page.evaluate( - ({ position, dir }) => { - document.documentElement.dir = dir; - for (const id of ['back', 'middle', 'front']) { - window.showStatus('success', { id, position }); - } - }, - { position, dir } - ); - - await page.waitForFunction( - () => matchMedia('(horizontal-viewport-segments: 2)').matches - ); - for (const [position, dir, left, width] of [ - ['top-center', 'ltr', 16, 308], - ['top-center', 'rtl', 386, 338], - ['top-left', 'rtl', 16, 308], - ['bottom-right', 'ltr', 386, 338], - ]) { - await showStack(position, dir); - const bounds = await lane.boundingBox(); - assert.equal(bounds.x, left); - assert.equal(bounds.width, width); - await page.keyboard.press('Alt+t'); - const boundsByCard = await lane - .locator('[data-onekey-toast]') - .evaluateAll((nodes) => - nodes.map((node) => { - const bounds = node.getBoundingClientRect(); - return [bounds.x, bounds.width]; - }) - ); - assert.deepEqual(boundsByCard, Array(3).fill([left, width])); - } - - await fold({ orientation: 'horizontal', offset: 370, maskLength: 30 }); - await page.waitForFunction( - () => matchMedia('(vertical-viewport-segments: 2)').matches - ); - await showStack('bottom-center'); - assert.equal((await lane.boundingBox()).y, 768); - - await fold(); - await page.waitForFunction( - () => !matchMedia('(vertical-viewport-segments: 2)').matches - ); - assert.equal((await lane.boundingBox()).x, 192); - assert.equal((await lane.boundingBox()).width, 356); - assert.deepEqual(await callbacks(page), []); -}); - -test('folded lanes merge by direction and remeasure a moved toast at its new width', async (t) => { - const { page, fold } = await foldablePage(t); - await fold({ orientation: 'vertical', offset: 255, maskLength: 30 }); - await page.waitForFunction( - () => matchMedia('(horizontal-viewport-segments: 2)').matches - ); - await page.evaluate(() => { - window.showStatus('success', { - id: 'left', - testID: 'left', - position: 'top-left', - }); - window.showStatus('success', { - id: 'center', - testID: 'center', - position: 'top-center', - }); - window.showStatus('success', { - id: 'right', - testID: 'right', - position: 'top-right', - title: { - paragraphs: [ - [ - { - text: 'Securely review the transaction details and the amount before choosing to continue.', - }, - ], - ], - fontSize: 14, - lineHeight: 20, - color: '#111', - }, - actions: [ - { - id: 'continue', - label: 'Review transaction details', - borderRadius: 11, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - paddingHorizontal: 12, - paddingVertical: 4, - }, - ], - }); - }); - const laneFor = (id) => - page.locator('[data-onekey-toast-toaster]').filter({ - has: page.getByTestId(id), - }); - const cardIDs = (lane) => - lane - .locator('[data-onekey-toast]') - .evaluateAll((nodes) => nodes.map((node) => node.dataset.testid)); - assert.deepEqual(await cardIDs(laneFor('center')), ['center', 'left']); - const right = page.getByTestId('right'); - const originalHeight = (await right.boundingBox()).height; - - await page.evaluate(() => { - document.documentElement.dir = 'rtl'; - }); - await page.waitForFunction( - () => - document.querySelector('[data-testid="center"]').parentElement === - document.querySelector('[data-testid="right"]').parentElement - ); - assert.deepEqual(await cardIDs(laneFor('center')), ['right', 'center']); - await page.evaluate(() => window.moveStatus('right', 'top-left')); - assert.deepEqual(await cardIDs(laneFor('left')), ['right', 'left']); - const bounds = await right.boundingBox(); - assert.ok( - bounds.height > originalHeight, - JSON.stringify({ originalHeight, bounds }) - ); - const action = right.getByRole('button', { - name: 'Review transaction details', - }); - const buttonBounds = await action.boundingBox(); - assert.ok(buttonBounds.y + buttonBounds.height <= bounds.y + bounds.height); - await action.click(); - assert.deepEqual(await callbacks(page), ['continue']); - - await fold(); - await page.waitForFunction( - () => - document.querySelector('[data-testid="center"]').parentElement !== - document.querySelector('[data-testid="left"]').parentElement - ); -}); - -test('expanded toasts and their actions stay within either horizontal-fold pane after obstruction', async (t) => { - const { page, fold } = await foldablePage(t); - await fold({ orientation: 'horizontal', offset: 225, maskLength: 380 }); - await page.waitForFunction( - () => matchMedia('(vertical-viewport-segments: 2)').matches - ); - for (const position of ['top-center', 'bottom-center']) { - await page.evaluate((position) => { - window.configure({ topObstruction: 100 }); - for (const id of ['oldest', 'middle', 'newest']) { - window.showStatus('success', { - id, - testID: id, - position, - actions: [ - { - id, - label: 'View transaction details', - borderRadius: 11, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - paddingHorizontal: 12, - paddingVertical: 4, - }, - ], - }); - } - }, position); - await page.keyboard.press('Alt+t'); - const cards = page.locator('[data-onekey-toast]'); - assert.equal(await cards.first().getAttribute('data-expanded'), 'true'); - for (const card of await cards.all()) { - assert.equal(await card.getAttribute('data-pane-constrained'), ''); - const bounds = await card.boundingBox(); - const action = card.getByRole('button', { - name: 'View transaction details', - }); - const buttonBounds = await action.boundingBox(); - assert.ok(buttonBounds.y >= bounds.y); - assert.ok( - buttonBounds.y + buttonBounds.height <= bounds.y + bounds.height - ); - if (position === 'top-center') { - assert.ok( - bounds.y >= 108 && bounds.y + bounds.height < 225, - JSON.stringify(bounds) - ); - } else { - assert.ok( - bounds.y > 605 && bounds.y + bounds.height <= 768, - JSON.stringify(bounds) - ); - } - } - await page - .getByTestId('oldest') - .getByRole('button', { name: 'View transaction details' }) - .click(); - await page.keyboard.press('Escape'); - } - assert.deepEqual(await callbacks(page), ['oldest', 'oldest']); -}); - -for (const reason of ['swipe', 'programmatic']) { - test(`reduced motion immediately completes an in-flight ${reason} exit`, async (t) => { - const page = await statusPage(t); - await page.clock.install(); - await page.evaluate(() => window.showToast(Infinity, 'top-center')); - const card = page.locator('[data-onekey-toast]'); - await card.click({ trial: true }); - await page.clock.pauseAt(Date.now() + 1000); - if (reason === 'swipe') { - const { x, y, width, height } = await card.boundingBox(); - await page.mouse.move(x + width / 2, y + height / 2); - await page.mouse.down(); - await page.mouse.move(x + width / 2 + 80, y + height / 2, { steps: 3 }); - await page.mouse.up(); - } else { - await page.evaluate(() => window.dismissNotification()); - } - assert.equal(await card.getAttribute('data-removed'), 'true'); - assert.deepEqual(await callbacks(page), []); - - await page.emulateMedia({ reducedMotion: 'reduce' }); - await card.waitFor({ state: 'detached', timeout: 1000 }); - assert.deepEqual(await callbacks(page), [reason]); - await page.clock.runFor(250); - assert.deepEqual(await callbacks(page), [reason]); - }); -} - -test('keyboard focus follows a stack across the narrow layout breakpoint', async (t) => { - const page = await statusPage(t, 'reduce'); - await page.setViewportSize({ width: 601, height: 800 }); - await page.clock.install(); - await page.evaluate(() => { - for (const id of ['older', 'newer']) { - window.showStatus('success', { - id, - position: 'bottom-right', - duration: 1000, - }); - } - }); - await page.keyboard.press('Alt+t'); - const oldLane = page.locator( - '[data-onekey-toast-toaster][data-x-position="right"]' - ); - assert.equal( - await oldLane.evaluate((lane) => lane === document.activeElement), - true - ); - - await page.setViewportSize({ width: 600, height: 800 }); - const newLane = page.locator( - '[data-onekey-toast-toaster][data-x-position="center"]' - ); - await newLane.waitFor({ state: 'attached' }); - assert.equal( - await newLane.evaluate((lane) => lane === document.activeElement), - true - ); - await page.keyboard.press('Escape'); - const cards = newLane.locator('[data-onekey-toast]'); - assert.equal(await cards.first().getAttribute('data-expanded'), 'false'); - await page.clock.runFor(1100); - assert.equal(await cards.count(), 0); -}); - -test('a toast with no pane space excludes its action from keyboard focus until space returns', async (t) => { - const { page, fold, client } = await foldablePage(t); - await fold({ orientation: 'horizontal', offset: 230, maskLength: 24 }); - await page.waitForFunction( - () => matchMedia('(vertical-viewport-segments: 2)').matches - ); - await page.evaluate(() => { - window.configure({ topObstruction: 260, topObstructionRoom: 4 }); - window.showStatus('success', { - actions: [ - { - id: 'view', - label: 'View details', - borderRadius: 11, - color: '#111', - backgroundColor: '#eee', - fontSize: 14, - lineHeight: 20, - paddingHorizontal: 12, - paddingVertical: 4, - }, - ], - }); - }); - const card = page.locator('[data-onekey-toast]'); - const action = card.locator('[data-okt-action]'); - assert.equal( - await card.evaluate((node) => - node.style.getPropertyValue('--toast-pane-scale') - ), - '0' - ); - assert.equal(await card.getAttribute('data-visible'), 'false'); - await action.focus(); - assert.equal( - await action.evaluate((node) => node === document.activeElement), - false - ); - const hasAccessibleAction = async () => { - const { nodes } = await client.send('Accessibility.getFullAXTree'); - return nodes.some( - (node) => - !node.ignored && - node.role?.value === 'button' && - node.name?.value === 'View details' - ); - }; - assert.equal(await hasAccessibleAction(), false); - await page.keyboard.press('Enter'); - assert.deepEqual(await callbacks(page), []); - - await page.evaluate(() => window.configure({ topObstruction: 0 })); - assert.equal(await card.getAttribute('data-visible'), 'true'); - assert.equal(await hasAccessibleAction(), true); - await card.getByRole('button', { name: 'View details' }).focus(); - await page.keyboard.press('Enter'); - assert.deepEqual(await callbacks(page), ['view']); -}); - -test('a folded centered toast follows direction set by a root CSS class', async (t) => { - const { page, fold } = await foldablePage(t); - await fold({ orientation: 'vertical', offset: 300, maskLength: 28 }); - await page.waitForFunction( - () => matchMedia('(horizontal-viewport-segments: 2)').matches - ); - await page.addStyleTag({ content: 'html.rtl-fixture { direction: rtl; }' }); - await page.evaluate(() => { - window.showStatus('success', { id: 'fixed', position: 'top-right' }); - window.showStatus('success', { id: 'center', testID: 'center' }); - }); - const card = page.getByTestId('center'); - assert.equal(await card.getAttribute('data-x-position'), 'left'); - - await page.evaluate(() => - document.documentElement.classList.add('rtl-fixture') - ); - assert.equal(await card.getAttribute('data-x-position'), 'right'); - assert.equal(await card.locator('..').getAttribute('dir'), 'rtl'); - assert.equal( - await card.locator('..').locator('[data-onekey-toast]').count(), - 2 - ); - - await page.evaluate(() => - document.documentElement.classList.remove('rtl-fixture') - ); - assert.equal(await card.getAttribute('data-x-position'), 'left'); - assert.equal(await card.locator('..').getAttribute('dir'), 'ltr'); -}); diff --git a/native-views/react-native-native-overlay/tests/ios/WindowManagerTests.swift b/native-views/react-native-native-overlay/tests/ios/WindowManagerTests.swift index 11e9e10d9..b4bda02c3 100644 --- a/native-views/react-native-native-overlay/tests/ios/WindowManagerTests.swift +++ b/native-views/react-native-native-overlay/tests/ios/WindowManagerTests.swift @@ -141,61 +141,6 @@ private func touchObserver(in window: UIWindow) throws -> NativeOverlayAppTouchO return observer } -@MainActor private func runToastCardTests() throws { - let spec = NativeOverlayToastSpec(json: [ - "id": "capped-toast", - "statusIcon": ["kind": "status", "status": "success", "size": 36, "glyph": ["contours": [[[6, 12], [10, 16], [18, 8]]]]], - "title": ["paragraphs": [[["text": "Done", "link": "details"]]], "fontSize": 16, "lineHeight": 24], - "actions": [["id": "view", "testID": "view", "label": "View", "lineHeight": 20, "paddingVertical": 4]], - ])! - let card = NativeOverlayToastCardView(spec: spec, cardColor: .white) - card.layoutCard(contentWidth: 180, contentMaxHeight: nil) - let body = card.subviews[0].subviews[0] - let button = body.subviews.first { $0.accessibilityIdentifier == "view" } as? UIControl - let link = body.subviews.compactMap { $0 as? ToastTextLabel }.first - try require(button != nil && link != nil, "toast has an action and a link") - guard let button, let link else { return } - try require(button.frame.minY > link.frame.maxY, "uncapped card puts the action below the text") - card.layoutCard(contentWidth: 180, contentMaxHeight: 36) - try require(card.bounds.height == 56 && button.frame.maxY <= 36, "capped action stays in the visible content box") - try require(button.frame.minX >= link.frame.maxX && link.frame.width > 0, "capped action and text share the row") - - card.canExpandStack = true - let elements = card.accessibilityElements ?? [] - try require(!card.isAccessibilityElement, "collapsed front card remains an accessibility container") - try require(elements.contains { ($0 as? UIView) === button }, "collapsed front card exposes its action") - try require(elements.contains { ($0 as? UIView) === link }, "collapsed front card exposes its link") - let expansion = elements.compactMap { $0 as? UIAccessibilityElement } - .first { $0.accessibilityLabel == "Expand notifications" } - var expanded = false - card.onPress = { expanded = true } - try require(expansion?.accessibilityActivate() == true && expanded, "separate accessibility element expands the stack") - card.canExpandStack = false - try require(card.accessibilityElements == nil && expansion?.accessibilityActivate() == false, "expansion control is removed after expand") - - var tallSpec = spec - tallSpec.actions = [] - tallSpec.title = NativeOverlayToastText(json: [ - "paragraphs": Array(repeating: [["text": "Long message"]], count: 8), - "lineHeight": 24, - ]) - card.apply(spec: tallSpec, cardColor: .white) - card.layoutCard(contentWidth: 180, contentMaxHeight: nil) - card.canExpandStack = true - guard let expansion else { throw Failure(name: "expansion control is available") } - let iconFrame = expansion.accessibilityFrameInContainerSpace - let partialCap = iconFrame.midY - body.frame.minY - card.layoutCard(contentWidth: 180, contentMaxHeight: partialCap) - let partialFrame = expansion.accessibilityFrameInContainerSpace - try require(partialFrame.minY == iconFrame.minY && abs(partialFrame.height - iconFrame.height / 2) < 0.01, - "expansion focus uses only the unclipped part of the icon") - - card.layoutCard(contentWidth: 180, contentMaxHeight: 36) - let fallbackFrame = expansion.accessibilityFrameInContainerSpace - try require(!fallbackFrame.isEmpty && card.bounds.contains(fallbackFrame) && fallbackFrame.minX == card.bounds.minX, - "expansion focus falls back to the visible leading inset when the icon is clipped") -} - @MainActor private func verifyClosingOverlayKeyHandoff(scene: UIWindowScene, app: UIWindow) throws -> Bool { let manager = NativeOverlayWindowManager() let closingOwner = Owner() @@ -232,8 +177,7 @@ private func touchObserver(in window: UIWindow) throws -> NativeOverlayAppTouchO } @MainActor private func runTests(scene: UIWindowScene, app: UIWindow) async throws -> [String] { - try runToastCardTests() - var passed = ["toast-height-cap-and-accessible-stack-controls"] + var passed: [String] = [] let manager = NativeOverlayWindowManager() let a = Owner(), b = Owner(), c = Owner(), toast = Owner() let wa = manager.window(for: a, level: .modal, stackOrder: Int.min, blocking: true, appWindow: app)! diff --git a/native-views/react-native-native-overlay/tests/ios/run.sh b/native-views/react-native-native-overlay/tests/ios/run.sh index 77d30478b..918b013ec 100755 --- a/native-views/react-native-native-overlay/tests/ios/run.sh +++ b/native-views/react-native-native-overlay/tests/ios/run.sh @@ -13,9 +13,6 @@ xcrun --sdk iphonesimulator swiftc -parse-as-library \ "$package_dir/ios/NativeOverlayWindowManager.swift" \ "$package_dir/ios/NativeOverlaySheetController.swift" \ "$package_dir/ios/NativeOverlayAnimation.swift" \ - "$package_dir/ios/NativeOverlayToastCardView.swift" \ - "$package_dir/ios/NativeOverlayToastSpec.swift" \ - "$package_dir/ios/ToastStatusTileView.swift" \ -sdk "$(xcrun --sdk iphonesimulator --show-sdk-path)" \ -target arm64-apple-ios18.0-simulator -module-cache-path "$output_dir/ModuleCache" \ -framework UIKit -o "$output_dir/OverlayWindowTests.app/OverlayWindowTests"