@mpxjs/webpack-plugin 2.10.7 → 2.10.8

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 (43) hide show
  1. package/lib/dependencies/RecordPageConfigsMapDependency.js +1 -1
  2. package/lib/dependencies/RequireExternalDependency.js +61 -0
  3. package/lib/file-loader.js +3 -2
  4. package/lib/index.js +55 -9
  5. package/lib/json-compiler/index.js +1 -0
  6. package/lib/parser.js +1 -1
  7. package/lib/platform/json/wx/index.js +43 -25
  8. package/lib/platform/style/wx/index.js +7 -0
  9. package/lib/platform/template/wx/component-config/fix-component-name.js +2 -2
  10. package/lib/platform/template/wx/component-config/index.js +5 -1
  11. package/lib/platform/template/wx/component-config/sticky-header.js +23 -0
  12. package/lib/platform/template/wx/component-config/sticky-section.js +23 -0
  13. package/lib/react/LoadAsyncChunkModule.js +74 -0
  14. package/lib/react/index.js +3 -1
  15. package/lib/react/processJSON.js +74 -13
  16. package/lib/react/processScript.js +6 -6
  17. package/lib/react/script-helper.js +100 -41
  18. package/lib/runtime/components/react/context.ts +12 -3
  19. package/lib/runtime/components/react/dist/context.js +4 -1
  20. package/lib/runtime/components/react/dist/mpx-async-suspense.jsx +135 -0
  21. package/lib/runtime/components/react/dist/mpx-button.jsx +2 -2
  22. package/lib/runtime/components/react/dist/mpx-movable-view.jsx +8 -6
  23. package/lib/runtime/components/react/dist/mpx-scroll-view.jsx +31 -15
  24. package/lib/runtime/components/react/dist/mpx-sticky-header.jsx +117 -0
  25. package/lib/runtime/components/react/dist/mpx-sticky-section.jsx +45 -0
  26. package/lib/runtime/components/react/mpx-async-suspense.tsx +180 -0
  27. package/lib/runtime/components/react/mpx-button.tsx +3 -2
  28. package/lib/runtime/components/react/mpx-movable-view.tsx +8 -4
  29. package/lib/runtime/components/react/mpx-scroll-view.tsx +84 -59
  30. package/lib/runtime/components/react/mpx-sticky-header.tsx +181 -0
  31. package/lib/runtime/components/react/mpx-sticky-section.tsx +96 -0
  32. package/lib/runtime/components/web/mpx-scroll-view.vue +18 -4
  33. package/lib/runtime/components/web/mpx-sticky-header.vue +99 -0
  34. package/lib/runtime/components/web/mpx-sticky-section.vue +15 -0
  35. package/lib/runtime/optionProcessorReact.d.ts +18 -0
  36. package/lib/runtime/optionProcessorReact.js +30 -0
  37. package/lib/script-setup-compiler/index.js +27 -5
  38. package/lib/template-compiler/bind-this.js +2 -1
  39. package/lib/template-compiler/compiler.js +4 -3
  40. package/lib/utils/dom-tag-config.js +17 -3
  41. package/lib/utils/trans-async-sub-rules.js +19 -0
  42. package/lib/web/script-helper.js +1 -1
  43. package/package.json +4 -4
@@ -8,11 +8,15 @@ const addQuery = require('../utils/add-query')
8
8
  const parseComponent = require('../parser')
9
9
  const getJSONContent = require('../utils/get-json-content')
10
10
  const resolve = require('../utils/resolve')
11
+ const { transSubpackage } = require('../utils/trans-async-sub-rules')
11
12
  const createJSONHelper = require('../json-compiler/helper')
12
13
  const getRulesRunner = require('../platform/index')
13
14
  const { RESOLVE_IGNORED_ERR } = require('../utils/const')
15
+ const normalize = require('../utils/normalize')
14
16
  const RecordResourceMapDependency = require('../dependencies/RecordResourceMapDependency')
15
17
  const RecordPageConfigsMapDependency = require('../dependencies/RecordPageConfigsMapDependency')
18
+ const mpxViewPath = normalize.lib('runtime/components/react/dist/mpx-view.jsx')
19
+ const mpxTextPath = normalize.lib('runtime/components/react/dist/mpx-text.jsx')
16
20
 
