feature: sk-react-toolkit holds the server helpers, web components and Vite font plugin shared by manage-ui and sql-query-webui.
Release / release (push) Failing after 1m18s
Release / release (push) Failing after 1m18s
This commit is contained in:
commit
4505b37abc
30 files changed
+4826
No files matched your search
@@ -0,0 +1,32 @@
|
||||
import { useSyncExternalStore } from 'react'
|
||||
|
||||
/**
|
||||
* The switches a browser keeps for an application, each off until set: keys maps each setting to its localStorage key.
|
||||
* browserSetting reads one, setBrowserSetting keeps it and tells every user of useBrowserSetting, which follows it as
|
||||
* it changes in this tab or in another tab of the browser. event names the event a change dispatches on window.
|
||||
*/
|
||||
export function createBrowserSettings<K extends string>(keys: Record<K, string>, event: string) {
|
||||
function browserSetting(setting: K) {
|
||||
return window.localStorage.getItem(keys[setting]) === 'on'
|
||||
}
|
||||
|
||||
function setBrowserSetting(setting: K, enabled: boolean) {
|
||||
window.localStorage.setItem(keys[setting], enabled ? 'on' : 'off')
|
||||
window.dispatchEvent(new Event(event))
|
||||
}
|
||||
|
||||
function subscribe(changed: () => void) {
|
||||
window.addEventListener(event, changed)
|
||||
window.addEventListener('storage', changed)
|
||||
return () => {
|
||||
window.removeEventListener(event, changed)
|
||||
window.removeEventListener('storage', changed)
|
||||
}
|
||||
}
|
||||
|
||||
function useBrowserSetting(setting: K) {
|
||||
return useSyncExternalStore(subscribe, () => browserSetting(setting))
|
||||
}
|
||||
|
||||
return { browserSetting, setBrowserSetting, useBrowserSetting }
|
||||
}
|
||||
Reference in new issue
Block a user