Projet en développement actif · Des changements cassants sont encore à prévoir.

Slint Kit Documentation

Rechercher dans la documentation

    ↑ ↓ pour parcourir · Entrée pour ouvrir · Échap pour fermer

    Composer des dialogues avec retour du focus

    Cette application Rust et Slint complète compose deux couches modales à l’intérieur d’une fenêtre avec KitDialogSurface, KitDialogPanel, KitDialogHeader, KitDialogBody, KitDialogFooter et KitFocusTarget. L’adaptateur DialogHost possède la pile de couches (OverlayStack) et le registre de focus (FocusRegistry) ; Slint affiche l’état publié et relaie les gestes. Ce sont des surfaces composées dans la fenêtre de l’application : le kit ne fournit pas de fenêtre modale système. Les actions de KitDialogFooter passent à la ligne quand la largeur disponible ou le texte agrandi l’exige.

    Ce que l’exemple démontre :

    Essayer l’application

    Créez un projet neuf, puis remplacez ses fichiers par les cinq fichiers complets ci-dessous. Les paquets viennent de crates.io ; aucun checkout du kit n’est nécessaire. Les prérequis natifs sont ceux du guide de démarrage.

    cargo new slint-kit-dialog-example
    cd slint-kit-dialog-example
    
    1. Activez Archiver depuis la fiche du projet. Le champ « Nom du projet » prend le focus. Tab parcourt Annuler puis Archiver…, et revient au champ ; Maj+Tab fait l’inverse.
    2. Appuyez sur Échap : le dialogue se ferme et le focus revient à Archiver depuis la fiche du projet. Ouvrez-le depuis la barre d’outils : Échap rend le focus à ce bouton-là.
    3. Ouvrez le dialogue, puis Archiver… : la confirmation s’affiche au-dessus. Tab ne circule qu’entre Conserver le projet et Archiver maintenant. Échap ferme la confirmation seule et rend le focus à Archiver… ; un second Échap ferme le dialogue.
    4. Dans la confirmation, activez Archiver maintenant : le bouton passe en état occupé et Échap ne ferme plus rien. Au bout d’un instant, les deux couches se ferment et le focus revient au déclencheur initial.

    Comment les pièces s’assemblent

    L’éligibilité est calculée une fois, dans Rust, puis publiée ; Slint n’en possède pas de copie. Dans cet exemple, l’action occupée reste éligible pendant le travail pour que la couche conserve le focus et consomme Échap et Retour ; ses voisines sont désactivées.

    Pour un dialogue sans composition fine, KitDialog et KitAlertDialog assemblent ces primitives : titre, description, bouton Fermer, corps défilant, boutons de pied (actions, chacun avec un token stable) et largeur size. Réglez modal-layer et tab-policy: DialogTabPolicy.native : le dialogue gère le focus de ses propres boutons, l’arrière-plan devient inerte et l’hôte garde dismiss et restore-focus. Gardez les primitives de cet exemple quand le dialogue doit enregistrer ses contrôles dans le registre de focus.

    Cargo.toml

    Télécharger cet exemple — 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

    Télécharger cet exemple — 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

    Télécharger cet exemple — 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

    Télécharger cet exemple — 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

    Télécharger cet exemple — 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)
    }
    
    

    Exécuter et adapter

    cargo run -- --fr
    

    Remplacez la temporisation par votre travail asynchrone réel : marquez la couche busy au départ, puis fermez-la par DismissReason::Programmatic à l’arrivée du résultat. Ajoutez une couche avec DialogLayerSpec et un contrôle avec DialogFocusSpec ; utilisez set_enabled lorsque son état change. Le compilateur signale chaque match à compléter. Avec tab-policy: DialogTabPolicy.native, Slint parcourt lui-même les contrôles montés. Réglez alors modal-layer sur chaque KitDialogSurface (nombres positifs distincts pour des couches imbriquées) et donnez le même modal-layer aux contrôles Kit de la couche : les autres contrôles Kit deviennent inertes sans jeton. Les contrôles personnalisés ne lisent pas ce contexte : l’hôte les désactive comme avant. Les calendriers, sélecteurs de date, d’heure, de couleur et de fichier, claviers numériques, zones défilantes, formulaires, centres de notifications, tableaux de données, listes de contenu, vues de texte, onglets, menus, accordéons, carrousels, fils d’Ariane et la pagination le lisent.

    Slint 1.19.0 ne fournit ni rôle de dialogue, ni état modal, ni propriété permettant de masquer un sous-arbre accessible tout en le gardant visible. Le panneau est annoncé comme groupbox avec son nom ; les contrôles couverts restent lisibles dans l’ordre de parcours du lecteur d’écran malgré leur désactivation. Le contrat « arrière-plan neutralisé » concerne les actions, pas l’isolement du parcours accessible.

    Les tests du kit prouvent ce contrat sans écran : retour du focus au déclencheur exact, couches imbriquées, Tab/Maj+Tab, Échap/Retour, état occupé et arrière-plan inerte. Ils ne qualifient ni les lecteurs d’écran ni les méthodes de saisie : vérifiez-les sur la plateforme cible. Consultez la référence KitDialogSurface et la référence KitFocusTarget pour l’API complète.