fix(ui): compare live reloads structurally instead of serialising them (#1812)
This commit is contained in:
1 file changed
+15
-12
@@ -3,23 +3,26 @@
|
||||
// unchanged row keeps its component, and a reload that changed nothing
|
||||
// triggers nothing at all.
|
||||
|
||||
const serializedCache = new WeakMap<object, string>();
|
||||
|
||||
function serialized(value: object): string {
|
||||
let json = serializedCache.get(value);
|
||||
if (json === undefined) {
|
||||
json = JSON.stringify(value);
|
||||
serializedCache.set(value, json);
|
||||
// Structural comparison, not JSON.stringify: payloads such as step debug events
|
||||
// and logs can be megabytes, and serialising them on every live reload (and
|
||||
// caching the string beside each retained object) exhausted browser memory.
|
||||
function sameContent(a: unknown, b: unknown): boolean {
|
||||
if (a === b) return true;
|
||||
if (a === null || b === null || typeof a !== "object" || typeof b !== "object") return false;
|
||||
if (Array.isArray(a) !== Array.isArray(b)) return false;
|
||||
if (Array.isArray(a) && Array.isArray(b)) {
|
||||
return a.length === b.length && a.every((item, i) => sameContent(item, b[i]));
|
||||
}
|
||||
return json;
|
||||
const x = a as Record<string, unknown>;
|
||||
const y = b as Record<string, unknown>;
|
||||
const keys = Object.keys(x);
|
||||
return keys.length === Object.keys(y).length && keys.every((k) => k in y && sameContent(x[k], y[k]));
|
||||
}
|
||||
|
||||
/** The previous value when the incoming one has the same content. */
|
||||
export function keepValue<T>(previous: T, incoming: T): T {
|
||||
if (previous === incoming) return previous;
|
||||
if (previous === null || incoming === null || typeof previous !== "object" || typeof incoming !== "object")
|
||||
return incoming;
|
||||
return serialized(previous) === serialized(incoming) ? previous : incoming;
|
||||
return sameContent(previous, incoming) ? previous : incoming;
|
||||
}
|
||||
|
||||
/** The incoming rows, each replaced by its previous object when unchanged, and
|
||||
@@ -30,7 +33,7 @@ export function keepRows<T extends { id: number | string }>(previous: readonly T
|
||||
let changed = previous.length !== incoming.length;
|
||||
const merged = incoming.map((row, index) => {
|
||||
const old = byId.get(row.id);
|
||||
const kept = old && serialized(old) === serialized(row) ? old : row;
|
||||
const kept = old && sameContent(old, row) ? old : row;
|
||||
if (kept !== previous[index]) changed = true;
|
||||
return kept;
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user