Commit 629a1bcf authored by huanglu's avatar huanglu

feat: update template

parent 2a9fc215
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
const App: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Header />
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>Engine: Hermes</Text>
</View>
)}
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Step One</Text>
<Text style={styles.sectionDescription}>
Edit <Text style={styles.highlight}>App.js</Text> to change this
screen and then come back to see your edits.
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>See Your Changes</Text>
<Text style={styles.sectionDescription}>
<ReloadInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Debug</Text>
<Text style={styles.sectionDescription}>
<DebugInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Learn More</Text>
<Text style={styles.sectionDescription}>
Read the docs to discover what to do next:
</Text>
</View>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
{
"name": "template",
"displayName": "template"
"name": "HH",
"displayName": "HH"
}
\ No newline at end of file
......@@ -5,5 +5,5 @@
import {AppRegistry} from 'react-native';
import App from './src/App';
import {name as appName} from './app.json';
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App);
{
"name": "rnrn",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@react-native-community/art": "^1.1.2",
"@react-native-community/async-storage": "^1.12.0",
"@react-native-community/masked-view": "^0.1.10",
"@react-native-community/viewpager": "^3.3.0",
"axios": "^0.20.0",
"easy-peasy": "3.1.0",
"geekbase": "^3.0.2",
"prop-types": "^15.7.2",
"react": "16.13.1",
"react-native": "0.63.3",
"react-native-code-push": "^6.3.0",
"react-native-extra-dimensions-android": "^1.2.5",
"react-native-fast-image": "^8.3.2",
"react-native-gesture-handler": "^1.8.0",
"react-native-modal": "^11.5.6",
"react-native-reanimated": "^1.13.0",
"react-native-refresh-list-view": "^1.0.12",
"react-native-root-siblings": "^4.0.6",
"react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1",
"react-native-scrollable-tab-view": "^1.0.0",
"react-native-version-number": "^0.3.6",
"react-navigation": "^4.4.0",
"react-navigation-stack": "^2.8.2",
"react-navigation-tabs": "^2.9.0",
"react-redux": "^7.2.1",
"rn-fetch-blob": "https://dev.jiuaoedu.com/sunzheng/rn-fetch-blob.git"
},
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/runtime": "^7.11.2",
"@react-native-community/eslint-config": "^2.0.0",
"@types/jest": "^26.0.14",
"@types/react": "^16.9.51",
"@types/react-native": "^0.63.25",
"@types/react-test-renderer": "^16.9.3",
"babel-jest": "^26.5.2",
"babel-plugin-root-import": "^6.5.0",
"eslint": "^7.10.0",
"jest": "^26.5.2",
"metro-react-native-babel-preset": "^0.63.0",
"react-test-renderer": "16.11.0",
"typescript": "^4.0.3"
},
"jest": {
"preset": "react-native"
}
"name": "rnrn",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"@react-native-community/art": "^1.1.2",
"@react-native-community/async-storage": "^1.12.0",
"@react-native-community/masked-view": "^0.1.10",
"@react-native-community/viewpager": "^3.3.0",
"axios": "^0.20.0",
"easy-peasy": "3.1.0",
"geekbase": "^3.0.2",
"prop-types": "^15.7.2",
"react": "16.13.1",
"react-native": "0.63.3",
"react-native-code-push": "^6.3.0",
"react-native-device-info": "^6.2.0",
"react-native-extra-dimensions-android": "^1.2.5",
"react-native-fast-image": "^8.3.2",
"react-native-fs": "^2.16.6",
"react-native-gesture-handler": "^1.8.0",
"react-native-modal": "^11.5.6",
"react-native-player": "https://dev.jiuaoedu.com/sunzheng/react-native-geek-player.git#v2.0.4",
"react-native-reanimated": "^1.13.0",
"react-native-refresh-list-view": "^1.0.12",
"react-native-root-siblings": "^4.0.6",
"react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1",
"react-native-scrollable-tab-view": "^1.0.0",
"react-native-tbswebview": "https://dev.jiuaoedu.com/sunzheng/react-native-tbswebview.git#v1.1.0",
"react-native-version-number": "^0.3.6",
"react-native-webview": "^10.9.2",
"react-native-weixin": "https://dev.jiuaoedu.com/sunzheng/react-native-weixin.git",
"react-navigation": "^4.4.0",
"react-navigation-stack": "^2.8.2",
"react-navigation-tabs": "^2.9.0",
"react-redux": "^7.2.1",
"rn-fetch-blob": "https://dev.jiuaoedu.com/sunzheng/rn-fetch-blob.git"
},
"devDependencies": {
"@babel/core": "^7.11.6",
"@babel/runtime": "^7.11.2",
"@react-native-community/eslint-config": "^2.0.0",
"@types/jest": "^26.0.14",
"@types/react": "^16.9.51",
"@types/react-native": "^0.63.25",
"@types/react-test-renderer": "^16.9.3",
"babel-jest": "^26.5.2",
"babel-plugin-root-import": "^6.5.0",
"eslint": "^7.10.0",
"jest": "^26.5.2",
"metro-react-native-babel-preset": "^0.63.0",
"react-test-renderer": "16.11.0",
"typescript": "^4.0.3"
},
"jest": {
"preset": "react-native"
},
"author": {
"name": "sss"
},
"description": "sss"
}
const fs = require('fs')
const path = require('path')
const CODE_PUSH_ENDPOINT = 'https://hot.jkwljy.com'
function replaceFile (relativePath) {
const realPath = path.resolve(__dirname, ...relativePath.split('/'))
fs.writeFileSync(
realPath,
fs.readFileSync(realPath, { encoding: 'utf-8' })
// .replace(/BuildConfig\.DEBUG\)/, `BuildConfig.DEBUG, \\"${CODE_PUSH_ENDPOINT}\\")`)
.replace(/(BuildConfig\.DEBUG, \\\"http\:\/\/119\.27\.181\.101\:3000\\\"\))|(BuildConfig\.DEBUG\))/, `BuildConfig.DEBUG, \\"${CODE_PUSH_ENDPOINT}\\")`)
)
}
replaceFile('node_modules/react-native-code-push/package.json')
replaceFile('node_modules/react-native-code-push/react-native.config.js')
\ No newline at end of file
......@@ -22,7 +22,6 @@ export default function App() {
const handleAppStateChange = (appState: AppStateStatus) => {
console.log('当前app状态', appState)
if (appState === 'background') {
// Toast.hideLoading()
}
}
......
const colors = {
pageBgColor: '#f5f5f5',
warmHighLightColor: '#F1551E',
coldHighLightColor: '#027AFF',
blackTextColor: '#484C4F',
grayTextColor: 'gray',
commonBorderColor: '#E1E1E1'
}
export default colors
\ No newline at end of file
/* eslint-disable react/prop-types */
import React, { useEffect, useState, useImperativeHandle, useRef } from "react";
import { View } from "react-native";
import WebView from "react-native-webview";
import { X5WebView } from "react-native-tbswebview";
import { device } from "geekbase";
/**
* 极客webview
* @param useToken 是否要传递token到H5
* @param onMessage H5页面交互数据
* @param onShare H5调用原生分享
* @param onTitle H5将title传递到页面
*/
export const GeekWebView = React.forwardRef((props, ref) => {
const {
uri,
style,
useToken,
onMessage,
onShare,
onShareTimeline,
onTitle,
renderLoading,
onPlayVideo,
onLog
} = props;
const [url, setUrl] = useState(uri);
const webViewRef = useRef(null);
const webviewCanGoBack = React.createRef(false);
const [loading, setLoading] = useState(false);
const handleMessage = (event) => {
const data =
device.os === "ios" ? JSON.parse(event.nativeEvent.data) : JSON.parse(event.data);
if (data.type === "share") {
onShare && onShare(data.data);
return;
}
if (data.type === "shareTimeline") {
onShareTimeline && onShareTimeline(data.data);
return;
}
if (data.type === "title") {
onTitle && onTitle(data.data);
return;
}
if (data.type === 'video') {
console.log('play', data)
onPlayVideo && onPlayVideo(data.data)
}
if (data.type === 'log') {
onLog && onLog(data.data)
}
onMessage(data);
};
useEffect(
function () {
setUrl(uri);
},
[uri, useToken]
);
const excuteJSMethod = ({ method = "", data = "" }) => {
const params = JSON.stringify({ method, data });
if (webViewRef.current) {
webViewRef.current.injectJavaScript(`window.$geek_excuteJS('${params}')`);
}
};
const goBack = () => {
if (webViewRef.current) {
webViewRef.current.goBack();
}
};
const goForward = () => {
if (webViewRef.current) {
webViewRef.current.goForward();
}
};
const reload = () => {
if (webViewRef.current) {
webViewRef.current.reload();
}
};
const canGoBack = () => {
return webviewCanGoBack.current;
};
useImperativeHandle(ref, () => ({
excuteJSMethod,
goBack,
goForward,
reload,
canGoBack,
}));
return (
<View style={{ flex: 1, width: "100%", backgroundColor: "red", ...style }}>
{device.os === "ios" && (
<WebView
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
ref={webViewRef}
mixedContentMode="always"
style={{ flex: 1 }}
source={{ uri: url }}
onMessage={handleMessage}
originWhitelist={["*"]}
useWebKit={true}
startInLoadingState={true}
renderLoading={renderLoading}
onLoadEnd={(event) => {
// eslint-disable-next-line no-shadow
const canGoBack = event.nativeEvent.canGoBack;
webviewCanGoBack.current = canGoBack;
}}
/>
)}
{device.os === "android" && (
<>
<X5WebView
ref={webViewRef}
url={url}
onProgressChanged={(data) => {}}
onLoadingFinish={(data) => {
const nativeData = JSON.parse(data);
// eslint-disable-next-line no-shadow
const canGoBack = nativeData.canGoBack;
webviewCanGoBack.current = canGoBack;
setLoading(false);
}}
onLoadingStart={(data) => {
setLoading(true);
}}
style={{ flex: 1 }}
onMessage={(data) => {
console.log('onMessage : ', data)
const nativeData = JSON.parse(data);
handleMessage(nativeData);
}}
/>
{loading && renderLoading && renderLoading()}
</>
)}
</View>
);
});
import {useEffect, useState, useLayoutEffect} from 'react';
import {NavigationStackProp} from 'react-navigation-stack';
import {StatusBar} from 'react-native';
import {device} from 'geekbase';
import {StackNavigationOptions} from 'react-navigation-stack/lib/typescript/src/vendor/types';
import {navigationOptions} from '@/router/constant';
import { createTypedHooks } from 'easy-peasy';
import StoreModels from '@/models'
// 路由进入时hook
export const useStackFocus = (
navigation: NavigationStackProp<{name: string}>,
cb: Function,
) => {
function handleFocus() {
cb && cb;
}
useEffect(() => {
const listener = navigation.addListener('willFocus', handleFocus);
return () => {
listener.remove();
};
}, []);
};
// 路由离开时的hook
export const useStackBlur = (
navigation: NavigationStackProp<any>,
cb: Function,
) => {
function handleBlur() {
cb && cb;
}
useEffect(() => {
const listener = navigation.addListener('willBlur', handleBlur);
return () => {
listener.remove();
};
}, []);
};
export function useFocusBlur(navigation: NavigationStackProp) {
const [isFocus, setIsFocus] = useState(false);
const [isBlur, setIsBlur] = useState(false);
// 第二个参数如果为undefined,则代表什么都依赖【componentDidMount + componentDidUpdate】
// 第二个参数如果为[],代表什么都不依赖【componentDidMount】
// 第二个参数如果为[status],代表依赖status,status变化才会触发useLayoutEffect 、useEffect
// DOM变更后,内核渲染前触发,其会同步触发渲染(阻塞,故只有在useEffect出问题时再用它)
// 此处监听页面的didFocus和didBlur,发现useEffect会出问题(switchNavigator切换时无法触发),故选用useLayoutEffect
useLayoutEffect(() => {
console.log('useFocusBlur', 'isFocus');
const focusListener = navigation.addListener('didFocus', (payload) => {
setIsFocus(true);
setIsBlur(false);
});
const blurListener = navigation.addListener('didBlur', (payload) => {
setIsFocus(false);
setIsBlur(true);
});
type ConfigType<P = {}, > = (config: {navigation: NavigationStackProp<{}, P>}) => StackNavigationOptions
return () => {
// didUnmount
focusListener && focusListener.remove();
blurListener && blurListener.remove();
};
}, []);
return {isFocus, isBlur};
}
export function useStatusBar(isFocus: boolean, show = true, color = 'black') {
useEffect(() => {
if (!isFocus) {
return;
}
if (!show) {
// 不显示状态栏
StatusBar.setHidden(true, 'none');
return;
}
StatusBar.setHidden(false, 'none');
if (device.os === 'android') {
StatusBar.setTranslucent(true);
StatusBar.setBackgroundColor('transparent');
}
switch (color) {
case 'black':
StatusBar.setBarStyle('dark-content');
break;
case 'white':
StatusBar.setBarStyle('light-content');
break;
default:
StatusBar.setBarStyle('dark-content');
}
}, [isFocus]);
}
export const withStackScreen = (
export const withStackScreen = <P = {}>(
Wrapp: React.ReactNode,
config: StackNavigationOptions,
config: StackNavigationOptions | ConfigType<P>,
) => {
(Wrapp as any).navigationOptions = {
(Wrapp as any).navigationOptions = typeof config === 'function' ? (args: any) => {
return {
...navigationOptions,
...(config(args) || {})
}
} : {
...navigationOptions,
...config,
};
......
......@@ -2,16 +2,15 @@ import { navigationService, getAppConfig } from 'geekbase'
import cache from '@/cache'
export default {
/**
* 去webview页面
* @param {uri, useToken, initTitle, onMessage } props
*/
navigateGeekWebViewPage(props: {
uri: string,
useToken: boolean,
initTitle: string,
onMessage: Function
useToken?: boolean,
initTitle?: string,
onMessage?: Function
}) {
const { uri, useToken, ...others } = props
let url = uri
......@@ -26,13 +25,13 @@ export default {
} else {
url = `${url}?token=${token}`;
}
navigationService.navigate('GeekWebViewPage', {
navigationService.navigate('webview', {
uri: /^https?:\/\//g.test(url) ? url : `${getAppConfig().baseUrl}${url}`,
...others
})
});
} else {
navigationService.navigate('GeekWebViewPage', {
navigationService.navigate('webview', {
uri: /^https?:\/\//g.test(url) ? url : `${getAppConfig().baseUrl}${url}`,
...others
})
......
import React, { useCallback, useEffect } from 'react'
import { View, ImageBackground, StyleSheet, Text } from "react-native";
import React, { useCallback, useEffect, useState } from 'react'
import { View, ImageBackground, StyleSheet, Text, Alert } from "react-native";
import { TouchableHighlight } from 'react-native-gesture-handler';
import { useStatusBar, withStackScreen } from '@/hooks';
import { withStackScreen } from '@/hooks';
import { SafeAreaView } from 'react-native-safe-area-context';
import { bgImg } from './assets';
import { rpx } from 'geekbase';
import { fileUtil, rpx, useFocusBlur, useStatusBar } from 'geekbase';
import navigate from '@/navigate';
const Home = (props: any) => {
useStatusBar(true, true, 'white')
const file = 'http://1257124244.vod2.myqcloud.com/c9be83a2vodcq1257124244/d9bd8ff25285890808419280862/1Ky6n7tAgF0A.mp4'
const { isFocus } = useFocusBlur(props.navigation)
useStatusBar(isFocus, true, 'white')
const [progress, setProgress] = useState('')
const [filePath, setFilePath] = useState('')
useEffect(() => {
console.log('bg: ', bgImg)
}, [])
const handleClickItem = useCallback((type: string) => {
switch (type) {
case '1':
navigate.navigateGeekWebViewPage({ uri: 'https://www.taobao.com', initTitle: 'tabobao' })
break;
case '2':
fileUtil.openFile(file)
break;
case '3':
fileUtil.fileExist(file).then(res => {
if (res) {
Alert.alert('文件存在')
setProgress('100')
} else {
fileUtil.downloadFile({ url: file }, (fprogress) => {
setProgress((fprogress.current / fprogress.total * 100).toFixed(2))
}).then(fs => {
console.log('===: ', fs)
});
}
})
break
case '4':
const path = fileUtil.dstFilePath(file)
setFilePath(path)
break
case '5':
fileUtil.unlinkFile(file).then(() => {
Alert.alert('删除成功')
})
break
case '6':
fileUtil.fileExist(file).then(res => {
Alert.alert(res ? '文件存在' : '文件不存在')
})
break
default:
break;
}
}, [])
return (
<ImageBackground source={bgImg} style={styles.bgStyle}>
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.functionalArea}>
<Text style={{ textAlign: 'center', width: '100%' }}>文件下载进度:{progress}%</Text>
<Text style={{ textAlign: 'center', width: '100%' }}>文件路径:{filePath}</Text>
<View style={{ marginTop: rpx(500) }}>
<View style={styles.functionalArea}>
<TouchableHighlight onPress={() => {
handleClickItem('1')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>作业批阅</Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={() => {
handleClickItem('2')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>预览文件</Text>
</View>
</TouchableHighlight>
</View>
<View style={styles.functionalArea}>
<TouchableHighlight onPress={() => {
handleClickItem('3')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>下载文件: http://1257124244.vod2.myqcloud.com/c9be83a2vodcq1257124244/d9bd8ff25285890808419280862/1Ky6n7tAgF0A.mp4</Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={() => {
handleClickItem('1')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>作业批阅</Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={() => {
handleClickItem('4')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>查看文件路径</Text>
</View>
</TouchableHighlight>
</View>
<View style={styles.functionalArea}>
<TouchableHighlight onPress={() => {
handleClickItem('5')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>删除文件</Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={() => {
handleClickItem('2')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>其他功能</Text>
</View>
</TouchableHighlight>
<TouchableHighlight onPress={() => {
handleClickItem('6')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>查看文件是否存在</Text>
</View>
</TouchableHighlight>
</View>
</View>
</SafeAreaView>
</ImageBackground>
......@@ -48,9 +124,9 @@ const styles = StyleSheet.create({
flex: 1
},
functionalArea: {
marginTop: rpx(500),
flexDirection: 'row',
justifyContent: 'space-around',
margin: rpx(10)
},
funItem: {
width: rpx(300),
......@@ -65,7 +141,7 @@ const styles = StyleSheet.create({
flex: 1
},
fucText: {
color: 'white', fontSize: rpx(30), fontWeight: 'bold'
color: 'white', fontSize: rpx(20), fontWeight: 'bold'
}
})
......
/* eslint-disable react/prop-types */
import React, { useEffect, useRef, useState } from "react";
import React, { useEffect, useRef } from "react";
import {
View,
StyleSheet,
......@@ -8,29 +8,40 @@ import {
Image,
ActivityIndicator,
} from "react-native";
import { device, rpx } from "geekbase";
import { useFocusBlur, useStatusBar, navigationOptions } from "@/appbase";
import { colors } from "@/assets";
import { device, rpx, GeekWebView, useStatusBar, navigationService, GeekWebViewComponent, useFocusBlur } from "geekbase";
import { back } from "./assets";
import { GeekWebView } from "@/components";
import colors from '@/assets/colors'
import { shareByWeb } from "@/utils";
import * as utils from '@/utils'
import { withStackScreen } from "@/hooks";
import { NavigationStackProp } from "react-navigation-stack";
function GeekWebViewPage(props) {
const uri = props.navigation.getParam("uri");
type WebViewPagePramasType = {
uri: string,
onMessage?: (msg: any) => void,
initTitle?: string,
title?: string,
onBack?: () => void
onClose?: () => void
}
function GeekWebViewPage(props: {
navigation: NavigationStackProp<{}, WebViewPagePramasType>
}) {
const uri = props.navigation.getParam('uri')
const onMessage = props.navigation.getParam("onMessage");
const webviewRef = useRef();
const [url] = useState(uri);
const webviewRef = useRef<GeekWebViewComponent>(null);
const { isFocus } = useFocusBlur(props.navigation);
useStatusBar(isFocus, true, "black");
// 返回逻辑
const onBack = () => {
if (webviewRef.current && webviewRef.current.canGoBack()) {
console.log('== click back ===', webviewRef.current.canGoBack())
webviewRef.current && webviewRef.current.goBack();
} else {
props.navigation.goBack();
console.log('== click back === goBack', webviewRef.current, navigationService)
navigationService.goBack()
}
};
......@@ -39,32 +50,31 @@ function GeekWebViewPage(props) {
props.navigation.goBack();
};
const onTitle = (title) => {
const onTitle = (title: string) => {
const initTitle = props.navigation.getParam("initTitle");
props.navigation.setParams({ title: title || initTitle });
};
const handleMessage = (event) => {
const handleMessage = (event: any) => {
if (onMessage) {
onMessage(event)
}
};
// 分享逻辑
const handleShare = (data) => {
const handleShare = (data: any) => {
shareByWeb(data);
};
// 分享朋友圈
const handleShareTimeline = (data) => {
const handleShareTimeline = (data: any) => {
console.log("onShareTimeline");
shareByWeb(data, true);
};
// 播放视频
// eslint-disable-next-line no-shadow
const playVideo = ({ url }) => {
utils.playVideo(url, (result) => {
const playVideo = ({ url }: { url: string }) => {
utils.playVideo(url, (result: any) => {
setTimeout(() => {
webviewRef.current && webviewRef.current.excuteJSMethod({
method: 'uploadPlayInfo',
......@@ -75,7 +85,7 @@ function GeekWebViewPage(props) {
}
// h5 的log日志
const handleLog = (args) => {
const handleLog = (args: any) => {
if (__DEV__) {
console.log('H5 LOG: ', args)
}
......@@ -97,43 +107,50 @@ function GeekWebViewPage(props) {
}, []);
return (
<GeekWebView
ref={webviewRef}
style={styles.container}
uri={url}
renderLoading={() => (
<View
style={{
height:
device.height -
device.headerHeight -
device.androidStatusBarHeight,
justifyContent: "center",
alignItems: "center",
}}
>
<ActivityIndicator size="large" />
</View>
)}
onTitle={onTitle}
onShare={handleShare}
onMessage={handleMessage}
onPlayVideo={playVideo}
onShareTimeline={handleShareTimeline}
onLog={handleLog}
/>
<View style={{ flex: 1, backgroundColor: 'blue'}}>
<GeekWebView
ref={webviewRef}
style={styles.container}
uri={uri}
renderLoading={() => (
<View
style={{
height:
device.height -
device.headerHeight -
device.androidStatusBarHeight,
justifyContent: "center",
alignItems: "center",
}}
>
<ActivityIndicator size="large" />
</View>
)}
onTitle={onTitle}
onShare={handleShare}
onMessage={handleMessage}
onPlayVideo={playVideo}
onShareTimeline={handleShareTimeline}
onLog={handleLog}
/>
</View>
);
}
GeekWebViewPage.navigationOptions = ({ navigation }) => {
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.pageBgColor,
},
});
withStackScreen<WebViewPagePramasType>(GeekWebViewPage, ({ navigation }) => {
return {
...navigationOptions,
headerStyle: {
...navigationOptions.headerStyle || {},
borderBottomColor: '#DEE2EA',
borderBottomWidth: rpx(1)
},
headerTitle: navigation.getParam("title"),
headerTitle: navigation.getParam("title") || navigation.getParam('initTitle'),
headerLeft: () => {
return (
<View
......@@ -144,7 +161,10 @@ GeekWebViewPage.navigationOptions = ({ navigation }) => {
alignItems: "center",
}}
>
<TouchableWithoutFeedback onPress={navigation.getParam("onBack")}>
<TouchableWithoutFeedback onPress={() => {
const onBack = navigation.getParam("onBack")
onBack && onBack()
}}>
<Image
source={back}
style={{ width: rpx(40), height: rpx(40), marginLeft: rpx(10), padding: rpx(10) }}
......@@ -154,13 +174,6 @@ GeekWebViewPage.navigationOptions = ({ navigation }) => {
);
},
};
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.pageBgColor,
},
});
})
export default GeekWebViewPage;
......@@ -5,6 +5,7 @@ import { NavigationCommonTabOptions } from 'react-navigation-tabs/lib/typescript
import Home from '@/pages/geek-home'
import Login from '@/pages/geek-login'
import SplashPage from '@/pages/geek-splash'
import WebView from '@/pages/geek-webview'
type StackPageProps = {
......@@ -29,7 +30,10 @@ export type SwitchProps = {
const appConfig: SwitchProps = {
splash: { component: SplashPage, name: 'SplashPage' },
auth: { component: Login, name: 'login' },
home: { component: Home, name: 'home' }
home: [
{ component: Home, name: 'home' },
{ component: WebView, name: 'webview' }
]
}
export default appConfig
\ No newline at end of file
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
......@@ -22,9 +24,9 @@ const renderStack = ( tabRoute: any ) => {
}, {})
} else {
routes = {
[tabRoute.name]: {
screen: tabRoute.component,
navigationOptions: tabRoute.navigationOptions
[tabRoute.name]: {
screen: tabRoute.component,
navigationOptions: tabRoute.navigationOptions
},
}
}
......@@ -48,7 +50,7 @@ const renderTabs = (tabsConfig: any[]) => {
[itm.name]: {
screen: renderStack(itm.children),
navigationOptions: itm.navigationOptions
}
}
} : {
[itm.name]: {
screen: itm.component,
......@@ -78,13 +80,13 @@ const renderTabs = (tabsConfig: any[]) => {
}
// switch
const renderSwitch = (routerConfig: any) => {
const switchRoutes = Object.keys(routerConfig).map(key => {
const screen = key === 'tabs' ? renderTabs(routerConfig[key]) : renderStack(routerConfig[key])
const renderSwitch = (routerCfg: any) => {
const switchRoutes = Object.keys(routerCfg).map(key => {
const screen = key === 'tabs' ? renderTabs(routerCfg[key]) : renderStack(routerCfg[key])
if (screen) {
return {
[key]: {
screen: key === 'tabs' ? renderTabs(routerConfig[key]) : renderStack(routerConfig[key])
screen: key === 'tabs' ? renderTabs(routerCfg[key]) : renderStack(routerCfg[key])
}
}
}
......
This diff is collapsed.
import RNFS from 'react-native-fs';
import {device} from 'geekbase';
import RNFetchBlob from 'rn-fetch-blob';
import {mimeTypeMaps} from './constant';
const dstSrc =
device.os === 'android'
? `${RNFS.ExternalDirectoryPath}/file`
: `${RNFS.CachesDirectoryPath}/file`;
const _getFilePath = (fileUrl, fileName) => {
const fileNamePath =
fileUrl.split('/')[fileUrl.split('/').length - 1] || new Date().getTime();
console.log(fileUrl, fileNamePath);
return `${dstSrc}/${fileName || fileNamePath}`;
};
const dstFilePath = _getFilePath;
// cb : { progress: number, error: ''}
const downloadFile = ({fileUrl, fileName, cb}) => {
dirExist(dstSrc);
console.log(fileUrl, fileName);
const dstPath = _getFilePath(fileUrl, fileName);
const {jobId, promise} = RNFS.downloadFile({
fromUrl: fileUrl,
toFile: dstPath,
background: true,
progress: ({jobId, contentLength, bytesWritten}) => {
cb &&
cb({
current: bytesWritten,
total: contentLength,
progress: bytesWritten / contentLength,
jobId,
file: dstPath,
start: false,
});
},
begin: ({jobId, statusCode}) => {
cb &&
cb({
jobId,
error:
statusCode >= 200 && statusCode <= 299
? null
: `下载失败,${statusCode}`,
file: dstPath,
start: true,
});
},
});
promise
.then(({bytesWritten}) => {
cb &&
cb({
current: bytesWritten,
total: bytesWritten,
jobId,
file: dstPath,
start: false,
end: true,
});
})
.catch(error => {
console.error(error);
});
};
const dirExist = dir => {
RNFS.exists(dir).then(exist => {
if (!exist) {
RNFS.mkdir(dir);
}
});
};
const fileExist = ({fileUrl, fileName, cb}) => {
const dstPath = _getFilePath(fileUrl, fileName);
RNFS.exists(dstPath)
.then(res => {
cb && cb(res);
})
.catch(error => {
cb && cb(false);
});
};
const getMimeTypeMap = filePath => {
const seperates = (filePath || '').split('.') || [];
const extension = seperates[seperates.length - 1] || '';
const mimeType = `.${extension}`;
const mime = mimeTypeMaps.find(item =>
Object.keys(item).find(itm => itm === mimeType),
);
console.log(mime);
return mime[mimeType];
};
const openFile = filePath => {
console.log(filePath);
try {
if (device.os === 'android') {
RNFetchBlob.android.actionViewIntent(filePath, getMimeTypeMap(filePath));
} else {
RNFetchBlob.ios.previewDocument(filePath);
}
} catch (error) {}
};
const stopDownload = jobId => {
if (jobId) {
RNFS.stopUpload(jobId);
}
};
const unlinkFile = ({fileUrl, fileName}) => {
console.log(fileUrl, fileName);
const dstPath = _getFilePath(fileUrl, fileName);
fileExist({
fileName,
fileUrl,
cb: exist => {
if (exist) {
RNFS.unlink(dstPath);
}
},
});
};
const saveBase64Image = async (base64Img, fileName, cb) => {
if (typeof fileName === 'function') {
(cb = fileName), (fileName = null);
}
const distPath = _getFilePath('', fileName || `${new Date().getTime()}.png`);
const imageDatas = base64Img.split('data:image/png;base64,');
const imageData = imageDatas[1];
try {
const result = await RNFetchBlob.fs.writeFile(
distPath,
imageData,
'base64',
);
cb && cb(distPath, null);
} catch (error) {
cb && cb(null, error);
}
};
export {
downloadFile,
fileExist,
dstFilePath,
openFile,
getMimeTypeMap,
stopDownload,
unlinkFile,
saveBase64Image,
};
......@@ -3,8 +3,8 @@ import DeviceInfo from "react-native-device-info";
import { Linking, findNodeHandle, UIManager } from "react-native";
import * as WeChat from "react-native-weixin";
import { Toast } from "geekbase";
import { saveBase64Image } from './fileUtil'
import http from "@/http";
// import { saveBase64Image } from './fileUtil'
// import http from "@/http";
import { playWithSeekPos } from "react-native-player";
// classin app 的下载地址
......@@ -13,13 +13,6 @@ const iosClassinAppUrl =
const androidClassinAppUrl =
"https://profile-1257124244.cos.ap-chengdu.myqcloud.com/app_resource/classin_android_install_3.0.3.2.apk";
const _operator = {
"+": "add",
"-": "sub",
"*": "mul",
"/": "div"
};
const sleep = async duration => {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
......@@ -29,6 +22,7 @@ const sleep = async duration => {
const linkClassinApp = url => {
return new Promise((resolve, reject) => {
const systemVersion = DeviceInfo.getSystemVersion();
// eslint-disable-next-line radix
if (systemVersion && parseInt(systemVersion) < 6) {
reject({
message:
......@@ -129,7 +123,7 @@ const openUrl = url => {
/**
* @type img | text | news
* @data img => {img: base64} , text => { description: '' } , news: { title: string, webpageUrl: url, description: string }
* @isTimeline 是否分享到朋友圈
* @isTimeline 是否分享到朋友圈
*/
const shareByWeb = ({ type = 'text', img, ...data } , isTimeline = false) => {
if (type === 'text' || type === 'news') {
......@@ -139,33 +133,33 @@ const shareByWeb = ({ type = 'text', img, ...data } , isTimeline = false) => {
}
share({ ...shareData }, isTimeline)
} else {
saveBase64Image(img, (imgPath, error ) => {
if (!error) {
share({
type: 'imageFile',
description: '图片分享',
imageUrl: "file://" + imgPath,
title: '图片分享'
}, isTimeline)
} else {
Toast.warn('图片分享失败, 请重试')
}
})
// saveBase64Image(img, (imgPath, error ) => {
// if (!error) {
// share({
// type: 'imageFile',
// description: '图片分享',
// imageUrl: "file://" + imgPath,
// title: '图片分享'
// }, isTimeline)
// } else {
// Toast.warn('图片分享失败, 请重试')
// }
// })
}
}
// 视频播放封装
const playVideo = async (url, cb) => {
const [res, error] = await http.queryVideoPlayTime(url || '')
console.log(res, error)
const { checkValue } = res || {}
const { current, total } = checkValue || {}
const currentTime = total > 0 ? (current + 5 > total ? 1 : current) : 1
playWithSeekPos(url, currentTime, (videoRes) => {
// const [res, error] = await http.queryVideoPlayTime(url || '')
// console.log(res, error)
// const { checkValue } = res || {}
// const { current, total } = checkValue || {}
// const currentTime = total > 0 ? (current + 5 > total ? 1 : current) : 1
playWithSeekPos(url, 0, (videoRes) => {
console.log('保存视频回调', videoRes)
http.saveVideoPlayTime(url, videoRes).then((res) => {
console.log('保存视频播放', res)
})
// http.saveVideoPlayTime(url, videoRes).then((res) => {
// console.log('保存视频播放', res)
// })
cb && cb(videoRes)
})
}
......
// typings.d.ts
declare module "*.json";
declare module "*.png";
declare module "*.jpg";
declare module "*.jpeg";
declare module "*.md";
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment