-
Notifications
You must be signed in to change notification settings - Fork 346
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[debugging] add mutation detector proxy class
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
/* | ||
* mutation-detector-proxy | ||
* | ||
* Copyright (C) 2025 Posit Software, PBC | ||
*/ | ||
|
||
export type DeepProxyChange = { | ||
type: "update" | "delete"; | ||
path: (string | symbol)[]; | ||
oldValue: unknown; | ||
newValue?: unknown; | ||
}; | ||
|
||
export type OnChangeCallback = (change: DeepProxyChange) => void; | ||
|
||
export function mutationDetectorProxy<T extends object>( | ||
obj: T, | ||
onChange: OnChangeCallback, | ||
path: (string | symbol)[] = [], | ||
): T { | ||
return new Proxy(obj, { | ||
get(target: T, property: string | symbol): any { | ||
const value = Reflect.get(target, property); | ||
if (value && typeof value === "object") { | ||
return mutationDetectorProxy( | ||
value, | ||
onChange, | ||
[...path, property], | ||
); | ||
} | ||
return value; | ||
}, | ||
|
||
set(target: T, property: string | symbol, value: any): boolean { | ||
const oldValue = Reflect.get(target, property); | ||
const result = Reflect.set(target, property, value); | ||
|
||
if (result) { | ||
onChange({ | ||
type: "update", | ||
path: [...path, property], | ||
oldValue, | ||
newValue: value, | ||
}); | ||
} | ||
|
||
return result; | ||
}, | ||
|
||
deleteProperty(target: T, property: string | symbol): boolean { | ||
const oldValue = Reflect.get(target, property); | ||
const result = Reflect.deleteProperty(target, property); | ||
|
||
if (result) { | ||
onChange({ | ||
type: "delete", | ||
path: [...path, property], | ||
oldValue, | ||
}); | ||
} | ||
|
||
return result; | ||
}, | ||
}); | ||
} |