1 /*
2 * Copyright (c) 2022-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "core/components_ng/pattern/tabs/tab_bar_pattern.h"
17
18 #include <optional>
19
20 #include "base/geometry/axis.h"
21 #include "base/geometry/dimension.h"
22 #include "base/geometry/ng/offset_t.h"
23 #include "base/geometry/ng/size_t.h"
24 #include "base/log/dump_log.h"
25 #include "base/memory/ace_type.h"
26 #include "base/utils/utils.h"
27 #include "core/common/agingadapation/aging_adapation_dialog_util.h"
28 #include "core/components/common/layout/constants.h"
29 #include "core/components_ng/pattern/scrollable/scrollable.h"
30 #include "core/components/tab_bar/tab_theme.h"
31 #include "core/components_ng/base/frame_node.h"
32 #include "core/components_ng/base/inspector_filter.h"
33 #include "core/components_ng/pattern/image/image_layout_property.h"
34 #include "core/components_ng/pattern/image/image_pattern.h"
35 #include "core/components_ng/pattern/pattern.h"
36 #include "core/components_ng/pattern/scroll/scroll_spring_effect.h"
37 #include "core/components_ng/pattern/swiper/swiper_event_hub.h"
38 #include "core/components_ng/pattern/swiper/swiper_model.h"
39 #include "core/components_ng/pattern/tabs/tabs_controller.h"
40 #include "core/components_ng/pattern/tabs/tabs_layout_property.h"
41 #include "core/components_ng/pattern/tabs/tabs_node.h"
42 #include "core/components_ng/pattern/tabs/tabs_pattern.h"
43 #include "core/components_ng/pattern/tabs/tab_content_model_ng.h"
44 #include "core/components_ng/pattern/text/text_layout_property.h"
45 #include "core/components_ng/pattern/symbol/constants.h"
46 #include "core/components_ng/pattern/symbol/symbol_effect_options.h"
47 #include "core/components_ng/property/property.h"
48 #include "core/components_v2/inspector/inspector_constants.h"
49 #include "core/pipeline_ng/pipeline_context.h"
50 #include "base/perfmonitor/perf_constants.h"
51 #include "base/perfmonitor/perf_monitor.h"
52 #include "core/components_ng/pattern/linear_layout/linear_layout_pattern.h"
53 #include "core/components_ng/pattern/text/text_pattern.h"
54 #include "core/components/toast/toast_theme.h"
55 #include "core/components/text_field/textfield_theme.h"
56 #include "core/components_ng/pattern/app_bar/app_bar_theme.h"
57 namespace OHOS::Ace::NG {
58 namespace {
59 constexpr int8_t LEFT_GRADIENT = 0;
60 constexpr int8_t RIGHT_GRADIENT = 1;
61 constexpr int8_t TOP_GRADIENT = 2;
62 constexpr int8_t BOTTOM_GRADIENT = 3;
63 constexpr float HALF_PROGRESS = 0.5f;
64 constexpr float FULL_PROGRESS = 1.0f;
65 constexpr float HALF_MASK_RADIUS_RATIO = 0.717f;
66 constexpr float FULL_MASK_RADIUS_RATIO = 1.414f;
67 constexpr float INVALID_RATIO = -1.0f;
68 constexpr uint16_t MASK_ANIMATION_DURATION = 200;
69 constexpr int8_t MASK_COUNT = 2;
70 constexpr float FULL_OPACITY = 1.0f;
71 constexpr float NEAR_FULL_OPACITY = 0.99f;
72 constexpr float NO_OPACITY = 0.0f;
73 constexpr float TEXT_COLOR_THREDHOLD = 0.673f;
74 constexpr int8_t HALF_OF_WIDTH = 2;
75 constexpr float MAX_FLING_VELOCITY = 4200.0f;
76
77 const auto DurationCubicCurve = AceType::MakeRefPtr<CubicCurve>(0.2f, 0.0f, 0.1f, 1.0f);
78 const auto SHOW_TAB_BAR_CURVE = AceType::MakeRefPtr<CubicCurve>(0.4f, 0.0f, 0.2f, 1.0f);
79 const auto SHOW_TAB_BAR_DURATION = 500.0f;
80 const std::string TAB_BAR_PROPERTY_NAME = "tabBar";
81 const std::string INDICATOR_OFFSET_PROPERTY_NAME = "indicatorOffset";
82 const std::string INDICATOR_WIDTH_PROPERTY_NAME = "translateWidth";
83 const auto SHOW_TAB_BAR_FRAME_RATE = 120;
84 const auto SHOW_TAB_BAR_FRAME_RATE_RANGE =
85 AceType::MakeRefPtr<FrameRateRange>(0, SHOW_TAB_BAR_FRAME_RATE, SHOW_TAB_BAR_FRAME_RATE);
86 } // namespace
87
TabBarPattern(const RefPtr<SwiperController> & swiperController)88 TabBarPattern::TabBarPattern(const RefPtr<SwiperController>& swiperController) : swiperController_(swiperController)
89 {
90 auto tabsController = AceType::DynamicCast<TabsControllerNG>(swiperController_);
91 CHECK_NULL_VOID(tabsController);
92 auto weak = WeakClaim(this);
93 tabsController->SetStartShowTabBarImpl([weak](int32_t delay) {
94 auto pattern = weak.Upgrade();
95 CHECK_NULL_VOID(pattern);
96 pattern->StartShowTabBar(delay);
97 });
98 tabsController->SetStopShowTabBarImpl([weak]() {
99 auto pattern = weak.Upgrade();
100 CHECK_NULL_VOID(pattern);
101 pattern->StopShowTabBar();
102 });
103 tabsController->SetUpdateTabBarHiddenRatioImpl([weak](float ratio) {
104 auto pattern = weak.Upgrade();
105 CHECK_NULL_VOID(pattern);
106 pattern->UpdateTabBarHiddenRatio(ratio);
107 });
108 tabsController->SetTabBarTranslateImpl([weak](const TranslateOptions& options) {
109 auto pattern = weak.Upgrade();
110 CHECK_NULL_VOID(pattern);
111 pattern->SetTabBarTranslate(options);
112 });
113 tabsController->SetTabBarOpacityImpl([weak](float opacity) {
114 auto pattern = weak.Upgrade();
115 CHECK_NULL_VOID(pattern);
116 pattern->SetTabBarOpacity(opacity);
117 });
118 }
119
StartShowTabBar(int32_t delay)120 void TabBarPattern::StartShowTabBar(int32_t delay)
121 {
122 auto host = GetHost();
123 CHECK_NULL_VOID(host);
124 auto renderContext = host->GetRenderContext();
125 CHECK_NULL_VOID(renderContext);
126 auto options = renderContext->GetTransformTranslateValue(TranslateOptions(0.0f, 0.0f, 0.0f));
127 auto translate = options.y.ConvertToPx();
128 auto size = renderContext->GetPaintRectWithoutTransform().Height();
129 if (axis_ == Axis::VERTICAL || NearZero(translate) || NearZero(size)) {
130 return;
131 }
132 if (delay == 0 && GreatOrEqual(std::abs(translate), size)) {
133 StopShowTabBar();
134 }
135 if (isTabBarShowing_) {
136 return;
137 }
138
139 InitTabBarProperty();
140 AnimationOption option;
141 delay = LessNotEqual(std::abs(translate), size) ? 0 : delay;
142 option.SetDelay(delay);
143 auto duration = SHOW_TAB_BAR_DURATION * (std::abs(translate) / size);
144 option.SetDuration(duration);
145 option.SetCurve(SHOW_TAB_BAR_CURVE);
146 option.SetFrameRateRange(SHOW_TAB_BAR_FRAME_RATE_RANGE);
147
148 showTabBarProperty_->Set(translate);
149 auto propertyCallback = [weak = WeakClaim(this)]() {
150 auto pattern = weak.Upgrade();
151 CHECK_NULL_VOID(pattern);
152 pattern->showTabBarProperty_->Set(0.0f);
153 };
154 auto finishCallback = [weak = WeakClaim(this)]() {
155 auto pattern = weak.Upgrade();
156 CHECK_NULL_VOID(pattern);
157 pattern->isTabBarShowing_ = false;
158 };
159 AnimationUtils::Animate(option, propertyCallback, finishCallback);
160 isTabBarShowing_ = true;
161 }
162
InitTabBarProperty()163 void TabBarPattern::InitTabBarProperty()
164 {
165 if (showTabBarProperty_) {
166 return;
167 }
168 auto host = GetHost();
169 CHECK_NULL_VOID(host);
170 auto renderContext = host->GetRenderContext();
171 CHECK_NULL_VOID(renderContext);
172
173 auto propertyCallback = [weak = WeakClaim(this)](float value) {
174 auto pattern = weak.Upgrade();
175 CHECK_NULL_VOID(pattern);
176 auto host = pattern->GetHost();
177 CHECK_NULL_VOID(host);
178 auto renderContext = host->GetRenderContext();
179 CHECK_NULL_VOID(renderContext);
180
181 pattern->SetTabBarTranslate(TranslateOptions(0.0f, value, 0.0f));
182 auto size = renderContext->GetPaintRectWithoutTransform().Height();
183 if (NearZero(size)) {
184 return;
185 }
186 pattern->SetTabBarOpacity(1.0f - std::abs(value) / size);
187 };
188 showTabBarProperty_ = AceType::MakeRefPtr<NodeAnimatablePropertyFloat>(0.0, std::move(propertyCallback));
189 renderContext->AttachNodeAnimatableProperty(showTabBarProperty_);
190 }
191
StopShowTabBar()192 void TabBarPattern::StopShowTabBar()
193 {
194 if (axis_ == Axis::VERTICAL || !isTabBarShowing_) {
195 return;
196 }
197 auto host = GetHost();
198 CHECK_NULL_VOID(host);
199 auto renderContext = host->GetRenderContext();
200 CHECK_NULL_VOID(renderContext);
201
202 AnimationOption option;
203 option.SetDuration(0);
204 option.SetCurve(Curves::LINEAR);
205 auto options = renderContext->GetTransformTranslateValue(TranslateOptions(0.0f, 0.0f, 0.0f));
206 auto translate = options.y.ConvertToPx();
207 auto propertyCallback = [weak = WeakClaim(this), translate]() {
208 auto pattern = weak.Upgrade();
209 CHECK_NULL_VOID(pattern);
210 pattern->showTabBarProperty_->Set(translate);
211 };
212 AnimationUtils::Animate(option, propertyCallback);
213 isTabBarShowing_ = false;
214 }
215
UpdateTabBarHiddenRatio(float ratio)216 void TabBarPattern::UpdateTabBarHiddenRatio(float ratio)
217 {
218 if (axis_ == Axis::VERTICAL || isTabBarShowing_) {
219 return;
220 }
221 auto host = GetHost();
222 CHECK_NULL_VOID(host);
223 auto renderContext = host->GetRenderContext();
224 CHECK_NULL_VOID(renderContext);
225 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
226 CHECK_NULL_VOID(tabsNode);
227 auto tabsLayoutProperty = AceType::DynamicCast<TabsLayoutProperty>(tabsNode->GetLayoutProperty());
228 CHECK_NULL_VOID(tabsLayoutProperty);
229
230 auto options = renderContext->GetTransformTranslateValue(TranslateOptions(0.0f, 0.0f, 0.0f));
231 float translate = options.y.ConvertToPx();
232 auto size = renderContext->GetPaintRectWithoutTransform().Height();
233 auto barPosition = tabsLayoutProperty->GetTabBarPosition().value_or(BarPosition::START);
234 if (barPosition == BarPosition::START) {
235 translate = std::clamp(translate - size * ratio, -size, 0.0f);
236 } else {
237 translate = std::clamp(translate + size * ratio, 0.0f, size);
238 }
239 renderContext->UpdateTransformTranslate(TranslateOptions(0.0f, translate, 0.0f));
240 float opacity = renderContext->GetOpacityValue(1.0f);
241 opacity = std::clamp(opacity - ratio, 0.0f, 1.0f);
242 renderContext->UpdateOpacity(opacity);
243 }
244
SetTabBarTranslate(const TranslateOptions & options)245 void TabBarPattern::SetTabBarTranslate(const TranslateOptions& options)
246 {
247 auto host = GetHost();
248 CHECK_NULL_VOID(host);
249 auto renderContext = host->GetRenderContext();
250 CHECK_NULL_VOID(renderContext);
251 renderContext->UpdateTransformTranslate(options);
252 }
253
SetTabBarOpacity(float opacity)254 void TabBarPattern::SetTabBarOpacity(float opacity)
255 {
256 auto host = GetHost();
257 CHECK_NULL_VOID(host);
258 auto renderContext = host->GetRenderContext();
259 CHECK_NULL_VOID(renderContext);
260 renderContext->UpdateOpacity(opacity);
261 }
262
FindTextAndImageNode(const RefPtr<FrameNode> & columnNode,RefPtr<FrameNode> & textNode,RefPtr<FrameNode> & imageNode)263 void FindTextAndImageNode(
264 const RefPtr<FrameNode>& columnNode, RefPtr<FrameNode>& textNode, RefPtr<FrameNode>& imageNode)
265 {
266 if (columnNode->GetTag() == V2::TEXT_ETS_TAG) {
267 textNode = columnNode;
268 } else if (columnNode->GetTag() == V2::IMAGE_ETS_TAG || columnNode->GetTag() == V2::SYMBOL_ETS_TAG) {
269 imageNode = columnNode;
270 } else {
271 std::list<RefPtr<UINode>> children = columnNode->GetChildren();
272 for (auto child : children) {
273 FindTextAndImageNode(AceType::DynamicCast<FrameNode>(child), textNode, imageNode);
274 }
275 }
276 }
277
OnAttachToFrameNode()278 void TabBarPattern::OnAttachToFrameNode()
279 {
280 auto host = GetHost();
281 CHECK_NULL_VOID(host);
282 auto renderContext = host->GetRenderContext();
283 CHECK_NULL_VOID(renderContext);
284 renderContext->SetClipToFrame(true);
285 host->GetLayoutProperty()->UpdateSafeAreaExpandOpts(
286 { .type = SAFE_AREA_TYPE_SYSTEM, .edges = SAFE_AREA_EDGE_BOTTOM });
287 swiperController_->SetTabBarFinishCallback([weak = WeakClaim(this)]() {
288 auto pattern = weak.Upgrade();
289 CHECK_NULL_VOID(pattern);
290 // always swipe with physical curve, ignore animationDuration
291 pattern->SetSwiperCurve(TabBarPhysicalCurve);
292
293 if (pattern->scrollableEvent_) {
294 auto scrollable = pattern->scrollableEvent_->GetScrollable();
295 if (scrollable) {
296 scrollable->StopScrollable();
297 }
298 }
299
300 pattern->StopTranslateAnimation();
301 pattern->ResetIndicatorAnimationState();
302 auto swiperPattern = pattern->GetSwiperPattern();
303 CHECK_NULL_VOID(swiperPattern);
304 auto currentIndex = swiperPattern->GetCurrentIndex();
305 auto totalCount = swiperPattern->TotalCount();
306 if (currentIndex >= totalCount || currentIndex < 0) {
307 currentIndex = 0;
308 }
309 auto layoutProperty = pattern->GetLayoutProperty<TabBarLayoutProperty>();
310 CHECK_NULL_VOID(layoutProperty);
311 if (layoutProperty->GetIndicatorValue(0) != currentIndex) {
312 pattern->UpdateSubTabBoard(currentIndex);
313 pattern->UpdateTextColorAndFontWeight(currentIndex);
314 pattern->UpdateIndicator(currentIndex);
315 pattern->SetChangeByClick(false);
316 }
317 });
318 InitSurfaceChangedCallback();
319 }
320
InitSurfaceChangedCallback()321 void TabBarPattern::InitSurfaceChangedCallback()
322 {
323 auto host = GetHost();
324 CHECK_NULL_VOID(host);
325 auto pipeline = host->GetContextRefPtr();
326 CHECK_NULL_VOID(pipeline);
327 if (!HasSurfaceChangedCallback()) {
328 auto callbackId = pipeline->RegisterSurfaceChangedCallback(
329 [weak = WeakClaim(this)](int32_t newWidth, int32_t newHeight, int32_t prevWidth, int32_t prevHeight,
330 WindowSizeChangeReason type) {
331 auto pattern = weak.Upgrade();
332 if (!pattern) {
333 return;
334 }
335
336 pattern->windowSizeChangeReason_ = type;
337 pattern->prevRootSize_ = std::make_pair(prevWidth, prevHeight);
338
339 if (type == WindowSizeChangeReason::ROTATION) {
340 pattern->StopTranslateAnimation();
341 }
342 });
343 UpdateSurfaceChangedCallbackId(callbackId);
344 }
345 }
346
OnDetachFromFrameNode(FrameNode * node)347 void TabBarPattern::OnDetachFromFrameNode(FrameNode* node)
348 {
349 auto pipeline = GetContext();
350 CHECK_NULL_VOID(pipeline);
351 if (HasSurfaceChangedCallback()) {
352 pipeline->UnregisterSurfaceChangedCallback(surfaceChangedCallbackId_.value_or(-1));
353 }
354 pipeline->RemoveWindowStateChangedCallback(node->GetId());
355 }
356
BeforeCreateLayoutWrapper()357 void TabBarPattern::BeforeCreateLayoutWrapper()
358 {
359 auto host = GetHost();
360 CHECK_NULL_VOID(host);
361 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
362 CHECK_NULL_VOID(layoutProperty);
363 if (targetIndex_) {
364 targetIndex_ = GetLoopIndex(targetIndex_.value());
365 }
366 if (isExecuteBuilder_) {
367 jumpIndex_ = layoutProperty->GetIndicatorValue(0);
368 isExecuteBuilder_ = false;
369 }
370 }
371
AddTabBarItemClickEvent(const RefPtr<FrameNode> & tabBarItem)372 void TabBarPattern::AddTabBarItemClickEvent(const RefPtr<FrameNode>& tabBarItem)
373 {
374 CHECK_NULL_VOID(tabBarItem);
375 auto tabBarItemId = tabBarItem->GetId();
376 if (clickEvents_.find(tabBarItemId) != clickEvents_.end()) {
377 return;
378 }
379
380 auto eventHub = tabBarItem->GetEventHub<EventHub>();
381 CHECK_NULL_VOID(eventHub);
382 auto gestureHub = eventHub->GetOrCreateGestureEventHub();
383 CHECK_NULL_VOID(gestureHub);
384 auto clickCallback = [weak = WeakClaim(this), tabBarItemId](GestureEvent& info) {
385 auto tabBar = weak.Upgrade();
386 CHECK_NULL_VOID(tabBar);
387 auto host = tabBar->GetHost();
388 CHECK_NULL_VOID(host);
389 auto index = host->GetChildFlatIndex(tabBarItemId).second;
390 tabBar->HandleClick(info.GetSourceDevice(), index);
391 };
392 auto clickEvent = AceType::MakeRefPtr<ClickEvent>(std::move(clickCallback));
393 clickEvents_[tabBarItemId] = clickEvent;
394 gestureHub->AddClickEvent(clickEvent);
395 }
396
AddMaskItemClickEvent()397 void TabBarPattern::AddMaskItemClickEvent()
398 {
399 auto host = GetHost();
400 CHECK_NULL_VOID(host);
401 auto childCount = host->GetChildren().size() - MASK_COUNT;
402
403 for (int32_t maskIndex = 0; maskIndex < MASK_COUNT; maskIndex++) {
404 auto maskNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(childCount + maskIndex));
405 CHECK_NULL_VOID(maskNode);
406 auto maskNodeId = maskNode->GetId();
407 if (clickEvents_.find(maskNodeId) != clickEvents_.end()) {
408 continue;
409 }
410
411 auto eventHub = maskNode->GetEventHub<EventHub>();
412 CHECK_NULL_VOID(eventHub);
413 auto gestureHub = eventHub->GetOrCreateGestureEventHub();
414 CHECK_NULL_VOID(gestureHub);
415 auto clickCallback = [weak = WeakClaim(this), maskIndex](GestureEvent& info) {
416 auto tabBar = weak.Upgrade();
417 CHECK_NULL_VOID(tabBar);
418 auto layoutProperty = tabBar->GetLayoutProperty<TabBarLayoutProperty>();
419 CHECK_NULL_VOID(layoutProperty);
420 auto index = (maskIndex == 0) ? layoutProperty->GetSelectedMask().value_or(-1) :
421 layoutProperty->GetUnselectedMask().value_or(-1);
422 if (index >= 0) {
423 tabBar->HandleClick(info.GetSourceDevice(), index);
424 }
425 };
426 auto clickEvent = AceType::MakeRefPtr<ClickEvent>(std::move(clickCallback));
427 clickEvents_[maskNodeId] = clickEvent;
428 gestureHub->AddClickEvent(clickEvent);
429 }
430 }
431
InitLongPressEvent(const RefPtr<GestureEventHub> & gestureHub)432 void TabBarPattern::InitLongPressEvent(const RefPtr<GestureEventHub>& gestureHub)
433 {
434 if (longPressEvent_) {
435 return;
436 }
437
438 auto longPressTask = [weak = WeakClaim(this)](GestureEvent& info) {
439 auto tabBar = weak.Upgrade();
440 if (tabBar) {
441 tabBar->HandleLongPressEvent(info);
442 }
443 };
444 longPressEvent_ = AceType::MakeRefPtr<LongPressEvent>(std::move(longPressTask));
445 gestureHub->SetLongPressEvent(longPressEvent_);
446 }
447
InitDragEvent(const RefPtr<GestureEventHub> & gestureHub)448 void TabBarPattern::InitDragEvent(const RefPtr<GestureEventHub>& gestureHub)
449 {
450 CHECK_NULL_VOID(!dragEvent_);
451 auto actionUpdateTask = [weak = WeakClaim(this)](const GestureEvent& info) {
452 auto tabBar = weak.Upgrade();
453 auto index = tabBar->CalculateSelectedIndex(info.GetLocalLocation());
454 auto host = tabBar->GetHost();
455 CHECK_NULL_VOID(host);
456 auto totalCount = host->TotalChildCount() - MASK_COUNT;
457 if (tabBar && tabBar->dialogNode_ && index >= 0 && index < totalCount) {
458 if (!tabBar->moveIndex_.has_value()) {
459 tabBar->moveIndex_ = index;
460 }
461
462 if (tabBar->moveIndex_ != index) {
463 tabBar->CloseDialog();
464 tabBar->moveIndex_ = index;
465 tabBar->ShowDialogWithNode(index);
466 }
467 }
468 };
469 dragEvent_ = MakeRefPtr<DragEvent>(nullptr, std::move(actionUpdateTask), nullptr, nullptr);
470 PanDirection panDirection = { .type = PanDirection::ALL };
471 gestureHub->SetDragEvent(dragEvent_, panDirection, DEFAULT_PAN_FINGER, DEFAULT_PAN_DISTANCE);
472 }
473
InitScrollableEvent(const RefPtr<TabBarLayoutProperty> & layoutProperty,const RefPtr<GestureEventHub> & gestureHub)474 void TabBarPattern::InitScrollableEvent(
475 const RefPtr<TabBarLayoutProperty>& layoutProperty, const RefPtr<GestureEventHub>& gestureHub)
476 {
477 if (layoutProperty->GetTabBarModeValue(TabBarMode::FIXED) == TabBarMode::SCROLLABLE) {
478 InitScrollable(gestureHub);
479 SetEdgeEffect(gestureHub);
480 } else {
481 if (scrollableEvent_) {
482 gestureHub->RemoveScrollableEvent(scrollableEvent_);
483 scrollableEvent_.Reset();
484 }
485 if (scrollEffect_) {
486 gestureHub->RemoveScrollEdgeEffect(scrollEffect_);
487 scrollEffect_.Reset();
488 }
489 }
490 }
491
InitScrollable(const RefPtr<GestureEventHub> & gestureHub)492 void TabBarPattern::InitScrollable(const RefPtr<GestureEventHub>& gestureHub)
493 {
494 auto host = GetHost();
495 CHECK_NULL_VOID(host);
496 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
497 CHECK_NULL_VOID(layoutProperty);
498 auto axis = layoutProperty->GetAxis().value_or(Axis::HORIZONTAL);
499 if (axis_ == axis && scrollableEvent_) {
500 return;
501 }
502
503 axis_ = axis;
504 auto task = [weak = WeakClaim(this)](double offset, int32_t source) {
505 if (source == SCROLL_FROM_START) {
506 return true;
507 }
508 auto pattern = weak.Upgrade();
509 CHECK_NULL_RETURN(pattern, false);
510 if (!pattern->CanScroll()) {
511 return false;
512 }
513
514 if (pattern->IsOutOfBoundary()) {
515 // over scroll in drag update from normal to over scroll or during over scroll.
516 auto scrollable = pattern->scrollableEvent_->GetScrollable();
517 if (scrollable) {
518 scrollable->SetCanOverScroll(true);
519 }
520
521 auto host = pattern->GetHost();
522 CHECK_NULL_RETURN(host, false);
523 auto geometryNode = host->GetGeometryNode();
524 CHECK_NULL_RETURN(geometryNode, false);
525 auto overScrollInfo = pattern->GetOverScrollInfo(geometryNode->GetPaddingSize());
526 if (source == SCROLL_FROM_UPDATE) {
527 // adjust offset.
528 if (overScrollInfo.second != 0.0f) {
529 pattern->canOverScroll_ = true;
530 auto friction = CalculateFriction(std::abs(overScrollInfo.first) / overScrollInfo.second);
531 pattern->UpdateCurrentOffset(static_cast<float>(offset * friction));
532 }
533 return true;
534 }
535 }
536 if (source != SCROLL_FROM_AXIS) {
537 pattern->canOverScroll_ = true;
538 }
539 pattern->UpdateCurrentOffset(static_cast<float>(offset));
540 return true;
541 };
542
543 if (scrollableEvent_) {
544 gestureHub->RemoveScrollableEvent(scrollableEvent_);
545 }
546
547 scrollableEvent_ = MakeRefPtr<ScrollableEvent>(axis);
548 auto scrollable = MakeRefPtr<Scrollable>(task, axis);
549 scrollable->SetNodeId(host->GetAccessibilityId());
550 scrollable->Initialize(host->GetContextRefPtr());
551 scrollable->SetMaxFlingVelocity(MAX_FLING_VELOCITY);
552 auto renderContext = host->GetRenderContext();
553 CHECK_NULL_VOID(renderContext);
554 auto springProperty = scrollable->GetSpringProperty();
555 renderContext->AttachNodeAnimatableProperty(springProperty);
556 auto frictionProperty = scrollable->GetFrictionProperty();
557 renderContext->AttachNodeAnimatableProperty(frictionProperty);
558 scrollableEvent_->SetScrollable(scrollable);
559 gestureHub->AddScrollableEvent(scrollableEvent_);
560 scrollableEvent_->GetScrollable()->SetEdgeEffect(EdgeEffect::SPRING);
561 }
562
CanScroll() const563 bool TabBarPattern::CanScroll() const
564 {
565 auto host = GetHost();
566 CHECK_NULL_RETURN(host, false);
567 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
568 CHECK_NULL_RETURN(layoutProperty, false);
569 if (layoutProperty->GetTabBarModeValue(TabBarMode::FIXED) == TabBarMode::FIXED) {
570 return false;
571 }
572
573 if (visibleItemPosition_.empty()) {
574 return false;
575 }
576 auto geometryNode = host->GetGeometryNode();
577 CHECK_NULL_RETURN(geometryNode, false);
578 auto visibleItemStartIndex = visibleItemPosition_.begin()->first;
579 auto visibleItemEndIndex = visibleItemPosition_.rbegin()->first;
580 auto visibleItemStartPos = visibleItemPosition_.begin()->second.startPos;
581 auto visibleItemEndPos = visibleItemPosition_.rbegin()->second.endPos;
582 auto childCount = host->TotalChildCount() - MASK_COUNT;
583 auto contentMainSize =
584 geometryNode->GetPaddingSize().MainSize(layoutProperty->GetAxis().value_or(Axis::HORIZONTAL));
585 return visibleItemStartIndex > 0 || LessNotEqual(visibleItemStartPos, scrollMargin_) ||
586 visibleItemEndIndex < (childCount - 1) || GreatNotEqual(visibleItemEndPos, contentMainSize - scrollMargin_);
587 }
588
GetOverScrollInfo(const SizeF & size)589 std::pair<float, float> TabBarPattern::GetOverScrollInfo(const SizeF& size)
590 {
591 auto overScroll = 0.0f;
592 auto mainSize = 0.0f;
593 if (visibleItemPosition_.empty()) {
594 return std::make_pair(overScroll, mainSize);
595 }
596
597 auto visibleItemStartPos = visibleItemPosition_.begin()->second.startPos;
598 auto visibleItemEndPos = visibleItemPosition_.rbegin()->second.endPos;
599 auto startPos = visibleItemStartPos - scrollMargin_;
600 mainSize = size.MainSize(axis_);
601 if (Positive(startPos)) {
602 overScroll = startPos;
603 } else {
604 overScroll = mainSize - visibleItemEndPos - scrollMargin_;
605 }
606 return std::make_pair(overScroll, mainSize);
607 }
608
InitTouch(const RefPtr<GestureEventHub> & gestureHub)609 void TabBarPattern::InitTouch(const RefPtr<GestureEventHub>& gestureHub)
610 {
611 if (touchEvent_) {
612 return;
613 }
614 auto touchCallback = [weak = WeakClaim(this)](const TouchEventInfo& info) {
615 auto pattern = weak.Upgrade();
616 CHECK_NULL_VOID(pattern);
617 pattern->HandleTouchEvent(info.GetTouches().front());
618 };
619 touchEvent_ = MakeRefPtr<TouchEventImpl>(std::move(touchCallback));
620 gestureHub->AddTouchEvent(touchEvent_);
621 }
622
InitHoverEvent()623 void TabBarPattern::InitHoverEvent()
624 {
625 if (hoverEvent_) {
626 return;
627 }
628 auto host = GetHost();
629 CHECK_NULL_VOID(host);
630 auto eventHub = GetHost()->GetEventHub<EventHub>();
631 auto inputHub = eventHub->GetOrCreateInputEventHub();
632
633 auto hoverTask = [weak = WeakClaim(this)](bool isHover) {
634 auto pattern = weak.Upgrade();
635 if (pattern) {
636 pattern->HandleHoverEvent(isHover);
637 }
638 };
639 hoverEvent_ = MakeRefPtr<InputEvent>(std::move(hoverTask));
640 inputHub->AddOnHoverEvent(hoverEvent_);
641 }
642
InitMouseEvent()643 void TabBarPattern::InitMouseEvent()
644 {
645 if (mouseEvent_) {
646 return;
647 }
648 auto host = GetHost();
649 CHECK_NULL_VOID(host);
650 auto eventHub = GetHost()->GetEventHub<EventHub>();
651 auto inputHub = eventHub->GetOrCreateInputEventHub();
652 auto mouseTask = [weak = WeakClaim(this)](const MouseInfo& info) {
653 auto pattern = weak.Upgrade();
654 if (pattern) {
655 pattern->HandleMouseEvent(info);
656 }
657 };
658 mouseEvent_ = MakeRefPtr<InputEvent>(std::move(mouseTask));
659 inputHub->AddOnMouseEvent(mouseEvent_);
660 }
661
HandleMouseEvent(const MouseInfo & info)662 void TabBarPattern::HandleMouseEvent(const MouseInfo& info)
663 {
664 if (IsContainsBuilder()) {
665 return;
666 }
667 auto host = GetHost();
668 CHECK_NULL_VOID(host);
669 auto totalCount = host->TotalChildCount() - MASK_COUNT;
670 if (totalCount < 0) {
671 return;
672 }
673 auto index = CalculateSelectedIndex(info.GetLocalLocation());
674 if (index < 0 || index >= totalCount) {
675 if (hoverIndex_.has_value() && !touchingIndex_.has_value()) {
676 HandleMoveAway(hoverIndex_.value());
677 }
678 hoverIndex_.reset();
679 return;
680 }
681 auto mouseAction = info.GetAction();
682 if (mouseAction == MouseAction::MOVE || mouseAction == MouseAction::WINDOW_ENTER) {
683 if (touchingIndex_.has_value()) {
684 hoverIndex_ = index;
685 return;
686 }
687 if (!hoverIndex_.has_value()) {
688 HandleHoverOnEvent(index);
689 hoverIndex_ = index;
690 return;
691 }
692 if (hoverIndex_.value() != index) {
693 HandleMoveAway(hoverIndex_.value());
694 HandleHoverOnEvent(index);
695 hoverIndex_ = index;
696 return;
697 }
698 return;
699 }
700 if (mouseAction == MouseAction::WINDOW_LEAVE) {
701 if (hoverIndex_.has_value()) {
702 HandleMoveAway(hoverIndex_.value());
703 }
704 }
705 }
706
HandleHoverEvent(bool isHover)707 void TabBarPattern::HandleHoverEvent(bool isHover)
708 {
709 if (IsContainsBuilder()) {
710 return;
711 }
712 isHover_ = isHover;
713 if (!isHover_ && hoverIndex_.has_value()) {
714 if (!touchingIndex_.has_value()) {
715 HandleMoveAway(hoverIndex_.value());
716 }
717 hoverIndex_.reset();
718 }
719 }
720
HandleHoverOnEvent(int32_t index)721 void TabBarPattern::HandleHoverOnEvent(int32_t index)
722 {
723 auto pipelineContext = PipelineContext::GetCurrentContext();
724 CHECK_NULL_VOID(pipelineContext);
725 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
726 CHECK_NULL_VOID(tabTheme);
727 PlayPressAnimation(index, tabTheme->GetSubTabBarHoverColor(), AnimationType::HOVER);
728 }
729
HandleMoveAway(int32_t index)730 void TabBarPattern::HandleMoveAway(int32_t index)
731 {
732 PlayPressAnimation(index, Color::TRANSPARENT, AnimationType::HOVER);
733 }
734
InitOnKeyEvent(const RefPtr<FocusHub> & focusHub)735 void TabBarPattern::InitOnKeyEvent(const RefPtr<FocusHub>& focusHub)
736 {
737 auto onKeyEvent = [wp = WeakClaim(this)](const KeyEvent& event) -> bool {
738 auto pattern = wp.Upgrade();
739 if (pattern) {
740 return pattern->OnKeyEvent(event);
741 }
742 return false;
743 };
744 focusHub->SetOnKeyEventInternal(std::move(onKeyEvent));
745
746 auto getInnerPaintRectCallback = [wp = WeakClaim(this)](RoundRect& paintRect) {
747 auto pattern = wp.Upgrade();
748 if (pattern) {
749 pattern->GetInnerFocusPaintRect(paintRect);
750 }
751 };
752 focusHub->SetInnerFocusPaintRectCallback(getInnerPaintRectCallback);
753 }
754
OnKeyEvent(const KeyEvent & event)755 bool TabBarPattern::OnKeyEvent(const KeyEvent& event)
756 {
757 auto pipeline = PipelineContext::GetCurrentContext();
758 CHECK_NULL_RETURN(pipeline, false);
759 if (!pipeline->GetIsFocusActive()) {
760 return false;
761 }
762 isFirstFocus_ = false;
763 if (event.action != KeyAction::DOWN) {
764 return false;
765 }
766 if (tabBarStyle_ == TabBarStyle::BOTTOMTABBATSTYLE || tabBarStyle_ == TabBarStyle::SUBTABBATSTYLE) {
767 return OnKeyEventWithoutClick(event);
768 }
769 auto host = GetHost();
770 CHECK_NULL_RETURN(host, false);
771 CHECK_NULL_RETURN(swiperController_, false);
772 swiperController_->FinishAnimation();
773 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
774 auto indicator = tabBarLayoutProperty->GetIndicatorValue(0);
775 if (event.code == (tabBarLayoutProperty->GetAxisValue(Axis::HORIZONTAL) == Axis::HORIZONTAL
776 ? (isRTL_ ? KeyCode::KEY_DPAD_RIGHT : KeyCode::KEY_DPAD_LEFT) : KeyCode::KEY_DPAD_UP) ||
777 event.IsShiftWith(KeyCode::KEY_TAB)) {
778 if (indicator <= 0) {
779 return false;
780 }
781 indicator -= 1;
782 FocusIndexChange(indicator);
783 return true;
784 }
785 if (event.code == (tabBarLayoutProperty->GetAxisValue(Axis::HORIZONTAL) == Axis::HORIZONTAL
786 ? (isRTL_ ? KeyCode::KEY_DPAD_LEFT : KeyCode::KEY_DPAD_RIGHT) : KeyCode::KEY_DPAD_DOWN) ||
787 event.code == KeyCode::KEY_TAB) {
788 if (indicator >= host->TotalChildCount() - MASK_COUNT - 1) {
789 return false;
790 }
791 indicator += 1;
792 FocusIndexChange(indicator);
793 return true;
794 }
795 if (event.code == KeyCode::KEY_MOVE_HOME) {
796 indicator = 0;
797 FocusIndexChange(indicator);
798 return true;
799 }
800 if (event.code == KeyCode::KEY_MOVE_END) {
801 indicator = host->TotalChildCount() - MASK_COUNT - 1;
802 FocusIndexChange(indicator);
803 return true;
804 }
805 return false;
806 }
807
OnKeyEventWithoutClick(const KeyEvent & event)808 bool TabBarPattern::OnKeyEventWithoutClick(const KeyEvent& event)
809 {
810 auto host = GetHost();
811 CHECK_NULL_RETURN(host, false);
812 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
813 if (event.code == (tabBarLayoutProperty->GetAxisValue(Axis::HORIZONTAL) == Axis::HORIZONTAL
814 ? KeyCode::KEY_DPAD_LEFT
815 : KeyCode::KEY_DPAD_UP) ||
816 event.IsShiftWith(KeyCode::KEY_TAB)) {
817 if (focusIndicator_ <= 0) {
818 return false;
819 }
820 if (!ContentWillChange(focusIndicator_ - 1)) {
821 return true;
822 }
823 focusIndicator_ -= 1;
824 PaintFocusState();
825 return true;
826 }
827 if (event.code == (tabBarLayoutProperty->GetAxisValue(Axis::HORIZONTAL) == Axis::HORIZONTAL
828 ? KeyCode::KEY_DPAD_RIGHT
829 : KeyCode::KEY_DPAD_DOWN) ||
830 event.code == KeyCode::KEY_TAB) {
831 if (focusIndicator_ >= host->TotalChildCount() - MASK_COUNT - 1) {
832 return false;
833 }
834 if (!ContentWillChange(focusIndicator_ + 1)) {
835 return true;
836 }
837 focusIndicator_ += 1;
838 PaintFocusState();
839 return true;
840 }
841 return OnKeyEventWithoutClick(host, event);
842 }
843
OnKeyEventWithoutClick(const RefPtr<FrameNode> & host,const KeyEvent & event)844 bool TabBarPattern::OnKeyEventWithoutClick(const RefPtr<FrameNode>& host, const KeyEvent& event)
845 {
846 if (event.code == KeyCode::KEY_MOVE_HOME) {
847 if (!ContentWillChange(0)) {
848 return true;
849 }
850 focusIndicator_ = 0;
851 PaintFocusState();
852 return true;
853 }
854 if (event.code == KeyCode::KEY_MOVE_END) {
855 if (!ContentWillChange(host->TotalChildCount() - MASK_COUNT - 1)) {
856 return true;
857 }
858 focusIndicator_ = host->TotalChildCount() - MASK_COUNT - 1;
859 PaintFocusState();
860 return true;
861 }
862 if (event.code == KeyCode::KEY_SPACE || event.code == KeyCode::KEY_ENTER) {
863 TabBarClickEvent(focusIndicator_);
864 FocusIndexChange(focusIndicator_);
865 return true;
866 }
867 return false;
868 }
869
FocusIndexChange(int32_t index)870 void TabBarPattern::FocusIndexChange(int32_t index)
871 {
872 auto host = GetHost();
873 CHECK_NULL_VOID(host);
874 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
875 CHECK_NULL_VOID(tabsNode);
876 auto tabsPattern = tabsNode->GetPattern<TabsPattern>();
877 CHECK_NULL_VOID(tabsPattern);
878 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
879 CHECK_NULL_VOID(tabBarLayoutProperty);
880
881 if (!ContentWillChange(tabBarLayoutProperty->GetIndicatorValue(0), index)) {
882 return;
883 }
884 changeByClick_ = true;
885 clickRepeat_ = true;
886 SetSwiperCurve(DurationCubicCurve);
887 if (tabsPattern->GetIsCustomAnimation()) {
888 OnCustomContentTransition(indicator_, index);
889 tabBarLayoutProperty->UpdateIndicator(index);
890 PaintFocusState(false);
891 } else {
892 UpdateAnimationDuration();
893 if (GetAnimationDuration().has_value()
894 && tabsPattern->GetAnimateMode() != TabAnimateMode::NO_ANIMATION) {
895 tabContentWillChangeFlag_ = true;
896 swiperController_->SwipeTo(index);
897 } else {
898 swiperController_->SwipeToWithoutAnimation(index);
899 }
900
901 tabBarLayoutProperty->UpdateIndicator(index);
902 PaintFocusState();
903 }
904 UpdateTextColorAndFontWeight(index);
905 UpdateSubTabBoard(index);
906 }
907
GetInnerFocusPaintRect(RoundRect & paintRect)908 void TabBarPattern::GetInnerFocusPaintRect(RoundRect& paintRect)
909 {
910 auto host = GetHost();
911 CHECK_NULL_VOID(host);
912 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
913 CHECK_NULL_VOID(tabBarLayoutProperty);
914 auto indicator = tabBarLayoutProperty->GetIndicatorValue(0);
915 if (tabBarStyle_ == TabBarStyle::BOTTOMTABBATSTYLE || tabBarStyle_ == TabBarStyle::SUBTABBATSTYLE) {
916 if (isFirstFocus_) {
917 focusIndicator_ = indicator;
918 } else {
919 indicator = focusIndicator_;
920 }
921 }
922 auto childNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(indicator));
923 CHECK_NULL_VOID(childNode);
924 auto renderContext = childNode->GetRenderContext();
925 CHECK_NULL_VOID(renderContext);
926 auto columnPaintRect = renderContext->GetPaintRectWithoutTransform();
927 auto pipeline = PipelineContext::GetCurrentContext();
928 CHECK_NULL_VOID(pipeline);
929 auto tabTheme = pipeline->GetTheme<TabTheme>();
930 CHECK_NULL_VOID(tabTheme);
931 auto radius = tabTheme->GetFocusIndicatorRadius();
932 auto outLineWidth = tabTheme->GetActiveIndicatorWidth();
933 columnPaintRect.SetOffset(OffsetF((columnPaintRect.GetOffset().GetX() + outLineWidth.ConvertToPx() / 2),
934 (columnPaintRect.GetOffset().GetY() + outLineWidth.ConvertToPx() / 2)));
935 columnPaintRect.SetSize(SizeF((columnPaintRect.GetSize().Width() - outLineWidth.ConvertToPx()),
936 (columnPaintRect.GetSize().Height() - outLineWidth.ConvertToPx())));
937
938 paintRect.SetRect(columnPaintRect);
939 paintRect.SetCornerRadius(RoundRect::CornerPos::TOP_LEFT_POS, static_cast<RSScalar>(radius.ConvertToPx()),
940 static_cast<RSScalar>(radius.ConvertToPx()));
941 paintRect.SetCornerRadius(RoundRect::CornerPos::TOP_RIGHT_POS, static_cast<RSScalar>(radius.ConvertToPx()),
942 static_cast<RSScalar>(radius.ConvertToPx()));
943 paintRect.SetCornerRadius(RoundRect::CornerPos::BOTTOM_LEFT_POS, static_cast<RSScalar>(radius.ConvertToPx()),
944 static_cast<RSScalar>(radius.ConvertToPx()));
945 paintRect.SetCornerRadius(RoundRect::CornerPos::BOTTOM_RIGHT_POS, static_cast<RSScalar>(radius.ConvertToPx()),
946 static_cast<RSScalar>(radius.ConvertToPx()));
947 }
948
PaintFocusState(bool needMarkDirty)949 void TabBarPattern::PaintFocusState(bool needMarkDirty)
950 {
951 auto host = GetHost();
952 CHECK_NULL_VOID(host);
953
954 RoundRect focusRect;
955 GetInnerFocusPaintRect(focusRect);
956
957 auto focusHub = host->GetFocusHub();
958 CHECK_NULL_VOID(focusHub);
959 focusHub->PaintInnerFocusState(focusRect);
960
961 if (needMarkDirty) {
962 host->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
963 }
964 }
965
OnModifyDone()966 void TabBarPattern::OnModifyDone()
967 {
968 Pattern::OnModifyDone();
969 auto host = GetHost();
970 CHECK_NULL_VOID(host);
971 auto hub = host->GetEventHub<EventHub>();
972 CHECK_NULL_VOID(hub);
973 auto gestureHub = hub->GetOrCreateGestureEventHub();
974 CHECK_NULL_VOID(gestureHub);
975
976 AddMaskItemClickEvent();
977 InitTurnPageRateEvent();
978 auto pipelineContext = PipelineContext::GetCurrentContext();
979 CHECK_NULL_VOID(pipelineContext);
980 if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_TWELVE)) {
981 auto tabBarPaintProperty = host->GetPaintProperty<TabBarPaintProperty>();
982 CHECK_NULL_VOID(tabBarPaintProperty);
983 auto theme = pipelineContext->GetTheme<TabTheme>();
984 CHECK_NULL_VOID(theme);
985 auto defaultBlurStyle = static_cast<BlurStyle>(theme->GetBottomTabBackgroundBlurStyle());
986 if (defaultBlurStyle != BlurStyle::NO_MATERIAL) {
987 tabBarPaintProperty->UpdateTabBarBlurStyle(defaultBlurStyle);
988 }
989 }
990 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
991 CHECK_NULL_VOID(layoutProperty);
992 InitScrollableEvent(layoutProperty, gestureHub);
993 InitTouch(gestureHub);
994 InitHoverEvent();
995 InitMouseEvent();
996 SetSurfaceChangeCallback();
997 auto focusHub = host->GetFocusHub();
998 CHECK_NULL_VOID(focusHub);
999 InitOnKeyEvent(focusHub);
1000 SetAccessibilityAction();
1001 UpdateSubTabBoard(indicator_);
1002 StopTranslateAnimation();
1003 jumpIndex_ = layoutProperty->GetIndicatorValue(0);
1004
1005 RemoveTabBarEventCallback();
1006 AddTabBarEventCallback();
1007
1008 axis_ = layoutProperty->GetAxis().value_or(Axis::HORIZONTAL);
1009 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
1010 CHECK_NULL_VOID(tabsNode);
1011 auto tabsLayoutProperty = AceType::DynamicCast<TabsLayoutProperty>(tabsNode->GetLayoutProperty());
1012 CHECK_NULL_VOID(tabsLayoutProperty);
1013 isRTL_ = tabsLayoutProperty->GetNonAutoLayoutDirection() == TextDirection::RTL;
1014 }
1015
SetSurfaceChangeCallback()1016 void TabBarPattern::SetSurfaceChangeCallback()
1017 {
1018 CHECK_NULL_VOID(swiperController_);
1019 auto surfaceChangeCallback = [weak = WeakClaim(this)]() {
1020 auto tabBarPattern = weak.Upgrade();
1021 CHECK_NULL_VOID(tabBarPattern);
1022 tabBarPattern->isTouchingSwiper_ = false;
1023 };
1024 swiperController_->SetSurfaceChangeCallback(std::move(surfaceChangeCallback));
1025 }
1026
RemoveTabBarEventCallback()1027 void TabBarPattern::RemoveTabBarEventCallback()
1028 {
1029 CHECK_NULL_VOID(swiperController_);
1030 auto removeEventCallback = [weak = WeakClaim(this)]() {
1031 auto tabBarPattern = weak.Upgrade();
1032 CHECK_NULL_VOID(tabBarPattern);
1033 auto host = tabBarPattern->GetHost();
1034 CHECK_NULL_VOID(host);
1035 auto hub = host->GetEventHub<EventHub>();
1036 CHECK_NULL_VOID(hub);
1037 auto gestureHub = hub->GetOrCreateGestureEventHub();
1038 CHECK_NULL_VOID(gestureHub);
1039 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1040 CHECK_NULL_VOID(layoutProperty);
1041 if (layoutProperty->GetTabBarModeValue(TabBarMode::FIXED) == TabBarMode::SCROLLABLE) {
1042 gestureHub->RemoveScrollableEvent(tabBarPattern->scrollableEvent_);
1043 }
1044 gestureHub->RemoveTouchEvent(tabBarPattern->touchEvent_);
1045 gestureHub->RemoveDragEvent();
1046 gestureHub->SetLongPressEvent(nullptr);
1047 tabBarPattern->longPressEvent_ = nullptr;
1048 tabBarPattern->dragEvent_ = nullptr;
1049 tabBarPattern->isTouchingSwiper_ = true;
1050 for (const auto& childNode : host->GetChildren()) {
1051 CHECK_NULL_VOID(childNode);
1052 auto frameNode = AceType::DynamicCast<FrameNode>(childNode);
1053 CHECK_NULL_VOID(frameNode);
1054 auto childHub = frameNode->GetEventHub<EventHub>();
1055 CHECK_NULL_VOID(childHub);
1056 auto childGestureHub = childHub->GetOrCreateGestureEventHub();
1057 CHECK_NULL_VOID(childGestureHub);
1058 auto iter = tabBarPattern->clickEvents_.find(frameNode->GetId());
1059 if (iter != tabBarPattern->clickEvents_.end()) {
1060 childGestureHub->RemoveClickEvent(iter->second);
1061 }
1062 }
1063 };
1064 swiperController_->SetRemoveTabBarEventCallback(std::move(removeEventCallback));
1065 }
1066
AddTabBarEventCallback()1067 void TabBarPattern::AddTabBarEventCallback()
1068 {
1069 CHECK_NULL_VOID(swiperController_);
1070 auto addEventCallback = [weak = WeakClaim(this)]() {
1071 auto tabBarPattern = weak.Upgrade();
1072 CHECK_NULL_VOID(tabBarPattern);
1073 auto host = tabBarPattern->GetHost();
1074 CHECK_NULL_VOID(host);
1075 auto hub = host->GetEventHub<EventHub>();
1076 CHECK_NULL_VOID(hub);
1077 auto gestureHub = hub->GetOrCreateGestureEventHub();
1078 CHECK_NULL_VOID(gestureHub);
1079 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1080 CHECK_NULL_VOID(layoutProperty);
1081 if (layoutProperty->GetTabBarModeValue(TabBarMode::FIXED) == TabBarMode::SCROLLABLE) {
1082 gestureHub->AddScrollableEvent(tabBarPattern->scrollableEvent_);
1083 }
1084 gestureHub->AddTouchEvent(tabBarPattern->touchEvent_);
1085 for (const auto& childNode : host->GetChildren()) {
1086 CHECK_NULL_VOID(childNode);
1087 auto frameNode = AceType::DynamicCast<FrameNode>(childNode);
1088 CHECK_NULL_VOID(frameNode);
1089 auto childHub = frameNode->GetEventHub<EventHub>();
1090 CHECK_NULL_VOID(childHub);
1091 auto childGestureHub = childHub->GetOrCreateGestureEventHub();
1092 CHECK_NULL_VOID(childGestureHub);
1093 auto iter = tabBarPattern->clickEvents_.find(frameNode->GetId());
1094 if (iter != tabBarPattern->clickEvents_.end()) {
1095 childGestureHub->AddClickEvent(iter->second);
1096 }
1097 }
1098 tabBarPattern->InitLongPressAndDragEvent();
1099 };
1100 swiperController_->SetAddTabBarEventCallback(std::move(addEventCallback));
1101 }
1102
UpdatePaintIndicator(int32_t indicator,bool needMarkDirty)1103 void TabBarPattern::UpdatePaintIndicator(int32_t indicator, bool needMarkDirty)
1104 {
1105 auto tabBarNode = GetHost();
1106 CHECK_NULL_VOID(tabBarNode);
1107 auto tabBarPattern = tabBarNode->GetPattern<TabBarPattern>();
1108 CHECK_NULL_VOID(tabBarPattern);
1109 auto paintProperty = GetPaintProperty<TabBarPaintProperty>();
1110 if (indicator_ >= static_cast<int32_t>(tabBarStyles_.size())) {
1111 return;
1112 }
1113 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
1114 CHECK_NULL_VOID(layoutProperty);
1115 if (tabBarPattern->IsContainsBuilder() || layoutProperty->GetAxis() == Axis::VERTICAL ||
1116 tabBarStyles_[indicator] == TabBarStyle::BOTTOMTABBATSTYLE) {
1117 paintProperty->UpdateIndicator({});
1118
1119 if (needMarkDirty) {
1120 tabBarNode->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
1121 }
1122
1123 return;
1124 }
1125
1126 RectF rect = {};
1127 if (visibleItemPosition_.find(indicator) != visibleItemPosition_.end()) {
1128 rect = layoutProperty->GetIndicatorRect(indicator);
1129 }
1130 paintProperty->UpdateIndicator(rect);
1131 if (!isTouchingSwiper_ || tabBarStyles_[indicator] != TabBarStyle::SUBTABBATSTYLE) {
1132 currentIndicatorOffset_ = rect.GetX() + rect.Width() / 2;
1133
1134 if (needMarkDirty) {
1135 tabBarNode->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
1136 }
1137 }
1138 }
1139
OnDirtyLayoutWrapperSwap(const RefPtr<LayoutWrapper> & dirty,const DirtySwapConfig & config)1140 bool TabBarPattern::OnDirtyLayoutWrapperSwap(const RefPtr<LayoutWrapper>& dirty, const DirtySwapConfig& config)
1141 {
1142 if (config.skipMeasure && config.skipLayout) {
1143 return false;
1144 }
1145 auto layoutAlgorithmWrapper = DynamicCast<LayoutAlgorithmWrapper>(dirty->GetLayoutAlgorithm());
1146 CHECK_NULL_RETURN(layoutAlgorithmWrapper, false);
1147 auto tabBarLayoutAlgorithm = DynamicCast<TabBarLayoutAlgorithm>(layoutAlgorithmWrapper->GetLayoutAlgorithm());
1148 CHECK_NULL_RETURN(tabBarLayoutAlgorithm, false);
1149 currentDelta_ = 0.0f;
1150 canOverScroll_ = false;
1151 visibleItemPosition_ = tabBarLayoutAlgorithm->GetVisibleItemPosition();
1152 scrollMargin_ = tabBarLayoutAlgorithm->GetScrollMargin();
1153 jumpIndex_ = tabBarLayoutAlgorithm->GetJumpIndex();
1154 auto layoutProperty = DynamicCast<TabBarLayoutProperty>(dirty->GetLayoutProperty());
1155 auto host = GetHost();
1156 CHECK_NULL_RETURN(host, false);
1157 auto swiperPattern = GetSwiperPattern();
1158 CHECK_NULL_RETURN(swiperPattern, false);
1159 int32_t indicator = swiperPattern->GetCurrentIndex();
1160 int32_t totalCount = swiperPattern->TotalCount();
1161 if (indicator > totalCount - 1 || indicator < 0) {
1162 indicator = 0;
1163 }
1164 if (totalCount == 0) {
1165 isTouchingSwiper_ = false;
1166 }
1167 auto pipelineContext = GetHost()->GetContext();
1168 CHECK_NULL_RETURN(pipelineContext, false);
1169 if (swiperPattern->IsUseCustomAnimation()) {
1170 UpdateSubTabBoard(indicator);
1171 UpdatePaintIndicator(indicator, false);
1172 }
1173
1174 if ((!swiperPattern->IsUseCustomAnimation() || isFirstLayout_) && !isAnimating_ && !IsMaskAnimationExecuted()) {
1175 UpdateSubTabBoard(indicator);
1176 UpdatePaintIndicator(indicator, true);
1177 }
1178 isFirstLayout_ = false;
1179
1180 if (targetIndex_) {
1181 TriggerTranslateAnimation(indicator_, targetIndex_.value());
1182 targetIndex_.reset();
1183 }
1184 indicator_ = layoutProperty->GetIndicatorValue(0);
1185
1186 if (windowSizeChangeReason_) {
1187 if (*windowSizeChangeReason_ == WindowSizeChangeReason::ROTATION &&
1188 animationTargetIndex_.value_or(indicator) != indicator) {
1189 swiperController_->SwipeToWithoutAnimation(animationTargetIndex_.value());
1190 animationTargetIndex_.reset();
1191 windowSizeChangeReason_.reset();
1192 } else if (prevRootSize_.first != PipelineContext::GetCurrentRootWidth() ||
1193 prevRootSize_.second != PipelineContext::GetCurrentRootHeight()) {
1194 StopTranslateAnimation();
1195 jumpIndex_ = indicator_;
1196 UpdateSubTabBoard(indicator_);
1197 UpdateIndicator(indicator_);
1198 windowSizeChangeReason_.reset();
1199 host->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1200 }
1201 }
1202 UpdateGradientRegions(!swiperPattern->IsUseCustomAnimation());
1203 if (!swiperPattern->IsUseCustomAnimation() && isTouchingSwiper_ &&
1204 layoutProperty->GetTabBarModeValue(TabBarMode::FIXED) == TabBarMode::SCROLLABLE) {
1205 ApplyTurnPageRateToIndicator(turnPageRate_);
1206 }
1207 return false;
1208 }
1209
InitLongPressAndDragEvent()1210 void TabBarPattern::InitLongPressAndDragEvent()
1211 {
1212 auto host = GetHost();
1213 CHECK_NULL_VOID(host);
1214 auto hub = host->GetEventHub<EventHub>();
1215 CHECK_NULL_VOID(hub);
1216 auto gestureHub = hub->GetOrCreateGestureEventHub();
1217 CHECK_NULL_VOID(gestureHub);
1218 auto pipelineContext = PipelineContext::GetCurrentContext();
1219 CHECK_NULL_VOID(pipelineContext);
1220 float scale = pipelineContext->GetFontScale();
1221
1222 bigScale_ = AgingAdapationDialogUtil::GetDialogBigFontSizeScale();
1223 largeScale_ = AgingAdapationDialogUtil::GetDialogLargeFontSizeScale();
1224 maxScale_ = AgingAdapationDialogUtil::GetDialogMaxFontSizeScale();
1225
1226 if (tabBarStyle_ == TabBarStyle::BOTTOMTABBATSTYLE && scale >= bigScale_) {
1227 InitLongPressEvent(gestureHub);
1228 InitDragEvent(gestureHub);
1229 } else {
1230 gestureHub->RemoveDragEvent();
1231 gestureHub->SetLongPressEvent(nullptr);
1232 longPressEvent_ = nullptr;
1233 dragEvent_ = nullptr;
1234 }
1235 }
1236
HandleLongPressEvent(const GestureEvent & info)1237 void TabBarPattern::HandleLongPressEvent(const GestureEvent& info)
1238 {
1239 auto index = CalculateSelectedIndex(info.GetLocalLocation());
1240 HandleClick(info.GetSourceDevice(), index);
1241 ShowDialogWithNode(index);
1242 }
1243
ShowDialogWithNode(int32_t index)1244 void TabBarPattern::ShowDialogWithNode(int32_t index)
1245 {
1246 auto tabBarNode = GetHost();
1247 CHECK_NULL_VOID(tabBarNode);
1248 auto columnNode = AceType::DynamicCast<FrameNode>(tabBarNode->GetChildAtIndex(index));
1249 CHECK_NULL_VOID(columnNode);
1250 RefPtr<FrameNode> imageNode = nullptr;
1251 RefPtr<FrameNode> textNode = nullptr;
1252 FindTextAndImageNode(columnNode, textNode, imageNode);
1253 CHECK_NULL_VOID(imageNode);
1254 CHECK_NULL_VOID(textNode);
1255
1256 auto textLayoutProperty = textNode->GetLayoutProperty<TextLayoutProperty>();
1257 CHECK_NULL_VOID(textLayoutProperty);
1258 auto textValue = textLayoutProperty->GetContent();
1259 if (imageNode->GetTag() == V2::SYMBOL_ETS_TAG) {
1260 auto symbolProperty = imageNode->GetLayoutProperty<TextLayoutProperty>();
1261 CHECK_NULL_VOID(symbolProperty);
1262 dialogNode_ =
1263 AgingAdapationDialogUtil::ShowLongPressDialog(textValue.value_or(""),
1264 symbolProperty->GetSymbolSourceInfoValue());
1265 } else {
1266 auto imageProperty = imageNode->GetLayoutProperty<ImageLayoutProperty>();
1267 CHECK_NULL_VOID(imageProperty);
1268 ImageSourceInfo imageSourceInfo = imageProperty->GetImageSourceInfoValue();
1269 dialogNode_ = AgingAdapationDialogUtil::ShowLongPressDialog(textValue.value_or(""), imageSourceInfo);
1270 }
1271 }
1272
CloseDialog()1273 void TabBarPattern::CloseDialog()
1274 {
1275 auto pipelineContext = PipelineContext::GetCurrentContext();
1276 CHECK_NULL_VOID(pipelineContext);
1277 auto context = AceType::DynamicCast<NG::PipelineContext>(pipelineContext);
1278 CHECK_NULL_VOID(context);
1279 auto overlayManager = context->GetOverlayManager();
1280 CHECK_NULL_VOID(overlayManager);
1281 overlayManager->CloseDialog(dialogNode_);
1282 dialogNode_.Reset();
1283 }
1284
HandleClick(SourceType type,int32_t index)1285 void TabBarPattern::HandleClick(SourceType type, int32_t index)
1286 {
1287 if (type == SourceType::KEYBOARD) {
1288 return;
1289 }
1290 auto host = GetHost();
1291 CHECK_NULL_VOID(host);
1292 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1293 CHECK_NULL_VOID(layoutProperty);
1294 if (layoutProperty->GetTabBarModeValue(TabBarMode::FIXED) == TabBarMode::SCROLLABLE && scrollableEvent_) {
1295 auto scrollable = scrollableEvent_->GetScrollable();
1296 if (scrollable) {
1297 if (IsOutOfBoundary()) {
1298 return;
1299 }
1300 scrollable->StopScrollable();
1301 }
1302 }
1303
1304 auto totalCount = host->TotalChildCount() - MASK_COUNT;
1305 if (totalCount < 0) {
1306 return;
1307 }
1308
1309 TAG_LOGI(AceLogTag::ACE_TABS, "Clicked tabBarIndex: %{public}d", index);
1310 if (index < 0 || index >= totalCount || !swiperController_ ||
1311 indicator_ >= static_cast<int32_t>(tabBarStyles_.size())) {
1312 return;
1313 }
1314 SetSwiperCurve(DurationCubicCurve);
1315
1316 TabBarClickEvent(index);
1317 if (!ContentWillChange(layoutProperty->GetIndicatorValue(0), index)) {
1318 return;
1319 }
1320 if (tabBarStyles_[indicator_] == TabBarStyle::SUBTABBATSTYLE &&
1321 tabBarStyles_[index] == TabBarStyle::SUBTABBATSTYLE &&
1322 layoutProperty->GetAxisValue(Axis::HORIZONTAL) == Axis::HORIZONTAL) {
1323 HandleSubTabBarClick(layoutProperty, index);
1324 return;
1325 }
1326 ClickTo(host, index);
1327 layoutProperty->UpdateIndicator(index);
1328 }
1329
ClickTo(const RefPtr<FrameNode> & host,int32_t index)1330 void TabBarPattern::ClickTo(const RefPtr<FrameNode>& host, int32_t index)
1331 {
1332 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
1333 CHECK_NULL_VOID(tabsNode);
1334 auto tabsPattern = tabsNode->GetPattern<TabsPattern>();
1335 CHECK_NULL_VOID(tabsPattern);
1336 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1337 CHECK_NULL_VOID(layoutProperty);
1338 int32_t indicator = layoutProperty->GetIndicatorValue(0);
1339 if (!tabsPattern->GetIsCustomAnimation() && indicator == index) {
1340 return;
1341 }
1342 swiperController_->FinishAnimation();
1343 UpdateAnimationDuration();
1344 auto duration = GetAnimationDuration().value_or(0);
1345 if (tabsPattern->GetIsCustomAnimation()) {
1346 OnCustomContentTransition(indicator, index);
1347 } else {
1348 if (duration > 0 && tabsPattern->GetAnimateMode() != TabAnimateMode::NO_ANIMATION) {
1349 PerfMonitor::GetPerfMonitor()->Start(PerfConstants::APP_TAB_SWITCH, PerfActionType::LAST_UP, "");
1350 tabContentWillChangeFlag_ = true;
1351 swiperController_->SwipeTo(index);
1352 animationTargetIndex_ = index;
1353 } else {
1354 swiperController_->SwipeToWithoutAnimation(index);
1355 }
1356 }
1357
1358 changeByClick_ = true;
1359 clickRepeat_ = true;
1360 if (duration > 0 && CanScroll()) {
1361 targetIndex_ = index;
1362 } else {
1363 jumpIndex_ = index;
1364 }
1365 host->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1366 }
1367
HandleBottomTabBarChange(int32_t index)1368 void TabBarPattern::HandleBottomTabBarChange(int32_t index)
1369 {
1370 AnimationUtils::StopAnimation(maskAnimation_);
1371 auto preIndex = GetImageColorOnIndex().value_or(indicator_);
1372 if (preIndex == index) {
1373 return;
1374 }
1375 UpdateImageColor(index);
1376 UpdateSymbolStats(index, preIndex);
1377 if (preIndex < 0 || preIndex >= static_cast<int32_t>(tabBarStyles_.size()) ||
1378 index < 0 || index >= static_cast<int32_t>(tabBarStyles_.size())) {
1379 return;
1380 }
1381 if (preIndex != index && (tabBarStyles_[preIndex] == TabBarStyle::BOTTOMTABBATSTYLE ||
1382 tabBarStyles_[index] == TabBarStyle::BOTTOMTABBATSTYLE)) {
1383 auto host = GetHost();
1384 CHECK_NULL_VOID(host);
1385 auto childCount = host->TotalChildCount() - MASK_COUNT;
1386 int32_t selectedIndex = -1;
1387 int32_t unselectedIndex = -1;
1388 if (preIndex < childCount && tabBarStyles_[preIndex] == TabBarStyle::BOTTOMTABBATSTYLE && CheckSvg(preIndex)) {
1389 unselectedIndex = preIndex;
1390 }
1391 if (index < childCount && tabBarStyles_[index] == TabBarStyle::BOTTOMTABBATSTYLE && CheckSvg(index)) {
1392 selectedIndex = index;
1393 }
1394 HandleBottomTabBarClick(selectedIndex, unselectedIndex);
1395 }
1396 }
1397
CheckSvg(int32_t index) const1398 bool TabBarPattern::CheckSvg(int32_t index) const
1399 {
1400 auto host = GetHost();
1401 CHECK_NULL_RETURN(host, false);
1402 auto columnNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(index));
1403 CHECK_NULL_RETURN(columnNode, false);
1404 auto imageNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
1405 CHECK_NULL_RETURN(imageNode, false);
1406 auto imageLayoutProperty = imageNode->GetLayoutProperty<ImageLayoutProperty>();
1407 CHECK_NULL_RETURN(imageLayoutProperty, false);
1408 ImageSourceInfo info;
1409 auto imageSourceInfo = imageLayoutProperty->GetImageSourceInfo().value_or(info);
1410 return imageSourceInfo.IsSvg();
1411 }
1412
HandleBottomTabBarClick(int32_t selectedIndex,int32_t unselectedIndex)1413 void TabBarPattern::HandleBottomTabBarClick(int32_t selectedIndex, int32_t unselectedIndex)
1414 {
1415 auto host = GetHost();
1416 CHECK_NULL_VOID(host);
1417 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1418 CHECK_NULL_VOID(layoutProperty);
1419
1420 std::vector<int32_t> selectedIndexes = {selectedIndex, unselectedIndex};
1421 OffsetF originalSelectedMaskOffset, originalUnselectedMaskOffset;
1422 float selectedImageSize = 0.0f, unselectedImageSize = 0.0f;
1423 for (int32_t maskIndex = 0; maskIndex < MASK_COUNT; maskIndex++) {
1424 if (maskIndex == 0) {
1425 layoutProperty->UpdateSelectedMask(selectedIndex);
1426 } else {
1427 layoutProperty->UpdateUnselectedMask(unselectedIndex);
1428 }
1429 if (selectedIndexes[maskIndex] < 0) {
1430 continue;
1431 }
1432 GetBottomTabBarImageSizeAndOffset(selectedIndexes, maskIndex, selectedImageSize, unselectedImageSize,
1433 originalSelectedMaskOffset, originalUnselectedMaskOffset);
1434 }
1435 ChangeMask(selectedIndex, selectedImageSize, originalSelectedMaskOffset, NO_OPACITY, HALF_MASK_RADIUS_RATIO, true);
1436 ChangeMask(unselectedIndex, unselectedImageSize, originalUnselectedMaskOffset, FULL_OPACITY,
1437 FULL_MASK_RADIUS_RATIO, false);
1438
1439 host->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1440 PlayMaskAnimation(selectedImageSize, originalSelectedMaskOffset, selectedIndex, unselectedImageSize,
1441 originalUnselectedMaskOffset, unselectedIndex);
1442 }
1443
GetBottomTabBarImageSizeAndOffset(const std::vector<int32_t> & selectedIndexes,int32_t maskIndex,float & selectedImageSize,float & unselectedImageSize,OffsetF & originalSelectedMaskOffset,OffsetF & originalUnselectedMaskOffset)1444 void TabBarPattern::GetBottomTabBarImageSizeAndOffset(const std::vector<int32_t>& selectedIndexes, int32_t maskIndex,
1445 float& selectedImageSize, float& unselectedImageSize, OffsetF& originalSelectedMaskOffset,
1446 OffsetF& originalUnselectedMaskOffset)
1447 {
1448 auto pipelineContext = PipelineContext::GetCurrentContext();
1449 CHECK_NULL_VOID(pipelineContext);
1450 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1451 CHECK_NULL_VOID(tabTheme);
1452
1453 auto host = GetHost();
1454 CHECK_NULL_VOID(host);
1455
1456 auto columnNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(selectedIndexes[maskIndex]));
1457 CHECK_NULL_VOID(columnNode);
1458 auto imageNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
1459 CHECK_NULL_VOID(imageNode);
1460 auto imageGeometryNode = imageNode->GetGeometryNode();
1461 CHECK_NULL_VOID(imageGeometryNode);
1462 auto imageOffset = imageGeometryNode->GetFrameOffset();
1463 auto imageSize = imageGeometryNode->GetFrameSize().Width();
1464 if (maskIndex == 0) {
1465 selectedImageSize = imageSize;
1466 } else {
1467 unselectedImageSize = imageSize;
1468 }
1469 auto imageLayoutProperty = imageNode->GetLayoutProperty<ImageLayoutProperty>();
1470 CHECK_NULL_VOID(imageLayoutProperty);
1471 ImageSourceInfo info;
1472 auto imageSourceInfo = imageLayoutProperty->GetImageSourceInfo().value_or(info);
1473
1474 auto maskPosition = host->GetChildren().size() - MASK_COUNT;
1475 if (maskPosition < 0) {
1476 return;
1477 }
1478 auto selectedMaskNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(maskPosition + maskIndex));
1479 CHECK_NULL_VOID(selectedMaskNode);
1480 selectedMaskNode->GetLayoutProperty()->UpdateLayoutDirection(TextDirection::LTR);
1481 if (maskIndex == 0) {
1482 originalSelectedMaskOffset = imageOffset;
1483 } else {
1484 originalUnselectedMaskOffset = imageOffset;
1485 }
1486 auto selectedImageNode = AceType::DynamicCast<FrameNode>(selectedMaskNode->GetChildren().front());
1487 CHECK_NULL_VOID(selectedImageNode);
1488
1489 auto selectedImageLayoutProperty = selectedImageNode->GetLayoutProperty<ImageLayoutProperty>();
1490 CHECK_NULL_VOID(selectedImageLayoutProperty);
1491 UpdateBottomTabBarImageColor(selectedIndexes, maskIndex);
1492 selectedImageLayoutProperty->UpdateImageSourceInfo(imageSourceInfo);
1493 imageLayoutProperty->UpdateImageSourceInfo(imageSourceInfo);
1494
1495 selectedImageNode->MarkModifyDone();
1496 selectedImageNode->MarkDirtyNode();
1497 imageNode->MarkModifyDone();
1498 imageNode->MarkDirtyNode();
1499 }
1500
UpdateBottomTabBarImageColor(const std::vector<int32_t> & selectedIndexes,int32_t maskIndex)1501 void TabBarPattern::UpdateBottomTabBarImageColor(const std::vector<int32_t>& selectedIndexes, int32_t maskIndex)
1502 {
1503 auto pipelineContext = PipelineContext::GetCurrentContext();
1504 CHECK_NULL_VOID(pipelineContext);
1505 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1506 CHECK_NULL_VOID(tabTheme);
1507
1508 auto host = GetHost();
1509 CHECK_NULL_VOID(host);
1510
1511 auto columnNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(selectedIndexes[maskIndex]));
1512 CHECK_NULL_VOID(columnNode);
1513 auto imageNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
1514 CHECK_NULL_VOID(imageNode);
1515
1516 auto maskPosition = host->GetChildren().size() - MASK_COUNT;
1517 if (maskPosition < 0) {
1518 return;
1519 }
1520 auto selectedMaskNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(maskPosition + maskIndex));
1521 CHECK_NULL_VOID(selectedMaskNode);
1522 auto selectedImageNode = AceType::DynamicCast<FrameNode>(selectedMaskNode->GetChildren().front());
1523 CHECK_NULL_VOID(selectedImageNode);
1524
1525 auto selectedImagePaintProperty = selectedImageNode->GetPaintProperty<ImageRenderProperty>();
1526 CHECK_NULL_VOID(selectedImagePaintProperty);
1527 auto unselectedImagePaintProperty = imageNode->GetPaintProperty<ImageRenderProperty>();
1528 CHECK_NULL_VOID(unselectedImagePaintProperty);
1529 if (selectedIndexes[maskIndex] >= 0 && selectedIndexes[maskIndex] < static_cast<int32_t>(iconStyles_.size())) {
1530 if (iconStyles_[selectedIndexes[maskIndex]].selectedColor.has_value()) {
1531 selectedImagePaintProperty->UpdateSvgFillColor(
1532 iconStyles_[selectedIndexes[maskIndex]].selectedColor.value());
1533 } else {
1534 selectedImagePaintProperty->UpdateSvgFillColor(tabTheme->GetBottomTabIconOn());
1535 }
1536
1537 if (iconStyles_[selectedIndexes[maskIndex]].unselectedColor.has_value()) {
1538 unselectedImagePaintProperty->UpdateSvgFillColor(
1539 iconStyles_[selectedIndexes[maskIndex]].unselectedColor.value());
1540 } else {
1541 unselectedImagePaintProperty->UpdateSvgFillColor(tabTheme->GetBottomTabIconOff());
1542 }
1543 }
1544 }
1545
PlayMaskAnimation(float selectedImageSize,const OffsetF & originalSelectedMaskOffset,int32_t selectedIndex,float unselectedImageSize,const OffsetF & originalUnselectedMaskOffset,int32_t unselectedIndex)1546 void TabBarPattern::PlayMaskAnimation(float selectedImageSize,
1547 const OffsetF& originalSelectedMaskOffset, int32_t selectedIndex, float unselectedImageSize,
1548 const OffsetF& originalUnselectedMaskOffset, int32_t unselectedIndex)
1549 {
1550 auto curve = AceType::MakeRefPtr<CubicCurve>(0.4f, 0.0f, 0.2f, 1.0f);
1551 AnimationOption option;
1552 option.SetDuration(MASK_ANIMATION_DURATION);
1553 option.SetCurve(curve);
1554
1555 maskAnimation_ = AnimationUtils::StartAnimation(
1556 option,
1557 [weak = AceType::WeakClaim(this), selectedIndex, unselectedIndex, selectedImageSize, originalSelectedMaskOffset,
1558 unselectedImageSize, originalUnselectedMaskOffset]() {
1559 AnimationUtils::AddKeyFrame(
1560 HALF_PROGRESS, [weak, selectedIndex, unselectedIndex, selectedImageSize, originalSelectedMaskOffset,
1561 unselectedImageSize, originalUnselectedMaskOffset]() {
1562 auto tabBar = weak.Upgrade();
1563 if (tabBar) {
1564 tabBar->ChangeMask(selectedIndex, selectedImageSize, originalSelectedMaskOffset, FULL_OPACITY,
1565 INVALID_RATIO, true);
1566 tabBar->ChangeMask(unselectedIndex, unselectedImageSize, originalUnselectedMaskOffset,
1567 NEAR_FULL_OPACITY, INVALID_RATIO, false);
1568 }
1569 });
1570 AnimationUtils::AddKeyFrame(
1571 FULL_PROGRESS, [weak, selectedIndex, unselectedIndex, selectedImageSize, originalSelectedMaskOffset,
1572 unselectedImageSize, originalUnselectedMaskOffset]() {
1573 auto tabBar = weak.Upgrade();
1574 if (tabBar) {
1575 tabBar->ChangeMask(selectedIndex, selectedImageSize, originalSelectedMaskOffset, FULL_OPACITY,
1576 FULL_MASK_RADIUS_RATIO, true);
1577 tabBar->ChangeMask(unselectedIndex, unselectedImageSize, originalUnselectedMaskOffset,
1578 NO_OPACITY, HALF_MASK_RADIUS_RATIO, false);
1579 }
1580 });
1581 },
1582 [weak = AceType::WeakClaim(this), selectedIndex, unselectedIndex]() {
1583 auto tabBar = weak.Upgrade();
1584 if (tabBar) {
1585 auto host = tabBar->GetHost();
1586 CHECK_NULL_VOID(host);
1587 MaskAnimationFinish(host, selectedIndex, true);
1588 MaskAnimationFinish(host, unselectedIndex, false);
1589 }
1590 });
1591 }
1592
MaskAnimationFinish(const RefPtr<FrameNode> & host,int32_t selectedIndex,bool isSelected)1593 void TabBarPattern::MaskAnimationFinish(const RefPtr<FrameNode>& host, int32_t selectedIndex,
1594 bool isSelected)
1595 {
1596 if (selectedIndex < 0) {
1597 return;
1598 }
1599 auto tabBarLayoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1600 CHECK_NULL_VOID(tabBarLayoutProperty);
1601 if (isSelected) {
1602 tabBarLayoutProperty->UpdateSelectedMask(-1);
1603 } else {
1604 tabBarLayoutProperty->UpdateUnselectedMask(-1);
1605 }
1606
1607 auto columnNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(selectedIndex));
1608 CHECK_NULL_VOID(columnNode);
1609 auto imageNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
1610 CHECK_NULL_VOID(imageNode);
1611
1612 auto imageLayoutProperty = imageNode->GetLayoutProperty<ImageLayoutProperty>();
1613 CHECK_NULL_VOID(imageLayoutProperty);
1614 auto imagePaintProperty = imageNode->GetPaintProperty<ImageRenderProperty>();
1615 CHECK_NULL_VOID(imagePaintProperty);
1616 ImageSourceInfo info;
1617 auto imageSourceInfo = imageLayoutProperty->GetImageSourceInfo().value_or(info);
1618
1619 auto pipelineContext = PipelineContext::GetCurrentContext();
1620 CHECK_NULL_VOID(pipelineContext);
1621 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1622 CHECK_NULL_VOID(tabTheme);
1623 auto tabBarPattern = host->GetPattern<TabBarPattern>();
1624 CHECK_NULL_VOID(tabBarPattern);
1625 auto iconStyles = tabBarPattern->GetIconStyle();
1626 if (selectedIndex >= 0 && selectedIndex < static_cast<int32_t>(iconStyles.size())) {
1627 if (isSelected) {
1628 if (iconStyles[selectedIndex].selectedColor.has_value()) {
1629 imagePaintProperty->UpdateSvgFillColor(iconStyles[selectedIndex].selectedColor.value());
1630 } else {
1631 imagePaintProperty->UpdateSvgFillColor(tabTheme->GetBottomTabIconOn());
1632 }
1633 } else {
1634 if (iconStyles[selectedIndex].unselectedColor.has_value()) {
1635 imagePaintProperty->UpdateSvgFillColor(iconStyles[selectedIndex].unselectedColor.value());
1636 } else {
1637 imagePaintProperty->UpdateSvgFillColor(tabTheme->GetBottomTabIconOff());
1638 }
1639 }
1640 }
1641 imageLayoutProperty->UpdateImageSourceInfo(imageSourceInfo);
1642
1643 host->MarkDirtyNode();
1644 imageNode->MarkModifyDone();
1645 imageNode->MarkDirtyNode();
1646 }
1647
ChangeMask(int32_t index,float imageSize,const OffsetF & originalMaskOffset,float opacity,float radiusRatio,bool isSelected)1648 void TabBarPattern::ChangeMask(int32_t index, float imageSize, const OffsetF& originalMaskOffset, float opacity,
1649 float radiusRatio, bool isSelected)
1650 {
1651 auto host = GetHost();
1652 CHECK_NULL_VOID(host);
1653 auto maskPosition = host->GetChildren().size() - MASK_COUNT;
1654 if (index < 0 || NearZero(imageSize) || maskPosition < 0) {
1655 return;
1656 }
1657
1658 auto maskNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(maskPosition + !isSelected));
1659 CHECK_NULL_VOID(maskNode);
1660 auto maskImageNode = AceType::DynamicCast<FrameNode>(maskNode->GetChildren().front());
1661 CHECK_NULL_VOID(maskImageNode);
1662 auto maskImageRenderContext = maskImageNode->GetRenderContext();
1663 CHECK_NULL_VOID(maskImageRenderContext);
1664
1665 if (NonNegative(radiusRatio)) {
1666 auto maskRenderContext = maskNode->GetRenderContext();
1667 CHECK_NULL_VOID(maskRenderContext);
1668 auto maskGeometryNode = maskNode->GetGeometryNode();
1669 CHECK_NULL_VOID(maskGeometryNode);
1670 auto tabBarNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(index));
1671 CHECK_NULL_VOID(tabBarNode);
1672 auto tabBarGeometryNode = tabBarNode->GetGeometryNode();
1673 CHECK_NULL_VOID(tabBarGeometryNode);
1674
1675 OffsetF maskOffset = originalMaskOffset;
1676 maskOffset.AddX(-imageSize * radiusRatio);
1677 maskOffset.AddY(imageSize * (1.0f - radiusRatio));
1678 auto tabBarOffset = tabBarGeometryNode->GetMarginFrameOffset();
1679 maskGeometryNode->SetMarginFrameOffset(maskOffset + tabBarOffset);
1680 maskGeometryNode->SetFrameSize(SizeF(imageSize * radiusRatio * 2.0f, imageSize * radiusRatio * 2.0f));
1681 maskRenderContext->SavePaintRect();
1682 maskRenderContext->SyncGeometryProperties(nullptr);
1683 BorderRadiusProperty borderRadiusProperty;
1684 borderRadiusProperty.SetRadius(Dimension(imageSize * radiusRatio));
1685 maskRenderContext->UpdateBorderRadius(borderRadiusProperty);
1686 maskImageRenderContext->UpdateOffset(OffsetT<Dimension>(Dimension(imageSize * radiusRatio),
1687 Dimension(imageSize * (radiusRatio - 1.0f))));
1688 auto maskImageGeometryNode = maskImageNode->GetGeometryNode();
1689 CHECK_NULL_VOID(maskImageGeometryNode);
1690 maskImageGeometryNode->SetFrameSize(SizeF(imageSize, imageSize));
1691 auto maskImageProperty = maskImageNode->GetLayoutProperty<ImageLayoutProperty>();
1692 CHECK_NULL_VOID(maskImageProperty);
1693 maskImageProperty->UpdateUserDefinedIdealSize(
1694 CalcSize(NG::CalcLength(Dimension(imageSize)), NG::CalcLength(Dimension(imageSize))));
1695 maskImageRenderContext->SetVisible(false);
1696 maskImageRenderContext->SavePaintRect();
1697 maskImageRenderContext->SyncGeometryProperties(nullptr);
1698 }
1699 maskImageRenderContext->UpdateOpacity(opacity);
1700 }
1701
HandleSubTabBarClick(const RefPtr<TabBarLayoutProperty> & layoutProperty,int32_t index)1702 void TabBarPattern::HandleSubTabBarClick(const RefPtr<TabBarLayoutProperty>& layoutProperty, int32_t index)
1703 {
1704 auto host = GetHost();
1705 CHECK_NULL_VOID(host);
1706 auto tabsFrameNode = AceType::DynamicCast<TabsNode>(host->GetParent());
1707 CHECK_NULL_VOID(tabsFrameNode);
1708 auto tabsPattern = tabsFrameNode->GetPattern<TabsPattern>();
1709 CHECK_NULL_VOID(tabsPattern);
1710 int32_t indicator = layoutProperty->GetIndicatorValue(0);
1711 if (!tabsPattern->GetIsCustomAnimation() && indicator == index) {
1712 return;
1713 }
1714 swiperController_->FinishAnimation();
1715 changeByClick_ = true;
1716 clickRepeat_ = true;
1717 UpdateAnimationDuration();
1718 auto duration = GetAnimationDuration().value_or(0);
1719 if (tabsPattern->GetIsCustomAnimation()) {
1720 OnCustomContentTransition(indicator, index);
1721 } else {
1722 if (duration> 0 && tabsPattern->GetAnimateMode() != TabAnimateMode::NO_ANIMATION) {
1723 PerfMonitor::GetPerfMonitor()->Start(PerfConstants::APP_TAB_SWITCH, PerfActionType::LAST_UP, "");
1724 tabContentWillChangeFlag_ = true;
1725 swiperController_->SwipeTo(index);
1726 } else {
1727 swiperController_->SwipeToWithoutAnimation(index);
1728 }
1729 }
1730 if (duration > 0 && CanScroll()) {
1731 targetIndex_ = index;
1732 } else if (duration <= 0) {
1733 jumpIndex_ = index;
1734 } else {
1735 TriggerTranslateAnimation(indicator, index);
1736 }
1737 swiperStartIndex_ = indicator;
1738 animationTargetIndex_ = index;
1739 UpdateTextColorAndFontWeight(index);
1740 UpdateSubTabBoard(index);
1741 layoutProperty->UpdateIndicator(index);
1742 host->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1743 }
1744
HandleTouchEvent(const TouchLocationInfo & info)1745 void TabBarPattern::HandleTouchEvent(const TouchLocationInfo& info)
1746 {
1747 auto host = GetHost();
1748 CHECK_NULL_VOID(host);
1749 auto touchType = info.GetTouchType();
1750 auto index = CalculateSelectedIndex(info.GetLocalLocation());
1751 if ((touchType == TouchType::UP || touchType == TouchType::CANCEL) && dialogNode_) {
1752 HandleClick(info.GetSourceDevice(), index);
1753 CloseDialog();
1754 }
1755
1756 if (IsContainsBuilder()) {
1757 return;
1758 }
1759
1760 auto totalCount = host->TotalChildCount() - MASK_COUNT;
1761 if (totalCount < 0) {
1762 return;
1763 }
1764
1765 if (touchType == TouchType::DOWN && index >= 0 && index < totalCount) {
1766 HandleTouchDown(index);
1767 touchingIndex_ = index;
1768 return;
1769 }
1770
1771 if ((touchType == TouchType::UP || touchType == TouchType::CANCEL) && touchingIndex_.has_value()) {
1772 HandleTouchUp(index);
1773 touchingIndex_.reset();
1774 }
1775 }
1776
CalculateSelectedIndex(const Offset & info)1777 int32_t TabBarPattern::CalculateSelectedIndex(const Offset& info)
1778 {
1779 if (visibleItemPosition_.empty()) {
1780 return -1;
1781 }
1782 auto host = GetHost();
1783 CHECK_NULL_RETURN(host, -1);
1784 auto geometryNode = host->GetGeometryNode();
1785 CHECK_NULL_RETURN(geometryNode, -1);
1786 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
1787 CHECK_NULL_RETURN(layoutProperty, -1);
1788 auto axis = layoutProperty->GetAxis().value_or(Axis::HORIZONTAL);
1789 auto mainSize = geometryNode->GetFrameSize().MainSize(axis);
1790 auto local = isRTL_ && axis == Axis::HORIZONTAL ? OffsetF(mainSize - info.GetX(), info.GetY())
1791 : OffsetF(info.GetX(), info.GetY());
1792 auto leftPadding = GetLeftPadding();
1793 for (auto& iter : visibleItemPosition_) {
1794 if (GreatOrEqual(local.GetMainOffset(axis), iter.second.startPos + leftPadding) &&
1795 LessOrEqual(local.GetMainOffset(axis), iter.second.endPos + leftPadding)) {
1796 return iter.first;
1797 }
1798 }
1799 return -1;
1800 }
1801
HandleTouchDown(int32_t index)1802 void TabBarPattern::HandleTouchDown(int32_t index)
1803 {
1804 const auto& removeSwiperEventCallback = swiperController_->GetRemoveSwiperEventCallback();
1805 if (removeSwiperEventCallback) {
1806 removeSwiperEventCallback();
1807 }
1808 SetTouching(true);
1809 auto pipelineContext = PipelineContext::GetCurrentContext();
1810 CHECK_NULL_VOID(pipelineContext);
1811 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1812 CHECK_NULL_VOID(tabTheme);
1813 PlayPressAnimation(index, tabTheme->GetSubTabBarPressedColor(), AnimationType::PRESS);
1814 }
1815
HandleTouchUp(int32_t index)1816 void TabBarPattern::HandleTouchUp(int32_t index)
1817 {
1818 const auto& addSwiperEventCallback = swiperController_->GetAddSwiperEventCallback();
1819 if (addSwiperEventCallback) {
1820 addSwiperEventCallback();
1821 }
1822 auto pipelineContext = PipelineContext::GetCurrentContext();
1823 CHECK_NULL_VOID(pipelineContext);
1824 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1825 CHECK_NULL_VOID(tabTheme);
1826 if (IsTouching()) {
1827 SetTouching(false);
1828 if (hoverIndex_.has_value() && touchingIndex_.value_or(-1) == index) {
1829 PlayPressAnimation(index, tabTheme->GetSubTabBarHoverColor(), AnimationType::HOVERTOPRESS);
1830 return;
1831 }
1832 PlayPressAnimation(touchingIndex_.value_or(-1), Color::TRANSPARENT, AnimationType::PRESS);
1833 if (hoverIndex_.has_value()) {
1834 PlayPressAnimation(hoverIndex_.value(), tabTheme->GetSubTabBarHoverColor(), AnimationType::HOVER);
1835 }
1836 }
1837 }
1838
PlayPressAnimation(int32_t index,const Color & pressColor,AnimationType animationType)1839 void TabBarPattern::PlayPressAnimation(int32_t index, const Color& pressColor, AnimationType animationType)
1840 {
1841 if (Container::GreatOrEqualAPIVersion(PlatformVersion::VERSION_TWELVE) &&
1842 tabBarStyle_ == TabBarStyle::BOTTOMTABBATSTYLE) {
1843 return;
1844 }
1845 auto pipelineContext = PipelineContext::GetCurrentContext();
1846 CHECK_NULL_VOID(pipelineContext);
1847 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1848 CHECK_NULL_VOID(tabTheme);
1849 AnimationOption option = AnimationOption();
1850 option.SetDuration(animationType == AnimationType::HOVERTOPRESS
1851 ? static_cast<int32_t>(tabTheme->GetSubTabBarHoverToPressDuration())
1852 : static_cast<int32_t>(tabTheme->GetSubTabBarHoverDuration()));
1853 option.SetDelay(0);
1854 option.SetCurve(animationType == AnimationType::PRESS ? DurationCubicCurve
1855 : animationType == AnimationType::HOVER ? Curves::FRICTION
1856 : Curves::SHARP);
1857 option.SetFillMode(FillMode::FORWARDS);
1858 Color color = pressColor;
1859 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
1860 CHECK_NULL_VOID(layoutProperty);
1861 auto totalCount = GetHost()->TotalChildCount() - MASK_COUNT;
1862 if (index < 0 || index >= totalCount || index >= static_cast<int32_t>(tabBarStyles_.size())) {
1863 return;
1864 }
1865 if (color == Color::TRANSPARENT && tabBarStyles_[index] == TabBarStyle::SUBTABBATSTYLE && index == indicator_ &&
1866 selectedModes_[index] == SelectedMode::BOARD &&
1867 layoutProperty->GetAxis().value_or(Axis::HORIZONTAL) == Axis::HORIZONTAL) {
1868 color = indicatorStyles_[index].color;
1869 }
1870 AnimationUtils::Animate(option, [weak = AceType::WeakClaim(this), selectedIndex = index, color = color]() {
1871 auto tabBar = weak.Upgrade();
1872 if (tabBar) {
1873 auto host = tabBar->GetHost();
1874 CHECK_NULL_VOID(host);
1875 auto columnNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(selectedIndex));
1876 CHECK_NULL_VOID(columnNode);
1877 auto renderContext = columnNode->GetRenderContext();
1878 CHECK_NULL_VOID(renderContext);
1879 if (tabBar->tabBarStyles_[selectedIndex] != TabBarStyle::SUBTABBATSTYLE) {
1880 BorderRadiusProperty borderRadiusProperty;
1881 auto pipelineContext = PipelineContext::GetCurrentContext();
1882 CHECK_NULL_VOID(pipelineContext);
1883 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
1884 CHECK_NULL_VOID(tabTheme);
1885 borderRadiusProperty.SetRadius(tabTheme->GetFocusIndicatorRadius());
1886 renderContext->UpdateBorderRadius(borderRadiusProperty);
1887 }
1888 renderContext->UpdateBackgroundColor(color);
1889 columnNode->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
1890 }
1891 }, [weak = AceType::WeakClaim(this), selectedIndex = index]() {
1892 auto tabBar = weak.Upgrade();
1893 if (tabBar) {
1894 if (tabBar->tabBarStyles_[selectedIndex] != TabBarStyle::SUBTABBATSTYLE) {
1895 auto host = tabBar->GetHost();
1896 CHECK_NULL_VOID(host);
1897 auto columnNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(selectedIndex));
1898 CHECK_NULL_VOID(columnNode);
1899 auto renderContext = columnNode->GetRenderContext();
1900 CHECK_NULL_VOID(renderContext);
1901 renderContext->ResetBorderRadius();
1902 columnNode->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
1903 }
1904 }
1905 });
1906 }
1907
OnTabBarIndexChange(int32_t index)1908 void TabBarPattern::OnTabBarIndexChange(int32_t index)
1909 {
1910 auto pipeline = PipelineContext::GetCurrentContext();
1911 CHECK_NULL_VOID(pipeline);
1912 pipeline->AddAfterRenderTask([weak = WeakClaim(this), index]() {
1913 auto tabBarPattern = weak.Upgrade();
1914 CHECK_NULL_VOID(tabBarPattern);
1915 auto tabBarNode = tabBarPattern->GetHost();
1916 CHECK_NULL_VOID(tabBarNode);
1917 auto tabBarLayoutProperty = tabBarPattern->GetLayoutProperty<TabBarLayoutProperty>();
1918 CHECK_NULL_VOID(tabBarLayoutProperty);
1919 if (!tabBarPattern->IsMaskAnimationByCreate()) {
1920 tabBarPattern->HandleBottomTabBarChange(index);
1921 }
1922 tabBarPattern->SetMaskAnimationByCreate(false);
1923 tabBarPattern->SetIndicator(index);
1924 tabBarPattern->UpdateSubTabBoard(index);
1925 tabBarPattern->UpdatePaintIndicator(index, true);
1926 tabBarPattern->UpdateTextColorAndFontWeight(index);
1927 tabBarPattern->StartShowTabBar();
1928 if (!tabBarPattern->GetClickRepeat() || tabBarLayoutProperty->GetIndicator().value_or(0) == index) {
1929 tabBarPattern->ResetIndicatorAnimationState();
1930 tabBarLayoutProperty->UpdateIndicator(index);
1931 }
1932 tabBarPattern->isTouchingSwiper_ = false;
1933 tabBarPattern->SetClickRepeat(false);
1934 if (tabBarPattern->GetChangeByClick()) {
1935 tabBarPattern->SetChangeByClick(false);
1936 return;
1937 }
1938 if (tabBarLayoutProperty->GetTabBarMode().value_or(TabBarMode::FIXED) == TabBarMode::SCROLLABLE) {
1939 tabBarPattern->UpdateAnimationDuration();
1940 auto duration = tabBarPattern->GetAnimationDuration().value_or(0);
1941 if (duration > 0 && tabBarPattern->CanScroll()) {
1942 tabBarPattern->StopTranslateAnimation();
1943 tabBarPattern->targetIndex_ = index;
1944 tabBarNode->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1945 } else {
1946 tabBarPattern->StopTranslateAnimation();
1947 tabBarPattern->jumpIndex_ = index;
1948 tabBarNode->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1949 }
1950 }
1951 });
1952 pipeline->RequestFrame();
1953 }
1954
UpdateCurrentOffset(float offset)1955 void TabBarPattern::UpdateCurrentOffset(float offset)
1956 {
1957 if (NearZero(offset)) {
1958 return;
1959 }
1960 auto host = GetHost();
1961 CHECK_NULL_VOID(host);
1962 currentDelta_ = offset;
1963 UpdateSubTabBoard(indicator_);
1964 UpdateIndicator(indicator_);
1965 host->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
1966 }
1967
UpdateIndicator(int32_t indicator)1968 void TabBarPattern::UpdateIndicator(int32_t indicator)
1969 {
1970 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
1971 CHECK_NULL_VOID(layoutProperty);
1972 layoutProperty->UpdateIndicator(indicator);
1973 clickRepeat_ = false;
1974
1975 UpdatePaintIndicator(indicator, true);
1976 }
1977
UpdateGradientRegions(bool needMarkDirty)1978 void TabBarPattern::UpdateGradientRegions(bool needMarkDirty)
1979 {
1980 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
1981 CHECK_NULL_VOID(layoutProperty);
1982 auto barMode = layoutProperty->GetTabBarMode().value_or(TabBarMode::FIXED);
1983 auto axis = layoutProperty->GetAxis().value_or(Axis::HORIZONTAL);
1984 auto tabBarNode = GetHost();
1985 CHECK_NULL_VOID(tabBarNode);
1986 auto childCount = tabBarNode->TotalChildCount() - MASK_COUNT;
1987 auto geometryNode = tabBarNode->GetGeometryNode();
1988 CHECK_NULL_VOID(geometryNode);
1989 auto mainSize = geometryNode->GetPaddingSize().MainSize(axis);
1990
1991 std::fill(gradientRegions_.begin(), gradientRegions_.end(), false);
1992 if (barMode == TabBarMode::SCROLLABLE && !visibleItemPosition_.empty()) {
1993 auto visibleItemStartIndex = visibleItemPosition_.begin()->first;
1994 auto visibleItemEndIndex = visibleItemPosition_.rbegin()->first;
1995 auto visibleItemStartPos = visibleItemPosition_.begin()->second.startPos;
1996 auto visibleItemEndPos = visibleItemPosition_.rbegin()->second.endPos;
1997 if (visibleItemStartIndex > 0 || LessNotEqual(visibleItemStartPos, scrollMargin_)) {
1998 auto gradientIndex = axis == Axis::HORIZONTAL ? (isRTL_ ? RIGHT_GRADIENT : LEFT_GRADIENT)
1999 : TOP_GRADIENT;
2000 gradientRegions_[gradientIndex] = true;
2001 }
2002 if (visibleItemEndIndex < childCount - 1 || GreatNotEqual(visibleItemEndPos + scrollMargin_, mainSize)) {
2003 auto gradientIndex = axis == Axis::HORIZONTAL ? (isRTL_ ? LEFT_GRADIENT : RIGHT_GRADIENT)
2004 : BOTTOM_GRADIENT;
2005 gradientRegions_[gradientIndex] = true;
2006 }
2007 }
2008
2009 if (needMarkDirty) {
2010 tabBarNode->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
2011 }
2012 }
2013
UpdateTextColorAndFontWeight(int32_t indicator)2014 void TabBarPattern::UpdateTextColorAndFontWeight(int32_t indicator)
2015 {
2016 auto tabBarNode = GetHost();
2017 CHECK_NULL_VOID(tabBarNode);
2018 auto columnNode = DynamicCast<FrameNode>(tabBarNode->GetChildAtIndex(indicator));
2019 CHECK_NULL_VOID(columnNode);
2020 auto selectedColumnId = columnNode->GetId();
2021 auto pipelineContext = PipelineContext::GetCurrentContext();
2022 CHECK_NULL_VOID(pipelineContext);
2023 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
2024 CHECK_NULL_VOID(tabTheme);
2025 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
2026 CHECK_NULL_VOID(tabBarLayoutProperty);
2027 auto axis = tabBarLayoutProperty->GetAxis().value_or(Axis::HORIZONTAL);
2028 int32_t index = 0;
2029 for (const auto& columnNode : tabBarNode->GetChildren()) {
2030 CHECK_NULL_VOID(columnNode);
2031 auto columnId = columnNode->GetId();
2032 auto iter = tabBarType_.find(columnId);
2033 if (iter != tabBarType_.end() && iter->second) {
2034 index++;
2035 continue;
2036 }
2037 if (labelStyles_.find(columnId) == labelStyles_.end()) {
2038 index++;
2039 continue;
2040 }
2041 auto textNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().back());
2042 CHECK_NULL_VOID(textNode);
2043 auto textLayoutProperty = textNode->GetLayoutProperty<TextLayoutProperty>();
2044 CHECK_NULL_VOID(textLayoutProperty);
2045 auto isSelected = columnId == selectedColumnId;
2046 if (isSelected) {
2047 auto selectedColor = index < static_cast<int32_t>(selectedModes_.size()) &&
2048 selectedModes_[index] == SelectedMode::BOARD && axis == Axis::HORIZONTAL
2049 ? tabTheme->GetSubTabBoardTextOnColor()
2050 : tabTheme->GetSubTabTextOnColor();
2051 textLayoutProperty->UpdateTextColor(labelStyles_[columnId].selectedColor.value_or(selectedColor));
2052 } else {
2053 textLayoutProperty->UpdateTextColor(
2054 labelStyles_[columnId].unselectedColor.value_or(tabTheme->GetSubTabTextOffColor()));
2055 }
2056 if (index < static_cast<int32_t>(tabBarStyles_.size()) && tabBarStyles_[index] != TabBarStyle::SUBTABBATSTYLE &&
2057 !labelStyles_[columnId].fontWeight.has_value()) {
2058 textLayoutProperty->UpdateFontWeight(isSelected ? FontWeight::MEDIUM : FontWeight::NORMAL);
2059 }
2060 textNode->MarkModifyDone();
2061 textNode->MarkDirtyNode();
2062 index++;
2063 }
2064 }
2065
UpdateImageColor(int32_t indicator)2066 void TabBarPattern::UpdateImageColor(int32_t indicator)
2067 {
2068 auto tabBarNode = GetHost();
2069 CHECK_NULL_VOID(tabBarNode);
2070 auto tabBarPattern = tabBarNode->GetPattern<TabBarPattern>();
2071 CHECK_NULL_VOID(tabBarPattern);
2072 if (tabBarPattern->IsContainsBuilder()) {
2073 return;
2074 }
2075 auto pipelineContext = PipelineContext::GetCurrentContext();
2076 CHECK_NULL_VOID(pipelineContext);
2077 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
2078 CHECK_NULL_VOID(tabTheme);
2079 int32_t index = 0;
2080 for (const auto& columnNode : tabBarNode->GetChildren()) {
2081 CHECK_NULL_VOID(columnNode);
2082 auto imageNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
2083 CHECK_NULL_VOID(imageNode);
2084 if (imageNode->GetTag() != V2::IMAGE_ETS_TAG) {
2085 index++;
2086 continue;
2087 }
2088 auto imageLayoutProperty = imageNode->GetLayoutProperty<ImageLayoutProperty>();
2089 CHECK_NULL_VOID(imageLayoutProperty);
2090 auto imagePaintProperty = imageNode->GetPaintProperty<ImageRenderProperty>();
2091 CHECK_NULL_VOID(imagePaintProperty);
2092 ImageSourceInfo info;
2093 auto imageSourceInfo = imageLayoutProperty->GetImageSourceInfo().value_or(info);
2094 if (index >= 0 && index < static_cast<int32_t>(iconStyles_.size())) {
2095 if (indicator == index) {
2096 imagePaintProperty->UpdateSvgFillColor(iconStyles_[index].selectedColor.has_value() ?
2097 iconStyles_[index].selectedColor.value() : tabTheme->GetBottomTabIconOn());
2098 } else {
2099 imagePaintProperty->UpdateSvgFillColor(iconStyles_[index].unselectedColor.has_value() ?
2100 iconStyles_[index].unselectedColor.value() : tabTheme->GetBottomTabIconOff());
2101 }
2102 }
2103 imageLayoutProperty->UpdateImageSourceInfo(imageSourceInfo);
2104 imageNode->MarkModifyDone();
2105 imageNode->MarkDirtyNode();
2106 index++;
2107 }
2108 SetImageColorOnIndex(indicator);
2109 }
2110
UpdateSymbolStats(int32_t index,int32_t preIndex)2111 void TabBarPattern::UpdateSymbolStats(int32_t index, int32_t preIndex)
2112 {
2113 auto tabBarNode = GetHost();
2114 CHECK_NULL_VOID(tabBarNode);
2115 auto tabBarPattern = tabBarNode->GetPattern<TabBarPattern>();
2116 CHECK_NULL_VOID(tabBarPattern);
2117 auto pipelineContext = PipelineContext::GetCurrentContext();
2118 CHECK_NULL_VOID(pipelineContext);
2119 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
2120 CHECK_NULL_VOID(tabTheme);
2121 if (tabBarPattern->IsContainsBuilder()) {
2122 return;
2123 }
2124 std::vector<int32_t> indexes = {index, preIndex};
2125 for (uint32_t i = 0; i < indexes.size(); i++) {
2126 if (indexes[i] < 0 || indexes[i] >= static_cast<int32_t>(symbolArray_.size())) {
2127 continue;
2128 }
2129 auto columnNode = DynamicCast<FrameNode>(tabBarNode->GetChildAtIndex(indexes[i]));
2130 CHECK_NULL_VOID(columnNode);
2131 auto symbolNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
2132 CHECK_NULL_VOID(symbolNode);
2133 if (symbolNode->GetTag() != V2::SYMBOL_ETS_TAG) {
2134 continue;
2135 }
2136 auto symbolLayoutProperty = symbolNode->GetLayoutProperty<TextLayoutProperty>();
2137 CHECK_NULL_VOID(symbolLayoutProperty);
2138 TabContentModelNG::UpdateDefaultSymbol(tabTheme, symbolLayoutProperty);
2139 if (i == 0) {
2140 symbolLayoutProperty->UpdateSymbolColorList({tabTheme->GetBottomTabSymbolOn()});
2141 auto modifierOnApply = symbolArray_[indexes[i]].onApply;
2142 UpdateSymbolApply(symbolNode, symbolLayoutProperty, indexes[i], "selected");
2143 if (preIndex != -1) {
2144 TabContentModelNG::UpdateSymbolEffect(symbolLayoutProperty, true);
2145 }
2146 } else {
2147 symbolLayoutProperty->UpdateSymbolColorList({tabTheme->GetBottomTabSymbolOff()});
2148 UpdateSymbolApply(symbolNode, symbolLayoutProperty, indexes[i], "normal");
2149 }
2150 symbolNode->MarkModifyDone();
2151 symbolNode->MarkDirtyNode();
2152 }
2153 }
2154
UpdateSymbolApply(const RefPtr<NG::FrameNode> & symbolNode,RefPtr<TextLayoutProperty> & symbolProperty,int32_t index,std::string type)2155 void TabBarPattern::UpdateSymbolApply(const RefPtr<NG::FrameNode>& symbolNode,
2156 RefPtr<TextLayoutProperty>& symbolProperty, int32_t index, std::string type)
2157 {
2158 auto modifierOnApply = symbolArray_[index].onApply;
2159 if (type == "selected" && !symbolArray_[index].selectedFlag) {
2160 return;
2161 }
2162 if (modifierOnApply != nullptr) {
2163 modifierOnApply(AccessibilityManager::WeakClaim(AccessibilityManager::RawPtr(symbolNode)), type);
2164 TabContentModelNG::UpdateSymbolEffect(symbolProperty, false);
2165 }
2166 }
2167
UpdateSymbolEffect(int32_t index)2168 void TabBarPattern::UpdateSymbolEffect(int32_t index)
2169 {
2170 if (index != GetImageColorOnIndex().value_or(indicator_)) {
2171 return;
2172 }
2173 auto tabBarNode = GetHost();
2174 CHECK_NULL_VOID(tabBarNode);
2175 auto columnNode = DynamicCast<FrameNode>(tabBarNode->GetChildAtIndex(index));
2176 CHECK_NULL_VOID(columnNode);
2177 auto symbolNode = AceType::DynamicCast<FrameNode>(columnNode->GetChildren().front());
2178 CHECK_NULL_VOID(symbolNode);
2179 if (symbolNode->GetTag() == V2::SYMBOL_ETS_TAG) {
2180 auto symbolLayoutProperty = symbolNode->GetLayoutProperty<TextLayoutProperty>();
2181 CHECK_NULL_VOID(symbolLayoutProperty);
2182 auto symbolEffectOptions = symbolLayoutProperty->GetSymbolEffectOptionsValue(SymbolEffectOptions());
2183 symbolEffectOptions.SetIsTxtActive(false);
2184 symbolLayoutProperty->UpdateSymbolEffectOptions(symbolEffectOptions);
2185 }
2186 }
2187
UpdateSubTabBoard(int32_t index)2188 void TabBarPattern::UpdateSubTabBoard(int32_t index)
2189 {
2190 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
2191 CHECK_NULL_VOID(layoutProperty);
2192 auto axis = layoutProperty->GetAxis().value_or(Axis::HORIZONTAL);
2193
2194 if (index >= static_cast<int32_t>(indicatorStyles_.size()) ||
2195 index >= static_cast<int32_t>(selectedModes_.size())) {
2196 return;
2197 }
2198 auto tabBarNode = GetHost();
2199 CHECK_NULL_VOID(tabBarNode);
2200 auto paintProperty = GetPaintProperty<TabBarPaintProperty>();
2201 CHECK_NULL_VOID(paintProperty);
2202 auto columnNode = DynamicCast<FrameNode>(tabBarNode->GetChildAtIndex(index));
2203 CHECK_NULL_VOID(columnNode);
2204 auto selectedColumnId = columnNode->GetId();
2205 auto pipelineContext = GetHost()->GetContext();
2206 CHECK_NULL_VOID(pipelineContext);
2207 for (auto& iter : visibleItemPosition_) {
2208 if (iter.first < 0 || iter.first >= static_cast<int32_t>(tabBarStyles_.size())) {
2209 break;
2210 }
2211 auto columnFrameNode = AceType::DynamicCast<FrameNode>(tabBarNode->GetChildAtIndex(iter.first));
2212 CHECK_NULL_VOID(columnFrameNode);
2213 auto renderContext = columnFrameNode->GetRenderContext();
2214 CHECK_NULL_VOID(renderContext);
2215 if (tabBarStyles_[iter.first] == TabBarStyle::SUBTABBATSTYLE) {
2216 if (selectedModes_[index] == SelectedMode::BOARD && columnFrameNode->GetId() == selectedColumnId &&
2217 axis == Axis::HORIZONTAL) {
2218 renderContext->UpdateBackgroundColor(indicatorStyles_[index].color);
2219 } else {
2220 renderContext->UpdateBackgroundColor(Color::BLACK.BlendOpacity(0.0f));
2221 }
2222 columnFrameNode->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
2223 }
2224 }
2225 }
2226
GetSelectedMode() const2227 SelectedMode TabBarPattern::GetSelectedMode() const
2228 {
2229 if (indicator_ >= static_cast<int32_t>(selectedModes_.size())) {
2230 return SelectedMode::INDICATOR;
2231 } else {
2232 return selectedModes_[indicator_];
2233 }
2234 }
2235
IsContainsBuilder()2236 bool TabBarPattern::IsContainsBuilder()
2237 {
2238 return std::any_of(tabBarType_.begin(), tabBarType_.end(), [](const auto& isBuilder) { return isBuilder.second; });
2239 }
2240
PlayTabBarTranslateAnimation(AnimationOption option,float targetCurrentOffset)2241 void TabBarPattern::PlayTabBarTranslateAnimation(AnimationOption option, float targetCurrentOffset)
2242 {
2243 auto weak = AceType::WeakClaim(this);
2244 const auto& pattern = weak.Upgrade();
2245 auto host = pattern->GetHost();
2246
2247 currentOffset_ = 0.0f;
2248 host->CreateAnimatablePropertyFloat(TAB_BAR_PROPERTY_NAME, 0, [weak](float value) {
2249 auto tabBarPattern = weak.Upgrade();
2250 CHECK_NULL_VOID(tabBarPattern);
2251 tabBarPattern->currentDelta_ = value - tabBarPattern->currentOffset_;
2252 tabBarPattern->currentOffset_ = value;
2253 auto host = tabBarPattern->GetHost();
2254 host->MarkDirtyNode(PROPERTY_UPDATE_LAYOUT);
2255 });
2256 host->UpdateAnimatablePropertyFloat(TAB_BAR_PROPERTY_NAME, currentOffset_);
2257 translateAnimationIsRunning_ = true;
2258 translateAnimation_ = AnimationUtils::StartAnimation(option,
2259 [host, targetCurrentOffset]() {
2260 host->UpdateAnimatablePropertyFloat(TAB_BAR_PROPERTY_NAME, targetCurrentOffset);
2261 },
2262 [weak]() {
2263 auto tabBarPattern = weak.Upgrade();
2264 CHECK_NULL_VOID(tabBarPattern);
2265 tabBarPattern->translateAnimationIsRunning_ = false;
2266 });
2267 }
2268
PlayIndicatorTranslateAnimation(AnimationOption option,RectF originalPaintRect,RectF targetPaintRect,float targetOffset)2269 void TabBarPattern::PlayIndicatorTranslateAnimation(AnimationOption option, RectF originalPaintRect,
2270 RectF targetPaintRect, float targetOffset)
2271 {
2272 auto weak = AceType::WeakClaim(this);
2273 const auto& pattern = weak.Upgrade();
2274 auto host = pattern->GetHost();
2275
2276 isAnimating_ = true;
2277 turnPageRate_ = 0.0f;
2278 indicatorStartPos_ = originalPaintRect.GetX() + originalPaintRect.Width() / HALF_OF_WIDTH;
2279 indicatorEndPos_ = targetPaintRect.GetX() + targetPaintRect.Width() / HALF_OF_WIDTH + targetOffset;
2280 auto propertyName = INDICATOR_OFFSET_PROPERTY_NAME;
2281
2282 if (NearZero(indicatorEndPos_ - indicatorStartPos_)) {
2283 indicatorStartPos_ = originalPaintRect.Width();
2284 indicatorEndPos_ = targetPaintRect.Width();
2285 propertyName = INDICATOR_WIDTH_PROPERTY_NAME;
2286 host->CreateAnimatablePropertyFloat(propertyName, 0, [weak](float value) {
2287 auto tabBarPattern = weak.Upgrade();
2288 CHECK_NULL_VOID(tabBarPattern);
2289 if (!tabBarPattern->isAnimating_ ||
2290 NearZero(tabBarPattern->indicatorEndPos_ - tabBarPattern->indicatorStartPos_)) {
2291 return;
2292 }
2293 tabBarPattern->turnPageRate_ = (value - tabBarPattern->indicatorStartPos_) /
2294 (tabBarPattern->indicatorEndPos_ - tabBarPattern->indicatorStartPos_);
2295 tabBarPattern->UpdateIndicatorCurrentOffset(0.0f);
2296 });
2297 } else {
2298 host->CreateAnimatablePropertyFloat(propertyName, 0, [weak](float value) {
2299 auto tabBarPattern = weak.Upgrade();
2300 CHECK_NULL_VOID(tabBarPattern);
2301 if (!tabBarPattern->isAnimating_ ||
2302 NearZero(tabBarPattern->indicatorEndPos_ - tabBarPattern->indicatorStartPos_)) {
2303 return;
2304 }
2305 tabBarPattern->turnPageRate_ = (value - tabBarPattern->indicatorStartPos_) /
2306 (tabBarPattern->indicatorEndPos_ - tabBarPattern->indicatorStartPos_);
2307 tabBarPattern->UpdateIndicatorCurrentOffset(
2308 static_cast<float>(value - tabBarPattern->currentIndicatorOffset_));
2309 });
2310 }
2311 host->UpdateAnimatablePropertyFloat(propertyName, indicatorStartPos_);
2312 indicatorAnimationIsRunning_ = true;
2313 tabbarIndicatorAnimation_ = AnimationUtils::StartAnimation(option,
2314 [host, propertyName, endPos = indicatorEndPos_]() {
2315 host->UpdateAnimatablePropertyFloat(propertyName, endPos);
2316 },
2317 [weak]() {
2318 auto tabBarPattern = weak.Upgrade();
2319 CHECK_NULL_VOID(tabBarPattern);
2320 tabBarPattern->indicatorAnimationIsRunning_ = false;
2321 });
2322 }
2323
StopTranslateAnimation()2324 void TabBarPattern::StopTranslateAnimation()
2325 {
2326 if (translateAnimation_)
2327 AnimationUtils::StopAnimation(translateAnimation_);
2328
2329 if (tabbarIndicatorAnimation_)
2330 AnimationUtils::StopAnimation(tabbarIndicatorAnimation_);
2331
2332 if (indicatorAnimationIsRunning_)
2333 indicatorAnimationIsRunning_ = false;
2334
2335 if (translateAnimationIsRunning_)
2336 translateAnimationIsRunning_ = false;
2337 }
2338
TriggerTranslateAnimation(int32_t currentIndex,int32_t targetIndex)2339 void TabBarPattern::TriggerTranslateAnimation(int32_t currentIndex, int32_t targetIndex)
2340 {
2341 auto curve = DurationCubicCurve;
2342 StopTranslateAnimation();
2343 SetSwiperCurve(curve);
2344 auto pipelineContext = PipelineContext::GetCurrentContextSafely();
2345 CHECK_NULL_VOID(pipelineContext);
2346 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
2347 CHECK_NULL_VOID(tabTheme);
2348 UpdateAnimationDuration();
2349 AnimationOption option = AnimationOption();
2350 option.SetDuration(static_cast<int32_t>(GetAnimationDuration().value_or(
2351 tabTheme->GetTabContentAnimationDuration())));
2352 option.SetCurve(curve);
2353 option.SetFillMode(FillMode::FORWARDS);
2354
2355 auto targetOffset = 0.0f;
2356 if (CanScroll()) {
2357 targetOffset = CalculateTargetOffset(targetIndex);
2358 PlayTabBarTranslateAnimation(option, targetOffset);
2359 }
2360
2361 auto host = GetHost();
2362 CHECK_NULL_VOID(host);
2363 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
2364 CHECK_NULL_VOID(layoutProperty);
2365 if (std::count(tabBarStyles_.begin(), tabBarStyles_.end(), TabBarStyle::SUBTABBATSTYLE) !=
2366 static_cast<int32_t>(tabBarStyles_.size()) ||
2367 layoutProperty->GetAxisValue(Axis::HORIZONTAL) != Axis::HORIZONTAL) {
2368 return;
2369 }
2370 auto originalPaintRect = layoutProperty->GetIndicatorRect(currentIndex);
2371 auto targetPaintRect = layoutProperty->GetIndicatorRect(targetIndex);
2372 auto paintProperty = host->GetPaintProperty<TabBarPaintProperty>();
2373 CHECK_NULL_VOID(paintProperty);
2374 paintProperty->UpdateIndicator(targetPaintRect);
2375 if (!changeByClick_) {
2376 return;
2377 }
2378 PlayIndicatorTranslateAnimation(option, originalPaintRect, targetPaintRect, targetOffset);
2379 }
2380
CalculateTargetOffset(int32_t targetIndex)2381 float TabBarPattern::CalculateTargetOffset(int32_t targetIndex)
2382 {
2383 auto targetOffset = 0.0f;
2384 auto space = GetSpace(targetIndex);
2385 auto startPos = 0.0f;
2386 auto endPos = 0.0f;
2387 auto iter = visibleItemPosition_.find(targetIndex);
2388 if (iter != visibleItemPosition_.end()) {
2389 startPos = iter->second.startPos;
2390 endPos = iter->second.endPos;
2391 }
2392 auto frontChildrenMainSize = CalculateFrontChildrenMainSize(targetIndex);
2393 auto backChildrenMainSize = CalculateBackChildrenMainSize(targetIndex);
2394 if (Negative(space)) {
2395 targetOffset = isRTL_ && axis_ == Axis::HORIZONTAL ? (startPos - scrollMargin_)
2396 : (scrollMargin_ - startPos);
2397 } else if (LessOrEqual(frontChildrenMainSize, space)) {
2398 targetOffset = isRTL_ && axis_ == Axis::HORIZONTAL ? (startPos - frontChildrenMainSize)
2399 : (frontChildrenMainSize - startPos);
2400 } else if (LessOrEqual(backChildrenMainSize, space)) {
2401 auto host = GetHost();
2402 CHECK_NULL_RETURN(host, targetOffset);
2403 auto mainSize = host->GetGeometryNode()->GetPaddingSize().MainSize(axis_);
2404 targetOffset = isRTL_ && axis_ == Axis::HORIZONTAL ? (backChildrenMainSize - (mainSize - endPos))
2405 : (mainSize - backChildrenMainSize - endPos);
2406 } else {
2407 targetOffset = isRTL_ && axis_ == Axis::HORIZONTAL ? (startPos - space) : (space - startPos);
2408 }
2409 return targetOffset;
2410 }
2411
UpdateIndicatorCurrentOffset(float offset)2412 void TabBarPattern::UpdateIndicatorCurrentOffset(float offset)
2413 {
2414 currentIndicatorOffset_ = currentIndicatorOffset_ + offset;
2415 auto host = GetHost();
2416 CHECK_NULL_VOID(host);
2417 host->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
2418 }
2419
CreateNodePaintMethod()2420 RefPtr<NodePaintMethod> TabBarPattern::CreateNodePaintMethod()
2421 {
2422 if (indicator_ < 0 || indicator_ >= static_cast<int32_t>(indicatorStyles_.size()) ||
2423 indicator_ >= static_cast<int32_t>(selectedModes_.size())) {
2424 return nullptr;
2425 }
2426
2427 if (!tabBarModifier_) {
2428 tabBarModifier_ = AceType::MakeRefPtr<TabBarModifier>();
2429 }
2430
2431 Color bgColor = GetTabBarBackgroundColor();
2432 RectF tabBarItemRect;
2433 auto paintProperty = GetPaintProperty<TabBarPaintProperty>();
2434 if (paintProperty) {
2435 RectF rect;
2436 tabBarItemRect = paintProperty->GetIndicator().value_or(rect);
2437 }
2438 IndicatorStyle indicatorStyle;
2439 OffsetF indicatorOffset = { currentIndicatorOffset_, tabBarItemRect.GetY() };
2440 GetIndicatorStyle(indicatorStyle, indicatorOffset);
2441 indicatorOffset.AddX(-indicatorStyle.width.ConvertToPx() / HALF_OF_WIDTH);
2442 auto hasIndicator = std::count(selectedModes_.begin(), selectedModes_.end(), SelectedMode::INDICATOR) ==
2443 static_cast<int32_t>(selectedModes_.size()) && !NearZero(tabBarItemRect.Height());
2444 return MakeRefPtr<TabBarPaintMethod>(tabBarModifier_, gradientRegions_, bgColor, indicatorStyle,
2445 indicatorOffset, hasIndicator);
2446 }
2447
GetTabBarBackgroundColor() const2448 Color TabBarPattern::GetTabBarBackgroundColor() const
2449 {
2450 Color bgColor = Color::WHITE;
2451 auto tabBarNode = GetHost();
2452 CHECK_NULL_RETURN(tabBarNode, bgColor);
2453 auto tabBarCtx = tabBarNode->GetRenderContext();
2454 CHECK_NULL_RETURN(tabBarCtx, bgColor);
2455 if (tabBarCtx->GetBackgroundColor()) {
2456 bgColor = *tabBarCtx->GetBackgroundColor();
2457 } else {
2458 auto tabsNode = AceType::DynamicCast<FrameNode>(tabBarNode->GetParent());
2459 CHECK_NULL_RETURN(tabsNode, bgColor);
2460 auto tabsCtx = tabsNode->GetRenderContext();
2461 CHECK_NULL_RETURN(tabsCtx, bgColor);
2462 if (tabsCtx->GetBackgroundColor()) {
2463 bgColor = *tabsCtx->GetBackgroundColor();
2464 } else {
2465 auto pipeline = PipelineContext::GetCurrentContext();
2466 CHECK_NULL_RETURN(pipeline, bgColor);
2467 auto tabTheme = pipeline->GetTheme<TabTheme>();
2468 CHECK_NULL_RETURN(tabTheme, bgColor);
2469 bgColor = tabTheme->GetBackgroundColor().ChangeAlpha(0xff);
2470 }
2471 }
2472 return bgColor;
2473 }
2474
GetIndicatorStyle(IndicatorStyle & indicatorStyle,OffsetF & indicatorOffset)2475 void TabBarPattern::GetIndicatorStyle(IndicatorStyle& indicatorStyle, OffsetF& indicatorOffset)
2476 {
2477 if (indicator_ < 0 || indicator_ >= static_cast<int32_t>(indicatorStyles_.size())) {
2478 return;
2479 }
2480 indicatorStyle = indicatorStyles_[indicator_];
2481 auto host = GetHost();
2482 CHECK_NULL_VOID(host);
2483 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
2484 CHECK_NULL_VOID(layoutProperty);
2485
2486 if (NonPositive(indicatorStyle.width.Value())) {
2487 auto paintProperty = GetPaintProperty<TabBarPaintProperty>();
2488 if (paintProperty) {
2489 RectF rect;
2490 indicatorStyle.width = Dimension(paintProperty->GetIndicator().value_or(rect).Width());
2491 }
2492 }
2493 if ((!isTouchingSwiper_ && !isAnimating_) || axis_ != Axis::HORIZONTAL) {
2494 return;
2495 }
2496 if (LessOrEqual(turnPageRate_, 0.0f)) {
2497 turnPageRate_ = 0.0f;
2498 }
2499 if (GreatOrEqual(turnPageRate_, 1.0f)) {
2500 turnPageRate_ = 1.0f;
2501 }
2502 auto totalCount = host->TotalChildCount() - MASK_COUNT;
2503 if (swiperStartIndex_ < 0 || swiperStartIndex_ >= totalCount ||
2504 swiperStartIndex_ >= static_cast<int32_t>(tabBarStyles_.size()) ||
2505 tabBarStyles_[swiperStartIndex_] != TabBarStyle::SUBTABBATSTYLE ||
2506 swiperStartIndex_ >= static_cast<int32_t>(selectedModes_.size()) ||
2507 selectedModes_[swiperStartIndex_] != SelectedMode::INDICATOR ||
2508 swiperStartIndex_ >= static_cast<int32_t>(indicatorStyles_.size())) {
2509 return;
2510 }
2511
2512 auto nextIndex = isTouchingSwiper_ ? swiperStartIndex_ + 1 : animationTargetIndex_.value_or(-1);
2513 if (nextIndex < 0 || nextIndex >= totalCount ||
2514 nextIndex >= static_cast<int32_t>(tabBarStyles_.size()) ||
2515 tabBarStyles_[nextIndex] != TabBarStyle::SUBTABBATSTYLE ||
2516 nextIndex >= static_cast<int32_t>(selectedModes_.size()) ||
2517 selectedModes_[nextIndex] != SelectedMode::INDICATOR ||
2518 nextIndex >= static_cast<int32_t>(indicatorStyles_.size())) {
2519 return;
2520 }
2521 CalculateIndicatorStyle(swiperStartIndex_, nextIndex, indicatorStyle, indicatorOffset);
2522 }
2523
CalculateIndicatorStyle(int32_t startIndex,int32_t nextIndex,IndicatorStyle & indicatorStyle,OffsetF & indicatorOffset)2524 void TabBarPattern::CalculateIndicatorStyle(
2525 int32_t startIndex, int32_t nextIndex, IndicatorStyle& indicatorStyle, OffsetF& indicatorOffset)
2526 {
2527 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
2528 CHECK_NULL_VOID(layoutProperty);
2529
2530 indicatorStyle = indicatorStyles_[startIndex];
2531 auto startItemRect = layoutProperty->GetIndicatorRect(startIndex);
2532 if (NonPositive(indicatorStyle.width.Value())) {
2533 indicatorStyle.width = Dimension(startItemRect.Width());
2534 }
2535 IndicatorStyle nextIndicatorStyle = indicatorStyles_[nextIndex];
2536 auto nextItemRect = layoutProperty->GetIndicatorRect(nextIndex);
2537 if (NonPositive(nextIndicatorStyle.width.Value())) {
2538 nextIndicatorStyle.width = Dimension(nextItemRect.Width());
2539 }
2540
2541 indicatorStyle.width = Dimension(indicatorStyle.width.ConvertToPx() +
2542 (nextIndicatorStyle.width.ConvertToPx() - indicatorStyle.width.ConvertToPx()) * turnPageRate_);
2543 indicatorStyle.marginTop = Dimension(indicatorStyle.marginTop.ConvertToPx() +
2544 (nextIndicatorStyle.marginTop.ConvertToPx() - indicatorStyle.marginTop.ConvertToPx()) * turnPageRate_);
2545 indicatorStyle.height = Dimension(indicatorStyle.height.ConvertToPx() +
2546 (nextIndicatorStyle.height.ConvertToPx() - indicatorStyle.height.ConvertToPx()) * turnPageRate_);
2547 LinearColor color = LinearColor(indicatorStyle.color) +
2548 (LinearColor(nextIndicatorStyle.color) - LinearColor(indicatorStyle.color)) * turnPageRate_;
2549 indicatorStyle.color = color.ToColor();
2550 indicatorOffset.SetY(startItemRect.GetY() + (nextItemRect.GetY() - startItemRect.GetY()) * turnPageRate_);
2551 }
2552
GetSpace(int32_t indicator)2553 float TabBarPattern::GetSpace(int32_t indicator)
2554 {
2555 auto host = GetHost();
2556 CHECK_NULL_RETURN(host, 0.0f);
2557 auto geometryNode = host->GetGeometryNode();
2558 auto childFrameNode = AceType::DynamicCast<FrameNode>(host->GetChildAtIndex(indicator));
2559 CHECK_NULL_RETURN(childFrameNode, 0.0f);
2560 auto childGeometryNode = childFrameNode->GetGeometryNode();
2561
2562 return (geometryNode->GetPaddingSize().MainSize(axis_) - childGeometryNode->GetMarginFrameSize().MainSize(axis_)) /
2563 2;
2564 }
2565
CalculateFrontChildrenMainSize(int32_t indicator)2566 float TabBarPattern::CalculateFrontChildrenMainSize(int32_t indicator)
2567 {
2568 float frontChildrenMainSize = scrollMargin_;
2569 if (visibleItemPosition_.empty()) {
2570 return frontChildrenMainSize;
2571 }
2572 for (auto& iter : visibleItemPosition_) {
2573 if (iter.first < indicator) {
2574 frontChildrenMainSize += iter.second.endPos - iter.second.startPos;
2575 }
2576 }
2577 return frontChildrenMainSize;
2578 }
2579
CalculateBackChildrenMainSize(int32_t indicator)2580 float TabBarPattern::CalculateBackChildrenMainSize(int32_t indicator)
2581 {
2582 float backChildrenMainSize = scrollMargin_;
2583 if (visibleItemPosition_.empty()) {
2584 return backChildrenMainSize;
2585 }
2586 for (auto& iter : visibleItemPosition_) {
2587 if (iter.first > indicator) {
2588 backChildrenMainSize += iter.second.endPos - iter.second.startPos;
2589 }
2590 }
2591 return backChildrenMainSize;
2592 }
2593
SetEdgeEffect(const RefPtr<GestureEventHub> & gestureHub)2594 void TabBarPattern::SetEdgeEffect(const RefPtr<GestureEventHub>& gestureHub)
2595 {
2596 CHECK_NULL_VOID(gestureHub);
2597 if (scrollEffect_) {
2598 gestureHub->RemoveScrollEdgeEffect(scrollEffect_);
2599 scrollEffect_.Reset();
2600 }
2601 if (!scrollEffect_) {
2602 auto springEffect = AceType::MakeRefPtr<ScrollSpringEffect>();
2603 CHECK_NULL_VOID(springEffect);
2604 springEffect->SetOutBoundaryCallback([weak = AceType::WeakClaim(this)]() {
2605 auto pattern = weak.Upgrade();
2606 CHECK_NULL_RETURN(pattern, false);
2607 return pattern->IsAtTop() || pattern->IsAtBottom();
2608 });
2609 // add callback to springEdgeEffect
2610 SetEdgeEffectCallback(springEffect);
2611 scrollEffect_ = springEffect;
2612 gestureHub->AddScrollEdgeEffect(axis_, scrollEffect_);
2613 }
2614 }
2615
SetEdgeEffectCallback(const RefPtr<ScrollEdgeEffect> & scrollEffect)2616 void TabBarPattern::SetEdgeEffectCallback(const RefPtr<ScrollEdgeEffect>& scrollEffect)
2617 {
2618 scrollEffect->SetCurrentPositionCallback([weak = AceType::WeakClaim(this)]() -> double {
2619 auto tabBar = weak.Upgrade();
2620 CHECK_NULL_RETURN(tabBar, 0.0);
2621 auto host = tabBar->GetHost();
2622 CHECK_NULL_RETURN(host, 0.0);
2623 auto geometryNode = host->GetGeometryNode();
2624 CHECK_NULL_RETURN(geometryNode, 0.0);
2625 if (tabBar->visibleItemPosition_.empty()) {
2626 return tabBar->scrollMargin_ + tabBar->currentDelta_;
2627 }
2628 if (tabBar->isRTL_ && tabBar->axis_ == Axis::HORIZONTAL) {
2629 return geometryNode->GetPaddingSize().Width() - tabBar->visibleItemPosition_.rbegin()->second.endPos +
2630 tabBar->currentDelta_;
2631 } else {
2632 return tabBar->visibleItemPosition_.begin()->second.startPos + tabBar->currentDelta_;
2633 }
2634 });
2635 auto leadingCallback = [weak = AceType::WeakClaim(this)]() -> double {
2636 auto tabBar = weak.Upgrade();
2637 CHECK_NULL_RETURN(tabBar, 0.0);
2638 auto host = tabBar->GetHost();
2639 CHECK_NULL_RETURN(host, 0.0);
2640 auto geometryNode = host->GetGeometryNode();
2641 CHECK_NULL_RETURN(geometryNode, 0.0);
2642 if (tabBar->visibleItemPosition_.empty()) {
2643 return geometryNode->GetPaddingSize().MainSize(tabBar->axis_) - tabBar->scrollMargin_;
2644 }
2645 auto visibleChildrenMainSize = tabBar->visibleItemPosition_.rbegin()->second.endPos -
2646 tabBar->visibleItemPosition_.begin()->second.startPos;
2647 return geometryNode->GetPaddingSize().MainSize(tabBar->axis_) - visibleChildrenMainSize - tabBar->scrollMargin_;
2648 };
2649 auto trailingCallback = [weak = AceType::WeakClaim(this)]() -> double {
2650 auto tabBar = weak.Upgrade();
2651 CHECK_NULL_RETURN(tabBar, 0.0);
2652 return tabBar->scrollMargin_;
2653 };
2654 scrollEffect->SetLeadingCallback(leadingCallback);
2655 scrollEffect->SetTrailingCallback(trailingCallback);
2656 scrollEffect->SetInitLeadingCallback(leadingCallback);
2657 scrollEffect->SetInitTrailingCallback(trailingCallback);
2658 }
2659
IsAtTop() const2660 bool TabBarPattern::IsAtTop() const
2661 {
2662 if (visibleItemPosition_.empty()) {
2663 return false;
2664 }
2665
2666 auto visibleItemStartIndex = visibleItemPosition_.begin()->first;
2667 auto visibleItemStartPos = visibleItemPosition_.begin()->second.startPos;
2668 return visibleItemStartIndex == 0 && GreatOrEqual(visibleItemStartPos, scrollMargin_);
2669 }
2670
IsAtBottom() const2671 bool TabBarPattern::IsAtBottom() const
2672 {
2673 if (visibleItemPosition_.empty()) {
2674 return false;
2675 }
2676 auto host = GetHost();
2677 CHECK_NULL_RETURN(host, false);
2678 auto geometryNode = host->GetGeometryNode();
2679 CHECK_NULL_RETURN(geometryNode, false);
2680
2681 auto visibleItemEndIndex = visibleItemPosition_.rbegin()->first;
2682 auto visibleItemEndPos = visibleItemPosition_.rbegin()->second.endPos;
2683 auto childCount = host->TotalChildCount() - MASK_COUNT;
2684 auto mainSize = geometryNode->GetPaddingSize().MainSize(axis_);
2685 return visibleItemEndIndex == (childCount - 1) && LessOrEqual(visibleItemEndPos, mainSize - scrollMargin_);
2686 }
2687
IsOutOfBoundary()2688 bool TabBarPattern::IsOutOfBoundary()
2689 {
2690 if (visibleItemPosition_.empty()) {
2691 return false;
2692 }
2693 auto host = GetHost();
2694 CHECK_NULL_RETURN(host, false);
2695 auto geometryNode = host->GetGeometryNode();
2696 CHECK_NULL_RETURN(geometryNode, false);
2697
2698 auto visibleItemStartPos = visibleItemPosition_.begin()->second.startPos;
2699 auto visibleItemEndPos = visibleItemPosition_.rbegin()->second.endPos;
2700 auto mainSize = geometryNode->GetPaddingSize().MainSize(axis_);
2701 bool outOfStart = Positive(visibleItemStartPos - scrollMargin_) &&
2702 GreatNotEqual(visibleItemEndPos + scrollMargin_, mainSize);
2703 bool outOfEnd = LessNotEqual(visibleItemEndPos + scrollMargin_, mainSize) &&
2704 Negative(visibleItemStartPos - scrollMargin_);
2705 return outOfStart || outOfEnd;
2706 }
2707
SetAccessibilityAction()2708 void TabBarPattern::SetAccessibilityAction()
2709 {
2710 auto host = GetHost();
2711 CHECK_NULL_VOID(host);
2712 auto accessibilityProperty = host->GetAccessibilityProperty<AccessibilityProperty>();
2713 CHECK_NULL_VOID(accessibilityProperty);
2714 accessibilityProperty->SetActionScrollForward([weakPtr = WeakClaim(this)]() {
2715 const auto& pattern = weakPtr.Upgrade();
2716 CHECK_NULL_VOID(pattern);
2717 auto tabBarLayoutProperty = pattern->GetLayoutProperty<TabBarLayoutProperty>();
2718 CHECK_NULL_VOID(tabBarLayoutProperty);
2719 auto frameNode = pattern->GetHost();
2720 CHECK_NULL_VOID(frameNode);
2721 if (tabBarLayoutProperty->GetTabBarMode().value_or(TabBarMode::FIXED) == TabBarMode::SCROLLABLE &&
2722 frameNode->TotalChildCount() - MASK_COUNT > 1) {
2723 auto index = pattern->GetIndicator() + 1;
2724 pattern->FocusIndexChange(index);
2725 // AccessibilityEventType::SCROLL_END
2726 }
2727 });
2728
2729 accessibilityProperty->SetActionScrollBackward([weakPtr = WeakClaim(this)]() {
2730 const auto& pattern = weakPtr.Upgrade();
2731 CHECK_NULL_VOID(pattern);
2732 auto tabBarLayoutProperty = pattern->GetLayoutProperty<TabBarLayoutProperty>();
2733 CHECK_NULL_VOID(tabBarLayoutProperty);
2734 auto frameNode = pattern->GetHost();
2735 CHECK_NULL_VOID(frameNode);
2736 if (tabBarLayoutProperty->GetTabBarMode().value_or(TabBarMode::FIXED) == TabBarMode::SCROLLABLE &&
2737 frameNode->TotalChildCount() - MASK_COUNT > 1) {
2738 auto index = pattern->GetIndicator() - 1;
2739 pattern->FocusIndexChange(index);
2740 // AccessibilityEventType::SCROLL_END
2741 }
2742 });
2743 }
2744
ProvideRestoreInfo()2745 std::string TabBarPattern::ProvideRestoreInfo()
2746 {
2747 auto jsonObj = JsonUtil::Create(true);
2748 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
2749 CHECK_NULL_RETURN(tabBarLayoutProperty, "");
2750 jsonObj->Put("Index", tabBarLayoutProperty->GetIndicator().value_or(0));
2751 return jsonObj->ToString();
2752 }
2753
OnRestoreInfo(const std::string & restoreInfo)2754 void TabBarPattern::OnRestoreInfo(const std::string& restoreInfo)
2755 {
2756 auto host = GetHost();
2757 CHECK_NULL_VOID(host);
2758 auto tabBarLayoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
2759 CHECK_NULL_VOID(tabBarLayoutProperty);
2760 auto info = JsonUtil::ParseJsonString(restoreInfo);
2761 if (!info->IsValid() || !info->IsObject()) {
2762 return;
2763 }
2764 auto jsonIsOn = info->GetValue("Index");
2765 auto index = jsonIsOn->GetInt();
2766 auto totalCount = host->TotalChildCount();
2767 if (index < 0 || index >= totalCount || !swiperController_ ||
2768 indicator_ >= static_cast<int32_t>(tabBarStyles_.size())) {
2769 return;
2770 }
2771 auto tabsFrameNode = AceType::DynamicCast<TabsNode>(host->GetParent());
2772 CHECK_NULL_VOID(tabsFrameNode);
2773 auto tabsPattern = tabsFrameNode->GetPattern<TabsPattern>();
2774 tabBarLayoutProperty->UpdateIndicator(index);
2775 clickRepeat_ = false;
2776 UpdateAnimationDuration();
2777 if (GetAnimationDuration().has_value()
2778 && (!tabsPattern || tabsPattern->GetAnimateMode() != TabAnimateMode::NO_ANIMATION)) {
2779 swiperController_->SwipeTo(index);
2780 } else {
2781 swiperController_->SwipeToWithoutAnimation(index);
2782 }
2783 }
2784
ToJsonValue(std::unique_ptr<JsonValue> & json,const InspectorFilter & filter) const2785 void TabBarPattern::ToJsonValue(std::unique_ptr<JsonValue>& json, const InspectorFilter& filter) const
2786 {
2787 Pattern::ToJsonValue(json, filter);
2788 /* no fixed attr below, just return */
2789 if (filter.IsFastFilter()) {
2790 return;
2791 }
2792 auto selectedModes = JsonUtil::CreateArray(true);
2793 for (const auto& selectedMode : selectedModes_) {
2794 auto mode = JsonUtil::Create(true);
2795 mode->Put("mode", selectedMode == SelectedMode::INDICATOR ? "INDICATOR" : "BOARD");
2796 selectedModes->Put(mode);
2797 }
2798 json->PutExtAttr("selectedModes", selectedModes->ToString().c_str(), filter);
2799
2800 auto indicatorStyles = JsonUtil::CreateArray(true);
2801 for (const auto& indicatorStyle : indicatorStyles_) {
2802 auto indicator = JsonUtil::Create(true);
2803 indicator->Put("color", indicatorStyle.color.ColorToString().c_str());
2804 indicator->Put("height", indicatorStyle.height.ToString().c_str());
2805 indicator->Put("width", indicatorStyle.width.ToString().c_str());
2806 indicator->Put("borderRadius", indicatorStyle.borderRadius.ToString().c_str());
2807 indicator->Put("marginTop", indicatorStyle.marginTop.ToString().c_str());
2808 indicatorStyles->Put(indicator);
2809 }
2810 json->PutExtAttr("indicatorStyles", indicatorStyles->ToString().c_str(), filter);
2811
2812 auto tabBarStyles = JsonUtil::CreateArray(true);
2813 for (const auto& tabBarStyle : tabBarStyles_) {
2814 auto style = JsonUtil::Create(true);
2815 style->Put("style", tabBarStyle == TabBarStyle::NOSTYLE ? "NOSTYLE"
2816 : tabBarStyle == TabBarStyle::SUBTABBATSTYLE ? "SUBTABBATSTYLE"
2817 : "BOTTOMTABBATSTYLE");
2818 tabBarStyles->Put(style);
2819 }
2820 json->PutExtAttr("tabBarStyles", tabBarStyles->ToString().c_str(), filter);
2821 }
2822
FromJson(const std::unique_ptr<JsonValue> & json)2823 void TabBarPattern::FromJson(const std::unique_ptr<JsonValue>& json)
2824 {
2825 auto selectedModes = JsonUtil::ParseJsonString(json->GetString("selectedModes"));
2826 for (int32_t i = 0; i < selectedModes->GetArraySize(); i++) {
2827 auto selectedMode = selectedModes->GetArrayItem(i);
2828 auto mode = selectedMode->GetString("mode");
2829 SetSelectedMode(mode == "INDICATOR" ? SelectedMode::INDICATOR : SelectedMode::BOARD, i);
2830 }
2831
2832 auto indicatorStyles = JsonUtil::ParseJsonString(json->GetString("indicatorStyles"));
2833 for (int32_t i = 0; i < indicatorStyles->GetArraySize(); i++) {
2834 auto indicatorStyle = indicatorStyles->GetArrayItem(i);
2835 IndicatorStyle style;
2836 style.color = Color::ColorFromString(indicatorStyle->GetString("color"));
2837 style.height = Dimension::FromString(indicatorStyle->GetString("height"));
2838 style.width = Dimension::FromString(indicatorStyle->GetString("width"));
2839 style.borderRadius = Dimension::FromString(indicatorStyle->GetString("borderRadius"));
2840 style.marginTop = Dimension::FromString(indicatorStyle->GetString("marginTop"));
2841 SetIndicatorStyle(style, i);
2842 }
2843
2844 auto tabBarStyles = JsonUtil::ParseJsonString(json->GetString("tabBarStyles"));
2845 for (int32_t i = 0; i < tabBarStyles->GetArraySize(); i++) {
2846 auto tabBarStyle = tabBarStyles->GetArrayItem(i);
2847 auto style = tabBarStyle->GetString("style");
2848 SetTabBarStyle(style == "NOSTYLE" ? TabBarStyle::NOSTYLE
2849 : style == "SUBTABBATSTYLE" ? TabBarStyle::SUBTABBATSTYLE
2850 : TabBarStyle::BOTTOMTABBATSTYLE,
2851 i);
2852 }
2853
2854 auto layoutProperty = GetLayoutProperty<TabBarLayoutProperty>();
2855 CHECK_NULL_VOID(layoutProperty);
2856 auto indicatorValue = layoutProperty->GetIndicatorValue(0);
2857 UpdateIndicator(indicatorValue);
2858 Pattern::FromJson(json);
2859 }
2860
TabBarClickEvent(int32_t index) const2861 void TabBarPattern::TabBarClickEvent(int32_t index) const
2862 {
2863 auto host = GetHost();
2864 CHECK_NULL_VOID(host);
2865 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
2866 CHECK_NULL_VOID(tabsNode);
2867 auto tabsPattern = tabsNode->GetPattern<TabsPattern>();
2868 CHECK_NULL_VOID(tabsPattern);
2869 auto tabBarClickEvent = tabsPattern->GetTabBarClickEvent();
2870 CHECK_NULL_VOID(tabBarClickEvent);
2871 auto event = *tabBarClickEvent;
2872 event(index);
2873 }
2874
2875
OnCustomContentTransition(int32_t fromIndex,int32_t toIndex)2876 void TabBarPattern::OnCustomContentTransition(int32_t fromIndex, int32_t toIndex)
2877 {
2878 auto swiperPattern = GetSwiperPattern();
2879 CHECK_NULL_VOID(swiperPattern);
2880
2881 swiperPattern->OnCustomContentTransition(toIndex);
2882 }
2883
GetSwiperPattern() const2884 RefPtr<SwiperPattern> TabBarPattern::GetSwiperPattern() const
2885 {
2886 auto host = GetHost();
2887 CHECK_NULL_RETURN(host, nullptr);
2888 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
2889 CHECK_NULL_RETURN(tabsNode, nullptr);
2890 auto swiperNode = AceType::DynamicCast<FrameNode>(tabsNode->GetTabs());
2891 CHECK_NULL_RETURN(swiperNode, nullptr);
2892 auto swiperPattern = swiperNode->GetPattern<SwiperPattern>();
2893 return swiperPattern;
2894 }
2895
CheckSwiperDisable() const2896 bool TabBarPattern::CheckSwiperDisable() const
2897 {
2898 auto host = GetHost();
2899 CHECK_NULL_RETURN(host, true);
2900 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
2901 CHECK_NULL_RETURN(tabsNode, true);
2902 auto swiperNode = AceType::DynamicCast<FrameNode>(tabsNode->GetTabs());
2903 CHECK_NULL_RETURN(swiperNode, true);
2904 auto props = swiperNode->GetLayoutProperty<SwiperLayoutProperty>();
2905 CHECK_NULL_RETURN(props, true);
2906 return props->GetDisableSwipe().value_or(false);
2907 }
2908
SetSwiperCurve(const RefPtr<Curve> & curve) const2909 void TabBarPattern::SetSwiperCurve(const RefPtr<Curve>& curve) const
2910 {
2911 auto host = GetHost();
2912 CHECK_NULL_VOID(host);
2913 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
2914 CHECK_NULL_VOID(tabsNode);
2915 auto swiperNode = AceType::DynamicCast<FrameNode>(tabsNode->GetTabs());
2916 CHECK_NULL_VOID(swiperNode);
2917 auto swiperPaintProperty = swiperNode->GetPaintProperty<SwiperPaintProperty>();
2918 CHECK_NULL_VOID(swiperPaintProperty);
2919 swiperPaintProperty->UpdateCurve(curve);
2920 }
2921
ApplyTurnPageRateToIndicator(float turnPageRate)2922 void TabBarPattern::ApplyTurnPageRateToIndicator(float turnPageRate)
2923 {
2924 auto host = GetHost();
2925 CHECK_NULL_VOID(host);
2926 auto layoutProperty = host->GetLayoutProperty<TabBarLayoutProperty>();
2927 auto totalCount = host->TotalChildCount() - MASK_COUNT;
2928 CHECK_NULL_VOID(layoutProperty);
2929 swiperStartIndex_ = std::clamp(swiperStartIndex_, 0, totalCount - 1);
2930 CHECK_NULL_VOID(IsValidIndex(swiperStartIndex_));
2931 auto index = swiperStartIndex_ + 1;
2932 auto isRtl = ParseTabsIsRtl();
2933 if ((index >= totalCount || index >= static_cast<int32_t>(tabBarStyles_.size())) && !isRtl) {
2934 swiperStartIndex_--;
2935 index--;
2936 turnPageRate = 1.0f;
2937 }
2938 if (isRtl && (index == static_cast<int32_t>(tabBarStyles_.size()) || NearEqual(turnPageRate, 1.0f))) {
2939 return;
2940 }
2941 if (Negative(turnPageRate)) {
2942 turnPageRate = 0.0f;
2943 }
2944 CHECK_NULL_VOID(IsValidIndex(index));
2945 if (GreatOrEqual(turnPageRate, 1.0f)) {
2946 turnPageRate_ = 1.0f;
2947 } else if (LessOrEqual(turnPageRate, 0.0f)) {
2948 turnPageRate_ = 0.0f;
2949 } else {
2950 if (turnPageRate_ <= TEXT_COLOR_THREDHOLD && turnPageRate > TEXT_COLOR_THREDHOLD) {
2951 UpdateTextColorAndFontWeight(index);
2952 } else if (turnPageRate <= 1.0f - TEXT_COLOR_THREDHOLD && turnPageRate_ > 1.0f - TEXT_COLOR_THREDHOLD) {
2953 UpdateTextColorAndFontWeight(swiperStartIndex_);
2954 }
2955 turnPageRate_ = turnPageRate;
2956 }
2957 auto originalPaintRect = layoutProperty->GetIndicatorRect(swiperStartIndex_);
2958 auto targetPaintRect = layoutProperty->GetIndicatorRect(index);
2959 auto paintRectDiff = std::abs(targetPaintRect.GetX() + targetPaintRect.Width() / 2 - originalPaintRect.GetX() -
2960 originalPaintRect.Width() / 2);
2961
2962 currentIndicatorOffset_ = originalPaintRect.GetX() + originalPaintRect.Width() / 2 + paintRectDiff * turnPageRate_;
2963 if (isRtl) {
2964 auto originalPaintRect = layoutProperty->GetIndicatorRect(swiperStartIndex_ + 1);
2965 auto targetPaintRect = layoutProperty->GetIndicatorRect(swiperStartIndex_ >= 0 ? swiperStartIndex_ : 0);
2966 auto paintRectDiff = std::abs(targetPaintRect.GetX() + targetPaintRect.Width() / HALF_OF_WIDTH -
2967 originalPaintRect.GetX() - originalPaintRect.Width() / HALF_OF_WIDTH);
2968 currentIndicatorOffset_ =
2969 originalPaintRect.GetX() + originalPaintRect.Width() / HALF_OF_WIDTH + paintRectDiff * (1 - turnPageRate_);
2970 }
2971 host->MarkDirtyNode(PROPERTY_UPDATE_RENDER);
2972 }
2973
InitTurnPageRateEvent()2974 void TabBarPattern::InitTurnPageRateEvent()
2975 {
2976 auto turnPageRateCallback = [weak = WeakClaim(this)](int32_t swipingIndex, float turnPageRate) {
2977 auto pattern = weak.Upgrade();
2978 if (pattern) {
2979 if (!pattern->CheckSwiperDisable() && pattern->axis_ == Axis::HORIZONTAL && pattern->isTouchingSwiper_) {
2980 pattern->swiperStartIndex_ = swipingIndex;
2981 pattern->ApplyTurnPageRateToIndicator(turnPageRate);
2982 } else if (!pattern->isAnimating_) {
2983 pattern->turnPageRate_ = 0.0f;
2984 }
2985 }
2986 };
2987 swiperController_->SetTurnPageRateCallback(std::move(turnPageRateCallback));
2988
2989 auto host = GetHost();
2990 CHECK_NULL_VOID(host);
2991 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
2992 CHECK_NULL_VOID(tabsNode);
2993 auto swiperNode = AceType::DynamicCast<FrameNode>(tabsNode->GetTabs());
2994 CHECK_NULL_VOID(swiperNode);
2995 auto eventHub = swiperNode->GetEventHub<SwiperEventHub>();
2996 CHECK_NULL_VOID(eventHub);
2997 if (!animationStartEvent_) {
2998 AnimationStartEvent animationStartEvent =
2999 [weak = WeakClaim(this)](int32_t index, int32_t targetIndex, const AnimationCallbackInfo& info) {
3000 auto pattern = weak.Upgrade();
3001 if (pattern) {
3002 pattern->HandleBottomTabBarAnimation(targetIndex);
3003 }
3004 };
3005 animationStartEvent_ = std::make_shared<AnimationStartEvent>(std::move(animationStartEvent));
3006 eventHub->AddAnimationStartEvent(animationStartEvent_);
3007 }
3008 if (!animationEndEvent_) {
3009 AnimationEndEvent animationEndEvent =
3010 [weak = WeakClaim(this)](int32_t index, const AnimationCallbackInfo& info) {
3011 PerfMonitor::GetPerfMonitor()->End(PerfConstants::APP_TAB_SWITCH, true);
3012 auto pattern = weak.Upgrade();
3013 if (pattern && (NearZero(pattern->turnPageRate_) || NearEqual(pattern->turnPageRate_, 1.0f))) {
3014 pattern->isTouchingSwiper_ = false;
3015 }
3016 pattern->SetMaskAnimationExecuted(false);
3017 };
3018 animationEndEvent_ = std::make_shared<AnimationEndEvent>(std::move(animationEndEvent));
3019 eventHub->AddAnimationEndEvent(animationEndEvent_);
3020 }
3021 }
3022
HandleBottomTabBarAnimation(int32_t index)3023 void TabBarPattern::HandleBottomTabBarAnimation(int32_t index)
3024 {
3025 auto preIndex = GetImageColorOnIndex().value_or(indicator_);
3026 if (preIndex < 0 || preIndex >= static_cast<int32_t>(tabBarStyles_.size())
3027 || index < 0 || index >= static_cast<int32_t>(tabBarStyles_.size())) {
3028 return;
3029 }
3030 if (tabBarStyles_[preIndex] != TabBarStyle::BOTTOMTABBATSTYLE &&
3031 tabBarStyles_[index] != TabBarStyle::BOTTOMTABBATSTYLE) {
3032 return;
3033 }
3034 if (preIndex != index) {
3035 auto host = GetHost();
3036 CHECK_NULL_VOID(host);
3037 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
3038 CHECK_NULL_VOID(tabsNode);
3039 auto tabsPattern = tabsNode->GetPattern<TabsPattern>();
3040 CHECK_NULL_VOID(tabsPattern);
3041 auto onChangeEvent = tabsPattern->GetChangeEvent();
3042 if (onChangeEvent) {
3043 (*onChangeEvent)(preIndex, index);
3044 }
3045 auto onIndexChangeEvent = tabsPattern->GetIndexChangeEvent();
3046 if (onIndexChangeEvent) {
3047 (*onIndexChangeEvent)(index);
3048 }
3049 }
3050 SetMaskAnimationExecuted(true);
3051 }
3052
GetLeftPadding() const3053 float TabBarPattern::GetLeftPadding() const
3054 {
3055 auto host = GetHost();
3056 CHECK_NULL_RETURN(host, 0.0f);
3057 auto geometryNode = host->GetGeometryNode();
3058 CHECK_NULL_RETURN(geometryNode, 0.0f);
3059 if (!geometryNode->GetPadding()) {
3060 return 0.0f;
3061 }
3062 return geometryNode->GetPadding()->left.value_or(0.0f);
3063 }
3064
UpdateAnimationDuration()3065 void TabBarPattern::UpdateAnimationDuration()
3066 {
3067 if (animationDuration_.has_value() && animationDuration_.value() >= 0) {
3068 return;
3069 }
3070
3071 std::optional<int32_t> duration;
3072 auto pipelineContext = PipelineContext::GetCurrentContext();
3073 CHECK_NULL_VOID(pipelineContext);
3074 auto tabTheme = pipelineContext->GetTheme<TabTheme>();
3075 CHECK_NULL_VOID(tabTheme);
3076 auto host = GetHost();
3077 CHECK_NULL_VOID(host);
3078 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
3079 CHECK_NULL_VOID(tabsNode);
3080 auto swiperNode = AceType::DynamicCast<FrameNode>(tabsNode->GetTabs());
3081 CHECK_NULL_VOID(swiperNode);
3082 auto swiperPaintProperty = swiperNode->GetPaintProperty<SwiperPaintProperty>();
3083 CHECK_NULL_VOID(swiperPaintProperty);
3084 duration = static_cast<int32_t>(tabTheme->GetTabContentAnimationDuration());
3085 if ((Container::GreatOrEqualAPIVersion(PlatformVersion::VERSION_ELEVEN) &&
3086 std::count(tabBarStyles_.begin(), tabBarStyles_.end(), TabBarStyle::BOTTOMTABBATSTYLE)) ||
3087 (!animationDuration_.has_value() && Container::LessThanAPIVersion(PlatformVersion::VERSION_ELEVEN))) {
3088 duration = 0;
3089 }
3090 SetAnimationDuration(duration.value());
3091 swiperPaintProperty->UpdateDuration(duration.value());
3092 }
3093
DumpAdvanceInfo()3094 void TabBarPattern::DumpAdvanceInfo()
3095 {
3096 isRTL_ ? DumpLog::GetInstance().AddDesc("isRTL:true") : DumpLog::GetInstance().AddDesc("isRTL:false");
3097 touching_ ? DumpLog::GetInstance().AddDesc("touching:true") : DumpLog::GetInstance().AddDesc("touching:false");
3098 isMaskAnimationByCreate_ ? DumpLog::GetInstance().AddDesc("isMaskAnimationByCreate:true")
3099 : DumpLog::GetInstance().AddDesc("isMaskAnimationByCreate:false");
3100 animationDuration_.has_value()
3101 ? DumpLog::GetInstance().AddDesc("animationDuration:" + std::to_string(animationDuration_.value()))
3102 : DumpLog::GetInstance().AddDesc("animationDuration:null");
3103 isFirstFocus_ ? DumpLog::GetInstance().AddDesc("isFirstFocus:true")
3104 : DumpLog::GetInstance().AddDesc("isFirstFocus:false");
3105 isTouchingSwiper_ ? DumpLog::GetInstance().AddDesc("isTouchingSwiper:true")
3106 : DumpLog::GetInstance().AddDesc("isTouchingSwiper:false");
3107 isAnimating_ ? DumpLog::GetInstance().AddDesc("isAnimating:true")
3108 : DumpLog::GetInstance().AddDesc("isAnimating:false");
3109 changeByClick_ ? DumpLog::GetInstance().AddDesc("changeByClick:true")
3110 : DumpLog::GetInstance().AddDesc("changeByClick:false");
3111 DumpLog::GetInstance().AddDesc("indicator:" + std::to_string(indicator_));
3112 DumpLog::GetInstance().AddDesc("focusIndicator:" + std::to_string(focusIndicator_));
3113 DumpLog::GetInstance().AddDesc("currentIndicatorOffset:" + std::to_string(currentIndicatorOffset_));
3114 DumpLog::GetInstance().AddDesc("turnPageRate:" + std::to_string(turnPageRate_));
3115 DumpLog::GetInstance().AddDesc("swiperStartIndex:" + std::to_string(swiperStartIndex_));
3116 DumpLog::GetInstance().AddDesc("scrollMargin:" + std::to_string(scrollMargin_));
3117 std::string regionString = std::string("region:");
3118 for (auto item : gradientRegions_) {
3119 item ? regionString.append("true ") : regionString.append("false ");
3120 }
3121 DumpLog::GetInstance().AddDesc(regionString);
3122 switch (axis_) {
3123 case Axis::NONE: {
3124 DumpLog::GetInstance().AddDesc("Axis:NONE");
3125 break;
3126 }
3127 case Axis::HORIZONTAL: {
3128 DumpLog::GetInstance().AddDesc("Axis:HORIZONTAL");
3129 break;
3130 }
3131 case Axis::FREE: {
3132 DumpLog::GetInstance().AddDesc("Axis:FREE");
3133 break;
3134 }
3135 case Axis::VERTICAL: {
3136 DumpLog::GetInstance().AddDesc("Axis:VERTICAL");
3137 break;
3138 }
3139 default: {
3140 break;
3141 }
3142 }
3143 }
3144
ContentWillChange(int32_t comingIndex)3145 bool TabBarPattern::ContentWillChange(int32_t comingIndex)
3146 {
3147 auto swiperPattern = GetSwiperPattern();
3148 CHECK_NULL_RETURN(swiperPattern, true);
3149 int32_t currentIndex = swiperPattern->GetCurrentIndex();
3150 return ContentWillChange(currentIndex, comingIndex);
3151 }
3152
ContentWillChange(int32_t currentIndex,int32_t comingIndex)3153 bool TabBarPattern::ContentWillChange(int32_t currentIndex, int32_t comingIndex)
3154 {
3155 auto host = GetHost();
3156 CHECK_NULL_RETURN(host, true);
3157 auto tabsNode = AceType::DynamicCast<TabsNode>(host->GetParent());
3158 CHECK_NULL_RETURN(tabsNode, true);
3159 auto tabsPattern = tabsNode->GetPattern<TabsPattern>();
3160 CHECK_NULL_RETURN(tabsPattern, true);
3161 if (tabsPattern->GetInterceptStatus() && currentIndex != comingIndex) {
3162 auto ret = tabsPattern->OnContentWillChange(currentIndex, comingIndex);
3163 return ret.has_value() ? ret.value() : true;
3164 }
3165 return true;
3166 }
3167
ParseTabsIsRtl()3168 bool TabBarPattern::ParseTabsIsRtl()
3169 {
3170 auto host = GetHost();
3171 CHECK_NULL_RETURN(host, false);
3172 auto tabsNode = AceType::DynamicCast<FrameNode>(host->GetParent());
3173 CHECK_NULL_RETURN(tabsNode, false);
3174 auto tabLayoutProperty = AceType::DynamicCast<TabsLayoutProperty>(tabsNode->GetLayoutProperty());
3175 CHECK_NULL_RETURN(tabLayoutProperty, false);
3176 auto isRTL = tabLayoutProperty->GetNonAutoLayoutDirection() == TextDirection::RTL;
3177 return isRTL;
3178 }
3179
IsValidIndex(int32_t index)3180 bool TabBarPattern::IsValidIndex(int32_t index)
3181 {
3182 if (index < 0 || index >= static_cast<int32_t>(tabBarStyles_.size()) ||
3183 tabBarStyles_[index] != TabBarStyle::SUBTABBATSTYLE || index >= static_cast<int32_t>(selectedModes_.size()) ||
3184 selectedModes_[index] != SelectedMode::INDICATOR) {
3185 return false;
3186 }
3187 return true;
3188 }
3189
GetLoopIndex(int32_t originalIndex) const3190 int32_t TabBarPattern::GetLoopIndex(int32_t originalIndex) const
3191 {
3192 auto host = GetHost();
3193 CHECK_NULL_RETURN(host, originalIndex);
3194 auto totalCount = host->TotalChildCount() - MASK_COUNT;
3195 if (totalCount <= 0) {
3196 return originalIndex;
3197 }
3198 return originalIndex % totalCount;
3199 }
3200 } // namespace OHOS::Ace::NG
3201