forked from didi/dimina
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathminiApp.js
More file actions
1996 lines (1759 loc) · 60.7 KB
/
Copy pathminiApp.js
File metadata and controls
1996 lines (1759 loc) · 60.7 KB
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { LAUNCH_SCREEN_MIN_MS, WAIT_TRANSITION_TIMEOUT_MS } from '@/constants/animation'
import { AppManager } from '@/core/appManager'
import { Bridge } from '@/core/bridge'
import { JSCore } from '@/core/jscore'
import { HashRouter } from '@/utils/hashRouter'
import { mergePageConfig, queryPath, readFile, sleep, uuid } from '@/utils/util'
// 等待元素上指定 transition property 结束,带超时兜底防止动画未触发时永久阻塞
const waitTransitionEnd = (el, property, timeout = WAIT_TRANSITION_TIMEOUT_MS) =>
new Promise(resolve => {
const timer = setTimeout(resolve, timeout)
const handler = (e) => {
if (!property || e.propertyName === property) {
clearTimeout(timer)
el.removeEventListener('transitionend', handler)
resolve()
}
}
el.addEventListener('transitionend', handler)
})
import tpl from './miniApp.html?raw'
import './miniApp.scss'
export class MiniApp {
constructor(opts) {
this.appInfo = opts
this.id = `mini_app_${uuid()}`
this.parent = null
this.appId = opts.appId
this.appConfig = null
this.bridgeList = []
this.jscore = new JSCore(this)
this.webviewsContainer = null
this.webviewAnimaEnd = true
this.el = document.createElement('div')
this.el.classList.add('dimina-native-view')
this.toastInfo = {
dom: null,
timer: null,
}
this.color = null
this.apiRegistry = {}
// 维护第三方扩展的持续订阅,key: `${module}_${event}`,value: unsubscribe 函数
this._extSubscriptions = new Map();
this.tabBarConfig = null // app.tabBar 配置
this.tabBarPaths = [] // 与 list 等长,pagePath 数组(已规范化、无前导 /)
this.tabBarBridges = new Map() // pagePath -> Bridge:懒加载的持久 tab 池
this.currentTabPath = null // 当前激活的 tab 路径;null 表示当前不在任何 tab 页
this.tabBarEl = null // .dimina-mini-app__tabbar 根节点
// showModal 用 LIFO stack:后来的 modal 压在前一个之上(z-index 递增),
// 关闭顶上 modal 露出下方;前后 modal 互不干扰,各自 success/complete 独立。
this._modalStack = []
this._modalPendingTimers = new Set()
this._destroyed = false
}
/**
* 规范化 pagePath:去除前导 /,与 app.tabBar.list 中声明的格式对齐。
*/
_normalizePagePath(path) {
if (!path) return ''
return path.startsWith('/') ? path.slice(1) : path
}
/**
* 判断给定路径是否为 tabBar 页面。
*/
_isTabBarPage(pagePath) {
return this.tabBarPaths.includes(this._normalizePagePath(pagePath))
}
getCurrentPagePath() {
const currentBridge = this.bridgeList[this.bridgeList.length - 1]
return currentBridge?.opts?.pagePath || this.appInfo.pagePath || this.appConfig?.app?.entryPagePath || ''
}
getCurrentPageQuery() {
const currentBridge = this.bridgeList[this.bridgeList.length - 1]
return currentBridge?.opts?.query || this.appInfo.query || {}
}
getEntryPagePath() {
return this.appInfo.pagePath || this.appConfig?.app?.entryPagePath || ''
}
async copyText(text, successText) {
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text)
}
else {
const textarea = document.createElement('textarea')
textarea.value = text
textarea.setAttribute('readonly', 'readonly')
textarea.style.position = 'fixed'
textarea.style.opacity = '0'
document.body.appendChild(textarea)
textarea.select()
document.execCommand('copy')
document.body.removeChild(textarea)
}
this.showToast({
title: successText,
icon: 'success',
})
}
catch {
this.showToast({
title: '复制失败',
icon: 'none',
})
}
}
closeMiniProgram() {
HashRouter.clear()
this.closeMiniAppMenu()
AppManager.closeApp(this)
}
renderMiniAppMenu() {
const name = this.el.querySelector('.dimina-mini-app-menu__app-name')
const appId = this.el.querySelector('.dimina-mini-app-menu__app-id')
const desc = this.el.querySelector('.dimina-mini-app-menu__app-desc')
const logo = this.el.querySelector('.dimina-mini-app-menu__app-logo-img')
const quickActions = this.el.querySelector('.dimina-mini-app-menu__quick-actions')
const currentPagePath = this.getCurrentPagePath()
const entryPagePath = this.getEntryPagePath()
const currentPageQuery = this.getCurrentPageQuery()
const pagePath = currentPagePath || entryPagePath || ''
const pageWithQuery = `${pagePath}${Object.keys(currentPageQuery).length ? `?${new URLSearchParams(currentPageQuery).toString()}` : ''}`
const addressUrl = `${window.location.origin}${window.location.pathname}#${this.appId}|${pageWithQuery}`
name.textContent = this.appInfo.name || '未命名小程序'
appId.textContent = `AppID:${this.appId || '--'}`
desc.textContent = `当前页面:${pagePath || '--'}`
logo.src = this.appInfo.logo || ''
const quickActionItems = [
{
label: '复制链接',
icon: '↗',
handler: () => this.copyText(addressUrl, '链接已复制'),
},
{
label: '重新进入',
icon: '↻',
handler: () => {
this.closeMiniAppMenu()
this.reLaunch({
url: entryPagePath || currentPagePath,
})
},
},
{
label: '关闭小程序',
icon: '×',
danger: true,
handler: () => this.closeMiniProgram(),
},
]
quickActions.innerHTML = quickActionItems
.map((item, index) => `
<button type="button" class="dimina-mini-app-menu__quick-action${item.danger ? ' is-danger' : ''}" data-quick-index="${index}">
<span class="dimina-mini-app-menu__quick-action-icon">${item.icon}</span>
<span class="dimina-mini-app-menu__quick-action-label">${item.label}</span>
</button>
`)
.join('')
quickActions.querySelectorAll('[data-quick-index]').forEach((node, index) => {
node.onclick = () => quickActionItems[index].handler()
})
}
openMiniAppMenu() {
const overlay = this.el.querySelector('.dimina-mini-app-menu__mask')
const menu = this.el.querySelector('.dimina-mini-app-menu')
this.renderMiniAppMenu()
overlay.style.display = 'block'
requestAnimationFrame(() => {
overlay.classList.add('show')
menu.classList.add('show')
})
}
closeMiniAppMenu() {
const overlay = this.el.querySelector('.dimina-mini-app-menu__mask')
const menu = this.el.querySelector('.dimina-mini-app-menu')
overlay.classList.remove('show')
menu.classList.remove('show')
}
/**
* 注册自定义 API 处理函数
* @param {string} name API 名称
* @param {function} handler 处理函数,接收 (params)
*/
registerApi(name, handler) {
this.apiRegistry[name] = handler
}
/**
* 按名称调用 API,优先查找自定义注册 → 内置方法 → 第三方扩展路由
* @param {string} name API 名称
* @param {object} params API 参数
*/
invokeApi(name, params) {
const handler = this.apiRegistry[name]
if (handler) {
handler.call(this, params)
}
else if (typeof this[name] === 'function') {
this[name](params)
}
else {
// 未命中已知方法,转发给第三方扩展路由处理
this._handleExtCall(name, params)
}
}
viewDidLoad() {
this.initPageFrame()
this.webviewsContainer = this.el.querySelector('.dimina-mini-app__webviews')
this.showLaunchScreen()
this.bindMoreEvent()
this.bindCloseEvent()
this.initApp()
}
async initApp() {
// 1. 等待逻辑线程初始化
await this.jscore.init()
// 2. 读取配置文件,同时保证 LaunchScreen 最少展示一个略长于 present 的时长
const root = 'main'
const configPath = `${this.appInfo.appId}/${root}/app-config.json`
const [configContent] = await Promise.all([
readFile(`${import.meta.env.BASE_URL}${configPath}`),
sleep(LAUNCH_SCREEN_MIN_MS),
])
if (!configContent) {
return
}
this.appConfig = JSON.parse(configContent)
// 缓存 tabBar 配置(list、color 等),并渲染 tabBar 容器;后续仅做选中态/可见性切换
this._initTabBar()
const entryPagePath = this.appInfo.pagePath || this.appConfig.app.entryPagePath
// 4. 读取页面配置
const pageConfig = this.appConfig.modules[entryPagePath]
const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig)
// 5. 设置状态栏的颜色模式
this.updateTargetPageColorStyle(mergeConfig)
// 6. 创建通信 bridge
const entryPageBridge = await this.createBridge({
pagePath: entryPagePath,
query: this.appInfo.query,
scene: this.appInfo.scene,
jscore: this.jscore,
isRoot: true,
root,
appId: this.appInfo.appId,
pages: this.appConfig.app.pages,
configInfo: mergeConfig,
})
this.bridgeList.push(entryPageBridge)
// 入口若是 tab 页:登记到 tab 池并设为当前 tab、显示 TabBar
if (this._isTabBarPage(entryPagePath)) {
const normalizedPath = this._normalizePagePath(entryPagePath)
this.tabBarBridges.set(normalizedPath, entryPageBridge)
this.currentTabPath = normalizedPath
this._setTabBarVisible(true)
this._updateTabBarSelection(normalizedPath)
}
entryPageBridge.start()
// 7. 若携带额外的恢复栈(刷新后恢复场景),静默重建后续页面
if (this.appInfo.restoreStack && this.appInfo.restoreStack.length > 1) {
await this.restorePageStack(this.appInfo.restoreStack.slice(1))
}
this._syncHash()
// 8. 隐藏 loading
this.hideLaunchScreen()
}
/**
* 静默恢复页面栈中根页之后的页面。
* 这些页面的 bridge 会被初始化并推入 bridgeList,但不播放入场动画,
* 当前页显示在最顶层,之前的页面以 slide-out 状态保留在 DOM 中,
* 使后退按钮可以正常工作。
* @param {Array<{pagePath: string, query: object}>} pages
*/
async restorePageStack(pages) {
for (let i = 0; i < pages.length; i++) {
const { pagePath: rawPagePath, query } = pages[i]
const isTop = i === pages.length - 1
// 规范化路径:去掉前导 /,与 app-config.json modules key 保持一致
const pagePath = rawPagePath.startsWith('/') ? rawPagePath.slice(1) : rawPagePath
// pageConfig 可能为空(该小程序所有页面共用 app.window 默认配置),
// mergePageConfig 支持 pageConfig 为 undefined,直接降级到 app 全局配置
const pageConfig = this.appConfig.modules[pagePath]
const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig)
const bridge = await this.createBridge({
pagePath,
query,
scene: this.appInfo.scene,
jscore: this.jscore,
isRoot: false,
root: pageConfig?.root || 'main',
appId: this.appInfo.appId,
pages: this.appConfig.app.pages,
configInfo: mergeConfig,
})
// 将上一个页面移到 slide-out 状态(不可见但保留在栈中,支持后退)
const prevBridge = this.bridgeList[this.bridgeList.length - 1]
prevBridge.webview.el.classList.remove('dimina-native-view--instage')
prevBridge.webview.el.classList.add('dimina-native-view--slide-out')
this.bridgeList.push(bridge)
bridge.webview.el.style.zIndex = this.bridgeList.length + 1
// 移除 before-enter(translateX 100%),让页面回到正常位置
bridge.webview.el.classList.remove('dimina-native-view--before-enter')
if (!isTop) {
// 中间页面再叠加 slide-out,被上层页面覆盖
bridge.webview.el.classList.add('dimina-native-view--slide-out')
}
bridge.start()
}
if (pages.length > 0) {
// 最顶层页面更新状态栏颜色
const topBridge = this.bridgeList[this.bridgeList.length - 1]
const topPageConfig = this.appConfig.modules[topBridge.opts.pagePath]
const topMergeConfig = mergePageConfig(this.appConfig.app, topPageConfig)
this.updateTargetPageColorStyle(topMergeConfig)
// 恢复后栈顶为非 tab 页:隐藏 TabBar(tab bridge 仍保留在 pool 中以备后退恢复)
if (!this._isTabBarPage(topBridge.opts.pagePath)) {
this._setTabBarVisible(false)
}
}
}
/**
* 将当前 bridgeList 序列化到 URL hash,用于刷新后恢复完整页面栈。
* pagePath 统一去掉前导 /,与 app-config.json modules key 保持一致。
*/
_syncHash() {
const stack = this.bridgeList.map((b) => {
const pagePath = b.opts.pagePath.startsWith('/') ? b.opts.pagePath.slice(1) : b.opts.pagePath
return { pagePath, query: b.opts.query || {} }
})
HashRouter.syncStack(this.appId, stack)
}
// 创建一个bridge对象
async createBridge(opts) {
const { jscore, configInfo, isRoot, appId, pagePath, query, scene, pages, root } = opts
const bridge = new Bridge({
jscore,
configInfo,
isRoot,
appId,
pagePath,
query,
scene,
pages,
root,
})
bridge.parent = this
await bridge.init()
return bridge
}
onPresentIn() {
const currentBridge = this.bridgeList[this.bridgeList.length - 1]
// 首次异步创建时, bridge 不存在,会在[Service]自行调用 invokeInitLifecycle
currentBridge?.appShow()
currentBridge?.pageShow()
}
onPresentOut() {
const currentBridge = this.bridgeList[this.bridgeList.length - 1]
currentBridge?.appHide()
currentBridge?.pageHide()
}
initPageFrame() {
this.el.innerHTML = tpl
}
// 设置指定页面状态栏的颜色模式
updateTargetPageColorStyle(mergeConfig) {
const { navigationBarTextStyle } = mergeConfig
this.updateActionColorStyle(navigationBarTextStyle)
}
showLaunchScreen() {
const launchScreen = this.el.querySelector('.dimina-mini-app__launch-screen')
const name = this.el.querySelector('.dimina-mini-app__name')
const logo = this.el.querySelector('.dimina-mini-app__logo-img-url')
this.updateActionColorStyle('black')
name.innerHTML = this.appInfo.name
logo.src = this.appInfo.logo
launchScreen.style.display = 'block'
}
hideLaunchScreen() {
const startPage = this.el.querySelector('.dimina-mini-app__launch-screen')
startPage.style.display = 'none'
}
updateActionColorStyle(color) {
this.color = color
const action = this.el.querySelector('.dimina-mini-app-navigation__actions')
if (color === 'white') {
action.classList.remove('dimina-mini-app-navigation__actions--black')
action.classList.add('dimina-mini-app-navigation__actions--white')
}
else if (color === 'black') {
action.classList.remove('dimina-mini-app-navigation__actions--white')
action.classList.add('dimina-mini-app-navigation__actions--black')
}
this.parent.updateStatusBarColor(color)
}
restoreColorStyle() {
this.updateActionColorStyle(this.color)
}
createCallbackFunction(funcId) {
if (funcId) {
return (args) => {
this.jscore.postMessage({
type: 'triggerCallback',
body: {
id: funcId,
args,
},
})
}
}
}
async navigateTo(opts) {
const { url, success, fail, complete } = opts
const { query, pagePath } = queryPath(url)
const onSuccess = this.createCallbackFunction(success)
const onFail = this.createCallbackFunction(fail)
const onComplete = this.createCallbackFunction(complete)
// 微信规范:navigateTo 不允许跳转到 tabBar 页面
if (this._isTabBarPage(pagePath)) {
onFail?.({ errMsg: `navigateTo:fail can not navigateTo a tabbar page` })
onComplete?.()
return
}
// 防抖处理
if (!this.webviewAnimaEnd) {
return
}
this.webviewAnimaEnd = false
const pageConfig = this.appConfig.modules[pagePath]
const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig)
// 更新状态栏颜色模式
this.updateTargetPageColorStyle(mergeConfig)
// 创建新的入口页面的 bridge
const bridge = await this.createBridge({
pagePath,
query,
scene: this.appInfo.scene,
jscore: this.jscore,
isRoot: false,
root: pageConfig?.root || 'main',
appId: this.appInfo.appId,
pages: this.appConfig.app.pages,
configInfo: mergeConfig,
})
// 获取前一个bridge
const preBridge = this.bridgeList[this.bridgeList.length - 1]
const preWebview = preBridge.webview
this.bridgeList.push(bridge)
// 触发新页面的初始化逻辑
bridge.start()
this._syncHash()
// 上一个页面推出
preWebview.el.classList.remove('dimina-native-view--instage')
preWebview.el.classList.add('dimina-native-view--slide-out')
preWebview.el.classList.add('dimina-native-view--linear-anima')
preBridge?.pageHide()
// 新页面推入
bridge.webview.el.style.zIndex = this.bridgeList.length + 1
bridge.webview.el.classList.add('dimina-native-view--enter-anima')
bridge.webview.el.classList.add('dimina-native-view--instage')
await waitTransitionEnd(bridge.webview.el, 'transform')
// 页面进入后移出动画相关class
this.webviewAnimaEnd = true
preWebview.el.classList.remove('dimina-native-view--linear-anima')
bridge.webview.el.classList.remove('dimina-native-view--before-enter')
bridge.webview.el.classList.remove('dimina-native-view--enter-anima')
bridge.webview.el.classList.remove('dimina-native-view--instage')
// navigateTo 的目标按规范不应是 tab 页:栈顶变为非 tab 页,隐藏 TabBar
this._setTabBarVisible(false)
onSuccess?.({ errMsg: 'navigateTo:ok' })
onComplete?.()
}
reLaunch(opts) {
// 防抖处理
if (!this.webviewAnimaEnd) {
return
}
this.webviewAnimaEnd = false
const { url, success, fail, complete } = opts
const { query, pagePath } = queryPath(url)
const onSuccess = this.createCallbackFunction(success)
const onFail = this.createCallbackFunction(fail)
const onComplete = this.createCallbackFunction(complete)
try {
// 检查页面路径是否存在
const pageConfig = this.appConfig.modules[pagePath]
// 合并页面配置
const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig)
// 更新状态栏颜色模式
this.updateTargetPageColorStyle(mergeConfig)
// 销毁所有现有的 bridge:合并 stack 与 tab 池(用 Set 去重)
const allBridges = new Set([...this.bridgeList, ...this.tabBarBridges.values()])
for (const bridge of allBridges) {
bridge.destroy()
bridge.webview?.el?.remove()
}
this.bridgeList.length = 0
this.tabBarBridges.clear()
this.currentTabPath = null
// 清空 webviews 容器
if (this.webviewsContainer) {
this.webviewsContainer.innerHTML = ''
}
// 创建新的入口页面的 bridge
this.createBridge({
pagePath,
query,
scene: this.appInfo.scene,
jscore: this.jscore,
isRoot: true, // 作为根页面
root: pageConfig?.root || 'main',
appId: this.appInfo.appId,
pages: this.appConfig.app.pages,
configInfo: mergeConfig,
}).then((bridge) => {
// 添加到 bridgeList
this.bridgeList.push(bridge)
// 入口若是 tab 页:登记到 pool 并显示 TabBar
if (this._isTabBarPage(pagePath)) {
const normalizedPath = this._normalizePagePath(pagePath)
this.tabBarBridges.set(normalizedPath, bridge)
this.currentTabPath = normalizedPath
this._setTabBarVisible(true)
this._updateTabBarSelection(normalizedPath)
}
else {
this._setTabBarVisible(false)
}
// 启动新页面
bridge.start()
this._syncHash()
// 设置 z-index
bridge.webview.el.style.zIndex = 1
// 恢复动画状态
this.webviewAnimaEnd = true
// 调用成功回调
onSuccess?.({ errMsg: 'reLaunch:ok' })
onComplete?.()
}).catch((error) => {
onFail?.({ errMsg: `reLaunch:fail ${error.message}` })
onComplete?.()
this.webviewAnimaEnd = true
})
}
catch (error) {
onFail?.({ errMsg: `reLaunch:fail ${error.message}` })
onComplete?.()
this.webviewAnimaEnd = true
}
}
redirectTo(opts) {
const { url, success, fail, complete } = opts
const { query, pagePath } = queryPath(url)
const onSuccess = this.createCallbackFunction(success)
const onFail = this.createCallbackFunction(fail)
const onComplete = this.createCallbackFunction(complete)
// 微信规范:redirectTo 不允许跳转到 tabBar 页面
if (this._isTabBarPage(pagePath)) {
onFail?.({ errMsg: `redirectTo:fail can not redirectTo a tabbar page` })
onComplete?.()
return
}
// 防抖处理
if (!this.webviewAnimaEnd) {
return
}
this.webviewAnimaEnd = false
// 获取当前 bridge
const curBridge = this.bridgeList[this.bridgeList.length - 1]
const prevPath = this._normalizePagePath(curBridge.opts.pagePath)
const pageConfig = this.appConfig.modules[pagePath]
const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig)
this.updateTargetPageColorStyle(mergeConfig)
// 更新 bridge
curBridge.destroy()
curBridge.opts = {
...curBridge.opts,
pagePath,
query,
configInfo: mergeConfig,
}
curBridge.resetStatus()
curBridge.start()
this._syncHash()
// redirectTo 的目标按规范不能是 tab 页:若被替换的是当前 tab 页,需从 pool 中移除并隐藏 TabBar
if (this.tabBarBridges.get(prevPath) === curBridge) {
this.tabBarBridges.delete(prevPath)
if (this.currentTabPath === prevPath) {
this.currentTabPath = null
}
}
this._setTabBarVisible(false)
this.webviewAnimaEnd = true
onSuccess?.({ errMsg: 'redirectTo:ok' })
onComplete?.()
}
async navigateBack() {
if (this.bridgeList.length < 2) {
return
}
if (!this.webviewAnimaEnd) {
return
}
this.webviewAnimaEnd = false
const currentBridge = this.bridgeList.pop()
const preBridge = this.bridgeList[this.bridgeList.length - 1]
const pageConfig = this.appConfig.modules[preBridge.opts.pagePath]
const mergeConfig = mergePageConfig(this.appConfig.app, pageConfig)
// 更新状态栏颜色模式
this.updateTargetPageColorStyle(mergeConfig)
// 当前页面推出
currentBridge.webview.el.classList.add('dimina-native-view--before-enter')
currentBridge.webview.el.classList.add('dimina-native-view--enter-anima')
// 触发当前页面的生命周期函数
currentBridge?.destroy()
// 上一个页面推入
preBridge.webview.el.classList.remove('dimina-native-view--slide-out')
preBridge.webview.el.classList.add('dimina-native-view--instage')
preBridge.webview.el.classList.add('dimina-native-view--enter-anima')
// 触发上一个页面的生命周期函数
preBridge?.pageShow()
this._syncHash()
// 后退到 tab 页:恢复 TabBar 可见 + 选中态
if (this._isTabBarPage(preBridge.opts.pagePath)) {
const path = this._normalizePagePath(preBridge.opts.pagePath)
this.currentTabPath = path
this._setTabBarVisible(true)
this._updateTabBarSelection(path)
}
await waitTransitionEnd(preBridge.webview.el, 'transform')
this.webviewAnimaEnd = true
// 页面进入后移出动画相关class
preBridge.webview.el.classList.remove('dimina-native-view--enter-anima')
preBridge.webview.el.classList.remove('dimina-native-view--instage')
currentBridge.webview.el.parentNode.removeChild(currentBridge.webview.el)
}
/**
* 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面。
* 参考鸿蒙 DMPNavigator.switchTab + DMPTabBarContainerView 的“按需创建 + 持久缓存”模型:
* 1. 弹出并销毁所有非 tab 页面
* 2. 隐藏旧 tab 的 iframe(保留在 pool 中)
* 3. 目标 tab 已在 pool → 复用;否则懒加载新建并入池
* 4. 切换生命周期:旧 pageHide / 新 pageShow
* 5. 更新 TabBar 选中态、状态栏颜色、URL hash
*/
async switchTab(opts) {
const { url, success, fail, complete } = opts
const { query, pagePath } = queryPath(url)
const targetPath = this._normalizePagePath(pagePath)
const onSuccess = this.createCallbackFunction(success)
const onFail = this.createCallbackFunction(fail)
const onComplete = this.createCallbackFunction(complete)
if (!this._isTabBarPage(targetPath)) {
onFail?.({ errMsg: `switchTab:fail not a tabBar page: ${targetPath}` })
onComplete?.()
return
}
// 防抖处理:避免与 navigateTo / navigateBack 动画并发
if (!this.webviewAnimaEnd) {
onFail?.({ errMsg: 'switchTab:fail busy' })
onComplete?.()
return
}
// 命中当前 tab:仅更新选中态 + 显示
if (this.currentTabPath === targetPath && this.bridgeList.length === 1) {
this._setTabBarVisible(true)
this._updateTabBarSelection(targetPath)
onSuccess?.({ errMsg: 'switchTab:ok' })
onComplete?.()
return
}
this.webviewAnimaEnd = false
try {
const prevPath = this.currentTabPath;
const prevTabBridge = prevPath
? this.tabBarBridges.get(prevPath)
: null;
const wasPrevTabVisible =
!!prevTabBridge &&
this.bridgeList.length === 1 &&
this.bridgeList[0] === prevTabBridge;
// 1. 隐藏 / 卸载非 tab 页面(从栈顶往下,遇到 tab 页停止)
while (this.bridgeList.length > 0) {
const top = this.bridgeList[this.bridgeList.length - 1];
if (this._isTabBarPage(top.opts.pagePath)) {
break;
}
top.pageHide();
top.destroy();
top.webview?.el?.remove();
this.bridgeList.pop();
}
// 2. 隐藏旧 tab 的 iframe(保留在 pool 中),栈顶若是旧 tab 则弹出(不销毁)
if (
prevTabBridge &&
prevTabBridge !== this.tabBarBridges.get(targetPath)
) {
if (wasPrevTabVisible) {
prevTabBridge.pageHide();
}
if (prevTabBridge.webview?.el) {
prevTabBridge.webview.el.style.display = "none";
}
const idx = this.bridgeList.indexOf(prevTabBridge);
if (idx >= 0) {
this.bridgeList.splice(idx, 1);
}
}
// 3. 取出 / 懒加载目标 tab
let targetBridge = this.tabBarBridges.get(targetPath)
const targetPageConfig = this.appConfig.modules[targetPath]
const targetMergeConfig = mergePageConfig(this.appConfig.app, targetPageConfig)
this.updateTargetPageColorStyle(targetMergeConfig)
if (!targetBridge) {
targetBridge = await this.createBridge({
pagePath: targetPath,
query,
scene: this.appInfo.scene,
jscore: this.jscore,
isRoot: true,
root: targetPageConfig?.root || 'main',
appId: this.appInfo.appId,
pages: this.appConfig.app.pages,
configInfo: targetMergeConfig,
})
this.tabBarBridges.set(targetPath, targetBridge)
targetBridge.start()
}
// 4. 显示目标 tab:清理动画类、重置 z-index、display
const targetEl = targetBridge.webview.el
targetEl.classList.remove(
'dimina-native-view--before-enter',
'dimina-native-view--slide-out',
'dimina-native-view--enter-anima',
'dimina-native-view--linear-anima',
'dimina-native-view--instage',
)
targetEl.style.display = ''
targetEl.style.zIndex = 1
// 5. 入栈(若不在),更新当前 tab,触发 pageShow
if (!this.bridgeList.includes(targetBridge)) {
this.bridgeList.push(targetBridge)
}
this.currentTabPath = targetPath
targetBridge.pageShow()
// 6. UI / 状态同步
this._setTabBarVisible(true)
this._updateTabBarSelection(targetPath)
this._syncHash()
onSuccess?.({ errMsg: 'switchTab:ok' })
}
catch (error) {
onFail?.({ errMsg: `switchTab:fail ${error.message}` })
}
finally {
this.webviewAnimaEnd = true
onComplete?.()
}
}
/**
* 解析并缓存 tabBar 配置;首次渲染 TabBar DOM(默认隐藏)。
* 后续切换仅通过 _setTabBarVisible / _updateTabBarSelection 调整,不重渲染。
*/
_initTabBar() {
const tabBar = this.appConfig?.app?.tabBar
if (!tabBar || !Array.isArray(tabBar.list) || tabBar.list.length === 0) {
return
}
this.tabBarConfig = tabBar
this.tabBarPaths = tabBar.list.map(item => this._normalizePagePath(item.pagePath))
this._renderTabBar()
}
/**
* 一次性渲染 TabBar DOM,使用事件委托处理点击。
*/
_renderTabBar() {
this.tabBarEl = this.el.querySelector('.dimina-mini-app__tabbar')
if (!this.tabBarEl) return
const { color, backgroundColor, borderStyle, list } = this.tabBarConfig
const normalColor = this._sanitizeCssColor(color) || '#999999'
const bg = this._sanitizeCssColor(backgroundColor) || '#ffffff'
const borderColor = borderStyle === 'white' ? '#FFFFFF' : '#E0E0E0'
// 用 DOM API 构建,避免 innerHTML 拼接被配置中的引号 / HTML 片段污染宿主 DOM
this.tabBarEl.textContent = ''
const tabbar = document.createElement('div')
tabbar.className = 'dimina-tabbar'
tabbar.style.backgroundColor = bg
tabbar.style.borderTop = `0.5px solid ${borderColor}`
list.forEach((item, index) => {
const path = this._normalizePagePath(item.pagePath)
const itemEl = document.createElement('div')
itemEl.className = 'dimina-tabbar-item'
itemEl.dataset.path = path
itemEl.dataset.index = String(index)
const defaultIconUrl = this._resolveTabBarIcon(item.iconPath)
if (defaultIconUrl) {
itemEl.appendChild(this._createTabBarIcon(defaultIconUrl, 'dimina-tabbar-icon-default'))
}
const selectedIconUrl = this._resolveTabBarIcon(item.selectedIconPath)
if (selectedIconUrl) {
itemEl.appendChild(this._createTabBarIcon(selectedIconUrl, 'dimina-tabbar-icon-selected'))
}
const text = document.createElement('span')
text.className = 'dimina-tabbar-text'
text.style.color = normalColor
text.textContent = item.text || ''
itemEl.appendChild(text)
tabbar.appendChild(itemEl)
})
this.tabBarEl.appendChild(tabbar)
// 事件委托:单一监听器处理所有 tab 项点击
this.tabBarEl.addEventListener('click', (e) => {
const item = e.target.closest('.dimina-tabbar-item')
if (!item) return
const path = item.dataset.path
if (path && path !== this.currentTabPath) {
this.switchTab({ url: `/${path}` })
}
})
// 监听 TabBar 实际高度(含 safe-area-inset-bottom)变化,
// 通过 CSS 变量同步 webviews 容器底部留白,避免硬编码与样式漂移
if (typeof ResizeObserver !== 'undefined') {
this._tabBarResizeObserver?.disconnect()
this._tabBarResizeObserver = new ResizeObserver(() => this._syncTabBarHeightVar())
this._tabBarResizeObserver.observe(this.tabBarEl)
}
}
/**
* 创建一张 tabBar 图标 <img>,带加载失败兜底(隐藏,避免破图占位)。
*/
_createTabBarIcon(src, modifierClass) {
const img = document.createElement('img')
img.className = `dimina-tabbar-icon ${modifierClass}`
img.src = src
img.alt = ''
img.addEventListener('error', () => {
img.style.display = 'none'
})
return img
}
/**
* 简单 CSS 颜色白名单:#hex / rgb(a)/hsl(a)/常见关键字。
* 拒绝包含尖括号、引号、分号、url() 等可能逃逸 style 上下文的字符;
* 不命中白名单时返回空串,让调用方走默认色。
*/
_sanitizeCssColor(value) {
if (!value || typeof value !== 'string') return ''
const v = value.trim()
if (v.length === 0 || v.length > 64) return ''
// 任意 url()/expression()/HTML 注入尝试都会包含下面的字符
if (/[<>"';{}()\\]/.test(v)) {
// 兼容 rgb(a)/hsl(a) 函数:仅放行严格匹配的形态
if (/^(?:rgb|rgba|hsl|hsla)\(\s*[\d.,%\s/-]+\)$/i.test(v)) {
return v
}
return ''
}
return v
}
/**
* 把 TabBar 当前实际高度同步到 CSS 变量,让 webviews 容器底部留白与之对齐。
* - 隐藏时高度记为 0,等价于不留白
* - 显示时取 getBoundingClientRect().height,含 safe-area-inset-bottom
*/
_syncTabBarHeightVar() {
if (!this.tabBarEl) return
const visible = this.tabBarEl.style.display !== 'none'
const height = visible ? this.tabBarEl.getBoundingClientRect().height : 0
this.el.style.setProperty('--dimina-tabbar-height', `${height}px`)
}