Files
Trilium/apps/client/src/services/options.ts

96 lines
2.4 KiB
TypeScript
Raw Normal View History

import { OptionNames } from "@triliumnext/commons";
2024-07-25 00:25:11 +03:00
import server from "./server.js";
import { isShare } from "./utils.js";
2024-07-25 00:25:11 +03:00
export type OptionValue = number | string;
2024-07-25 00:25:11 +03:00
class Options {
initializedPromise: Promise<void>;
2024-07-25 00:25:11 +03:00
private arr!: Record<string, OptionValue>;
constructor() {
if (!isShare) {
this.initializedPromise = server.get<Record<string, OptionValue>>("options").then((data) => this.load(data));
2025-06-09 22:40:45 +03:00
} else {
this.initializedPromise = Promise.resolve();
}
2024-07-25 00:25:11 +03:00
}
load(arr: Record<string, OptionValue>) {
this.arr = arr;
}
get(key: OptionNames) {
2025-01-07 12:34:10 +02:00
return this.arr?.[key] as string;
2024-07-25 00:25:11 +03:00
}
getNames() {
return Object.keys(this.arr || []);
}
2025-01-07 12:34:10 +02:00
getJson(key: string) {
2024-07-25 00:25:11 +03:00
const value = this.arr?.[key];
if (typeof value !== "string") {
return null;
}
try {
return JSON.parse(value);
2025-01-09 18:07:02 +02:00
} catch (e) {
2024-07-25 00:25:11 +03:00
return null;
}
}
getInt(key: OptionNames) {
2024-07-25 00:25:11 +03:00
const value = this.arr?.[key];
if (typeof value === "number") {
return value;
}
if (typeof value == "string") {
return parseInt(value);
2024-07-25 00:25:11 +03:00
}
console.warn("Attempting to read int for unsupported value: ", value);
return null;
2024-07-25 00:25:11 +03:00
}
getFloat(key: OptionNames) {
2024-07-25 00:25:11 +03:00
const value = this.arr?.[key];
if (typeof value !== "string") {
return null;
}
return parseFloat(value);
}
is(key: OptionNames) {
2025-01-09 18:07:02 +02:00
return this.arr[key] === "true";
2024-07-25 00:25:11 +03:00
}
set(key: OptionNames, value: OptionValue) {
2024-07-25 00:25:11 +03:00
this.arr[key] = value;
}
async save(key: OptionNames, value: OptionValue) {
2024-07-25 00:25:11 +03:00
this.set(key, value);
const payload: Record<string, OptionValue> = {};
payload[key] = value;
await server.put(`options`, payload);
}
2025-08-20 20:34:00 +03:00
/**
* Saves multiple options at once, by supplying a record where the keys are the option names and the values represent the stringified value to set.
* @param newValues the record of keys and values.
*/
async saveMany<T extends OptionNames>(newValues: Record<T, OptionValue>) {
await server.put<void>("options", newValues);
}
async toggle(key: OptionNames) {
2024-07-25 00:25:11 +03:00
await this.save(key, (!this.is(key)).toString());
}
}
const options = new Options();
2025-01-07 12:34:10 +02:00
export default options;