1 /*
2  * Copyright (c) 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 "frameworks/bridge/declarative_frontend/jsview/js_scope_util.h"
17 
18 #include "base/memory/referenced.h"
19 #include "frameworks/core/common/container.h"
20 
21 namespace OHOS::Ace::Framework {
22 static thread_local std::vector<int32_t> restoreInstanceIds_;
23 
JSScopeUtil()24 JSScopeUtil::JSScopeUtil() {}
25 
JSBind(BindingTarget globalObj)26 void JSScopeUtil::JSBind(BindingTarget globalObj)
27 {
28     JSClass<JSScopeUtil>::Declare("__JSScopeUtil__");
29     JSClass<JSScopeUtil>::StaticMethod("syncInstanceId", &JSScopeUtil::SyncInstanceId);
30     JSClass<JSScopeUtil>::StaticMethod("restoreInstanceId", &JSScopeUtil::RestoreInstanceId);
31     JSClass<JSScopeUtil>::Bind(globalObj);
32 }
33 
SyncInstanceId(const JSCallbackInfo & info)34 void JSScopeUtil::SyncInstanceId(const JSCallbackInfo& info)
35 {
36     if (info.Length() < 1) {
37         return;
38     }
39 
40     if (!info[0]->IsNumber()) {
41         return;
42     }
43 
44     restoreInstanceIds_.emplace_back(Container::CurrentId());
45     int32_t instanceId = info[0]->ToNumber<int32_t>();
46     ContainerScope::UpdateCurrent(instanceId);
47 }
48 
RestoreInstanceId(const JSCallbackInfo & info)49 void JSScopeUtil::RestoreInstanceId(const JSCallbackInfo& info)
50 {
51     if (restoreInstanceIds_.empty()) {
52         ContainerScope::UpdateCurrent(INSTANCE_ID_UNDEFINED);
53         return;
54     }
55     ContainerScope::UpdateCurrent(restoreInstanceIds_.back());
56     restoreInstanceIds_.pop_back();
57 }
58 } // namespace OHOS::Ace::Framework