• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2024 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
16class RefInfo {
17  private static obj2ref: WeakMap<object, object> = new WeakMap();
18  private static setMapProxy: SetMapProxyHandler = new SetMapProxyHandler(true);
19  private static arrayProxy: ArrayProxyHandler = new ArrayProxyHandler(true);
20  private static objectProxy: ObjectProxyHandler = new ObjectProxyHandler(true);
21
22  static get(target: Object): any {
23    if (!target || typeof target !== 'object') {
24      stateMgmtConsole.warn(`makeObserved target is not a valid object, return target directly`);
25      return { proxy: target };
26    }
27    // makeObserved does not support @Observed, @ObservedV2/@Trace class or makeObserved proxy, will return target directly
28    if (ObservedObject.IsObservedObject(target) || ObserveV2.IsObservedObjectV2(target) || ObserveV2.IsMakeObserved(target)) {
29      stateMgmtConsole.warn(`${target.constructor.name} is Observed ${ObservedObject.IsObservedObject(target)}, IsObservedV2 ${ObserveV2.IsObservedObjectV2(target)} or makeObserved proxy value ${ObserveV2.IsMakeObserved(target)}. makeObserved will stop work`);
30      return { proxy: target };
31    }
32    let ret = RefInfo.obj2ref.get(target);
33    if (!ret) {
34      if (Array.isArray(target) || SendableType.isArray(target)) {
35        ret = { proxy: new Proxy(target, RefInfo.arrayProxy) };
36      } else if (target instanceof Set || SendableType.isSet(target) ||
37                 target instanceof Map || SendableType.isMap(target)) {
38        ret = { proxy: new Proxy(target, RefInfo.setMapProxy) };
39      } else {
40        ret = { proxy: new Proxy(target, RefInfo.objectProxy) };
41      }
42      RefInfo.obj2ref.set(target, ret);
43    }
44    return ret;
45  }
46}