All files / src/settings base.ts

57.14% Statements 8/14
25% Branches 1/4
28.57% Functions 2/7
54.54% Lines 6/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 471x                     1x                                     1x 1x         7x 7x                  
import joplin from "api";
import { SettingItem } from "api/types";
 
export interface PluginSetting<T> {
    id: string;
    manifest: SettingItem;
 
    get(): Promise<T>;
    set(newValue: T): Promise<void>;
}
 
export const createSimpleSetting = <T>(id: string, manifest: SettingItem): PluginSetting<T> => {
    return class {
        static id = id;
        static manifest = manifest;
 
        static async get(): Promise<T> {
            return await joplin.settings.value(id);
        }
 
        static async set(newValue: T): Promise<void> {
            await joplin.settings.setValue(id, newValue);
        }
    }
}
 
/**
 * This considers that the original setting is of type `string`. On `set` if no original value
 * can be traced back, the setting is set to an empty string.
 */
export const createMappedSetting = <T>(id: string, manifest: SettingItem, valueMap: Record<string, T>, defaultValue: T): PluginSetting<T> => {
    return class {
        static id = id;
        static manifest = manifest;
 
        static async get(): Promise<T> {
            const value: string = await joplin.settings.value(id);
            return value in valueMap ? valueMap[value] : defaultValue;
        }
 
        static async set(newValue: T): Promise<void> {
            const potentialValues = Object.entries(valueMap).filter((entry) => entry[1] === newValue);
            await joplin.settings.setValue(id, potentialValues.length ? potentialValues[0][0] : "" );
        }
    }
}