aboutsummaryrefslogtreecommitdiff
path: root/extension/src/features/settings.ts
blob: 9a3c32dbdbaefc552a3f2bdc09c67ad21a8be41a (plain)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// Copyright (C) 2023 Vaughn Nugent
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

import { storage } from "webextension-polyfill"
import { } from 'lodash'
import { configureApi, debugLog } from '@vnuge/vnlib.browser'
import { MaybeRefOrGetter, readonly, Ref, shallowRef, watch } from "vue";
import { JsonObject } from "type-fest";
import { Watchable } from "./types";
import { BgRuntime, FeatureApi, optionsOnly, IFeatureExport, exportForegroundApi, popupAndOptionsOnly } from './framework'
import { get, set, toRefs } from "@vueuse/core";
import { waitForChangeFn, useStorage } from "./util";
import { ServerApi, useServerApi } from "./server-api";

export interface PluginConfig extends JsonObject {
    readonly apiUrl: string;
    readonly accountBasePath: string;
    readonly nostrEndpoint: string;
    readonly heartbeat: boolean;
    readonly maxHistory: number;
    readonly tagFilter: boolean,
}

//Default storage config
const defaultConfig : PluginConfig = {
    apiUrl: import.meta.env.VITE_API_URL,
    accountBasePath: import.meta.env.VITE_ACCOUNTS_BASE_PATH,
    nostrEndpoint: import.meta.env.VITE_NOSTR_ENDPOINT,
    heartbeat: import.meta.env.VITE_HEARTBEAT_ENABLED === 'true',
    maxHistory: 50,
    tagFilter: true,
};

export interface AppSettings{
    saveConfig(config: PluginConfig): void;
    useStorageSlot<T>(slot: string, defaultValue: MaybeRefOrGetter<T>): Ref<T>;
    useServerApi(): ServerApi,
    readonly currentConfig: Readonly<Ref<PluginConfig>>;
}

export interface SettingsApi extends FeatureApi, Watchable {
    getSiteConfig: () => Promise<PluginConfig>;
    setSiteConfig: (config: PluginConfig) => Promise<PluginConfig>;
    setDarkMode: (darkMode: boolean) => Promise<void>;
    getDarkMode: () => Promise<boolean>;
}

export const useAppSettings = (): AppSettings => {

    const _storageBackend = storage.local;
    const store = useStorage<PluginConfig>(_storageBackend, 'siteConfig', defaultConfig);

    watch(store, (config, _) => {
        //Configure the vnlib api
        configureApi({
            session: {
                cookiesEnabled: false,
                browserIdSize: 32,
            },
            user: {
                accountBasePath: config.accountBasePath,
            },
            axios: {
                baseURL: config.apiUrl,
                tokenHeader: import.meta.env.VITE_WEB_TOKEN_HEADER,
            },
            storage: localStorage
        })

    }, { deep: true })

    //Save the config and update the current config
    const saveConfig = (config: PluginConfig) => set(store, config);

    //Reactive urls for server api
    const { accountBasePath, nostrEndpoint } = toRefs(store)
    const serverApi = useServerApi(nostrEndpoint, accountBasePath)

    return {
        saveConfig,
        currentConfig: readonly(store),
        useStorageSlot: <T>(slot: string, defaultValue: MaybeRefOrGetter<T>) => {
            return useStorage<T>(_storageBackend, slot, defaultValue)
        },
        useServerApi: () => serverApi
    }
}

export const useSettingsApi = () : IFeatureExport<AppSettings, SettingsApi> =>{

    return{
        background: ({ state }: BgRuntime<AppSettings>) => {

            const _darkMode = shallowRef(false);

            return {
                waitForChange: waitForChangeFn([state.currentConfig, _darkMode]),
                getSiteConfig: () => Promise.resolve(state.currentConfig.value),
                setSiteConfig: optionsOnly(async (config: PluginConfig): Promise<PluginConfig> => {

                    //Save the config
                    state.saveConfig(config);

                    debugLog('Config settings saved!');

                    //Return the config
                    return get(state.currentConfig)
                }),
                setDarkMode: popupAndOptionsOnly(async (darkMode: boolean) => {
                    _darkMode.value = darkMode 
                }),
                getDarkMode: async () => get(_darkMode),
            }
        },
        foreground: exportForegroundApi([
            'getSiteConfig',
            'setSiteConfig',
            'setDarkMode',
            'getDarkMode',
            'waitForChange'
        ]) 
    }
}