1 /*
2 * Copyright (c) 2021-2025 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 "frameworks/bridge/declarative_frontend/jsview/js_text_clock.h"
17
18 #include <regex>
19 #include <string>
20
21 #include "base/log/ace_scoring_log.h"
22 #include "base/utils/string_utils.h"
23 #include "bridge/declarative_frontend/jsview/js_view_abstract.h"
24 #include "bridge/declarative_frontend/jsview/js_view_common_def.h"
25 #include "bridge/declarative_frontend/jsview/js_utils.h"
26 #include "bridge/declarative_frontend/jsview/models/text_clock_model_impl.h"
27 #include "core/components/common/properties/text_style.h"
28 #include "core/components/common/properties/text_style_parser.h"
29 #include "core/components_ng/base/view_stack_processor.h"
30 #include "core/components_ng/pattern/text_clock/text_clock_model.h"
31 #include "core/components_ng/pattern/text_clock/text_clock_model_ng.h"
32 #include "frameworks/core/components/text_clock/text_clock_theme.h"
33
34 namespace OHOS::Ace {
35
36 std::unique_ptr<TextClockModel> TextClockModel::instance_ = nullptr;
37 std::mutex TextClockModel::mutex_;
38 const char TEXTCLOCK_DATE_TIME_OPTIONS_HOUR[] = "hour";
39 const std::string TEXTCLOCK_DATE_TIME_OPTIONS_TWO_DIGIT_VAL = "2-digit";
40 const std::string TEXTCLOCK_DATE_TIME_OPTIONS_NUMERIC_VAL = "numeric";
41
GetInstance()42 TextClockModel* TextClockModel::GetInstance()
43 {
44 if (!instance_) {
45 std::lock_guard<std::mutex> lock(mutex_);
46 if (!instance_) {
47 #ifdef NG_BUILD
48 instance_.reset(new NG::TextClockModelNG());
49 #else
50 if (Container::IsCurrentUseNewPipeline()) {
51 instance_.reset(new NG::TextClockModelNG());
52 } else {
53 instance_.reset(new Framework::TextClockModelImpl());
54 }
55 #endif
56 }
57 }
58 return instance_.get();
59 }
60 } // namespace OHOS::Ace
61
62 namespace OHOS::Ace::Framework {
63
64 namespace {
65 const std::vector<FontStyle> FONT_STYLES = { FontStyle::NORMAL, FontStyle::ITALIC };
66 const std::string DEFAULT_FORMAT_API_TEN = "hms";
67 constexpr int32_t HOURS_WEST_LOWER_LIMIT = -14;
68 constexpr int32_t HOURS_WEST_UPPER_LIMIT = 12;
69 constexpr float HOURS_WEST[] = { 9.5f, 3.5f, -3.5f, -4.5f, -5.5f, -5.75f, -6.5f, -9.5f, -10.5f, -12.75f };
70
HoursWestIsValid(int32_t hoursWest)71 bool HoursWestIsValid(int32_t hoursWest)
72 {
73 return !(hoursWest < HOURS_WEST_LOWER_LIMIT || hoursWest > HOURS_WEST_UPPER_LIMIT);
74 }
75
GetHoursWest(float hoursWest)76 float GetHoursWest(float hoursWest)
77 {
78 if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_ELEVEN)) {
79 for (float i : HOURS_WEST) {
80 if (NearEqual(hoursWest, i)) {
81 return hoursWest;
82 }
83 }
84 }
85
86 return int32_t(hoursWest);
87 }
88 } // namespace
89
Create(const JSCallbackInfo & info)90 void JSTextClock::Create(const JSCallbackInfo& info)
91 {
92 auto controller = TextClockModel::GetInstance()->Create();
93 if (info.Length() < 1 || !info[0]->IsObject()) {
94 return;
95 }
96 JSRef<JSObject> optionsObject = JSRef<JSObject>::Cast(info[0]);
97 JSRef<JSVal> hourWestVal = optionsObject->GetProperty("timeZoneOffset");
98 if (hourWestVal->IsNumber() && HoursWestIsValid(hourWestVal->ToNumber<int32_t>())) {
99 float hourWest = GetHoursWest(hourWestVal->ToNumber<float>());
100 TextClockModel::GetInstance()->SetHoursWest(hourWest);
101 } else {
102 TextClockModel::GetInstance()->SetHoursWest(NAN);
103 }
104 auto controllerObj = optionsObject->GetProperty("controller");
105 if (!controllerObj->IsUndefined() && !controllerObj->IsNull() && controllerObj->IsObject()) {
106 auto* jsController = JSRef<JSObject>::Cast(controllerObj)->Unwrap<JSTextClockController>();
107 if (jsController != nullptr) {
108 jsController->SetInstanceId(Container::CurrentId());
109 if (controller) {
110 jsController->AddController(controller);
111 }
112 }
113 return;
114 }
115 }
116
JSBind(BindingTarget globalObj)117 void JSTextClock::JSBind(BindingTarget globalObj)
118 {
119 JSClass<JSTextClock>::Declare("TextClock");
120 MethodOptions opt = MethodOptions::NONE;
121 JSClass<JSTextClock>::StaticMethod("create", &JSTextClock::Create, opt);
122 JSClass<JSTextClock>::StaticMethod("format", &JSTextClock::SetFormat, opt);
123 JSClass<JSTextClock>::StaticMethod("onDateChange", &JSTextClock::JsOnDateChange, opt);
124 JSClass<JSTextClock>::StaticMethod("onClick", &JSInteractableView::JsOnClick);
125 JSClass<JSTextClock>::StaticMethod("onTouch", &JSInteractableView::JsOnTouch);
126 JSClass<JSTextClock>::StaticMethod("onKeyEvent", &JSInteractableView::JsOnKey);
127 JSClass<JSTextClock>::StaticMethod("onDeleteEvent", &JSInteractableView::JsOnDelete);
128 JSClass<JSTextClock>::StaticMethod("onAttach", &JSInteractableView::JsOnAttach);
129 JSClass<JSTextClock>::StaticMethod("onAppear", &JSInteractableView::JsOnAppear);
130 JSClass<JSTextClock>::StaticMethod("onDetach", &JSInteractableView::JsOnDetach);
131 JSClass<JSTextClock>::StaticMethod("onDisAppear", &JSInteractableView::JsOnDisAppear);
132 JSClass<JSTextClock>::StaticMethod("fontColor", &JSTextClock::SetTextColor, opt);
133 JSClass<JSTextClock>::StaticMethod("fontSize", &JSTextClock::SetFontSize, opt);
134 JSClass<JSTextClock>::StaticMethod("fontWeight", &JSTextClock::SetFontWeight, opt);
135 JSClass<JSTextClock>::StaticMethod("fontStyle", &JSTextClock::SetFontStyle, opt);
136 JSClass<JSTextClock>::StaticMethod("fontFamily", &JSTextClock::SetFontFamily, opt);
137 JSClass<JSTextClock>::StaticMethod("textShadow", &JSTextClock::SetTextShadow, opt);
138 JSClass<JSTextClock>::StaticMethod("fontFeature", &JSTextClock::SetFontFeature, opt);
139 JSClass<JSTextClock>::StaticMethod("dateTimeOptions", &JSTextClock::SetDateTimeOptions, opt);
140 JSClass<JSTextClock>::InheritAndBind<JSViewAbstract>(globalObj);
141 }
142
SetTextColor(const JSCallbackInfo & info)143 void JSTextClock::SetTextColor(const JSCallbackInfo& info)
144 {
145 if (info.Length() < 1) {
146 return;
147 }
148 Color textColor;
149 if (!ParseJsColor(info[0], textColor)) {
150 TextClockModel::GetInstance()->ResetTextColor();
151 return;
152 }
153 TextClockModel::GetInstance()->SetTextColor(textColor);
154 }
155
SetFontSize(const JSCallbackInfo & info)156 void JSTextClock::SetFontSize(const JSCallbackInfo& info)
157 {
158 if (info.Length() < 1) {
159 return;
160 }
161 auto pipelineContext = PipelineContext::GetCurrentContext();
162 CHECK_NULL_VOID(pipelineContext);
163 auto theme = pipelineContext->GetTheme<TextClockTheme>();
164 CHECK_NULL_VOID(theme);
165
166 CalcDimension fontSize;
167 if (!ParseJsDimensionFpNG(info[0], fontSize, false)) {
168 fontSize = theme->GetTextStyleClock().GetFontSize();
169 }
170
171 if (fontSize.IsNegative() || fontSize.Unit() == DimensionUnit::PERCENT) {
172 auto pipelineContext = PipelineContext::GetCurrentContext();
173 CHECK_NULL_VOID(pipelineContext);
174 auto theme = pipelineContext->GetTheme<TextClockTheme>();
175 CHECK_NULL_VOID(theme);
176 fontSize = theme->GetTextStyleClock().GetFontSize();
177 }
178
179 TextClockModel::GetInstance()->SetFontSize(fontSize);
180 }
181
SetFontWeight(const JSCallbackInfo & info)182 void JSTextClock::SetFontWeight(const JSCallbackInfo& info)
183 {
184 if (info.Length() < 1) {
185 return;
186 }
187 RefPtr<TextClockTheme> textTheme = GetTheme<TextClockTheme>();
188 CHECK_NULL_VOID(textTheme);
189 const auto& fontWeight = info[0];
190 if (fontWeight->IsUndefined()) {
191 TextClockModel::GetInstance()->SetFontWeight(textTheme->GetTextStyleClock().GetFontWeight());
192 return;
193 }
194
195 if (!fontWeight->IsNull()) {
196 std::string weight;
197 if (fontWeight->IsNumber()) {
198 weight = std::to_string(fontWeight->ToNumber<int32_t>());
199 } else {
200 ParseJsString(fontWeight, weight);
201 }
202 TextClockModel::GetInstance()->SetFontWeight(ConvertStrToFontWeight(weight));
203 } else {
204 TextClockModel::GetInstance()->SetFontWeight(textTheme->GetTextStyleClock().GetFontWeight());
205 }
206 }
207
SetFontStyle(int32_t value)208 void JSTextClock::SetFontStyle(int32_t value)
209 {
210 if (value < 0 || value >= static_cast<int32_t>(FONT_STYLES.size())) {
211 return;
212 }
213 TextClockModel::GetInstance()->SetItalicFontStyle(FONT_STYLES[value]);
214 }
215
SetFontFamily(const JSCallbackInfo & info)216 void JSTextClock::SetFontFamily(const JSCallbackInfo& info)
217 {
218 if (info.Length() < 1) {
219 return;
220 }
221 std::vector<std::string> fontFamilies;
222 if (!ParseJsFontFamilies(info[0], fontFamilies)) {
223 return;
224 }
225 TextClockModel::GetInstance()->SetFontFamily(fontFamilies);
226 }
227
SetFormat(const JSCallbackInfo & info)228 void JSTextClock::SetFormat(const JSCallbackInfo& info)
229 {
230 if (info.Length() < 1) {
231 return;
232 }
233 if (!info[0]->IsString()) {
234 if (Container::GreatOrEqualAPITargetVersion(PlatformVersion::VERSION_ELEVEN)) {
235 TextClockModel::GetInstance()->SetFormat("");
236 } else {
237 TextClockModel::GetInstance()->SetFormat(DEFAULT_FORMAT_API_TEN);
238 }
239 return;
240 }
241
242 auto format = info[0]->ToString();
243 if (Container::LessThanAPITargetVersion(PlatformVersion::VERSION_ELEVEN)) {
244 std::regex pattern(
245 R"(^([Yy]*[_|\W\s]*[M]*[_|\W\s]*[d]*[_|\W\s]*[D]*[_|\W\s]*[Hh]*[_|\W\s]*[m]*[_|\W\s]*[s]*[_|\W\s]*[S]*)$)");
246 if (format.empty() || !StringUtils::IsAscii(format) || !std::regex_match(format, pattern)) {
247 TextClockModel::GetInstance()->SetFormat(DEFAULT_FORMAT_API_TEN);
248 return;
249 }
250 }
251
252 TextClockModel::GetInstance()->SetFormat(format);
253 }
254
SetTextShadow(const JSCallbackInfo & info)255 void JSTextClock::SetTextShadow(const JSCallbackInfo& info)
256 {
257 if (info.Length() < 1) {
258 return;
259 }
260 std::vector<Shadow> shadows;
261 ParseTextShadowFromShadowObject(info[0], shadows);
262 if (!shadows.empty()) {
263 TextClockModel::GetInstance()->SetTextShadow(shadows);
264 }
265 }
266
SetFontFeature(const JSCallbackInfo & info)267 void JSTextClock::SetFontFeature(const JSCallbackInfo& info)
268 {
269 if (info.Length() < 1) {
270 return;
271 }
272 if (!info[0]->IsString()) {
273 return;
274 }
275
276 std::string fontFeatureSettings = info[0]->ToString();
277 TextClockModel::GetInstance()->SetFontFeature(ParseFontFeatureSettings(fontFeatureSettings));
278 }
279
JsOnDateChange(const JSCallbackInfo & info)280 void JSTextClock::JsOnDateChange(const JSCallbackInfo& info)
281 {
282 if (!info[0]->IsFunction()) {
283 return;
284 }
285
286 auto jsFunc = AceType::MakeRefPtr<JsFunction>(JSRef<JSObject>(), JSRef<JSFunc>::Cast(info[0]));
287 WeakPtr<NG::FrameNode> targetNode = AceType::WeakClaim(NG::ViewStackProcessor::GetInstance()->GetMainFrameNode());
288 auto onChange = [execCtx = info.GetExecutionContext(), func = std::move(jsFunc), node = targetNode](
289 const std::string& value) {
290 JAVASCRIPT_EXECUTION_SCOPE_WITH_CHECK(execCtx);
291 ACE_SCORING_EVENT("TextClock.onDateChange");
292 PipelineContext::SetCallBackNode(node);
293 auto newJSVal = JSRef<JSVal>::Make(ToJSValue(value));
294 func->ExecuteJS(1, &newJSVal);
295 };
296 TextClockModel::GetInstance()->SetOnDateChange(std::move(onChange));
297 }
298
JSBind(BindingTarget globalObj)299 void JSTextClockController::JSBind(BindingTarget globalObj)
300 {
301 JSClass<JSTextClockController>::Declare("TextClockController");
302 JSClass<JSTextClockController>::Method("start", &JSTextClockController::Start);
303 JSClass<JSTextClockController>::Method("stop", &JSTextClockController::Stop);
304 JSClass<JSTextClockController>::Bind(
305 globalObj, JSTextClockController::Constructor, JSTextClockController::Destructor);
306 }
307
Constructor(const JSCallbackInfo & args)308 void JSTextClockController::Constructor(const JSCallbackInfo& args)
309 {
310 auto scroller = Referenced::MakeRefPtr<JSTextClockController>();
311 scroller->IncRefCount();
312 args.SetReturnValue(Referenced::RawPtr(scroller));
313 }
314
Destructor(JSTextClockController * scroller)315 void JSTextClockController::Destructor(JSTextClockController* scroller)
316 {
317 if (scroller != nullptr) {
318 scroller->DecRefCount();
319 }
320 }
321
Start()322 void JSTextClockController::Start()
323 {
324 ContainerScope scope(instanceId_);
325 if (!controller_.empty()) {
326 for (auto& i : controller_) {
327 i->Start();
328 }
329 }
330 }
331
Stop()332 void JSTextClockController::Stop()
333 {
334 ContainerScope scope(instanceId_);
335 if (!controller_.empty()) {
336 for (auto& i : controller_) {
337 i->Stop();
338 }
339 }
340 }
341
removeController(const RefPtr<TextClockController> & controller)342 void JSTextClockController::removeController(const RefPtr<TextClockController>& controller)
343 {
344 for (auto it = controller_.begin(); it != controller_.end(); it++) {
345 if (controller == *it) {
346 controller_.erase(it);
347 break;
348 }
349 }
350 }
351
SetDateTimeOptions(const JSCallbackInfo & info)352 void JSTextClock::SetDateTimeOptions(const JSCallbackInfo& info)
353 {
354 JSRef<JSObject> paramObject;
355 ZeroPrefixType hourType = ZeroPrefixType::AUTO;
356 if (info.Length() >= 1 && info[0]->IsObject()) {
357 paramObject = JSRef<JSObject>::Cast(info[0]);
358 auto hourValue = paramObject->GetProperty(TEXTCLOCK_DATE_TIME_OPTIONS_HOUR);
359 if (hourValue->IsString()) {
360 std::string hour = hourValue->ToString();
361 if (hour == TEXTCLOCK_DATE_TIME_OPTIONS_TWO_DIGIT_VAL) {
362 hourType = ZeroPrefixType::SHOW;
363 } else if (hour == TEXTCLOCK_DATE_TIME_OPTIONS_NUMERIC_VAL) {
364 hourType = ZeroPrefixType::HIDE;
365 }
366 }
367 }
368 TextClockModel::GetInstance()->SetDateTimeOptions(hourType);
369 }
370 } // namespace OHOS::Ace::Framework
371