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()22std::vector<std::string> JsForEachFunction::ExecuteIdentityMapper() 23 { 24 std::vector<std::string> result; 25 26 JSRef<JSVal> jsKeys; 27 if (!jsIdentityMapperFunc_.IsEmpty()) { 28 JSRef<JSVal> argv[] = { jsIdentityMapperFunc_.Lock() }; 29 jsKeys = JsFunction::ExecuteJS(1, argv); 30 if (jsKeys.IsEmpty()) { 31 return result; 32 } 33 } 34 35 JSRef<JSArray> jsKeysArr; 36 if (!jsKeys.IsEmpty()) { 37 if (jsKeys->IsArray()) { 38 jsKeysArr = JSRef<JSArray>::Cast(jsKeys); 39 } 40 } else { 41 auto jsThis = This(); 42 if (jsThis->IsArray()) { 43 jsKeysArr = JSRef<JSArray>::Cast(jsThis); 44 } else { 45 return result; 46 } 47 } 48 int length = static_cast<int>(jsKeysArr->Length()); 49 50 for (int i = 0; i < length; i++) { 51 if (!jsKeys.IsEmpty()) { 52 JSRef<JSVal> jsKey = jsKeysArr->GetValueAt(i); 53 54 if (!jsKey->IsString() && !jsKey->IsNumber()) { 55 continue; 56 } 57 58 std::string key(jsKey->ToString()); 59 result.emplace_back(key.c_str()); 60 } else { 61 result.emplace_back(std::to_string(i)); 62 } 63 } 64 65 return result; 66 } 67 ExecuteBuilderForIndex(int32_t index)68void JsForEachFunction::ExecuteBuilderForIndex(int32_t index) 69 { 70 // indexed item 71 auto jsThis = This(); 72 if (jsThis->IsArray()) { 73 JSRef<JSArray> jsArray = JSRef<JSArray>::Cast(jsThis); 74 JSRef<JSVal> params[2]; 75 params[0] = jsArray->GetValueAt(index); 76 params[1] = JSRef<JSVal>::Make(ToJSValue(index)); 77 jsViewMapperFunc_.Lock()->Call(This(), 2, params); // 2: array size of params 78 } 79 } 80 81 } // namespace OHOS::Ace::Framework 82