Compose dialogs with focus return
This complete Rust and Slint application composes two modal layers inside one window with KitDialogSurface, KitDialogPanel, KitDialogHeader, KitDialogBody, KitDialogFooter and KitFocusTarget. The DialogHost adapter owns the layer stack (OverlayStack) and focus registry (FocusRegistry); Slint shows the published state and relays gestures. These are surfaces composed in the application window: the kit does not provide a system modal window. KitDialogFooter actions wrap when the available width or enlarged text requires it.
What the example demonstrates:
- Several triggers, exact return. Two buttons open the same dialog. On close, focus returns to the button that opened it, not to a default location.
- Nested layers. “Archive…” opens a confirmation above the dialog. Escape and system Back close one layer at a time; each layer returns focus to its own trigger.
- Tab and Shift+Tab stay inside the topmost layer and wrap, skipping disabled controls. A native text field is a target like any other.
- Busy state. While archiving runs, Escape, system Back and the backdrop are consumed without closing; the action button shows the busy state and keeps focus inside the layer. On completion both layers close and focus returns to the first trigger.
- Background neutralized, not only clicks. Covered controls are ineligible in the registry and disabled in Slint from the same flag: pointer, keyboard and accessibility activation are all neutral. The backdrop alone is not enough, because it does not stop semantic actions.
Try the application
Create a fresh project, then replace its files with the five complete files below. Packages come from crates.io; no kit checkout is needed. The native prerequisites match the getting-started guide.
cargo new slint-kit-dialog-example
cd slint-kit-dialog-example
- Activate Archive from the project card. The “Project name” field takes focus. Tab visits Cancel, then Archive…, then returns to the field; Shift+Tab goes the other way.
- Press Escape: the dialog closes and focus returns to Archive from the project card. Open it from the toolbar: Escape returns focus to that button instead.
- Open the dialog, then Archive…: the confirmation appears above it. Tab only cycles between Keep project and Archive now. Escape closes the confirmation alone and returns focus to Archive…; a second Escape closes the dialog.
- In the confirmation, activate Archive now: the button enters the busy state and Escape no longer closes anything. After a moment both layers close and focus returns to the original trigger.
How the pieces fit
DialogHost<W, L, T>accepts typed identities throughDialogLayerSpec(parent, first control) andDialogFocusSpec(stable token, layer, enabled state). Declare parents before descendants; construction rejects invalid topology.DialogHostPortsnames the setters for three projections:FocusSlot,DialogStateandFocusRequest. The kit publishes eligibility, then states, then focus after releasing its borrow, so focus callbacks may safely re-enter the host.- Connect
open,close,cycleandobserve_focusto view events.set_activity(layer, DialogActivity::Busy(target))keeps only the busy action eligible. Nested close checks the entire closing subtree before mutating the stack (a busy or policy-blocked descendant atomically rejects user dismissal of its parent, whileProgrammaticandHostClosedclose the whole subtree) and restores the exact opener once, or an eligible fallback. For a custom host mixing modal dialogs and non-modal popovers,OverlayStackpreserves bottom-to-top registration order (iter,get,topmost_modal), links each layer to its optionalOverlaySpec.focus_scope, and restricts in-place mutation toset_busyandset_policy. PreferOverlaySpec::new(no focus scope by default); complete struct literals now requirefocus_scope. The stack stores scope metadata; custom hosts still push/pop theirFocusRegistrytraps and observe actual focus.DialogHostperforms modal trap management for its registered layers. KitFocusTargetrelaysfocus-requestedto the real control’stake-focus()and is not a focus stop. The real control callsobserve-focus(focused);focus-observed(token, generation, focused)goes toobserve_focus, which ignores a stale generation. Bind the sameslot.eligibleto its access/disabled state: a backdrop alone cannot block accessibility actions.
Eligibility is computed once, in Rust, then published; Slint keeps no copy of the rule. In this example the busy action stays eligible during the work so the layer keeps focus and consumes Escape and Back; its neighbours are disabled.
For a dialog that needs no fine-grained composition, KitDialog and KitAlertDialog assemble these primitives: title, description, close button, scrolling body, footer buttons (actions, each with a stable token) and a size width. Set modal-layer and tab-policy: DialogTabPolicy.native: the dialog manages the focus of its own buttons, the background becomes inert and the host keeps dismiss and restore-focus. Keep the primitives of this example when the dialog must register its controls in the focus registry.
Cargo.toml
Download this example — Cargo.toml
[package]
name = "slint-kit-dialog-example"
version = "0.1.0"
edition = "2024"
rust-version = "1.95"
license = "GPL-3.0-or-later"
publish = false
[dependencies]
slint-kit = "=0.9.0"
slint = { version = "=1.19.0", default-features = false, features = ["std", "compat-1-18", "backend-winit", "renderer-skia", "accessibility"] }
[build-dependencies]
slint-kit-build = "=0.9.0"
[workspace]
build.rs
Download this example — build.rs
// SPDX-License-Identifier: GPL-3.0-or-later
fn main() {
slint_kit_build::compile("ui/dialog.slint").expect("compile dialog example");
}
ui/dialog.slint
Download this example — ui/dialog.slint
// SPDX-License-Identifier: GPL-3.0-or-later
import { KitWrap, KitButton, ButtonIntent, KitTextField, FieldAccess, KitDialogSurface, KitDialogPanel, KitDialogHeader, KitDialogBody, KitDialogFooter, KitFocusTarget, DialogState, FocusRequest, CloseReason, KitTheme, KitThemes, FocusSlot } from "@kit";
export { DialogState, FocusRequest, CloseReason, FocusSlot }
export enum DialogLanguage { english, french }
// The two modal layers of this window, outer layer first. Each one is a
// surface rendered inside the window, not a separate system window.
export enum DialogLayer { archive, confirm }
// What the host publishes for one focus target: the generation of its
// registration and whether it may take focus and act right now.
// A button the host addresses by token. `eligible: false` also disables the
// button, so pointer, keyboard and accessibility activation are all neutral
// while a layer covers it. KitFocusTarget applies the host's focus requests.
component FocusButton inherits KitFocusTarget {
in property <KitTheme> theme;
in property <string> text;
in property <ButtonIntent> intent: ButtonIntent.secondary;
in property <FocusSlot> slot;
in property <bool> busy;
callback activated();
generation: root.slot.generation;
eligible: root.slot.eligible;
min-height: button.min-height; preferred-height: button.preferred-height; vertical-stretch: 0;
min-width: button.min-width; preferred-width: button.preferred-width; max-width: self.preferred-width; horizontal-stretch: 0;
focus-requested => { button.take-focus(); }
button := KitButton {
theme: root.theme; text: root.text; intent: root.intent; busy: root.busy; busy-label: root.text; disabled: !root.eligible;
activated => { root.activated(); }
focus-observed(focused) => { root.observe-focus(focused); }
}
}
export component DialogApp inherits Window {
in property <DialogLanguage> language: DialogLanguage.english;
private property <bool> french: root.language == DialogLanguage.french;
in-out property <KitTheme> theme: KitThemes.light;
title: root.french ? "Dialogues Slint Kit" : "Slint Kit dialogs";
preferred-width: 720px;
preferred-height: 520px;
background: root.theme.canvas;
// Published by the host: one slot per token (the index is the token), the
// state of each layer and the focus request to apply.
in property <[FocusSlot]> slots;
in property <DialogState> archive;
in property <DialogState> confirm;
in property <FocusRequest> focus-request;
in property <string> status;
in-out property <string> project-name: "Atlas";
// The second argument is the token of the control that opens the layer;
// focus returns to that exact control when the layer closes.
callback open-requested(DialogLayer, int);
callback dismiss(DialogLayer, CloseReason);
callback confirm-requested();
callback focus-next(bool);
callback focus-changed(int, int, bool);
public function focus-layer(layer: DialogLayer) {
if (layer == DialogLayer.archive) { archive-surface.take-scope-focus(); }
else { confirm-surface.take-scope-focus(); }
}
VerticalLayout {
padding: 24px;
spacing: 16px;
alignment: start;
Text { text: root.french ? "Projet Atlas" : "Atlas project"; color: root.theme.text-primary; font-size: 24px * root.theme.text-scale; font-weight: 600; }
Text { text: root.french ? "Deux contrôles ouvrent le même dialogue. Fermez-le avec Échap, Retour système, le voile ou un bouton : le focus revient au contrôle qui l’a ouvert." : "Two controls open the same dialog. Close it with Escape, system Back, the backdrop or a button: focus returns to the control that opened it."; color: root.theme.text-secondary; font-size: 14px * root.theme.text-scale; wrap: word-wrap; }
KitWrap {
theme: root.theme; spacing: root.theme.spacing.unit * 3; alignment: start;
FocusButton { theme: root.theme; token: 1; slot: root.slots[1]; request: root.focus-request; intent: ButtonIntent.primary; text: root.french ? "Archiver depuis la barre d’outils" : "Archive from the toolbar"; activated => { root.open-requested(DialogLayer.archive, self.token); } focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); } }
FocusButton { theme: root.theme; token: 2; slot: root.slots[2]; request: root.focus-request; text: root.french ? "Archiver depuis la fiche du projet" : "Archive from the project card"; activated => { root.open-requested(DialogLayer.archive, self.token); } focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); } }
}
Text { text: root.status; color: root.theme.text-primary; font-size: 14px * root.theme.text-scale; wrap: word-wrap; }
}
// Rendered last, so the layers cover the window content: the archive layer,
// then the nested confirmation above it. Only the topmost layer reacts to
// Escape, system Back and the backdrop; Tab stays inside it.
archive-surface := KitDialogSurface {
theme: root.theme; state: root.archive;
dismiss(reason) => { root.dismiss(DialogLayer.archive, reason); }
focus-next(backward) => { root.focus-next(backward); }
KitDialogPanel {
theme: root.theme; accessible-name: root.french ? "Archiver le projet" : "Archive project";
width: min(480px, parent.width - 48px); height: archive-content.preferred-height;
x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2;
archive-content := VerticalLayout {
padding: 24px; spacing: 16px;
KitDialogHeader { theme: root.theme; Text { text: root.french ? "Archiver ce projet ?" : "Archive this project?"; color: root.theme.text-primary; font-size: 20px * root.theme.text-scale; font-weight: 600; wrap: word-wrap; } }
KitDialogBody {
theme: root.theme;
Text { text: root.french ? "Le projet quitte la liste active. Vous pourrez le restaurer depuis les archives." : "The project leaves the active list. You can restore it from the archive later."; color: root.theme.text-secondary; font-size: 14px * root.theme.text-scale; wrap: word-wrap; }
// A native editor is a focus target too: the request reaches the field through take-focus().
name-target := KitFocusTarget {
token: 3; generation: root.slots[3].generation; eligible: root.slots[3].eligible; request: root.focus-request;
min-height: name.min-height; preferred-height: name.preferred-height; vertical-stretch: 0;
focus-requested => { name.take-focus(); }
focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); }
name := KitTextField { theme: root.theme; label: root.french ? "Nom du projet" : "Project name"; text <=> root.project-name; access: root.slots[3].eligible ? FieldAccess.editable : FieldAccess.disabled; focus-observed(focused) => { name-target.observe-focus(focused); } }
}
}
KitDialogFooter {
theme: root.theme;
FocusButton { theme: root.theme; token: 4; slot: root.slots[4]; request: root.focus-request; text: root.french ? "Annuler" : "Cancel"; activated => { root.dismiss(DialogLayer.archive, CloseReason.programmatic); } focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); } }
FocusButton { theme: root.theme; token: 5; slot: root.slots[5]; request: root.focus-request; intent: ButtonIntent.destructive; text: root.french ? "Archiver…" : "Archive…"; activated => { root.open-requested(DialogLayer.confirm, self.token); } focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); } }
}
}
}
}
confirm-surface := KitDialogSurface {
theme: root.theme; state: root.confirm;
dismiss(reason) => { root.dismiss(DialogLayer.confirm, reason); }
focus-next(backward) => { root.focus-next(backward); }
KitDialogPanel {
theme: root.theme; accessible-name: root.french ? "Confirmer l’archivage" : "Confirm archiving";
width: min(400px, parent.width - 48px); height: confirm-content.preferred-height;
x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2;
confirm-content := VerticalLayout {
padding: 24px; spacing: 16px;
KitDialogHeader { theme: root.theme; Text { text: root.french ? "Archiver « " + root.project-name + " » ?" : "Archive “" + root.project-name + "”?"; color: root.theme.text-primary; font-size: 20px * root.theme.text-scale; font-weight: 600; wrap: word-wrap; } }
KitDialogBody { theme: root.theme; Text { text: root.french ? "L’archivage prend un instant. Pendant ce temps, ce dialogue ne peut pas être fermé." : "Archiving takes a moment. The dialog cannot be dismissed until it completes."; color: root.theme.text-secondary; font-size: 14px * root.theme.text-scale; wrap: word-wrap; } }
KitDialogFooter {
theme: root.theme;
FocusButton { theme: root.theme; token: 6; slot: root.slots[6]; request: root.focus-request; text: root.french ? "Conserver le projet" : "Keep project"; activated => { root.dismiss(DialogLayer.confirm, CloseReason.programmatic); } focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); } }
FocusButton { theme: root.theme; token: 7; slot: root.slots[7]; request: root.focus-request; intent: ButtonIntent.primary; busy: root.confirm.busy; text: root.confirm.busy ? (root.french ? "Archivage…" : "Archiving…") : (root.french ? "Archiver maintenant" : "Archive now"); activated => { root.confirm-requested(); } focus-observed(token, generation, focused) => { root.focus-changed(token, generation, focused); } }
}
}
}
}
}
src/main.rs
Download this example — src/main.rs
// SPDX-License-Identifier: GPL-3.0-or-later
use slint::ComponentHandle;
pub mod ui {
pub use slint_kit::ui::*;
slint::include_modules!();
}
mod controller;
pub use controller::create_app;
pub fn main() -> Result<(), slint::PlatformError> {
let language = if std::env::args().any(|arg| arg == "--fr") {
ui::DialogLanguage::French
} else {
ui::DialogLanguage::English
};
create_app(language)?.run()
}
src/controller.rs
Download this example — src/controller.rs
// SPDX-License-Identifier: GPL-3.0-or-later
use super::ui;
use slint::ComponentHandle;
use slint_kit::{
DialogActivity, DialogFocusRequest, DialogFocusSpec, DialogHost, DialogHostPorts,
DialogLayerSpec, DismissReason, FocusDirection,
};
use std::time::Duration;
// Slint declares the presentation-only layer set once. The generated enum's
// structural equality is total, so it is a stable identity for the host.
impl Eq for ui::DialogLayer {}
pub type Layer = ui::DialogLayer;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Target {
Toolbar,
Card,
Name,
Cancel,
Archive,
Keep,
Confirm,
}
pub type Host = DialogHost<ui::DialogApp, Layer, Target>;
fn status(language: ui::DialogLanguage, project: &str, archived: bool) -> String {
match (language, archived) {
(ui::DialogLanguage::English, false) => format!("{project} is active."),
(ui::DialogLanguage::English, true) => format!("{project} is archived."),
(ui::DialogLanguage::French, false) => format!("{project} est actif."),
(ui::DialogLanguage::French, true) => format!("{project} est archivé."),
}
}
/// The application declares identities, topology and commands; the kit owns
/// focus eligibility, traps, nested restoration and safe publication ordering.
pub fn create_app_with_host(
language: ui::DialogLanguage,
) -> Result<(ui::DialogApp, Host), slint::PlatformError> {
let app = ui::DialogApp::new()?;
slint_kit::install(&app);
app.set_language(language);
app.set_status(status(language, &app.get_project_name(), false).into());
let host = DialogHost::new(
&app,
[
DialogLayerSpec {
key: Layer::Archive,
parent: None,
initial_focus: Target::Name,
},
DialogLayerSpec {
key: Layer::Confirm,
parent: Some(Layer::Archive),
initial_focus: Target::Keep,
},
],
[
(Target::Toolbar, None),
(Target::Card, None),
(Target::Name, Some(Layer::Archive)),
(Target::Cancel, Some(Layer::Archive)),
(Target::Archive, Some(Layer::Archive)),
(Target::Keep, Some(Layer::Confirm)),
(Target::Confirm, Some(Layer::Confirm)),
]
.into_iter()
.enumerate()
.map(|(index, (key, layer))| DialogFocusSpec {
key,
layer,
token: u16::try_from(index + 1).expect("seven targets"),
enabled: true,
}),
DialogHostPorts {
slots: ui::DialogApp::set_slots,
state: |app, layer, state| match layer {
Layer::Archive => app.set_archive(state),
Layer::Confirm => app.set_confirm(state),
},
focus: |app, request| match request {
DialogFocusRequest::Control(request) => app.set_focus_request(request),
DialogFocusRequest::Layer(layer) => {
app.set_focus_request(ui::FocusRequest::default());
app.invoke_focus_layer(layer);
}
},
},
)
.expect("valid modal topology");
app.on_open_requested({
let host = host.clone();
move |layer, token| {
if let Some(target) = host.target(token) {
host.open(layer, target);
}
}
});
app.on_dismiss({
let host = host.clone();
move |layer, reason| host.close(layer, DismissReason::from(reason))
});
app.on_focus_next({
let host = host.clone();
move |backward| {
host.cycle(if backward {
FocusDirection::Backward
} else {
FocusDirection::Forward
})
}
});
app.on_focus_changed({
let host = host.clone();
move |token, generation, focused| host.observe_focus(token, generation, focused)
});
app.on_confirm_requested({
let (weak, host) = (app.as_weak(), host.clone());
move || {
if host
.state(Layer::Confirm)
.is_none_or(|state| !state.open || !state.topmost || state.busy)
|| !host.eligible(Target::Confirm)
{
return;
}
host.set_activity(Layer::Confirm, DialogActivity::Busy(Target::Confirm));
let (weak, host) = (weak.clone(), host.clone());
slint::Timer::single_shot(Duration::from_millis(1200), move || {
let Some(app) = weak.upgrade() else {
return;
};
host.close(Layer::Archive, DismissReason::Programmatic);
app.set_status(status(language, &app.get_project_name(), true).into());
});
}
});
Ok((app, host))
}
pub fn create_app(language: ui::DialogLanguage) -> Result<ui::DialogApp, slint::PlatformError> {
create_app_with_host(language).map(|(app, _)| app)
}
Run and adapt
cargo run
Replace the timer with your real asynchronous work: mark the layer busy when it starts, then close it with DismissReason::Programmatic when the result arrives. Add a layer with DialogLayerSpec and a control with DialogFocusSpec; call set_enabled when its enabled state changes. The compiler reports every match to complete. With tab-policy: DialogTabPolicy.native, Slint traverses the mounted controls itself. Then set modal-layer on each KitDialogSurface (distinct positive numbers for nested layers) and give the layer's kit controls the same modal-layer: every other kit control becomes inert without a token. Custom controls do not read this context: the host disables them as before. Calendars, date, time, color and file pickers, keypads, scroll areas, forms, notification centers, data tables, content lists, text views, tabs, menus, accordions, carousels, breadcrumbs and pagination do.
Slint 1.19.0 exposes no dialog role, modal state, or property that hides an accessible subtree while keeping it visible. The panel is exposed as a named groupbox; covered controls remain readable in the screen reader browse order despite being disabled. The inert-background contract covers actions, not isolation of the accessibility browse tree.
The kit’s tests prove this contract headlessly: focus return to the exact trigger, nested layers, Tab/Shift+Tab, Escape/Back, busy state and an inert background. They do not qualify screen readers or input methods: verify those on the target platform. See the KitDialogSurface reference and the KitFocusTarget reference for the full API.