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<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 continue; 50 } 51 52 std::string key(jsKey->ToString()); 53 result.emplace_back(key.c_str()); 54 } else { 55 result.emplace_back(std::to_string(i)); 56 } 57 } 58 59 return result; 60 } 61 ExecuteBuilderForIndex(int32_t index)62void JsForEachFunction::ExecuteBuilderForIndex(int32_t index) 63 { 64 // indexed item 65 JSRef<JSArray> jsArray = JSRef<JSArray>::Cast(jsThis_.Lock()); 66 JSRef<JSVal> params[2]; 67 params[0] = jsArray->GetValueAt(index); 68 params[1] = JSRef<JSVal>::Make(ToJSValue(index)); 69 jsViewMapperFunc_.Lock()->Call(jsThis_.Lock(), 2, params); 70 } 71 72 } // namespace OHOS::Ace::Framework 73