@tarojs/plugin-framework-react 3.5.0-canary.0 → 3.5.0-theta.1

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/dist/runtime.js CHANGED
@@ -1,353 +1,114 @@
1
- import { Current, incrementId, container, SERVICE_IDENTIFIER, document, getPageInstance, injectPageInstance, safeExecute, eventHandler, addLeadingSlash } from '@tarojs/runtime';
2
- import { isFunction, isArray, EMPTY_OBJ, ensure } from '@tarojs/shared';
1
+ import { EMPTY_OBJ, isFunction, isArray, hooks, ensure } from '@tarojs/shared';
2
+ import { Current, getPageInstance, injectPageInstance, incrementId, document, safeExecute, eventHandler, addLeadingSlash } from '@tarojs/runtime';
3
3
 
4
- const HOOKS_APP_ID = 'taro-app';
5
- function isClassComponent(R, component) {
6
- const prototype = component.prototype;
7
- return (isFunction(component.render) ||
8
- !!(prototype === null || prototype === void 0 ? void 0 : prototype.isReactComponent) ||
9
- prototype instanceof R.Component // compat for some others react-like library
10
- );
11
- }
12
- function ensureIsArray(item) {
13
- if (isArray(item)) {
14
- return item;
15
- }
16
- else {
17
- return item ? [item] : [];
18
- }
19
- }
20
- /**
21
- * set writable, enumerable to true
22
- */
23
- function setDefaultDescriptor(obj) {
24
- obj.writable = true;
25
- obj.enumerable = true;
26
- return obj;
27
- }
28
- /**
29
- * 设置入口的路由参数
30
- * @param options 小程序传入的参数
31
- */
32
- function setRouterParams(options) {
33
- Current.router = Object.assign({ params: options === null || options === void 0 ? void 0 : options.query }, options);
34
- }
4
+ const reactMeta = {
5
+ PageContext: EMPTY_OBJ,
6
+ R: EMPTY_OBJ
7
+ };
35
8
 
