@tarojs/plugin-framework-solid 4.0.0-alpha.19 → 4.0.0-beta.84

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 DELETED
@@ -1,1165 +0,0 @@
1
- import { EMPTY_OBJ, isFunction, isArray, hooks, ensure, isUndefined } from '@tarojs/shared';
2
- import { Current, getPageInstance, injectPageInstance, incrementId, document, perf, PAGE_INIT, getPath, window, CONTEXT_ACTIONS, safeExecute, removePageInstance, ON_READY, requestAnimationFrame, eventCenter, getOnReadyEventKey, ON_SHOW, getOnShowEventKey, ON_HIDE, getOnHideEventKey, eventHandler, addLeadingSlash } from '@tarojs/runtime';
3
- import * as Solid from 'solid-js';
4
- import { createContext, createMemo, useContext, createRenderEffect, onCleanup } from 'solid-js';
5
- import * as SolidReconciler from '@tarojs/plugin-framework-react/dist/reconciler';
6
-
7
- const reactMeta = {
8
- PageContext: EMPTY_OBJ,
9
- R: EMPTY_OBJ,
10
- };
11
- const solidMeta = {
12
- PageContext: createContext(''),
13
- };
14
-
15
- const HOOKS_APP_ID = 'taro-app';
16
- function isClassComponent(R, component) {
17
- var _a;
18
- const prototype = component.prototype;
19
- // For React Redux
20
- if ((_a = component.displayName) === null || _a === void 0 ? void 0 : _a.includes('Connect'))
21
- return false;
22
- return (isFunction(component.render) ||
23
- !!(prototype === null || prototype === void 0 ? void 0 : prototype.isReactComponent) ||
24
- prototype instanceof R.Component // compat for some others react-like library
25
- );
26
- }
27
- function ensureIsArray(item) {
28
- if (isArray(item)) {
29
- return item;
30
- }
31
- else {
32
- return item ? [item] : [];
33
- }
34
- }
35
- /**
36
- * set writable, enumerable to true
37
- */
38
- function setDefaultDescriptor(obj) {
39
- obj.writable = true;
40
- obj.enumerable = true;
41
- return obj;
42
- }
43
- /**
44
- * 设置入口的路由参数
45
- * @param options 小程序传入的参数
46
- */
47
- function setRouterParams(options) {
48
- Current.router = Object.assign({ params: options === null || options === void 0 ? void 0 : options.query }, options);
49
- }
50
-
51
- const createTaroHook = (lifecycle) => {
52
- return (fn) => {
53
- if (process.env.FRAMEWORK !== 'solid') {
54
- const { R: React, PageContext } = reactMeta;
55
- const id = React.useContext(PageContext) || HOOKS_APP_ID;
56
- const instRef = React.useRef();
57
- // hold fn ref and keep up to date
58
- const fnRef = React.useRef(fn);
59
- if (fnRef.current !== fn)
60
- fnRef.current = fn;
61
- React.useLayoutEffect(() => {
62
- let inst = instRef.current = getPageInstance(id);
63
- let first = false;
64
- if (!inst) {
65
- first = true;
66
- instRef.current = Object.create(null);
67
- inst = instRef.current;
68
- }
69
- // callback is immutable but inner function is up to date
70
- const callback = (...args) => fnRef.current(...args);
71
- if (isFunction(inst[lifecycle])) {
72
- (inst[lifecycle]) = [inst[lifecycle], callback];
73
- }
74
- else {
75
- (inst[lifecycle]) = [
76
- ...((inst[lifecycle]) || []),
77
- callback
78
- ];
79
- }
80
- if (first) {
81
- injectPageInstance(inst, id);
82
- }
83
- return () => {
84
- const inst = instRef.current;
85
- if (!inst)
86
- return;
87
- const list = inst[lifecycle];
88
- if (list === callback) {
89
- (inst[lifecycle]) = undefined;
90
- }
91
- else if (isArray(list)) {
92
- (inst[lifecycle]) = list.filter(item => item !== callback);
93
- }
94
- instRef.current = undefined;
95
- };
96
- }, []);
97
- }
98
- else {
99
- const context = useContext(solidMeta.PageContext);
100
- const id = context || HOOKS_APP_ID;
101
- createRenderEffect(() => {
102
- let inst = getPageInstance(id);
103
- let first = false;
104
- if (!inst) {
105
- first = true;
106
- inst = Object.create({
107
- id: id,
108
- type: 'page',
109
- });
110
- }
111
- if (isFunction(inst[lifecycle])) {
112
- inst[lifecycle] = [inst[lifecycle], fn];
113
- }
114
- else {
115
- inst[lifecycle] = [
116
- ...((inst[lifecycle]) || []),
117
- fn
118
- ];
119
- }
120
- if (first) {
121
- injectPageInstance(inst, id);
122
- }
123
- onCleanup(() => {
124
- const list = inst[lifecycle];
125
- if (list === fn) {
126
- (inst[lifecycle]) = undefined;
127
- }
128
- else if (isArray(list)) {
129
- (inst[lifecycle]) = list.filter(item => item !== fn);
130
- }
131
- });
132
- });
133
- }
134
- };
135
- };
136
- /** LifeCycle */
137
- const useDidHide = createTaroHook('componentDidHide');
138
- const useDidShow = createTaroHook('componentDidShow');
139
- /** App */
140
- const useError = createTaroHook('onError');
141
- const useUnhandledRejection = createTaroHook('onUnhandledRejection');
142
- const useLaunch = createTaroHook('onLaunch');
143
- const usePageNotFound = createTaroHook('onPageNotFound');
144
- /** Page */
145
- const useLoad = createTaroHook('onLoad');
146
- const usePageScroll = createTaroHook('onPageScroll');
147
- const usePullDownRefresh = createTaroHook('onPullDownRefresh');
148
- const usePullIntercept = createTaroHook('onPullIntercept');
149
- const useReachBottom = createTaroHook('onReachBottom');
150
- const useResize = createTaroHook('onResize');
151
- const useUnload = createTaroHook('onUnload');
152
- /** Mini-Program */
153
- const useAddToFavorites = createTaroHook('onAddToFavorites');
154
- const useOptionMenuClick = createTaroHook('onOptionMenuClick');
155
- const useSaveExitState = createTaroHook('onSaveExitState');
156
- const useShareAppMessage = createTaroHook('onShareAppMessage');
157
- const useShareTimeline = createTaroHook('onShareTimeline');
158
- const useTitleClick = createTaroHook('onTitleClick');
159
- /** Router */
160
- const useReady = createTaroHook('onReady');
161
- const useRouter = (dynamic = false) => {
162
- if (process.env.FRAMEWORK !== 'solid') {
163
- const React = reactMeta.R;
164
- return dynamic ? Current.router : React.useMemo(() => Current.router, []);
165
- }
166
- else {
167
- return dynamic ? Current.router : createMemo(() => Current.router);
168
- }
169
- };
170
- const useTabItemTap = createTaroHook('onTabItemTap');
171
- const useScope = () => undefined;
172
-
173
- var taroHooks = /*#__PURE__*/Object.freeze({
174
- __proto__: null,
175
- useAddToFavorites: useAddToFavorites,
176
- useDidHide: useDidHide,
177
- useDidShow: useDidShow,
178
- useError: useError,
179
- useLaunch: useLaunch,
180
- useLoad: useLoad,
181
- useOptionMenuClick: useOptionMenuClick,
182
- usePageNotFound: usePageNotFound,
183
- usePageScroll: usePageScroll,
184
- usePullDownRefresh: usePullDownRefresh,
185
- usePullIntercept: usePullIntercept,
186
- useReachBottom: useReachBottom,
187
- useReady: useReady,
188
- useResize: useResize,
189
- useRouter: useRouter,
190
- useSaveExitState: useSaveExitState,
191
- useScope: useScope,
192
- useShareAppMessage: useShareAppMessage,
193
- useShareTimeline: useShareTimeline,
194
- useTabItemTap: useTabItemTap,
195
- useTitleClick: useTitleClick,
196
- useUnhandledRejection: useUnhandledRejection,
197
- useUnload: useUnload
198
- });
199
-
200
- let h$1;
201
- let ReactDOM$1;
202
- let Fragment;
203
- const pageKeyId = incrementId();
204
- function setReconciler(ReactDOM) {
205
- hooks.tap('getLifecycle', function (instance, lifecycle) {
206
- lifecycle = lifecycle.replace(/^on(Show|Hide)$/, 'componentDid$1');
207
- return instance[lifecycle];
208
- });
209
- hooks.tap('modifyMpEvent', function (event) {
210
- // Note: ohos 上事件没有设置 type 类型 setter 方法导致报错
211
- Object.defineProperty(event, 'type', {
212
- value: event.type.replace(/-/g, '')
213
- });
214
- });
215
- hooks.tap('batchedEventUpdates', function (cb) {
216
- if (process.env.FRAMEWORK !== 'solid') {
217
- ReactDOM === null || ReactDOM === void 0 ? void 0 : ReactDOM.unstable_batchedUpdates(cb);
218
- }
219
- else {
220
- Solid.batch(cb);
221
- }
222
- });
223
- hooks.tap('mergePageInstance', function (prev, next) {
224
- if (!prev || !next)
225
- return;
226
- // 子组件使用 lifecycle hooks 注册了生命周期后,会存在 prev,里面是注册的生命周期回调。
227
- // prev 使用 Object.create(null) 创建,H5 的 fast-refresh 可能也会导致存在 prev,要排除这些意外产生的 prev
228
- if ('constructor' in prev)
229
- return;
230
- Object.keys(prev).forEach(item => {
231
- const prevList = prev[item];
232
- const nextList = ensureIsArray(next[item]);
233
- next[item] = nextList.concat(prevList);
234
- });
235
- });
236
- // TODO 使用 solid 时,暂不支持以下事件
237
- if (process.env.TARO_PLATFORM === 'web' && process.env.FRAMEWORK !== 'solid') {
238
- hooks.tap('createPullDownComponent', (el, _, R, customWrapper) => {
239
- const isReactComponent = isClassComponent(R, el);
240
- return R.forwardRef((props, ref) => {
241
- const newProps = Object.assign({}, props);
242
- const refs = isReactComponent ? { ref: ref } : {
243
- forwardedRef: ref,
244
- // 兼容 react-redux 7.20.1+
245
- reactReduxForwardedRef: ref
246
- };
247
- return h$1(customWrapper || 'taro-pull-to-refresh-core', null, h$1(el, Object.assign(Object.assign({}, newProps), refs)));
248
- });
249
- });
250
- hooks.tap('getDOMNode', (inst) => {
251
- // 由于react 18移除了ReactDOM.findDOMNode方法,修复H5端 Taro.createSelectorQuery设置in(scope)时,报错问题
252
- // https://zh-hans.react.dev/reference/react-dom/findDOMNode
253
- if (!inst) {
254
- return document;
255
- }
256
- else if (inst instanceof HTMLElement) {
257
- return inst;
258
- }
259
- else if (inst.$taroPath) {
260
- const el = document.getElementById(inst.$taroPath);
261
- return el !== null && el !== void 0 ? el : document;
262
- }
263
- });
264
- }
265
- }
266
- function connectReactPage(R, id) {
267
- return (Page) => {
268
- // eslint-disable-next-line dot-notation
269
- const isReactComponent = isClassComponent(R, Page);
270
- const inject = (node) => node && injectPageInstance(node, id);
271
- const refs = isReactComponent ? { ref: inject } : {
272
- forwardedRef: inject,
273
- // 兼容 react-redux 7.20.1+
274
- reactReduxForwardedRef: inject
275
- };
276
- if (reactMeta.PageContext === EMPTY_OBJ) {
277
- reactMeta.PageContext = R.createContext('');
278
- }
279
- return class PageWrapper extends R.Component {
280
- constructor() {
281
- super(...arguments);
282
- this.state = {
283
- hasError: false
284
- };
285
- }
286
- static getDerivedStateFromError(error) {
287
- var _a, _b;
288
- (_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);
289
- return { hasError: true };
290
- }
291
- // React 16 uncaught error 会导致整个应用 crash,
292
- // 目前把错误缩小到页面
293
- componentDidCatch(error, info) {
294
- if (process.env.NODE_ENV !== 'production') {
295
- console.warn(error);
296
- console.error(info.componentStack);
297
- }
298
- }
299
- render() {
300
- const children = this.state.hasError
301
- ? []
302
- : h$1(reactMeta.PageContext.Provider, { value: id }, h$1(Page, Object.assign(Object.assign({}, this.props), refs)));
303
- if (process.env.TARO_PLATFORM === 'web') {
304
- return h$1('div', { id, className: 'taro_page' }, children);
305
- }
306
- else {
307
- return h$1('root', { id }, children);
308
- }
309
- }
310
- };
311
- };
312
- }
313
- /**
314
- * 桥接小程序 App 构造器和 React 渲染流程
315
- * @param App 用户编写的入口组件
316
- * @param react 框架
317
- * @param dom 框架渲染器
318
- * @param config 入口组件配置 app.config.js 的内容
319
- * @returns 传递给 App 构造器的对象 obj :App(obj)
320
- */
321
- function createReactApp(App, react, dom, config) {
322
- if (process.env.NODE_ENV !== 'production') {
323
- ensure(!!dom, '构建 React/Nerv 项目请把 process.env.FRAMEWORK 设置为 \'react\'/\'preact\'/\'nerv\' ');
324
- }
325
- reactMeta.R = react;
326
- h$1 = react.createElement;
327
- ReactDOM$1 = dom;
328
- Fragment = react.Fragment;
329
- const appInstanceRef = react.createRef();
330
- const isReactComponent = isClassComponent(react, App);
331
- let appWrapper;
332
- let appWrapperResolver;
333
- const appWrapperPromise = new Promise(resolve => (appWrapperResolver = resolve));
334
- setReconciler(ReactDOM$1);
335
- function getAppInstance() {
336
- return appInstanceRef.current;
337
- }
338
- function waitAppWrapper(cb) {
339
- appWrapper ? cb() : appWrapperPromise.then(() => cb());
340
- }
341
- function renderReactRoot() {
342
- var _a, _b;
343
- let appId = 'app';
344
- if (process.env.TARO_PLATFORM === 'web') {
345
- appId = (config === null || config === void 0 ? void 0 : config.appId) || appId;
346
- }
347
- const container = document.getElementById(appId);
348
- if ((react.version || '').startsWith('18')) {
349
- const root = ReactDOM$1.createRoot(container);
350
- (_a = root.render) === null || _a === void 0 ? void 0 : _a.call(root, h$1(AppWrapper));
351
- }
352
- else {
353
- // eslint-disable-next-line react/no-deprecated
354
- (_b = ReactDOM$1.render) === null || _b === void 0 ? void 0 : _b.call(ReactDOM$1, h$1(AppWrapper), container);
355
- }
356
- }
357
- class AppWrapper extends react.Component {
358
- constructor(props) {
359
- super(props);
360
- // run createElement() inside the render function to make sure that owner is right
361
- this.pages = [];
362
- this.elements = [];
363
- appWrapper = this;
364
- appWrapperResolver(this);
365
- }
366
- mount(pageComponent, id, cb) {
367
- const pageWrapper = connectReactPage(react, id)(pageComponent);
368
- const key = id + pageKeyId();
369
- const page = () => h$1(pageWrapper, { key, tid: id });
370
- this.pages.push(page);
371
- this.forceUpdate((...args) => {
372
- perf.stop(PAGE_INIT);
373
- return cb(...args);
374
- });
375
- }
376
- unmount(id, cb) {
377
- const elements = this.elements;
378
- const idx = elements.findIndex(item => item.props.tid === id);
379
- elements.splice(idx, 1);
380
- this.forceUpdate(cb);
381
- }
382
- render() {
383
- const { pages, elements } = this;
384
- while (pages.length > 0) {
385
- const page = pages.pop();
386
- elements.push(page());
387
- }
388
- let props = null;
389
- if (isReactComponent) {
390
- props = { ref: appInstanceRef };
391
- }
392
- return h$1(App, props, process.env.TARO_PLATFORM === 'web' ? h$1(Fragment !== null && Fragment !== void 0 ? Fragment : 'div', null, elements.slice()) : elements.slice());
393
- }
394
- }
395
- if (process.env.TARO_PLATFORM !== 'web') {
396
- renderReactRoot();
397
- }
398
- const [ONLAUNCH, ONSHOW, ONHIDE] = hooks.call('getMiniLifecycleImpl').app;
399
- const appObj = Object.create({
400
- render(cb) {
401
- appWrapper.forceUpdate(cb);
402
- },
403
- mount(component, id, cb) {
404
- if (appWrapper) {
405
- appWrapper.mount(component, id, cb);
406
- }
407
- else {
408
- appWrapperPromise.then(appWrapper => appWrapper.mount(component, id, cb));
409
- }
410
- },
411
- unmount(id, cb) {
412
- appWrapper.unmount(id, cb);
413
- }
414
- }, {
415
- config: setDefaultDescriptor({
416
- configurable: true,
417
- value: config
418
- }),
419
- [ONLAUNCH]: setDefaultDescriptor({
420
- value(options) {
421
- setRouterParams(options);
422
- if (process.env.TARO_PLATFORM === 'web') {
423
- // 由于 H5 路由初始化的时候会清除 app 下的 dom 元素,所以需要在路由初始化后执行 render
424
- renderReactRoot();
425
- }
426
- const onLaunch = () => {
427
- var _a;
428
- // 用户编写的入口组件实例
429
- const app = getAppInstance();
430
- this.$app = app;
431
- if (app) {
432
- // 把 App Class 上挂载的额外属性同步到全局 app 对象中
433
- if (app.taroGlobalData) {
434
- const globalData = app.taroGlobalData;
435
- const keys = Object.keys(globalData);
436
- const descriptors = Object.getOwnPropertyDescriptors(globalData);
437
- keys.forEach(key => {
438
- Object.defineProperty(this, key, {
439
- configurable: true,
440
- enumerable: true,
441
- get() {
442
- return globalData[key];
443
- },
444
- set(value) {
445
- globalData[key] = value;
446
- }
447
- });
448
- });
449
- Object.defineProperties(this, descriptors);
450
- }
451
- (_a = app.onLaunch) === null || _a === void 0 ? void 0 : _a.call(app, options);
452
- }
453
- triggerAppHook('onLaunch', options);
454
- };
455
- waitAppWrapper(onLaunch);
456
- }
457
- }),
458
- [ONSHOW]: setDefaultDescriptor({
459
- value(options) {
460
- setRouterParams(options);
461
- const onShow = () => {
462
- var _a;
463
- /**
464
- * trigger lifecycle
465
- */
466
- const app = getAppInstance();
467
- // class component, componentDidShow
468
- (_a = app === null || app === void 0 ? void 0 : app.componentDidShow) === null || _a === void 0 ? void 0 : _a.call(app, options);
469
- // functional component, useDidShow
470
- triggerAppHook('onShow', options);
471
- };
472
- waitAppWrapper(onShow);
473
- }
474
- }),
475
- [ONHIDE]: setDefaultDescriptor({
476
- value() {
477
- const onHide = () => {
478
- var _a;
479
- /**
480
- * trigger lifecycle
481
- */
482
- const app = getAppInstance();
483
- // class component, componentDidHide
484
- (_a = app === null || app === void 0 ? void 0 : app.componentDidHide) === null || _a === void 0 ? void 0 : _a.call(app);
485
- // functional component, useDidHide
486
- triggerAppHook('onHide');
487
- };
488
- waitAppWrapper(onHide);
489
- }
490
- }),
491
- onError: setDefaultDescriptor({
492
- value(error) {
493
- const onError = () => {
494
- var _a;
495
- const app = getAppInstance();
496
- (_a = app === null || app === void 0 ? void 0 : app.onError) === null || _a === void 0 ? void 0 : _a.call(app, error);
497
- triggerAppHook('onError', error);
498
- if (process.env.NODE_ENV !== 'production' && (error === null || error === void 0 ? void 0 : error.includes('Minified React error'))) {
499
- console.warn('React 出现报错,请打开编译配置 mini.debugReact 查看报错详情:https://docs.taro.zone/docs/config-detail#minidebugreact');
500
- }
501
- };
502
- waitAppWrapper(onError);
503
- }
504
- }),
505
- onUnhandledRejection: setDefaultDescriptor({
506
- value(res) {
507
- const onUnhandledRejection = () => {
508
- var _a;
509
- const app = getAppInstance();
510
- (_a = app === null || app === void 0 ? void 0 : app.onUnhandledRejection) === null || _a === void 0 ? void 0 : _a.call(app, res);
511
- triggerAppHook('onUnhandledRejection', res);
512
- };
513
- waitAppWrapper(onUnhandledRejection);
514
- }
515
- }),
516
- onPageNotFound: setDefaultDescriptor({
517
- value(res) {
518
- const onPageNotFound = () => {
519
- var _a;
520
- const app = getAppInstance();
521
- (_a = app === null || app === void 0 ? void 0 : app.onPageNotFound) === null || _a === void 0 ? void 0 : _a.call(app, res);
522
- triggerAppHook('onPageNotFound', res);
523
- };
524
- waitAppWrapper(onPageNotFound);
525
- }
526
- })
527
- });
528
- function triggerAppHook(lifecycle, ...option) {
529
- const instance = getPageInstance(HOOKS_APP_ID);
530
- if (instance) {
531
- const app = getAppInstance();
532
- const func = hooks.call('getLifecycle', instance, lifecycle);
533
- if (Array.isArray(func)) {
534
- func.forEach(cb => cb.apply(app, option));
535
- }
536
- }
537
- }
538
- Current.app = appObj;
539
- return appObj;
540
- }
541
- function createSolidApp(App, config) {
542
- setReconciler();
543
- const appRef = {
544
- mount: () => { },
545
- unmount: () => { },
546
- };
547
- function getAppInstance() {
548
- return appRef;
549
- }
550
- function AppWrapper() {
551
- const [pages, setPages] = Solid.createSignal([]);
552
- appRef.mount = (component, id) => {
553
- setPages((old) => {
554
- return [...old, { id, component }];
555
- });
556
- };
557
- appRef.unmount = (id) => {
558
- setPages(pages().filter((item) => {
559
- return item.id !== id;
560
- }));
561
- };
562
- return SolidReconciler.createComponent(App, {
563
- ref: appRef,
564
- children: SolidReconciler.createComponent(Solid.For, {
565
- get each() {
566
- return pages();
567
- },
568
- children: ({ id, component }) => {
569
- const children = () => SolidReconciler.createComponent(solidMeta.PageContext.Provider, {
570
- value: id,
571
- children: () => {
572
- injectPageInstance({ id: id, type: 'page' }, id);
573
- return SolidReconciler.createComponent(component, {
574
- tid: id,
575
- });
576
- },
577
- });
578
- const root = process.env.TARO_PLATFORM === 'web'
579
- ? document.createElement('div')
580
- : SolidReconciler.createElement('root');
581
- if (process.env.TARO_PLATFORM === 'web') {
582
- root.setAttribute('id', id);
583
- root.classList.add('taro_page');
584
- }
585
- else {
586
- SolidReconciler.setProp(root, 'id', id);
587
- }
588
- SolidReconciler.insert(root, children);
589
- return root;
590
- },
591
- }),
592
- });
593
- }
594
- function renderSolidRoot() {
595
- let appId = 'app';
596
- if (process.env.TARO_PLATFORM === 'web') {
597
- appId = (config === null || config === void 0 ? void 0 : config.appId) || appId;
598
- }
599
- const container = document.getElementById(appId);
600
- SolidReconciler.render(AppWrapper, container);
601
- }
602
- if (process.env.TARO_PLATFORM !== 'web') {
603
- renderSolidRoot();
604
- }
605
- const [ONLAUNCH, ONSHOW, ONHIDE] = hooks.call('getMiniLifecycleImpl').app;
606
- const appObj = Object.create({
607
- mount(component, id, cb) {
608
- const appInstance = getAppInstance();
609
- appInstance === null || appInstance === void 0 ? void 0 : appInstance.mount(component, id);
610
- Solid.batch((...args) => {
611
- perf.stop(PAGE_INIT);
612
- return cb(...args);
613
- });
614
- },
615
- unmount(id, cb) {
616
- const appInstance = getAppInstance();
617
- appInstance === null || appInstance === void 0 ? void 0 : appInstance.unmount(id);
618
- Solid.batch(cb);
619
- },
620
- }, {
621
- config: setDefaultDescriptor({
622
- configurable: true,
623
- value: config,
624
- }),
625
- [ONLAUNCH]: setDefaultDescriptor({
626
- value(options) {
627
- setRouterParams(options);
628
- if (process.env.TARO_PLATFORM === 'web') {
629
- renderSolidRoot();
630
- }
631
- const onLaunch = () => {
632
- var _a;
633
- const app = getAppInstance();
634
- if (app) {
635
- // 把 App Class 上挂载的额外属性同步到全局 app 对象中
636
- if (app.taroGlobalData) {
637
- const globalData = app.taroGlobalData;
638
- const keys = Object.keys(globalData);
639
- const descriptors = Object.getOwnPropertyDescriptors(globalData);
640
- keys.forEach(key => {
641
- Object.defineProperty(this, key, {
642
- configurable: true,
643
- enumerable: true,
644
- get() {
645
- return globalData[key];
646
- },
647
- set(value) {
648
- globalData[key] = value;
649
- }
650
- });
651
- });
652
- Object.defineProperties(this, descriptors);
653
- }
654
- (_a = app.onCreate) === null || _a === void 0 ? void 0 : _a.call(app);
655
- }
656
- };
657
- onLaunch();
658
- triggerAppHook('onLaunch', options);
659
- },
660
- }),
661
- [ONSHOW]: setDefaultDescriptor({
662
- value(options) {
663
- setRouterParams(options);
664
- triggerAppHook('onShow', options);
665
- },
666
- }),
667
- [ONHIDE]: setDefaultDescriptor({
668
- value() {
669
- triggerAppHook('onHide');
670
- },
671
- }),
672
- onError: setDefaultDescriptor({
673
- value(error) {
674
- triggerAppHook('onError', error);
675
- },
676
- }),
677
- onPageNotFound: setDefaultDescriptor({
678
- value(res) {
679
- triggerAppHook('onPageNotFound', res);
680
- },
681
- }),
682
- });
683
- function triggerAppHook(lifecycle, ...option) {
684
- const instance = getPageInstance(HOOKS_APP_ID);
685
- if (instance) {
686
- const app = getAppInstance();
687
- const func = hooks.call('getLifecycle', instance, lifecycle);
688
- if (Array.isArray(func)) {
689
- func.forEach((cb) => cb.apply(app, option));
690
- }
691
- }
692
- }
693
- Current.app = appObj;
694
- return appObj;
695
- }
696
-
697
- const getNativeCompId = incrementId();
698
- let h;
699
- let ReactDOM;
700
- let nativeComponentApp;
701
- function initNativeComponentEntry(params) {
702
- const { R, ReactDOM, cb, isDefaultEntryDom = true } = params;
703
- class NativeComponentWrapper extends R.Component {
704
- constructor() {
705
- super(...arguments);
706
- this.root = R.createRef();
707
- this.ctx = this.props.getCtx();
708
- }
709
- componentDidMount() {
710
- this.ctx.component = this;
711
- const rootElement = this.root.current;
712
- rootElement.ctx = this.ctx;
713
- rootElement.performUpdate(true);
714
- }
715
- render() {
716
- return (h('root', {
717
- ref: this.root,
718
- id: this.props.compId
719
- }, this.props.renderComponent(this.ctx)));
720
- }
721
- }
722
- class Entry extends R.Component {
723
- constructor() {
724
- super(...arguments);
725
- this.state = {
726
- components: []
727
- };
728
- }
729
- componentDidMount() {
730
- if (isDefaultEntryDom) {
731
- Current.app = this;
732
- }
733
- else {
734
- nativeComponentApp = this;
735
- }
736
- cb && cb();
737
- }
738
- mount(Component, compId, getCtx, cb) {
739
- const isReactComponent = isClassComponent(R, Component);
740
- const inject = (node) => node && injectPageInstance(node, compId);
741
- const refs = isReactComponent ? { ref: inject } : {
742
- forwardedRef: inject,
743
- reactReduxForwardedRef: inject
744
- };
745
- if (reactMeta.PageContext === EMPTY_OBJ) {
746
- reactMeta.PageContext = R.createContext('');
747
- }
748
- const item = {
749
- compId,
750
- element: h(NativeComponentWrapper, {
751
- key: compId,
752
- compId,
753
- getCtx,
754
- renderComponent(ctx) {
755
- return h(reactMeta.PageContext.Provider, { value: compId }, h(Component, Object.assign(Object.assign(Object.assign({}, (ctx.data || (ctx.data = {})).props), refs), { $scope: ctx })));
756
- }
757
- })
758
- };
759
- this.setState({
760
- components: [...this.state.components, item]
761
- }, () => cb && cb());
762
- }
763
- unmount(compId, cb) {
764
- const components = this.state.components;
765
- const index = components.findIndex(item => item.compId === compId);
766
- const next = [...components.slice(0, index), ...components.slice(index + 1)];
767
- this.setState({
768
- components: next
769
- }, () => {
770
- removePageInstance(compId);
771
- cb && cb();
772
- });
773
- }
774
- render() {
775
- const components = this.state.components;
776
- return (components.map(({ element }) => element));
777
- }
778
- }
779
- setReconciler(ReactDOM);
780
- let app = document.getElementById('app');
781
- if (!isDefaultEntryDom && !nativeComponentApp) {
782
- // create
783
- const nativeApp = document.createElement('nativeComponent');
784
- // insert
785
- app === null || app === void 0 ? void 0 : app.appendChild(nativeApp);
786
- app = nativeApp;
787
- }
788
- // eslint-disable-next-line react/no-deprecated
789
- ReactDOM.render(h(Entry, {}), app);
790
- }
791
- function createNativePageConfig(Component, pageName, data, react, reactDOM, pageConfig) {
792
- reactMeta.R = react;
793
- h = react.createElement;
794
- ReactDOM = reactDOM;
795
- setReconciler(ReactDOM);
796
- const [ONLOAD, ONUNLOAD, ONREADY, ONSHOW, ONHIDE, LIFECYCLES, SIDE_EFFECT_LIFECYCLES] = hooks.call('getMiniLifecycleImpl').page;
797
- let unmounting = false;
798
- let prepareMountList = [];
799
- let pageElement = null;
800
- let loadResolver;
801
- let hasLoaded;
802
- const id = pageName !== null && pageName !== void 0 ? pageName : `taro_page_${getNativeCompId()}`;
803
- function setCurrentRouter(page) {
804
- const router = page.route || page.__route__ || page.$taroPath;
805
- Current.router = {
806
- params: page.$taroParams,
807
- path: addLeadingSlash(router),
808
- $taroPath: page.$taroPath,
809
- onReady: getOnReadyEventKey(id),
810
- onShow: getOnShowEventKey(id),
811
- onHide: getOnHideEventKey(id)
812
- };
813
- if (!isUndefined(page.exitState)) {
814
- Current.router.exitState = page.exitState;
815
- }
816
- }
817
- const pageObj = {
818
- options: pageConfig,
819
- [ONLOAD](options = {}, cb) {
820
- hasLoaded = new Promise(resolve => { loadResolver = resolve; });
821
- Current.page = this;
822
- this.config = pageConfig || {};
823
- // this.$taroPath 是页面唯一标识
824
- const uniqueOptions = Object.assign({}, options, { $taroTimestamp: Date.now() });
825
- const $taroPath = this.$taroPath = getPath(id, uniqueOptions);
826
- // this.$taroParams 作为暴露给开发者的页面参数对象,可以被随意修改
827
- if (this.$taroParams == null) {
828
- this.$taroParams = uniqueOptions;
829
- }
830
- setCurrentRouter(this);
831
- window.trigger(CONTEXT_ACTIONS.INIT, $taroPath);
832
- const mountCallback = () => {
833
- pageElement = document.getElementById($taroPath);
834
- ensure(pageElement !== null, '没有找到页面实例。');
835
- safeExecute($taroPath, ONLOAD, this.$taroParams);
836
- loadResolver();
837
- pageElement.ctx = this;
838
- pageElement.performUpdate(true, cb);
839
- };
840
- const mount = () => {
841
- if (!Current.app) {
842
- initNativeComponentEntry({
843
- R: react,
844
- ReactDOM,
845
- cb: () => {
846
- Current.app.mount(Component, $taroPath, () => this, mountCallback);
847
- }
848
- });
849
- }
850
- else {
851
- Current.app.mount(Component, $taroPath, () => this, mountCallback);
852
- }
853
- };
854
- if (unmounting) {
855
- prepareMountList.push(mount);
856
- }
857
- else {
858
- mount();
859
- }
860
- },
861
- [ONUNLOAD]() {
862
- const $taroPath = this.$taroPath;
863
- // 销毁当前页面的上下文信息
864
- window.trigger(CONTEXT_ACTIONS.DESTORY, $taroPath);
865
- // 触发onUnload生命周期
866
- safeExecute($taroPath, ONUNLOAD);
867
- resetCurrent();
868
- unmounting = true;
869
- Current.app.unmount($taroPath, () => {
870
- unmounting = false;
871
- removePageInstance($taroPath);
872
- if (pageElement) {
873
- pageElement.ctx = null;
874
- pageElement = null;
875
- }
876
- if (prepareMountList.length) {
877
- prepareMountList.forEach(fn => fn());
878
- prepareMountList = [];
879
- }
880
- });
881
- },
882
- [ONREADY]() {
883
- hasLoaded.then(() => {
884
- // 触发生命周期
885
- safeExecute(this.$taroPath, ON_READY);
886
- // 通过事件触发子组件的生命周期
887
- requestAnimationFrame(() => eventCenter.trigger(getOnReadyEventKey(id)));
888
- this.onReady.called = true;
889
- });
890
- },
891
- [ONSHOW](options = {}) {
892
- hasLoaded.then(() => {
893
- // 设置 Current 的 page 和 router
894
- Current.page = this;
895
- setCurrentRouter(this);
896
- // 恢复上下文信息
897
- window.trigger(CONTEXT_ACTIONS.RECOVER, this.$taroPath);
898
- // 触发生命周期
899
- safeExecute(this.$taroPath, ON_SHOW, options);
900
- // 通过事件触发子组件的生命周期
901
- requestAnimationFrame(() => eventCenter.trigger(getOnShowEventKey(id)));
902
- });
903
- },
904
- [ONHIDE]() {
905
- // 缓存当前页面上下文信息
906
- window.trigger(CONTEXT_ACTIONS.RESTORE, this.$taroPath);
907
- // 设置 Current 的 page 和 router
908
- if (Current.page === this) {
909
- Current.page = null;
910
- Current.router = null;
911
- }
912
- // 触发生命周期
913
- safeExecute(this.$taroPath, ON_HIDE);
914
- // 通过事件触发子组件的生命周期
915
- eventCenter.trigger(getOnHideEventKey(id));
916
- },
917
- };
918
- function resetCurrent() {
919
- // 小程序插件页面卸载之后返回到宿主页面时,需重置Current页面和路由。否则引发插件组件二次加载异常 fix:#11991
920
- Current.page = null;
921
- Current.router = null;
922
- }
923
- LIFECYCLES.forEach((lifecycle) => {
924
- pageObj[lifecycle] = function () {
925
- return safeExecute(this.$taroPath, lifecycle, ...arguments);
926
- };
927
- });
928
- // onShareAppMessage 和 onShareTimeline 一样,会影响小程序右上方按钮的选项,因此不能默认注册。
929
- SIDE_EFFECT_LIFECYCLES.forEach(lifecycle => {
930
- var _a;
931
- if (Component[lifecycle] ||
932
- ((_a = Component.prototype) === null || _a === void 0 ? void 0 : _a[lifecycle]) ||
933
- Component[lifecycle.replace(/^on/, 'enable')]) {
934
- pageObj[lifecycle] = function (...args) {
935
- var _a;
936
- const target = (_a = args[0]) === null || _a === void 0 ? void 0 : _a.target;
937
- if (target === null || target === void 0 ? void 0 : target.id) {
938
- const id = target.id;
939
- const element = document.getElementById(id);
940
- if (element) {
941
- target.dataset = element.dataset;
942
- }
943
- }
944
- return safeExecute(this.$taroPath, lifecycle, ...args);
945
- };
946
- }
947
- });
948
- pageObj.eh = eventHandler;
949
- if (!isUndefined(data)) {
950
- pageObj.data = data;
951
- }
952
- hooks.call('modifyPageObject', pageObj);
953
- return pageObj;
954
- }
955
- function createH5NativeComponentConfig(Component, react, reactdom) {
956
- reactMeta.R = react;
957
- h = react.createElement;
958
- ReactDOM = reactdom;
959
- setReconciler(ReactDOM);
960
- return Component;
961
- }
962
- function createNativeComponentConfig(Component, react, reactdom, componentConfig) {
963
- var _a, _b;
964
- reactMeta.R = react;
965
- h = react.createElement;
966
- ReactDOM = reactdom;
967
- setReconciler(ReactDOM);
968
- const { isNewBlended } = componentConfig;
969
- const componentObj = {
970
- options: componentConfig,
971
- properties: {
972
- props: {
973
- type: null,
974
- value: null,
975
- observer(_newVal, oldVal) {
976
- var _a;
977
- oldVal && ((_a = this.component) === null || _a === void 0 ? void 0 : _a.forceUpdate());
978
- }
979
- }
980
- },
981
- created() {
982
- const app = (isNewBlended ? nativeComponentApp : Current.app);
983
- if (!app) {
984
- initNativeComponentEntry({
985
- R: react,
986
- ReactDOM,
987
- isDefaultEntryDom: !isNewBlended
988
- });
989
- }
990
- },
991
- attached() {
992
- const compId = this.compId = getNativeCompId();
993
- setCurrent(compId);
994
- this.config = componentConfig;
995
- const app = (isNewBlended ? nativeComponentApp : Current.app);
996
- app.mount(Component, compId, () => this, () => {
997
- const instance = getPageInstance(compId);
998
- if (instance && instance.node) {
999
- const el = document.getElementById(instance.node.uid);
1000
- if (el) {
1001
- el.ctx = this;
1002
- }
1003
- }
1004
- });
1005
- },
1006
- ready() {
1007
- safeExecute(this.compId, 'onReady');
1008
- },
1009
- detached() {
1010
- resetCurrent();
1011
- const app = (isNewBlended ? nativeComponentApp : Current.app);
1012
- app.unmount(this.compId);
1013
- },
1014
- pageLifetimes: {
1015
- show(options) {
1016
- safeExecute(this.compId, 'onShow', options);
1017
- },
1018
- hide() {
1019
- safeExecute(this.compId, 'onHide');
1020
- }
1021
- },
1022
- methods: {
1023
- eh: eventHandler,
1024
- onLoad(options) {
1025
- safeExecute(this.compId, 'onLoad', options);
1026
- },
1027
- onUnload() {
1028
- safeExecute(this.compId, 'onUnload');
1029
- }
1030
- }
1031
- };
1032
- function resetCurrent() {
1033
- // 小程序插件页面卸载之后返回到宿主页面时,需重置Current页面和路由。否则引发插件组件二次加载异常 fix:#11991
1034
- Current.page = null;
1035
- Current.router = null;
1036
- }
1037
- // onShareAppMessage 和 onShareTimeline 一样,会影响小程序右上方按钮的选项,因此不能默认注册。
1038
- if (Component.onShareAppMessage ||
1039
- ((_a = Component.prototype) === null || _a === void 0 ? void 0 : _a.onShareAppMessage) ||
1040
- Component.enableShareAppMessage) {
1041
- componentObj.methods.onShareAppMessage = function (options) {
1042
- const target = options === null || options === void 0 ? void 0 : options.target;
1043
- if (target) {
1044
- const id = target.id;
1045
- const element = document.getElementById(id);
1046
- if (element) {
1047
- target.dataset = element.dataset;
1048
- }
1049
- }
1050
- return safeExecute(this.compId, 'onShareAppMessage', options);
1051
- };
1052
- }
1053
- if (Component.onShareTimeline ||
1054
- ((_b = Component.prototype) === null || _b === void 0 ? void 0 : _b.onShareTimeline) ||
1055
- Component.enableShareTimeline) {
1056
- componentObj.methods.onShareTimeline = function () {
1057
- return safeExecute(this.compId, 'onShareTimeline');
1058
- };
1059
- }
1060
- return componentObj;
1061
- }
1062
- function setCurrent(compId) {
1063
- if (!getCurrentPages || typeof getCurrentPages !== 'function')
1064
- return;
1065
- const pages = getCurrentPages();
1066
- const currentPage = pages[pages.length - 1];
1067
- if (Current.page === currentPage)
1068
- return;
1069
- Current.page = currentPage;
1070
- const route = currentPage.route || currentPage.__route__;
1071
- const router = {
1072
- params: currentPage.options || {},
1073
- path: addLeadingSlash(route),
1074
- $taroPath: compId,
1075
- onReady: '',
1076
- onHide: '',
1077
- onShow: ''
1078
- };
1079
- Current.router = router;
1080
- if (!currentPage.options) {
1081
- // 例如在微信小程序中,页面 options 的设置时机比组件 attached 慢
1082
- Object.defineProperty(currentPage, 'options', {
1083
- enumerable: true,
1084
- configurable: true,
1085
- get() {
1086
- return this._optionsValue;
1087
- },
1088
- set(value) {
1089
- router.params = value;
1090
- this._optionsValue = value;
1091
- }
1092
- });
1093
- }
1094
- }
1095
-
1096
- hooks.tap('initNativeApi', function (taro) {
1097
- for (const hook in taroHooks) {
1098
- taro[hook] = taroHooks[hook];
1099
- }
1100
- });
1101
- if (process.env.FRAMEWORK === 'preact' && process.env.TARO_PLATFORM === 'mini') {
1102
- const options = require('preact').options;
1103
- const oldVNodeHook = options.vnode;
1104
- const oldDiffedHook = options.diffed;
1105
- options.vnode = vnode => {
1106
- const { type, props } = vnode;
1107
- let normalizedProps = props;
1108
- // only normalize props on Element nodes
1109
- if (typeof type === 'string') {
1110
- normalizedProps = {};
1111
- for (let i in props) {
1112
- const value = props[i];
1113
- if (/^on/.test(i)) {
1114
- i = i.toLowerCase();
1115
- }
1116
- if (type === 'map' && i === 'onregionchange') {
1117
- // map 组件的 regionchange 事件非常特殊,详情:https://github.com/NervJS/taro/issues/5766
1118
- normalizedProps.onbegin = value;
1119
- normalizedProps.onend = value;
1120
- continue;
1121
- }
1122
- normalizedProps[i] = value;
1123
- }
1124
- vnode.props = normalizedProps;
1125
- }
1126
- if (oldVNodeHook)
1127
- oldVNodeHook(vnode);
1128
- };
1129
- options.diffed = function (newVNode) {
1130
- var _a;
1131
- const domProp = Object.keys(newVNode).find(k => { var _a; return ((_a = newVNode[k]) === null || _a === void 0 ? void 0 : _a.setAttribute); });
1132
- const dom = domProp ? newVNode[domProp] : null;
1133
- const newVNodeProps = newVNode.props;
1134
- if (dom) { /** ElementNode */
1135
- for (const propName in newVNodeProps) {
1136
- const propValue = newVNodeProps[propName];
1137
- if (propValue === false && ((_a = dom.props) === null || _a === void 0 ? void 0 : _a[propName]) === undefined) {
1138
- // 值为 false 的属性在 Preact 的 diff 中被 removeAttribute 了,这里手动 setAttribute
1139
- // fix https://github.com/NervJS/taro/issues/11197
1140
- dom.setAttribute(propName, propValue);
1141
- }
1142
- }
1143
- }
1144
- if (oldDiffedHook)
1145
- oldDiffedHook(newVNode);
1146
- };
1147
- hooks.tap('modifyMpEvent', e => {
1148
- const type = e.type;
1149
- if (type === 'tap') {
1150
- e.type = 'click';
1151
- }
1152
- else if (type === 'focus') {
1153
- // 兼容 preact/compat/src/render.js options.vnode 的处理逻辑
1154
- e.type = 'focusin';
1155
- }
1156
- else if (type === 'blur') {
1157
- e.type = 'focusout';
1158
- }
1159
- });
1160
- // hooks.modifyDispatchEventImpls?.push(e => {
1161
- // })
1162
- }
1163
-
1164
- export { connectReactPage, createH5NativeComponentConfig, createNativeComponentConfig, createNativePageConfig, createReactApp, createSolidApp, setReconciler, useAddToFavorites, useDidHide, useDidShow, useError, useLaunch, useLoad, useOptionMenuClick, usePageNotFound, usePageScroll, usePullDownRefresh, usePullIntercept, useReachBottom, useReady, useResize, useRouter, useSaveExitState, useScope, useShareAppMessage, useShareTimeline, useTabItemTap, useTitleClick, useUnhandledRejection, useUnload };
1165
- //# sourceMappingURL=runtime.js.map