-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
common.ts
348 lines (311 loc) · 9.53 KB
/
common.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/* eslint-disable dot-notation */
import { isFunction, EMPTY_OBJ, ensure, Shortcuts, isUndefined, isArray, warn } from '@tarojs/shared'
import { eventHandler } from '../dom/event'
import { Current } from '../current'
import { document } from '../bom/document'
import { TaroRootElement } from '../dom/root'
import { MpInstance } from '../hydrate'
import { Instance, PageInstance, PageProps } from './instance'
import { incrementId } from '../utils'
import { perf } from '../perf'
import { PAGE_INIT } from '../constants'
import { isBrowser } from '../env'
import { eventCenter } from '../emitter/emitter'
import { raf } from '../bom/raf'
import { CurrentReconciler } from '../reconciler'
import type { PageConfig } from '@tarojs/taro'
import type { Func } from '../utils/types'
const instances = new Map<string, Instance>()
export function injectPageInstance (inst: Instance<PageProps>, id: string) {
CurrentReconciler.mergePageInstance?.(instances.get(id), inst)
instances.set(id, inst)
}
export function getPageInstance (id: string) {
return instances.get(id)
}
export function addLeadingSlash (path?: string) {
if (path == null) {
return ''
}
return path.charAt(0) === '/' ? path : '/' + path
}
const pageId = incrementId()
export function safeExecute (path: string, lifecycle: keyof PageInstance, ...args: unknown[]) {
const instance = instances.get(path)
if (instance == null) {
return
}
const func = CurrentReconciler.getLifecyle(instance, lifecycle)
if (isArray(func)) {
const res = func.map(fn => fn.apply(instance, args))
return res[0]
}
if (!isFunction(func)) {
return
}
return func.apply(instance, args)
}
export function stringify (obj?: Record<string, unknown>) {
if (obj == null) {
return ''
}
const path = Object.keys(obj).map((key) => {
return key + '=' + obj[key]
}).join('&')
return path === '' ? path : '?' + path
}
export function getPath (id: string, options?: Record<string, unknown>): string {
let path = id
if (!isBrowser) {
path = id + stringify(options)
}
return path
}
export function getOnReadyEventKey (path: string) {
return path + '.' + 'onReady'
}
export function getOnShowEventKey (path: string) {
return path + '.' + 'onShow'
}
export function getOnHideEventKey (path: string) {
return path + '.' + 'onHide'
}
export function createPageConfig (component: any, pageName?: string, data?: Record<string, unknown>, pageConfig?: PageConfig) {
const id = pageName ?? `taro_page_${pageId()}`
// 小程序 Page 构造器是一个傲娇小公主,不能把复杂的对象挂载到参数上
let pageElement: TaroRootElement | null = null
let unmounting = false
let prepareMountList: (() => void)[] = []
const config: PageInstance = {
onLoad (this: MpInstance, options, cb?: Func) {
perf.start(PAGE_INIT)
Current.page = this as any
this.config = pageConfig || {}
if (this.options == null) {
this.options = options
}
const path = getPath(id, options)
const router = isBrowser ? path : this.route || this.__route__
Current.router = {
params: options,
path: addLeadingSlash(router),
onReady: getOnReadyEventKey(id),
onShow: getOnShowEventKey(id),
onHide: getOnHideEventKey(id)
}
const mount = () => {
Current.app!.mount!(component, path, () => {
pageElement = document.getElementById<TaroRootElement>(path)
ensure(pageElement !== null, '没有找到页面实例。')
safeExecute(path, 'onLoad', options)
if (!isBrowser) {
pageElement.ctx = this
pageElement.performUpdate(true, cb)
}
})
}
if (unmounting) {
prepareMountList.push(mount)
} else {
mount()
}
},
onReady () {
const path = getPath(id, this.options)
raf(() => {
eventCenter.trigger(getOnReadyEventKey(id))
})
safeExecute(path, 'onReady')
this.onReady.called = true
},
onUnload () {
const path = getPath(id, this.options)
unmounting = true
Current.app!.unmount!(path, () => {
unmounting = false
instances.delete(path)
if (pageElement) {
pageElement.ctx = null
}
if (prepareMountList.length) {
prepareMountList.forEach(fn => fn())
prepareMountList = []
}
})
},
onShow () {
Current.page = this as any
this.config = pageConfig || {}
const path = getPath(id, this.options)
const router = isBrowser ? path : this.route || this.__route__
Current.router = {
params: this.options,
path: addLeadingSlash(router),
onReady: getOnReadyEventKey(id),
onShow: getOnShowEventKey(id),
onHide: getOnHideEventKey(id)
}
raf(() => {
eventCenter.trigger(getOnShowEventKey(id))
})
safeExecute(path, 'onShow')
},
onHide () {
Current.page = null
Current.router = null
const path = getPath(id, this.options)
safeExecute(path, 'onHide')
eventCenter.trigger(getOnHideEventKey(id))
},
onPullDownRefresh () {
const path = getPath(id, this.options)
return safeExecute(path, 'onPullDownRefresh')
},
onReachBottom () {
const path = getPath(id, this.options)
return safeExecute(path, 'onReachBottom')
},
onPageScroll (options) {
const path = getPath(id, this.options)
return safeExecute(path, 'onPageScroll', options)
},
onResize (options) {
const path = getPath(id, this.options)
return safeExecute(path, 'onResize', options)
},
onTabItemTap (options) {
const path = getPath(id, this.options)
return safeExecute(path, 'onTabItemTap', options)
},
onTitleClick () {
const path = getPath(id, this.options)
return safeExecute(path, 'onTitleClick')
},
onOptionMenuClick () {
const path = getPath(id, this.options)
return safeExecute(path, 'onOptionMenuClick')
},
onPopMenuClick () {
const path = getPath(id, this.options)
return safeExecute(path, 'onPopMenuClick')
},
onPullIntercept () {
const path = getPath(id, this.options)
return safeExecute(path, 'onPullIntercept')
},
onAddToFavorites () {
const path = getPath(id, this.options)
return safeExecute(path, 'onAddToFavorites')
}
}
// onShareAppMessage 和 onShareTimeline 一样,会影响小程序右上方按钮的选项,因此不能默认注册。
if (component.onShareAppMessage ||
component.prototype?.onShareAppMessage ||
component.enableShareAppMessage) {
config.onShareAppMessage = function (options) {
const target = options.target
if (target != null) {
const id = target.id
const element = document.getElementById(id)
if (element != null) {
options.target!.dataset = element.dataset
}
}
const path = getPath(id, this.options)
return safeExecute(path, 'onShareAppMessage', options)
}
}
if (component.onShareTimeline ||
component.prototype?.onShareTimeline ||
component.enableShareTimeline) {
config.onShareTimeline = function () {
const path = getPath(id, this.options)
return safeExecute(path, 'onShareTimeline')
}
}
config.eh = eventHandler
if (!isUndefined(data)) {
config.data = data
}
if (isBrowser) {
config.path = id
}
return config
}
export function createComponentConfig (component: React.ComponentClass, componentName?: string, data?: Record<string, unknown>) {
const id = componentName ?? `taro_component_${pageId()}`
let componentElement: TaroRootElement | null = null
const config: any = {
attached () {
perf.start(PAGE_INIT)
const path = getPath(id, { id: this.getPageId() })
Current.app!.mount!(component, path, () => {
componentElement = document.getElementById<TaroRootElement>(path)
ensure(componentElement !== null, '没有找到组件实例。')
safeExecute(path, 'onLoad')
if (!isBrowser) {
componentElement.ctx = this
componentElement.performUpdate(true)
}
})
},
detached () {
const path = getPath(id, { id: this.getPageId() })
Current.app!.unmount!(path, () => {
instances.delete(path)
if (componentElement) {
componentElement.ctx = null
}
})
},
pageLifetimes: {
show () {
safeExecute(id, 'onShow')
},
hide () {
safeExecute(id, 'onHide')
}
},
methods: {
eh: eventHandler
}
}
if (!isUndefined(data)) {
config.data = data
}
config['options'] = component?.['options'] ?? EMPTY_OBJ
config['externalClasses'] = component?.['externalClasses'] ?? EMPTY_OBJ
config['behaviors'] = component?.['behaviors'] ?? EMPTY_OBJ
return config
}
export function createRecursiveComponentConfig (componentName?: string) {
return {
properties: {
i: {
type: Object,
value: {
[Shortcuts.NodeName]: 'view'
}
},
l: {
type: String,
value: ''
}
},
observers: {
i (val: Record<string, unknown>) {
warn(
val[Shortcuts.NodeName] === '#text',
`请在此元素外再套一层非 Text 元素:<text>${val[Shortcuts.Text]}</text>,详情:https://github.com/NervJS/taro/issues/6054`
)
}
},
options: {
addGlobalClass: true,
virtualHost: componentName !== 'custom-wrapper'
},
methods: {
eh: eventHandler
}
}
}