@mpxjs/webpack-plugin 2.10.6-beta.3 → 2.10.6-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/lib/dependencies/RecordFileUrlDependency.js +58 -0
  2. package/lib/file-loader.js +3 -2
  3. package/lib/index.js +17 -4
  4. package/lib/platform/json/wx/index.js +43 -25
  5. package/lib/platform/template/wx/component-config/fix-component-name.js +2 -2
  6. package/lib/platform/template/wx/index.js +2 -1
  7. package/lib/react/processJSON.js +66 -11
  8. package/lib/react/processScript.js +2 -2
  9. package/lib/react/script-helper.js +24 -51
  10. package/lib/runtime/components/react/AsyncSuspense.tsx +194 -0
  11. package/lib/runtime/components/react/dist/AsyncSuspense.jsx +137 -0
  12. package/lib/runtime/components/react/dist/getInnerListeners.js +1 -1
  13. package/lib/runtime/components/react/dist/mpx-input.jsx +1 -1
  14. package/lib/runtime/components/react/dist/mpx-movable-view.jsx +2 -2
  15. package/lib/runtime/components/react/dist/mpx-swiper-item.jsx +2 -2
  16. package/lib/runtime/components/react/dist/mpx-swiper.jsx +53 -27
  17. package/lib/runtime/components/react/dist/mpx-web-view.jsx +14 -28
  18. package/lib/runtime/components/react/dist/useAnimationHooks.js +2 -87
  19. package/lib/runtime/components/react/dist/utils.jsx +84 -0
  20. package/lib/runtime/components/react/mpx-swiper.tsx +0 -7
  21. package/lib/runtime/components/react/useAnimationHooks.ts +2 -85
  22. package/lib/runtime/components/react/utils.tsx +83 -1
  23. package/lib/runtime/optionProcessorReact.d.ts +18 -0
  24. package/lib/runtime/optionProcessorReact.js +24 -0
  25. package/lib/template-compiler/compiler.js +2 -2
  26. package/lib/utils/dom-tag-config.js +2 -2
  27. package/package.json +1 -1
  28. package/lib/runtime/components/react/AsyncContainer.tsx +0 -189
