TopNavigationComponent.ets
21.1 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
import { BottomNavDTO, CompDTO, TopNavDTO } from 'wdBean';
import { LazyDataSource, Logger,SPHelper } from 'wdKit';
import { SpConstants } from 'wdConstant';
import { ProcessUtils } from 'wdRouter';
import { PageComponent } from './PageComponent';
import { ChannelSubscriptionLayout } from './ChannelSubscriptionLayout';
import { FirstTabTopSearchComponent } from '../search/FirstTabTopSearchComponent';
import { VideoChannelDetail } from 'wdDetailPlayShortVideo/Index';
import { AssignChannelParam } from 'wdRouter/src/main/ets/utils/HomeChannelUtils';
import { PeopleShipMainComponent } from '../peopleShip/PeopleShipMainComponent';
import { WDRouterPage, WDRouterRule } from 'wdRouter'
const TAG = 'TopNavigationComponent';
PersistentStorage.persistProp('channelIds', '');
PersistentStorage.persistProp('indexSettingChannelId', 2002);
const storage = LocalStorage.getShared();
/**
* 顶部页签导航栏/顶导
*/
@Entry(storage)
@Component
export struct TopNavigationComponent {
private groupId: number = 0
private currentBottomNavName: string = ''
private tabsController: TabsController = new TabsController()
@Consume isLayoutFullScreen: boolean
@Consume bottomRectHeight: number
@Consume topRectHeight: number
@Consume @Watch('topOrBottomNavChange') currentBottomNavInfo: BottomNavDTO // 当前底导信息
@Consume barBackgroundColor: Color
@State bottomSafeHeight: number = AppStorage.get<number>('bottomSafeHeight') || 0
@State topSafeHeight: number = AppStorage.get<number>('topSafeHeight') || 0
@Link _currentNavIndex?: number;
// 顶导当前选中/焦点下标
@State @Watch('topOrBottomNavChange') currentTopNavSelectedIndex: number = 0;
@State currentTopNavName: string = '';
// 顶导数据
@State @Watch('onTopNavigationDataUpdated') topNavList: TopNavDTO[] = []
@State compList: LazyDataSource<CompDTO> = new LazyDataSource();
@StorageProp('indexSettingChannelId') indexSettingChannelId: number = 2002
//我的频道id列表
@State channelIds: number[] = []
//本地缓存频道id列表
@StorageProp('channelIds') storageChannelIds: string = ''
@State homeChannelList: TopNavDTO[] = []
// 我的频道列表
@State myChannelList: TopNavDTO[] = []
// 更多频道列表
@State moreChannelList: TopNavDTO[] = []
// 地方频道列表
@State localChannelList: TopNavDTO[] = []
readonly MAX_LINE: number = 1;
@ObjectLink @Watch('onAssignChannelChange') assignChannel: AssignChannelParam
// 底导传递过来的自动刷新通知
@Prop @Watch('onAutoRefresh') autoRefresh: number = 0
// 传递给page的自动刷新通知
@State autoRefresh2Page: number = 0
// 当前底导index
@State navIndex: number = 0
@State animationDuration: number = 0
@State indicatorLeftMargin: number = 0
@State indicatorWidth: number = 0
private tabsWidth: number = 0
//定时器延时处理切换至版面、播报tab时 返回上一个tab
@State tabTimmer: number = 0
topOrBottomNavChange() {
if (this.currentBottomNavName === this.currentBottomNavInfo?.name) {
this.setBarBackgroundColor()
}
}
setBarBackgroundColor() {
console.error('setBarBackgroundColor', this.currentTopNavName, this.currentBottomNavInfo?.name)
if (this.currentTopNavName === '视频' && this.currentBottomNavInfo?.name === '视频') {
this.barBackgroundColor = Color.Black
} else {
this.barBackgroundColor = Color.White
}
}
//处理新闻tab顶导频道数据
topNavListHandle() {
let cityName = SPHelper.default.getSync(SpConstants.LOCATION_CITY_NAME, '') as string
let _channelIds: number [] = []
let _myChannelList: TopNavDTO [] = []
let _storageChannelIds: string [] = [] //list1
let defaultMyChannelList: TopNavDTO[] = []
let defaultList = [...this.topNavList]
defaultList.sort((a, b) => {
return a.num - b.num;
});
//defaultMyChannelList
defaultList.forEach(item => {
if (item.defaultPermitted === 1 || item.movePermitted === 0 || item.delPermitted === 0 ||
item.headlinesOn === 1) {
defaultMyChannelList.push(item);
}
if (item.defaultPermitted === 1) {
this.homeChannelList.push(item)
}
})
//有缓存频道id
if (this.storageChannelIds) {
_storageChannelIds = this.storageChannelIds.split(',')
}
defaultMyChannelList.forEach(item => {
item.myChannel = '1'
if (item.defaultPermitted === 1) {
item.homeChannel = '1'
}
let index = defaultList.findIndex(_item => _item.channelId === item.channelId)
if (index !== -1) {
defaultList.splice(index, 1)
}
})
defaultList.unshift(...defaultMyChannelList)
defaultList.forEach((item, index) => {
if (this.storageChannelIds && _storageChannelIds.includes(String(item.channelId))) {
item.myChannel = '1'
}
if (item.channelType === 2) {
if(cityName.includes(item.name)){
item.myChannel = '1'
}
item.localChannel = '1'
}
if (index >= 11) {
if (item.channelType === 1) {
item.moreChannel = '1'
}
} else {
if (item.channelType === 1 && item.myChannel !== '1') {
item.moreChannel = '1'
}
}
//频道分类
if (item.name !== '播报') { //暂时隐藏播报
if (item.myChannel === '1') {
_myChannelList.push(item)
_channelIds.push(item.channelId)
} else if (item.moreChannel === '1') {
this.moreChannelList.push(item)
} else if (item.localChannel === '1' && item.myChannel !== '1') {
this.localChannelList.push(item)
}
}
})
if(cityName){
let index = _myChannelList.findIndex(ele=> cityName.includes(ele.name))
const localChannelitem = _myChannelList.splice(index, 1)[0];
// 将当前地区频道插入到第四个
_myChannelList.splice(3, 0, localChannelitem);
}
this.channelIds = _channelIds
this.myChannelList = _myChannelList
// 崩溃
// this.currentTopNavName = this._currentNavIndex === 0 ? this.myChannelList[0].name : this.topNavList[0].name
if (this._currentNavIndex === 0 && this.myChannelList && this.myChannelList.length > 0 && this.myChannelList[0].name) {
this.currentTopNavName = this.myChannelList[0].name
}else if(this._currentNavIndex != 0 && this.topNavList && this.topNavList.length > 0 && this.topNavList[0].name){
this.currentTopNavName = this.topNavList[0].name
}
//缓存首页频道
let index = this.myChannelList.findIndex(_item => _item?.channelId === this.indexSettingChannelId)
if (index > -1) {
this.currentTopNavSelectedIndex = index
this.currentTopNavName = this.myChannelList[index].name
}
}
isBroadcast(item: TopNavDTO) {
return item.name === '播报'
}
isLayout(item: TopNavDTO) {
return item.name === '版面'
}
build() {
Column() {
// 顶部搜索、日报logo、早晚报
Column() {
Row() {
FirstTabTopSearchComponent()
Image($r('app.media.icon_ren_min_ri_bao'))
.width(72)
.height(29)
.onClick(() => {
ProcessUtils.gotoENewsPaper()
})
Stack({ alignContent: Alignment.Center }) {
Image($r('app.media.background_read_paper_home'))
.width('100%')
.height('100%')
.objectFit(ImageFit.Contain)
Row() {
Image($r('app.media.icon_read_paper_home'))
.width(18)
.height(18)
Text('早晚报')
.fontColor("#666666")
.fontSize($r('app.float.font_size_13'))
}
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
}
.height(30)
.width(124)
.onClick(() => {
ProcessUtils.gotoMorningEveningPaper()
})
}.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
}
.width('100%')
.height(40)
.padding({ top: 10 })
.backgroundColor($r('app.color.white'))
.visibility(this._currentNavIndex == 0 ? Visibility.Visible : Visibility.None)
// 频道分类list
Stack({ alignContent: Alignment.TopEnd }) {
Tabs({ index: this.currentTopNavSelectedIndex, controller: this.tabsController }) {
ForEach(this.currentBottomNavName === '新闻' ? this.myChannelList : this.topNavList,
(navItem: TopNavDTO, index: number) => {
TabContent() {
if (this.currentBottomNavName === '视频' && navItem.name === '视频') {
VideoChannelDetail({
bottomNavIndex: $_currentNavIndex,
topNavIndex: $currentTopNavSelectedIndex,
groupId: this.groupId + '',
pageId: navItem.pageId + '',
channelId: navItem.channelId + '',
})
} else if (this.currentBottomNavName === '人民号' && navItem.name === '关注') {
PeopleShipMainComponent({
currentTopNavSelectedIndex: $currentTopNavSelectedIndex,
navIndex: index,
pageId: navItem.pageId + '',
channelId: navItem.channelId + '',
})
} else
if (!this.isBroadcast(navItem) && !this.isLayout(navItem)) {
PageComponent({
currentTopNavSelectedIndex: $currentTopNavSelectedIndex,
navIndex: index,
pageId: navItem.pageId + '',
channelId: navItem.channelId + '',
autoRefresh: this.autoRefresh2Page
})
}
}
.tabBar(this.tabBarBuilder(navItem, index))
}, (navItem: TopNavDTO) => JSON.stringify(navItem));
}
.barHeight($r('app.float.top_tab_bar_height'))
.barMode(BarMode.Scrollable)
.vertical(false)
.barBackgroundColor(this.barBackgroundColor)
.onAreaChange((oldValue: Area, newValue: Area) => {
let width = Number.parseFloat(newValue.width.toString())
this.tabsWidth = Number.isNaN(width) ? 0 : width
})
.animationDuration(this.animationDuration)
.onChange((index: number) => {
if(this.tabTimmer){
clearTimeout(this.tabTimmer)
}
this.currentTopNavName =
this._currentNavIndex === 0 ? this.myChannelList[index].name : this.topNavList[index].name
Logger.info(TAG, `onChange index : ${index}`);
if (!this.isBroadcast(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index]) &&
!this.isLayout(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index])
) {
this.currentTopNavSelectedIndex = index;
}
if (this.isBroadcast(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index])) {
// 跳转到播报页面
ProcessUtils.gotoBroadcastPage(this.myChannelList[index].pageId)
this.tabTimmer = setTimeout(() => {
this.tabsController.changeIndex(this.currentTopNavSelectedIndex)
}, 500)
}
if (this.isLayout(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index])) {
ProcessUtils.gotoENewsPaper()
this.tabTimmer = setTimeout(() => {
this.tabsController.changeIndex(this.currentTopNavSelectedIndex)
}, 500)
}
})
.onAnimationStart((index: number, targetIndex: number, event: TabsAnimationEvent) => {
if (!this.isBroadcast(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index]) &&
!this.isLayout(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index])
) {
return
}
this.currentTopNavSelectedIndex = targetIndex
// 切换动画开始时触发该回调。下划线跟着页面一起滑动,同时宽度渐变。
let targetIndexInfo = this.getTextInfo(targetIndex)
this.startAnimateTo(this.animationDuration, targetIndexInfo.left, targetIndexInfo.width)
})
.onAnimationEnd((index: number, event: TabsAnimationEvent) => {
if (!this.isBroadcast(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index]) &&
!this.isLayout(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index])
) {
return
}
// 切换动画结束时触发该回调。下划线动画停止。
let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
this.startAnimateTo(0, currentIndicatorInfo.left, currentIndicatorInfo.width)
})
.onGestureSwipe((index: number, event: TabsAnimationEvent) => {
if (!this.isBroadcast(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index]) &&
!this.isLayout(this._currentNavIndex === 0 ? this.myChannelList[index] : this.topNavList[index])
) {
return
}
// 在页面跟手滑动过程中,逐帧触发该回调。
let currentIndicatorInfo = this.getCurrentIndicatorInfo(index, event)
this.currentTopNavSelectedIndex = currentIndicatorInfo.index
this.indicatorLeftMargin = currentIndicatorInfo.left
this.indicatorWidth = currentIndicatorInfo.width
})
// 分类列表最右侧频道设置
if (this._currentNavIndex === 0) {
ChannelSubscriptionLayout({
currentTopNavSelectedIndex: $currentTopNavSelectedIndex,
indexSettingChannelId: this.indexSettingChannelId,
homeChannelList: this.homeChannelList,
myChannelList: $myChannelList,
moreChannelList: $moreChannelList,
localChannelList: $localChannelList,
channelIds: $channelIds,
changeTab: (index) => {
this.tabsController.changeIndex(index)
}
})
}else {
Row() {
Image($r('app.media.icon_search'))
.width('24vp')
.height('24vp')
}
.height('40vp')
.width('40vp')
.margin({ right: 10 })
.alignItems(VerticalAlign.Center)
.justifyContent(FlexAlign.Center)
.onClick(() => {
WDRouterRule.jumpWithPage(WDRouterPage.searchPage)
})
}
}
}
}
/**
* TODO:根据顶导配置获取颜色展示效果不对,待确认
*/
getTopNavFontColor(item: TopNavDTO, index: number): Color | string {
if (item.name === '视频' && this.currentBottomNavInfo.name === '视频') {
return this.currentTopNavSelectedIndex === index ? Color.White : '#e5e0e0'
} else {
return this.currentTopNavSelectedIndex === index ? Color.Black : "#999999"
}
}
@Builder
tabBarBuilder(item: TopNavDTO, index: number) {
Column() {
Text(item.name)
.fontSize($r('app.float.selected_text_size'))
.fontWeight(this.currentTopNavSelectedIndex === index ? FontWeight.Bold : FontWeight.Normal)
.fontColor(this.getTopNavFontColor(item, index))
.padding({ top: $r('app.float.top_tab_item_padding_top'), bottom: $r('app.float.top_tab_item_padding_bottom') })
.maxLines(this.MAX_LINE)
.id(index.toString())
.onAreaChange((oldValue: Area, newValue: Area) => {
if (this.currentTopNavSelectedIndex === index &&
(this.indicatorLeftMargin === 0 || this.indicatorWidth === 0)) {
if (newValue.position.x != undefined) {
let positionX = Number.parseFloat(newValue.position.x.toString())
this.indicatorLeftMargin = Number.isNaN(positionX) ? 0 : positionX
}
let width = Number.parseFloat(newValue.width.toString())
this.indicatorWidth = Number.isNaN(width) ? 0 : width
}
})
// .backgroundImage(this.currentTopNavSelectedIndex === index ? item.iconCUrl : item.iconUrl)
if (this.currentTopNavSelectedIndex === index) {
Row()
.width(20)
.height(3)
.backgroundImage($r('app.media.icon_channel_active'), ImageRepeat.NoRepeat)
.backgroundImageSize(ImageSize.Contain)
}
}
.hoverEffect(HoverEffect.Highlight)
.constraintSize({
minWidth: $r('app.float.top_tab_item_min_width'),
maxWidth: $r('app.float.top_tab_item_max_width')
})
// .backgroundColor(Color.Transparent)
.padding({
left: $r('app.float.top_tab_item_padding_horizontal'),
right: $r('app.float.top_tab_item_padding_horizontal'),
})
.id(`col_tabBar${index}`)
.margin({ right: this.myChannelList.length === index + 1 ? 36 : 0 })
}
aboutToAppear() {
//处理新闻tab顶导频道数据
this.topNavListHandle()
this.setBarBackgroundColor()
}
aboutToDisappear() {
AppStorage.set('channelIds', this.channelIds.join(','))
}
onTopNavigationDataUpdated() {
Logger.info(TAG,
`onTopNavigationDataUpdated currentTopNavIndex: ${this.currentTopNavSelectedIndex},topNavList.length:${this.topNavList.length}`);
}
onAutoRefresh() {
if (this.navIndex != this._currentNavIndex) {
return
}
// 通知page刷新
this.autoRefresh2Page++
}
/**
* 频道id变化,即指定频道跳转场景
*/
onAssignChannelChange() {
let channelId = this.assignChannel.channelId
let index = -1
if (this._currentNavIndex === 0) {
// 第一个,新闻,先拿我的,再拿其他
index = this.getChannelByMine(channelId)
if (index == -1) {
// 不在我的里,需要临时新增频道展示
let channel = this.getChannelByOthers(channelId)
if (channel) {
this.myChannelList.push(channel)
setTimeout(() => {
this.tabsController.changeIndex(this.myChannelList.length - 1)
}, 20)
}
} else {
// 直接切换
this.tabsController.changeIndex(index)
}
} else {
index = this.getChannelByTopNav(channelId)
if (index > -1) {
// 找到了,直接切换,否则不处理
this.tabsController.changeIndex(index)
}
}
}
/**
* 非新闻,从topNav里拿数据
*/
private getChannelByTopNav(channelId: string) {
for (let i = 0; i < this.topNavList.length; i++) {
let topNavDTO: TopNavDTO = this.topNavList[i]
if (topNavDTO.channelId.toString() === channelId) {
return i
}
}
return -1
}
/**
* 新闻,从myChannelList里拿数据
*/
private getChannelByMine(channelId: string) {
for (let i = 0; i < this.myChannelList.length; i++) {
let topNavDTO: TopNavDTO = this.myChannelList[i]
if (topNavDTO.channelId.toString() === channelId) {
return i
}
}
return -1
}
/**
* 新闻,从其他里拿数据
*/
private getChannelByOthers(channelId: string) {
for (let i = 0; i < this.moreChannelList.length; i++) {
let topNavDTO: TopNavDTO = this.moreChannelList[i]
if (topNavDTO.channelId.toString() === channelId) {
return topNavDTO
}
}
for (let j = 0; j < this.localChannelList.length; j++) {
let topNavDTO: TopNavDTO = this.localChannelList[j]
if (topNavDTO.channelId.toString() === channelId) {
return topNavDTO
}
}
return null
}
private getTextInfo(index: number): Record<string, number> {
let strJson = getInspectorByKey(index.toString())
try {
let obj: Record<string, string> = JSON.parse(strJson)
let rectInfo: number[][] = JSON.parse('[' + obj.$rect + ']')
return { 'left': px2vp(rectInfo[0][0]), 'width': px2vp(rectInfo[1][0] - rectInfo[0][0]) }
} catch (error) {
return { 'left': 0, 'width': 0 }
}
}
private getCurrentIndicatorInfo(index: number, event: TabsAnimationEvent): Record<string, number> {
let nextIndex = index
if (index > 0 && event.currentOffset > 0) {
nextIndex--
} else if (index < 3 && event.currentOffset < 0) {
nextIndex++
}
let indexInfo = this.getTextInfo(index)
let nextIndexInfo = this.getTextInfo(nextIndex)
let swipeRatio = Math.abs(event.currentOffset / this.tabsWidth)
let currentIndex = swipeRatio > 0.5 ? nextIndex : index // 页面滑动超过一半,tabBar切换到下一页。
let currentLeft = indexInfo.left + (nextIndexInfo.left - indexInfo.left) * swipeRatio
let currentWidth = indexInfo.width + (nextIndexInfo.width - indexInfo.width) * swipeRatio
return { 'index': currentIndex, 'left': currentLeft, 'width': currentWidth }
}
private startAnimateTo(duration: number, leftMargin: number, width: number) {
animateTo({
duration: duration, // 动画时长
curve: Curve.Linear, // 动画曲线
iterations: 1, // 播放次数
playMode: PlayMode.Normal, // 动画模式
onFinish: () => {
console.info('play end')
}
}, () => {
this.indicatorLeftMargin = leftMargin
this.indicatorWidth = width
})
}
}