// SPDX-License-Identifier: AGPL-3.0-or-later import type { InstanceSettings, InstanceSettingsUpdate } from "@docwell/api-client"; import { onMounted, ref } from "vue"; import { api, errorMessage } from "./session"; /** Loads the instance settings and saves one section at a time. */ export function useInstanceSettings() { const settings = ref(null); const error = ref(""); const saved = ref(false); const busy = ref(false); async function load() { error.value = ""; try { settings.value = await api.settings.get(); } catch (e) { error.value = errorMessage(e); } } onMounted(load); async function save(patch: InstanceSettingsUpdate) { busy.value = true; error.value = ""; saved.value = false; try { settings.value = await api.settings.update(patch); saved.value = true; setTimeout(() => (saved.value = false), 2500); } catch (e) { error.value = errorMessage(e); } finally { busy.value = false; } } return { settings, error, saved, busy, load, save }; } /** Bytes as KB/MB/GB for people. */ export function formatBytes(n: number): string { if (n < 1024) return `${n} B`; const units = ["KB", "MB", "GB", "TB"]; let v = n / 1024; let i = 0; while (v >= 1024 && i < units.length - 1) { v /= 1024; i++; } return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`; } /** Hands a downloaded file to the browser. */ export function saveBlob(blob: Blob, filename: string) { const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = filename; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); }