Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions e2e/tests/issues/issue-1154-page-change-focus.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,28 @@ test(
}
);

test(
'a setPage back to the page a slide is passing lands there',
{ ...options, platforms: ['ios'] },
async ({ app, screen, platform }) => {
await openExample(app, screen, 'Issue #1154 Page Change Focus Repro');

// The second command goes out from the scroll events, as soon as the slide
// to page 2 is more than halfway to page 1, rather than on a timer. TabView
// used to take page 1 as reached and let the slide run on to page 2.
await screen.getByTestId('issue-1154-go-2-back-to-1').tap();
await wait(SETTLE_MS);
// Sent mid-slide, or the run proves nothing.
await expect(screen.getByTestId('issue-1154-events')).toHaveText(
/redirect at (0\.[5-9]|1\.[0-4])/
);
await expectStatus(screen, platform, 1, 'none');
await expect(screen.getByTestId('issue-1154-events')).toHaveText(
/state idle at 1$/
);
}
);

test(
'a setPage that interrupts another still lands on the later page',
{ ...options, platforms: ['ios'] },
Expand Down
22 changes: 22 additions & 0 deletions example/src/gh-issues/Issue1154PageChangeFocusRepro.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const PAGE_COLORS = ['#fde2e2', '#e2fde6', '#e2e8fd', '#fdf3e2'];
export function Issue1154PageChangeFocusRepro() {
const pagerRef = useRef<PagerViewRef>(null);
const followUpCommand = useRef<{ at: number; go: number } | null>(null);
const pastMiddleCommand = useRef<number | null>(null);
const [selectedPage, setSelectedPage] = useState(0);
const [focusedInput, setFocusedInput] = useState<number | null>(null);
const [keyboardVisible, setKeyboardVisible] = useState(false);
Expand All @@ -43,6 +44,7 @@ export function Issue1154PageChangeFocusRepro() {
const startCommand = () => {
setEvents([]);
followUpCommand.current = null;
pastMiddleCommand.current = null;
if (lateCommand.current) {
clearTimeout(lateCommand.current);
lateCommand.current = null;
Expand Down Expand Up @@ -121,6 +123,16 @@ export function Issue1154PageChangeFocusRepro() {
title="Go 1 then 2"
onPress={() => goToPageThen(1, 2)}
/>
<Button
testID="issue-1154-go-2-back-to-1"
title="Go 2, back to 1"
onPress={() => {
startCommand();
// Already on page 2, nothing slides and the redirect never goes out.
pastMiddleCommand.current = selectedPage === 2 ? null : 1;
pagerRef.current?.setPage(2);
}}
/>
<Button
testID="issue-1154-go-1-and-0"
title="Go 1 and 0"
Expand Down Expand Up @@ -166,6 +178,16 @@ export function Issue1154PageChangeFocusRepro() {
ref={pagerRef}
style={styles.pager}
onPageScroll={(e) => {
// Sent as soon as the slide is more than halfway to that page, so it
// is the page nearest the offset when the command lands. The log
// shows how far the slide had come.
const back = pastMiddleCommand.current;
const progress = e.nativeEvent.position + e.nativeEvent.offset;
if (back !== null && progress > back - 0.5) {
pastMiddleCommand.current = null;
log(`redirect at ${progress.toFixed(2)}`);
pagerRef.current?.setPage(back);
}
// The pager sends the snapped page with no offset just before it
// reports stopping, which is where it actually came to rest.
if (e.nativeEvent.offset === 0) {
Expand Down
47 changes: 47 additions & 0 deletions ios/PagerGestureObserver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ private extension PagerGestureObserver {
// paging, so the override would stop scrolling that is not paging.
if #available(iOS 16, *) {
addRevealOverride(to: subclass, from: currentClass)
addScrollTargetRecorder(to: subclass, from: currentClass)
}

objc_registerClassPair(subclass)
Expand Down Expand Up @@ -225,4 +226,50 @@ private extension PagerGestureObserver {
method_getTypeEncoding(method)
)
}

/// Records where an animated scroll is heading, which UIKit does not expose.
/// `TabView` starts each slide this way, so the pager can tell a slide it
/// started from one it skipped.
private static func addScrollTargetRecorder(to subclass: AnyClass, from currentClass: AnyClass) {
let selector = #selector(UIScrollView.setContentOffset(_:animated:))

guard let method = class_getInstanceMethod(currentClass, selector) else {
return
}

typealias SetContentOffset = @convention(c) (AnyObject, Selector, CGPoint, Bool) -> Void
let superImplementation = unsafeBitCast(method_getImplementation(method), to: SetContentOffset.self)

let override: @convention(block) (AnyObject, CGPoint, Bool) -> Void = { object, offset, animated in
if let scrollView = object as? UIScrollView {
scrollView.animatedScrollTarget = animated ? offset : nil
}
superImplementation(object, selector, offset, animated)
}

class_addMethod(
subclass,
selector,
imp_implementationWithBlock(override),
method_getTypeEncoding(method)
)
}
}

private var animatedScrollTargetKey: UInt8 = 0

extension UIScrollView {
/// The offset the last animated `setContentOffset` headed for. Only the
/// pager's runtime subclass records it, see `PagerGestureObserver`.
var animatedScrollTarget: CGPoint? {
get { (objc_getAssociatedObject(self, &animatedScrollTargetKey) as? NSValue)?.cgPointValue }
set {
objc_setAssociatedObject(
self,
&animatedScrollTargetKey,
newValue.map { NSValue(cgPoint: $0) },
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
}
1 change: 1 addition & 0 deletions ios/PagerView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ struct PagerView: View {
.environment(\.layoutDirection, props.layoutDirection.converted)
.introspect(.tabView(style: .page), on: .iOS(.v14...)) { collectionView in
self.collectionView = collectionView
props.collectionView = collectionView
applyOverdrag(props.overdrag)
applyScrollEnabled(props.scrollEnabled)
collectionView.keyboardDismissMode = props.keyboardDismissMode
Expand Down
61 changes: 61 additions & 0 deletions ios/PagerViewProps.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,67 @@ class PagerViewProps: ObservableObject {
@Published var layoutDirection: PagerLayoutDirection = .ltr
@Published var orientation: UICollectionView.ScrollDirection = .horizontal
@Published var pageTransition: PageTransition?
/// Not published: holding it must not re-render the pager.
weak var collectionView: UICollectionView?

/// While a slide runs, TabView writes the page nearest the offset into the
/// selection, which overwrites a new one before TabView acts on it. Stopping
/// the slide where it is leaves TabView nothing to write.
func stopSlideBeforeSelectionChange() {
guard #available(iOS 16, *),
let collectionView,
!collectionView.isTracking,
!collectionView.isDecelerating,
let heading = collectionView.animatedScrollTarget,
abs(collectionView.contentOffset.x - heading.x) >= 1 else {
return
}
collectionView.setContentOffset(collectionView.contentOffset, animated: false)
}

/// TabView starts no scroll for a selection that is the page nearest the
/// offset, so a slide redirected to the page it is passing runs on to its
/// old target, and TabView then writes that page back as the selection.
func scrollToSelectionSkippedMidSlide(_ page: Int, animated: Bool) {
// A later command or TabView itself may have changed the selection since.
guard #available(iOS 16, *),
page == currentPage,
pageTransition == nil,
let collectionView,
!collectionView.isTracking,
!collectionView.isDecelerating,
collectionView.numberOfSections > 0 else {
return
}
// Pages added or removed in the same pass are not in the collection view yet.
let pageCount = collectionView.numberOfItems(inSection: 0)
let pageSize = collectionView.frame.width
guard page < pageCount, pageSize > 0 else {
return
}
// The offset is physical, and a right-to-left layout mirrors it.
let physicalPage = layoutDirection == .rtl ? pageCount - 1 - page : page
guard Int((collectionView.contentOffset.x / pageSize).rounded()) == physicalPage else {
return
}
let target = CGPoint(x: CGFloat(physicalPage) * pageSize, y: collectionView.contentOffset.y)
// TabView started a slide there, which a slow main thread can let pass the
// middle before this check runs. A second scroll would replace that slide,
// and TabView takes the selection from the offset while the new one runs.
if let heading = collectionView.animatedScrollTarget, abs(heading.x - target.x) < 1 {
return
}
// Already there, with nothing running that could move it on.
if collectionView.animatedScrollTarget == nil && abs(collectionView.contentOffset.x - target.x) < 1 {
return
}
// An animated scroll to the offset already shown does nothing and leaves
// the old slide running, so a slide crossing the page exactly is stopped.
collectionView.setContentOffset(
target,
animated: animated && abs(collectionView.contentOffset.x - target.x) >= 1
)
}

/// The page the selection names, held inside the pages that exist. Nothing
/// clamps the index a command carries, and `-1` stands for no selection yet.
Expand Down
12 changes: 12 additions & 0 deletions ios/PagerViewProvider.swift
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,10 @@ final class PagerViewProvider: UIView, RNCPagerViewProviding {
if index != props.currentPage {
props.resignFirstResponder(outsidePage: index)
}
let previousPage = props.currentPage
if index != previousPage {
props.stopSlideBeforeSelectionChange()
}
// Setting a published value updates the view even when it is already nil,
// and an update outside the animation would cut a running slide short.
let previousTransition = props.pageTransition
Expand All @@ -196,6 +200,14 @@ final class PagerViewProvider: UIView, RNCPagerViewProviding {
case .direct:
slideDirectly(to: index, after: previousTransition)
}
// Only a plain selection change can be skipped by TabView: a two-step
// direct slide starts its animation from `PagerView.slide`. Checked on the
// next pass, once the commands sent together have settled the selection.
if props.pageTransition == nil && props.currentPage != previousPage {
DispatchQueue.main.async { [props] in
props.scrollToSelectionSkippedMidSlide(index, animated: animation != .none)
}
}
}

/// Jumps to the target's neighbour, moving the current page into it, so only
Expand Down
Loading