• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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/engine/functions/js_foreach_function.h"
17 
18 #include "frameworks/bridge/declarative_frontend/jsview/js_view.h"
19 
20 namespace OHOS::Ace::Framework {
21 
ExecuteIdentityMapper()22 std::vector<std::string> JsForEachFunction::ExecuteIdentityMapper()
23 {
24     std::vector<std::string> result;
25 
26     JSRef<JSObject> jsKeys;
27     if (!jsIdentityMapperFunc_.IsEmpty()) {
28         JSRef<JSVal> argv[] = { jsIdentityMapperFunc_.Lock() };
29         jsKeys = JSRef<JSObject>::Cast(JsFunction::ExecuteJS(1, argv));
30 
31         if (jsKeys.IsEmpty()) {
32             return result;
33         }
34     }
35 
36     JSRef<JSArray> jsKeysArr;
37     if (!jsKeys.IsEmpty()) {
38         jsKeysArr = JSRef<JSArray>::Cast(jsKeys);
39     } else {
40         jsKeysArr = JSRef<JSArray>::Cast(jsThis_.Lock());
41     }
42     int length = static_cast<int>(jsKeysArr->Length());
43 
44     for (int i = 0; i < length; i++) {
45         if (!jsKeys.IsEmpty()) {
46             JSRef<JSVal> jsKey = jsKeysArr->GetValueAt(i);
47 
48             if (!jsKey->IsString() && !jsKey->IsNumber()) {
49                 LOGE("ForEach Item with invalid identifier.........");
50                 continue;
51             }
52 
53             std::string key(jsKey->ToString());
54             result.emplace_back(key.c_str());
55         } else {
56             result.emplace_back(std::to_string(i));
57         }
58     }
59 
60     return result;
61 }
62 
ExecuteBuilderForIndex(int32_t index)63 void JsForEachFunction::ExecuteBuilderForIndex(int32_t index)
64 {
65     LOGD("ExecuteBuilderForIndex: start, index %{public}d", index);
66     // indexed item
67     JSRef<JSArray> jsArray = JSRef<JSArray>::Cast(jsThis_.Lock());
68     JSRef<JSVal> params[2];
69     params[0] = jsArray->GetValueAt(index);
70     params[1] = JSRef<JSVal>::Make(ToJSValue(index));
71     jsViewMapperFunc_.Lock()->Call(jsThis_.Lock(), 2, params);
72 }
73 
74 } // namespace OHOS::Ace::Framework
75