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", "name": "HH",
"displayName": "template" "displayName": "HH"
} }
\ No newline at end of file
...@@ -5,5 +5,5 @@ ...@@ -5,5 +5,5 @@
import {AppRegistry} from 'react-native'; import {AppRegistry} from 'react-native';
import App from './src/App'; import App from './src/App';
import {name as appName} from './app.json'; import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App); AppRegistry.registerComponent(appName, () => App);
...@@ -21,17 +21,23 @@ ...@@ -21,17 +21,23 @@
"react": "16.13.1", "react": "16.13.1",
"react-native": "0.63.3", "react-native": "0.63.3",
"react-native-code-push": "^6.3.0", "react-native-code-push": "^6.3.0",
"react-native-device-info": "^6.2.0",
"react-native-extra-dimensions-android": "^1.2.5", "react-native-extra-dimensions-android": "^1.2.5",
"react-native-fast-image": "^8.3.2", "react-native-fast-image": "^8.3.2",
"react-native-fs": "^2.16.6",
"react-native-gesture-handler": "^1.8.0", "react-native-gesture-handler": "^1.8.0",
"react-native-modal": "^11.5.6", "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-reanimated": "^1.13.0",
"react-native-refresh-list-view": "^1.0.12", "react-native-refresh-list-view": "^1.0.12",
"react-native-root-siblings": "^4.0.6", "react-native-root-siblings": "^4.0.6",
"react-native-safe-area-context": "^3.1.7", "react-native-safe-area-context": "^3.1.7",
"react-native-screens": "^2.10.1", "react-native-screens": "^2.10.1",
"react-native-scrollable-tab-view": "^1.0.0", "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-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": "^4.4.0",
"react-navigation-stack": "^2.8.2", "react-navigation-stack": "^2.8.2",
"react-navigation-tabs": "^2.9.0", "react-navigation-tabs": "^2.9.0",
...@@ -56,5 +62,9 @@ ...@@ -56,5 +62,9 @@
}, },
"jest": { "jest": {
"preset": "react-native" "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() { ...@@ -22,7 +22,6 @@ export default function App() {
const handleAppStateChange = (appState: AppStateStatus) => { const handleAppStateChange = (appState: AppStateStatus) => {
console.log('当前app状态', appState) console.log('当前app状态', appState)
if (appState === 'background') { 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 {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 {StackNavigationOptions} from 'react-navigation-stack/lib/typescript/src/vendor/types';
import {navigationOptions} from '@/router/constant'; import {navigationOptions} from '@/router/constant';
import { createTypedHooks } from 'easy-peasy'; import { createTypedHooks } from 'easy-peasy';
import StoreModels from '@/models' import StoreModels from '@/models'
// 路由进入时hook type ConfigType<P = {}, > = (config: {navigation: NavigationStackProp<{}, P>}) => StackNavigationOptions
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) => { export const withStackScreen = <P = {}>(
setIsFocus(false);
setIsBlur(true);
});
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 = (
Wrapp: React.ReactNode, 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, ...navigationOptions,
...config, ...config,
}; };
......
...@@ -2,16 +2,15 @@ import { navigationService, getAppConfig } from 'geekbase' ...@@ -2,16 +2,15 @@ import { navigationService, getAppConfig } from 'geekbase'
import cache from '@/cache' import cache from '@/cache'
export default { export default {
/** /**
* 去webview页面 * 去webview页面
* @param {uri, useToken, initTitle, onMessage } props * @param {uri, useToken, initTitle, onMessage } props
*/ */
navigateGeekWebViewPage(props: { navigateGeekWebViewPage(props: {
uri: string, uri: string,
useToken: boolean, useToken?: boolean,
initTitle: string, initTitle?: string,
onMessage: Function onMessage?: Function
}) { }) {
const { uri, useToken, ...others } = props const { uri, useToken, ...others } = props
let url = uri let url = uri
...@@ -26,13 +25,13 @@ export default { ...@@ -26,13 +25,13 @@ export default {
} else { } else {
url = `${url}?token=${token}`; url = `${url}?token=${token}`;
} }
navigationService.navigate('GeekWebViewPage', { navigationService.navigate('webview', {
uri: /^https?:\/\//g.test(url) ? url : `${getAppConfig().baseUrl}${url}`, uri: /^https?:\/\//g.test(url) ? url : `${getAppConfig().baseUrl}${url}`,
...others ...others
}) })
}); });
} else { } else {
navigationService.navigate('GeekWebViewPage', { navigationService.navigate('webview', {
uri: /^https?:\/\//g.test(url) ? url : `${getAppConfig().baseUrl}${url}`, uri: /^https?:\/\//g.test(url) ? url : `${getAppConfig().baseUrl}${url}`,
...others ...others
}) })
......
import React, { useCallback, useEffect } from 'react' import React, { useCallback, useEffect, useState } from 'react'
import { View, ImageBackground, StyleSheet, Text } from "react-native"; import { View, ImageBackground, StyleSheet, Text, Alert } from "react-native";
import { TouchableHighlight } from 'react-native-gesture-handler'; 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 { SafeAreaView } from 'react-native-safe-area-context';
import { bgImg } from './assets'; import { bgImg } from './assets';
import { rpx } from 'geekbase'; import { fileUtil, rpx, useFocusBlur, useStatusBar } from 'geekbase';
import navigate from '@/navigate';
const Home = (props: any) => { const Home = (props: any) => {
const file = 'http://1257124244.vod2.myqcloud.com/c9be83a2vodcq1257124244/d9bd8ff25285890808419280862/1Ky6n7tAgF0A.mp4'
useStatusBar(true, true, 'white') const { isFocus } = useFocusBlur(props.navigation)
useStatusBar(isFocus, true, 'white')
const [progress, setProgress] = useState('')
const [filePath, setFilePath] = useState('')
useEffect(() => { useEffect(() => {
console.log('bg: ', bgImg)
}, []) }, [])
const handleClickItem = useCallback((type: string) => { 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 ( return (
<ImageBackground source={bgImg} style={styles.bgStyle}> <ImageBackground source={bgImg} style={styles.bgStyle}>
<SafeAreaView style={{ flex: 1 }}> <SafeAreaView style={{ flex: 1 }}>
<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}> <View style={styles.functionalArea}>
<TouchableHighlight onPress={() => { <TouchableHighlight onPress={() => {
handleClickItem('1') handleClickItem('1')
}} style={styles.funItem}> }} style={styles.funItem}>
...@@ -29,15 +71,49 @@ const Home = (props: any) => { ...@@ -29,15 +71,49 @@ const Home = (props: any) => {
<Text style={styles.fucText}>作业批阅</Text> <Text style={styles.fucText}>作业批阅</Text>
</View> </View>
</TouchableHighlight> </TouchableHighlight>
<TouchableHighlight onPress={() => { <TouchableHighlight onPress={() => {
handleClickItem('2') handleClickItem('2')
}} style={styles.funItem}> }} style={styles.funItem}>
<View style={styles.funContainer}> <View style={styles.funContainer}>
<Text style={styles.fucText}>其他功能</Text> <Text style={styles.fucText}>预览文件</Text>
</View> </View>
</TouchableHighlight> </TouchableHighlight>
</View> </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('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('6')
}} style={styles.funItem}>
<View style={styles.funContainer}>
<Text style={styles.fucText}>查看文件是否存在</Text>
</View>
</TouchableHighlight>
</View>
</View>
</SafeAreaView> </SafeAreaView>
</ImageBackground> </ImageBackground>
) )
...@@ -48,9 +124,9 @@ const styles = StyleSheet.create({ ...@@ -48,9 +124,9 @@ const styles = StyleSheet.create({
flex: 1 flex: 1
}, },
functionalArea: { functionalArea: {
marginTop: rpx(500),
flexDirection: 'row', flexDirection: 'row',
justifyContent: 'space-around', justifyContent: 'space-around',
margin: rpx(10)
}, },
funItem: { funItem: {
width: rpx(300), width: rpx(300),
...@@ -65,7 +141,7 @@ const styles = StyleSheet.create({ ...@@ -65,7 +141,7 @@ const styles = StyleSheet.create({
flex: 1 flex: 1
}, },
fucText: { fucText: {
color: 'white', fontSize: rpx(30), fontWeight: 'bold' color: 'white', fontSize: rpx(20), fontWeight: 'bold'
} }
}) })
......
/* eslint-disable react/prop-types */ /* eslint-disable react/prop-types */
import React, { useEffect, useRef, useState } from "react"; import React, { useEffect, useRef } from "react";
import { import {
View, View,
StyleSheet, StyleSheet,
...@@ -8,29 +8,40 @@ import { ...@@ -8,29 +8,40 @@ import {
Image, Image,
ActivityIndicator, ActivityIndicator,
} from "react-native"; } from "react-native";
import { device, rpx } from "geekbase"; import { device, rpx, GeekWebView, useStatusBar, navigationService, GeekWebViewComponent, useFocusBlur } from "geekbase";
import { useFocusBlur, useStatusBar, navigationOptions } from "@/appbase";
import { colors } from "@/assets";
import { back } from "./assets"; import { back } from "./assets";
import { GeekWebView } from "@/components"; import colors from '@/assets/colors'
import { shareByWeb } from "@/utils"; import { shareByWeb } from "@/utils";
import * as utils from '@/utils' import * as utils from '@/utils'
import { withStackScreen } from "@/hooks";
import { NavigationStackProp } from "react-navigation-stack";
function GeekWebViewPage(props) { type WebViewPagePramasType = {
const uri = props.navigation.getParam("uri"); 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 onMessage = props.navigation.getParam("onMessage");
const webviewRef = useRef(); const webviewRef = useRef<GeekWebViewComponent>(null);
const [url] = useState(uri);
const { isFocus } = useFocusBlur(props.navigation); const { isFocus } = useFocusBlur(props.navigation);
useStatusBar(isFocus, true, "black"); useStatusBar(isFocus, true, "black");
// 返回逻辑 // 返回逻辑
const onBack = () => { const onBack = () => {
if (webviewRef.current && webviewRef.current.canGoBack()) { if (webviewRef.current && webviewRef.current.canGoBack()) {
console.log('== click back ===', webviewRef.current.canGoBack())
webviewRef.current && webviewRef.current.goBack(); webviewRef.current && webviewRef.current.goBack();
} else { } else {
props.navigation.goBack(); console.log('== click back === goBack', webviewRef.current, navigationService)
navigationService.goBack()
} }
}; };
...@@ -39,32 +50,31 @@ function GeekWebViewPage(props) { ...@@ -39,32 +50,31 @@ function GeekWebViewPage(props) {
props.navigation.goBack(); props.navigation.goBack();
}; };
const onTitle = (title) => { const onTitle = (title: string) => {
const initTitle = props.navigation.getParam("initTitle"); const initTitle = props.navigation.getParam("initTitle");
props.navigation.setParams({ title: title || initTitle }); props.navigation.setParams({ title: title || initTitle });
}; };
const handleMessage = (event) => { const handleMessage = (event: any) => {
if (onMessage) { if (onMessage) {
onMessage(event) onMessage(event)
} }
}; };
// 分享逻辑 // 分享逻辑
const handleShare = (data) => { const handleShare = (data: any) => {
shareByWeb(data); shareByWeb(data);
}; };
// 分享朋友圈 // 分享朋友圈
const handleShareTimeline = (data) => { const handleShareTimeline = (data: any) => {
console.log("onShareTimeline"); console.log("onShareTimeline");
shareByWeb(data, true); shareByWeb(data, true);
}; };
// 播放视频 // 播放视频
// eslint-disable-next-line no-shadow const playVideo = ({ url }: { url: string }) => {
const playVideo = ({ url }) => { utils.playVideo(url, (result: any) => {
utils.playVideo(url, (result) => {
setTimeout(() => { setTimeout(() => {
webviewRef.current && webviewRef.current.excuteJSMethod({ webviewRef.current && webviewRef.current.excuteJSMethod({
method: 'uploadPlayInfo', method: 'uploadPlayInfo',
...@@ -75,7 +85,7 @@ function GeekWebViewPage(props) { ...@@ -75,7 +85,7 @@ function GeekWebViewPage(props) {
} }
// h5 的log日志 // h5 的log日志
const handleLog = (args) => { const handleLog = (args: any) => {
if (__DEV__) { if (__DEV__) {
console.log('H5 LOG: ', args) console.log('H5 LOG: ', args)
} }
...@@ -97,10 +107,11 @@ function GeekWebViewPage(props) { ...@@ -97,10 +107,11 @@ function GeekWebViewPage(props) {
}, []); }, []);
return ( return (
<View style={{ flex: 1, backgroundColor: 'blue'}}>
<GeekWebView <GeekWebView
ref={webviewRef} ref={webviewRef}
style={styles.container} style={styles.container}
uri={url} uri={uri}
renderLoading={() => ( renderLoading={() => (
<View <View
style={{ style={{
...@@ -122,18 +133,24 @@ function GeekWebViewPage(props) { ...@@ -122,18 +133,24 @@ function GeekWebViewPage(props) {
onShareTimeline={handleShareTimeline} onShareTimeline={handleShareTimeline}
onLog={handleLog} onLog={handleLog}
/> />
</View>
); );
} }
GeekWebViewPage.navigationOptions = ({ navigation }) => { const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.pageBgColor,
},
});
withStackScreen<WebViewPagePramasType>(GeekWebViewPage, ({ navigation }) => {
return { return {
...navigationOptions,
headerStyle: { headerStyle: {
...navigationOptions.headerStyle || {},
borderBottomColor: '#DEE2EA', borderBottomColor: '#DEE2EA',
borderBottomWidth: rpx(1) borderBottomWidth: rpx(1)
}, },
headerTitle: navigation.getParam("title"), headerTitle: navigation.getParam("title") || navigation.getParam('initTitle'),
headerLeft: () => { headerLeft: () => {
return ( return (
<View <View
...@@ -144,7 +161,10 @@ GeekWebViewPage.navigationOptions = ({ navigation }) => { ...@@ -144,7 +161,10 @@ GeekWebViewPage.navigationOptions = ({ navigation }) => {
alignItems: "center", alignItems: "center",
}} }}
> >
<TouchableWithoutFeedback onPress={navigation.getParam("onBack")}> <TouchableWithoutFeedback onPress={() => {
const onBack = navigation.getParam("onBack")
onBack && onBack()
}}>
<Image <Image
source={back} source={back}
style={{ width: rpx(40), height: rpx(40), marginLeft: rpx(10), padding: rpx(10) }} style={{ width: rpx(40), height: rpx(40), marginLeft: rpx(10), padding: rpx(10) }}
...@@ -154,13 +174,6 @@ GeekWebViewPage.navigationOptions = ({ navigation }) => { ...@@ -154,13 +174,6 @@ GeekWebViewPage.navigationOptions = ({ navigation }) => {
); );
}, },
}; };
}; })
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.pageBgColor,
},
});
export default GeekWebViewPage; export default GeekWebViewPage;
...@@ -5,6 +5,7 @@ import { NavigationCommonTabOptions } from 'react-navigation-tabs/lib/typescript ...@@ -5,6 +5,7 @@ import { NavigationCommonTabOptions } from 'react-navigation-tabs/lib/typescript
import Home from '@/pages/geek-home' import Home from '@/pages/geek-home'
import Login from '@/pages/geek-login' import Login from '@/pages/geek-login'
import SplashPage from '@/pages/geek-splash' import SplashPage from '@/pages/geek-splash'
import WebView from '@/pages/geek-webview'
type StackPageProps = { type StackPageProps = {
...@@ -29,7 +30,10 @@ export type SwitchProps = { ...@@ -29,7 +30,10 @@ export type SwitchProps = {
const appConfig: SwitchProps = { const appConfig: SwitchProps = {
splash: { component: SplashPage, name: 'SplashPage' }, splash: { component: SplashPage, name: 'SplashPage' },
auth: { component: Login, name: 'login' }, auth: { component: Login, name: 'login' },
home: { component: Home, name: 'home' } home: [
{ component: Home, name: 'home' },
{ component: WebView, name: 'webview' }
]
} }
export default appConfig 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 React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation'; import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack'; import { createStackNavigator } from 'react-navigation-stack';
...@@ -78,13 +80,13 @@ const renderTabs = (tabsConfig: any[]) => { ...@@ -78,13 +80,13 @@ const renderTabs = (tabsConfig: any[]) => {
} }
// switch // switch
const renderSwitch = (routerConfig: any) => { const renderSwitch = (routerCfg: any) => {
const switchRoutes = Object.keys(routerConfig).map(key => { const switchRoutes = Object.keys(routerCfg).map(key => {
const screen = key === 'tabs' ? renderTabs(routerConfig[key]) : renderStack(routerConfig[key]) const screen = key === 'tabs' ? renderTabs(routerCfg[key]) : renderStack(routerCfg[key])
if (screen) { if (screen) {
return { return {
[key]: { [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"; ...@@ -3,8 +3,8 @@ import DeviceInfo from "react-native-device-info";
import { Linking, findNodeHandle, UIManager } from "react-native"; import { Linking, findNodeHandle, UIManager } from "react-native";
import * as WeChat from "react-native-weixin"; import * as WeChat from "react-native-weixin";
import { Toast } from "geekbase"; import { Toast } from "geekbase";
import { saveBase64Image } from './fileUtil' // import { saveBase64Image } from './fileUtil'
import http from "@/http"; // import http from "@/http";
import { playWithSeekPos } from "react-native-player"; import { playWithSeekPos } from "react-native-player";
// classin app 的下载地址 // classin app 的下载地址
...@@ -13,13 +13,6 @@ const iosClassinAppUrl = ...@@ -13,13 +13,6 @@ const iosClassinAppUrl =
const androidClassinAppUrl = const androidClassinAppUrl =
"https://profile-1257124244.cos.ap-chengdu.myqcloud.com/app_resource/classin_android_install_3.0.3.2.apk"; "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 => { const sleep = async duration => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
setTimeout(resolve, duration); setTimeout(resolve, duration);
...@@ -29,6 +22,7 @@ const sleep = async duration => { ...@@ -29,6 +22,7 @@ const sleep = async duration => {
const linkClassinApp = url => { const linkClassinApp = url => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const systemVersion = DeviceInfo.getSystemVersion(); const systemVersion = DeviceInfo.getSystemVersion();
// eslint-disable-next-line radix
if (systemVersion && parseInt(systemVersion) < 6) { if (systemVersion && parseInt(systemVersion) < 6) {
reject({ reject({
message: message:
...@@ -139,33 +133,33 @@ const shareByWeb = ({ type = 'text', img, ...data } , isTimeline = false) => { ...@@ -139,33 +133,33 @@ const shareByWeb = ({ type = 'text', img, ...data } , isTimeline = false) => {
} }
share({ ...shareData }, isTimeline) share({ ...shareData }, isTimeline)
} else { } else {
saveBase64Image(img, (imgPath, error ) => { // saveBase64Image(img, (imgPath, error ) => {
if (!error) { // if (!error) {
share({ // share({
type: 'imageFile', // type: 'imageFile',
description: '图片分享', // description: '图片分享',
imageUrl: "file://" + imgPath, // imageUrl: "file://" + imgPath,
title: '图片分享' // title: '图片分享'
}, isTimeline) // }, isTimeline)
} else { // } else {
Toast.warn('图片分享失败, 请重试') // Toast.warn('图片分享失败, 请重试')
} // }
}) // })
} }
} }
// 视频播放封装 // 视频播放封装
const playVideo = async (url, cb) => { const playVideo = async (url, cb) => {
const [res, error] = await http.queryVideoPlayTime(url || '') // const [res, error] = await http.queryVideoPlayTime(url || '')
console.log(res, error) // console.log(res, error)
const { checkValue } = res || {} // const { checkValue } = res || {}
const { current, total } = checkValue || {} // const { current, total } = checkValue || {}
const currentTime = total > 0 ? (current + 5 > total ? 1 : current) : 1 // const currentTime = total > 0 ? (current + 5 > total ? 1 : current) : 1
playWithSeekPos(url, currentTime, (videoRes) => { playWithSeekPos(url, 0, (videoRes) => {
console.log('保存视频回调', videoRes) console.log('保存视频回调', videoRes)
http.saveVideoPlayTime(url, videoRes).then((res) => { // http.saveVideoPlayTime(url, videoRes).then((res) => {
console.log('保存视频播放', res) // console.log('保存视频播放', res)
}) // })
cb && cb(videoRes) 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