import m, {MithrilComponent} from '@garage44/mithril'
import {Button, Dialog} from '@garage44/mithril/components'
import {ARMED_MS, armed, isArmed, tap} from '@/lib/confirm'
import {local} from '@/lib/reactive'
type Variant = 'primary' | 'secondary' | 'ghost' | 'danger'
/**
* A button that asks for a second tap: the first turns it into what it will
* do ("Tap again to stop"), the second within a few seconds does it. `key`
* names this one button, so arming another disarms it.
*/
export function confirmButton(
key: string,
o: {label: m.Children; armedLabel: m.Children; run: () => unknown; variant?: Variant; size?: 'sm' | 'md'; disabled?: boolean; title?: string; class?: string},
): m.Children {
const on = isArmed(armed, key, Date.now())
return (
)
}
/** The one confirm dialog: for a change with consequences worth a sentence. */
const ask = local({open: false, title: '', text: '' as m.Children, yes: '', danger: false})
/** Who waits on the answer: never in `ask`, as reactive state takes a function put in it for a
computed and calls it on reading, which answered every confirm "no" before it was shown. */
let waiting: null | ((ok: boolean) => void) = null
export function askConfirm(o: {title: string; text: m.Children; yes: string; danger?: boolean}): Promise {
waiting?.(false)
return new Promise((resolve) => {
waiting = resolve
Object.assign(ask, {open: true, title: o.title, text: o.text, yes: o.yes, danger: !!o.danger})
})
}
function close(ok: boolean) {
const r = waiting
waiting = null
ask.open = false
r?.(ok)
}
/** Mounted once, in the frame. */
export class ConfirmHost extends MithrilComponent {
view() {
return (
)
}
}