From 1645913b7f5a23193f2bb4eb2f14b22e9ffff420 Mon Sep 17 00:00:00 2001 From: Vendicated Date: Sat, 3 Sep 2022 18:01:06 +0200 Subject: [PATCH] Improve settings listener api --- src/api/settings.ts | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/src/api/settings.ts b/src/api/settings.ts index 86464124..e6d92737 100644 --- a/src/api/settings.ts +++ b/src/api/settings.ts @@ -37,7 +37,7 @@ try { var settings = mergeDefaults({} as Settings, DefaultSettings); } -type SubscriptionCallback = ((newValue: any) => void) & { _path?: string; }; +type SubscriptionCallback = ((newValue: any, path: string) => void) & { _path?: string; }; const subscriptions = new Set(); function makeProxy(settings: Settings, root = settings, path = ""): Settings { @@ -55,7 +55,7 @@ function makeProxy(settings: Settings, root = settings, path = ""): Settings { const setPath = `${path}${path && "."}${p}`; for (const subscription of subscriptions) { if (!subscription._path || subscription._path === setPath) { - subscription(v); + subscription(v, setPath); } } VencordNative.ipc.invoke(IpcEvents.SET_SETTINGS, JSON.stringify(root, null, 4)); @@ -92,9 +92,19 @@ type ResolvePropDeep = P extends "" ? T : P extends `${infer Pre}.${infer Suf}` ? Pre extends keyof T ? ResolvePropDeep : never : P extends keyof T ? T[P] : never; -export function addSettingsListener(path: Path, onUpdate: (newValue: Settings[Path]) => void): void; -export function addSettingsListener(path: Path, onUpdate: (newValue: ResolvePropDeep) => void): void; -export function addSettingsListener(path: string, onUpdate: (newValue: any) => void) { +/** + * Add a settings listener that will be invoked whenever the desired setting is updated + * @param path Path to the setting that you want to watch, for example "plugins.Unindent.enabled" will fire your callback + * whenever Unindent is toggled. Pass an empty string to get notified for all changes + * @param onUpdate Callback function whenever a setting matching path is updated. It gets passed the new value and the path + * to the updated setting. This path will be the same as your path argument, unless it was an empty string. + * + * @example addSettingsListener("", (newValue, path) => console.log(`${path} is now ${newValue}`)) + * addSettingsListener("plugins.Unindent.enabled", v => console.log("Unindent is now", v ? "enabled" : "disabled")) + */ +export function addSettingsListener(path: Path, onUpdate: (newValue: Settings[Path], path: Path) => void): void; +export function addSettingsListener(path: Path, onUpdate: (newValue: Path extends "" ? any : ResolvePropDeep, path: Path extends "" ? string : Path) => void): void; +export function addSettingsListener(path: string, onUpdate: (newValue: any, path: string) => void) { (onUpdate as SubscriptionCallback)._path = path; subscriptions.add(onUpdate); -} \ No newline at end of file +}