writekit/frontends/owner-tools/src/stores/app.ts

65 lines
1.6 KiB
TypeScript
Raw Normal View History

import { atom, map, onMount } from 'nanostores'
import { getSettings, getSettingsSchema, saveSettings as apiSaveSettings } from '../api'
import type { Settings, SettingDefinition } from '../api'
export const $panelOpen = atom(false)
export const $regenerating = atom(false)
export const $error = atom<string | null>(null)
export const $settings = map<Settings>({})
export const $schema = atom<SettingDefinition[]>([])
export const $dirty = atom(false)
export function openPanel() {
$panelOpen.set(true)
}
export function closePanel() {
$panelOpen.set(false)
}
export function updateSetting(key: string, value: string) {
$settings.setKey(key, value)
$dirty.set(true)
}
async function softReload() {
const res = await fetch(window.location.href)
if (!res.ok) throw new Error('Failed to fetch page')
const html = await res.text()
const parser = new DOMParser()
const newDoc = parser.parseFromString(html, 'text/html')
const currentPage = document.getElementById('page')
const newPage = newDoc.getElementById('page')
if (currentPage && newPage) {
currentPage.outerHTML = newPage.outerHTML
}
}
export async function saveSettings() {
$regenerating.set(true)
$error.set(null)
try {
await apiSaveSettings($settings.get())
await softReload()
$regenerating.set(false)
$dirty.set(false)
} catch {
$regenerating.set(false)
$error.set('Failed to save')
}
}
onMount($settings, () => {
getSettings()
.then(data => $settings.set(data))
.catch(() => $error.set('Failed to load settings'))
getSettingsSchema()
.then(data => $schema.set(data))
.catch(() => {})
})