From bf567021057256084903210bc44bb477820c14d3 Mon Sep 17 00:00:00 2001 From: Connor McManus Date: Tue, 17 Nov 2026 07:59:52 -0800 Subject: [PATCH 1/4] Page a horizontal pager by its own width beside a sideways bar on iOS Beside a vertical bar (the iPhone Duo's side rail, or a notched iPhone held sideways) the pager's ScrollView draws into the bar's inset, so the next page showed under the bar. Its visibleRect takes in that inset too, so a page measured against it was wider than the step .paging takes. The reported page and the tab underline fell further behind on each later page. A horizontal pager now measures a page by the ScrollView's own width, which is what .paging steps by, and clips its sides. A scrollable tab row clips its sides the same way. Pages still run under a bar at the bottom, and vertical pagers are unchanged. --- resources/ios/NativeUIPagerRenderer.swift | 29 +++++++++++++++++++---- tests/IosPagerTabBarTest.php | 9 +++++++ 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/resources/ios/NativeUIPagerRenderer.swift b/resources/ios/NativeUIPagerRenderer.swift index be1bb518..370f4a3f 100644 --- a/resources/ios/NativeUIPagerRenderer.swift +++ b/resources/ios/NativeUIPagerRenderer.swift @@ -197,6 +197,11 @@ private struct PagerBody: View { .scrollTargetLayout() } .ignoresSafeArea(.container, edges: horizontal ? .bottom : []) + // Beside a sideways bar (an iPhone Duo's rail) the ScrollView + // also draws into the bar's inset, so the next page showed + // under it. Clip the sides only: the pages still run under a + // bar at the bottom. + .clipShape(PagerSideClip(horizontal: horizontal)) .scrollTargetBehavior(.paging) .scrollPosition(id: $position) // On a non-lazy stack SwiftUI ignores the initial value of @@ -207,14 +212,16 @@ private struct PagerBody: View { .scrollIndicators(.hidden) .scrollBounceBehavior(.basedOnSize) .contentMargins(0) - // `visibleRect` is inset-adjusted: its origin is 0 on page 0 - // and its length is the viewport, whatever the bar insets are. + // `visibleRect` is inset-adjusted: its origin is 0 on page 0. + // Its width is not a page, though: beside a sideways bar it + // takes in the bar's inset too, so horizontally a page is the + // ScrollView's own width, which `.paging` steps by. // Before the first layout the pager has no size. That is no // page yet, not page 0: reported as page 0, PHP would think the // user had left the start page. .onScrollGeometryChange(for: Int?.self) { geometry in let visible = geometry.visibleRect - let length = horizontal ? visible.width : visible.height + let length = horizontal ? geometry.bounds.width : visible.height guard length > 0, count > 0 else { return nil } let offset = horizontal ? visible.minX : visible.minY return min(count - 1, max(0, Int((offset / length).rounded()))) @@ -236,7 +243,7 @@ private struct PagerBody: View { // pager has a size, so the row doesn't flash the first tab. .onScrollGeometryChange(for: CGFloat?.self) { geometry in let visible = geometry.visibleRect - let length = horizontal ? visible.width : visible.height + let length = horizontal ? geometry.bounds.width : visible.height guard length > 0 else { return nil } return (horizontal ? visible.minX : visible.minY) / length } action: { _, value in @@ -503,6 +510,7 @@ private struct PagerTabStrip: View { row(theme) .padding(.horizontal, tabs.edgePadding) } + .clipShape(PagerSideClip(horizontal: true)) .scrollIndicators(.hidden) .scrollPosition($rowPosition) .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { viewportWidth = $0 } @@ -1017,3 +1025,16 @@ private struct PagerHeaderScrollViewFinder: UIViewRepresentable { } } } + +/// Clips a horizontal pager at its sides only, leaving a page's height of +/// room above and below, so its pages can still draw under a bar at the +/// bottom. A vertical pager gets that much room on every side as well. +private struct PagerSideClip: Shape { + let horizontal: Bool + + func path(in rect: CGRect) -> Path { + Path(horizontal + ? rect.insetBy(dx: 0, dy: -rect.height) + : rect.insetBy(dx: -rect.width, dy: -rect.height)) + } +} diff --git a/tests/IosPagerTabBarTest.php b/tests/IosPagerTabBarTest.php index 9c446dd6..05e3c52d 100644 --- a/tests/IosPagerTabBarTest.php +++ b/tests/IosPagerTabBarTest.php @@ -14,3 +14,12 @@ expect($source)->toMatch('/\.safeAreaPadding\(\.bottom, bottomInset\)\s*\.frame\(width: size\.width, height: size\.height\)\s*\.clipped\(\)/'); }); + +it('pages a horizontal pager by its own width and clips its sides beside a sideways bar', function () { + $source = file_get_contents(dirname(__DIR__).'/resources/ios/NativeUIPagerRenderer.swift'); + + expect($source) + ->toContain('let length = horizontal ? geometry.bounds.width : visible.height') + ->toContain('.clipShape(PagerSideClip(horizontal: horizontal))') + ->toContain('.clipShape(PagerSideClip(horizontal: true))'); +}); From 4a0131a54041fafe32adf6e2694271c4b8d01ea9 Mon Sep 17 00:00:00 2001 From: Connor McManus Date: Tue, 17 Nov 2026 07:59:52 -0800 Subject: [PATCH 2/4] Bring a horizontal pager back to its page after iOS resizes it When iOS resizes the pager, it can come back between two pages. That happens when iOS resizes the app in the background, or when the Duo folds or unfolds while the app is in front. PagerResume keeps the page the user chose, a tab tap or a page PHP jumped to, and scrolls back to it once the size settles. It tries twice, then gives up, accepts the nearest page and reports it to PHP. One geometry sample now drives the page, the tab progress and the report, so they can't disagree mid resize. --- resources/ios/NativeUIPagerRenderer.swift | 449 ++++++++++++++++++++-- tests/IosPagerStartPageTest.php | 6 +- tests/PagerReportOnSettleTest.php | 7 +- tests/PagerTabsTest.php | 6 +- 4 files changed, 432 insertions(+), 36 deletions(-) diff --git a/resources/ios/NativeUIPagerRenderer.swift b/resources/ios/NativeUIPagerRenderer.swift index 370f4a3f..35d65efd 100644 --- a/resources/ios/NativeUIPagerRenderer.swift +++ b/resources/ios/NativeUIPagerRenderer.swift @@ -98,6 +98,8 @@ private struct PagerBody: View { /// Programmatic-jump binding only. Reading it back is useless here: /// under `.paging` it goes nil the moment the pager moves. @State private var position: Int? + /// A same-ID tap still needs an explicit scroll when geometry is off-grid. + @State private var tabRequest = 0 /// Page nearest the leading edge, derived from the scroll geometry. @State private var leading: Int /// Pages reported to PHP that it has not echoed back yet, oldest first. @@ -114,6 +116,10 @@ private struct PagerBody: View { @State private var progress: PagerProgress /// Where the header is, and each page's list, when there's a header. @State private var headerScroll = PagerHeaderScroll() + /// How a horizontal pager gets back on its page after iOS resizes it + /// while the app is in the background (see PagerResume). + @State private var resume: PagerResume + @Environment(\.scenePhase) private var scenePhase /// Loaded-but-unshipped pages this far from the current one get their /// placeholder image; the rest stay empty. Wide enough that a fast @@ -141,6 +147,7 @@ private struct PagerBody: View { _reported = State(initialValue: [requestedPage]) _lastReported = State(initialValue: requestedPage) _progress = State(initialValue: PagerProgress(CGFloat(requestedPage))) + _resume = State(initialValue: PagerResume(page: requestedPage, count: count)) } var body: some View { @@ -185,6 +192,7 @@ private struct PagerBody: View { // both size pages against the extended container and drift by // the inset on every swipe.) GeometryReader { geo in + ScrollViewReader { proxy in // A horizontal pager runs under a bar at the bottom of the // screen (a tab bar), as a screen's own list does. Its pages // take the full height and hand the bar's inset back to their @@ -219,41 +227,91 @@ private struct PagerBody: View { // Before the first layout the pager has no size. That is no // page yet, not page 0: reported as page 0, PHP would think the // user had left the start page. - .onScrollGeometryChange(for: Int?.self) { geometry in + // Rounded selection and fractional progress share one sample, + // so recovery ownership is checked before either can escape. + .onScrollGeometryChange(for: PagerPosition?.self) { geometry in let visible = geometry.visibleRect let length = horizontal ? geometry.bounds.width : visible.height - guard length > 0, count > 0 else { return nil } - let offset = horizontal ? visible.minX : visible.minY - return min(count - 1, max(0, Int((offset / length).rounded()))) - } action: { _, page in - guard let page else { return } + guard length > 0 else { return nil } + return PagerPosition(pages: (horizontal ? visible.minX : visible.minY) / length, length: length) + } action: { _, value in + if observe(value, proxy: proxy) { return } + guard let value else { return } + if resume.phase == .idle, resume.userScrolling { + // Idle had no size; this is its first measurable finish. + resume.settled() + reconcile(value) + resume.armed = horizontal && !resume.active + return + } + if horizontal, resume.active, !resume.armed, let target = resume.target { + // A timeout cannot cancel a scroll already sent to UIKit. + // Keep following its fresh geometry, including a late ack. + if value.isOn(target) { + resume.settled() + } + reconcile(value) + return + } + if resume.holds(horizontal: horizontal) { + // Not the user's doing: iOS sizing the app while it's in + // the background, or the pager being put back. Nothing + // follows it until the pager is back on its page. + resume.armed = resume.armed || !resume.active + if resume.active, resume.armed { + restore(proxy) + } + return + } + guard resume.count > 0 else { return } + let page = min(resume.count - 1, max(0, Int(value.pages.rounded()))) leading = page - // Report the moment a page becomes the nearest one, mid-swipe, - // so PHP's round-trip overlaps the animation instead of - // starting after it. Idle re-reports the same page (no-op). - // With `report_on_settle` only idle reports, so the frame - // the report causes never lands during the animation. - if !reportOnSettle { + // Report mid-swipe unless PHP requested settle-only reports. + if !reportOnSettle, !(horizontal && resume.target != nil) { report(page) } - // A header follows the page nearest the leading edge. headerScroll.lead(page) + if tabs != nil { + progress.value = value.pages + } } - // The same position, unrounded, for the tab row. Nil until the - // pager has a size, so the row doesn't flash the first tab. - .onScrollGeometryChange(for: CGFloat?.self) { geometry in - let visible = geometry.visibleRect - let length = horizontal ? geometry.bounds.width : visible.height - guard length > 0 else { return nil } - return (horizontal ? visible.minX : visible.minY) / length - } action: { _, value in - if tabs != nil, let value { - progress.value = value + .onScrollPhaseChange { _, phase, context in + scrollPhaseChanged(phase, geometry: context.geometry, proxy: proxy) + } + .onChange(of: scenePhase, initial: true) { _, phase in + resume.active = phase == .active + // Work queued before the app left the foreground is stale. + resume.suspend() + if !resume.active { + // Background sizing belongs to warm-resume, not an active + // resize's deadline. Keep its accepted selection and hold. + resume.resize = nil + } + if resume.active, resume.armed, horizontal { + // Hold the pager until it's checked: the geometry it + // came back with is not a page the user chose. + resume.restoring = true + restore(proxy) } } - .onScrollPhaseChange { _, phase in - guard phase == .idle else { return } - report(leading) + .onChange(of: count) { _, count in + resume.count = count + resume.accepted = min(resume.accepted, max(count - 1, 0)) + if count == 0 { + resume.settled() + resume.phase = .idle + return + } + if let target = resume.target { + resume.target = min(target, count - 1) + } + if let resize = resume.resize { + resize.page = min(resize.page, count - 1) + } + resume.suspend() + if resume.active, resume.armed, horizontal { + restore(proxy) + } } .onChange(of: requestedPage) { _, page in // An echo of something we reported: drop it and everything @@ -268,8 +326,229 @@ private struct PagerBody: View { } reported = [page] lastReported = page + resume.chosen(page) position = page + if horizontal { + verifySelection(proxy) + } + } + .onChange(of: tabRequest) { _, _ in + verifySelection(proxy) + } + } + } + } + + /// Tracking is only a finger down. Keep the recovery until that finger + /// actually moves, or check it again when the touch ends without a drag. + private func scrollPhaseChanged(_ phase: ScrollPhase, geometry: ScrollGeometry, proxy: ScrollViewProxy) { + resume.phase = phase + if phase == .tracking { + resume.suspend() + return + } + if phase == .interacting { + resume.settled() + resume.userScrolling = true + return + } + guard phase == .idle else { return } + let finishedSwipe = resume.userScrolling + let visible = geometry.visibleRect + let length = horizontal ? geometry.bounds.width : visible.height + guard length > 0, resume.count > 0 else { + if horizontal, resume.armed, resume.target != nil { + resume.restoring = true + } + return + } + let final = PagerPosition(pages: (horizontal ? visible.minX : visible.minY) / length, length: length) + if observe(final, proxy: proxy) { return } + resume.userScrolling = false + if finishedSwipe { + resume.settled() + reconcile(final) + // A real swipe can finish after the scene became inactive. + // Accept it now; subsequent system resizes must not replace it. + resume.armed = horizontal && !resume.active + } else if horizontal, resume.armed, let target = resume.target { + if resume.active, final.isOn(target) { + resume.settled() + reconcile(final) + } else if resume.active { + restore(proxy) + } + } else if resume.holds(horizontal: horizontal) { + if resume.active, resume.armed { + restore(proxy) + } + } else { + if horizontal, let target = resume.target, final.isOn(target) { + resume.settled() } + reconcile(final) + } + } + + /// Classify a sample before it can change selection, header or PHP. Width + /// changes belong to layout, unless a genuine swipe already owns the move. + /// A quiet width groups the burst; it does not forget its selected page. + private func observe(_ value: PagerPosition?, proxy: ScrollViewProxy) -> Bool { + resume.position = value + resume.geometryVersion += 1 + guard horizontal, let value else { return false } + let changed = resume.width.map { abs($0 - value.length) > 0.5 } ?? false + resume.width = value.length + guard resume.active, !resume.userScrolling, resume.count > 0 else { return false } + if changed { + let page = resume.resize?.page ?? (resume.armed ? resume.target : nil) ?? resume.accepted + // Quiet is not an acknowledgement. Churn cannot refill a live + // or exhausted repair; only a completed selection can start anew. + if resume.resize == nil || (resume.resize!.stable && !resume.resize!.checking && !resume.resize!.exhausted) { + let resize = PagerResize(page: page) + resume.resize = resize + } + let resize = resume.resize! + resize.version += 1 + resize.stable = false + let version = resize.version + resume.suspend() + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250)) { + guard resume.resize === resize, resize.version == version else { return } + resize.stable = true + if resume.active, resume.armed, !resize.exhausted { + restore(proxy) + } + } + } + guard let resize = resume.resize, !resize.exhausted else { return false } + if !resize.checking { + resize.checking = true + resize.timerVersion += 1 + let timer = resize.timerVersion + // Bound each outstanding repair burst, not passive selection + // ownership. Acknowledgement cancels this timer, not its budget. + DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) { + guard resume.resize === resize, resize.timerVersion == timer, !resize.exhausted else { return } + resize.overdue = true + if resume.active, resume.phase == .idle, resume.armed { + failResume() + } + } + } + resume.accepted = min(resize.page, resume.count - 1) + resume.target = resume.accepted + resume.armed = true + resume.restoring = true + if resize.stable || resize.overdue, resume.phase == .idle { + restore(proxy) + } + return true + } + + /// Reconcile from one geometry sample, not separately delivered rounded + /// and fractional callbacks. `report` de-duplicates a page PHP knows. + private func reconcile(_ position: PagerPosition) { + guard resume.count > 0 else { return } + let page = min(max(Int(position.pages.rounded()), 0), resume.count - 1) + resume.accepted = page + leading = page + headerScroll.lead(page) + if tabs != nil { + progress.value = position.pages + } + report(page) + } + + /// Every explicit horizontal selection gets a check, including a binding + /// assignment that does not move anything. Give an ordinary animation time + /// to start; its idle callback owns completion if it is still running. + private func verifySelection(_ proxy: ScrollViewProxy) { + guard resume.active, resume.armed else { return } + if resume.phase == .idle, let position = resume.position, position.isOn(resume.accepted) { + resume.settled(preservingResize: true) + reconcile(position) + return + } + let generation = resume.generation + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250)) { + guard generation == resume.generation, resume.active, resume.armed, resume.phase == .idle else { return } + restore(proxy) + } + } + + /// Puts the pager back on the page it was meant to be on, once the app + /// is in front again: one check at a time, on the next turn of the run + /// loop, dropped if anything newer happened first. Each of two attempts + /// waits for new geometry, with a bounded timeout if layout never replies. + private func restore(_ proxy: ScrollViewProxy) { + let generation = resume.generation + guard resume.pending != generation else { return } + resume.pending = generation + DispatchQueue.main.async { + if resume.pending == generation { + resume.pending = nil + } + guard generation == resume.generation, resume.active, resume.armed, resume.phase == .idle else { return } + if let resize = resume.resize { + if resize.exhausted { return } + if resize.overdue { + failResume() + return + } + if !resize.stable { return } + } + guard resume.count > 0 else { + resume.settled() + return + } + guard let position = resume.position else { + // The next valid geometry sample continues this idle check. + resume.restoring = true + return + } + let page = min(max(resume.accepted, 0), resume.count - 1) + if position.isOn(page) { + resume.settled(preservingResize: true) + reconcile(position) + return + } + if let waiting = resume.waitingForGeometry, resume.geometryVersion <= waiting { + return + } + if (resume.resize?.attempts ?? resume.attempts) >= 2 { + failResume() + return + } + resume.restoring = true + resume.target = page + resume.attempts += 1 + resume.resize?.attempts += 1 + resume.waitingForGeometry = resume.geometryVersion + let attempt = resume.attempts + var transaction = Transaction() + transaction.disablesAnimations = true + withTransaction(transaction) { proxy.scrollTo(page, anchor: .leading) } + DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(250)) { + guard generation == resume.generation, resume.armed, resume.attempts == attempt else { return } + failResume() + } + } + } + + /// A failed correction is not a successful restore. Release the hold, + /// reconcile PHP and native selection with the actual nearest page. Keep + /// ownership of the issued scroll until it acknowledges or newer intent + /// supersedes it: timing out cannot cancel a native scroll already issued. + private func failResume() { + NSLog("NativeUI pager resume correction failed after \(resume.attempts) attempt(s)") + let target = resume.target + resume.resize?.exhausted = true + resume.settled(preservingResize: true) + resume.target = target + if let position = resume.position { + reconcile(position) + resume.resize?.page = resume.accepted } } @@ -337,13 +616,23 @@ private struct PagerBody: View { private func selectTab(_ index: Int) { guard index >= 0, index < count else { return } - if index == leading, abs(progress.value - CGFloat(index)) < 0.01 { + resume.chosen(index) + if index == leading, abs(progress.value - CGFloat(index)) < 0.01, resume.position?.isOn(index) == true { + resume.settled() if let cb = tabs?.reselectCbId, cb != 0 { NativeElementBridge.sendTabChangeEvent(cb, nodeId: nodeId, index: index) } return } + if horizontal, resume.active, resume.phase == .idle, let actual = resume.position, actual.isOn(index) { + resume.settled() + reconcile(actual) + return + } + if horizontal { + tabRequest += 1 + } withAnimation { position = index } } @@ -1038,3 +1327,109 @@ private struct PagerSideClip: Shape { : rect.insetBy(dx: -rect.width, dy: -rect.height)) } } + +/// Where the pager is, in pages, and how long a page is. +private struct PagerPosition: Equatable { + let pages: CGFloat + let length: CGFloat + + /// Within half a point of `page`. + func isOn(_ page: Int) -> Bool { + abs(pages - CGFloat(page)) * length <= 0.5 + } +} + +/// A horizontal pager's way back to its page after iOS resizes it in the +/// background (on an iPhone Duo beside its side rail, the pager came back +/// between two pages). A class, so none of this redraws the pages. +private final class PagerResume { + /// The page the pager is meant to be on: where it last came to rest on + /// a page, a tapped tab, or a page PHP jumped to. + var accepted: Int + var count: Int + /// The latest scroll geometry; nil while the pager has no size. + var position: PagerPosition? + /// Last measurable width survives zero-size layout samples. + var width: CGFloat? + var resize: PagerResize? + var active = true + var phase: ScrollPhase = .idle + var userScrolling = false + var geometryVersion = 0 + var waitingForGeometry: Int? + /// An explicit selection or issued correction still owns its completion, + /// even after its retry timeout. New user/PHP intent replaces this target. + var target: Int? + /// The pager moved while the app wasn't in front, so it may be off its page. + var armed = false + /// The pager is being put back; its moves are not the user's. + var restoring = false + var attempts = 0 + /// Bumped by anything that makes queued work stale. + var generation = 0 + /// The generation a check is queued for. + var pending: Int? + + init(page: Int, count: Int) { + accepted = page + self.count = count + } + + /// Geometry changes aren't the user's: the app isn't in front, or the + /// pager is being put back, and nobody is scrolling. + func holds(horizontal: Bool) -> Bool { + horizontal && (!active || restoring) && !userScrolling + } + + /// A tab tap or a PHP jump: the pager goes there instead. In the + /// background its move is only seen once the app is in front again. + func chosen(_ page: Int) { + let holding = restoring || !active + settled() + accepted = page + target = page + armed = true + restoring = holding + } + + /// Cancel queued checks and timeouts without losing the recovery intent. + func suspend() { + generation += 1 + waitingForGeometry = nil + attempts = 0 + } + + /// The user scrolled: whatever was pending is theirs to decide. + func settled(preservingResize: Bool = false) { + suspend() + restoring = false + armed = false + userScrolling = false + target = nil + if preservingResize { + resize?.checking = false + resize?.overdue = false + resize?.timerVersion += 1 + } else { + resize = nil + } + } +} + +/// Selection survives an acknowledgement; command budget does not reset on +/// alignment, tracking or duplicate geometry. A later width burst gets a new +/// episode, while a same-width late clamp still belongs to this one. +private final class PagerResize { + var page: Int + var stable = false + var exhausted = false + var attempts = 0 + var version = 0 + var checking = false + var overdue = false + var timerVersion = 0 + + init(page: Int) { + self.page = page + } +} diff --git a/tests/IosPagerStartPageTest.php b/tests/IosPagerStartPageTest.php index a670cd5b..71fb3258 100644 --- a/tests/IosPagerStartPageTest.php +++ b/tests/IosPagerStartPageTest.php @@ -12,7 +12,7 @@ $source = file_get_contents(dirname(__DIR__).'/resources/ios/NativeUIPagerRenderer.swift'); expect($source) - ->toContain('.onScrollGeometryChange(for: Int?.self)') - ->toContain('guard length > 0, count > 0 else { return nil }') - ->toContain('guard let page else { return }'); + ->toContain('.onScrollGeometryChange(for: PagerPosition?.self)') + ->toContain('guard length > 0 else { return nil }') + ->toContain('guard let value else { return }'); }); diff --git a/tests/PagerReportOnSettleTest.php b/tests/PagerReportOnSettleTest.php index 207c0d48..568888cc 100644 --- a/tests/PagerReportOnSettleTest.php +++ b/tests/PagerReportOnSettleTest.php @@ -5,14 +5,15 @@ expect($source) ->toContain('reportOnSettle: p.getBool("report_on_settle")') - ->toMatch('/leading = page\s*(\/\/[^\n]*\s*)*if !reportOnSettle \{\s*report\(page\)\s*\}/') - ->toMatch('/guard phase == \.idle else \{ return \}\s*report\(leading\)/'); + ->toMatch('/leading = page\s*(\/\/[^\n]*\s*)*if !reportOnSettle, [^{]*\{\s*report\(page\)\s*\}/') + ->toMatch('/guard phase == \.idle else \{ return \}[\s\S]*?reconcile\(final\)/') + ->toMatch('/private func reconcile\(_ position: PagerPosition\) \{[\s\S]*?report\(page\)\s*\}/'); }); it('counts a programmatic jump as known to PHP on iOS', function () { $source = file_get_contents(dirname(__DIR__).'/resources/ios/NativeUIPagerRenderer.swift'); - expect($source)->toMatch('/reported = \[page\]\s*lastReported = page\s*position = page/'); + expect($source)->toMatch('/reported = \[page\]\s*lastReported = page\s*resume\.chosen\(page\)\s*position = page/'); }); it('reports the settled page on Android when reporting on settle', function () { diff --git a/tests/PagerTabsTest.php b/tests/PagerTabsTest.php index 20877b82..37c7bfda 100644 --- a/tests/PagerTabsTest.php +++ b/tests/PagerTabsTest.php @@ -140,8 +140,8 @@ function pagerTabProps(array $attrs, ?CallbackRegistry $registry = null): array expect($source) // The unrounded position, written every frame into an observable only the row reads. - ->toContain('.onScrollGeometryChange(for: CGFloat?.self)') - ->toContain('progress.value = value') + ->toContain('.onScrollGeometryChange(for: PagerPosition?.self)') + ->toContain('progress.value = value.pages') ->toContain('@Observable') // Highlight: the nearest page. Indicator: between the labels either side. ->toContain('Int(progress.value.rounded())') @@ -156,7 +156,7 @@ function pagerTabProps(array $attrs, ?CallbackRegistry $registry = null): array $source = file_get_contents(dirname(__DIR__).'/resources/ios/NativeUIPagerRenderer.swift'); expect($source) - ->toMatch('/if index == leading, abs\(progress\.value - CGFloat\(index\)\) < 0\.01 \{\s*if let cb = tabs\?\.reselectCbId, cb != 0 \{\s*NativeElementBridge\.sendTabChangeEvent\(cb, nodeId: nodeId, index: index\)/') + ->toMatch('/if index == leading, abs\(progress\.value - CGFloat\(index\)\) < 0\.01, resume\.position\?\.isOn\(index\) == true \{\s*resume\.settled\(\)\s*if let cb = tabs\?\.reselectCbId, cb != 0 \{\s*NativeElementBridge\.sendTabChangeEvent\(cb, nodeId: nodeId, index: index\)/') ->toContain('withAnimation { position = index }'); }); From b35b3b17f8ed9bc643bb9dfbb0eca1c635890826 Mon Sep 17 00:00:00 2001 From: Connor McManus Date: Sat, 14 Nov 2026 15:09:28 -0800 Subject: [PATCH 3/4] Draw a pager's header beside its pages on a wide iOS window header-beside="expanded" (any breakpoint name, or a width in points) moves a horizontal pager's header into a leading column of its own once the window is that wide. The tabs and pages fill the trailing column. On a foldable the columns split at the fold. When the fold is partly closed they stop at the edges of its division region, so no control sits in the crease. Elsewhere the two columns share the width evenly. Narrower than the breakpoint, the header stays above the tabs, in each page's list, as before. Native decides from the live window width, as it does for responsive classes, so PHP sends the header once and unfolding or Split View moves it without a round trip. Both layouts share one paging scroll view, so crossing the breakpoint keeps the page and every page's scroll offset. iOS only for now. Android keeps the header above the tabs at any width. --- resources/ios/NativeUIPagerRenderer.swift | 176 ++++++++++++++++++---- src/Elements/Pager.php | 29 ++++ src/Elements/PagerHeader.php | 4 + tests/PagerHeaderTest.php | 24 ++- 4 files changed, 203 insertions(+), 30 deletions(-) diff --git a/resources/ios/NativeUIPagerRenderer.swift b/resources/ios/NativeUIPagerRenderer.swift index 35d65efd..84fcca1b 100644 --- a/resources/ios/NativeUIPagerRenderer.swift +++ b/resources/ios/NativeUIPagerRenderer.swift @@ -26,6 +26,11 @@ import SwiftUI struct NativeUIPagerRenderer: View { let node: NativeUINode + /// The window width responsive variants resolve against, so the header + /// moves beside the pages at the same width an `expanded:` class applies. + @Environment(\.windowWidth) private var windowWidth + @Environment(\.availableWidth) private var availableWidth + var body: some View { let p = node.props let horizontal = p.getBool("horizontal") @@ -49,6 +54,14 @@ struct NativeUIPagerRenderer: View { return map }() + // Only a horizontal pager's pages scroll up and down under a header. + let header = horizontal ? node.children.first { $0.type == "pager_header" } : nil + let besideFrom = CGFloat(p.getFloat("header_beside_from")) + // As NodeView resolves the classes: the window has no width yet on + // the first frame. + let width = windowWidth > 0 ? windowWidth : availableWidth + let beside = header != nil && besideFrom > 0 && width >= besideFrom + PagerBody( nodeId: node.id, count: pageCount, @@ -60,8 +73,8 @@ struct NativeUIPagerRenderer: View { pageByIndex: pageByIndex, placeholders: p.getStringList("placeholders"), tabs: PagerTabs(props: p), - // Only a horizontal pager's pages scroll up and down under a header. - header: horizontal ? node.children.first { $0.type == "pager_header" } : nil, + header: beside ? nil : header, + besideHeader: beside ? header : nil, overlay: node.children.first { $0.type == "pager_overlay" }, background: PagerColor(light: node.style?.bgColor, dark: p.has("dark_bg_color") ? p.getColor("dark_bg_color", default: 0) : nil), a11yLabel: p.getString("a11y_label") @@ -89,6 +102,9 @@ private struct PagerBody: View { let tabs: PagerTabs? /// The `pager_header`, which each page's list draws above the tabs. let header: NativeUINode? + /// The `pager_header` instead drawn in a column of its own beside the + /// pages, once the window is wide enough (`header_beside_from`). + let besideHeader: NativeUINode? /// The `pager_overlay`, laid over the pages under the tabs. let overlay: NativeUINode? /// The pager's own background, behind the tabs a header pins. @@ -116,6 +132,8 @@ private struct PagerBody: View { @State private var progress: PagerProgress /// Where the header is, and each page's list, when there's a header. @State private var headerScroll = PagerHeaderScroll() + /// Where the header beside the pages ends and the pages begin. + @State private var split = PagerSplit.even(0) /// How a horizontal pager gets back on its page after iOS resizes it /// while the app is in the background (see PagerResume). @State private var resume: PagerResume @@ -127,7 +145,7 @@ private struct PagerBody: View { /// long feed never fetches stills it may never reach. static let placeholderRadius = 4 - init(nodeId: Int, count: Int, loaded: Int, requestedPage: Int, horizontal: Bool, reportOnSettle: Bool, cbId: Int, pageByIndex: [Int: NativeUINode], placeholders: [String], tabs: PagerTabs?, header: NativeUINode?, overlay: NativeUINode?, background: PagerColor, a11yLabel: String) { + init(nodeId: Int, count: Int, loaded: Int, requestedPage: Int, horizontal: Bool, reportOnSettle: Bool, cbId: Int, pageByIndex: [Int: NativeUINode], placeholders: [String], tabs: PagerTabs?, header: NativeUINode?, besideHeader: NativeUINode?, overlay: NativeUINode?, background: PagerColor, a11yLabel: String) { self.nodeId = nodeId self.count = count self.loaded = loaded @@ -139,6 +157,7 @@ private struct PagerBody: View { self.placeholders = placeholders self.tabs = tabs self.header = header + self.besideHeader = besideHeader self.overlay = overlay self.background = background self.a11yLabel = a11yLabel @@ -150,27 +169,47 @@ private struct PagerBody: View { _resume = State(initialValue: PagerResume(page: requestedPage, count: count)) } + /// One layout whether the header is beside the pages, in them or absent, + /// so crossing `header_beside_from` (unfolding, Split View) shows or + /// hides the column and the tab row around the same paging scroll view + /// instead of rebuilding it and every page's list. var body: some View { - if header != nil { - // The pages' lists draw the header and the tabs themselves, so - // they scroll with the page (see NativeUIPagerHeader). - pager - .overlay(alignment: .top) { overlayView } - .modifier(PagerA11yLabelModifier(label: a11yLabel)) - .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in - headerScroll.pageWidth = frame.width - headerScroll.pagerMinY = frame.minY + HStack(spacing: 0) { + if let besideHeader { + // The header scrolls by itself in the leading column, and + // the tabs and pages fill the trailing one. + ScrollView(.vertical) { + PagerChildren(node: besideHeader) + .frame(maxWidth: .infinity, alignment: .leading) } - } else { + .frame(width: split.leading) + Color.clear + .frame(width: split.gap) + .accessibilityHidden(true) + } VStack(spacing: 0) { - if let tabs { + // Under a header the pages' lists draw the header and the + // tabs themselves, so they scroll with the page (see + // NativeUIPagerHeader). + if let tabs, header == nil { PagerTabStrip(tabs: tabs, progress: progress, select: selectTab) } pager .overlay(alignment: .top) { overlayView } .modifier(PagerA11yLabelModifier(label: a11yLabel)) + .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in + headerScroll.pageWidth = frame.width + headerScroll.pagerMinY = frame.minY + } } } + .onGeometryChange(for: PagerSplit.self) { PagerSplit(in: $0) } action: { split = $0 } + // Beside the pages, the header leaves their lists, which stop + // reporting where they are but keep their scroll views. Forgotten + // now, each is found again where it is once the header is back. + .onChange(of: header == nil) { _, gone in + if gone { headerScroll.reset() } + } } @ViewBuilder @@ -584,7 +623,7 @@ private struct PagerBody: View { Group { if let child = pageByIndex[index] { NodeView(node: child).equatable() - .environment(\.nativeUIPagerHeader, header.map { pagerHeader(page: index, node: $0) }) + .environment(\.nativeUIPagerHeader, (header ?? besideHeader).map { pagerHeader(page: index, node: $0) }) } else if index >= loaded { ProgressView() .controlSize(.large) @@ -606,8 +645,10 @@ private struct PagerBody: View { /// What page `index` gets of the header: the same object for the life /// of the pager, so a render only redraws the parts of it that changed. + /// A page gets it beside the pages too, with nothing to draw, so its + /// list is the same list either way and keeps its place. private func pagerHeader(page index: Int, node: NativeUINode) -> NativeUIPagerHeader { - headerScroll.header(page: index, node: node, tabs: tabs, background: background, progress: progress, select: selectTab) + headerScroll.header(page: index, node: node, inList: header != nil, tabs: tabs, background: background, progress: progress, select: selectTab) } /// A tap on a tab: scroll there, and the page is reported when the @@ -957,6 +998,37 @@ private struct PagerTabStrip: View { // MARK: - Header +/// Where a pager splits into its header and its pages: at a foldable's fold, +/// for an even split around the hinge. Flat, the columns meet on it. Partly +/// folded, its division region is active and they stop at its margins, +/// keeping controls out of the crease. Without a fold across the pager the +/// columns share the width evenly. +private struct PagerSplit: Equatable { + var leading: CGFloat + var gap: CGFloat + + static func even(_ width: CGFloat) -> PagerSplit { + PagerSplit(leading: (width / 2).rounded(), gap: 0) + } + + init(leading: CGFloat, gap: CGFloat) { + self.leading = leading + self.gap = gap + } + + init(in proxy: GeometryProxy) { + let width = proxy.size.width + self = .even(width) + guard #available(iOS 27.1, *) else { return } + let folds = proxy.reservedRegions(kind: .division, options: .includeInactive) + .filter { $0.frame.height > $0.frame.width && $0.frame.minX > 0 && $0.frame.maxX < width } + guard let fold = folds.min(by: { abs($0.frame.midX - width / 2) < abs($1.frame.midX - width / 2) }) else { return } + self = fold.isActive + ? PagerSplit(leading: fold.frame.minX, gap: fold.frame.width) + : PagerSplit(leading: fold.frame.midX, gap: 0) + } +} + /// A colour as PHP sent it, light and dark, nil where it sent none. struct PagerColor: Equatable { let light: Int? @@ -987,15 +1059,19 @@ struct PagerColor: Equatable { final class NativeUIPagerHeader { let page: Int var node: NativeUINode + /// Whether the page's list draws the header and the tabs. Beside the + /// pages, the pager draws them itself and the list only its own rows. + var inList: Bool fileprivate var tabs: PagerTabs? var background: PagerColor fileprivate let progress: PagerProgress @ObservationIgnored fileprivate var select: (Int) -> Void let scroll: PagerHeaderScroll - fileprivate init(page: Int, node: NativeUINode, tabs: PagerTabs?, background: PagerColor, progress: PagerProgress, select: @escaping (Int) -> Void, scroll: PagerHeaderScroll) { + fileprivate init(page: Int, node: NativeUINode, inList: Bool, tabs: PagerTabs?, background: PagerColor, progress: PagerProgress, select: @escaping (Int) -> Void, scroll: PagerHeaderScroll) { self.page = page self.node = node + self.inList = inList self.tabs = tabs self.background = background self.progress = progress @@ -1070,15 +1146,16 @@ final class PagerHeaderScroll { weak var view: UIScrollView? } - fileprivate func header(page: Int, node: NativeUINode, tabs: PagerTabs?, background: PagerColor, progress: PagerProgress, select: @escaping (Int) -> Void) -> NativeUIPagerHeader { + fileprivate func header(page: Int, node: NativeUINode, inList: Bool, tabs: PagerTabs?, background: PagerColor, progress: PagerProgress, select: @escaping (Int) -> Void) -> NativeUIPagerHeader { guard let header = headers[page] else { - let header = NativeUIPagerHeader(page: page, node: node, tabs: tabs, background: background, progress: progress, select: select, scroll: self) + let header = NativeUIPagerHeader(page: page, node: node, inList: inList, tabs: tabs, background: background, progress: progress, select: select, scroll: self) headers[page] = header return header } // Only what changed, so an unchanged header doesn't redraw. if header.node !== node { header.node = node } + if header.inList != inList { header.inList = inList } if header.tabs != tabs { header.tabs = tabs } if header.background != background { header.background = background } header.select = select @@ -1108,11 +1185,27 @@ final class PagerHeaderScroll { scrollViews[page] = WeakScrollView(view: scrollView) offsets[page] = scrollView.contentOffset.y + scrollView.adjustedContentInset.top - if page != leading { + if page == leading { + // The header follows this list from where it is, and any list + // found before it is brought level with it. + collapse = min(offsets[page] ?? 0, headerHeight) + for other in scrollViews.keys where other != page { + align(other) + } + } else if scrollViews[leading]?.view != nil { align(page) } } + /// Forget every list and how far the header had gone, so each list is + /// found again as it is. + func reset() { + collapse = 0 + stripMaxY = [:] + offsets = [:] + scrollViews = [:] + } + /// A page's list scrolled to `y`, its distance from its own top. func scrolled(page: Int, y: CGFloat) { offsets[page] = y @@ -1149,17 +1242,27 @@ final class PagerHeaderScroll { } /// The header as a page's list draws it: its first row. +/// +/// With the header beside the pages the row stays, drawing nothing, as does +/// the section the tabs head: taking either out reloads the whole list, +/// which loses its place. struct NativeUIPagerHeaderRow: View { let header: NativeUIPagerHeader var body: some View { - PagerChildren(node: header.node) - .frame(maxWidth: .infinity, alignment: .leading) - .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in - if header.scroll.headerHeight != height { header.scroll.headerHeight = height } - } - .background(PagerHeaderScrollViewFinder { header.scroll.attach($0, page: header.page) }) - .modifier(PagerStationary(header: header)) + if header.inList { + PagerChildren(node: header.node) + .frame(maxWidth: .infinity, alignment: .leading) + .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { height in + if header.scroll.headerHeight != height { header.scroll.headerHeight = height } + } + .background(PagerHeaderScrollViewFinder { header.scroll.attach($0, page: header.page) }) + .modifier(PagerStationary(header: header)) + } else { + Color.clear + .frame(height: 0) + .accessibilityHidden(true) + } } } @@ -1172,6 +1275,16 @@ struct NativeUIPagerHeaderStrip: View { @Environment(\.colorScheme) private var colorScheme var body: some View { + if header.inList { + strip + } else { + Color.clear + .frame(height: 0) + .accessibilityHidden(true) + } + } + + private var strip: some View { header.strip .frame(maxWidth: .infinity) .background(header.background.resolve(colorScheme, fallback: themeStore.resolve(for: colorScheme).surface)) @@ -1205,10 +1318,13 @@ struct NativeUIPagerHeaderListModifier: ViewModifier { func body(content: Content) -> some View { if let header { content - // Section headers get a minimum height and space above. + // Section headers get a minimum height and space above, and + // rows a minimum height, which the header's row beside the + // pages must not have. .environment(\.defaultMinListHeaderHeight, 0) + .environment(\.defaultMinListRowHeight, 0) .listSectionSpacing(0) - .contentMargins(.bottom, room, for: .scrollContent) + .contentMargins(.bottom, header.inList ? room : 0, for: .scrollContent) .onScrollGeometryChange(for: PagerListGeometry.self) { geometry in PagerListGeometry( y: geometry.contentOffset.y + geometry.contentInsets.top, @@ -1218,6 +1334,8 @@ struct NativeUIPagerHeaderListModifier: ViewModifier { container: geometry.containerSize.height ) } action: { _, geometry in + guard header.inList else { return } + header.scroll.scrolled(page: header.page, y: geometry.y) // The room this list needs to scroll the header away, past diff --git a/src/Elements/Pager.php b/src/Elements/Pager.php index c3980707..96d1d7cc 100644 --- a/src/Elements/Pager.php +++ b/src/Elements/Pager.php @@ -6,6 +6,7 @@ use InvalidArgumentException; use Native\Mobile\Edge\CallbackRegistry; use Native\Mobile\Edge\Element; +use Native\Mobile\Edge\TailwindParser; use Native\Mobile\UI\Concerns\ResolvesColorValues; use Native\Mobile\UI\Theme; @@ -83,6 +84,8 @@ * that scrolls up with the page showing while the tabs pin under the nav * bar: see {@see PagerHeader}. A {@see PagerOverlay} hangs under the tabs * over the pages. Neither counts as a page, and neither is windowed. + * `header-beside="expanded"` moves the header beside the pages once the + * window is that wide (see headerBeside()). * * The page index rides the tab-change transport, so a single feed is * capped at 32,767 pages per screen. @@ -138,6 +141,10 @@ public function applyAttributes(array $attrs): void if ($settle !== null) { $this->reportOnSettle(filter_var($settle, FILTER_VALIDATE_BOOLEAN)); } + $beside = $attrs['header_beside'] ?? $attrs['headerBeside'] ?? $attrs['header-beside'] ?? null; + if ($beside !== null) { + $this->headerBeside($beside); + } $cb = $attrs['on_page_change'] ?? $attrs['onPageChange'] ?? $attrs['on-page-change'] ?? null; if ($cb !== null) { $this->onPageChange($cb); @@ -212,6 +219,28 @@ public function reportOnSettle(bool $value = true): static return $this; } + /** + * From a breakpoint (`expanded`, `lg`, … as the responsive classes name + * them) or a width in points up, the header scrolls by itself in a + * leading column and the tabs and pages fill the trailing one, split at + * a foldable's fold or evenly elsewhere. Narrower, it is above the tabs + * as usual. Native decides against the live window width, as it does + * for the classes, so the header is sent once for either layout. iOS + * only so far: Android keeps the header above the tabs at any width. + */ + public function headerBeside(string|int|float $from): static + { + $width = is_numeric($from) ? (float) $from : TailwindParser::breakpointMinWidth($from); + + if ($width === null) { + throw new InvalidArgumentException("Unknown breakpoint [{$from}] for header-beside."); + } + + $this->pagerProps['header_beside_from'] = $width; + + return $this; + } + public function onPageChange(string $method): static { $this->pageCallback = $method; diff --git a/src/Elements/PagerHeader.php b/src/Elements/PagerHeader.php index d286e9ed..a82cd5c3 100644 --- a/src/Elements/PagerHeader.php +++ b/src/Elements/PagerHeader.php @@ -26,6 +26,10 @@ * always finds the header at the height it left it. Once the header has * gone, each page keeps its own place. A page too short to scroll the * header away gets room at its end to do so. + * + * With `header-beside` on the pager, a wide enough window has the header in + * a column of its own beside the pages instead, and the pages' lists draw + * only their own rows (see {@see Pager::headerBeside()}). */ class PagerHeader extends Element { diff --git a/tests/PagerHeaderTest.php b/tests/PagerHeaderTest.php index 51a43de7..3b548dd6 100644 --- a/tests/PagerHeaderTest.php +++ b/tests/PagerHeaderTest.php @@ -68,6 +68,28 @@ function kotlinSource(string $file): string ->and(array_column($tree['children'], 'type'))->toBe(['pager_header', 'column', 'column', 'pager_overlay']); }); +it('sends the width from which the header moves beside the pages', function () { + NativeElementCollector::open('pager', ['horizontal' => true, 'header-beside' => 'expanded']); + NativeElementCollector::close(); + + $tree = NativeElementCollector::collect()->toArray(new CallbackRegistry); + + expect($tree['props']['header_beside_from'])->toBe(840.0) + ->and(Pager::make()->headerBeside(700)->toArray(new CallbackRegistry)['props']['header_beside_from'])->toBe(700.0) + ->and(Pager::make()->toArray(new CallbackRegistry)['props'])->not->toHaveKey('header_beside_from'); +}); + +it('rejects a header-beside breakpoint it does not know', function () { + Pager::make()->headerBeside('enormous'); +})->throws(InvalidArgumentException::class, 'Unknown breakpoint [enormous] for header-beside.'); + +it('draws the header beside the pages on iOS once the window reaches that width', function () { + expect(swiftSource('NativeUIPagerRenderer.swift')) + ->toContain('let beside = header != nil && besideFrom > 0 && width >= besideFrom') + ->toContain('header: beside ? nil : header,') + ->toContain('besideHeader: beside ? header : nil,'); +}); + it('registers the header and the overlay for the pager to draw', function () { $components = collect(json_decode(file_get_contents(dirname(__DIR__).'/nativephp.json'), true)['components'])->keyBy('type'); @@ -85,7 +107,7 @@ function kotlinSource(string $file): string it('keeps the header and the overlay out of the pages on both platforms', function () { expect(swiftSource('NativeUIPagerRenderer.swift')) ->toContain('let pages = node.children.filter { $0.type != "pager_header" && $0.type != "pager_overlay" }') - ->toContain('header: horizontal ? node.children.first { $0.type == "pager_header" } : nil'); + ->toContain('let header = horizontal ? node.children.first { $0.type == "pager_header" } : nil'); expect(kotlinSource('PagerRenderer.kt')) ->toContain('node.children.filter { it.type != "pager_header" && it.type != "pager_overlay" }') From 1bef5438f9c06f3553dd15f63ed3d7a42c720c2e Mon Sep 17 00:00:00 2001 From: Connor McManus Date: Sat, 14 Nov 2026 15:09:28 -0800 Subject: [PATCH 4/4] Run lists and scroll views under a bar at their side on iOS Beside a vertical bar (the iPhone Duo's side rail, or a notched iPhone held sideways) a list stopped at the bar's inset. Its scroll indicator floated in from the screen edge, and row backgrounds ended short of the bar. Apple's own lists run under the bar. Lists, virtual lists, scroll views and a pager's beside-header column now ignore the horizontal container safe area and hand that inset back to their content as safe area. Rows stay where they were, their backgrounds reach under the bar, and the indicator sits at the screen edge. A horizontal pager does the same at its sides. Each page now spans the side insets as well as the bottom one, so .paging still steps by one page, and the pager measures its page width with the side insets included. On a screen with no side inset, such as a portrait iPhone, nothing changes. --- resources/ios/NativeUIListRenderer.swift | 1 + resources/ios/NativeUIPagerRenderer.swift | 40 +++++++++++++------ .../ios/NativeUIScrollViewRenderer.swift | 19 +++++++++ .../ios/NativeUIVirtualListRenderer.swift | 1 + tests/IosPagerTabBarTest.php | 23 ++++++++--- 5 files changed, 65 insertions(+), 19 deletions(-) diff --git a/resources/ios/NativeUIListRenderer.swift b/resources/ios/NativeUIListRenderer.swift index a6480ec2..e298c3d6 100644 --- a/resources/ios/NativeUIListRenderer.swift +++ b/resources/ios/NativeUIListRenderer.swift @@ -200,6 +200,7 @@ struct NativeUIListRenderer: View { // Only this list draws the header, not one in its rows. .environment(\.nativeUIPagerHeader, nil) .modifier(ListAutoScrollModifier(request: autoScrollTo, targetID: autoScrollTarget, anchor: .top)) + .modifier(NativeUIScrollEdgeExtension()) } } diff --git a/resources/ios/NativeUIPagerRenderer.swift b/resources/ios/NativeUIPagerRenderer.swift index 84fcca1b..af54aaec 100644 --- a/resources/ios/NativeUIPagerRenderer.swift +++ b/resources/ios/NativeUIPagerRenderer.swift @@ -182,6 +182,7 @@ private struct PagerBody: View { PagerChildren(node: besideHeader) .frame(maxWidth: .infinity, alignment: .leading) } + .modifier(NativeUIScrollEdgeExtension()) .frame(width: split.leading) Color.clear .frame(width: split.gap) @@ -197,7 +198,12 @@ private struct PagerBody: View { pager .overlay(alignment: .top) { overlayView } .modifier(PagerA11yLabelModifier(label: a11yLabel)) - .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frame in + .onGeometryChange(for: CGRect.self) { proxy in + // A page also spans the bar insets at its sides (see `pager`). + let sides = horizontal ? proxy.safeAreaInsets.leading + proxy.safeAreaInsets.trailing : 0 + let frame = proxy.frame(in: .global) + return CGRect(x: frame.minX, y: frame.minY, width: frame.width + sides, height: frame.height) + } action: { frame in headerScroll.pageWidth = frame.width headerScroll.pagerMinY = frame.minY } @@ -238,17 +244,25 @@ private struct PagerBody: View { // content as safe area, so a list in a page draws under the // bar and still scrolls its last row clear of it. Paging is // sideways, so the extra height can't make the pages drift. - let bottomInset = horizontal ? geo.safeAreaInsets.bottom : 0 + // + // It runs under a bar at its side (an iPhone Duo's vertical bar) + // the same way, so a page's list can put its scroll indicator at + // the screen's edge while its rows stay clear of the bar. Each + // page spans the insets, so `.paging` still steps by one page. + let insets = horizontal + ? EdgeInsets(top: 0, leading: geo.safeAreaInsets.leading, bottom: geo.safeAreaInsets.bottom, trailing: geo.safeAreaInsets.trailing) + : EdgeInsets() ScrollView(axis) { - pages(size: CGSize(width: geo.size.width, height: geo.size.height + bottomInset), bottomInset: bottomInset) + pages(size: CGSize(width: geo.size.width + insets.leading + insets.trailing, height: geo.size.height + insets.bottom), insets: insets) .scrollTargetLayout() } - .ignoresSafeArea(.container, edges: horizontal ? .bottom : []) - // Beside a sideways bar (an iPhone Duo's rail) the ScrollView - // also draws into the bar's inset, so the next page showed - // under it. Clip the sides only: the pages still run under a - // bar at the bottom. + // A ScrollView draws past its sides, so the next page showed + // beside the pager. Clip the sides only, at the edges the pages + // run to: inside the safe-area extension, which lays this out + // over the side insets. The pages still run under a bar at the + // bottom. .clipShape(PagerSideClip(horizontal: horizontal)) + .ignoresSafeArea(.container, edges: horizontal ? [.bottom, .horizontal] : []) .scrollTargetBehavior(.paging) .scrollPosition(id: $position) // On a non-lazy stack SwiftUI ignores the initial value of @@ -610,15 +624,15 @@ private struct PagerBody: View { /// stack expensive, so they only exist within `placeholderRadius` of /// the current page; further slots are clear until scrolled towards. @ViewBuilder - private func pages(size: CGSize, bottomInset: CGFloat) -> some View { + private func pages(size: CGSize, insets: EdgeInsets) -> some View { if horizontal { - HStack(spacing: 0) { pageViews(size: size, bottomInset: bottomInset) } + HStack(spacing: 0) { pageViews(size: size, insets: insets) } } else { - VStack(spacing: 0) { pageViews(size: size, bottomInset: bottomInset) } + VStack(spacing: 0) { pageViews(size: size, insets: insets) } } } - private func pageViews(size: CGSize, bottomInset: CGFloat) -> some View { + private func pageViews(size: CGSize, insets: EdgeInsets) -> some View { ForEach(0.. some View { + content + .safeAreaPadding(.leading, insets.leading) + .safeAreaPadding(.trailing, insets.trailing) + .ignoresSafeArea(.container, edges: .horizontal) + .onGeometryChange(for: EdgeInsets.self) { proxy in + EdgeInsets(top: 0, leading: proxy.safeAreaInsets.leading, bottom: 0, trailing: proxy.safeAreaInsets.trailing) + } action: { insets = $0 } + } +} diff --git a/resources/ios/NativeUIVirtualListRenderer.swift b/resources/ios/NativeUIVirtualListRenderer.swift index 1709d5a2..69ec666c 100644 --- a/resources/ios/NativeUIVirtualListRenderer.swift +++ b/resources/ios/NativeUIVirtualListRenderer.swift @@ -56,6 +56,7 @@ struct NativeUIVirtualListRenderer: View { // Environment-propagating, so it reaches the List inside the body // without threading another property through it. .scrollIndicators(node.props.getBool("shows_indicators", default: true) ? .automatic : .hidden) + .modifier(NativeUIScrollEdgeExtension()) } } diff --git a/tests/IosPagerTabBarTest.php b/tests/IosPagerTabBarTest.php index 05e3c52d..7289103a 100644 --- a/tests/IosPagerTabBarTest.php +++ b/tests/IosPagerTabBarTest.php @@ -1,18 +1,18 @@ toContain('let bottomInset = horizontal ? geo.safeAreaInsets.bottom : 0') - ->toContain('height: geo.size.height + bottomInset') - ->toContain('.ignoresSafeArea(.container, edges: horizontal ? .bottom : [])'); + ->toContain('EdgeInsets(top: 0, leading: geo.safeAreaInsets.leading, bottom: geo.safeAreaInsets.bottom, trailing: geo.safeAreaInsets.trailing)') + ->toContain('CGSize(width: geo.size.width + insets.leading + insets.trailing, height: geo.size.height + insets.bottom)') + ->toContain('.ignoresSafeArea(.container, edges: horizontal ? [.bottom, .horizontal] : [])'); }); -it('gives the bar inset back to the page content as safe area', function () { +it('gives the bar insets back to the page content as safe area', function () { $source = file_get_contents(dirname(__DIR__).'/resources/ios/NativeUIPagerRenderer.swift'); - expect($source)->toMatch('/\.safeAreaPadding\(\.bottom, bottomInset\)\s*\.frame\(width: size\.width, height: size\.height\)\s*\.clipped\(\)/'); + expect($source)->toMatch('/\.safeAreaPadding\(insets\)\s*\.frame\(width: size\.width, height: size\.height\)\s*\.clipped\(\)/'); }); it('pages a horizontal pager by its own width and clips its sides beside a sideways bar', function () { @@ -23,3 +23,14 @@ ->toContain('.clipShape(PagerSideClip(horizontal: horizontal))') ->toContain('.clipShape(PagerSideClip(horizontal: true))'); }); + +it('runs lists and scroll views under a bar at their sides and hands its inset back as safe area', function () { + $ios = dirname(__DIR__).'/resources/ios/'; + + expect(file_get_contents($ios.'NativeUIScrollViewRenderer.swift')) + ->toMatch('/\.safeAreaPadding\(\.leading, insets\.leading\)\s*\.safeAreaPadding\(\.trailing, insets\.trailing\)\s*\.ignoresSafeArea\(\.container, edges: \.horizontal\)/'); + + foreach (['NativeUIScrollViewRenderer.swift', 'NativeUIListRenderer.swift', 'NativeUIVirtualListRenderer.swift', 'NativeUIPagerRenderer.swift'] as $file) { + expect(file_get_contents($ios.$file))->toContain('.modifier(NativeUIScrollEdgeExtension())'); + } +});