@@ -0,0 +1,194 @@
1
+ import { useState, ComponentType, useEffect, useCallback, useRef, ReactNode, createElement } from 'react'
2
+ import { View, Image, StyleSheet, Text, TouchableOpacity } from 'react-native'
3
+ import FastImage from '@d11/react-native-fast-image'
4
+
5
+ const asyncChunkMap = new Map()
6
+
7
+ const styles = StyleSheet.create({
8
+ container: {
9
+ flex: 1,
10
+ padding: 20,
11
+ backgroundColor: '#fff'
12
+ },
13
+ loadingImage: {
14
+ width: 100,
15
+ height: 100,
16
+ marginTop: 220,
17
+ alignSelf: 'center'
18
+ },
19
+ buttonText: {
20
+ color: '#fff',
21
+ fontSize: 16,
22
+ fontWeight: '500',
23
+ textAlign: 'center'
24
+ },
25
+ errorImage: {
26
+ marginTop: 80,
27
+ width: 220,
28
+ aspectRatio: 1,
29
+ alignSelf: 'center'
30
+ },
31
+ errorText: {
32
+ fontSize: 16,
33
+ textAlign: 'center',
34
+ color: '#333',
35
+ marginBottom: 20
36
+ },
37
+ retryButton: {
38
+ position: 'absolute',
39
+ bottom: 54,
40
+ left: 20,
41
+ right: 20,
42
+ backgroundColor: '#fff',
43
+ paddingVertical: 15,
44
+ borderRadius: 30,
45
+ marginTop: 40,
46
+ borderWidth: 1,
47
+ borderColor: '#FF5F00'
48
+ },
49
+ retryButtonText: {
50
+ color: '#FF5F00',
51
+ fontSize: 16,
52
+ fontWeight: '500',
53
+ textAlign: 'center'
54
+ }
55
+ })
56
+
57
+ interface LayoutViewProps {
58
+ children: ReactNode
59
+ }
60
+
61
+ interface AsyncModule {
62
+ __esModule: boolean
63
+ default: ReactNode
64
+ }
65
+
66
+ interface DefaultFallbackProps {
67
+ onReload: () => void
68
+ }
69
+
70
+ const DefaultFallback = ({ onReload }: DefaultFallbackProps) => {
71
+ return (
72
+ <View style={styles.container}>
73
+ <Image
74
+ source={{
75
+ uri: 'https://dpubstatic.udache.com/static/dpubimg/Vak5mZvezPpKV5ZJI6P9b_drn-fallbak.png'
76
+ }}
77
+ style={styles.errorImage}
78
+ resizeMode="contain"
79
+ />
80
+ <Text style={styles.errorText}>网络出了点问题,请查看网络环境</Text>
81
+ <TouchableOpacity
82
+ style={styles.retryButton}
83
+ onPress={onReload}
84
+ activeOpacity={0.7}
85
+ >
86
+ <Text style={styles.retryButtonText}>点击重试</Text>
87
+ </TouchableOpacity>
88
+ </View>
89
+ )
90
+ }
91
+
92
+ const LayoutView = (props: LayoutViewProps) => {
93
+ return (
94
+ <View style={{ flex: 1 }} collapsable={false}>{props.children}</View>
95
+ )
96
+ }
97
+
98
+ const DefaultLoading = () => {
99
+ return (
100
+ <View style={styles.container}>
101
+ <FastImage
102
+ style={styles.loadingImage}
103
+ source={{
104
+ uri: 'https://dpubstatic.udache.com/static/dpubimg/439jiCVOtNOnEv9F2LaDs_loading.gif'
105
+ }}
106
+ resizeMode={FastImage.resizeMode.contain}
107
+ ></FastImage>
108
+ </View>
109
+ )
110
+ }
111
+
112
+ interface AsyncSuspenseProps {
113
+ type: 'component' | 'page'
114
+ chunkName: string
115
+ moduleId: string
116
+ innerProps: any,
117
+ loading: ComponentType<unknown>
118
+ fallback: ComponentType<unknown>
119
+ getChildren: () => Promise<AsyncModule>
120
+ }
121
+
122
+ type ComponentStauts = 'pending' | 'error' | 'loaded'
123
+
124
+ const AsyncSuspense: React.FC<AsyncSuspenseProps> = ({
125
+ type,
126
+ innerProps,
127
+ chunkName,
128
+ moduleId,
129
+ loading,
130
+ fallback,
131
+ getChildren
132
+ }) => {
133
+ const [status, setStatus] = useState<ComponentStauts>('pending')
134
+ const chunkLoaded = asyncChunkMap.has(moduleId)
135
+ const loadChunkPromise = useRef<null | Promise<AsyncModule>>(null)
136
+
137
+ const reloadPage = useCallback(() => {
138
+ setStatus('pending')
139
+ }, [])
140
+
141
+ useEffect(() => {
142
+ let cancelled = false
143
+ if (!chunkLoaded && status === 'pending') {
144
+ if (loadChunkPromise.current) {
145
+ loadChunkPromise
146
+ .current.then((m: AsyncModule) => {
147
+ if (cancelled) return
148
+ asyncChunkMap.set(moduleId, m.__esModule ? m.default : m)
149
+ setStatus('loaded')
150
+ })
151
+ .catch((e) => {
152
+ if (cancelled) return
153
+ if (type === 'component') {
154
+ global.onLazyLoadError({
155
+ type: 'subpackage',
156
+ subpackage: [chunkName],
157
+ errMsg: `loadSubpackage: ${e.type}`
158
+ })
159
+ }
160
+ loadChunkPromise.current = null
161
+ setStatus('error')
162
+ })
163
+ }
164
+ }
165
+
166
+ return () => {
167
+ cancelled = true
168
+ }
169
+ }, [status])
170
+
171
+ if (chunkLoaded) {
172
+ const Comp = asyncChunkMap.get(moduleId)
173
+ return createElement(Comp, innerProps)
174
+ } else if (status === 'error') {
175
+ if (type === 'page') {
176
+ const Fallback =
177
+ (fallback as ComponentType<DefaultFallbackProps>) || DefaultFallback
178
+ return createElement(LayoutView, null, createElement(Fallback, { onReload: reloadPage }))
179
+ } else {
180
+ return createElement(fallback, innerProps)
181
+ }
182
+ } else {
183
+ if (!loadChunkPromise.current) {
184
+ loadChunkPromise.current = getChildren()
185
+ }
186
+ if (type === 'page') {
187
+ return createElement(LayoutView, null, createElement(loading || DefaultLoading))
188
+ } else {
189
+ return createElement(fallback, innerProps)
190
+ }
191
+ }
192
+ }
193
+
194
+ export default AsyncSuspense
@@ -0,0 +1,137 @@
1
+ import { useState, useEffect, useCallback, useRef, createElement } from 'react';
2
+ import { View, Image, StyleSheet, Text, TouchableOpacity } from 'react-native';
3
+ import FastImage from '@d11/react-native-fast-image';
4
+ const asyncChunkMap = new Map();
5
+ const styles = StyleSheet.create({
6
+ container: {
7
+ flex: 1,
8
+ padding: 20,
9
+ backgroundColor: '#fff'
10
+ },
11
+ loadingImage: {
12
+ width: 100,
13
+ height: 100,
14
+ marginTop: 220,
15
+ alignSelf: 'center'
16
+ },
17
+ buttonText: {
18
+ color: '#fff',
19
+ fontSize: 16,
20
+ fontWeight: '500',
21
+ textAlign: 'center'
22
+ },
23
+ errorImage: {
24
+ marginTop: 80,
25
+ width: 220,
26
+ aspectRatio: 1,
27
+ alignSelf: 'center'
28
+ },
29
+ errorText: {
30
+ fontSize: 16,
31
+ textAlign: 'center',
32
+ color: '#333',
33
+ marginBottom: 20
34
+ },
35
+ retryButton: {
36
+ position: 'absolute',
37
+ bottom: 54,
38
+ left: 20,
39
+ right: 20,
40
+ backgroundColor: '#fff',
41
+ paddingVertical: 15,
42
+ borderRadius: 30,
43
+ marginTop: 40,
44
+ borderWidth: 1,
45
+ borderColor: '#FF5F00'
46
+ },
47
+ retryButtonText: {
48
+ color: '#FF5F00',
49
+ fontSize: 16,
50
+ fontWeight: '500',
51
+ textAlign: 'center'
52
+ }
53
+ });
54
+ const DefaultFallback = ({ onReload }) => {
55
+ return (<View style={styles.container}>
56
+ <Image source={{
57
+ uri: 'https://dpubstatic.udache.com/static/dpubimg/Vak5mZvezPpKV5ZJI6P9b_drn-fallbak.png'
58
+ }} style={styles.errorImage} resizeMode="contain"/>
59
+ <Text style={styles.errorText}>网络出了点问题,请查看网络环境</Text>
60
+ <TouchableOpacity style={styles.retryButton} onPress={onReload} activeOpacity={0.7}>
61
+ <Text style={styles.retryButtonText}>点击重试</Text>
62
+ </TouchableOpacity>
63
+ </View>);
64
+ };
65
+ const LayoutView = (props) => {
66
+ return (<View style={{ flex: 1 }} collapsable={false}>{props.children}</View>);
67
+ };
68
+ const DefaultLoading = () => {
69
+ return (<View style={styles.container}>
70
+ <FastImage style={styles.loadingImage} source={{
71
+ uri: 'https://dpubstatic.udache.com/static/dpubimg/439jiCVOtNOnEv9F2LaDs_loading.gif'
72
+ }} resizeMode={FastImage.resizeMode.contain}></FastImage>
73
+ </View>);
74
+ };
75
+ const AsyncSuspense = ({ type, innerProps, chunkName, moduleId, loading, fallback, getChildren }) => {
76
+ const [status, setStatus] = useState('pending');
77
+ const chunkLoaded = asyncChunkMap.has(moduleId);
78
+ const loadChunkPromise = useRef(null);
79
+ const reloadPage = useCallback(() => {
80
+ setStatus('pending');
81
+ }, []);
82
+ useEffect(() => {
83
+ let cancelled = false;
84
+ if (!chunkLoaded && status === 'pending') {
85
+ if (loadChunkPromise.current) {
86
+ loadChunkPromise
87
+ .current.then((m) => {
88
+ if (cancelled)
89
+ return;
90
+ asyncChunkMap.set(moduleId, m.__esModule ? m.default : m);
91
+ setStatus('loaded');
92
+ })
93
+ .catch((e) => {
94
+ if (cancelled)
95
+ return;
96
+ if (type === 'component') {
97
+ global.onLazyLoadError({
98
+ type: 'subpackage',
99
+ subpackage: [chunkName],
100
+ errMsg: `loadSubpackage: ${e.type}`
101
+ });
102
+ }
103
+ loadChunkPromise.current = null;
104
+ setStatus('error');
105
+ });
106
+ }
107
+ }
108
+ return () => {
109
+ cancelled = true;
110
+ };
111
+ }, [status]);
112
+ if (chunkLoaded) {
113
+ const Comp = asyncChunkMap.get(moduleId);
114
+ return createElement(Comp, innerProps);
115
+ }
116
+ else if (status === 'error') {
117
+ if (type === 'page') {
118
+ const Fallback = fallback || DefaultFallback;
119
+ return createElement(LayoutView, null, createElement(Fallback, { onReload: reloadPage }));
120
+ }
121
+ else {
122
+ return createElement(fallback, innerProps);
123
+ }
124
+ }
125
+ else {
126
+ if (!loadChunkPromise.current) {
127
+ loadChunkPromise.current = getChildren();
128
+ }
129
+ if (type === 'page') {
130
+ return createElement(LayoutView, null, createElement(loading || DefaultLoading));
131
+ }
132
+ else {
133
+ return createElement(fallback, innerProps);
134
+ }
135
+ }
136
+ };
137
+ export default AsyncSuspense;
@@ -8,7 +8,7 @@ const globalEventState = {
8
8
  const getTouchEvent = (type, event, config) => {
9
9
  const { navigation, propsRef, layoutRef } = config;
10
10
  const props = propsRef.current;
11
- const { y: navigationY = 0 } = navigation?.layout || {};
11
+ const { top: navigationY = 0 } = navigation?.layout || {};
12
12
  const nativeEvent = event.nativeEvent;
13
13
  const { timestamp, pageX, pageY, touches, changedTouches } = nativeEvent;
14
14
  const { id } = props;
@@ -91,7 +91,7 @@ const Input = forwardRef((props, ref) => {
91
91
  });
92
92
  const { layoutRef, layoutStyle, layoutProps } = useLayout({ props, hasSelfPercent, setWidth, setHeight, nodeRef });
93
93
  useEffect(() => {
94
- if (inputValue !== value) {
94
+ if (value !== tmpValue.current) {
95
95
  const parsed = parseValue(value);
96
96
  tmpValue.current = parsed;
97
97
  setInputValue(parsed);
@@ -223,14 +223,14 @@ const _MovableView = forwardRef((movableViewProps, ref) => {
223
223
  setHeight(height || 0);
224
224
  }
225
225
  nodeRef.current?.measure((x, y, width, height) => {
226
- const { y: navigationY = 0 } = navigation?.layout || {};
226
+ const { top: navigationY = 0 } = navigation?.layout || {};
227
227
  layoutRef.current = { x, y: y - navigationY, width, height, offsetLeft: 0, offsetTop: 0 };
228
228
  resetBoundaryAndCheck({ width, height });
229
229
  });
230
230
  props.onLayout && props.onLayout(e);
231
231
  };
232
232
  const extendEvent = useCallback((e, type) => {
233
- const { y: navigationY = 0 } = navigation?.layout || {};
233
+ const { top: navigationY = 0 } = navigation?.layout || {};
234
234
  const touchArr = [e.changedTouches, e.allTouches];
235
235
  touchArr.forEach(touches => {
236
236
  touches && touches.forEach((item) => {
@@ -2,7 +2,7 @@ import Animated, { useAnimatedStyle, interpolate } from 'react-native-reanimated
2
2
  import { forwardRef, useRef, useContext, createElement } from 'react';
3
3
  import useInnerProps from './getInnerListeners';
4
4
  import useNodesRef from './useNodesRef'; // 引入辅助函数
5
- import { useTransformStyle, splitStyle, splitProps, wrapChildren, useLayout, extendObject } from './utils';
5
+ import { useTransformStyle, splitStyle, splitProps, wrapChildren, useLayout, extendObject, isHarmony } from './utils';
6
6
  import { SwiperContext } from './context';
7
7
  const _SwiperItem = forwardRef((props, ref) => {
8
8
  const { 'enable-var': enableVar, 'external-var-context': externalVarContext, style, customStyle, itemIndex } = props;
@@ -29,7 +29,7 @@ const _SwiperItem = forwardRef((props, ref) => {
29
29
  'style'
30
30
  ], { layoutRef });
31
31
  const itemAnimatedStyle = useAnimatedStyle(() => {
32
- if (!step.value)
32
+ if (!step.value && !isHarmony)
33
33
  return {};
34
34
  const inputRange = [step.value, 0];
35
35
  const outputRange = [0.7, 1];
@@ -125,6 +125,10 @@ const SwiperWrapper = forwardRef((props, ref) => {
125
125
  const moveTranstion = useSharedValue(0);
126
126
  // 记录从onBegin 到 onTouchesUp 的时间
127
127
  const moveTime = useSharedValue(0);
128
+ // 记录从onBegin 到 onTouchesCancelled 另外一个方向移动的距离
129
+ const anotherDirectionMove = useSharedValue(0);
130
+ // 另一个方向的
131
+ const anotherAbso = 'absolute' + (dir === 'x' ? 'y' : 'x').toUpperCase();
128
132
  const timerId = useRef(0);
129
133
  const intervalTimer = props.interval || 500;
130
134
  const simultaneousHandlers = flatGesture(originSimultaneousHandlers);
@@ -405,7 +409,11 @@ const SwiperWrapper = forwardRef((props, ref) => {
405
409
  }
406
410
  }, [children.length]);
407
411
  useEffect(() => {
408
- updateCurrent(props.current || 0, step.value);
412
+ // 1. 如果用户在touch的过程中, 外部更新了current以外部为准(小程序表现)
413
+ // 2. 手指滑动过程中更新索引,外部会把current再穿进来,导致offset直接更新了
414
+ if (props.current !== currentIndex.value) {
415
+ updateCurrent(props.current || 0, step.value);
416
+ }
409
417
  }, [props.current]);
410
418
  useEffect(() => {
411
419
  autoplayShared.value = autoplay;
@@ -468,20 +476,26 @@ const SwiperWrapper = forwardRef((props, ref) => {
468
476
  targetOffset: -moveToTargetPos
469
477
  };
470
478
  }
471
- function canMove(eventData) {
479
+ function checkUnCircular(eventData) {
472
480
  'worklet';
473
481
  const { translation } = eventData;
474
482
  const currentOffset = Math.abs(offset.value);
475
- if (!circularShared.value) {
476
- if (translation < 0) {
477
- return currentOffset < step.value * (childrenLength.value - 1);
478
- }
479
- else {
480
- return currentOffset > 0;
481
- }
483
+ // 向右滑动swiper
484
+ if (translation < 0) {
485
+ const boundaryOffset = step.value * (childrenLength.value - 1);
486
+ const gestureMovePos = Math.abs(translation) + currentOffset;
487
+ return {
488
+ // 防止快速连续向右滑动时,手势移动的距离 当前的offset超出边界
489
+ targetOffset: gestureMovePos > boundaryOffset ? -boundaryOffset : offset.value + translation,
490
+ canMove: currentOffset < boundaryOffset
491
+ };
482
492
  }
483
493
  else {
484
- return true;
494
+ const gestureMovePos = currentOffset - translation;
495
+ return {
496
+ targetOffset: gestureMovePos < 0 ? 0 : offset.value + translation,
497
+ canMove: currentOffset > 0
498
+ };
485
499
  }
486
500
  }
487
501
  function handleEnd(eventData) {
@@ -541,7 +555,7 @@ const SwiperWrapper = forwardRef((props, ref) => {
541
555
  }
542
556
  });
543
557
  }
544
- function handleLongPress() {
558
+ function computeHalf() {
545
559
  'worklet';
546
560
  const currentOffset = Math.abs(offset.value);
547
561
  let preOffset = (currentIndex.value + patchElmNumShared.value) * step.value;
@@ -551,6 +565,14 @@ const SwiperWrapper = forwardRef((props, ref) => {
551
565
  // 正常事件中拿到的transition值(正向滑动<0,倒着滑>0)
552
566
  const diffOffset = preOffset - currentOffset;
553
567
  const half = Math.abs(diffOffset) > step.value / 2;
568
+ return {
569
+ diffOffset,
570
+ half
571
+ };
572
+ }
573
+ function handleLongPress() {
574
+ 'worklet';
575
+ const { diffOffset, half } = computeHalf();
554
576
  if (+diffOffset === 0) {
555
577
  runOnJS(resumeLoop)();
556
578
  }
@@ -610,19 +632,30 @@ const SwiperWrapper = forwardRef((props, ref) => {
610
632
  runOnJS(pauseLoop)();
611
633
  preAbsolutePos.value = e[strAbso];
612
634
  moveTranstion.value = e[strAbso];
635
+ anotherDirectionMove.value = e[anotherAbso];
613
636
  moveTime.value = new Date().getTime();
614
637
  })
615
- .onTouchesMove((e) => {
638
+ .onUpdate((e) => {
616
639
  'worklet';
617
640
  if (touchfinish.value)
618
641
  return;
619
- const touchEventData = e.changedTouches[0];
620
- const moveDistance = touchEventData[strAbso] - preAbsolutePos.value;
642
+ const moveDistance = e[strAbso] - preAbsolutePos.value;
621
643
  const eventData = {
622
644
  translation: moveDistance
623
645
  };
624
- // 处理用户一直拖拽到临界点的场景, 不会执行onEnd
625
- if (!circularShared.value && !canMove(eventData)) {
646
+ // 1. 在Move过程中,如果手指一直没抬起来,超过一半的话也会更新索引
647
+ const { half } = computeHalf();
648
+ if (half) {
649
+ const { selectedIndex } = getTargetPosition(eventData);
650
+ currentIndex.value = selectedIndex;
651
+ }
652
+ // 2. 处理用户一直拖拽到临界点的场景, 不会执行onEnd
653
+ const { canMove, targetOffset } = checkUnCircular(eventData);
654
+ if (!circularShared.value) {
655
+ if (canMove) {
656
+ offset.value = targetOffset;
657
+ preAbsolutePos.value = e[strAbso];
658
+ }
626
659
  return;
627
660
  }
628
661
  const { isBoundary, resetOffset } = reachBoundary(eventData);
@@ -632,30 +665,23 @@ const SwiperWrapper = forwardRef((props, ref) => {
632
665
  else {
633
666
  offset.value = moveDistance + offset.value;
634
667
  }
635
- preAbsolutePos.value = touchEventData[strAbso];
668
+ preAbsolutePos.value = e[strAbso];
636
669
  })
637
- .onTouchesUp((e) => {
670
+ .onFinalize((e) => {
638
671
  'worklet';
639
672
  if (touchfinish.value)
640
673
  return;
641
- const touchEventData = e.changedTouches[0];
642
- const moveDistance = touchEventData[strAbso] - moveTranstion.value;
674
+ const moveDistance = e[strAbso] - moveTranstion.value;
643
675
  touchfinish.value = true;
644
676
  const eventData = {
645
677
  translation: moveDistance
646
678
  };
647
- if (childrenLength.value === 1) {
648
- return handleBackInit();
649
- }
650
- // 用户手指按下起来, 需要计算正确的位置, 比如在滑动过程中突然按下然后起来,需要计算到正确的位置
651
- if (!circularShared.value && !canMove(eventData)) {
652
- return;
653
- }
654
679
  const strVelocity = moveDistance / (new Date().getTime() - moveTime.value) * 1000;
655
680
  if (Math.abs(strVelocity) < longPressRatio) {
656
681
  handleLongPress();
657
682
  }
658
683
  else {
684
+ // 如果触发了onTouchesCancelled,不会触发onUpdate不会更新offset值, 索引不会变更
659
685
  handleEnd(eventData);
660
686
  }
661
687
  })
@@ -1,6 +1,7 @@
1
1
  import { forwardRef, useRef, useContext, useMemo, useState } from 'react';
2
2
  import { warn, isFunction } from '@mpxjs/utils';
3
3
  import Portal from './mpx-portal/index';
4
+ import { usePreventRemove } from '@react-navigation/native';
4
5
  import { getCustomEvent } from './getInnerListeners';
5
6
  import { promisify, redirectTo, navigateTo, navigateBack, reLaunch, switchTab } from '@mpxjs/api-proxy';
6
7
  import { WebView } from 'react-native-webview';
@@ -55,8 +56,8 @@ const _WebView = forwardRef((props, ref) => {
55
56
  const webViewRef = useRef(null);
56
57
  const fristLoaded = useRef(false);
57
58
  const isLoadError = useRef(false);
59
+ const isNavigateBack = useRef(false);
58
60
  const statusCode = useRef('');
59
- const [isLoaded, setIsLoaded] = useState(true);
60
61
  const defaultWebViewStyle = {
61
62
  position: 'absolute',
62
63
  left: 0,
@@ -64,27 +65,18 @@ const _WebView = forwardRef((props, ref) => {
64
65
  top: 0,
65
66
  bottom: 0
66
67
  };
67
- const canGoBack = useRef(false);
68
- const isNavigateBack = useRef(false);
69
- const beforeRemoveHandle = (e) => {
70
- if (canGoBack.current && !isNavigateBack.current) {
68
+ const navigation = useNavigation();
69
+ const [isIntercept, setIsIntercept] = useState(false);
70
+ usePreventRemove(isIntercept, (event) => {
71
+ const { data } = event;
72
+ if (isNavigateBack.current) {
73
+ navigation?.dispatch(data.action);
74
+ }
75
+ else {
71
76
  webViewRef.current?.goBack();
72
- e.preventDefault();
73
77
  }
74
78
  isNavigateBack.current = false;
75
- };
76
- const navigation = useNavigation();
77
- // useEffect(() => {
78
- // let beforeRemoveSubscription:any
79
- // if (__mpx_mode__ !== 'ios') {
80
- // beforeRemoveSubscription = navigation?.addListener?.('beforeRemove', beforeRemoveHandle)
81
- // }
82
- // return () => {
83
- // if (isFunction(beforeRemoveSubscription)) {
84
- // beforeRemoveSubscription()
85
- // }
86
- // }
87
- // }, [])
79
+ });
88
80
  useNodesRef(props, ref, webViewRef, {
89
81
  style: defaultWebViewStyle
90
82
  });
@@ -131,13 +123,13 @@ const _WebView = forwardRef((props, ref) => {
131
123
  };
132
124
  const _changeUrl = function (navState) {
133
125
  if (navState.navigationType) { // navigationType这个事件在页面开始加载时和页面加载完成时都会被触发所以判断这个避免其他无效触发执行该逻辑
134
- canGoBack.current = navState.canGoBack;
135
126
  currentPage.__webViewUrl = navState.url;
127
+ setIsIntercept(navState.canGoBack);
136
128
  }
137
129
  };
138
130
  const _onLoadProgress = function (event) {
139
131
  if (__mpx_mode__ !== 'ios') {
140
- canGoBack.current = event.nativeEvent.canGoBack;
132
+ setIsIntercept(event.nativeEvent.canGoBack);
141
133
  }
142
134
  };
143
135
  const _message = function (res) {
@@ -227,7 +219,6 @@ const _WebView = forwardRef((props, ref) => {
227
219
  };
228
220
  const onLoadEndHandle = function (res) {
229
221
  fristLoaded.current = true;
230
- setIsLoaded(true);
231
222
  const src = res.nativeEvent?.url;
232
223
  if (isLoadError.current) {
233
224
  isLoadError.current = false;
@@ -275,18 +266,13 @@ const _WebView = forwardRef((props, ref) => {
275
266
  setPageLoadErr(true);
276
267
  }
277
268
  };
278
- const onLoadStart = function () {
279
- if (!fristLoaded.current) {
280
- setIsLoaded(false);
281
- }
282
- };
283
269
  return (<Portal>
284
270
  {pageLoadErr
285
271
  ? (<View style={[styles.loadErrorContext, defaultWebViewStyle]}>
286
272
  <View style={styles.loadErrorText}><Text style={{ fontSize: 14, color: '#999999' }}>{currentErrorText.text}</Text></View>
287
273
  <View style={styles.loadErrorButton} onTouchEnd={_reload}><Text style={{ fontSize: 12, color: '#666666' }}>{currentErrorText.button}</Text></View>
288
274
  </View>)
289
- : (<WebView style={defaultWebViewStyle} pointerEvents={isLoaded ? 'auto' : 'none'} source={{ uri: src }} ref={webViewRef} javaScriptEnabled={true} onNavigationStateChange={_changeUrl} onMessage={_message} injectedJavaScript={injectedJavaScript} onLoadProgress={_onLoadProgress} onLoadEnd={onLoadEnd} onHttpError={onHttpError} onError={onError} onLoadStart={onLoadStart} allowsBackForwardNavigationGestures={true}></WebView>)}
275
+ : (<WebView style={defaultWebViewStyle} source={{ uri: src }} ref={webViewRef} javaScriptEnabled={true} onNavigationStateChange={_changeUrl} onMessage={_message} injectedJavaScript={injectedJavaScript} onLoadProgress={_onLoadProgress} onLoadEnd={onLoadEnd} onHttpError={onHttpError} onError={onError} allowsBackForwardNavigationGestures={true}></WebView>)}
290
276
  </Portal>);
291
277
  });
292
278
  _WebView.displayName = 'MpxWebview';