Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat(desktop-gpui): keyboard navigation and focus rings in the main, settings and mode select windows

Richie McIlroy15785e92a4b3
diff --git a/apps/desktop-gpui/src/hotkeys.rs b/apps/desktop-gpui/src/hotkeys.rs
index 46bb17797..175906491 100644
--- a/apps/desktop-gpui/src/hotkeys.rs
+++ b/apps/desktop-gpui/src/hotkeys.rs
@@ -216,6 +216,11 @@ pub fn pause(cx: &mut App) -> bool {
true
}
+pub fn is_paused(cx: &App) -> bool {
+ cx.try_global::<Hotkeys>()
+ .is_some_and(|hotkeys| hotkeys.paused)
+}
+
pub fn editing_blocked(cx: &App) -> bool {
#[cfg(target_os = "linux")]
if cx
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index cabac8bdd..eb97a6dfc 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -851,6 +851,8 @@ pub struct MainWindow {
input_enumeration_gate: devices::InputEnumerationGate,
/// `scheduleTargetListPrewarm` (`new-main/index.tsx:1897-1965`).
prewarm_task: Option<gpui::Task<()>>,
+ keyboard_nav: bool,
+ _keyboard_nav: gpui::Subscription,
}
/// `createLicenseQuery` (`utils/queries.ts:257-273`): pro from the auth
@@ -1059,6 +1061,8 @@ impl MainWindow {
})
.detach();
+ let keyboard_nav = ui::keyboard_nav::install(window, cx, Self::keyboard_nav_blocked);
+
Self {
theme,
// `rawOptions.mode` -- the recording mode is a persisted setting,
@@ -1113,9 +1117,19 @@ impl MainWindow {
input_poll_generation: 0,
input_enumeration_gate: devices::InputEnumerationGate::default(),
prewarm_task: None,
+ keyboard_nav: false,
+ _keyboard_nav: keyboard_nav,
}
}
+ fn keyboard_nav_blocked(&self, cx: &gpui::App) -> bool {
+ self.session.read(cx).phase != Phase::Idle
+ || self.microphone_warning.is_some()
+ || self.sign_in_prompt.is_some()
+ || self.idle_error(cx).is_some()
+ || app_windows::clean_capture_pending(cx)
+ }
+
/// Kick off device enumeration.
///
/// Deliberately *not* called from `new`. `new` runs inside `open_window`'s
@@ -2695,6 +2709,7 @@ impl MainWindow {
impl Render for MainWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
+ self.keyboard_nav = ui::keyboard_nav::active(window, cx);
let theme = self.theme;
let meter_active = self.panel.is_none()
&& self.microphone.is_some()
@@ -2762,6 +2777,7 @@ impl Render for MainWindow {
cx.stop_propagation();
}
}))
+ .capture_any_mouse_down(|_, window, cx| ui::keyboard_nav::pointer_used(window, cx))
}
}
@@ -3456,6 +3472,7 @@ impl MainWindow {
/// 8px from the window edges (`mx-2`).
fn render_header_actions(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = self.theme;
+ let keyboard_nav = self.keyboard_nav;
// `IconButton::header`: a 20px hit box with no fill, `text-gray-11`
// going to `text-gray-12` on hover.
@@ -3474,6 +3491,9 @@ impl MainWindow {
.group(id)
.when(cfg!(target_os = "windows"), |this| this.occlude())
.tab_index(0)
+ .when(keyboard_nav, ui::keyboard_nav::ring)
+ .role(gpui::Role::Button)
+ .aria_label(label)
.flex()
.items_center()
.justify_center()
@@ -3901,6 +3921,9 @@ impl MainWindow {
.child(
div()
.id("panel-back")
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Button)
+ .aria_label("Back")
.flex()
.flex_row()
.items_center()
@@ -5631,6 +5654,10 @@ impl MainWindow {
div()
.id(id)
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Button)
+ .aria_label(label.clone())
+ .aria_selected(selected)
.flex()
.flex_col()
.w(px(self.target_card_width()))
@@ -5876,6 +5903,10 @@ impl MainWindow {
div()
.id(id)
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Button)
+ .aria_label(label.clone())
+ .aria_selected(selected)
.relative()
.flex()
.flex_row()
@@ -6150,6 +6181,10 @@ impl MainWindow {
div()
.id(SharedString::from(id))
.tab_index(0)
+ .when(self.keyboard_nav, ui::keyboard_nav::ring)
+ .role(gpui::Role::Button)
+ .aria_label(mode.panel_title())
+ .aria_selected(selected)
.relative()
.on_hover(cx.listener(move |this, hovered, _, cx| {
this.update_mode_hover(mode, false, *hovered, cx);
@@ -6218,6 +6253,9 @@ impl MainWindow {
div()
.id("mode-info")
.tab_index(0)
+ .when(self.keyboard_nav, ui::keyboard_nav::ring)
+ .role(gpui::Role::Button)
+ .aria_label("Recording mode info")
.tooltip(move |_, cx| ui::Tooltip::new(&theme, "Recording mode info").view(cx))
.tooltip_show_delay(ui::TOOLTIP_SHOW_DELAY)
.absolute()
@@ -6303,6 +6341,12 @@ impl MainWindow {
.child(
div()
.id(dropdown_id.clone())
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Button)
+ .aria_label(match target {
+ TargetType::Display => "Choose a display",
+ _ => "Choose a window",
+ })
.flex()
.w(px(28.))
.rounded_r(px(9.))
@@ -6394,6 +6438,10 @@ impl MainWindow {
let base = div()
.id(SharedString::from(target.label()))
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Button)
+ .aria_label(target.label())
+ .aria_selected(selected)
.flex()
.flex_1()
.py(px(8.))
@@ -6567,6 +6615,9 @@ impl MainWindow {
div()
.id(SharedString::from(id))
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Button)
+ .aria_label(label.clone())
.relative()
.flex()
.flex_row()
diff --git a/apps/desktop-gpui/src/menus.rs b/apps/desktop-gpui/src/menus.rs
index 8e3996369..7cf9201db 100644
--- a/apps/desktop-gpui/src/menus.rs
+++ b/apps/desktop-gpui/src/menus.rs
@@ -26,9 +26,11 @@ use gpui::{
use crate::{
app_windows::{self, AppWindows},
+ hotkeys,
main_window::MainWindow,
platform,
session::{Phase, RecordingSession},
+ settings_window::Page,
store,
ui::text_input,
};
@@ -66,6 +68,8 @@ actions!(
Zoom,
/// `PredefinedMenuItem::fullscreen` -- ⌃⌘F.
ToggleFullscreen,
+ /// Settings… -- ⌘, on macOS, Ctrl+, on Windows and Linux.
+ OpenSettings,
]
);
@@ -77,14 +81,7 @@ pub fn init(cx: &mut App) {
// commands. Deliberately *not* including cmd-z/x/c/v/a -- those stay the
// text field's own `TextInput`-scoped bindings (and, for the editor, its
// `on_key_down` project-undo). A global binding here would shadow both.
- cx.bind_keys([
- KeyBinding::new("cmd-q", Quit, None),
- KeyBinding::new("cmd-h", HideSelf, None),
- KeyBinding::new("alt-cmd-h", HideOthers, None),
- KeyBinding::new("cmd-w", CloseWindow, None),
- KeyBinding::new("cmd-m", Minimize, None),
- KeyBinding::new("ctrl-cmd-f", ToggleFullscreen, None),
- ]);
+ cx.bind_keys(bindings());
cx.on_action(|_: &About, cx: &mut App| {
// Ordering a window front re-enters gpui's window callbacks, so it runs
@@ -99,6 +96,24 @@ pub fn init(cx: &mut App) {
cx.on_action(|_: &CloseWindow, cx: &mut App| close_key_window(cx));
cx.on_action(|_: &Minimize, cx: &mut App| with_key_native(cx, platform::minimize_native));
cx.on_action(|_: &Zoom, cx: &mut App| with_key_native(cx, platform::zoom_native));
+ cx.on_action(|_: &OpenSettings, cx: &mut App| {
+ // While a recording runs, onboarding is up or the Shortcuts page is
+ // recording a combo, the chord belongs to whatever has focus.
+ let idle = RecordingSession::global(cx).read(cx).phase == Phase::Idle;
+ let onboarding_open = cx
+ .try_global::<AppWindows>()
+ .is_some_and(|windows| windows.onboarding.is_some());
+ if !settings_shortcut_allowed(idle, onboarding_open, hotkeys::is_paused(cx)) {
+ cx.propagate();
+ return;
+ }
+ // Deferred: the keystroke arrives inside the key window's dispatch, and
+ // `open_settings` updates the settings window, which may be that one.
+ cx.defer(|cx: &mut App| {
+ app_windows::open_settings(Page::General, cx);
+ cx.activate(true);
+ });
+ });
cx.on_action(|_: &ToggleFullscreen, cx: &mut App| {
#[cfg(target_os = "windows")]
if let Some(handle) = cx.active_window() {
@@ -113,10 +128,27 @@ pub fn init(cx: &mut App) {
cx.set_menus(build_menus());
}
+pub(crate) fn bindings() -> Vec<KeyBinding> {
+ vec![
+ KeyBinding::new("cmd-q", Quit, None),
+ KeyBinding::new("cmd-h", HideSelf, None),
+ KeyBinding::new("alt-cmd-h", HideOthers, None),
+ KeyBinding::new("cmd-w", CloseWindow, None),
+ KeyBinding::new("cmd-m", Minimize, None),
+ KeyBinding::new("ctrl-cmd-f", ToggleFullscreen, None),
+ KeyBinding::new("secondary-,", OpenSettings, None),
+ ]
+}
+
+fn settings_shortcut_allowed(idle: bool, onboarding_open: bool, hotkeys_paused: bool) -> bool {
+ idle && !onboarding_open && !hotkeys_paused
+}
+
/// The menu bar model.
///
/// One-to-one with `build_macos_app_menu`, including the empty Help submenu
-/// (`Submenu::with_id_and_items(.., HELP_SUBMENU_ID, "Help", true, &[])`).
+/// (`Submenu::with_id_and_items(.., HELP_SUBMENU_ID, "Help", true, &[])`),
+/// plus the standard Settings… item the Tauri menu never had.
pub fn build_menus() -> Vec<Menu> {
vec![
Menu {
@@ -125,6 +157,8 @@ pub fn build_menus() -> Vec<Menu> {
items: vec![
MenuItem::action(format!("About {APP_NAME}"), About),
MenuItem::separator(),
+ MenuItem::action("Settings…", OpenSettings),
+ MenuItem::separator(),
MenuItem::os_submenu("Services", SystemMenuType::Services),
MenuItem::separator(),
MenuItem::action(format!("Hide {APP_NAME}"), HideSelf),
@@ -880,6 +914,58 @@ mod tests {
assert!(gate.pending.is_none());
}
+ #[test]
+ fn settings_shortcut_yields_to_recording_onboarding_and_the_recorder() {
+ assert!(settings_shortcut_allowed(true, false, false));
+ assert!(!settings_shortcut_allowed(false, false, false));
+ assert!(!settings_shortcut_allowed(true, true, false));
+ assert!(!settings_shortcut_allowed(true, false, true));
+ }
+
+ fn keystrokes(binding: &KeyBinding) -> Vec<gpui::Keystroke> {
+ binding
+ .keystrokes()
+ .iter()
+ .map(|keystroke| keystroke.inner().clone())
+ .collect()
+ }
+
+ #[test]
+ fn global_keymap_is_unchanged_apart_from_settings() {
+ let settings = if cfg!(target_os = "macos") {
+ "cmd-,"
+ } else {
+ "ctrl-,"
+ };
+ let expected: &[(&str, &dyn gpui::Action)] = &[
+ ("cmd-q", &Quit),
+ ("cmd-h", &HideSelf),
+ ("alt-cmd-h", &HideOthers),
+ ("cmd-w", &CloseWindow),
+ ("cmd-m", &Minimize),
+ ("ctrl-cmd-f", &ToggleFullscreen),
+ (settings, &OpenSettings),
+ ];
+ let bindings = bindings();
+ assert_eq!(bindings.len(), expected.len());
+ for (binding, (source, action)) in bindings.iter().zip(expected) {
+ assert_eq!(
+ keystrokes(binding),
+ vec![gpui::Keystroke::parse(source).unwrap()],
+ "{source}"
+ );
+ assert!(binding.action().partial_eq(*action), "{source}");
+ assert!(binding.predicate().is_none(), "{source}");
+ }
+ let mut seen = std::collections::HashSet::new();
+ for binding in &bindings {
+ assert!(
+ seen.insert(keystrokes(binding)),
+ "{binding:?} is bound twice"
+ );
+ }
+ }
+
/// The menu bar, transcribed from `build_macos_app_menu`. Separators are
/// spelled `"-"` so the ordering is checked too.
fn describe(menu: &Menu) -> (String, Vec<String>) {
@@ -907,6 +993,8 @@ mod tests {
vec![
"About Cap".to_string(),
"-".into(),
+ "Settings…".into(),
+ "-".into(),
"Services".into(),
"-".into(),
"Hide Cap".into(),
diff --git a/apps/desktop-gpui/src/mode_select_window.rs b/apps/desktop-gpui/src/mode_select_window.rs
index 660d27316..4f80b3352 100644
--- a/apps/desktop-gpui/src/mode_select_window.rs
+++ b/apps/desktop-gpui/src/mode_select_window.rs
@@ -9,11 +9,11 @@
use gpui::{
Context, FocusHandle, FontWeight, Hsla, InteractiveElement, IntoElement, ParentElement, Pixels,
- Point, Render, SharedString, StatefulInteractiveElement, Styled, Window, div,
- prelude::FluentBuilder, px, svg,
+ Point, Render, Role, SharedString, StatefulInteractiveElement, Styled, Subscription, Window,
+ div, prelude::FluentBuilder, px, svg,
};
-use crate::{main_window::Mode, theme::Theme};
+use crate::{main_window::Mode, theme::Theme, ui::keyboard_nav};
/// `.inner_size(580.0, 340.0)` / `.min_inner_size(580.0, 340.0)` /
/// `.resizable(false)` on the `ShowCapWindow::ModeSelect` arm in `windows.rs`,
@@ -45,6 +45,8 @@ pub struct ModeSelectWindow {
/// cannot drift.
mode: Mode,
focus: FocusHandle,
+ keyboard_nav: bool,
+ _keyboard_nav: Subscription,
}
impl ModeSelectWindow {
@@ -67,6 +69,8 @@ impl ModeSelectWindow {
theme: Theme::for_window(window, cx, false),
mode,
focus: cx.focus_handle(),
+ keyboard_nav: false,
+ _keyboard_nav: keyboard_nav::install(window, cx, |_, _| false),
}
}
@@ -104,6 +108,11 @@ impl ModeSelectWindow {
div()
.id(SharedString::from(mode.panel_title()))
+ .when(self.keyboard_nav, keyboard_nav::stop)
+ .role(Role::Button)
+ .aria_label(mode.panel_title())
+ .aria_description(mode.card_description())
+ .aria_selected(selected)
.relative()
.flex()
.flex_col()
@@ -236,10 +245,12 @@ impl ModeSelectWindow {
impl Render for ModeSelectWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
+ self.keyboard_nav = keyboard_nav::active(window, cx);
let theme = self.theme;
let shell = div()
.track_focus(&self.focus)
+ .capture_any_mouse_down(|_, window, cx| keyboard_nav::pointer_used(window, cx))
// `flex flex-col relative justify-center items-center min-h-screen
// bg-gray-1`
.size_full()
diff --git a/apps/desktop-gpui/src/settings_pages.rs b/apps/desktop-gpui/src/settings_pages.rs
index c0d5d6bb4..7f00fe3d1 100644
--- a/apps/desktop-gpui/src/settings_pages.rs
+++ b/apps/desktop-gpui/src/settings_pages.rs
@@ -20,12 +20,12 @@ use std::{
time::Duration,
};
+use cap_cli_install as cli_install;
use gpui::{
AppContext as _, Context, Entity, FontWeight, Hsla, InteractiveElement, IntoElement,
MouseButton, ParentElement, SharedString, StatefulInteractiveElement, Styled, Window, div,
prelude::FluentBuilder, px, rgb, svg,
};
-use cap_cli_install as cli_install;
use serde::Deserialize;
use serde_json::{Map, Value, json};
@@ -1329,6 +1329,10 @@ impl SettingsWindow {
cx.notify();
}
+ pub(crate) fn shortcut_listening(&self) -> bool {
+ self.pages.listening.is_some()
+ }
+
/// Leave recording mode without touching the binding. Safe to call when
/// nothing is recording; every exit path (Escape, a click elsewhere,
/// another page, the window losing focus or closing) lands here.
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index 52d2a2fd3..7d75af5b4 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -663,6 +663,8 @@ pub struct SettingsWindow {
_sign_in_subscriptions: [gpui::Subscription; 2],
user_profile: Option<UserProfile>,
profile_image: Option<Arc<RenderImage>>,
+ keyboard_nav: bool,
+ _keyboard_nav: gpui::Subscription,
}
impl SettingsWindow {
@@ -749,6 +751,9 @@ impl SettingsWindow {
let pages = crate::settings_pages::PagesState::new(window, cx);
let page_scroll = ScrollHandle::new();
+ let keyboard_nav = ui::keyboard_nav::install(window, cx, |this: &Self, _| {
+ this.menu.is_some() || this.shortcut_listening()
+ });
Self {
theme,
@@ -784,6 +789,8 @@ impl SettingsWindow {
_sign_in_subscriptions: sign_in_subscriptions,
user_profile,
profile_image: None,
+ keyboard_nav: false,
+ _keyboard_nav: keyboard_nav,
}
}
@@ -1553,6 +1560,7 @@ fn covers_default_exclusion(entry: &WindowExclusion, default: &WindowExclusion)
impl Render for SettingsWindow {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
self.sync_appearance(window, cx);
+ self.keyboard_nav = ui::keyboard_nav::active(window, cx);
let theme = self.theme;
if self.page == Page::Quality
&& let Some(mode) = self.quality_scroll_request.take()
@@ -1567,6 +1575,7 @@ impl Render for SettingsWindow {
let shell = div()
.track_focus(&self.focus)
+ .capture_any_mouse_down(|_, window, cx| ui::keyboard_nav::pointer_used(window, cx))
// `(window-chrome).tsx` binds Cmd-W to `getCurrentWindow().close()`
// for every chrome window. Escape is not bound there and is not
// bound here.
@@ -1774,6 +1783,7 @@ impl SettingsWindow {
div()
.id("settings-nav")
+ .role(gpui::Role::TabList)
.flex()
.flex_col()
// `.cap-settings-nav { padding: 0 var(--sidebar-padding-x)
@@ -1788,6 +1798,10 @@ impl SettingsWindow {
let selected = page == self.page;
div()
.id(SharedString::from(page.slug()))
+ .when(self.keyboard_nav, ui::keyboard_nav::stop)
+ .role(gpui::Role::Tab)
+ .aria_label(page.label())
+ .aria_selected(selected)
.flex()
.flex_row()
.items_center()
diff --git a/apps/desktop-gpui/src/ui/button.rs b/apps/desktop-gpui/src/ui/button.rs
index 048cadefa..fc5741245 100644
--- a/apps/desktop-gpui/src/ui/button.rs
+++ b/apps/desktop-gpui/src/ui/button.rs
@@ -8,7 +8,7 @@ use gpui::{
prelude::FluentBuilder, px, svg,
};
-use super::menu::OpenHandler;
+use super::{keyboard_nav, menu::OpenHandler};
use crate::theme::Theme;
/// The click handler every component takes. `cx.listener(..)` produces exactly
@@ -408,7 +408,7 @@ fn radix_paint(theme: &Theme, variant: ButtonVariant) -> ButtonPaint {
}
impl RenderOnce for Button {
- fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
+ fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let Button {
id,
label,
@@ -433,6 +433,8 @@ impl RenderOnce for Button {
div()
.id(id)
.tab_index(0)
+ .tab_stop(!disabled)
+ .when(keyboard_nav::active(window, cx), keyboard_nav::ring)
.flex()
.flex_row()
.items_center()
@@ -635,7 +637,7 @@ impl IconButton {
}
impl RenderOnce for IconButton {
- fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
+ fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let IconButton {
id,
icon,
@@ -659,6 +661,8 @@ impl RenderOnce for IconButton {
.id(id)
.when(occlude, |this| this.occlude())
.tab_index(0)
+ .tab_stop(!disabled)
+ .when(keyboard_nav::active(window, cx), keyboard_nav::ring)
.flex()
.items_center()
.justify_center()
diff --git a/apps/desktop-gpui/src/ui/keyboard_nav.rs b/apps/desktop-gpui/src/ui/keyboard_nav.rs
new file mode 100644
index 000000000..3692c0b28
--- /dev/null
+++ b/apps/desktop-gpui/src/ui/keyboard_nav.rs
@@ -0,0 +1,183 @@
+//! Tab / Shift-Tab focus navigation for the windows that opt in.
+//!
+//! Nothing in a window has focus until the user presses Tab, and the main
+//! window has no root focus handle, so a key binding would never match there:
+//! with no focused node only the root receives keys. An owner-scoped
+//! keystroke interceptor runs before bindings and element listeners instead.
+//!
+//! Tab stops that are not already focusable are only added while a window is
+//! in keyboard mode, which starts on Tab and ends on the next mouse press. A
+//! focusable element takes focus on click and fires its click handler on
+//! Enter/Space key-up, so adding them unconditionally would change what mouse
+//! users get.
+
+use std::collections::HashSet;
+
+use gpui::{
+ App, BoxShadow, Context, Global, InteractiveElement, Keystroke, Styled, Subscription, Window,
+ WindowId, point, px, rgb,
+};
+
+use crate::{theme::Theme, ui::text_input::text_input_is_composing};
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Direction {
+ Next,
+ Previous,
+}
+
+pub fn direction(keystroke: &Keystroke) -> Option<Direction> {
+ let modifiers = keystroke.modifiers;
+ if keystroke.key != "tab"
+ || modifiers.control
+ || modifiers.alt
+ || modifiers.platform
+ || modifiers.function
+ {
+ return None;
+ }
+ Some(if modifiers.shift {
+ Direction::Previous
+ } else {
+ Direction::Next
+ })
+}
+
+fn takes_tab(blocked: bool, prompt_active: bool, composing: bool) -> bool {
+ !(blocked || prompt_active || composing)
+}
+
+#[derive(Default)]
+struct KeyboardWindows(HashSet<WindowId>);
+
+impl Global for KeyboardWindows {}
+
+pub fn active(window: &Window, cx: &App) -> bool {
+ cx.try_global::<KeyboardWindows>()
+ .is_some_and(|windows| windows.0.contains(&window.window_handle().window_id()))
+}
+
+pub fn pointer_used(window: &mut Window, cx: &mut App) {
+ if !active(window, cx) {
+ return;
+ }
+ cx.global_mut::<KeyboardWindows>()
+ .0
+ .remove(&window.window_handle().window_id());
+ window.refresh();
+}
+
+/// Route Tab in `window` to focus navigation. `blocked` lets the owner keep
+/// Tab for itself, e.g. while a shortcut recorder or a modal is up.
+pub fn install<V: 'static>(
+ window: &Window,
+ cx: &mut Context<V>,
+ blocked: impl Fn(&V, &App) -> bool + 'static,
+) -> Subscription {
+ let owner = window.window_handle().window_id();
+ let view = cx.weak_entity();
+ cx.intercept_keystrokes(move |event, window, cx| {
+ if window.window_handle().window_id() != owner {
+ return;
+ }
+ let Some(direction) = direction(&event.keystroke) else {
+ return;
+ };
+ let Some(view) = view.upgrade() else {
+ return;
+ };
+ if !takes_tab(
+ blocked(view.read(cx), cx),
+ window.has_active_prompt(),
+ text_input_is_composing(window, cx),
+ ) {
+ return;
+ }
+ navigate(direction, window, cx);
+ window.prevent_default();
+ cx.stop_propagation();
+ })
+}
+
+fn navigate(direction: Direction, window: &mut Window, cx: &mut App) {
+ let entered = cx
+ .default_global::<KeyboardWindows>()
+ .0
+ .insert(window.window_handle().window_id());
+ if !entered {
+ move_focus(direction, window, cx);
+ return;
+ }
+ // The stops gated on keyboard mode only exist from the next draw on, and
+ // `focus_next` walks the last rendered frame. Next-frame callbacks run
+ // before that frame draws, so the move waits one frame more.
+ window.refresh();
+ window.on_next_frame(move |window, _| {
+ window.on_next_frame(move |window, cx| move_focus(direction, window, cx));
+ });
+}
+
+fn move_focus(direction: Direction, window: &mut Window, cx: &mut App) {
+ match direction {
+ Direction::Next => window.focus_next(cx),
+ Direction::Previous => window.focus_prev(cx),
+ }
+}
+
+pub fn ring<E: InteractiveElement>(element: E) -> E {
+ element.focus_visible(|style| {
+ style.shadow(vec![BoxShadow {
+ color: rgb(Theme::SETTINGS_ACCENT).into(),
+ offset: point(px(0.), px(0.)),
+ blur_radius: px(0.),
+ spread_radius: px(2.),
+ inset: true,
+ }])
+ })
+}
+
+pub fn stop<E: InteractiveElement>(element: E) -> E {
+ ring(element.tab_index(0))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn parsed(source: &str) -> Option<Direction> {
+ direction(&Keystroke::parse(source).unwrap())
+ }
+
+ #[test]
+ fn only_bare_tab_and_shift_tab_navigate() {
+ assert_eq!(parsed("tab"), Some(Direction::Next));
+ assert_eq!(parsed("shift-tab"), Some(Direction::Previous));
+ for source in [
+ "ctrl-tab",
+ "ctrl-shift-tab",
+ "alt-tab",
+ "cmd-tab",
+ "fn-tab",
+ "secondary-tab",
+ "enter",
+ "space",
+ "escape",
+ "t",
+ ] {
+ assert_eq!(parsed(source), None, "{source}");
+ }
+ }
+
+ #[test]
+ fn tab_is_left_alone_while_anything_else_owns_it() {
+ assert!(takes_tab(false, false, false));
+ for (blocked, prompt_active, composing) in [
+ (true, false, false),
+ (false, true, false),
+ (false, false, true),
+ (true, true, true),
+ ] {
+ assert!(!takes_tab(blocked, prompt_active, composing));
+ }
+ }
+}
diff --git a/apps/desktop-gpui/src/ui/mod.rs b/apps/desktop-gpui/src/ui/mod.rs
index e69609d4b..5c64f3f2c 100644
--- a/apps/desktop-gpui/src/ui/mod.rs
+++ b/apps/desktop-gpui/src/ui/mod.rs
@@ -46,6 +46,7 @@ mod color_picker;
mod editor_button;
mod field;
mod kbd;
+pub mod keyboard_nav;
mod menu;
mod microphone_level;
mod number_field;
diff --git a/apps/desktop-gpui/src/ui/select.rs b/apps/desktop-gpui/src/ui/select.rs
index 172d2d398..fd5bd3a43 100644
--- a/apps/desktop-gpui/src/ui/select.rs
+++ b/apps/desktop-gpui/src/ui/select.rs
@@ -12,7 +12,7 @@ use gpui::{
div, prelude::FluentBuilder, px, svg,
};
-use super::menu::OpenHandler;
+use super::{keyboard_nav, menu::OpenHandler};
use crate::theme::Theme;
#[derive(IntoElement)]
@@ -126,7 +126,7 @@ impl Select {
}
impl RenderOnce for Select {
- fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
+ fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let Select {
id,
label,
@@ -150,6 +150,7 @@ impl RenderOnce for Select {
div()
.id(id)
+ .when(keyboard_nav::active(window, cx), keyboard_nav::ring)
.flex()
.flex_row()
.items_center()
diff --git a/apps/desktop-gpui/src/ui/text_input.rs b/apps/desktop-gpui/src/ui/text_input.rs
index 88bc8eb30..940feff89 100644
--- a/apps/desktop-gpui/src/ui/text_input.rs
+++ b/apps/desktop-gpui/src/ui/text_input.rs
@@ -213,6 +213,21 @@ pub fn text_input_has_focus(window: &Window, cx: &App) -> bool {
})
}
+/// Is a focused field in this window composing IME text? Tab belongs to the
+/// input method then.
+pub fn text_input_is_composing(window: &Window, cx: &App) -> bool {
+ let Some(live) = cx.try_global::<LiveInputs>() else {
+ return false;
+ };
+ let inputs = live.0.borrow();
+ inputs.iter().any(|weak| {
+ weak.upgrade().is_some_and(|entity| {
+ let input = entity.read(cx);
+ input.marked_range.is_some() && input.focus.is_focused(window)
+ })
+ })
+}
+
fn register_live_input(weak: WeakEntity<TextInputState>, cx: &mut App) {
if !cx.has_global::<LiveInputs>() {
cx.set_global(LiveInputs::default());
@@ -1828,7 +1843,11 @@ impl RenderOnce for TextInput {
let state = self.state.clone();
let (focus, multi_line, disabled) = {
let read = state.read(cx);
- (read.focus.clone(), read.multi_line, read.disabled)
+ (
+ read.focus.clone().tab_stop(!read.disabled),
+ read.multi_line,
+ read.disabled,
+ )
};
let focused = focus.is_focused(window);
// `leading-normal` on a `text-xs` input is 1.35 in this font stack;
diff --git a/apps/desktop-gpui/src/ui/toggle.rs b/apps/desktop-gpui/src/ui/toggle.rs
index ff8e690b5..ec5c136cd 100644
--- a/apps/desktop-gpui/src/ui/toggle.rs
+++ b/apps/desktop-gpui/src/ui/toggle.rs
@@ -9,6 +9,7 @@ use gpui::{
RenderOnce, StatefulInteractiveElement, Styled, Window, div, prelude::FluentBuilder, px,
};
+use super::keyboard_nav;
use crate::theme::Theme;
/// `cva` sizes. `lg` is `w-14 h-7 p-0.75` with a `size-6` thumb; no window
@@ -125,7 +126,7 @@ impl Toggle {
}
impl RenderOnce for Toggle {
- fn render(self, _window: &mut Window, _cx: &mut App) -> impl IntoElement {
+ fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let Toggle {
id,
checked,
@@ -140,6 +141,10 @@ impl RenderOnce for Toggle {
div()
.id(id)
+ .when(
+ keyboard_nav::active(window, cx) && !disabled,
+ keyboard_nav::stop,
+ )
.w(width)
.h(height)
.p(padding)