@mpxjs/core 2.10.7 → 2.10.9

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.
package/@types/index.d.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  /// <reference path="./global.d.ts" />
8
8
  /// <reference path="./node.d.ts" />
9
9
 
10
- import { GetComputedType } from '@mpxjs/store'
10
+ import type { GetComputedType } from '@mpxjs/store'
11
11
 
12
12
  export * from '@mpxjs/store'
13
13
 
@@ -255,11 +255,22 @@ interface AnyConstructor {
255
255
  prototype: any
256
256
  }
257
257
 
258
- interface WebviewConfig {
258
+ export interface WebviewConfig {
259
259
  hostWhitelists?: Array<string>
260
260
  apiImplementations?: object
261
261
  }
262
262
 
263
+ export interface RnConfig {
264
+ onStateChange?: (state: any) => void
265
+ parseAppProps?: (props: any) => ({ initialRouteName?: string, initialParams?: any } | undefined | null | void)
266
+ /**
267
+ * 外层可能会异常设置此配置,因此加载监听函数内部
268
+ */
269
+ disableAppStateListener?: boolean
270
+ /** 进入页面是否控制回退按钮的展示以及监听回退按钮的点击 */
271
+ onStackTopBack?: () => void
272
+ }
273
+
263
274
  interface MpxConfig {
264
275
  useStrictDiff: boolean
265
276
  ignoreWarning: boolean | string | RegExp | ((msg: string, location: string, e: Error) => boolean)
@@ -272,8 +283,14 @@ interface MpxConfig {
272
283
  forceFlushSync: boolean,
273
284
  webRouteConfig: object,
274
285
  webConfig: object,
286
+ /*
287
+ * 支持两个属性
288
+ * hostWhitelists Array 类型 支持h5域名白名单安全校验
289
+ * apiImplementations webview JSSDK接口 例如getlocation
290
+ */
275
291
  webviewConfig: WebviewConfig,
276
- rnConfig: object,
292
+ /** react-native 相关配置,用于挂载事件等,如 onShareAppMessage */
293
+ rnConfig?: RnConfig,
277
294
  }
278
295
 
279
296
  type SupportedMode = 'wx' | 'ali' | 'qq' | 'swan' | 'tt' | 'web' | 'qa'
@@ -664,9 +681,15 @@ export const SERVERPREFETCH: string
664
681
  export const REACTHOOKSEXEC: string
665
682
 
666
683
  declare global {
684
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
685
+ // @ts-expect-error
667
686
  const defineProps: (<T extends Properties = {}>(props: T) => Readonly<GetPropsType<T>>) & (<T>() => Readonly<T>)
668
687
  const defineOptions: <D extends Data = {}, P extends Properties = {}, C = {}, M extends Methods = {}, Mi extends Array<any> = [], S extends AnyObject = {}, O extends AnyObject = {}> (opt: ThisTypedComponentOpt<D, P, C, M, Mi, S, O>) => void
688
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
689
+ // @ts-expect-error
669
690
  const defineExpose: <E extends AnyObject = AnyObject>(exposed?: E) => void
670
691
  const useContext: () => Context
692
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
693
+ // @ts-expect-error
671
694
  const withDefaults: <Props, Defaults extends InferDefaults<Props>>(props: Props, defaults: Defaults) => PropsWithDefaults<Props, Defaults>
672
695
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mpxjs/core",
3
- "version": "2.10.7",
3
+ "version": "2.10.9",
4
4
  "description": "mpx runtime core",
5
5
  "keywords": [
6
6
  "miniprogram",
@@ -19,7 +19,7 @@
19
19
  ],
20
20
  "main": "src/index.js",
21
21
  "dependencies": {
22
- "@mpxjs/utils": "^2.10.6",
22
+ "@mpxjs/utils": "^2.10.8",
23
23
  "lodash": "^4.1.1",
24
24
  "miniprogram-api-typings": "^3.10.0"
25
25
  },
@@ -109,5 +109,5 @@
109
109
  "url": "https://github.com/didi/mpx/issues"
110
110
  },
111
111
  "sideEffects": false,
112
- "gitHead": "3c56726c27464abac9cea343167d1b40933fff0d"
112
+ "gitHead": "be35dbe5958da40bf149768171798b4776e63937"
113
113
  }
package/src/index.js CHANGED
@@ -115,6 +115,9 @@ function use (plugin, options = {}) {
115
115
 
116
116
  APIs.use = use
117
117
 
118
+ /**
119
+ * @returns {import('@mpxjs/core').Mpx}
120
+ */
118
121
  function factory () {
119
122
  // 作为原型挂载属性的中间层
120
123
  function Mpx () {
@@ -125,6 +128,9 @@ function factory () {
125
128
  return Mpx
126
129
  }
127
130
 
131
+ /**
132
+ * @type {import('@mpxjs/core').Mpx}
133
+ */
128
134
  const Mpx = factory()
129
135
 
130
136
  Mpx.config = {
@@ -4,7 +4,7 @@ export default function pageRouteMixin (mixinType) {
4
4
  if (mixinType === 'page') {
5
5
  return {
6
6
  [BEFORECREATE] () {
7
- const mpxEventChannel = global.__mpxEventChannel
7
+ const mpxEventChannel = global.__mpxEventChannel || {}
8
8
  if (mpxEventChannel.route === this.route) {
9
9
  this._eventChannel = mpxEventChannel.eventChannel
10
10
  } else {
@@ -2,6 +2,9 @@ import { isObject, isArray, dash2hump, cached, isEmptyObject } from '@mpxjs/util
2
2
  import { Dimensions, StyleSheet } from 'react-native'
3
3
 
4
4
  let { width, height } = Dimensions.get('screen')
5
+ // TODO 临时适配折叠屏场景适配
6
+ const isLargeFoldableLike = (__mpx_mode__ === 'android') && (height / width < 1.5) && (width > 600)
7
+ if (isLargeFoldableLike) width = width / 2
5
8
 
6
9
  Dimensions.addEventListener('change', ({ screen }) => {
7
10
  width = screen.width
@@ -53,44 +53,41 @@ export default function createApp (options) {
53
53
  defaultOptions.onUnhandledRejection && global.__mpxAppCbs.rejection.push(defaultOptions.onUnhandledRejection.bind(appInstance))
54
54
  defaultOptions.onAppInit && defaultOptions.onAppInit()
55
55
 
56
- const pages = currentInject.getPages() || {}
56
+ const pagesMap = currentInject.pagesMap || {}
57
57
  const firstPage = currentInject.firstPage
58
58
  const Stack = createNativeStackNavigator()
59
- const withHeader = (wrappedComponent, { pageConfig = {} }) => {
60
- return ({ navigation, ...props }) => {
61
- return createElement(GestureHandlerRootView,
62
- {
63
- style: {
64
- flex: 1
65
- }
66
- },
67
- createElement(innerNav, {
68
- pageConfig: pageConfig,
69
- navigation
70
- }),
71
- createElement(wrappedComponent, { navigation, ...props })
72
- )
73
- }
74
- }
75
59
  const getPageScreens = (initialRouteName, initialParams) => {
76
- return Object.entries(pages).map(([key, item]) => {
77
- // const options = {
78
- // // __mpxPageStatusMap 为编译注入的全局变量
79
- // headerShown: !(Object.assign({}, global.__mpxPageConfig, global.__mpxPageConfigsMap[key]).navigationStyle === 'custom')
80
- // }
60
+ return Object.entries(pagesMap).map(([key, item]) => {
81
61
  const pageConfig = Object.assign({}, global.__mpxPageConfig, global.__mpxPageConfigsMap[key])
62
+ const headerLayout = ({ navigation, children }) => {
63
+ return createElement(GestureHandlerRootView,
64
+ {
65
+ style: {
66
+ flex: 1
67
+ }
68
+ },
69
+ createElement(innerNav, {
70
+ pageConfig: pageConfig,
71
+ navigation
72
+ }),
73
+ children
74
+ )
75
+ }
76
+ const getComponent = () => {
77
+ return item.displayName ? item : item()
78
+ }
82
79
  if (key === initialRouteName) {
83
80
  return createElement(Stack.Screen, {
84
81
  name: key,
85
- component: withHeader(item, { pageConfig }),
86
- initialParams
87
- // options
82
+ getComponent,
83
+ initialParams,
84
+ layout: headerLayout
88
85
  })
89
86
  }
90
87
  return createElement(Stack.Screen, {
91
88
  name: key,
92
- component: withHeader(item, { pageConfig })
93
- // options
89
+ getComponent,
90
+ layout: headerLayout
94
91
  })
95
92
  })
96
93
  }
@@ -239,7 +236,7 @@ export default function createApp (options) {
239
236
  headerShown: false,
240
237
  statusBarTranslucent: true,
241
238
  statusBarBackgroundColor: 'transparent'
242
- }
239
+ }
243
240
 
244
241
  return createElement(SafeAreaProvider,
245
242
  null,
@@ -10,13 +10,15 @@ export function init (Mpx) {
10
10
  show: [],
11
11
  hide: [],
12
12
  error: [],
13
- rejection: []
13
+ rejection: [],
14
+ lazyLoad: []
14
15
  }
15
16
  global.__navigationHelper = navigationHelper
16
17
  if (global.i18n) {
17
18
  Mpx.i18n = createI18n(global.i18n)
18
19
  }
19
20
  initGlobalErrorHandling()
21
+ initGlobalLazyLoadHandling()
20
22
  }
21
23
 
22
24
  function initGlobalErrorHandling () {
@@ -63,3 +65,13 @@ function initGlobalErrorHandling () {
63
65
  require('promise/setimmediate/rejection-tracking').enable(rejectionTrackingOptions)
64
66
  }
65
67
  }
68
+
69
+ function initGlobalLazyLoadHandling () {
70
+ global.onLazyLoadError = function (error) {
71
+ if (global.__mpxAppCbs?.lazyLoad?.length) {
72
+ global.__mpxAppCbs.lazyLoad.forEach((cb) => {
73
+ cb(error)
74
+ })
75
+ }
76
+ }
77
+ }
@@ -1,6 +1,6 @@
1
- import { createElement, useState, useMemo } from 'react'
1
+ import { createElement, useState, useMemo, memo } from 'react'
2
2
  import { useSafeAreaInsets } from 'react-native-safe-area-context'
3
- import { StatusBar, processColor, TouchableOpacity, Image, View, StyleSheet, Text } from 'react-native'
3
+ import { StatusBar, processColor, TouchableWithoutFeedback, Image, View, StyleSheet, Text } from 'react-native'
4
4
  import Mpx from '../../index'
5
5
 
6
6
  function convertToHex (color) {
@@ -76,7 +76,7 @@ const validBarTextStyle = (textStyle) => {
76
76
  return NavColor.White
77
77
  }
78
78
  }
79
- export function innerNav ({ pageConfig, navigation }) {
79
+ export const innerNav = memo(({ pageConfig, navigation }) => {
80
80
  const [innerPageConfig, setPageConfig] = useState(pageConfig || {})
81
81
  navigation.setPageConfig = (config) => {
82
82
  const newConfig = Object.assign({}, innerPageConfig, config)
@@ -95,35 +95,43 @@ export function innerNav ({ pageConfig, navigation }) {
95
95
  const safeAreaTop = useSafeAreaInsets()?.top || 0
96
96
  // 假设是栈导航,获取栈的长度
97
97
  const stackLength = navigation.getState()?.routes?.length
98
- // 用于外部注册打开RN容器之前的栈长度
99
- const beforeStackLength = Mpx.config?.rnConfig?.beforeStackLength || 0
98
+ const onStackTopBack = Mpx.config?.rnConfig?.onStackTopBack
99
+ const isHandleStackTopBack = typeof onStackTopBack === 'function'
100
100
 
101
101
  // 回退按钮与图标
102
- const backElement = stackLength + beforeStackLength > 1
103
- ? createElement(TouchableOpacity, {
104
- style: [styles.backButton],
105
- onPress: () => { navigation.goBack() }
106
- }, createElement(Image, {
107
- source: { uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAABICAYAAACqT5alAAAA2UlEQVR4nO3bMQrCUBRE0Yla6AYEN2nnBrTL+izcitW3MRDkEUWSvPzJvfCqgMwhZbAppWhNbbIHzB1g9wATERFRVyvpkj1irlpJ5X326D7WHh1hbdFD2CLpLmmftm7kfsEe09aNHFiBrT+wAlt/YAW2/sAKbP2BFdj6Ayuwy+ufz6XPL893krZ//O6iu2n4LT8kndLWTRTo4EC7BDo40C6BDg60S6CDA+0S6OBAuwQ6uNWiD2nrJmoIfU7cNWkR2hbb1UfbY7uuWhGWiIg+a/iHuHmA3QPs3gu4JW9Gan+OJAAAAABJRU5ErkJggg==' },
108
- // 回退按钮的颜色与设置的title文案颜色一致
109
- style: [styles.backButtonImage, { tintColor: navigationBarTextStyle }]
110
- }))
111
- : null
102
+ const backElement = stackLength > 1 || isHandleStackTopBack
103
+ ? createElement(TouchableWithoutFeedback, {
104
+ onPress: () => {
105
+ if (stackLength <= 1 && isHandleStackTopBack) {
106
+ onStackTopBack()
107
+ return
108
+ }
109
+ navigation.goBack()
110
+ }
111
+ }, createElement(View, {
112
+ style: [styles.backButton]
113
+ }, createElement(Image, {
114
+ source: { uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADwAAABICAYAAACqT5alAAAA2UlEQVR4nO3bMQrCUBRE0Yla6AYEN2nnBrTL+izcitW3MRDkEUWSvPzJvfCqgMwhZbAppWhNbbIHzB1g9wATERFRVyvpkj1irlpJ5X326D7WHh1hbdFD2CLpLmmftm7kfsEe09aNHFiBrT+wAlt/YAW2/sAKbP2BFdj6Ayuwy+ufz6XPL893krZ//O6iu2n4LT8kndLWTRTo4EC7BDo40C6BDg60S6CDA+0S6OBAuwQ6uNWiD2nrJmoIfU7cNWkR2hbb1UfbY7uuWhGWiIg+a/iHuHmA3QPs3gu4JW9Gan+OJAAAAABJRU5ErkJggg==' },
115
+ // 回退按钮的颜色与设置的title文案颜色一致
116
+ style: [styles.backButtonImage, { tintColor: navigationBarTextStyle }]
117
+ })
118
+ ))
119
+ : null
112
120
 
113
121
  return createElement(View, {
114
- style: [styles.header, {
115
- paddingTop: safeAreaTop,
116
- backgroundColor: innerPageConfig.navigationBarBackgroundColor || '#000000'
117
- }]
118
- },
119
- statusBarElement,
120
- createElement(View, {
121
- style: styles.headerContent,
122
- height: titleHeight
123
- }, backElement,
122
+ style: [styles.header, {
123
+ paddingTop: safeAreaTop,
124
+ backgroundColor: innerPageConfig.navigationBarBackgroundColor || '#000000'
125
+ }]
126
+ },
127
+ statusBarElement,
128
+ createElement(View, {
129
+ style: styles.headerContent,
130
+ height: titleHeight
131
+ }, backElement,
124
132
  createElement(Text, {
125
133
  style: [styles.title, { color: navigationBarTextStyle }],
126
134
  numberOfLines: 1
127
135
  }, innerPageConfig.navigationBarTitleText?.trim() || ''))
128
- )
129
- }
136
+ )
137
+ })
@@ -1,14 +1,12 @@
1
1
  import { createNativeStackNavigator } from '@react-navigation/native-stack'
2
2
  import { NavigationContainer, StackActions } from '@react-navigation/native'
3
3
  import PortalHost from '@mpxjs/webpack-plugin/lib/runtime/components/react/dist/mpx-portal/portal-host'
4
- import { useHeaderHeight } from '@react-navigation/elements'
5
4
  import { SafeAreaProvider, useSafeAreaInsets } from 'react-native-safe-area-context'
6
5
  import { GestureHandlerRootView } from 'react-native-gesture-handler'
7
6
 
8
7
  export {
9
8
  createNativeStackNavigator,
10
9
  NavigationContainer,
11
- useHeaderHeight,
12
10
  StackActions,
13
11
  GestureHandlerRootView,
14
12
  PortalHost,
@@ -33,7 +33,7 @@ function getSystemInfo () {
33
33
  }
34
34
  }
35
35
 
36
- function createEffect (proxy, components) {
36
+ function createEffect (proxy, componentsMap) {
37
37
  const update = proxy.update = () => {
38
38
  // react update props in child render(async), do not need exec pre render
39
39
  // if (proxy.propsUpdatedFlag) {
@@ -50,10 +50,11 @@ function createEffect (proxy, components) {
50
50
  const getComponent = (tagName) => {
51
51
  if (!tagName) return null
52
52
  if (tagName === 'block') return Fragment
53
- const appComponents = global.__getAppComponents?.() || {}
53
+ const appComponentsMap = global.__appComponentsMap || {}
54
54
  const generichash = proxy.target.generichash || ''
55
- const genericComponents = global.__mpxGenericsMap?.[generichash] || noop
56
- return components[tagName] || genericComponents(tagName) || appComponents[tagName] || getByPath(ReactNative, tagName)
55
+ const genericComponentsMap = global.__mpxGenericsMap?.[generichash] || {}
56
+ const component = componentsMap[tagName] || genericComponentsMap[tagName] || appComponentsMap[tagName]
57
+ return component ? component.displayName ? component : component() : getByPath(ReactNative, tagName)
57
58
  }
58
59
  const innerCreateElement = (type, ...rest) => {
59
60
  if (!type) return null
@@ -123,6 +124,13 @@ const instanceProto = {
123
124
  createIntersectionObserver (opt) {
124
125
  return createIntersectionObserver(this, opt, this.__intersectionCtx)
125
126
  },
127
+ // 触发页面范围内的所有observer的计算
128
+ __triggerIntersectionObserver () {
129
+ const intersectionObservers = this.__intersectionCtx
130
+ for (const key in this.__intersectionCtx) {
131
+ intersectionObservers[key].throttleMeasure()
132
+ }
133
+ },
126
134
  __resetInstance () {
127
135
  this.__dispatchedSlotSet = new WeakSet()
128
136
  },
@@ -203,7 +211,7 @@ const instanceProto = {
203
211
  }
204
212
  }
205
213
 
206
- function createInstance ({ propsRef, type, rawOptions, currentInject, validProps, components, pageId, intersectionCtx, relation, parentProvides }) {
214
+ function createInstance ({ propsRef, type, rawOptions, currentInject, validProps, componentsMap, pageId, intersectionCtx, relation, parentProvides }) {
207
215
  const instance = Object.create(instanceProto, {
208
216
  dataset: {
209
217
  get () {
@@ -304,7 +312,14 @@ function createInstance ({ propsRef, type, rawOptions, currentInject, validProps
304
312
 
305
313
  if (type === 'page') {
306
314
  const props = propsRef.current
307
- proxy.callHook(ONLOAD, [props.route.params || {}])
315
+ const loadParams = {}
316
+ // 此处拿到的props.route.params内属性的value被进行过了一次decode, 不符合预期,此处额外进行一次encode来与微信对齐
317
+ if (isObject(props.route.params)) {
318
+ for (const key in props.route.params) {
319
+ loadParams[key] = encodeURIComponent(props.route.params[key])
320
+ }
321
+ }
322
+ proxy.callHook(ONLOAD, [loadParams])
308
323
  }
309
324
 
310
325
  Object.assign(proxy, {
@@ -312,7 +327,7 @@ function createInstance ({ propsRef, type, rawOptions, currentInject, validProps
312
327
  stateVersion: Symbol(),
313
328
  subscribe: (onStoreChange) => {
314
329
  if (!proxy.effect) {
315
- createEffect(proxy, components)
330
+ createEffect(proxy, componentsMap)
316
331
  proxy.stateVersion = Symbol()
317
332
  }
318
333
  proxy.onStoreChange = onStoreChange
@@ -328,7 +343,7 @@ function createInstance ({ propsRef, type, rawOptions, currentInject, validProps
328
343
  })
329
344
  // react数据响应组件更新管理器
330
345
  if (!proxy.effect) {
331
- createEffect(proxy, components)
346
+ createEffect(proxy, componentsMap)
332
347
  }
333
348
 
334
349
  return instance
@@ -419,6 +434,26 @@ function usePageStatus (navigation, pageId) {
419
434
  }, [navigation])
420
435
  }
421
436
 
437
+ function usePagePreload (route) {
438
+ const name = route.name
439
+ useEffect(() => {
440
+ const timer = setTimeout(() => {
441
+ const preloadRule = global.__preloadRule || {}
442
+ const { packages } = preloadRule[name] || {}
443
+ if (packages?.length > 0) {
444
+ const downloadChunkAsync = mpxGlobal.__mpx.config?.rnConfig?.downloadChunkAsync
445
+ if (typeof downloadChunkAsync === 'function') {
446
+ callWithErrorHandling(() => downloadChunkAsync(packages))
447
+ }
448
+ }
449
+ }, 800)
450
+
451
+ return () => {
452
+ clearTimeout(timer)
453
+ }
454
+ }, [])
455
+ }
456
+
422
457
  const RelationsContext = createContext(null)
423
458
 
424
459
  const checkRelation = (options) => {
@@ -485,6 +520,7 @@ export function PageWrapperHOC (WrappedComponent, pageConfig = {}) {
485
520
  return () => dimensionListener?.remove()
486
521
  }, [])
487
522
 
523
+ usePagePreload(route)
488
524
  usePageStatus(navigation, currentPageId)
489
525
 
490
526
  const withKeyboardAvoidingView = (element) => {
@@ -543,7 +579,12 @@ export function PageWrapperHOC (WrappedComponent, pageConfig = {}) {
543
579
  }
544
580
  export function getDefaultOptions ({ type, rawOptions = {}, currentInject }) {
545
581
  rawOptions = mergeOptions(rawOptions, type, false)
546
- const components = Object.assign({}, rawOptions.components, currentInject.getComponents())
582
+ const componentsMap = currentInject.componentsMap
583
+ if (rawOptions.components) {
584
+ Object.entries(rawOptions.components).forEach(([key, item]) => {
585
+ componentsMap[key] = () => item
586
+ })
587
+ }
547
588
  const validProps = Object.assign({}, rawOptions.props, rawOptions.properties)
548
589
  const { hasDescendantRelation, hasAncestorRelation } = checkRelation(rawOptions)
549
590
  if (rawOptions.methods) rawOptions.methods = wrapMethodsWithErrorHandling(rawOptions.methods)
@@ -561,7 +602,7 @@ export function getDefaultOptions ({ type, rawOptions = {}, currentInject }) {
561
602
  let isFirst = false
562
603
  if (!instanceRef.current) {
563
604
  isFirst = true
564
- instanceRef.current = createInstance({ propsRef, type, rawOptions, currentInject, validProps, components, pageId, intersectionCtx, relation, parentProvides })
605
+ instanceRef.current = createInstance({ propsRef, type, rawOptions, currentInject, validProps, componentsMap, pageId, intersectionCtx, relation, parentProvides })
565
606
  }
566
607
  const instance = instanceRef.current
567
608
  useImperativeHandle(ref, () => {
@@ -608,7 +649,6 @@ export function getDefaultOptions ({ type, rawOptions = {}, currentInject }) {
608
649
  })
609
650
 
610
651
  usePageEffect(proxy, pageId)
611
-
612
652
  useEffect(() => {
613
653
  proxy.mounted()
614
654
  return () => {
@@ -89,8 +89,8 @@ export function getDefaultOptions ({ type, rawOptions = {} }) {
89
89
  },
90
90
  destroyed () {
91
91
  if (this.__mpxProxy) {
92
- this.__mpxProxy.state = UNMOUNTED
93
92
  this.__mpxProxy.callHook(UNMOUNTED)
93
+ this.__mpxProxy.state = UNMOUNTED
94
94
  }
95
95
  },
96
96
  serverPrefetch (...args) {