How-to
Website
Web app
Build a confirm dialog
Before a reader deletes something, ask them. This component wraps an AlertDialog with Cancel and Confirm buttons and tells the page which one was pressed, so every destructive action on the site asks the same way:
Needs: nothing besides the page. It claims /: paste it into a new project, or replace the starter's src/pages/Home.wf with it.
component Confirm(_ title: String, visible: Bool, danger: Bool = false) {
event confirm()
event cancel()
slot
AlertDialog(visible: visible, title: title) {
on close { emit cancel() }
children
Row(gap: .sm, justify: .end) {
Button("Cancel") { on click { emit cancel() } }
Button("Confirm", tone: if danger { .danger } else { .primary }) { on click { emit confirm() } }
}
}
}
page Account(path: "/", title: "Account", description: "Close your account.") {
state asking = false
state gone = false
Heading("Account").h1
Button("Delete account").danger { on click { asking = true } }
Confirm("Delete your account?", visible: asking, danger: true) {
on confirm { gone = true asking = false }
on cancel { asking = false }
Text("Everything goes. This cannot be undone.")
}
if gone { Alert("Account deleted.").info }
}
How it works
Confirmtakes the question as its positionaltitle, whether it shows asvisible, and adangerprop that turns the confirm button red.tone:picks the button's case from a condition instead of a fixed flag.- It declares two events,
confirmandcancel, and each button fires one withemit. The component decides nothing; the page does. slotdeclares a default slot, andchildrenplaces it inside the dialog. The caller's block fills it, so the question's detail is the caller's to write.- The page owns
asking. Delete account sets it, and both handlers clear it, which closes the dialog. - An
AlertDialogis one to a screen reader, read with its body. Escape closes it, and a press beside it does not: an answer is a button. Itson closeruns however it closes, so Escape firescanceltoo and the page clearsasking; without it,askingwould staytrueand the next Delete account would change nothing.
One question, from a handler
When the question is asked once, from one handler, await ask(…) draws the alert dialog itself and is the answer:
page Account(path: "/", title: "Account", description: "Close your account.") {
state gone = false
Heading("Account").h1
Button("Delete account").danger {
on click {
if await ask("Delete your account?", detail: "Everything goes. This cannot be undone.", yes: "Delete", danger: true) {
gone = true
}
}
}
if gone { Alert("Account deleted.").info }
}
The focus starts on Cancel, the answer that loses nothing, and goes back to the button once it is answered.