36
- // 初始值设置为 any 主要是为了过 TS 的校验
37
- let PageContext = EMPTY_OBJ;
38
- let R$1 = EMPTY_OBJ;
39
- let h$1;
40
- let ReactDOM$1;
41
- const pageKeyId = incrementId();
42
- const hooks$1 = container.get(SERVICE_IDENTIFIER.Hooks);
43
- function setReconciler() {
44
- var _a;
45
- hooks$1.getLifecycle = function (instance, lifecycle) {
46
- lifecycle = lifecycle.replace(/^on(Show|Hide)$/, 'componentDid$1');
47
- return instance[lifecycle];
48
- };
49
- (_a = hooks$1.modifyMpEventImpls) === null || _a === void 0 ? void 0 : _a.push(function (event) {
50
- event.type = event.type.replace(/-/g, '');
51
- });
52
- hooks$1.batchedEventUpdates = function (cb) {
53
- ReactDOM$1.unstable_batchedUpdates(cb);
54
- };
55
- hooks$1.mergePageInstance = function (prev, next) {
56
- if (!prev || !next)
57
- return;
58
- // 子组件使用 lifecycle hooks 注册了生命周期后,会存在 prev,里面是注册的生命周期回调。
59
- // prev 使用 Object.create(null) 创建,H5 的 fast-refresh 可能也会导致存在 prev,要排除这些意外产生的 prev
60
- if ('constructor' in prev)
61
- return;
62
- Object.keys(prev).forEach(item => {
63
- const prevList = prev[item];
64
- const nextList = ensureIsArray(next[item]);
65
- next[item] = nextList.concat(prevList);
66
- });
67
- };
68
- if (process.env.TARO_ENV === 'h5') {
69
- hooks$1.createPullDownComponent = (el, _, R, customWrapper) => {
70
- const isReactComponent = isClassComponent(R, el);
71
- return R.forwardRef((props, ref) => {
72
- const newProps = Object.assign({}, props);
73
- const refs = isReactComponent ? { ref: ref } : {
74
- forwardedRef: ref,
75
- // 兼容 react-redux 7.20.1+
76
- reactReduxForwardedRef: ref
77
- };
78
- return h$1(customWrapper || 'taro-pull-to-refresh', null, h$1(el, Object.assign(Object.assign({}, newProps), refs)));
79
- });
80
- };
81
- hooks$1.getDOMNode = inst => {
82
- return ReactDOM$1.findDOMNode(inst);
83
- };
84
- }
85
- }
86
- function connectReactPage(R, id) {
87
- return (Page) => {
88
- // eslint-disable-next-line dot-notation
89
- const isReactComponent = isClassComponent(R, Page);
90
- const inject = (node) => node && injectPageInstance(node, id);
91
- const refs = isReactComponent ? { ref: inject } : {
92
- forwardedRef: inject,
93
- // 兼容 react-redux 7.20.1+
94
- reactReduxForwardedRef: inject
95
- };
96
- if (PageContext === EMPTY_OBJ) {
97
- PageContext = R.createContext('');
98
- }
99
- return class PageWrapper extends R.Component {
100
- constructor() {
101
- super(...arguments);
102
- this.state = {
103
- hasError: false
104
- };
105
- }
106
- static getDerivedStateFromError(error) {
107
- process.env.NODE_ENV !== 'production' && console.warn(error);
108
- return { hasError: true };
109
- }
110
- // React 16 uncaught error 会导致整个应用 crash,
111
- // 目前把错误缩小到页面
112
- componentDidCatch(error, info) {
113
- if (process.env.NODE_ENV !== 'production') {
114
- console.warn(error);
115
- console.error(info.componentStack);
116
- }
117
- }
118
- render() {
119
- const children = this.state.hasError
120
- ? []
121
- : h$1(PageContext.Provider, { value: id }, h$1(Page, Object.assign(Object.assign({}, this.props), refs)));
122
- if (process.env.TARO_ENV === 'h5') {
123
- return h$1('div', { id, className: 'taro_page' }, children);
124
- }
125
- else {
126
- return h$1('root', { id }, children);
127
- }
128
- }
129
- };
130
- };
131
- }
132
- /**
133
- * 桥接小程序 App 构造器和 React 渲染流程
134
- * @param App 用户编写的入口组件
135
- * @param react 框架
136
- * @param reactdom 框架渲染器
137
- * @param config 入口组件配置 app.config.js 的内容
138
- * @returns 传递给 App 构造器的对象 obj :App(obj)
139
- */
140
- function createReactApp(App, react, reactdom, config) {
141
- if (process.env.NODE_ENV !== 'production') {
142
- ensure(!!reactdom, '构建 React/Nerv 项目请把 process.env.FRAMEWORK 设置为 \'react\'/\'nerv\' ');
143
- }
144
- R$1 = react;
145
- h$1 = react.createElement;
146
- ReactDOM$1 = reactdom;
147
- const appInstanceRef = react.createRef();
148
- const isReactComponent = isClassComponent(R$1, App);
149
- let appWrapper;
150
- setReconciler();
151
- function getAppInstance() {
152
- return appInstanceRef.current;
153
- }
154
- class AppWrapper extends R$1.Component {
155
- constructor() {
156
- super(...arguments);
157
- // run createElement() inside the render function to make sure that owner is right
158
- this.pages = [];
159
- this.elements = [];
160
- }
161
- mount(pageComponent, id, cb) {
162
- const pageWrapper = connectReactPage(R$1, id)(pageComponent);
163
- const key = id + pageKeyId();
164
- const page = () => h$1(pageWrapper, { key, tid: id });
165
- this.pages.push(page);
166
- this.forceUpdate(cb);
167
- }
168
- unmount(id, cb) {
169
- const elements = this.elements;
170
- const idx = elements.findIndex(item => item.props.tid === id);
171
- elements.splice(idx, 1);
172
- this.forceUpdate(cb);
173
- }
174
- render() {
175
- const { pages, elements } = this;
176
- while (pages.length > 0) {
177
- const page = pages.pop();
178
- elements.push(page());
179
- }
180
- let props = null;
181
- if (isReactComponent) {
182
- props = { ref: appInstanceRef };
183
- }
184
- return h$1(App, props, process.env.TARO_ENV === 'h5' ? h$1('div', null, elements.slice()) : elements.slice());
185
- }
186
- }
187
- if (process.env.TARO_ENV !== 'h5') {
188
- // eslint-disable-next-line react/no-render-return-value
189
- appWrapper = ReactDOM$1.render(h$1(AppWrapper), document.getElementById('app'));
190
- }
191
- const [ONLAUNCH, ONSHOW, ONHIDE] = hooks$1.getMiniLifecycleImpl().app;
192
- const appObj = Object.create({
193
- render(cb) {
194
- appWrapper.forceUpdate(cb);
195
- },
196
- mount(component, id, cb) {
197
- appWrapper.mount(component, id, cb);
198
- },
199
- unmount(id, cb) {
200
- appWrapper.unmount(id, cb);
201
- }
202
- }, {
203
- config: setDefaultDescriptor({
204
- configurable: true,
205
- value: config
206
- }),
207
- [ONLAUNCH]: setDefaultDescriptor({
208
- value(options) {
209
- var _a;
210
- setRouterParams(options);
211
- if (process.env.TARO_ENV === 'h5') {
212
- // 由于 H5 路由初始化的时候会清除 app 下的 dom 元素,所以需要在路由初始化后执行 render
213
- // eslint-disable-next-line react/no-render-return-value
214
- appWrapper = ReactDOM$1.render(h$1(AppWrapper), document.getElementById('app'));
215
- }
216
- // 用户编写的入口组件实例
217
- const app = getAppInstance();
218
- this.$app = app;
219
- if (app) {
220
- // 把 App Class 上挂载的额外属性同步到全局 app 对象中
221
- if (app.taroGlobalData) {
222
- const globalData = app.taroGlobalData;
223
- const keys = Object.keys(globalData);
224
- const descriptors = Object.getOwnPropertyDescriptors(globalData);
225
- keys.forEach(key => {
226
- Object.defineProperty(this, key, {
227
- configurable: true,
228
- enumerable: true,
229
- get() {
230
- return globalData[key];
231
- },
232
- set(value) {
233
- globalData[key] = value;
234
- }
235
- });
236
- });
237
- Object.defineProperties(this, descriptors);
238
- }
239
- (_a = app.onLaunch) === null || _a === void 0 ? void 0 : _a.call(app, options);
240
- }
241
- }
242
- }),
243
- [ONSHOW]: setDefaultDescriptor({
244
- value(options) {
245
- var _a;
246
- setRouterParams(options);
247
- /**
248
- * trigger lifecycle
249
- */
250
- const app = getAppInstance();
251
- // class component, componentDidShow
252
- (_a = app === null || app === void 0 ? void 0 : app.componentDidShow) === null || _a === void 0 ? void 0 : _a.call(app, options);
253
- // functional component, useDidShow
254
- triggerAppHook('onShow');
255
- }
256
- }),
257
- [ONHIDE]: setDefaultDescriptor({
258
- value(options) {
259
- var _a;
260
- /**
261
- * trigger lifecycle
262
- */
263
- const app = getAppInstance();
264
- // class component, componentDidHide
265
- (_a = app === null || app === void 0 ? void 0 : app.componentDidHide) === null || _a === void 0 ? void 0 : _a.call(app, options);
266
- // functional component, useDidHide
267
- triggerAppHook('onHide');
268
- }
269
- }),
270
- onPageNotFound: setDefaultDescriptor({
271
- value(res) {
272
- var _a;
273
- const app = getAppInstance();
274
- (_a = app === null || app === void 0 ? void 0 : app.onPageNotFound) === null || _a === void 0 ? void 0 : _a.call(app, res);
275
- }
276
- })
277
- });
278
- function triggerAppHook(lifecycle) {
279
- const instance = getPageInstance(HOOKS_APP_ID);
280
- if (instance) {
281
- const app = getAppInstance();
282
- const func = hooks$1.getLifecycle(instance, lifecycle);
283
- if (Array.isArray(func)) {
284
- func.forEach(cb => cb.apply(app));
285
- }
286
- }
287
- }
288
- Current.app = appObj;
289
- return appObj;
9
+ const HOOKS_APP_ID = 'taro-app';
10
+ function isClassComponent(R, component) {
11
+ var _a;
12
+ const prototype = component.prototype;
13
+ // For React Redux
14
+ if ((_a = component.displayName) === null || _a === void 0 ? void 0 : _a.includes('Connect'))
15
+ return false;
16
+ return (isFunction(component.render) ||
17
+ !!(prototype === null || prototype === void 0 ? void 0 : prototype.isReactComponent) ||
18
+ prototype instanceof R.Component // compat for some others react-like library
19
+ );
20
+ }
21
+ function ensureIsArray(item) {
22
+ if (isArray(item)) {
23
+ return item;
24
+ }
25
+ else {
26
+ return item ? [item] : [];
27
+ }
28
+ }
29
+ /**
30
+ * set writable, enumerable to true
31
+ */
32
+ function setDefaultDescriptor(obj) {
33
+ obj.writable = true;
34
+ obj.enumerable = true;
35
+ return obj;
36
+ }
37
+ /**
38
+ * 设置入口的路由参数
39
+ * @param options 小程序传入的参数
40
+ */
41
+ function setRouterParams(options) {
42
+ Current.router = Object.assign({ params: options === null || options === void 0 ? void 0 : options.query }, options);
290
43
  }
291
44
 
292
- const taroHooks = (lifecycle) => {
293
- return (fn) => {
294
- const id = R$1.useContext(PageContext) || HOOKS_APP_ID;
295
- // hold fn ref and keep up to date
296
- const fnRef = R$1.useRef(fn);
297
- if (fnRef.current !== fn)
298
- fnRef.current = fn;
299
- R$1.useLayoutEffect(() => {
300
- let inst = getPageInstance(id);
301
- let first = false;
302
- if (inst == null) {
303
- first = true;
304
- inst = Object.create(null);
305
- }
306
- inst = inst;
307
- // callback is immutable but inner function is up to date
308
- const callback = (...args) => fnRef.current(...args);
309
- if (isFunction(inst[lifecycle])) {
310
- inst[lifecycle] = [inst[lifecycle], callback];
311
- }
312
- else {
313
- inst[lifecycle] = [
314
- ...(inst[lifecycle] || []),
315
- callback
316
- ];
317
- }
318
- if (first) {
319
- injectPageInstance(inst, id);
320
- }
321
- return () => {
322
- const inst = getPageInstance(id);
323
- const list = inst[lifecycle];
324
- if (list === callback) {
325
- inst[lifecycle] = undefined;
326
- }
327
- else if (isArray(list)) {
328
- inst[lifecycle] = list.filter(item => item !== callback);
329
- }
330
- };
331
- }, []);
332
- };
333
- };
334
- const useDidShow = taroHooks('componentDidShow');
335
- const useDidHide = taroHooks('componentDidHide');
336
- const usePullDownRefresh = taroHooks('onPullDownRefresh');
337
- const useReachBottom = taroHooks('onReachBottom');
338
- const usePageScroll = taroHooks('onPageScroll');
339
- const useResize = taroHooks('onResize');
340
- const useShareAppMessage = taroHooks('onShareAppMessage');
341
- const useTabItemTap = taroHooks('onTabItemTap');
342
- const useTitleClick = taroHooks('onTitleClick');
343
- const useOptionMenuClick = taroHooks('onOptionMenuClick');
344
- const usePullIntercept = taroHooks('onPullIntercept');
345
- const useShareTimeline = taroHooks('onShareTimeline');
346
- const useAddToFavorites = taroHooks('onAddToFavorites');
347
- const useReady = taroHooks('onReady');
348
- const useRouter = (dynamic = false) => {
349
- return dynamic ? Current.router : R$1.useMemo(() => Current.router, []);
350
- };
45
+ const taroHooks = (lifecycle) => {
46
+ return (fn) => {
47
+ const { R: React, PageContext } = reactMeta;
48
+ const id = React.useContext(PageContext) || HOOKS_APP_ID;
49
+ // hold fn ref and keep up to date
50
+ const fnRef = React.useRef(fn);
51
+ if (fnRef.current !== fn)
52
+ fnRef.current = fn;
53
+ React.useLayoutEffect(() => {
54
+ let inst = getPageInstance(id);
55
+ let first = false;
56
+ if (inst == null) {
57
+ first = true;
58
+ inst = Object.create(null);
59
+ }
60
+ inst = inst;
61
+ // callback is immutable but inner function is up to date
62
+ const callback = (...args) => fnRef.current(...args);
63
+ if (isFunction(inst[lifecycle])) {
64
+ inst[lifecycle] = [inst[lifecycle], callback];
65
+ }
66
+ else {
67
+ inst[lifecycle] = [
68
+ ...(inst[lifecycle] || []),
69
+ callback
70
+ ];
71
+ }
72
+ if (first) {
73
+ injectPageInstance(inst, id);
74
+ }
75
+ return () => {
76
+ const inst = getPageInstance(id);
77
+ const list = inst[lifecycle];
78
+ if (list === callback) {
79
+ inst[lifecycle] = undefined;
80
+ }
81
+ else if (isArray(list)) {
82
+ inst[lifecycle] = list.filter(item => item !== callback);
83
+ }
84
+ };
85
+ }, []);
86
+ };
87
+ };
88
+ const useDidShow = taroHooks('componentDidShow');
89
+ const useDidHide = taroHooks('componentDidHide');
90
+ const usePullDownRefresh = taroHooks('onPullDownRefresh');
91
+ const useReachBottom = taroHooks('onReachBottom');
92
+ const usePageScroll = taroHooks('onPageScroll');
93
+ const useResize = taroHooks('onResize');
94
+ const useShareAppMessage = taroHooks('onShareAppMessage');
95
+ const useTabItemTap = taroHooks('onTabItemTap');
96
+ const useTitleClick = taroHooks('onTitleClick');
97
+ const useOptionMenuClick = taroHooks('onOptionMenuClick');
98
+ const usePullIntercept = taroHooks('onPullIntercept');
99
+ const useShareTimeline = taroHooks('onShareTimeline');
100
+ const useAddToFavorites = taroHooks('onAddToFavorites');
101
+ const useSaveExitState = taroHooks('onSaveExitState');
102
+ const useReady = taroHooks('onReady');
103
+ const useLaunch = taroHooks('onLaunch');
104
+ const useLoad = taroHooks('onLoad');
105
+ const useUnload = taroHooks('onUnload');
106
+ const useError = taroHooks('onError');
107
+ const usePageNotFound = taroHooks('onPageNotFound');
108
+ const useRouter = (dynamic = false) => {
109
+ const React = reactMeta.R;
110
+ return dynamic ? Current.router : React.useMemo(() => Current.router, []);
111
+ };
351
112
  const useScope = () => undefined;
352
113
 
353
114
  var taroHooks$1 = /*#__PURE__*/Object.freeze({
@@ -365,177 +126,538 @@ var taroHooks$1 = /*#__PURE__*/Object.freeze({
365
126
  usePullIntercept: usePullIntercept,
366
127
  useShareTimeline: useShareTimeline,
367
128
  useAddToFavorites: useAddToFavorites,
129
+ useSaveExitState: useSaveExitState,
368
130
  useReady: useReady,
131
+ useLaunch: useLaunch,
132
+ useLoad: useLoad,
133
+ useUnload: useUnload,
134
+ useError: useError,
135
+ usePageNotFound: usePageNotFound,
369
136
  useRouter: useRouter,
370
137
  useScope: useScope
371
138
  });
372
139
 
373
- const getNativeCompId = incrementId();
374
- let R;
375
- let h;
376
- let ReactDOM;
377
- function initNativeComponentEntry(R, ReactDOM) {
378
- class NativeComponentWrapper extends R.Component {
379
- constructor() {
380
- super(...arguments);
381
- this.root = R.createRef();
382
- this.ctx = this.props.getCtx();
383
- }
384
- componentDidMount() {
385
- this.ctx.component = this;
386
- const rootElement = this.root.current;
387
- rootElement.ctx = this.ctx;
388
- rootElement.performUpdate(true);
389
- }
390
- render() {
391
- return (h('root', {
392
- ref: this.root
393
- }, this.props.renderComponent(this.ctx)));
394
- }
395
- }
396
- class Entry extends R.Component {
397
- constructor() {
398
- super(...arguments);
399
- this.state = {
400
- components: []
401
- };
402
- }
403
- componentDidMount() {
404
- Current.app = this;
405
- }
406
- mount(Component, compId, getCtx) {
407
- const isReactComponent = isClassComponent(R, Component);
408
- const inject = (node) => node && injectPageInstance(node, compId);
409
- const refs = isReactComponent ? { ref: inject } : {
410
- forwardedRef: inject,
411
- reactReduxForwardedRef: inject
412
- };
413
- const item = {
414
- compId,
415
- element: h(NativeComponentWrapper, {
416
- key: compId,
417
- getCtx,
418
- renderComponent(ctx) {
419
- return h(Component, Object.assign(Object.assign({}, (ctx.data || (ctx.data = {})).props), refs));
420
- }
421
- })
422
- };
423
- this.setState({
424
- components: [...this.state.components, item]
425
- });
426
- }
427
- unmount(compId) {
428
- const components = this.state.components;
429
- const index = components.findIndex(item => item.compId === compId);
430
- const next = [...components.slice(0, index), ...components.slice(index + 1)];
431
- this.setState({
432
- components: next
433
- });
434
- }
435
- render() {
436
- const components = this.state.components;
437
- return (components.map(({ element }) => element));
438
- }
439
- }
440
- setReconciler();
441
- const app = document.getElementById('app');
442
- ReactDOM.render(h(Entry, {}), app);
443
- }
444
- function createNativeComponentConfig(Component, react, reactdom, componentConfig) {
445
- R = react;
446
- h = react.createElement;
447
- ReactDOM = reactdom;
448
- setReconciler();
449
- const componentObj = {
450
- properties: {
451
- props: {
452
- type: null,
453
- value: null,
454
- observer(_newVal, oldVal) {
455
- oldVal && this.component.forceUpdate();
456
- }
457
- }
458
- },
459
- created() {
460
- if (!Current.app) {
461
- initNativeComponentEntry(R, ReactDOM);
462
- }
463
- },
464
- attached() {
465
- setCurrent();
466
- this.compId = getNativeCompId();
467
- this.config = componentConfig;
468
- Current.app.mount(Component, this.compId, () => this);
469
- },
470
- ready() {
471
- safeExecute(this.compId, 'onReady');
472
- },
473
- detached() {
474
- Current.app.unmount(this.compId);
475
- },
476
- pageLifetimes: {
477
- show() {
478
- safeExecute(this.compId, 'onShow');
479
- },
480
- hide() {
481
- safeExecute(this.compId, 'onHide');
482
- }
483
- },
484
- methods: {
485
- eh: eventHandler
486
- }
487
- };
488
- function setCurrent() {
489
- const pages = getCurrentPages();
490
- const currentPage = pages[pages.length - 1];
491
- if (Current.page === currentPage)
492
- return;
493
- Current.page = currentPage;
494
- const route = currentPage.route || currentPage.__route__;
495
- const router = {
496
- params: currentPage.options || {},
497
- path: addLeadingSlash(route),
498
- onReady: '',
499
- onHide: '',
500
- onShow: ''
501
- };
502
- Current.router = router;
503
- if (!currentPage.options) {
504
- // 例如在微信小程序中,页面 options 的设置时机比组件 attached 慢
505
- Object.defineProperty(currentPage, 'options', {
506
- enumerable: true,
507
- configurable: true,
508
- get() {
509
- return this._optionsValue;
510
- },
511
- set(value) {
512
- router.params = value;
513
- this._optionsValue = value;
514
- }
515
- });
516
- }
517
- }
518
- return componentObj;
140
+ let h$1;
141
+ let ReactDOM$1;
142
+ let Fragment;
143
+ const pageKeyId = incrementId();
144
+ function setReconciler(ReactDOM) {
145
+ hooks.tap('getLifecycle', function (instance, lifecycle) {
146
+ lifecycle = lifecycle.replace(/^on(Show|Hide)$/, 'componentDid$1');
147
+ return instance[lifecycle];
148
+ });
149
+ hooks.tap('modifyMpEvent', function (event) {
150
+ event.type = event.type.replace(/-/g, '');
151
+ });
152
+ hooks.tap('batchedEventUpdates', function (cb) {
153
+ ReactDOM.unstable_batchedUpdates(cb);
154
+ });
155
+ hooks.tap('mergePageInstance', function (prev, next) {
156
+ if (!prev || !next)
157
+ return;
158
+ // 子组件使用 lifecycle hooks 注册了生命周期后,会存在 prev,里面是注册的生命周期回调。
159
+ // prev 使用 Object.create(null) 创建,H5 的 fast-refresh 可能也会导致存在 prev,要排除这些意外产生的 prev
160
+ if ('constructor' in prev)
161
+ return;
162
+ Object.keys(prev).forEach(item => {
163
+ const prevList = prev[item];
164
+ const nextList = ensureIsArray(next[item]);
165
+ next[item] = nextList.concat(prevList);
166
+ });
167
+ });
168
+ if (process.env.TARO_ENV === 'h5') {
169
+ hooks.tap('createPullDownComponent', (el, _, R, customWrapper) => {
170
+ const isReactComponent = isClassComponent(R, el);
171
+ return R.forwardRef((props, ref) => {
172
+ const newProps = Object.assign({}, props);
173
+ const refs = isReactComponent ? { ref: ref } : {
174
+ forwardedRef: ref,
175
+ // 兼容 react-redux 7.20.1+
176
+ reactReduxForwardedRef: ref
177
+ };
178
+ return h$1(customWrapper || 'taro-pull-to-refresh', null, h$1(el, Object.assign(Object.assign({}, newProps), refs)));
179
+ });
180
+ });
181
+ hooks.tap('getDOMNode', inst => {
182
+ return ReactDOM.findDOMNode(inst);
183
+ });
184
+ }
185
+ }
186
+ function connectReactPage(R, id) {
187
+ return (Page) => {
188
+ // eslint-disable-next-line dot-notation
189
+ const isReactComponent = isClassComponent(R, Page);
190
+ const inject = (node) => node && injectPageInstance(node, id);
191
+ const refs = isReactComponent ? { ref: inject } : {
192
+ forwardedRef: inject,
193
+ // 兼容 react-redux 7.20.1+
194
+ reactReduxForwardedRef: inject
195
+ };
196
+ if (reactMeta.PageContext === EMPTY_OBJ) {
197
+ reactMeta.PageContext = R.createContext('');
198
+ }
199
+ return class PageWrapper extends R.Component {
200
+ constructor() {
201
+ super(...arguments);
202
+ this.state = {
203
+ hasError: false
204
+ };
205
+ }
206
+ static getDerivedStateFromError(error) {
207
+ var _a, _b;
208
+ (_b = (_a = Current.app) === null || _a === void 0 ? void 0 : _a.onError) === null || _b === void 0 ? void 0 : _b.call(_a, error.message + error.stack);
209
+ return { hasError: true };
210
+ }
211
+ // React 16 uncaught error 会导致整个应用 crash,
212
+ // 目前把错误缩小到页面
213
+ componentDidCatch(error, info) {
214
+ if (process.env.NODE_ENV !== 'production') {
215
+ console.warn(error);
216
+ console.error(info.componentStack);
217
+ }
218
+ }
219
+ render() {
220
+ const children = this.state.hasError
221
+ ? []
222
+ : h$1(reactMeta.PageContext.Provider, { value: id }, h$1(Page, Object.assign(Object.assign({}, this.props), refs)));
223
+ if (process.env.TARO_ENV === 'h5') {
224
+ return h$1('div', { id, className: 'taro_page' }, children);
225
+ }
226
+ else {
227
+ return h$1('root', { id }, children);
228
+ }
229
+ }
230
+ };
231
+ };
232
+ }
233
+ /**
234
+ * 桥接小程序 App 构造器和 React 渲染流程
235
+ * @param App 用户编写的入口组件
236
+ * @param react 框架
237
+ * @param dom 框架渲染器
238
+ * @param config 入口组件配置 app.config.js 的内容
239
+ * @returns 传递给 App 构造器的对象 obj :App(obj)
240
+ */
241
+ function createReactApp(App, react, dom, config) {
242
+ if (process.env.NODE_ENV !== 'production') {
243
+ ensure(!!dom, '构建 React/Nerv 项目请把 process.env.FRAMEWORK 设置为 \'react\'/\'nerv\' ');
244
+ }
245
+ reactMeta.R = react;
246
+ h$1 = react.createElement;
247
+ ReactDOM$1 = dom;
248
+ Fragment = react.Fragment;
249
+ const appInstanceRef = react.createRef();
250
+ const isReactComponent = isClassComponent(react, App);
251
+ let appWrapper;
252
+ setReconciler(ReactDOM$1);
253
+ function getAppInstance() {
254
+ return appInstanceRef.current;
255
+ }
256
+ function renderReactRoot() {
257
+ var _a, _b;
258
+ const reactMode = __TARO_FRAMEWORK_REACT_MODE__;
259
+ let appId = 'app';
260
+ if (process.env.TARO_ENV === 'h5') {
261
+ appId = (config === null || config === void 0 ? void 0 : config.appId) || appId;
262
+ }
263
+ else {
264
+ ReactDOM$1.version = react.version;
265
+ }
266
+ const container = document.getElementById(appId);
267
+ const version = Number((ReactDOM$1.version || '').split('.')[0]);
268
+ if (version >= 18 && reactMode === 'concurrent') {
269
+ const root = ReactDOM$1.createRoot(container);
270
+ (_a = root.render) === null || _a === void 0 ? void 0 : _a.call(root, h$1(AppWrapper));
271
+ }
272
+ else {
273
+ (_b = ReactDOM$1.render) === null || _b === void 0 ? void 0 : _b.call(ReactDOM$1, h$1(AppWrapper), container);
274
+ }
275
+ }
276
+ class AppWrapper extends react.Component {
277
+ constructor(props) {
278
+ super(props);
279
+ // run createElement() inside the render function to make sure that owner is right
280
+ this.pages = [];
281
+ this.elements = [];
282
+ appWrapper = this;
283
+ }
284
+ mount(pageComponent, id, cb) {
285
+ const pageWrapper = connectReactPage(react, id)(pageComponent);
286
+ const key = id + pageKeyId();
287
+ const page = () => h$1(pageWrapper, { key, tid: id });
288
+ this.pages.push(page);
289
+ this.forceUpdate(cb);
290
+ }
291
+ unmount(id, cb) {
292
+ const elements = this.elements;
293
+ const idx = elements.findIndex(item => item.props.tid === id);
294
+ elements.splice(idx, 1);
295
+ this.forceUpdate(cb);
296
+ }
297
+ render() {
298
+ const { pages, elements } = this;
299
+ while (pages.length > 0) {
300
+ const page = pages.pop();
301
+ elements.push(page());
302
+ }
303
+ let props = null;
304
+ if (isReactComponent) {
305
+ props = { ref: appInstanceRef };
306
+ }
307
+ return h$1(App, props, process.env.TARO_ENV === 'h5' ? h$1(Fragment !== null && Fragment !== void 0 ? Fragment : 'div', null, elements.slice()) : elements.slice());
308
+ }
309
+ }
310
+ if (process.env.TARO_ENV !== 'h5') {
311
+ renderReactRoot();
312
+ }
313
+ const [ONLAUNCH, ONSHOW, ONHIDE] = hooks.call('getMiniLifecycleImpl').app;
314
+ const appObj = Object.create({
315
+ render(cb) {
316
+ appWrapper.forceUpdate(cb);
317
+ },
318
+ mount(component, id, cb) {
319
+ appWrapper.mount(component, id, cb);
320
+ },
321
+ unmount(id, cb) {
322
+ appWrapper.unmount(id, cb);
323
+ }
324
+ }, {
325
+ config: setDefaultDescriptor({
326
+ configurable: true,
327
+ value: config
328
+ }),
329
+ [ONLAUNCH]: setDefaultDescriptor({
330
+ value(options) {
331
+ var _a;
332
+ setRouterParams(options);
333
+ if (process.env.TARO_ENV === 'h5') {
334
+ // 由于 H5 路由初始化的时候会清除 app 下的 dom 元素,所以需要在路由初始化后执行 render
335
+ renderReactRoot();
336
+ }
337
+ // 用户编写的入口组件实例
338
+ const app = getAppInstance();
339
+ this.$app = app;
340
+ if (app) {
341
+ // 把 App Class 上挂载的额外属性同步到全局 app 对象中
342
+ if (app.taroGlobalData) {
343
+ const globalData = app.taroGlobalData;
344
+ const keys = Object.keys(globalData);
345
+ const descriptors = Object.getOwnPropertyDescriptors(globalData);
346
+ keys.forEach(key => {
347
+ Object.defineProperty(this, key, {
348
+ configurable: true,
349
+ enumerable: true,
350
+ get() {
351
+ return globalData[key];
352
+ },
353
+ set(value) {
354
+ globalData[key] = value;
355
+ }
356
+ });
357
+ });
358
+ Object.defineProperties(this, descriptors);
359
+ }
360
+ (_a = app.onLaunch) === null || _a === void 0 ? void 0 : _a.call(app, options);
361
+ }
362
+ triggerAppHook('onLaunch', options);
363
+ }
364
+ }),
365
+ [ONSHOW]: setDefaultDescriptor({
366
+ value(options) {
367
+ var _a;
368
+ setRouterParams(options);
369
+ /**
370
+ * trigger lifecycle
371
+ */
372
+ const app = getAppInstance();
373
+ // class component, componentDidShow
374
+ (_a = app === null || app === void 0 ? void 0 : app.componentDidShow) === null || _a === void 0 ? void 0 : _a.call(app, options);
375
+ // functional component, useDidShow
376
+ triggerAppHook('onShow', options);
377
+ }
378
+ }),
379
+ [ONHIDE]: setDefaultDescriptor({
380
+ value() {
381
+ var _a;
382
+ /**
383
+ * trigger lifecycle
384
+ */
385
+ const app = getAppInstance();
386
+ // class component, componentDidHide
387
+ (_a = app === null || app === void 0 ? void 0 : app.componentDidHide) === null || _a === void 0 ? void 0 : _a.call(app);
388
+ // functional component, useDidHide
389
+ triggerAppHook('onHide');
390
+ }
391
+ }),
392
+ onError: setDefaultDescriptor({
393
+ value(error) {
394
+ var _a;
395
+ const app = getAppInstance();
396
+ (_a = app === null || app === void 0 ? void 0 : app.onError) === null || _a === void 0 ? void 0 : _a.call(app, error);
397
+ triggerAppHook('onError', error);
398
+ if (process.env.NODE_ENV !== 'production' && error.includes('Minified React error')) {
399
+ console.warn('React 出现报错,请打开编译配置 mini.debugReact 查看报错详情:https://docs.taro.zone/docs/config-detail#minidebugreact');
400
+ }
401
+ }
402
+ }),
403
+ onPageNotFound: setDefaultDescriptor({
404
+ value(res) {
405
+ var _a;
406
+ const app = getAppInstance();
407
+ (_a = app === null || app === void 0 ? void 0 : app.onPageNotFound) === null || _a === void 0 ? void 0 : _a.call(app, res);
408
+ triggerAppHook('onPageNotFound', res);
409
+ }
410
+ })
411
+ });
412
+ function triggerAppHook(lifecycle, ...option) {
413
+ const instance = getPageInstance(HOOKS_APP_ID);
414
+ if (instance) {
415
+ const app = getAppInstance();
416
+ const func = hooks.call('getLifecycle', instance, lifecycle);
417
+ if (Array.isArray(func)) {
418
+ func.forEach(cb => cb.apply(app, option));
419
+ }
420
+ }
421
+ }
422
+ Current.app = appObj;
423
+ return appObj;
424
+ }
425
+
426
+ const getNativeCompId = incrementId();
427
+ let h;
428
+ let ReactDOM;
429
+ function initNativeComponentEntry(R, ReactDOM) {
430
+ class NativeComponentWrapper extends R.Component {
431
+ constructor() {
432
+ super(...arguments);
433
+ this.root = R.createRef();
434
+ this.ctx = this.props.getCtx();
435
+ }
436
+ componentDidMount() {
437
+ this.ctx.component = this;
438
+ const rootElement = this.root.current;
439
+ rootElement.ctx = this.ctx;
440
+ rootElement.performUpdate(true);
441
+ }
442
+ render() {
443
+ return (h('root', {
444
+ ref: this.root
445
+ }, this.props.renderComponent(this.ctx)));
446
+ }
447
+ }
448
+ class Entry extends R.Component {
449
+ constructor() {
450
+ super(...arguments);
451
+ this.state = {
452
+ components: []
453
+ };
454
+ }
455
+ componentDidMount() {
456
+ Current.app = this;
457
+ }
458
+ mount(Component, compId, getCtx) {
459
+ const isReactComponent = isClassComponent(R, Component);
460
+ const inject = (node) => node && injectPageInstance(node, compId);
461
+ const refs = isReactComponent ? { ref: inject } : {
462
+ forwardedRef: inject,
463
+ reactReduxForwardedRef: inject
464
+ };
465
+ if (reactMeta.PageContext === EMPTY_OBJ) {
466
+ reactMeta.PageContext = R.createContext('');
467
+ }
468
+ const item = {
469
+ compId,
470
+ element: h(NativeComponentWrapper, {
471
+ key: compId,
472
+ getCtx,
473
+ renderComponent(ctx) {
474
+ return h(reactMeta.PageContext.Provider, { value: compId }, h(Component, Object.assign(Object.assign(Object.assign({}, (ctx.data || (ctx.data = {})).props), refs), { $scope: ctx })));
475
+ }
476
+ })
477
+ };
478
+ this.setState({
479
+ components: [...this.state.components, item]
480
+ });
481
+ }
482
+ unmount(compId) {
483
+ const components = this.state.components;
484
+ const index = components.findIndex(item => item.compId === compId);
485
+ const next = [...components.slice(0, index), ...components.slice(index + 1)];
486
+ this.setState({
487
+ components: next
488
+ });
489
+ }
490
+ render() {
491
+ const components = this.state.components;
492
+ return (components.map(({ element }) => element));
493
+ }
494
+ }
495
+ setReconciler(ReactDOM);
496
+ const app = document.getElementById('app');
497
+ ReactDOM.render(h(Entry, {}), app);
498
+ }
499
+ function createNativeComponentConfig(Component, react, reactdom, componentConfig) {
500
+ var _a, _b;
501
+ reactMeta.R = react;
502
+ h = react.createElement;
503
+ ReactDOM = reactdom;
504
+ setReconciler(ReactDOM);
505
+ const componentObj = {
506
+ options: componentConfig,
507
+ properties: {
508
+ props: {
509
+ type: null,
510
+ value: null,
511
+ observer(_newVal, oldVal) {
512
+ oldVal && this.component.forceUpdate();
513
+ }
514
+ }
515
+ },
516
+ created() {
517
+ if (!Current.app) {
518
+ initNativeComponentEntry(react, ReactDOM);
519
+ }
520
+ },
521
+ attached() {
522
+ const compId = this.compId = getNativeCompId();
523
+ setCurrent(compId);
524
+ this.config = componentConfig;
525
+ Current.app.mount(Component, compId, () => this);
526
+ },
527
+ ready() {
528
+ safeExecute(this.compId, 'onReady');
529
+ },
530
+ detached() {
531
+ Current.app.unmount(this.compId);
532
+ },
533
+ pageLifetimes: {
534
+ show(options) {
535
+ safeExecute(this.compId, 'onShow', options);
536
+ },
537
+ hide() {
538
+ safeExecute(this.compId, 'onHide');
539
+ }
540
+ },
541
+ methods: {
542
+ eh: eventHandler
543
+ }
544
+ };
545
+ function setCurrent(compId) {
546
+ const pages = getCurrentPages();
547
+ const currentPage = pages[pages.length - 1];
548
+ if (Current.page === currentPage)
549
+ return;
550
+ Current.page = currentPage;
551
+ const route = currentPage.route || currentPage.__route__;
552
+ const router = {
553
+ params: currentPage.options || {},
554
+ path: addLeadingSlash(route),
555
+ $taroPath: compId,
556
+ onReady: '',
557
+ onHide: '',
558
+ onShow: ''
559
+ };
560
+ Current.router = router;
561
+ if (!currentPage.options) {
562
+ // 例如在微信小程序中,页面 options 的设置时机比组件 attached 慢
563
+ Object.defineProperty(currentPage, 'options', {
564
+ enumerable: true,
565
+ configurable: true,
566
+ get() {
567
+ return this._optionsValue;
568
+ },
569
+ set(value) {
570
+ router.params = value;
571
+ this._optionsValue = value;
572
+ }
573
+ });
574
+ }
575
+ }
576
+ // onShareAppMessage 和 onShareTimeline 一样,会影响小程序右上方按钮的选项,因此不能默认注册。
577
+ if (Component.onShareAppMessage ||
578
+ ((_a = Component.prototype) === null || _a === void 0 ? void 0 : _a.onShareAppMessage) ||
579
+ Component.enableShareAppMessage) {
580
+ componentObj.methods.onShareAppMessage = function (options) {
581
+ const target = options === null || options === void 0 ? void 0 : options.target;
582
+ if (target) {
583
+ const id = target.id;
584
+ const element = document.getElementById(id);
585
+ if (element) {
586
+ target.dataset = element.dataset;
587
+ }
588
+ }
589
+ return safeExecute(this.compId, 'onShareAppMessage', options);
590
+ };
591
+ }
592
+ if (Component.onShareTimeline ||
593
+ ((_b = Component.prototype) === null || _b === void 0 ? void 0 : _b.onShareTimeline) ||
594
+ Component.enableShareTimeline) {
595
+ componentObj.methods.onShareTimeline = function () {
596
+ return safeExecute(this.compId, 'onShareTimeline');
597
+ };
598
+ }
599
+ return componentObj;
519
600
  }
520
601
 
521
- var _a, _b;
522
- const hooks = container.get(SERVICE_IDENTIFIER.Hooks);
523
- hooks.initNativeApiImpls || (hooks.initNativeApiImpls = []);
524
- hooks.initNativeApiImpls.push(function (taro) {
525
- for (const hook in taroHooks$1) {
526
- taro[hook] = taroHooks$1[hook];
527
- }
528
- });
529
- if (__TARO_FRAMEWORK__ === 'preact') {
530
- (_a = hooks.modifyMpEventImpls) === null || _a === void 0 ? void 0 : _a.push(e => {
531
- if (e.type === 'tap')
532
- e.type = 'click';
533
- });
534
- (_b = hooks.modifyDispatchEventImpls) === null || _b === void 0 ? void 0 : _b.push(e => {
535
- const type = e.type;
536
- e.type = type[0].toUpperCase() + type.slice(1);
537
- });
602
+ hooks.tap('initNativeApi', function (taro) {
603
+ for (const hook in taroHooks$1) {
604
+ taro[hook] = taroHooks$1[hook];
605
+ }
606
+ });
607
+ if (__TARO_FRAMEWORK__ === 'preact') {
608
+ const options = require('preact').options;
609
+ const oldVNodeHook = options.vnode;
610
+ const oldDiffedHook = options.diffed;
611
+ options.vnode = vnode => {
612
+ const { type, props } = vnode;
613
+ let normalizedProps = props;
614
+ // only normalize props on Element nodes
615
+ if (typeof type === 'string') {
616
+ normalizedProps = {};
617
+ for (let i in props) {
618
+ const value = props[i];
619
+ if (/^on/.test(i)) {
620
+ i = i.toLowerCase();
621
+ }
622
+ normalizedProps[i] = value;
623
+ }
624
+ vnode.props = normalizedProps;
625
+ }
626
+ if (oldVNodeHook)
627
+ oldVNodeHook(vnode);
628
+ };
629
+ options.diffed = function (newVNode) {
630
+ const dom = newVNode._dom;
631
+ const newVNodeProps = newVNode.props;
632
+ if (dom) { /** ElementNode */
633
+ for (const propName in newVNodeProps) {
634
+ const propValue = newVNodeProps[propName];
635
+ if (propValue === false && dom.props[propName] === undefined) {
636
+ // 值为 false 的属性在 Preact 的 diff 中被 removeAttribute 了,这里手动 setAttribute
637
+ // fix https://github.com/NervJS/taro/issues/11197
638
+ dom.setAttribute(propName, propValue);
639
+ }
640
+ }
641
+ }
642
+ if (oldDiffedHook)
643
+ oldDiffedHook(newVNode);
644
+ };
645
+ hooks.tap('modifyMpEvent', e => {
646
+ const type = e.type;
647
+ if (type === 'tap') {
648
+ e.type = 'click';
649
+ }
650
+ else if (type === 'focus') {
651
+ // 兼容 preact/compat/src/render.js options.vnode 的处理逻辑
652
+ e.type = 'focusin';
653
+ }
654
+ else if (type === 'blur') {
655
+ e.type = 'focusout';
656
+ }
657
+ });
658
+ // hooks.modifyDispatchEventImpls?.push(e => {
659
+ // })
538
660
  }
539
661
 
540
- export { PageContext, R$1 as R, connectReactPage, createNativeComponentConfig, createReactApp, setReconciler, useAddToFavorites, useDidHide, useDidShow, useOptionMenuClick, usePageScroll, usePullDownRefresh, usePullIntercept, useReachBottom, useReady, useResize, useRouter, useScope, useShareAppMessage, useShareTimeline, useTabItemTap, useTitleClick };
662
+ export { connectReactPage, createNativeComponentConfig, createReactApp, setReconciler, useAddToFavorites, useDidHide, useDidShow, useError, useLaunch, useLoad, useOptionMenuClick, usePageNotFound, usePageScroll, usePullDownRefresh, usePullIntercept, useReachBottom, useReady, useResize, useRouter, useSaveExitState, useScope, useShareAppMessage, useShareTimeline, useTabItemTap, useTitleClick, useUnload };
541
663
  //# sourceMappingURL=runtime.js.map