fix: empty snapLines arrays would cause re-render (#7454)

Co-authored-by: Lynda Lin <lynda.lin@optoma.com>
Co-authored-by: dwelle <5153846+dwelle@users.noreply.github.com>
This commit is contained in:
Lynda Lin 2023-12-18 20:42:17 +08:00 committed by GitHub
parent 7bd6496854
commit 2a0fe2584e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
7 changed files with 139 additions and 64 deletions

View file

@ -769,6 +769,24 @@ export const queryFocusableElements = (container: HTMLElement | null) => {
: [];
};
/** use as a fallback after identity check (for perf reasons) */
const _defaultIsShallowComparatorFallback = (a: any, b: any): boolean => {
// consider two empty arrays equal
if (
Array.isArray(a) &&
Array.isArray(b) &&
a.length === 0 &&
b.length === 0
) {
return true;
}
return a === b;
};
/**
* Returns whether object/array is shallow equal.
* Considers empty object/arrays as equal (whether top-level or second-level).
*/
export const isShallowEqual = <
T extends Record<string, any>,
K extends readonly unknown[],
@ -796,10 +814,12 @@ export const isShallowEqual = <
if (comparators && Array.isArray(comparators)) {
for (const key of comparators) {
const ret = objA[key] === objB[key];
const ret =
objA[key] === objB[key] ||
_defaultIsShallowComparatorFallback(objA[key], objB[key]);
if (!ret) {
if (debug) {
console.info(
console.warn(
`%cisShallowEqual: ${key} not equal ->`,
"color: #8B4000",
objA[key],
@ -818,9 +838,11 @@ export const isShallowEqual = <
)?.[key as keyof T];
const ret = comparator
? comparator(objA[key], objB[key])
: objA[key] === objB[key];
: objA[key] === objB[key] ||
_defaultIsShallowComparatorFallback(objA[key], objB[key]);
if (!ret && debug) {
console.info(
console.warn(
`%cisShallowEqual: ${key} not equal ->`,
"color: #8B4000",
objA[key],
@ -960,3 +982,13 @@ export const cloneJSON = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));
export const isFiniteNumber = (value: any): value is number => {
return typeof value === "number" && Number.isFinite(value);
};
export const updateStable = <T extends any[] | Record<string, any>>(
prevValue: T,
nextValue: T,
) => {
if (isShallowEqual(prevValue, nextValue)) {
return prevValue;
}
return nextValue;
};