| b69ab31 | | | 1 | /** |
| b69ab31 | | | 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| b69ab31 | | | 3 | * |
| b69ab31 | | | 4 | * This source code is licensed under the MIT license found in the |
| b69ab31 | | | 5 | * LICENSE file in the root directory of this source tree. |
| b69ab31 | | | 6 | */ |
| b69ab31 | | | 7 | |
| b69ab31 | | | 8 | import type {ValueObject} from 'immutable'; |
| b69ab31 | | | 9 | |
| b69ab31 | | | 10 | const IS_RECORD_SYMBOL = '@@__IMMUTABLE_RECORD__@@'; |
| b69ab31 | | | 11 | |
| b69ab31 | | | 12 | /** Wraps a ValueObject so it self-updates on equals. */ |
| b69ab31 | | | 13 | export class SelfUpdate<T extends ValueObject> implements ValueObject { |
| b69ab31 | | | 14 | inner: T; |
| b69ab31 | | | 15 | |
| b69ab31 | | | 16 | /** |
| b69ab31 | | | 17 | * Tell Recoil to not deepFreeze (Object.seal) this object. This is needed |
| b69ab31 | | | 18 | * since we might update the `inner` field. We didn't break Recoil |
| b69ab31 | | | 19 | * assumptions since we maintain the same "value" of the object. |
| b69ab31 | | | 20 | * |
| b69ab31 | | | 21 | * See https://github.com/facebookexperimental/Recoil/blob/0.7.7/packages/shared/util/Recoil_deepFreezeValue.js#L42 |
| b69ab31 | | | 22 | * Recoil tests `value[IS_RECORD_SYMBOL] != null`. |
| b69ab31 | | | 23 | * |
| b69ab31 | | | 24 | * For immutable.js, it actually checks the boolean value. |
| b69ab31 | | | 25 | * See https://github.com/immutable-js/immutable-js/blob/v4.3.4/src/predicates/isRecord.js |
| b69ab31 | | | 26 | * Immutable.js uses `Boolean(maybeRecord && maybeRecord[IS_RECORD_SYMBOL])`. |
| b69ab31 | | | 27 | * |
| b69ab31 | | | 28 | * By using `false`, this tricks Recoil to treat us as an immutable value, |
| b69ab31 | | | 29 | * while does not break Immutable.js' type checking. |
| b69ab31 | | | 30 | */ |
| b69ab31 | | | 31 | [IS_RECORD_SYMBOL] = false; |
| b69ab31 | | | 32 | |
| b69ab31 | | | 33 | constructor(inner: T) { |
| b69ab31 | | | 34 | this.inner = inner; |
| b69ab31 | | | 35 | } |
| b69ab31 | | | 36 | |
| b69ab31 | | | 37 | hashCode(): number { |
| b69ab31 | | | 38 | return this.inner.hashCode() + 1; |
| b69ab31 | | | 39 | } |
| b69ab31 | | | 40 | |
| b69ab31 | | | 41 | equals(other: unknown): boolean { |
| b69ab31 | | | 42 | if (!(other instanceof SelfUpdate)) { |
| b69ab31 | | | 43 | return false; |
| b69ab31 | | | 44 | } |
| b69ab31 | | | 45 | if (this === other) { |
| b69ab31 | | | 46 | return true; |
| b69ab31 | | | 47 | } |
| b69ab31 | | | 48 | const otherInner = other.inner; |
| b69ab31 | | | 49 | const result = this.inner.equals(otherInner); |
| b69ab31 | | | 50 | if (result && this.inner !== otherInner) { |
| b69ab31 | | | 51 | this.inner = otherInner; |
| b69ab31 | | | 52 | } |
| b69ab31 | | | 53 | return result; |
| b69ab31 | | | 54 | } |
| b69ab31 | | | 55 | } |