17
21
  module.exports = function (jsonContent, {
18
22
  loaderContext,
@@ -133,6 +137,45 @@ module.exports = function (jsonContent, {
133
137
  isShow: true
134
138
  }
135
139
 
140
+ const fillInComponentPlaceholder = (name, placeholder, placeholderEntry) => {
141
+ const componentPlaceholder = jsonObj.componentPlaceholder || {}
142
+ if (componentPlaceholder[name]) return
143
+ componentPlaceholder[name] = placeholder
144
+ jsonObj.componentPlaceholder = componentPlaceholder
145
+ if (placeholderEntry && !jsonObj.usingComponents[placeholder]) jsonObj.usingComponents[placeholder] = placeholderEntry
146
+ }
147
+
148
+ const fillInComponentsMap = (name, entry, tarRoot) => {
149
+ const { resource, outputPath } = entry
150
+ const { resourcePath } = parseRequest(resource)
151
+ tarRoot = transSubpackage(mpx.transSubpackageRules, tarRoot)
152
+ componentsMap[resourcePath] = outputPath
153
+ loaderContext._module && loaderContext._module.addPresentationalDependency(new RecordResourceMapDependency(resourcePath, 'component', outputPath))
154
+ localComponentsMap[name] = {
155
+ resource: addQuery(resource, {
156
+ isComponent: true,
157
+ outputPath
158
+ }),
159
+ async: tarRoot
160
+ }
161
+ }
162
+
163
+ const normalizePlaceholder = (placeholder) => {
164
+ if (typeof placeholder === 'string') {
165
+ const placeholderMap = mode === 'ali'
166
+ ? {
167
+ view: { name: 'mpx-view', resource: mpxViewPath },
168
+ text: { name: 'mpx-text', resource: mpxTextPath }
169
+ }
170
+ : {}
171
+ placeholder = placeholderMap[placeholder] || { name: placeholder }
172
+ }
173
+ if (!placeholder.name) {
174
+ emitError('The asyncSubpackageRules configuration format of @mpxjs/webpack-plugin a is incorrect')
175
+ }
176
+ return placeholder
177
+ }
178
+
136
179
  const processTabBar = (tabBar, callback) => {
137
180
  if (tabBar) {
138
181
  tabBar = Object.assign({}, defaultTabbar, tabBar)
@@ -247,7 +290,7 @@ module.exports = function (jsonContent, {
247
290
  if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err)
248
291
  if (pageKeySet.has(key)) return callback()
249
292
  pageKeySet.add(key)
250
- const { resourcePath, queryObj } = parseRequest(resource)
293
+ const { resourcePath } = parseRequest(resource)
251
294
  if (localPagesMap[outputPath]) {
252
295
  const { resourcePath: oldResourcePath } = parseRequest(localPagesMap[outputPath].resource)
253
296
  if (oldResourcePath !== resourcePath) {
@@ -259,9 +302,11 @@ module.exports = function (jsonContent, {
259
302
 
260
303
  pagesMap[resourcePath] = outputPath
261
304
  loaderContext._module && loaderContext._module.addPresentationalDependency(new RecordResourceMapDependency(resourcePath, 'page', outputPath))
305
+ // 通过asyncSubPackagesNameRules对tarRoot进行修改,仅修改tarRoot,不修改outputPath页面路径
306
+ tarRoot = transSubpackage(mpx.transSubpackageRules, tarRoot)
262
307
  localPagesMap[outputPath] = {
263
308
  resource: addQuery(resource, { isPage: true }),
264
- async: queryObj.async || tarRoot,
309
+ async: tarRoot,
265
310
  isFirst
266
311
  }
267
312
  callback()
@@ -301,19 +346,35 @@ module.exports = function (jsonContent, {
301
346
  const processComponents = (components, context, callback) => {
302
347
  if (components) {
303
348
  async.eachOf(components, (component, name, callback) => {
304
- processComponent(component, context, {}, (err, { resource, outputPath } = {}, { tarRoot } = {}) => {
349
+ processComponent(component, context, {}, (err, entry = {}, { tarRoot, placeholder } = {}) => {
305
350
  if (err) return callback(err === RESOLVE_IGNORED_ERR ? null : err)
306
- const { resourcePath, queryObj } = parseRequest(resource)
307
- componentsMap[resourcePath] = outputPath
308
- loaderContext._module && loaderContext._module.addPresentationalDependency(new RecordResourceMapDependency(resourcePath, 'component', outputPath))
309
- localComponentsMap[name] = {
310
- resource: addQuery(resource, {
311
- isComponent: true,
312
- outputPath
313
- }),
314
- async: queryObj.async || tarRoot
351
+ fillInComponentsMap(name, entry, tarRoot)
352
+ const { relativePath } = entry
353
+
354
+ if (tarRoot) {
355
+ if (placeholder) {
356
+ placeholder = normalizePlaceholder(placeholder)
357
+ if (placeholder.resource) {
358
+ processComponent(placeholder.resource, projectRoot, { relativePath }, (err, entry) => {
359
+ if (err) return callback(err)
360
+ fillInComponentPlaceholder(name, placeholder.name, entry)
361
+ fillInComponentsMap(placeholder.name, entry, '')
362
+ callback()
363
+ })
364
+ } else {
365
+ fillInComponentPlaceholder(name, placeholder.name)
366
+ callback()
367
+ }
368
+ } else {
369
+ if (!jsonObj.componentPlaceholder || !jsonObj.componentPlaceholder[name]) {
370
+ const errMsg = `componentPlaceholder of "${name}" doesn't exist! \n\r`
371
+ emitError(errMsg)
372
+ }
373
+ callback()
374
+ }
375
+ } else {
376
+ callback()
315
377
  }
316
- callback()
317
378
  })
318
379
  }, callback)
319
380
  } else {
@@ -13,6 +13,7 @@ module.exports = function (script, {
13
13
  builtInComponentsMap,
14
14
  localComponentsMap,
15
15
  localPagesMap,
16
+ rnConfig,
16
17
  componentGenerics,
17
18
  genericsInfo
18
19
  }, callback) {
@@ -34,12 +35,13 @@ module.exports = function (script, {
34
35
  let output = '/* script */\n'
35
36
  if (ctorType === 'app') {
36
37
  output += `
37
- import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPath)}
38
+ import { getComponent, getAsyncSuspense } from ${stringifyRequest(loaderContext, optionProcessorPath)}
38
39
  \n`
39
40
  const { pagesMap, firstPage } = buildPagesMap({
40
41
  localPagesMap,
41
42
  loaderContext,
42
- jsonConfig
43
+ jsonConfig,
44
+ rnConfig
43
45
  })
44
46
  const componentsMap = buildComponentsMap({
45
47
  localComponentsMap,
@@ -50,9 +52,7 @@ import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPa
50
52
  output += getRequireScript({ ctorType, script, loaderContext })
51
53
  output += `export default global.__mpxOptionsMap[${JSON.stringify(moduleId)}]\n`
52
54
  } else {
53
- // RN环境暂不支持异步加载
54
- // output += 'import { lazy } from \'react\'\n'
55
- output += `import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPath)}\n`
55
+ output += `import { getComponent, getAsyncSuspense } from ${stringifyRequest(loaderContext, optionProcessorPath)}\n`
56
56
  // 获取组件集合
57
57
  const componentsMap = buildComponentsMap({
58
58
  localComponentsMap,
@@ -61,7 +61,7 @@ import { getComponent } from ${stringifyRequest(loaderContext, optionProcessorPa
61
61
  jsonConfig
62
62
  })
63
63
 
64
- output += buildGlobalParams({ moduleId, scriptSrcMode, loaderContext, isProduction, ctorType, jsonConfig, componentsMap, outputPath, genericsInfo, componentGenerics })
64
+ output += buildGlobalParams({ moduleId, scriptSrcMode, loaderContext, isProduction, ctorType, jsonConfig, componentsMap, outputPath, genericsInfo, componentGenerics, hasApp })
65
65
  output += getRequireScript({ ctorType, script, loaderContext })
66
66
  output += `export default global.__mpxOptionsMap[${JSON.stringify(moduleId)}]\n`
67
67
  }
@@ -3,30 +3,71 @@ const createHelpers = require('../helpers')
3
3
  const parseRequest = require('../utils/parse-request')
4
4
  const shallowStringify = require('../utils/shallow-stringify')
5
5
  const normalize = require('../utils/normalize')
6
+ const addQuery = require('../utils/add-query')
7
+ const { isBuildInReactTag } = require('../utils/dom-tag-config')
6
8
 
7
9
  function stringifyRequest (loaderContext, request) {
8
10
  return loaderUtils.stringifyRequest(loaderContext, request)
9
11
  }
10
12
 
11
- // function getAsyncChunkName (chunkName) {
12
- // if (chunkName && typeof chunkName !== 'boolean') {
13
- // return `/* webpackChunkName: "${chunkName}" */`
14
- // }
15
- // return ''
13
+ function getBuiltInComponentRequest (component) {
14
+ return JSON.stringify(addQuery(`@mpxjs/webpack-plugin/lib/runtime/components/react/dist/${component}`, { isComponent: true }))
15
+ }
16
+
17
+ function getAsyncChunkName (chunkName) {
18
+ if (chunkName && typeof chunkName !== 'boolean') {
19
+ return `/* webpackChunkName: "${chunkName}/index" */`
20
+ }
21
+ return ''
22
+ }
23
+
24
+ function getAsyncSuspense (type, moduleId, componentRequest, componentName, chunkName, fallback, loading) {
25
+ return `getAsyncSuspense({
26
+ type: ${JSON.stringify(type)},
27
+ moduleId: ${JSON.stringify(moduleId)},
28
+ chunkName: ${JSON.stringify(chunkName)},
29
+ loading: ${loading},
30
+ fallback: ${fallback},
31
+ getChildren () {
32
+ return import(${getAsyncChunkName(chunkName)}${componentRequest}).then(function (res) {
33
+ return getComponent(res, {displayName: ${JSON.stringify(componentName)}})
34
+ })
35
+ }
36
+ })`
37
+ }
38
+
39
+ function getComponent (componentRequest, componentName) {
40
+ return `getComponent(require(${componentRequest}), {displayName: ${JSON.stringify(componentName)}})`
41
+ }
42
+
43
+ function getBuiltInComponent (componentRequest) {
44
+ return `getComponent(require(${componentRequest}), {__mpxBuiltIn: true})`
45
+ }
46
+
47
+ // function getLazyPage (componentRequest) {
48
+ // return `getLazyPage(${getComponentGetter(getComponent(componentRequest, 'Page'))})`
16
49
  // }
17
50
 
18
- function buildPagesMap ({ localPagesMap, loaderContext, jsonConfig }) {
51
+ function getComponentGetter (component) {
52
+ return `function(){ return ${component} }`
53
+ }
54
+
55
+ function buildPagesMap ({ localPagesMap, loaderContext, jsonConfig, rnConfig }) {
19
56
  let firstPage = ''
20
57
  const pagesMap = {}
58
+ const mpx = loaderContext.getMpx()
21
59
  Object.keys(localPagesMap).forEach((pagePath) => {
22
60
  const pageCfg = localPagesMap[pagePath]
23
61
  const pageRequest = stringifyRequest(loaderContext, pageCfg.resource)
24
- // if (pageCfg.async) {
25
- // pagesMap[pagePath] = `lazy(function(){return import(${getAsyncChunkName(pageCfg.async)} ${pageRequest}).then(function(res){return getComponent(res, {__mpxPageRoute: ${JSON.stringify(pagePath)}, displayName: "Page"})})})`
26
- // } else {
27
- // 为了保持小程序中app->page->component的js执行顺序,所有的page和component都改为require引入
28
- pagesMap[pagePath] = `getComponent(require(${pageRequest}), {__mpxPageRoute: ${JSON.stringify(pagePath)}, displayName: "Page"})`
29
- // }
62
+ if (pageCfg.async) {
63
+ const moduleId = mpx.getModuleId(pageCfg.resource)
64
+ const fallback = rnConfig.asyncChunk && rnConfig.asyncChunk.fallback && getComponent(stringifyRequest(loaderContext, addQuery(rnConfig.asyncChunk.fallback, { isComponent: true })), 'PageFallback')
65
+ const loading = rnConfig.asyncChunk && rnConfig.asyncChunk.loading && getComponent(stringifyRequest(loaderContext, addQuery(rnConfig.asyncChunk.loading, { isComponent: true })), 'PageLoading')
66
+ pagesMap[pagePath] = getComponentGetter(getAsyncSuspense('page', moduleId, pageRequest, 'Page', pageCfg.async, fallback, loading))
67
+ } else {
68
+ // 为了保持小程序中app->page->component的js执行顺序,所有的page和component都改为require引入
69
+ pagesMap[pagePath] = getComponentGetter(getComponent(pageRequest, 'Page'))
70
+ }
30
71
  if (pagePath === jsonConfig.entryPagePath) {
31
72
  firstPage = pagePath
32
73
  }
@@ -42,30 +83,58 @@ function buildPagesMap ({ localPagesMap, loaderContext, jsonConfig }) {
42
83
 
43
84
  function buildComponentsMap ({ localComponentsMap, builtInComponentsMap, loaderContext, jsonConfig }) {
44
85
  const componentsMap = {}
86
+ const mpx = loaderContext.getMpx()
45
87
  if (localComponentsMap) {
46
88
  Object.keys(localComponentsMap).forEach((componentName) => {
47
89
  const componentCfg = localComponentsMap[componentName]
48
90
  const componentRequest = stringifyRequest(loaderContext, componentCfg.resource)
49
- // RN中暂不支持异步加载
50
- // if (componentCfg.async) {
51
- // componentsMap[componentName] = `lazy(function(){return import(${getAsyncChunkName(componentCfg.async)}${componentRequest}).then(function(res){return getComponent(res, {displayName: ${JSON.stringify(componentName)}})})})`
52
- // } else {
53
- componentsMap[componentName] = `getComponent(require(${componentRequest}), {displayName: ${JSON.stringify(componentName)}})`
54
- // }
91
+ if (componentCfg.async) {
92
+ const moduleId = mpx.getModuleId(componentCfg.resource)
93
+ const placeholder = jsonConfig.componentPlaceholder && jsonConfig.componentPlaceholder[componentName]
94
+ let fallback
95
+ if (placeholder) {
96
+ if (localComponentsMap[placeholder]) {
97
+ const placeholderCfg = localComponentsMap[placeholder]
98
+ const placeholderRequest = stringifyRequest(loaderContext, placeholderCfg.resource)
99
+ if (placeholderCfg.async) {
100
+ loaderContext.emitWarning(
101
+ new Error(`[json processor][${loaderContext.resource}]: componentPlaceholder ${placeholder} should not be a async component, please check!`)
102
+ )
103
+ }
104
+ fallback = getComponent(placeholderRequest, placeholder)
105
+ } else {
106
+ const tag = `mpx-${placeholder}`
107
+ if (isBuildInReactTag(tag)) {
108
+ fallback = getBuiltInComponent(getBuiltInComponentRequest(tag))
109
+ } else {
110
+ loaderContext.emitError(
111
+ new Error(`[json processor][${loaderContext.resource}]: componentPlaceholder ${placeholder} is not built-in component, please check!`)
112
+ )
113
+ }
114
+ }
115
+ } else {
116
+ loaderContext.emitError(
117
+ new Error(`[json processor][${loaderContext.resource}]: ${componentName} has no componentPlaceholder, please check!`)
118
+ )
119
+ }
120
+ componentsMap[componentName] = getComponentGetter(getAsyncSuspense('component', moduleId, componentRequest, componentName, componentCfg.async, fallback))
121
+ } else {
122
+ componentsMap[componentName] = getComponentGetter(getComponent(componentRequest, componentName))
123
+ }
55
124
  })
56
125
  }
57
126
  if (builtInComponentsMap) {
58
127
  Object.keys(builtInComponentsMap).forEach((componentName) => {
59
128
  const componentCfg = builtInComponentsMap[componentName]
60
129
  const componentRequest = stringifyRequest(loaderContext, componentCfg.resource)
61
- componentsMap[componentName] = `getComponent(require(${componentRequest}), {__mpxBuiltIn: true})`
130
+ componentsMap[componentName] = getComponentGetter(getBuiltInComponent(componentRequest))
62
131
  })
63
132
  }
64
133
  return componentsMap
65
134
  }
66
135
 
67
136
  function getRequireScript ({ script, ctorType, loaderContext }) {
68
- let content = ' /** script content **/\n'
137
+ let content = '/** script content **/\n'
69
138
  const { getRequire } = createHelpers(loaderContext)
70
139
  const { resourcePath, queryObj } = parseRequest(loaderContext.resource)
71
140
  const extraOptions = {
@@ -75,7 +144,7 @@ function getRequireScript ({ script, ctorType, loaderContext }) {
75
144
  ctorType,
76
145
  lang: script.lang || 'js'
77
146
  }
78
- content += ` ${getRequire('script', script, extraOptions)}\n`
147
+ content += `${getRequire('script', script, extraOptions)}\n`
79
148
  return content
80
149
  }
81
150
 
@@ -104,17 +173,11 @@ global.__mpxOptionsMap = {}
104
173
  global.__mpxPagesMap = {}
105
174
  global.__style = ${JSON.stringify(jsonConfig.style || 'v1')}
106
175
  global.__mpxPageConfig = ${JSON.stringify(jsonConfig.window)}
107
- global.__getAppComponents = function () {
108
- return ${shallowStringify(componentsMap)}
109
- }
110
- global.currentInject.getPages = function () {
111
- return ${shallowStringify(pagesMap)}
112
- }
176
+ global.__appComponentsMap = ${shallowStringify(componentsMap)}
177
+ global.__preloadRule = ${JSON.stringify(jsonConfig.preloadRule)}
178
+ global.currentInject.pagesMap = ${shallowStringify(pagesMap)}
113
179
  global.currentInject.firstPage = ${JSON.stringify(firstPage)}\n`
114
180
  } else {
115
- if (!hasApp) {
116
- content += ' global.__mpxGenericsMap = global.__mpxGenericsMap || {}\n'
117
- }
118
181
  if (ctorType === 'page') {
119
182
  const pageConfig = Object.assign({}, jsonConfig)
120
183
  delete pageConfig.usingComponents
@@ -122,19 +185,15 @@ global.currentInject.firstPage = ${JSON.stringify(firstPage)}\n`
122
185
  }
123
186
 
124
187
  content += `
125
-
126
- function getComponents() {
127
- return ${shallowStringify(componentsMap)}
128
- }
129
-
130
- global.currentInject.getComponents = getComponents\n`
188
+ var componentsMap = ${shallowStringify(componentsMap)}
189
+ global.currentInject.componentsMap = componentsMap\n`
131
190
  if (genericsInfo) {
191
+ if (!hasApp) {
192
+ content += 'global.__mpxGenericsMap = global.__mpxGenericsMap || {}\n'
193
+ }
132
194
  content += `
133
- const genericHash = ${JSON.stringify(genericsInfo.hash)}\n
134
- global.__mpxGenericsMap[genericHash] = function (name) {
135
- return getComponents()[name]
136
- }
137
- \n`
195
+ const genericHash = ${JSON.stringify(genericsInfo.hash)}\n
196
+ global.__mpxGenericsMap[genericHash] = componentsMap\n`
138
197
  }
139
198
  if (ctorType === 'component') {
140
199
  content += `global.currentInject.componentPath = '/' + ${JSON.stringify(outputPath)}\n`
@@ -1,5 +1,6 @@
1
1
  import { createContext, Dispatch, MutableRefObject, SetStateAction } from 'react'
2
- import { NativeSyntheticEvent } from 'react-native'
2
+ import { NativeSyntheticEvent, Animated } from 'react-native'
3
+ import { noop } from '@mpxjs/utils'
3
4
 
4
5
  export type LabelContextValue = MutableRefObject<{
5
6
  triggerChange: (evt: NativeSyntheticEvent<TouchEvent>) => void
@@ -42,7 +43,8 @@ export interface PortalContextValue {
42
43
  }
43
44
 
44
45
  export interface ScrollViewContextValue {
45
- gestureRef: React.RefObject<any> | null
46
+ gestureRef: React.RefObject<any> | null,
47
+ scrollOffset: Animated.Value
46
48
  }
47
49
 
48
50
  export interface RouteContextValue {
@@ -50,6 +52,11 @@ export interface RouteContextValue {
50
52
  navigation: Record<string, any>
51
53
  }
52
54
 
55
+ export interface StickyContextValue {
56
+ registerStickyHeader: Function,
57
+ unregisterStickyHeader: Function
58
+ }
59
+
53
60
  export const MovableAreaContext = createContext({ width: 0, height: 0 })
54
61
 
55
62
  export const FormContext = createContext<FormContextValue | null>(null)
@@ -72,6 +79,8 @@ export const SwiperContext = createContext({})
72
79
 
73
80
  export const KeyboardAvoidContext = createContext<KeyboardAvoidContextValue | null>(null)
74
81
 
75
- export const ScrollViewContext = createContext<ScrollViewContextValue>({ gestureRef: null })
82
+ export const ScrollViewContext = createContext<ScrollViewContextValue>({ gestureRef: null, scrollOffset: new Animated.Value(0) })
76
83
 
77
84
  export const PortalContext = createContext<PortalContextValue>(null as any)
85
+
86
+ export const StickyContext = createContext<StickyContextValue>({ registerStickyHeader: noop, unregisterStickyHeader: noop })
@@ -1,4 +1,6 @@
1
1
  import { createContext } from 'react';
2
+ import { Animated } from 'react-native';
3
+ import { noop } from '@mpxjs/utils';
2
4
  export const MovableAreaContext = createContext({ width: 0, height: 0 });
3
5
  export const FormContext = createContext(null);
4
6
  export const CheckboxGroupContext = createContext(null);
@@ -10,5 +12,6 @@ export const IntersectionObserverContext = createContext(null);
10
12
  export const RouteContext = createContext(null);
11
13
  export const SwiperContext = createContext({});
12
14
  export const KeyboardAvoidContext = createContext(null);
13
- export const ScrollViewContext = createContext({ gestureRef: null });
15
+ export const ScrollViewContext = createContext({ gestureRef: null, scrollOffset: new Animated.Value(0) });
14
16
  export const PortalContext = createContext(null);
17
+ export const StickyContext = createContext({ registerStickyHeader: noop, unregisterStickyHeader: noop });
@@ -0,0 +1,135 @@
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 DefaultLoading = () => {
66
+ return (<View style={styles.container}>
67
+ <FastImage style={styles.loadingImage} source={{
68
+ uri: 'https://dpubstatic.udache.com/static/dpubimg/439jiCVOtNOnEv9F2LaDs_loading.gif'
69
+ }} resizeMode={FastImage.resizeMode.contain}></FastImage>
70
+ </View>);
71
+ };
72
+ const AsyncSuspense = ({ type, innerProps, chunkName, moduleId, loading, fallback, getChildren }) => {
73
+ const [status, setStatus] = useState('pending');
74
+ const chunkLoaded = asyncChunkMap.has(moduleId);
75
+ const loadChunkPromise = useRef(null);
76
+ const reloadPage = useCallback(() => {
77
+ setStatus('pending');
78
+ }, []);
79
+ useEffect(() => {
80
+ let cancelled = false;
81
+ if (!chunkLoaded && status === 'pending') {
82
+ if (loadChunkPromise.current) {
83
+ loadChunkPromise
84
+ .current.then((res) => {
85
+ if (cancelled)
86
+ return;
87
+ asyncChunkMap.set(moduleId, res);
88
+ setStatus('loaded');
89
+ })
90
+ .catch((e) => {
91
+ if (cancelled)
92
+ return;
93
+ if (type === 'component') {
94
+ global.onLazyLoadError({
95
+ type: 'subpackage',
96
+ subpackage: [chunkName],
97
+ errMsg: `loadSubpackage: ${e.type}`
98
+ });
99
+ }
100
+ loadChunkPromise.current = null;
101
+ setStatus('error');
102
+ });
103
+ }
104
+ }
105
+ return () => {
106
+ cancelled = true;
107
+ };
108
+ }, [status]);
109
+ if (chunkLoaded) {
110
+ const Comp = asyncChunkMap.get(moduleId);
111
+ return createElement(Comp, innerProps);
112
+ }
113
+ else if (status === 'error') {
114
+ if (type === 'page') {
115
+ fallback = fallback || DefaultFallback;
116
+ return createElement(fallback, { onReload: reloadPage });
117
+ }
118
+ else {
119
+ return fallback ? createElement(fallback, innerProps) : null;
120
+ }
121
+ }
122
+ else {
123
+ if (!loadChunkPromise.current) {
124
+ loadChunkPromise.current = getChildren();
125
+ }
126
+ if (type === 'page') {
127
+ return createElement(loading || DefaultLoading);
128
+ }
129
+ else {
130
+ return fallback ? createElement(fallback, innerProps) : null;
131
+ }
132
+ }
133
+ };
134
+ AsyncSuspense.displayName = 'MpxAsyncSuspense';
135
+ export default AsyncSuspense;
@@ -35,7 +35,7 @@
35
35
  * ✔ bindtap
36
36
  */
37
37
  import { createElement, useEffect, useRef, forwardRef, useContext } from 'react';
38
- import { View, StyleSheet, Animated, Easing } from 'react-native';
38
+ import { View, StyleSheet, Animated, Easing, useAnimatedValue } from 'react-native';
39
39
  import { warn } from '@mpxjs/utils';
40
40
  import { GestureDetector } from 'react-native-gesture-handler';
41
41
  import { getCurrentPage, splitProps, splitStyle, useLayout, useTransformStyle, wrapChildren, extendObject, useHover } from './utils';
@@ -104,7 +104,7 @@ const timer = (data, time = 3000) => new Promise((resolve) => {
104
104
  }, time);
105
105
  });
106
106
  const Loading = ({ alone = false }) => {
107
- const image = useRef(new Animated.Value(0)).current;
107
+ const image = useAnimatedValue(0);
108
108
  const rotate = image.interpolate({
109
109
  inputRange: [0, 1],
110
110
  outputRange: ['0deg', '360deg']
@@ -41,7 +41,7 @@ const _MovableView = forwardRef((movableViewProps, ref) => {
41
41
  const hasLayoutRef = useRef(false);
42
42
  const propsRef = useRef({});
43
43
  propsRef.current = (props || {});
44
- const { x = 0, y = 0, inertia = false, disabled = false, animation = true, 'out-of-bounds': outOfBounds = false, 'enable-var': enableVar, 'external-var-context': externalVarContext, 'parent-font-size': parentFontSize, 'parent-width': parentWidth, 'parent-height': parentHeight, direction = 'none', 'simultaneous-handlers': originSimultaneousHandlers = [], 'wait-for': waitFor = [], style = {}, changeThrottleTime = 60, bindtouchstart, catchtouchstart, bindhtouchmove, bindvtouchmove, bindtouchmove, catchhtouchmove, catchvtouchmove, catchtouchmove, bindtouchend, catchtouchend, bindchange } = props;
44
+ const { x = 0, y = 0, inertia = false, disabled = false, animation = true, 'out-of-bounds': outOfBounds = false, 'enable-var': enableVar, 'external-var-context': externalVarContext, 'parent-font-size': parentFontSize, 'parent-width': parentWidth, 'parent-height': parentHeight, direction = 'none', 'disable-event-passthrough': disableEventPassthrough = false, 'simultaneous-handlers': originSimultaneousHandlers = [], 'wait-for': waitFor = [], style = {}, changeThrottleTime = 60, bindtouchstart, catchtouchstart, bindhtouchmove, bindvtouchmove, bindtouchmove, catchhtouchmove, catchvtouchmove, catchtouchmove, bindtouchend, catchtouchend, bindchange } = props;
45
45
  const { hasSelfPercent, normalStyle, hasVarDec, varContextRef, setWidth, setHeight } = useTransformStyle(Object.assign({}, style, styles.container), { enableVar, externalVarContext, parentFontSize, parentWidth, parentHeight });
46
46
  const navigation = useNavigation();
47
47
  const prevSimultaneousHandlersRef = useRef(originSimultaneousHandlers || []);
@@ -449,11 +449,13 @@ const _MovableView = forwardRef((movableViewProps, ref) => {
449
449
  }
450
450
  })
451
451
  .withRef(movableGestureRef);
452
- if (direction === 'horizontal') {
453
- gesturePan.activeOffsetX([-5, 5]).failOffsetY([-5, 5]);
454
- }
455
- else if (direction === 'vertical') {
456
- gesturePan.activeOffsetY([-5, 5]).failOffsetX([-5, 5]);
452
+ if (!disableEventPassthrough) {
453
+ if (direction === 'horizontal') {
454
+ gesturePan.activeOffsetX([-5, 5]).failOffsetY([-5, 5]);
455
+ }
456
+ else if (direction === 'vertical') {
457
+ gesturePan.activeOffsetY([-5, 5]).failOffsetX([-5, 5]);
458
+ }
457
459
  }
458
460
  if (simultaneousHandlers && simultaneousHandlers.length) {
459
461
  gesturePan.simultaneousWithExternalGesture(...simultaneousHandlers);