aboutsummaryrefslogtreecommitdiffstats
path: root/apps/browser-extension/src/utils/settings.ts
blob: 6d51acde4f0cd5b81bf79ad8a3c6168e8e7d5e82 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React from "react";

export interface Settings {
  apiKey: string;
  apiKeyId?: string;
  address: string;
}

const STORAGE = chrome.storage.sync;

export default function usePluginSettings() {
  const [settings, setSettingsInternal] = React.useState<Settings>({
    apiKey: "",
    address: "",
  });

  const [isInit, setIsInit] = React.useState(false);

  React.useEffect(() => {
    if (!isInit) {
      getPluginSettings().then((settings) => {
        setSettingsInternal(settings);
        setIsInit(true);
      });
    }
    const onChange = (
      changes: Record<string, chrome.storage.StorageChange>,
    ) => {
      if (changes.settings === undefined) {
        return;
      }
      setSettingsInternal(changes.settings.newValue as Settings);
    };
    STORAGE.onChanged.addListener(onChange);
    return () => {
      STORAGE.onChanged.removeListener(onChange);
    };
  }, []);

  const setSettings = async (s: (_: Settings) => Settings) => {
    const newVal = s(settings);
    await STORAGE.set({ settings: newVal });
  };

  return { settings, setSettings, isPending: isInit };
}

export async function getPluginSettings() {
  return (await STORAGE.get("settings")).settings as Settings;
}

export function subscribeToSettingsChanges(
  callback: (settings: Settings) => void,
) {
  chrome.storage.sync.onChanged.addListener((changes) => {
    if (changes.settings === undefined) {
      return;
    }
    callback(changes.settings.newValue as Settings);
  });
}