refactor: follow native example and int native pager view

Signed-off-by: Innei <tukon479@gmail.com>
This commit is contained in:
Innei
2025-03-31 00:49:58 +08:00
parent 2881d655ee
commit a6d264de85
21 changed files with 467 additions and 2577 deletions
-1
View File
@@ -1 +0,0 @@
node-linker=hoisted
-13
View File
@@ -1,13 +0,0 @@
import { ScrollView, View } from "react-native"
import { SharedWebView } from "@/src/components/native/webview"
export default function App() {
return (
<ScrollView>
<SharedWebView url="https://innei.in" />
<View style={{ height: 1000, backgroundColor: "red" }} />
</ScrollView>
)
}
+27
View File
@@ -0,0 +1,27 @@
import type { ConfigContext, ExpoConfig } from "expo/config"
import PKG from "./package.json"
// const iconPath = resolve(__dirname, "./assets/icon.png")
export default ({ config }: ConfigContext): ExpoConfig => ({
...config,
owner: "follow",
name: "Folo Native Kit Demo",
slug: "follow-native-kit-demo",
version: PKG.version,
orientation: "portrait",
// icon: iconPath,
scheme: "follow-native-kit-demo",
userInterfaceStyle: "automatic",
newArchEnabled: true,
ios: {
supportsTablet: false,
bundleIdentifier: "is.follow.native-kit-demo",
},
android: {
package: "is.follow.nativekitdemo",
},
})
-30
View File
@@ -1,30 +0,0 @@
{
"expo": {
"name": "follow-native-example",
"slug": "follow-native-example",
"version": "1.0.0",
"orientation": "portrait",
"icon": "./assets/icon.png",
"userInterfaceStyle": "light",
"newArchEnabled": true,
"splash": {
"image": "./assets/splash-icon.png",
"resizeMode": "contain",
"backgroundColor": "#ffffff"
},
"ios": {
"supportsTablet": true,
"bundleIdentifier": "expo.modules.follownative.example"
},
"android": {
"adaptiveIcon": {
"foregroundImage": "./assets/adaptive-icon.png",
"backgroundColor": "#ffffff"
},
"package": "expo.modules.follownative.example"
},
"web": {
"favicon": "./assets/favicon.png"
}
}
}
+2 -1
View File
@@ -1,6 +1,7 @@
module.exports = function (api) {
api.cache(true)
return {
presets: ["babel-preset-expo"],
presets: [["babel-preset-expo", { jsxImportSource: "nativewind" }], "nativewind/babel"],
plugins: ["react-native-reanimated/plugin"],
}
}
+3
View File
@@ -0,0 +1,3 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
+3 -1
View File
@@ -1,6 +1,8 @@
import "./global.css"
import { registerRootComponent } from "expo"
import App from "./App"
import App from "./src/App"
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
// It also ensures that whether you load the app in Expo Go or in a native build,
+8 -23
View File
@@ -1,28 +1,9 @@
// Learn more https://docs.expo.io/guides/customizing-metro
const { getDefaultConfig } = require("expo/metro-config")
const { withNativeWind } = require("nativewind/metro")
const path = require("node:path")
const { wrapWithReanimatedMetroConfig } = require("react-native-reanimated/metro-config")
const config = getDefaultConfig(__dirname)
// npm v7+ will install ../node_modules/react and ../node_modules/react-native because of peerDependencies.
// To prevent the incompatible react-native between ./node_modules/react-native and ../node_modules/react-native,
// excludes the one from the parent folder when bundling.
config.resolver.blockList = [
...Array.from(config.resolver.blockList ?? []),
new RegExp(path.resolve("..", "node_modules", "react")),
new RegExp(path.resolve("..", "node_modules", "react-native")),
]
config.resolver.nodeModulesPaths = [
path.resolve(__dirname, "./node_modules"),
path.resolve(__dirname, "../node_modules"),
]
config.resolver.extraNodeModules = {
"follow-native": "..",
}
config.watchFolders = [path.resolve(__dirname, "..")]
const config = getDefaultConfig(__dirname, { isCSSEnabled: true })
config.transformer.getTransformOptions = async () => ({
transform: {
@@ -31,4 +12,8 @@ config.transformer.getTransformOptions = async () => ({
},
})
module.exports = config
config.resolver.nodeModulesPaths = [path.resolve(__dirname, "./node_modules")]
config.watchFolders = [path.resolve(__dirname, "./node_modules"), path.resolve(__dirname, "./src")]
module.exports = wrapWithReanimatedMetroConfig(withNativeWind(config, { input: "./global.css" }))
+3
View File
@@ -0,0 +1,3 @@
/// <reference types="nativewind/types" />
// NOTE: This file should not be edited and should be committed with your source code. It is generated by NativeWind.
+7 -3
View File
@@ -5,14 +5,18 @@
"main": "index.ts",
"scripts": {
"android": "expo run:android",
"dev": "expo start --dev-client",
"ios": "expo run:ios",
"start": "expo start",
"web": "expo start --web"
},
"peerDependencies": {
"expo": "52.0.35",
"dependencies": {
"expo": "52.0.41",
"nativewind": "4.1.23",
"react": "18.3.1",
"react-native": "0.77.1"
"react-native": "0.77.2",
"react-native-reanimated": "3.17.1",
"react-native-safe-area-context": "5.3.0"
},
"expo": {
"autolinking": {
+11
View File
@@ -0,0 +1,11 @@
import { SafeAreaProvider } from "react-native-safe-area-context"
import { Pager } from "./demo/Pager"
export default function App() {
return (
<SafeAreaProvider>
<Pager />
</SafeAreaProvider>
)
}
@@ -0,0 +1,65 @@
import { requireNativeView } from "expo"
import { Text, View } from "react-native"
import { useSafeAreaInsets } from "react-native-safe-area-context"
const EnhancePagerView = requireNativeView("EnhancePagerView")
const EnhancePageView = requireNativeView("EnhancePageView")
export const Pager = () => {
const insets = useSafeAreaInsets()
return (
<View style={{ flex: 1, backgroundColor: "white", paddingTop: insets.top }}>
<EnhancePagerView
style={{
flex: 1,
}}
>
<EnhancePageView style={{ flex: 1, backgroundColor: "white" }}>
<View>
<Text>
aaa Dignissimos repellendus voluptate. Beatae optio odit quod impedit sunt explicabo
laudantium. Assumenda aspernatur pariatur. Perspiciatis dolorum impedit impedit
explicabaaaaaao iste iusto ullam commodi fuga. Omnis iure minima eveniet ea fugiat.
Reiciendis cupiditate rem natus non quo ut. Sint dolorum porro delectus omnis earum
vitae perspiciatis consequatur occaecati. Nesciunt nesciunt inventore porro architecto
neque aspernatur ullam delectus. Animi dolorem voluptatum nemo. Veniam ea sit
architecto dicta. Suscipit repellat quidem omnis. Rerum quam rem repellendus non quia
veniam numquam perferendis. Accusamus mollitia eos illo nam. Doloribus voluptatum amet
architecto veniam nobis recusandae. Placeat minima sed vel aspernatur maxime ipsa hic
veniam reiciendis. Adipisci impedit magni accusantium reprehenderit tempore hic sequi.
Rem saepe eos ut nobis consequuntur dolore autem labore.
</Text>
</View>
</EnhancePageView>
<EnhancePageView style={{ flex: 1, backgroundColor: "white" }}>
<View>
<Text>
deleniti expedita. Dolore odit ad consequatur quasi quas labore ipsum. Ipsam impedit
harum quidem. Odio quas voluptatibus nihil. Aliquid eligendi dolorem tempora vel quae
dolores deleniti optio suscipit. Quo ducimus nobis esse architecto. Vel dolorem fuga
natus. Aperiam non non nostrum illum unde. Neque quam dolore molestias quidem culpa
praesentium magni minus debitis. Ab molestiae ab accusantium optio quisquam. Rem
accusantium veniam quasi rerum sit voluptatum commodi perspiciatis quas. Tempore neque
ducimus porro debitis repellat porro nam fugiat iure. Quidem earum pariatur. Unde
optio nisi alias hic distinctio quia magnam fuga. Aspernatur incidunt unde enim
eligendi ipsum dolores voluptas atque. Quaerat earum saepe iure doloremque.
</Text>
</View>
</EnhancePageView>
<EnhancePageView style={{ flex: 1, backgroundColor: "white" }}>
<View>
<Text>
Perferendis amet vitae dolore laborum. In veritatis odio iure. Fugiat facilis
voluptatibus magni consectetur distinctio. Voluptate incidunt hic porro atque.
Sapiente similique hic ratione dolorum quasi quasi. Quaerat esse sed quibusdam
distinctio. Accusantium et consequatur enim quos vero tempore. Sed quia maxime quaerat
eos tempore quod veniam. Id repellendus dolorem molestias facere earum. Odit eaque
esse nostrum quod. Quo ad magnam adipisci. Dolores fugiat perferendis doloremque
accusantium saepe eligendi alias doloribus suscipit. Praesentium similique repudiandae
blanditiis reprehenderit dolorum quas.
</Text>
</View>
</EnhancePageView>
</EnhancePagerView>
</View>
)
}
@@ -0,0 +1,20 @@
/** @type {import('tailwindcss').Config} */
import { withUIKit } from "react-native-uikit-colors/tailwind"
export default withUIKit({
darkMode: "class",
content: ["./src/**/*.{js,jsx,ts,tsx}", "./App.tsx"],
presets: [require("nativewind/preset")],
plugins: [require("@tailwindcss/typography")],
theme: {
extend: {
fontFamily: {
mono: "monospace",
},
colors: {
accent: "#FF5C00",
},
},
},
})
+3 -5
View File
@@ -2,9 +2,7 @@
"extends": "expo/tsconfig.base",
"compilerOptions": {
"strict": true,
"paths": {
"follow-native": ["../src/index"],
"follow-native/*": ["../src/*"]
}
}
"paths": {}
},
"include": ["**/*.ts", "**/*.tsx", "nativewind-env.d.ts", "src/App.tsx"]
}
@@ -1,20 +0,0 @@
const createConfigAsync = require("@expo/webpack-config")
const path = require("node:path")
module.exports = async (env, argv) => {
const config = await createConfigAsync(
{
...env,
babel: {
dangerouslyAddModulePathsToTranspile: ["follow-native"],
},
},
argv,
)
config.resolve.modules = [
path.resolve(__dirname, "./node_modules"),
path.resolve(__dirname, "../node_modules"),
]
return config
}
+3 -1
View File
@@ -11,7 +11,9 @@
"TabBarModule",
"TabScreenModule",
"TabBarPortalModule",
"ProfileViewModule"
"ProfileViewModule",
"EnhancePagerViewModule",
"EnhancePageViewModule"
]
},
"android": {
@@ -0,0 +1,24 @@
//
// EnhancePageViewModule.swift
// FollowNative
//
// Created by Innei on 2025/3/31.
//
import ExpoModulesCore
public class EnhancePageViewModule: Module {
public func definition() -> ModuleDefinition {
Name("EnhancePageView")
View(EnhancePageView.self) {
}
}
}
class EnhancePageView: ExpoView {
}
@@ -0,0 +1,184 @@
//
// PagerView.swift
// FollowNative
//
// Created by Innei on 2025/3/30.
//
import SnapKit
import UIKit
private class PagerViewController: UIViewController {
private var pageIndex = 0
private var pageView: UIView? = nil
convenience init(index: Int, view: UIView) {
self.init()
self.pageIndex = index
self.pageView = view
}
override func loadView() {
view = pageView
}
public func getPageIndex() -> Int { pageIndex }
public func setPageIndex(index: Int) { self.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
}
let positionFromStartOfCurrentPage = abs(startOffset - scrollView.contentOffset.x)
let percent = positionFromStartOfCurrentPage / self.view.frame.width
debugPrint(percent, direction)
}
}
// 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]
}
}
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 {
return pageControllers[index + 1]
}
}
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
}
}
}
}
// 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)
let hasPageControllerBefore = pageControllers.count > 0
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
}
for (i, pagerVC) in pageControllers.enumerated() {
pagerVC.setPageIndex(index: i)
}
}
}
@@ -0,0 +1,60 @@
//
// EnhancePagerModule.swift
// FollowNative
//
// Created by Innei on 2025/3/30.
//
import ExpoModulesCore
public class EnhancePagerViewModule: Module {
public func definition() -> ModuleDefinition {
Name("EnhancePagerView")
View(EnhancePagerView.self) {
}
}
}
class EnhancePagerProps {
@Field var initialPage: Int = 0
@Field var pageGap: CGFloat = 0
}
private class EnhancePagerView: ExpoView {
private var pageController: EnhancePagerController
required init(appContext: AppContext? = nil) {
pageController = EnhancePagerController(pageViews: [], initialPageIndex: 0)
super.init(appContext: appContext)
addSubview(pageController.view)
pageController.view.snp.makeConstraints { make in
make.edges.equalToSuperview()
}
}
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)
}
}
override func unmountChildComponentView(_ childComponentView: UIView, index: Int) {
if childComponentView is EnhancePageView {
self.willRemoveSubview(childComponentView, at: index)
}
}
#endif
}
+1 -17
View File
@@ -14,24 +14,8 @@
"follow-native",
"FollowNative"
],
"main": "build/index.js",
"types": "build/index.d.ts",
"scripts": {
"//prepare": "expo-module prepare",
"build": "expo-module build",
"clean": "expo-module clean",
"expo-module": "expo-module",
"lint": "expo-module lint",
"open:android": "open -a \"Android Studio\" example/android",
"open:ios": "xed example/ios",
"prepublishOnly": "expo-module prepublishOnly"
},
"peerDependencies": {
"expo": "52.0.35",
"react": "18.3.1",
"react-native": "0.77.1"
},
"devDependencies": {
"expo-module-scripts": "4.0.4"
"open:ios": "xed example/ios"
}
}
+43 -2462
View File
File diff suppressed because it is too large Load Diff