garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/lib/actions.ts

raw

import {toast} from '@garage44/mithril/components'
import type {Toast} from '@garage44/mithril/components'

import {local} from '@/lib/reactive'
import {poll} from '@/lib/store'

/** The page's toasts (the `Toaster` in `main.tsx`). */
export const toasts = local({list: [] as Toast[]})
export const toastModel = {
    get value() {
        return toasts.list
    },
    set value(v: Toast[]) {
        toasts.list = v
    },
}

/**
 * Run a change, say how it went, and show the workspace as it is afterwards.
 * `quiet`: no word when it worked — the change shows for itself (a message in
 * the conversation); a refusal is still said. Whether it worked.
 */
export async function act(what: string, run: () => Promise<unknown>, opts: {quiet?: boolean} = {}): Promise<boolean> {
    let ok = true
    try {
        await run()
        if (!opts.quiet) toast(toastModel, {tone: 'success', message: what})
    } catch (e) {
        ok = false
        toast(toastModel, {tone: 'danger', title: `${what}: refused`, message: (e as Error).message, timeout: 10000})
    }
    await poll()
    return ok
}