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 public static readonly MAKE_OBSERVED_PROXY = Symbol('__make_observed_proxy'); 22 23 static get(target: Object): any { 24 if (!target || typeof target !== 'object') { 25 stateMgmtConsole.warn(`makeObserved target is not a valid object, return target directly`); 26 return { [RefInfo.MAKE_OBSERVED_PROXY]: target }; 27 } 28 // makeObserved does not support @Observed, @ObservedV2/@Trace class or makeObserved proxy, will return target directly 29 if (ObservedObject.IsObservedObject(target) || ObserveV2.IsObservedObjectV2(target) || ObserveV2.IsMakeObserved(target)) { 30 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`); 31 return { [RefInfo.MAKE_OBSERVED_PROXY]: target }; 32 } 33 let ret = RefInfo.obj2ref.get(target); 34 if (!ret) { 35 if (Array.isArray(target) || SendableType.isArray(target)) { 36 ret = { [RefInfo.MAKE_OBSERVED_PROXY]: new Proxy(target, RefInfo.arrayProxy) }; 37 } else if (target instanceof Set || SendableType.isSet(target) || 38 target instanceof Map || SendableType.isMap(target)) { 39 ret = { [RefInfo.MAKE_OBSERVED_PROXY]: new Proxy(target, RefInfo.setMapProxy) }; 40 } else { 41 ret = { [RefInfo.MAKE_OBSERVED_PROXY]: new Proxy(target, RefInfo.objectProxy) }; 42 } 43 RefInfo.obj2ref.set(target, ret); 44 } 45 return ret; 46 } 47}