diff --git a/crates/text/src/ui/editor.rs b/crates/text/src/ui/editor.rs index 13f35cd6a..47abe4a89 100644 --- a/crates/text/src/ui/editor.rs +++ b/crates/text/src/ui/editor.rs @@ -27,8 +27,7 @@ use std::ops::Range; use craft_behavior::kurbo::Point; use craft_behavior::{ - CancelReason, CanvasView, CursorIcon, CursorPriority, EditCommand, EditorInput, GesturePhase, Granularity, Metrics, MoveMods, NavMove, - PressPhase, Sense, TextPos, + CancelReason, CanvasView, CursorIcon, CursorPriority, EditCommand, EditorInput, GesturePhase, Metrics, PressPhase, Sense, TextPos, }; use craft_ui::canvas::canvas_space; use craft_ui::contract::{ @@ -302,8 +301,9 @@ impl Outcome for TextEditorOutput { /// the text's screen bounds while the session is open and drops it when the session ends. /// /// What the user sees and does: -/// - A caret drawn as two strokes (light under dark), so it shows on any image. It blinks in Photoshop's rhythm, -/// solid while dragging and restarting at each edit or move. Marked text is underlined, the converted segment +/// - A caret drawn as two strokes (light under dark), so it shows on any image. It blinks in Photoshop's rhythm for +/// as long as the session runs, also while another control holds the keys, solid while dragging and restarting at +/// each edit or move. Marked text is underlined, the converted segment /// thicker. /// - Clicks: one places the caret, Shift-click extends; quick clicks in one spot select more: two a word, three the /// laid-out line, four the paragraph, five all text, the sixth starts over (Photoshop). Dragging extends by char, @@ -312,7 +312,9 @@ impl Outcome for TextEditorOutput { /// line, Cmd+Up and Cmd+Down to the text's start or end, Home and End to the line's edges, Shift extends any of /// them. Backspace and Delete by char, Alt by word, Cmd+Backspace to the line start. Cmd+A all, Cmd+C, Cmd+X and /// Cmd+V the clipboard. Enter a line break; Cmd+Enter commits; Esc commits or cancels. The -/// [`TextEditorCommand`]s format. In vertical text the arrows turn with the flow. +/// [`TextEditorCommand`]s format. In vertical text the arrows turn with the flow, the formatting keys too: Alt+Up +/// and Alt+Down track, Alt+Left and Alt+Right set the leading. A formatting key the host does not take moves the +/// caret as its arrow does: a line, a word, or with Cmd to the text's start or end; Shift extends. /// - Typed straight quotes become the language's marks while [`smart_quotes`](Self::smart_quotes) is set; pasted /// text is kept as it is. Pasted line endings become `\n`. #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] @@ -536,14 +538,14 @@ impl Component for TextEditor<'_> { } for command in fired { + let command = command.along_flow(edits.host.vertical()); let empty = edits.selection.is_empty(); match command.style_key(empty) { None => edits.done.commit |= edits.session.preedit.is_none(), Some(key) => { let handled = edits.host.style_key(key, edits.selection); - if !handled && let Some(forward) = command.word_move() { - let step = if forward { NavMove::Forward } else { NavMove::Back }; - edits.motion(step, MoveMods::new(false, false, Granularity::Word)); + if !handled && let Some((step, mods)) = command.fallback() { + edits.move_along(step, mods); } } } @@ -612,7 +614,6 @@ impl Component for TextEditor<'_> { let caret = self.host.caret(caret_at, None); let caret_rect = caret.map(|CaretLine { top, bottom }| Rect::from_two_pos(screen(top), screen(bottom)).expand(1.0)); if range.is_empty() - && cx.is_focused() && (session.dragging.is_some() || cx.blink(session.blink_start)) && let Some(CaretLine { top, bottom }) = caret { diff --git a/crates/text/src/ui/editor/commands.rs b/crates/text/src/ui/editor/commands.rs index a8f26391b..553f548b2 100644 --- a/crates/text/src/ui/editor/commands.rs +++ b/crates/text/src/ui/editor/commands.rs @@ -1,6 +1,8 @@ //! The editor's own commands: Photoshop's type formatting keys and the commit chord. The editor reads them with //! `take_command`, so the keymap rebinds them like any command; the editor reads no raw keys. +use craft_behavior::{Granularity, MoveMods, NavMove}; + use super::{CharToggle, StyleKey}; /// How far a leading, baseline or tracking step moves, in points or thousandths of an em. @@ -103,13 +105,45 @@ impl TextEditorCommand { }) } - /// Whether the command is a tracking step that moves the caret by word when the host has no pair to kern: - /// the direction is forward for a loosen step. - pub(super) fn word_move(self) -> Option { + /// The command the same key means in text that runs vertically: the arrows follow the flow (Up is Left, Down + /// Right, Left Down, Right Up), so the leading and tracking steps trade places. Other commands and horizontal text + /// unchanged. + pub(super) fn along_flow(self, vertical: bool) -> Self { + use TextEditorCommand as C; + if !vertical { + return self; + } match self { - TextEditorCommand::TrackingLess | TextEditorCommand::TrackingLessFar => Some(false), - TextEditorCommand::TrackingMore | TextEditorCommand::TrackingMoreFar => Some(true), - _ => None, + C::LeadingLess => C::TrackingLess, + C::LeadingMore => C::TrackingMore, + C::LeadingLessFar => C::TrackingLessFar, + C::LeadingMoreFar => C::TrackingMoreFar, + C::TrackingLess => C::LeadingMore, + C::TrackingMore => C::LeadingLess, + C::TrackingLessFar => C::LeadingMoreFar, + C::TrackingMoreFar => C::LeadingLessFar, + other => other, } } + + /// The caret move along the text that the command's arrow key makes when the host takes no formatting step: + /// leading a line up or down (with the command modifier to the text's start or end), baseline the same while + /// extending the selection, tracking a word back or forward. `None` for the commands without an arrow. + pub(super) fn fallback(self) -> Option<(NavMove, MoveMods)> { + use TextEditorCommand as C; + let line = |extend: bool, by: Granularity| MoveMods::new(extend, false, by); + Some(match self { + C::LeadingLess => (NavMove::Up, line(false, Granularity::Unit)), + C::LeadingMore => (NavMove::Down, line(false, Granularity::Unit)), + C::LeadingLessFar => (NavMove::Up, line(false, Granularity::Document)), + C::LeadingMoreFar => (NavMove::Down, line(false, Granularity::Document)), + C::BaselineUp => (NavMove::Up, line(true, Granularity::Unit)), + C::BaselineDown => (NavMove::Down, line(true, Granularity::Unit)), + C::BaselineUpFar => (NavMove::Up, line(true, Granularity::Document)), + C::BaselineDownFar => (NavMove::Down, line(true, Granularity::Document)), + C::TrackingLess | C::TrackingLessFar => (NavMove::Back, line(false, Granularity::Word)), + C::TrackingMore | C::TrackingMoreFar => (NavMove::Forward, line(false, Granularity::Word)), + _ => return None, + }) + } } diff --git a/crates/text/src/ui/editor/edits.rs b/crates/text/src/ui/editor/edits.rs index 80b21cbc6..5c200ef5c 100644 --- a/crates/text/src/ui/editor/edits.rs +++ b/crates/text/src/ui/editor/edits.rs @@ -295,14 +295,19 @@ impl Edits<'_> { } } - /// A logical move of the caret. + /// The caret move an arrow key means, in the flow of the text: in vertical text Up is the previous char. pub fn motion(&mut self, step: NavMove, mods: MoveMods) { + let step = flow_move(step, self.host.vertical()); + self.move_along(step, mods); + } + + /// A move of the caret along the text, whatever its flow: Back and Forward by char or word, Up and Down by line. + pub fn move_along(&mut self, step: NavMove, mods: MoveMods) { self.clamp_selection(); let text = self.host.text().to_owned(); let chars = text.chars().count(); let caret = self.selection.caret; let range = self.selection.range(); - let step = flow_move(step, self.host.vertical()); let to = match step { NavMove::Back | NavMove::Forward => { let forward = step == NavMove::Forward; diff --git a/crates/text/tests/it/editor.rs b/crates/text/tests/it/editor.rs index 696ede708..fd6d889cc 100644 --- a/crates/text/tests/it/editor.rs +++ b/crates/text/tests/it/editor.rs @@ -1,4 +1,4 @@ -//! The text editor over an in-memory host: one line, one unit per char. +//! The text editor over an in-memory host: lines of four chars, one unit per char. use std::cell::{Cell, RefCell}; use std::ops::Range; @@ -6,7 +6,7 @@ use std::rc::Rc; use craft_behavior::kurbo::Point; use craft_text::quotes::QuoteStyle; -use craft_text::ui::editor::{CaretLine, EditKind, HostLine, TextEditor, TextEditorHost, TextSelection}; +use craft_text::ui::editor::{CaretLine, EditKind, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection}; use craft_ui::canvas::Canvas; use craft_ui::contract::{Bind, Show as _, ShowContainer as _}; use craft_ui::testing::{Fixture, trial}; @@ -17,8 +17,15 @@ struct Host { text: String, revision: u64, vertical: bool, + /// The host applies formatting keys. + formats: bool, + /// The formatting keys the editor asked for. + styles: Vec, } +/// The chars of one line. +const LINE: usize = 4; + impl TextEditorHost for Host { fn text(&self) -> &str { &self.text @@ -65,24 +72,35 @@ impl TextEditorHost for Host { 0..self.text.chars().count() } - fn line_step(&mut self, offset: usize, _: i32) -> usize { - offset + fn line_step(&mut self, offset: usize, lines: i32) -> usize { + (offset as i64 + i64::from(lines) * LINE as i64).clamp(0, self.text.chars().count() as i64) as usize } fn line_edge(&mut self, offset: usize, end: bool) -> usize { let _ = offset; if end { self.text.chars().count() } else { 0 } } + + fn style_key(&mut self, key: StyleKey, _: TextSelection) -> bool { + self.styles.push(key); + self.formats + } } struct Session { fixture: Fixture, host: Rc>, + selection: Rc>, commits: Rc>, } fn session(text: &str, quotes: Option) -> Session { - let host = Rc::new(RefCell::new(Host { text: text.to_owned(), ..Host::default() })); + session_on(Host { text: text.to_owned(), ..Host::default() }, quotes) +} + +fn session_on(host: Host, quotes: Option) -> Session { + let text = host.text.clone(); + let host = Rc::new(RefCell::new(host)); let selection = Rc::new(RefCell::new(TextSelection::caret_at(text.chars().count()))); let commits = Rc::new(Cell::new(0)); let (shown_host, shown_selection, shown_commits) = (Rc::clone(&host), Rc::clone(&selection), Rc::clone(&commits)); @@ -97,7 +115,7 @@ fn session(text: &str, quotes: Option) -> Session { }); }); fixture.settle(); - Session { fixture, host, commits } + Session { fixture, host, selection, commits } } impl Session { @@ -122,3 +140,22 @@ fn command_enter_commits_one_session_and_a_session_without_edits_commits_nothing assert_eq!(editor.commits.get(), 1); assert_eq!(editor.text(), "abcd"); } + +/// In vertical text Alt+Down follows the flow and loosens the tracking; a host that applies no formatting leaves +/// Alt+Up to move the caret a line up. +#[trial] +fn formatting_keys_follow_the_flow_and_fall_back_to_caret_moves() { + let mut vertical = session_on(Host { text: "abcdefgh".to_owned(), vertical: true, formats: true, ..Host::default() }, None); + vertical.focus(); + vertical.fixture.key(Key::ArrowDown, Modifiers::ALT).settle(); + let asked = vertical.host.borrow().styles.last().copied(); + assert!(matches!(asked, Some(StyleKey::Kern(by) | StyleKey::Tracking(by)) if by > 0.0), "Alt+Down tracks in vertical text: {asked:?}"); + + let mut plain = session_on(Host { text: "abcdefgh".to_owned(), ..Host::default() }, None); + plain.focus(); + let before = plain.selection.borrow().caret; + assert!(before >= LINE, "the click left the caret past the first line"); + plain.fixture.key(Key::ArrowUp, Modifiers::ALT).settle(); + assert!(!plain.host.borrow().styles.is_empty(), "the host was asked for the leading step"); + assert_eq!(plain.selection.borrow().caret, before.saturating_sub(LINE), "the step the host did not take moved the caret a line up"); +}