diff --git a/android/src/main/java/expo/modules/swipeable/SwipeableView.kt b/android/src/main/java/expo/modules/swipeable/SwipeableView.kt index 2aa082a..e9c549f 100644 --- a/android/src/main/java/expo/modules/swipeable/SwipeableView.kt +++ b/android/src/main/java/expo/modules/swipeable/SwipeableView.kt @@ -372,6 +372,13 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context private val requestedActions = mutableSetOf() private val observedSlotCounts = mutableMapOf() private val configurationRunnable = Runnable { applyPendingConfiguration() } + // Fabric adds a three-child row one child at a time. Until the next main-thread turn, + // a lone child can be the first rail of that batch, so it gets no role yet. + private var childrenSettled = true + private val settleChildrenRunnable = Runnable { + childrenSettled = true + reconcileSideChildren() + } private val activeSide: SwipeSide? get() = gestureSide ?: animationSide ?: openSide ?: defaultOpenSide() @@ -379,6 +386,19 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context private var contentView: View? = null private var leftActionsView: View? = null private var rightActionsView: View? = null + // The flags of each rail before refreshRailVisibility() first changed them. + private class RailFlags(view: View) { + private val visibility = view.visibility + private val importantForAccessibility = view.importantForAccessibility + private val pointerEvents = (view as? ReactViewGroup)?.pointerEvents + + fun restoreTo(view: View) { + view.visibility = visibility + view.importantForAccessibility = importantForAccessibility + pointerEvents?.let { (view as? ReactViewGroup)?.pointerEvents = it } + } + } + private val railOriginalFlags = HashMap() private val actionsView: View? get() = railFor(activeSide) @@ -475,14 +495,14 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context override fun onViewAdded(child: View?) { super.onViewAdded(child) child ?: return + markChildrenChanging() reconcileSideChildren() } override fun onViewRemoved(child: View?) { super.onViewRemoved(child) - if (child === leftActionsView || child === rightActionsView) { - (child as? ReactViewGroup)?.pointerEvents = PointerEvents.AUTO - } + markChildrenChanging() + if (child != null) restoreRailFlags(child) if (child === contentView) { contentView = null isCurrentTouchCancelled = true @@ -1505,6 +1525,18 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context } } + private fun markChildrenChanging() { + childrenSettled = false + removeCallbacks(settleChildrenRunnable) + post(settleChildrenRunnable) + } + + /** Returns the visibility, accessibility and pointer events a rail had before this view hid it. */ + private fun restoreRailFlags(view: View) { + railOriginalFlags.remove(view)?.restoreTo(view) + } + + /** One child is the content only. Three children are the left rail, the right rail and the content. */ private fun reconcileSideChildren() { val previousContent = contentView val previousLeft = leftActionsView @@ -1518,6 +1550,11 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context if (contentView?.parent !== this) contentView = null if (leftActionsView?.parent !== this) leftActionsView = null if (rightActionsView?.parent !== this) rightActionsView = null + val only = if (childCount == 1) getChildAt(0) else null + if (only != null && contentView == null && childrenSettled && + only !== leftActionsView && only !== rightActionsView) { + contentView = only + } } for (side in SwipeSide.values()) { val rail = railFor(side) @@ -1530,6 +1567,14 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context clipToPadding = false } } + // A view that lost its rail role, by removal or by a new role, gets its own flags back. + val savedRails = railOriginalFlags.entries.iterator() + while (savedRails.hasNext()) { + val (view, flags) = savedRails.next() + if (view === leftActionsView || view === rightActionsView) continue + savedRails.remove() + flags.restoreTo(view) + } if (contentView !== previousContent) contentView?.translationX = currentTranslation if (isOpen || isDragging || isAnimating) activeSide?.let(::requestActions) updateActionsTransform() @@ -1540,6 +1585,7 @@ class SwipeableView(context: Context, appContext: AppContext) : ExpoView(context val visible = childCount == 3 && isSideEnabled(side) && side == activeSide && (isOpen || isDragging || isAnimating) && (currentTranslation != 0f || isOpen) railFor(side)?.apply { + railOriginalFlags.getOrPut(this) { RailFlags(this) } visibility = if (visible) View.VISIBLE else View.INVISIBLE // RN's TouchTargetHelper ignores Android visibility. An empty // zero-width rail still spans the row and otherwise steals taps diff --git a/android/src/test/java/expo/modules/swipeable/SwipeableViewTest.kt b/android/src/test/java/expo/modules/swipeable/SwipeableViewTest.kt index abfb75f..779665c 100644 --- a/android/src/test/java/expo/modules/swipeable/SwipeableViewTest.kt +++ b/android/src/test/java/expo/modules/swipeable/SwipeableViewTest.kt @@ -371,6 +371,82 @@ class SwipeableViewTest { assertEquals(0f, left.translationX, .01f) } + @Test fun contentOnlyRowOpensAndClosesWithoutRails() { + val (row, content) = contentRow() + row.open(SwipeSide.LEFT) + settle() + assertEquals(160f, content.translationX, .01f) + assertEquals(listOf("left"), named("onActionsNeeded").map { it["side"] }) + row.close() + settle() + assertEquals(0f, content.translationX, 0f) + } + + @Test fun loneChildBecomesContentOnlyAfterTheMountTurn() { + val row = row(children = false) + val content = FrameLayout(activity) + row.addView(content) + row.open(SwipeSide.LEFT) + row.layout(0, 0, 400, 64) + assertEquals(0f, content.translationX, 0f) + settle() + assertEquals(160f, content.translationX, .01f) + } + + @Test fun railPairMountKeepsContentIdentityAndTranslation() { + val (row, content) = contentRow() + row.open(SwipeSide.LEFT) + settle() + events.clear() + val left = FrameLayout(activity).apply { addView(View(activity)) } + val right = FrameLayout(activity) + row.addView(left, 0) + row.addView(right, 1) + row.layout(0, 0, 400, 64) + assertSame(content, row.getChildAt(2)) + assertEquals(160f, content.translationX, .01f) + assertEquals(0f, left.translationX, .01f) + assertEquals(View.VISIBLE, left.visibility) + assertHidden(right) + } + + @Test fun railPairUnmountKeepsContentIdentityAndTranslation() { + val row = row() + val content = content(row) + row.open(SwipeSide.LEFT) + settle() + row.removeViewAt(0) + row.removeViewAt(0) + row.layout(0, 0, 400, 64) + settle() + assertSame(content, row.getChildAt(0)) + assertEquals(160f, content.translationX, .01f) + row.close() + settle() + assertEquals(0f, content.translationX, 0f) + } + + @Test fun railPairMountedMidDragShowsTheDraggedSide() { + val (row, content) = contentRow() + row.handleGestureStart() + row.handleGestureUpdate(100f, 0f) + assertEquals(100f, content.translationX, .01f) + val left = FrameLayout(activity).apply { addView(View(activity)) } + val right = FrameLayout(activity) + row.addView(left, 0) + row.addView(right, 1) + row.layout(0, 0, 400, 64) + assertSame(content, row.getChildAt(2)) + assertEquals(100f, content.translationX, .01f) + assertEquals(View.VISIBLE, left.visibility) + assertHidden(right) + row.handleGestureEnd(100f, 0f) + settle() + assertEquals(160f, content.translationX, .01f) + assertEquals(listOf("open:left"), ends()) + assertEquals(setOf("left"), named("onActionsNeeded").map { it["side"] }.toSet()) + } + @Test fun remountingAUsedSlotRequestsActionsAgain() { val row = row() row.open(SwipeSide.LEFT) @@ -854,6 +930,44 @@ class SwipeableViewTest { assertEquals(right.getChildAt(0).id, TouchTargetHelper.findTargetTagForTouch(280f, 32f, row)) } + @Test fun removedHiddenRailRestoresVisibilityAndAccessibilityBeforeReuse() { + val row = row() + val right = row.getChildAt(1) + assertHidden(right) + row.removeView(right) + assertEquals(View.VISIBLE, right.visibility) + assertEquals(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO, right.importantForAccessibility) + row.addView(right, 1) + assertHidden(right) + } + + @Test fun hiddenRailThatBecomesContentIsShownAgain() { + val row = row() + val right = row.getChildAt(1) + assertHidden(right) + row.removeViewAt(2) + row.removeViewAt(0) + row.addView(FrameLayout(activity), 0) + row.addView(FrameLayout(activity), 1) + row.layout(0, 0, 400, 64) + assertSame(right, row.getChildAt(2)) + assertEquals(View.VISIBLE, right.visibility) + assertEquals(View.IMPORTANT_FOR_ACCESSIBILITY_AUTO, right.importantForAccessibility) + } + + @Test fun hiddenReactRailThatBecomesContentTakesTouchesAgain() { + val row = reactRow() + val right = row.getChildAt(1) as ReactViewGroup + assertEquals(PointerEvents.NONE, right.pointerEvents) + row.removeViewAt(2) + row.removeViewAt(0) + row.addView(ReactViewGroup(activity), 0) + row.addView(ReactViewGroup(activity), 1) + row.layout(0, 0, 400, 64) + assertSame(right, row.getChildAt(2)) + assertEquals(PointerEvents.AUTO, right.pointerEvents) + } + @Test fun cancelPendingDirectGestureCannotActivateUntilAnotherStart() { val row = row() row.handleGestureStart() @@ -3070,6 +3184,17 @@ class SwipeableViewTest { return row } + /** A closed row as JS mounts it: the content view only, after the mount turn. */ + private fun contentRow(): Pair { + val row = row(children = false) + val content = FrameLayout(activity) + row.addView(content) + row.layout(0, 0, 400, 64) + // A detached view runs its posted settle at the next attach traversal. + shadowOf(Looper.getMainLooper()).idleFor(Duration.ofMillis(16)) + return row to content + } + private fun content(row: SwipeableView): View = row.getChildAt(2) private fun settle() { // Paused vsync delivers on clock advancement; advance a frame at a time diff --git a/ios/SwipePhysics.swift b/ios/SwipePhysics.swift index 682de01..ac381c0 100644 --- a/ios/SwipePhysics.swift +++ b/ios/SwipePhysics.swift @@ -362,6 +362,13 @@ struct SwipeChildRoles: Equatable { let content: Int } +/// The child views that hold each role. A role is nil when no child holds it. +struct SwipeChildAssignment { + var left: Child? + var right: Child? + var content: Child? +} + protocol SwipeChildVisibility: AnyObject { var isHidden: Bool { get set } var isUserInteractionEnabled: Bool { get set } @@ -488,9 +495,37 @@ extension SwipePhysics { width.isFinite && width > 0 ? width : 0 } + /// One child is the content only. Three children are the left rail, the right rail and the content. static func childRoles(count: Int) -> SwipeChildRoles? { - guard count == 3 else { return nil } - return SwipeChildRoles(left: 0, right: 1, content: 2) + switch count { + case 1: return SwipeChildRoles(left: nil, right: nil, content: 0) + case 3: return SwipeChildRoles(left: 0, right: 1, content: 2) + default: return nil + } + } + + /// Any other child count is a Fabric transaction in progress: only the surviving roles stay. + /// A known rail never becomes content. Fabric mounts a three-child row one child at a time, + /// so a lone child with no role becomes content only when the transaction is `settled`. + static func assignChildRoles( + children: [Child], current: SwipeChildAssignment, settled: Bool + ) -> SwipeChildAssignment { + func surviving(_ view: Child?) -> Child? { + guard let view = view, children.contains(where: { $0 === view }) else { return nil } + return view + } + let kept = SwipeChildAssignment( + left: surviving(current.left), right: surviving(current.right), content: surviving(current.content) + ) + guard let roles = childRoles(count: children.count) else { return kept } + let content = children[roles.content] + if roles.left == nil { + if content === kept.left || content === kept.right { return kept } + if content !== kept.content && !settled { return kept } + } + return SwipeChildAssignment( + left: roles.left.map { children[$0] }, right: roles.right.map { children[$0] }, content: content + ) } static func latchedSide( diff --git a/ios/SwipeableView.swift b/ios/SwipeableView.swift index b5586bc..5ee28e8 100644 --- a/ios/SwipeableView.swift +++ b/ios/SwipeableView.swift @@ -948,24 +948,31 @@ public class SwipeableView: ExpoView { slotChildren.removeAll() } - private func reconcileChildRoles() { + /// `settled` is false inside Fabric's child mount callbacks, where a transaction can be in progress. + private func reconcileChildRoles(settled: Bool = true) { guard !isDetached else { return } let children = reactChildren.views - // On removal, preserve surviving identities instead of promoting a rail to content. - if let view = contentView, !children.contains(where: { $0 === view }) { releaseChild(view); contentView = nil } - if let view = leftActionsView, !children.contains(where: { $0 === view }) { releaseChild(view); leftActionsView = nil } - if let view = rightActionsView, !children.contains(where: { $0 === view }) { releaseChild(view); rightActionsView = nil } - guard let roles = SwipePhysics.childRoles(count: children.count) else { return } let previousLeft = leftActionsView let previousRight = rightActionsView - contentView = children[roles.content] + let roles = SwipePhysics.assignChildRoles( + children: children, + current: SwipeChildAssignment(left: leftActionsView, right: rightActionsView, content: contentView), + settled: settled + ) + // On removal, preserve surviving identities instead of promoting a rail to content. + for view in [contentView, leftActionsView, rightActionsView].compactMap({ $0 }) + where !children.contains(where: { $0 === view }) { + releaseChild(view) + } + contentView = roles.content + leftActionsView = roles.left + rightActionsView = roles.right + if previousLeft !== leftActionsView { requestedSides.remove(.left) } + if previousRight !== rightActionsView { requestedSides.remove(.right) } + guard contentView != nil, SwipePhysics.childRoles(count: children.count) != nil else { return } // A complete Fabric transaction can give a previously hidden rail the content role. // Restore only flags that this view owned, for all side configurations. if let contentView = contentView { railVisibility.release(contentView) } - leftActionsView = roles.left.map { children[$0] } - rightActionsView = roles.right.map { children[$0] } - if previousLeft !== leftActionsView { requestedSides.remove(.left) } - if previousRight !== rightActionsView { requestedSides.remove(.right) } contentView?.layer.zPosition = 1 for side in SwipeSide.allCases { guard let rail = actionsView(for: side) else { continue } @@ -989,7 +996,7 @@ public class SwipeableView: ExpoView { releaseChild(childComponentView) reactChildren.mount(childComponentView, at: index) // Fabric mounts slots individually; commit only a complete child protocol. - reconcileChildRoles() + reconcileChildRoles(settled: false) scheduleReconciliation() } @@ -1028,7 +1035,7 @@ public class SwipeableView: ExpoView { let generation = workGeneration if let cancelled = cancelled { onGestureCancelled(cancelled) } guard generation == workGeneration else { return } - reconcileChildRoles() + reconcileChildRoles(settled: false) scheduleReconciliation() } diff --git a/ios/Tests/SwipeMainIntegrationTests.swift b/ios/Tests/SwipeMainIntegrationTests.swift index fbdade7..9f5bfc5 100644 --- a/ios/Tests/SwipeMainIntegrationTests.swift +++ b/ios/Tests/SwipeMainIntegrationTests.swift @@ -350,6 +350,98 @@ final class SwipeMainIntegrationTests: XCTestCase { XCTAssertEqual(children.views.count, 2) } + private typealias Roles = SwipeChildAssignment + + private func assign(_ children: SwipeReactChildren, _ current: Roles, settled: Bool = true) -> Roles { + SwipePhysics.assignChildRoles(children: children.views, current: current, settled: settled) + } + + func testLoneChildBecomesContentOnlyAtASettlePoint() { + let content = Child() + var children = SwipeReactChildren() + children.mount(content, at: 0) + let unsettled = assign(children, Roles(), settled: false) + XCTAssertNil(unsettled.content) + let settled = assign(children, unsettled) + XCTAssertTrue(settled.content === content) + XCTAssertNil(settled.left) + XCTAssertNil(settled.right) + } + + func testInitialThreeChildMountNeverMakesTheLeftRailContent() { + let left = Child() + let right = Child() + let content = Child() + var children = SwipeReactChildren() + var roles = Roles() + children.mount(left, at: 0) + roles = assign(children, roles, settled: false) + XCTAssertNil(roles.content) + children.mount(right, at: 1) + roles = assign(children, roles, settled: false) + XCTAssertNil(roles.content) + children.mount(content, at: 2) + roles = assign(children, roles, settled: false) + XCTAssertTrue(roles.left === left) + XCTAssertTrue(roles.right === right) + XCTAssertTrue(roles.content === content) + } + + func testRailPairMountKeepsTheContentIdentity() { + let left = Child() + let right = Child() + let content = Child() + var children = SwipeReactChildren() + children.mount(content, at: 0) + var roles = assign(children, Roles()) + children.mount(left, at: 0) + roles = assign(children, roles, settled: false) + XCTAssertTrue(roles.content === content) + XCTAssertNil(roles.left) + children.mount(right, at: 1) + roles = assign(children, roles, settled: false) + XCTAssertTrue(roles.content === content) + XCTAssertTrue(roles.left === left) + XCTAssertTrue(roles.right === right) + } + + func testRailPairUnmountKeepsTheContentIdentity() { + let left = Child() + let right = Child() + let content = Child() + var children = SwipeReactChildren() + children.mount(left, at: 0) + children.mount(right, at: 1) + children.mount(content, at: 2) + var roles = assign(children, Roles()) + children.unmount(left, at: 0) + roles = assign(children, roles, settled: false) + XCTAssertTrue(roles.content === content) + XCTAssertNil(roles.left) + XCTAssertTrue(roles.right === right) + children.unmount(right, at: 0) + roles = assign(children, roles, settled: false) + XCTAssertTrue(roles.content === content) + XCTAssertNil(roles.right) + } + + func testLoneKnownRailNeverBecomesContent() { + let left = Child() + let right = Child() + let content = Child() + var children = SwipeReactChildren() + children.mount(left, at: 0) + children.mount(right, at: 1) + children.mount(content, at: 2) + var roles = assign(children, Roles()) + children.unmount(content, at: 2) + children.unmount(right, at: 1) + roles = assign(children, roles) + XCTAssertNil(roles.content) + XCTAssertTrue(roles.left === left) + XCTAssertNil(roles.right) + } + func testRemountDoesNotDuplicateChildAndClampsFabricIndex() { let left = Child() let right = Child() diff --git a/ios/Tests/SwipePhysicsTests.swift b/ios/Tests/SwipePhysicsTests.swift index 7eb98c1..647c411 100644 --- a/ios/Tests/SwipePhysicsTests.swift +++ b/ios/Tests/SwipePhysicsTests.swift @@ -498,7 +498,7 @@ final class TwoSidedSwipePhysicsTests: XCTestCase { } func testIncompleteTwoSidedSlotsNeverHaveContentRole() { - for count in [0, 1, 2, 4] { XCTAssertNil(SwipePhysics.childRoles(count: count)) } + for count in [0, 2, 4] { XCTAssertNil(SwipePhysics.childRoles(count: count)) } let roles = SwipePhysics.childRoles(count: 3) XCTAssertEqual(roles?.left, 0) XCTAssertEqual(roles?.right, 1) @@ -508,7 +508,6 @@ final class TwoSidedSwipePhysicsTests: XCTestCase { func testSingleSideRowsRequireTheSameCompleteChildProtocol() { XCTAssertNil(SwipePhysics.childRoles(count: 0)) - XCTAssertNil(SwipePhysics.childRoles(count: 1)) XCTAssertNil(SwipePhysics.childRoles(count: 2)) XCTAssertNil(SwipePhysics.childRoles(count: 4)) let roles = SwipePhysics.childRoles(count: 3) @@ -517,6 +516,10 @@ final class TwoSidedSwipePhysicsTests: XCTestCase { XCTAssertEqual(roles?.content, 2) } + func testOneChildIsContentOnly() { + XCTAssertEqual(SwipePhysics.childRoles(count: 1), SwipeChildRoles(left: nil, right: nil, content: 0)) + } + func testCacheRestoresExactSideAndEvictsOldestOpenKey() { var cache = SwipeOpenStateCache(capacity: 2) cache.set(.left, for: "a") diff --git a/jestSetup.js b/jestSetup.js index 2211ce0..e8141ab 100644 --- a/jestSetup.js +++ b/jestSetup.js @@ -54,6 +54,8 @@ jest.mock('./src/SwipeableView.tsx', () => { return { SwipeableModule, - SwipeableView + SwipeableView, + // Swipeable renders the raw native view directly. + NativeSwipeableView: SwipeableView } }) diff --git a/src/Swipeable.tsx b/src/Swipeable.tsx index 3fe9cf7..c14002f 100644 --- a/src/Swipeable.tsx +++ b/src/Swipeable.tsx @@ -24,7 +24,6 @@ import { import { resolveSwipeableActions } from './resolveSwipeableActions' import type { ActionsNeededEvent, - NativeSwipeableRef, SwipeSide, SwipeableComponentProps, SwipeableMethods, @@ -34,7 +33,10 @@ import type { SwipeStateEvent } from './Swipeable.types' import { SwipeableActions } from './SwipeableActions' -import { SwipeableView } from './SwipeableView' +import { NativeSwipeableView, SwipeableView } from './SwipeableView' + +// A consumer's own Jest mock of this module can predate the raw export. +const NativeHost = NativeSwipeableView ?? SwipeableView function normalizeRecyclingKey(key: string | number | undefined): string | undefined { if (key == null) return undefined @@ -102,7 +104,6 @@ const Swipeable = forwardRef(function }, ref ) { - const nativeRef = useRef(null) const named = useMemo( () => resolveSwipeableActions({ @@ -163,8 +164,10 @@ const Swipeable = forwardRef(function // state: a side mounts if the native cache has it open or the current key asked for it. const [renderedSides, setRenderedSides] = useState(initialSides) const ownSides = renderedSides.key === normalizedKey ? renderedSides : null - const showLeft = initialSides.left || ownSides?.left === true - const showRight = initialSides.right || ownSides?.right === true + const showLeft = (initialSides.left || ownSides?.left === true) && resolved.left.width > 0 + const showRight = (initialSides.right || ownSides?.right === true) && resolved.right.width > 0 + // A closed row mounts only the content. Both rails mount as a pair once a side is needed. + const showRails = showLeft || showRight // A layout effect, so a static command from any passive mount effect sees the row. useLayoutEffect(() => { @@ -299,8 +302,7 @@ const Swipeable = forwardRef(function ) return ( - (function onSwipeStateChange={handleSwipeStateChange} onSwipeEnd={handleSwipeEnd} > - - - {showLeft && resolved.left.width > 0 ? resolved.left.node : null} - - - - - {showRight && resolved.right.width > 0 ? resolved.right.node : null} - - + {showRails ? ( + + {showLeft ? resolved.left.node : null} + + ) : null} + {showRails ? ( + + {showRight ? resolved.right.node : null} + + ) : null} {children} - + ) }) diff --git a/src/SwipeableView.tsx b/src/SwipeableView.tsx index 8669bda..345a0ee 100644 --- a/src/SwipeableView.tsx +++ b/src/SwipeableView.tsx @@ -9,6 +9,9 @@ type NativeViewProps = SwipeableViewProps & { const NativeView = requireNativeViewManager('Swipeable') +/** @internal The raw native view. `Swipeable` renders it without the `forwardRef` wrapper. */ +export const NativeSwipeableView = NativeView + // Module-level functions interface interface SwipeableNativeModule { openByKey: (key: string) => void diff --git a/src/__tests__/SwipeableLazyRails.test.tsx b/src/__tests__/SwipeableLazyRails.test.tsx new file mode 100644 index 0000000..06e3ec0 --- /dev/null +++ b/src/__tests__/SwipeableLazyRails.test.tsx @@ -0,0 +1,125 @@ +import { createElement, useEffect } from 'react' +import { act, create, type ReactTestRendererJSON } from 'react-test-renderer' +import { createControlledNativeMock } from './helpers/createControlledNativeMock' +import type { SwipeableProps } from '../Swipeable.types' + +type SwipeableComponent = typeof import('../Swipeable').default + +const mock = createControlledNativeMock() +jest.mock('../SwipeableView', () => ({ __esModule: true, ...mock })) + +let Swipeable: SwipeableComponent +beforeAll(() => { + Swipeable = require('../Swipeable').default +}) + +const contentLifecycle = { mounts: 0, unmounts: 0 } +function Content() { + useEffect(() => { + contentLifecycle.mounts++ + return () => { + contentLifecycle.unmounts++ + } + }, []) + return createElement('View', { testID: 'content' }, 'Message') +} + +const props: SwipeableProps = { + children: , + leftActions: createElement('View', { testID: 'left-node' }, 'Reply'), + leftActionsWidth: 60, + rightActions: createElement('View', { testID: 'right-node' }, 'Delete'), + rightActionsWidth: 80, + testID: 'row' +} + +let tree: ReturnType | undefined +const noOverrides: Partial = {} + +const render = (overrides = noOverrides) => { + act(() => { + tree = create() + }) +} +const update = (overrides = noOverrides) => { + act(() => { + tree?.update() + }) +} + +/** The testIDs of the native host's direct children, in mount order. */ +const nativeChildren = () => { + const host = tree?.toJSON() as ReactTestRendererJSON + return (host.children ?? []).map((child) => (child as ReactTestRendererJSON).props.testID) +} +const has = (testID: string) => tree?.root.findAll((n) => n.props.testID === testID).length !== 0 + +beforeEach(() => { + mock.reset() + contentLifecycle.mounts = 0 + contentLifecycle.unmounts = 0 +}) + +afterEach(() => { + act(() => tree?.unmount()) + tree = undefined +}) + +it('renders a closed row as the native view and the content view only', () => { + render({ recyclingKey: 'closed' }) + expect(nativeChildren()).toEqual([undefined]) + expect(has('content')).toBe(true) +}) + +it('mounts both rails in front of the content when native asks for one side', () => { + render({ recyclingKey: 'row' }) + act(() => mock.getLastInstance()?.requestActions('right')) + expect(nativeChildren()).toEqual(['row-left-actions', 'row-right-actions', undefined]) + expect(has('right-node')).toBe(true) + expect(has('left-node')).toBe(false) +}) + +it('keeps the content mounted while the rails mount and unmount', () => { + render({ recyclingKey: 'first' }) + act(() => mock.getLastInstance()?.requestActions('left')) + update({ recyclingKey: 'second' }) + expect(nativeChildren()).toEqual([undefined]) + expect(contentLifecycle).toEqual({ mounts: 1, unmounts: 0 }) +}) + +it('mounts the rails in the first render of a key that the native cache has open', () => { + mock.SwipeableModule.getOpenSideByKey.mockImplementation((key: string) => + key === 'open' ? 'left' : null + ) + render({ recyclingKey: 'open' }) + expect(nativeChildren()).toEqual(['row-left-actions', 'row-right-actions', undefined]) + expect(has('left-node')).toBe(true) +}) + +it('keeps the rails mounted after the row closes', () => { + render({ recyclingKey: 'row' }) + const native = mock.getLastInstance() + act(() => { + native?.requestActions('right') + native?.triggerSwipeStart() + native?.triggerSwipeEnd('closed', 'right') + }) + expect(nativeChildren()).toEqual(['row-left-actions', 'row-right-actions', undefined]) +}) + +it('ignores a request for a side without a width', () => { + render({ recyclingKey: 'row', leftActionsWidth: 0 }) + act(() => mock.getLastInstance()?.requestActions('left')) + expect(nativeChildren()).toEqual([undefined]) +}) + +it('ignores a request from the key the row held before a recycle', () => { + render({ recyclingKey: 'first' }) + update({ recyclingKey: 'second' }) + act(() => { + tree?.root + .findByType(mock.SwipeableView) + .props.onActionsNeeded({ nativeEvent: { recyclingKey: 'first', side: 'left' } }) + }) + expect(nativeChildren()).toEqual([undefined]) +}) diff --git a/src/__tests__/SwipeableLegacyMock.test.tsx b/src/__tests__/SwipeableLegacyMock.test.tsx new file mode 100644 index 0000000..36c945d --- /dev/null +++ b/src/__tests__/SwipeableLegacyMock.test.tsx @@ -0,0 +1,26 @@ +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { createControlledNativeMock } from './helpers/createControlledNativeMock' + +const mockNative = createControlledNativeMock() +// A consumer's own mock of this module, written before the raw native view export. +jest.mock('../SwipeableView', () => ({ + __esModule: true, + SwipeableModule: mockNative.SwipeableModule, + SwipeableView: mockNative.SwipeableView +})) + +it('renders through the public wrapper when a mock has no raw native view', () => { + const Swipeable = (require('../Swipeable') as typeof import('../Swipeable')).default + let tree: ReturnType | undefined + act(() => { + tree = create( + + {createElement('View', { testID: 'content' })} + + ) + }) + expect(tree?.root.findAllByType(mockNative.SwipeableView)).toHaveLength(1) + expect(tree?.root.findAll((node) => node.props.testID === 'content').length).toBeGreaterThan(0) + act(() => tree?.unmount()) +}) diff --git a/src/__tests__/SwipeableView.test.tsx b/src/__tests__/SwipeableView.test.tsx index 5522df6..79f0695 100644 --- a/src/__tests__/SwipeableView.test.tsx +++ b/src/__tests__/SwipeableView.test.tsx @@ -62,3 +62,16 @@ it('forwards explicit-side raw-view props, refs and native events through the re expect(onSwipeProgress).toHaveBeenCalledWith({ nativeEvent: { progress: 0.2, translationX: 18 } }) expect(onSwipeEnd).toHaveBeenCalledWith({ nativeEvent: { state: 'closed' } }) }) + +it('lets Swipeable render the native manager without the public wrapper', () => { + const Swipeable = (require('../Swipeable') as typeof import('../Swipeable')).default + act(() => { + tree = create( + + {createElement(View)} + + ) + }) + expect(tree?.root.findAllByType(SwipeableView)).toHaveLength(0) + expect(tree?.root.findAllByType(mock.SwipeableView)).toHaveLength(1) +}) diff --git a/src/__tests__/TwoSidedSwipeable.test.tsx b/src/__tests__/TwoSidedSwipeable.test.tsx index b3bd958..6bddeac 100644 --- a/src/__tests__/TwoSidedSwipeable.test.tsx +++ b/src/__tests__/TwoSidedSwipeable.test.tsx @@ -39,16 +39,16 @@ afterEach(() => { jest.restoreAllMocks() }) -it('mounts stable empty shells, then only the requested action subtree', () => { +it('mounts no shells while closed, then both shells and only the requested action subtree', () => { render() + expect(tree?.root.findAllByType(SwipeableActions)).toHaveLength(0) + expect(mountedSides()).toEqual([]) + act(() => mock.getLastInstance()?.requestActions('left')) const shells = tree?.root.findAllByType(SwipeableActions) - expect(shells).toHaveLength(2) expect(shells?.map((node) => node.props.testID)).toEqual([ 'two-sided-row-left-actions', 'two-sided-row-right-actions' ]) - expect(mountedSides()).toEqual([]) - act(() => mock.getLastInstance()?.requestActions('left')) expect(mountedSides()).toEqual(['left']) act(() => mock.getLastInstance()?.requestActions('left')) expect(mountedSides()).toEqual(['left']) diff --git a/src/__tests__/helpers/createControlledNativeMock.tsx b/src/__tests__/helpers/createControlledNativeMock.tsx index 8e9353c..1f0a2c5 100644 --- a/src/__tests__/helpers/createControlledNativeMock.tsx +++ b/src/__tests__/helpers/createControlledNativeMock.tsx @@ -44,6 +44,7 @@ interface SwipeableViewMock { getOpenSideByKey: jest.Mock } SwipeableView: ForwardRefExoticComponent> + NativeSwipeableView: ForwardRefExoticComponent> instances: ControlledSwipeableInstance[] getLastInstance: () => ControlledSwipeableInstance | undefined getInstances: () => ControlledSwipeableInstance[] @@ -155,6 +156,7 @@ export function createControlledNativeMock(): SwipeableViewMock { return { SwipeableModule, SwipeableView, + NativeSwipeableView: SwipeableView, instances, getLastInstance: () => instances[instances.length - 1], getInstances: () => instances,