feat(ios): native enhance page view

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-03-31 17:05:52 +08:00
parent 987d2611ce
commit b2cafedae8
9 changed files with 8148 additions and 187 deletions
+3
View File
@@ -0,0 +1,3 @@
shamefully-hoist=true
node-linker=hoisted
save-exact=true
+2 -1
View File
@@ -5,7 +5,7 @@
"main": "index.ts",
"scripts": {
"android": "expo run:android",
"dev": "expo start --dev-client",
"dev": "pnpm install --ignore-workspace && expo start --dev-client",
"ios": "expo run:ios",
"start": "expo start",
"web": "expo start --web"
@@ -15,6 +15,7 @@
"nativewind": "4.1.23",
"react": "18.3.1",
"react-native": "0.77.2",
"react-native-css-interop": "0.1.22",
"react-native-reanimated": "3.17.1",
"react-native-safe-area-context": "5.3.0"
},
File diff suppressed because it is too large Load Diff
+54 -5
View File
@@ -1,20 +1,59 @@
/* eslint-disable no-console */
import { requireNativeView } from "expo"
import { Text, View } from "react-native"
import { useRef } from "react"
import type { NativeSyntheticEvent, ViewProps } from "react-native"
import { Button, ScrollView, StyleSheet, Text, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
const EnhancePagerView = requireNativeView("EnhancePagerView")
const EnhancePagerView = requireNativeView<ViewProps & PagerProps>("EnhancePagerView")
const EnhancePageView = requireNativeView("EnhancePageView")
interface PagerProps {
onPageChange?: (e: NativeSyntheticEvent<{ index: number }>) => void
onScroll?: (e: NativeSyntheticEvent<{ percent: number; direction: "left" | "right" }>) => void
onScrollBegin?: () => void
onScrollEnd?: () => void
onPageWillAppear?: (e: NativeSyntheticEvent<{ index: number }>) => void
page?: number
pageGap?: number
transitionStyle?: "scroll" | "pageCurl"
}
interface PagerRef {
setPage: (index: number) => void
}
export const Pager = () => {
const insets = useSafeAreaInsets()
const pagerRef = useRef<PagerRef>(null)
return (
<View style={{ flex: 1, backgroundColor: "white", paddingTop: insets.top }}>
<EnhancePagerView
// @ts-expect-error
ref={pagerRef}
// pageGap={100}
// transitionStyle="pageCurl"
onPageChange={(e) => {
console.log(e.nativeEvent, "onPageChange")
}}
onScroll={(e) => {
console.log(e.nativeEvent, "onScroll")
}}
onScrollBegin={() => {
console.log("onScrollBegin")
}}
onScrollEnd={() => {
console.log("onScrollEnd")
}}
onPageWillAppear={(e) => {
console.log(e.nativeEvent, "onPageWillAppear")
}}
page={0}
style={{
flex: 1,
}}
>
<EnhancePageView style={{ flex: 1, backgroundColor: "white" }}>
<View>
<EnhancePageView style={{ ...StyleSheet.absoluteFillObject, backgroundColor: "white" }}>
<ScrollView style={{ flex: 1 }}>
<Text>
aaa Dignissimos repellendus voluptate. Beatae optio odit quod impedit sunt explicabo
laudantium. Assumenda aspernatur pariatur. Perspiciatis dolorum impedit impedit
@@ -28,7 +67,7 @@ export const Pager = () => {
veniam reiciendis. Adipisci impedit magni accusantium reprehenderit tempore hic sequi.
Rem saepe eos ut nobis consequuntur dolore autem labore.
</Text>
</View>
</ScrollView>
</EnhancePageView>
<EnhancePageView style={{ flex: 1, backgroundColor: "white" }}>
<View>
@@ -60,6 +99,16 @@ export const Pager = () => {
</View>
</EnhancePageView>
</EnhancePagerView>
<View
style={{
position: "absolute",
bottom: 30,
left: 0,
right: 0,
}}
>
<Button title="Set to End page" onPress={() => pagerRef.current?.setPage(2)} />
</View>
</View>
)
}
@@ -13,8 +13,6 @@ public class EnhancePageViewModule: Module {
View(EnhancePageView.self) {
}
}
}
@@ -8,177 +8,204 @@
import SnapKit
import UIKit
enum PagerDirection: String {
case left
case right
case none
}
private class PagerViewController: UIViewController {
private var pageIndex = 0
private var pageView: UIView? = nil
private var pageIndex = 0
private var pageView: UIView?
convenience init(index: Int, view: UIView) {
self.init()
self.pageIndex = index
self.pageView = view
}
convenience init(index: Int, view: UIView) {
self.init()
pageIndex = index
pageView = view
}
override func loadView() {
view = pageView
}
override func loadView() {
view = pageView
}
public func getPageIndex() -> Int { pageIndex }
public func setPageIndex(index: Int) { self.pageIndex = index }
public func getPageIndex() -> Int { pageIndex }
public func setPageIndex(index: Int) { pageIndex = index }
}
class EnhancePagerController: UIPageViewController, UIScrollViewDelegate {
private var pageControllers = [PagerViewController]()
private var currentPageIndex: Int = 0 {
willSet {
// debugPrint("set", newValue, currentPageIndex)
if newValue != currentPageIndex {
// notify
}
}
}
convenience init(pageViews: [UIView], initialPageIndex: Int = 0) {
self.init(transitionStyle: .scroll, navigationOrientation: .horizontal)
self.pageControllers = pageViews.enumerated().map { (index, view) in
PagerViewController(index: index, view: view)
}
currentPageIndex = initialPageIndex
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let hasPageController = pageControllers.indices.contains(currentPageIndex)
if hasPageController {
let vc = pageControllers[currentPageIndex]
self.setViewControllers([vc], direction: .forward, animated: false)
vc.didMove(toParent: self)
} else {
self.setViewControllers([UIViewController()], direction: .forward, animated: false)
}
self.view.subviews.forEach {
if let scrollView = $0 as? UIScrollView {
scrollView.delegate = self
}
}
}
var startOffset: CGFloat = 0
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffset = scrollView.contentOffset.x
debugPrint(scrollView.contentOffset.x)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
var direction = 0 //scroll stopped
if startOffset < scrollView.contentOffset.x {
direction = 1 //going right
} else if startOffset > scrollView.contentOffset.x {
direction = -1 //going left
private var pageControllers = [PagerViewController]()
private var currentPageIndex: Int = 0 {
willSet {
if newValue != currentPageIndex {
onPageIndexChange?(newValue)
}
}
}
let positionFromStartOfCurrentPage = abs(startOffset - scrollView.contentOffset.x)
let percent = positionFromStartOfCurrentPage / self.view.frame.width
// Events
var onPageIndexChange: ((Int) -> Void)?
var onScroll: ((CGFloat, PagerDirection) -> Void)?
var onScrollEnd: ((Int) -> Void)?
var onScrollStart: ((Int) -> Void)?
var onPageWillAppear: ((Int) -> Void)?
debugPrint(percent, direction)
}
convenience init(pageViews: [UIView], initialPageIndex: Int = 0,
transitionStyle: UIPageViewController.TransitionStyle = .scroll,
options: [UIPageViewController.OptionsKey: Any]? = nil
) {
self.init(transitionStyle: transitionStyle, navigationOrientation: .horizontal, options: options)
pageControllers = pageViews.enumerated().map { index, view in
PagerViewController(index: index, view: view)
}
currentPageIndex = initialPageIndex
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = self
delegate = self
let hasPageController = pageControllers.indices.contains(currentPageIndex)
if hasPageController {
let vc = pageControllers[currentPageIndex]
setViewControllers([vc], direction: .forward, animated: false)
vc.didMove(toParent: self)
} else {
setViewControllers([UIViewController()], direction: .forward, animated: false)
}
view.subviews.forEach {
if let scrollView = $0 as? UIScrollView {
scrollView.delegate = self
}
}
}
var startOffset: CGFloat = 0
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
startOffset = scrollView.contentOffset.x
debugPrint(scrollView.contentOffset.x)
onScrollStart?(currentPageIndex)
}
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
var direction: PagerDirection = .none
if startOffset < scrollView.contentOffset.x {
direction = .right
} else if startOffset > scrollView.contentOffset.x {
direction = .left
}
let positionFromStartOfCurrentPage = abs(startOffset - scrollView.contentOffset.x)
let percent = positionFromStartOfCurrentPage / view.frame.width
debugPrint(percent, direction)
onScroll?(percent, direction)
}
public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
onScrollEnd?(currentPageIndex)
}
}
// Add this extension to implement UIPageViewControllerDataSource
extension EnhancePagerController: UIPageViewControllerDataSource, UIPageViewControllerDelegate {
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
if let pagerController = pageViewController.viewControllers?.first as? PagerViewController {
let index = pagerController.getPageIndex()
if index > 0 {
return pageControllers[index - 1]
}
func pageViewController(
_ pageViewController: UIPageViewController,
viewControllerBefore viewController: UIViewController
) -> UIViewController? {
if let pagerController = pageViewController.viewControllers?.first as? PagerViewController {
let index = pagerController.getPageIndex()
if index > 0 {
onPageWillAppear?(index - 1)
return pageControllers[index - 1]
}
}
return nil
}
return nil
}
func pageViewController(
_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController
) -> UIViewController? {
if let pagerController = pageViewController.viewControllers?.first as? PagerViewController {
let index = pagerController.getPageIndex()
if index < pageControllers.count - 1 {
onPageWillAppear?(index + 1)
return pageControllers[index + 1]
}
}
func pageViewController(
_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController
) -> UIViewController? {
if let pagerController = pageViewController.viewControllers?.first as? PagerViewController {
let index = pagerController.getPageIndex()
if index < pageControllers.count - 1 {
return pageControllers[index + 1]
}
return nil
}
return nil
}
func pageViewController(
_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool
) {
if completed {
if let currentVC = pageViewController.viewControllers?.first as? PagerViewController,
let newIndex = pageControllers.firstIndex(of: currentVC)
{
currentPageIndex = newIndex
}
func pageViewController(
_ pageViewController: UIPageViewController,
didFinishAnimating finished: Bool,
previousViewControllers: [UIViewController],
transitionCompleted completed: Bool
) {
if completed {
if let currentVC = pageViewController.viewControllers?.first as? PagerViewController,
let newIndex = pageControllers.firstIndex(of: currentVC) {
currentPageIndex = newIndex
}
}
}
}
}
// MARK: Add this extension to implement insert and remove page view
extension EnhancePagerController {
public func insertPageView(view: UIView, animated: Bool = false) {
let index = pageControllers.count
let vc = PagerViewController(index: index, view: view)
public func insertPageView(view: UIView, animated: Bool = false) {
let index = pageControllers.count
let vc = PagerViewController(index: index, view: view)
let hasPageControllerBefore = pageControllers.count > 0
let hasPageControllerBefore = pageControllers.count > 0
pageControllers.append(vc)
debugPrint("inset \(index) \(pageControllers.count)")
pageControllers.append(vc)
debugPrint("inset \(index) \(pageControllers.count)")
if !hasPageControllerBefore {
self.setViewControllers([vc], direction: .forward, animated: animated)
}
}
public func removePageView(at index: Int) {
pageControllers.remove(at: index)
if currentPageIndex == index {
if !pageControllers.isEmpty {
let newIndex = min(index, pageControllers.count - 1)
let newVC = pageControllers[newIndex]
self.setViewControllers([newVC], direction: .forward, animated: true)
currentPageIndex = newIndex
} else {
let emptyVC = UIViewController()
self.setViewControllers([emptyVC], direction: .forward, animated: false)
currentPageIndex = 0
}
} else if currentPageIndex > index {
currentPageIndex -= 1
if !hasPageControllerBefore {
setViewControllers([vc], direction: .forward, animated: animated)
}
}
for (i, pagerVC) in pageControllers.enumerated() {
pagerVC.setPageIndex(index: i)
}
}
public func removePageView(at index: Int) {
pageControllers.remove(at: index)
if currentPageIndex == index {
if !pageControllers.isEmpty {
let newIndex = min(index, pageControllers.count - 1)
let newVC = pageControllers[newIndex]
setViewControllers([newVC], direction: .forward, animated: true)
currentPageIndex = newIndex
} else {
// let emptyVC = UIViewController()
// self.setViewControllers([emptyVC], direction: .forward, animated: false)
currentPageIndex = 0
}
} else if currentPageIndex > index {
currentPageIndex -= 1
}
for (i, pagerVC) in pageControllers.enumerated() {
pagerVC.setPageIndex(index: i)
}
}
}
// MARK: PagerController utils
extension EnhancePagerController {
public func setÇurrentPage(index: Int) {
if pageControllers.indices.contains(index) {
let vc = pageControllers[index]
setViewControllers([vc], direction: .forward, animated: true)
currentPageIndex = index
}
}
}
@@ -8,53 +8,128 @@
import ExpoModulesCore
public class EnhancePagerViewModule: Module {
public func definition() -> ModuleDefinition {
Name("EnhancePagerView")
public func definition() -> ModuleDefinition {
Name("EnhancePagerView")
View(EnhancePagerView.self) {
View(EnhancePagerView.self) {
OnViewDidUpdateProps { view in
view.initizlize()
}
Prop("page") { (view: EnhancePagerView, index: Int) in
view.page = index
}
Prop("pageGap") { (view: EnhancePagerView, gap: Int) in
view.pageGap = gap
}
Prop("transitionStyle") { (view: EnhancePagerView, style: TransitionStyle?) in
guard let style = style else { return }
view.transitionStyle = style
}
AsyncFunction("setPage") { (view: EnhancePagerView, index: Int) in
view.pageController?.setÇurrentPage(index: index)
}
Events("onPageChange")
Events("onScroll")
Events("onScrollBegin")
Events("onScrollEnd")
Events("onPageWillAppear")
}
}
}
}
class EnhancePagerProps {
@Field var initialPage: Int = 0
@Field var pageGap: CGFloat = 0
enum TransitionStyle: String, Enumerable {
case scroll
case pageCurl
func toUIPageViewControllerTransitionStyle() -> UIPageViewController.TransitionStyle {
switch self {
case .scroll:
return .scroll
case .pageCurl:
return .pageCurl
}
}
}
private class EnhancePagerView: ExpoView {
private var pageController: EnhancePagerController
required init(appContext: AppContext? = nil) {
pageController = EnhancePagerController(pageViews: [], initialPageIndex: 0)
fileprivate var pageController: EnhancePagerController?
super.init(appContext: appContext)
private let onScroll = EventDispatcher()
private let onScrollBegin = EventDispatcher()
private let onScrollEnd = EventDispatcher()
private let onPageChange = EventDispatcher()
private let onPageWillAppear = EventDispatcher()
addSubview(pageController.view)
pageController.view.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
private var pageViews: [UIView] = []
override func insertSubview(_ view: UIView, at index: Int) {
pageController.insertPageView(view: view, animated: false)
}
func willRemoveSubview(_ subview: UIView, at index: Int) {
pageController.removePageView(at: index)
}
#if RCT_NEW_ARCH_ENABLED
override func mountChildComponentView(_ childComponentView: UIView, index: Int) {
if childComponentView is EnhancePageView {
self.insertSubview(childComponentView, at: index)
}
required init(appContext: AppContext? = nil) {
super.init(appContext: appContext)
}
override func unmountChildComponentView(_ childComponentView: UIView, index: Int) {
if childComponentView is EnhancePageView {
self.willRemoveSubview(childComponentView, at: index)
}
override func insertSubview(_ view: UIView, at index: Int) {
pageViews.insert(view, at: index)
pageController?.insertPageView(view: view)
}
#endif
func willRemoveSubview(_ subview: UIView, at index: Int) {
pageViews.remove(at: index)
pageController?.removePageView(at: index)
}
// Props
var page: Int = 0 {
willSet {
pageController?.setÇurrentPage(index: newValue)
}
}
var pageGap = 20
var transitionStyle: TransitionStyle = .scroll
func initizlize() {
pageController = EnhancePagerController(pageViews: pageViews, initialPageIndex: page,
transitionStyle: transitionStyle.toUIPageViewControllerTransitionStyle(),
options: [
.interPageSpacing: pageGap,
])
guard let pageController = pageController else { return }
addSubview(pageController.view)
pageController.view.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
pageController.onPageIndexChange = { [weak self] index in
self?.onPageChange(["index": index])
}
pageController.onScrollStart = { [weak self] index in
self?.onScrollBegin(["index": index])
}
pageController.onScroll = { [weak self] percent, direction in
self?.onScroll(["percent": percent, "direction": direction.rawValue])
}
pageController.onScrollEnd = { [weak self] index in
self?.onScrollEnd(["index": index])
}
pageController.onPageWillAppear = { [weak self] index in
self?.onPageWillAppear(["index": index])
}
}
#if RCT_NEW_ARCH_ENABLED
override func mountChildComponentView(_ childComponentView: UIView, index: Int) {
if childComponentView is EnhancePageView {
insertSubview(childComponentView, at: index)
}
}
override func unmountChildComponentView(_ childComponentView: UIView, index: Int) {
if childComponentView is EnhancePageView {
willRemoveSubview(childComponentView, at: index)
}
}
#endif
}
-2
View File
@@ -1084,8 +1084,6 @@ importers:
specifier: 8.5.3
version: 8.5.3
apps/mobile/native: {}
apps/mobile/web-app: {}
apps/ssr:
+2 -2
View File
@@ -3,10 +3,10 @@ packages:
- packages/*
- apps/desktop/*
- apps/desktop/src/*
- apps/mobile/native
- "!apps/mobile/native/example"
- apps/mobile/web-app
- "!**/example"
- "!**/example/*"
- "!**/example/**"
onlyBuiltDependencies:
- "@firebase/util"
- "@sentry/cli"