mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 05:37:04 +00:00
pdf-forms-w2: net change of 2 commits
- pdf-forms-w2: written from its sheet - pdf-forms-w2: review fixes (review-1)
This commit is contained in:
@@ -1,7 +1,8 @@
|
||||
//! The direction lock of the move gesture.
|
||||
|
||||
use craft_behavior::geometry::{Directions, lock_direction};
|
||||
use kurbo::Vec2;
|
||||
use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, lock_direction};
|
||||
use craft_keymap::Mods;
|
||||
use kurbo::{Point, Vec2};
|
||||
|
||||
fn polar(deg: f64, len: f64) -> Vec2 {
|
||||
let a = deg.to_radians();
|
||||
@@ -19,3 +20,16 @@ fn lock_direction_keeps_the_axis_until_eight_degrees_past_half() {
|
||||
let switched = lock_direction(polar(31.0, 10.0), Some(axis), Directions::Eight);
|
||||
assert!((switched.y - switched.x).abs() < 1e-9 && switched.y > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shift_move_with_four_directions_locks_an_axis_and_frees_it_when_shift_is_let_go() {
|
||||
let mut drag = MoveGesture::press(&ConstrainStyle::new(4.0, 4.0), Point::ZERO, Mods::SHIFT, Directions::Four);
|
||||
let at = Point::new(10.0, 3.0);
|
||||
let locked = drag.follow(at, Mods::SHIFT, 1.0).expect("the move changed the value");
|
||||
assert_eq!(locked.delta.y, 0.0, "Shift holds the offset to the horizontal axis: {:?}", locked.delta);
|
||||
assert!(locked.delta.x > 0.0, "{:?}", locked.delta);
|
||||
assert!(drag.locked().is_some(), "the lock is remembered while Shift is down");
|
||||
let free = drag.follow(at, Mods::NONE, 1.0).expect("letting Shift go changed the value");
|
||||
assert_eq!(free.delta, Vec2::new(10.0, 3.0), "without Shift the offset is free");
|
||||
assert_eq!(drag.locked(), None, "the lock is forgotten when Shift is let go");
|
||||
}
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
//! The column bar: a divider drag moves the two columns it divides.
|
||||
//! The column bar: a divider drag or an arrow key moves the two columns it divides.
|
||||
|
||||
use craft_pages::ui::ColumnBar;
|
||||
use craft_pages::ui::reading::MAX_COLUMNS;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::Vec2;
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
@@ -20,14 +21,7 @@ fn close(a: f64, b: f64) -> bool {
|
||||
|
||||
#[trial]
|
||||
fn a_divider_moves_only_the_two_columns_it_divides() {
|
||||
let widths = Rc::new(RefCell::new(vec![EQUAL; COLUMNS]));
|
||||
let seen = Rc::clone(&widths);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = seen.borrow().clone();
|
||||
ColumnBar::new("Columns", Bind::bound(&mut current)).show(ui);
|
||||
*seen.borrow_mut() = current;
|
||||
});
|
||||
fixture.settle();
|
||||
let (mut fixture, widths) = bar(vec![EQUAL; COLUMNS]);
|
||||
let divider = fixture.by_label("Column 2 width").expect("the second divider");
|
||||
fixture.drag(÷r, Vec2::new(FAR, 0.0));
|
||||
let widths = widths.borrow();
|
||||
@@ -36,3 +30,52 @@ fn a_divider_moves_only_the_two_columns_it_divides() {
|
||||
assert!(widths[1] > EQUAL && widths[2] < EQUAL, "the divided pair shares the change: {widths:?}");
|
||||
assert!(close(widths[3], EQUAL), "the column past the pair is untouched: {widths:?}");
|
||||
}
|
||||
|
||||
/// A bar over `widths`, which every pass writes back.
|
||||
fn bar(widths: Vec<f64>) -> (Fixture, Rc<RefCell<Vec<f64>>>) {
|
||||
let widths = Rc::new(RefCell::new(widths));
|
||||
let seen = Rc::clone(&widths);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = seen.borrow().clone();
|
||||
ColumnBar::new("Columns", Bind::bound(&mut current)).show(ui);
|
||||
*seen.borrow_mut() = current;
|
||||
});
|
||||
fixture.settle();
|
||||
(fixture, widths)
|
||||
}
|
||||
|
||||
/// With many narrow columns the first and last dividers still move as far as the clamps allow, the total stays and
|
||||
/// no column reaches zero.
|
||||
#[trial]
|
||||
fn a_divider_between_many_narrow_columns_still_moves_and_keeps_the_total() {
|
||||
for count in [30, MAX_COLUMNS] {
|
||||
let (mut fixture, widths) = bar(vec![EQUAL; count]);
|
||||
let total = EQUAL * count as f64;
|
||||
for (label, by) in [("Column 1 width".to_owned(), FAR), (format!("Column {} width", count - 1), -FAR)] {
|
||||
let divider = fixture.by_label(&label).unwrap_or_else(|| panic!("{count} columns: the divider {label}"));
|
||||
let before = widths.borrow().clone();
|
||||
fixture.drag(÷r, Vec2::new(by, 0.0));
|
||||
let now = widths.borrow();
|
||||
assert_ne!(*now, before, "{count} columns: {label} moved");
|
||||
assert!(close(now.iter().sum::<f64>(), total), "{count} columns: the total stays after {label}: {now:?}");
|
||||
assert!(now.iter().all(|width| *width > 0.0), "{count} columns: every column keeps a width after {label}: {now:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An arrow moves the focused divider one step toward its side, Shift ten steps; the total stays.
|
||||
#[trial]
|
||||
fn an_arrow_moves_the_focused_divider_one_step_and_shift_ten() {
|
||||
let (mut fixture, widths) = bar(vec![EQUAL; COLUMNS]);
|
||||
let divider = fixture.by_label("Column 2 width").expect("the second divider");
|
||||
fixture.click(÷r).settle();
|
||||
let before = widths.borrow()[1];
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE).settle();
|
||||
let step = widths.borrow()[1] - before;
|
||||
assert!(step > 0.0, "Right moves the divider right and widens the column before it: {:?}", widths.borrow());
|
||||
fixture.key(Key::ArrowRight, Modifiers::SHIFT).settle();
|
||||
let jump = widths.borrow()[1] - before - step;
|
||||
assert!(close(jump, 10.0 * step), "Shift moves ten steps: {jump} after a step of {step}");
|
||||
let widths = widths.borrow();
|
||||
assert!(close(widths.iter().sum::<f64>(), EQUAL * COLUMNS as f64), "the total stays: {widths:?}");
|
||||
}
|
||||
|
||||
@@ -49,10 +49,18 @@ pub use commands::TextEditorCommand;
|
||||
pub use edits::{click_count, click_selection, word_boundary};
|
||||
|
||||
use crate::quotes::QuoteStyle;
|
||||
use craft_keymap::{Chord, Key};
|
||||
use craft_keymap::{Chord, Key, Mods};
|
||||
use edits::{Edits, Session, char_slice, fingerprint};
|
||||
|
||||
const ESCAPE: Chord = Chord::plain(Key::Escape);
|
||||
const ENTER: Chord = Chord::plain(Key::Enter);
|
||||
const TAB: Chord = Chord::plain(Key::Tab);
|
||||
const SHIFT_TAB: Chord = Chord::new(Mods::SHIFT, Key::Tab);
|
||||
|
||||
/// The keys that end a one-line field's session: Enter keeps the text, Tab and Shift+Tab keep it and move on.
|
||||
static FIELD_LINE_ENDS: [(Chord, EditorEnd); 3] = [(ENTER, EditorEnd::Commit), (TAB, EditorEnd::Next), (SHIFT_TAB, EditorEnd::Previous)];
|
||||
/// The keys that end a multi-line field's session; Enter is a line break there.
|
||||
static FIELD_LINES_ENDS: [(Chord, EditorEnd); 2] = [(TAB, EditorEnd::Next), (SHIFT_TAB, EditorEnd::Previous)];
|
||||
|
||||
/// The selection: `anchor` stays where it started, `caret` moves. Equal: a caret with nothing selected. Char
|
||||
/// offsets.
|
||||
@@ -282,19 +290,37 @@ pub enum EditorEnd {
|
||||
Previous,
|
||||
}
|
||||
|
||||
/// What the editor is.
|
||||
/// What the editor is: which keys end its session and which are text.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum EditorMode {
|
||||
/// The canvas text editor.
|
||||
/// The canvas text editor: Enter is a line break and Tab a tab character.
|
||||
#[default]
|
||||
Canvas,
|
||||
/// A one-line form field.
|
||||
/// A one-line form field: Enter commits, Tab and Shift+Tab move to the next or previous field, and pasted line
|
||||
/// breaks become spaces.
|
||||
FieldLine,
|
||||
/// A multi-line form field.
|
||||
/// A multi-line form field: Enter is a line break, Tab and Shift+Tab move to the next or previous field.
|
||||
FieldLines,
|
||||
}
|
||||
|
||||
impl EditorMode {
|
||||
/// The chords that end a session in this mode and how each ends it. The editor claims them while focused, so
|
||||
/// they reach it rather than focus navigation or its own text.
|
||||
fn ending_keys(self) -> &'static [(Chord, EditorEnd)] {
|
||||
match self {
|
||||
EditorMode::Canvas => &[],
|
||||
EditorMode::FieldLine => &FIELD_LINE_ENDS,
|
||||
EditorMode::FieldLines => &FIELD_LINES_ENDS,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `text` on one line: each line ending (`\r\n`, `\r` or `\n`) becomes one space.
|
||||
fn one_line(text: &str) -> String {
|
||||
text.replace("\r\n", " ").replace(['\r', '\n'], " ")
|
||||
}
|
||||
|
||||
/// What the editor did this pass.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
@@ -309,11 +335,13 @@ pub struct TextEditorOutput {
|
||||
/// The text changes of the session as one gesture over the selection. The first text change gives `Begin`, later
|
||||
/// changes `Update`; the session's end ([`ended`](Self::ended)) commits or cancels the gesture when one runs.
|
||||
pub edit: EditResponse<TextSelection>,
|
||||
/// The session ended this pass, whether or not its text changed. `Commit` is Cmd+Enter, a primary press on the
|
||||
/// canvas background, or Esc when Esc commits ([`TextEditor::esc_commits`], Photoshop's Use ESC Key to Commit
|
||||
/// Text, on by default): the app ends the session, keeps the text and records one undo step when it changed.
|
||||
/// The session ended this pass, whether or not its text changed. `Commit` is Cmd+Enter, Enter in a
|
||||
/// [`EditorMode::FieldLine`], a primary press on the canvas background, or Esc when Esc commits
|
||||
/// ([`TextEditor::esc_commits`], Photoshop's Use ESC Key to Commit Text, on by default): the app ends the
|
||||
/// session, keeps the text and records one undo step when it changed. `Next` and `Previous` are Tab and
|
||||
/// Shift+Tab in a field mode: the app keeps the text as for `Commit` and moves to the next or previous field.
|
||||
/// `Cancel` is Cmd+., or Esc when it doesn't commit: the app ends the session and undoes it. While a composition
|
||||
/// is open the keys give neither.
|
||||
/// is open the keys give none of them.
|
||||
pub ended: Option<EditorEnd>,
|
||||
/// The Character panel command was pressed: the host shows or hides the panel. Set for the one pass.
|
||||
pub character_panel: bool,
|
||||
@@ -350,12 +378,15 @@ 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; Cmd+. cancels;
|
||||
/// Cmd+T asks the host for its Character panel. The
|
||||
/// Cmd+T asks the host for its Character panel. In a form field ([`mode`](Self::mode)) Tab and Shift+Tab end the
|
||||
/// session toward the next or previous field, and in a one-line field Enter commits. The
|
||||
/// [`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`.
|
||||
/// text is kept as it is. Pasted line endings become `\n`, in a one-line field a space.
|
||||
/// - A [`masked`](Self::masked) editor is a password field: the host draws its text as bullets, and Copy and Cut
|
||||
/// put nothing on the clipboard.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct TextEditor<'a> {
|
||||
#[common]
|
||||
@@ -371,11 +402,10 @@ pub struct TextEditor<'a> {
|
||||
esc_commits: bool,
|
||||
/// What the editor is: the canvas text editor, or a one-line or multi-line form field.
|
||||
#[prop]
|
||||
#[allow(dead_code)] // P3(pdf-forms-w2): FM-PF6
|
||||
mode: EditorMode,
|
||||
/// Whether the text is drawn as bullets, for a password field.
|
||||
/// Whether the text is a secret, for a password field: the host draws it as bullets, the input method and
|
||||
/// assistive technology treat it as a password, and Copy and Cut put nothing on the clipboard.
|
||||
#[prop(flag)]
|
||||
#[allow(dead_code)] // P3(pdf-forms-w2): FM-PF7
|
||||
masked: bool,
|
||||
changed: bool,
|
||||
selection_changed: bool,
|
||||
@@ -515,7 +545,7 @@ impl Component for TextEditor<'_> {
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.editor(EDITOR, rect, EditorPurpose::Text);
|
||||
cx.editor(EDITOR, rect, if self.masked { EditorPurpose::Password } else { EditorPurpose::Text });
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
@@ -529,6 +559,7 @@ impl Component for TextEditor<'_> {
|
||||
let press = *cx.press();
|
||||
let now = cx.now();
|
||||
let pasted = pasted_text(cx, &inputs);
|
||||
let (mode, masked) = (self.mode, self.masked);
|
||||
let mut copied: Option<String> = None;
|
||||
let mut session = std::mem::take(cx.memory::<Session>());
|
||||
let mut edits = Edits {
|
||||
@@ -561,8 +592,11 @@ impl Component for TextEditor<'_> {
|
||||
}
|
||||
EditorInput::ImeCommit => ending = edits.session.preedit.take(),
|
||||
EditorInput::Text(text) => edits.done.changed |= edits.insert_typed(&text),
|
||||
EditorInput::Newline if edits.session.preedit.is_none() => edits.done.changed |= edits.insert_text("\n", EditKind::Typed),
|
||||
EditorInput::Tab => edits.done.changed |= edits.insert_text("\t", EditKind::Typed),
|
||||
// In a field mode Enter (one-line) and Tab are the claimed keys that end the session, never text.
|
||||
EditorInput::Newline if edits.session.preedit.is_none() && mode != EditorMode::FieldLine => {
|
||||
edits.done.changed |= edits.insert_text("\n", EditKind::Typed);
|
||||
}
|
||||
EditorInput::Tab if mode == EditorMode::Canvas => edits.done.changed |= edits.insert_text("\t", EditKind::Typed),
|
||||
EditorInput::Move(step, mods) => edits.motion(step, mods),
|
||||
EditorInput::Delete { forward, by, .. } => edits.done.changed |= edits.delete(forward, by),
|
||||
EditorInput::DeleteSurrounding { before, after, unit, .. } => edits.done.changed |= edits.delete_around(before, after, unit),
|
||||
@@ -572,14 +606,16 @@ impl Component for TextEditor<'_> {
|
||||
edits.selection = TextSelection { anchor: char_at(&lines, anchor), caret: char_at(&lines, focus) };
|
||||
}
|
||||
EditorInput::Edit(EditCommand::SelectAll) => edits.select_all(),
|
||||
EditorInput::Edit(EditCommand::Copy) => copied = edits.selected_text(),
|
||||
EditorInput::Edit(EditCommand::Cut) => {
|
||||
// A masked text never reaches the clipboard, and a Cut that cannot copy keeps the text.
|
||||
EditorInput::Edit(EditCommand::Copy) if !masked => copied = edits.selected_text(),
|
||||
EditorInput::Edit(EditCommand::Cut) if !masked => {
|
||||
copied = edits.selected_text();
|
||||
edits.done.changed |= edits.delete_selection();
|
||||
}
|
||||
EditorInput::Edit(EditCommand::Paste) => {
|
||||
if let Some(text) = &pasted {
|
||||
edits.done.changed |= edits.insert_text(text, EditKind::Pasted);
|
||||
let text = if mode == EditorMode::FieldLine { one_line(text) } else { text.to_string() };
|
||||
edits.done.changed |= edits.insert_text(&text, EditKind::Pasted);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -605,9 +641,9 @@ impl Component for TextEditor<'_> {
|
||||
edits.done.commit = true;
|
||||
}
|
||||
|
||||
// Commands and the claimed Escape arrive with the pass's own input: a second pass of the frame takes none, so
|
||||
// a commit, a cancel or the panel toggle is reported by one pass only. Commit and Cancel wait while a
|
||||
// composition is open: the key belongs to the input method then.
|
||||
// Commands and the claimed keys arrive with the pass's own input: a second pass of the frame takes none, so
|
||||
// a commit, a cancel, a move to another field or the panel toggle is reported by one pass only. No key ends
|
||||
// the session while a composition is open: the key belongs to the input method then.
|
||||
if cx.take_claimed(ESCAPE) && edits.session.preedit.is_none() {
|
||||
if edits.esc_commits {
|
||||
edits.done.commit = true;
|
||||
@@ -615,6 +651,17 @@ impl Component for TextEditor<'_> {
|
||||
edits.done.cancel = true;
|
||||
}
|
||||
}
|
||||
for &(chord, end) in mode.ending_keys() {
|
||||
cx.claim(chord);
|
||||
if cx.take_claimed(chord) && edits.session.preedit.is_none() {
|
||||
match end {
|
||||
EditorEnd::Commit => edits.done.commit = true,
|
||||
EditorEnd::Next => edits.done.next = true,
|
||||
EditorEnd::Previous => edits.done.previous = true,
|
||||
EditorEnd::Cancel => edits.done.cancel = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut character_panel = false;
|
||||
for command in fired {
|
||||
match command.along_flow(edits.host.vertical()) {
|
||||
@@ -655,19 +702,19 @@ impl Component for TextEditor<'_> {
|
||||
cx.set(selection);
|
||||
}
|
||||
}
|
||||
if done.commit {
|
||||
if done.commit || done.next || done.previous {
|
||||
cx.commit();
|
||||
} else if done.cancel {
|
||||
cx.cancel(CancelReason::Escape);
|
||||
}
|
||||
self.ended = if done.commit {
|
||||
Some(EditorEnd::Commit)
|
||||
} else if done.next {
|
||||
Some(EditorEnd::Next)
|
||||
} else if done.previous {
|
||||
Some(EditorEnd::Previous)
|
||||
} else if done.cancel {
|
||||
Some(EditorEnd::Cancel)
|
||||
} else if done.next {
|
||||
Some(EditorEnd::Next) // P3(pdf-forms-w2): FM-PF8
|
||||
} else if done.previous {
|
||||
Some(EditorEnd::Previous) // P3(pdf-forms-w2): FM-PF8
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
@@ -14,7 +14,7 @@ use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, stage_fitting, story};
|
||||
use egui::{Pos2, Rect, Response, Ui, Vec2};
|
||||
|
||||
use super::{CaretLine, EditKind, HostLine, HostRun, TextEditor, TextEditorHost, TextSelection};
|
||||
use super::{CaretLine, EditKind, EditorMode, HostLine, HostRun, TextEditor, TextEditorHost, TextSelection};
|
||||
|
||||
/// The width of a char's cell, in document units.
|
||||
const CELL: f64 = 10.0;
|
||||
@@ -192,6 +192,8 @@ struct MonoText {
|
||||
#[common]
|
||||
common: Common,
|
||||
rows: Vec<String>,
|
||||
/// Each char is painted as a bullet, as a password field's host lays it out.
|
||||
masked: bool,
|
||||
}
|
||||
|
||||
impl Component for MonoText {
|
||||
@@ -223,6 +225,7 @@ impl Component for MonoText {
|
||||
let size = TEXT_SIZE * space.view.zoom as f32;
|
||||
for (line, text) in self.rows.iter().enumerate() {
|
||||
for (column, c) in text.chars().enumerate() {
|
||||
let c = if self.masked { '•' } else { c };
|
||||
let centre = space.view.to_screen(Point::new((column as f64 + 0.5) * CELL, (line as f64 + 0.5) * LINE));
|
||||
let run = [DocRun::new(c.to_string(), FontRef::monospace(), size, ink)];
|
||||
let layout = cx.layout_doc(&DocText::new(&run));
|
||||
@@ -239,10 +242,10 @@ impl Component for MonoText {
|
||||
/// The text the stories edit.
|
||||
const SAMPLE: &str = "The quick brown fox\njumps over the lazy dog";
|
||||
|
||||
/// The editor over `text` with the selection bound to `bind`, on a canvas as tall as the text wrapped at the stage's
|
||||
/// width, whose view puts document (0, 0) at its top left. The host's edits (typed, pasted and composed text) are
|
||||
/// written back to `text`, which the story keeps between passes.
|
||||
fn over_canvas(ui: &mut Ui, text: &mut String, mut bind: Bind<'_, TextSelection>) -> StoryOutput {
|
||||
/// The editor in `mode` (`masked` for a password field) over `text` with the selection bound to `bind`, on a canvas
|
||||
/// as tall as the text wrapped at the stage's width, whose view puts document (0, 0) at its top left. The host's
|
||||
/// edits (typed, pasted and composed text) are written back to `text`, which the story keeps between passes.
|
||||
fn over_canvas(ui: &mut Ui, text: &mut String, mut bind: Bind<'_, TextSelection>, mode: EditorMode, masked: bool) -> StoryOutput {
|
||||
let mut host = MonoHost { text: std::mem::take(text), columns: 1 };
|
||||
let room = stage_fitting(ui, |width| {
|
||||
// One cell stays free at the end of a row for the caret after its last char.
|
||||
@@ -252,18 +255,24 @@ fn over_canvas(ui: &mut Ui, text: &mut String, mut bind: Bind<'_, TextSelection>
|
||||
let view = CanvasView::new(room, Point::new(f64::from(room.width()) / 2.0, f64::from(room.height()) / 2.0), 1.0);
|
||||
let shown = Canvas::new("Document").view(view).show_at(ui, room, |ui, _| {
|
||||
let bounds = Rect::from_min_size(view.to_screen(Point::ZERO), host.extent_with_caret_cell());
|
||||
MonoText { common: Common::new(), rows: host.row_texts() }.show_at(ui, bounds);
|
||||
TextEditor::new("Text", &mut host, bind.reborrowed()).show_at(ui, bounds)
|
||||
MonoText { common: Common::new(), rows: host.row_texts(), masked }.show_at(ui, bounds);
|
||||
let editor = TextEditor::new("Text", &mut host, bind.reborrowed()).mode(mode);
|
||||
if masked { editor.masked() } else { editor }.show_at(ui, bounds)
|
||||
});
|
||||
*text = host.text;
|
||||
shown.inner.map(StoryOutput::from).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The editor over `text` with `selection` on a canvas.
|
||||
/// The canvas editor over `text` with `selection` on a canvas.
|
||||
fn on_canvas(ui: &mut Ui, data: &mut StoryData, text: &str, selection: TextSelection) -> StoryOutput {
|
||||
as_field(ui, data, text, selection, EditorMode::Canvas, false)
|
||||
}
|
||||
|
||||
/// The editor in `mode` (`masked` for a password field) over `text` with `selection` on a canvas.
|
||||
fn as_field(ui: &mut Ui, data: &mut StoryData, text: &str, selection: TextSelection, mode: EditorMode, masked: bool) -> StoryOutput {
|
||||
let mut host = data.value("text", text.to_owned()).clone();
|
||||
let selection = data.value("selection", selection);
|
||||
let out = over_canvas(ui, &mut host, Bind::bound(&mut *selection));
|
||||
let out = over_canvas(ui, &mut host, Bind::bound(&mut *selection), mode, masked);
|
||||
*data.value("text", String::new()) = host;
|
||||
out
|
||||
}
|
||||
@@ -298,7 +307,7 @@ fn composing(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
fn selections_that_differ(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut host = data.value("text", SAMPLE.to_owned()).clone();
|
||||
let selection = data.value("selection", Mixed::<TextSelection>::Mixed);
|
||||
over_canvas(ui, &mut host, Bind::bound_mixed(&mut *selection))
|
||||
over_canvas(ui, &mut host, Bind::bound_mixed(&mut *selection), EditorMode::Canvas, false)
|
||||
}
|
||||
|
||||
#[story(TextEditor<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
@@ -309,5 +318,23 @@ fn selection_past_the_text(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let inside = move |selection: &TextSelection| {
|
||||
if selection.caret > end { Validity::Refuse(Message::new("The selection is past the text")) } else { Validity::Ok }
|
||||
};
|
||||
over_canvas(ui, &mut host, Bind::bound(&mut *selection).check(inside))
|
||||
over_canvas(ui, &mut host, Bind::bound(&mut *selection).check(inside), EditorMode::Canvas, false)
|
||||
}
|
||||
|
||||
/// A one-line form field with the caret after its text.
|
||||
#[story(TextEditor<'static>, covers = [], drive = Drive::Never)]
|
||||
fn editor_field_line(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
as_field(ui, data, "Jane Doe", TextSelection::caret_at(8), EditorMode::FieldLine, false)
|
||||
}
|
||||
|
||||
/// A multi-line form field with "quick" selected.
|
||||
#[story(TextEditor<'static>, covers = [], drive = Drive::Never)]
|
||||
fn editor_field_lines(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
as_field(ui, data, SAMPLE, TextSelection::new(4, 9), EditorMode::FieldLines, false)
|
||||
}
|
||||
|
||||
/// A password field: the host lays its text out as bullets.
|
||||
#[story(TextEditor<'static>, covers = [], drive = Drive::Never)]
|
||||
fn editor_masked(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
as_field(ui, data, "hunter22", TextSelection::caret_at(8), EditorMode::FieldLine, true)
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::rc::Rc;
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_text::quotes::QuoteStyle;
|
||||
use craft_text::ui::editor::{CaretLine, EditKind, EditorEnd, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection};
|
||||
use craft_text::ui::editor::{CaretLine, EditKind, EditorEnd, EditorMode, HostLine, StyleKey, TextEditor, TextEditorHost, TextSelection};
|
||||
use craft_ui::canvas::Canvas;
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::{Fixture, pointer, trial};
|
||||
@@ -99,11 +99,12 @@ struct Session {
|
||||
}
|
||||
|
||||
fn session(text: &str, quotes: Option<QuoteStyle>) -> Session {
|
||||
session_on(Host { text: text.to_owned(), ..Host::default() }, quotes, false)
|
||||
session_on(Host { text: text.to_owned(), ..Host::default() }, quotes, false, EditorMode::Canvas, false)
|
||||
}
|
||||
|
||||
/// A session on `host`; with `beside`, a second editor on its own text is shown after the session's.
|
||||
fn session_on(host: Host, quotes: Option<QuoteStyle>, beside: bool) -> Session {
|
||||
/// A session on `host` of an editor in `mode`, `masked` or not; with `beside`, a second editor on its own text is
|
||||
/// shown after the session's.
|
||||
fn session_on(host: Host, quotes: Option<QuoteStyle>, beside: bool, mode: EditorMode, masked: bool) -> 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())));
|
||||
@@ -126,7 +127,8 @@ fn session_on(host: Host, quotes: Option<QuoteStyle>, beside: bool) -> Session {
|
||||
Canvas::new("Document").view(view).show(ui, |ui, body| {
|
||||
let bounds = Rect::from_min_size(body.rect.min, vec2(200.0, 20.0));
|
||||
let esc_commits = !host.esc_cancels;
|
||||
let editor = TextEditor::new("Text", &mut *host, Bind::bound(&mut *selection)).esc_commits(esc_commits);
|
||||
let editor = TextEditor::new("Text", &mut *host, Bind::bound(&mut *selection)).esc_commits(esc_commits).mode(mode);
|
||||
let editor = if masked { editor.masked() } else { editor };
|
||||
let output = if let Some(style) = quotes { editor.smart_quotes(style) } else { editor }.show_at(ui, bounds);
|
||||
let commits = output.edit.events.iter().filter(|event| matches!(event, craft_behavior::EditEvent::Commit { .. })).count() as u32;
|
||||
shown_commits.set(shown_commits.get() + commits);
|
||||
@@ -223,7 +225,7 @@ fn preedit(text: &str) -> Event {
|
||||
/// shown after the composing one leaves the composing editor's report standing.
|
||||
#[trial]
|
||||
fn a_click_during_composition_keeps_the_marked_text_and_interrupts_the_composition_once() {
|
||||
let mut editor = session_on(Host { text: "abc".to_owned(), ..Host::default() }, None, true);
|
||||
let mut editor = session_on(Host { text: "abc".to_owned(), ..Host::default() }, None, true, EditorMode::Canvas, false);
|
||||
editor.focus();
|
||||
editor.fixture.frame(vec![preedit("kzk")]).settle();
|
||||
assert_eq!(editor.text(), "abckzk", "the marked text is written at the caret");
|
||||
@@ -319,7 +321,7 @@ fn escape_ends_an_untouched_session_and_a_typed_one() {
|
||||
assert_eq!(*editor.ends.borrow(), [EditorEnd::Commit], "Esc commits an untouched session");
|
||||
assert_eq!((editor.commits.get(), editor.cancels.get()), (0, 0), "no text changed, so no gesture ends");
|
||||
|
||||
let mut editor = session_on(Host { text: "abc".to_owned(), esc_cancels: true, ..Host::default() }, None, false);
|
||||
let mut editor = session_on(Host { text: "abc".to_owned(), esc_cancels: true, ..Host::default() }, None, false, EditorMode::Canvas, false);
|
||||
editor.focus();
|
||||
editor.fixture.key(Key::Escape, Modifiers::NONE).settle();
|
||||
assert_eq!(*editor.ends.borrow(), [EditorEnd::Cancel], "Esc cancels an untouched session where it does not commit");
|
||||
@@ -332,13 +334,14 @@ fn escape_ends_an_untouched_session_and_a_typed_one() {
|
||||
/// 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, false);
|
||||
let mut vertical =
|
||||
session_on(Host { text: "abcdefgh".to_owned(), vertical: true, formats: true, ..Host::default() }, None, false, EditorMode::Canvas, false);
|
||||
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, false);
|
||||
let mut plain = session_on(Host { text: "abcdefgh".to_owned(), ..Host::default() }, None, false, EditorMode::Canvas, false);
|
||||
plain.focus();
|
||||
let before = plain.selection.borrow().caret;
|
||||
assert!(before >= LINE, "the click left the caret past the first line");
|
||||
@@ -346,3 +349,62 @@ fn formatting_keys_follow_the_flow_and_fall_back_to_caret_moves() {
|
||||
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");
|
||||
}
|
||||
|
||||
/// A focused editor in `mode` over "abc", `masked` or not, with the caret after the text.
|
||||
fn field(mode: EditorMode, masked: bool) -> Session {
|
||||
let mut editor = session_on(Host { text: "abc".to_owned(), ..Host::default() }, None, false, mode, masked);
|
||||
editor.focus();
|
||||
editor
|
||||
}
|
||||
|
||||
/// A one-line field ends its session on Enter (commit), Tab (next) and Shift+Tab (previous) and pastes line breaks as
|
||||
/// spaces; a multi-line field takes Enter as a line break and ends on Tab; while a composition is open no key ends a
|
||||
/// field's session; the canvas editor still types Tab as a tab character.
|
||||
#[trial]
|
||||
fn field_modes_end_on_enter_tab_and_shift_tab_but_not_while_composing() {
|
||||
let mut line = field(EditorMode::FieldLine, false);
|
||||
line.fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
line.fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
line.fixture.key(Key::Tab, Modifiers::SHIFT).settle();
|
||||
assert_eq!(*line.ends.borrow(), [EditorEnd::Commit, EditorEnd::Next, EditorEnd::Previous], "Enter, Tab and Shift+Tab end the session");
|
||||
assert_eq!(line.text(), "abc", "the keys that end the session type nothing");
|
||||
line.fixture.frame(vec![Event::Paste("d\r\ne\nf\rg".to_owned())]).settle();
|
||||
assert_eq!(line.text(), "abcd e f g", "each pasted line ending becomes one space");
|
||||
line.fixture.frame(vec![preedit("k")]).settle();
|
||||
line.fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
line.fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
line.fixture.key(Key::Tab, Modifiers::SHIFT).settle();
|
||||
assert_eq!(line.ends.borrow().len(), 3, "while composing the keys belong to the input method: {:?}", line.ends.borrow());
|
||||
|
||||
let mut lines = field(EditorMode::FieldLines, false);
|
||||
lines.fixture.key(Key::Enter, Modifiers::NONE).settle();
|
||||
assert_eq!(lines.text(), "abc\n", "Enter is a line break in a multi-line field");
|
||||
assert!(lines.ends.borrow().is_empty(), "Enter does not end a multi-line field's session");
|
||||
lines.fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
assert_eq!(*lines.ends.borrow(), [EditorEnd::Next], "Tab moves on from a multi-line field");
|
||||
assert_eq!(lines.text(), "abc\n", "Tab types nothing in a field");
|
||||
|
||||
let mut canvas = field(EditorMode::Canvas, false);
|
||||
canvas.fixture.key(Key::Tab, Modifiers::NONE).settle();
|
||||
assert_eq!(canvas.text(), "abc\t", "the canvas editor types Tab");
|
||||
assert!(canvas.ends.borrow().is_empty(), "Tab does not end a canvas session");
|
||||
}
|
||||
|
||||
/// A masked editor puts nothing on the clipboard for Copy or Cut, and a Cut keeps the text; the same editor
|
||||
/// unmasked copies the selection.
|
||||
#[trial]
|
||||
fn a_masked_editor_copies_and_cuts_nothing() {
|
||||
let mut plain = field(EditorMode::FieldLine, false);
|
||||
plain.fixture.key(Key::A, Modifiers::COMMAND).settle();
|
||||
plain.fixture.frame(vec![Event::Copy]);
|
||||
assert_eq!(plain.fixture.copied().to_vec(), vec!["abc".to_owned()], "an unmasked editor copies its selection");
|
||||
|
||||
let mut masked = field(EditorMode::FieldLine, true);
|
||||
masked.fixture.key(Key::A, Modifiers::COMMAND).settle();
|
||||
masked.fixture.frame(vec![Event::Copy]);
|
||||
assert!(masked.fixture.copied().is_empty(), "Copy puts nothing on the clipboard: {:?}", masked.fixture.copied());
|
||||
masked.fixture.frame(vec![Event::Cut]);
|
||||
assert!(masked.fixture.copied().is_empty(), "Cut puts nothing on the clipboard: {:?}", masked.fixture.copied());
|
||||
masked.fixture.settle();
|
||||
assert_eq!(masked.text(), "abc", "Cut keeps the text");
|
||||
}
|
||||
|
||||
@@ -104,6 +104,26 @@ fn show(
|
||||
}
|
||||
}
|
||||
|
||||
/// The window losing focus while a value is typed keeps the draft and commits nothing; back in the window, typing
|
||||
/// goes on from the draft.
|
||||
#[trial]
|
||||
fn a_window_blur_mid_typing_keeps_the_typed_draft() {
|
||||
let mut rig = Rig::new(5.0, None);
|
||||
rig.focus();
|
||||
rig.key(Key::A, Modifiers::COMMAND);
|
||||
rig.frame(vec![Event::Text("1".into())]);
|
||||
rig.idle(1);
|
||||
rig.frame(vec![Event::WindowFocused(false)]);
|
||||
rig.idle(2);
|
||||
assert_eq!(rig.value(), Some(5.0), "the blur commits nothing");
|
||||
assert!(rig.frames.texts().iter().any(|text| text.text == "1"), "the field still shows the typed draft");
|
||||
rig.frame(vec![Event::WindowFocused(true)]);
|
||||
rig.idle(1);
|
||||
rig.frame(vec![Event::Text("2".into())]);
|
||||
rig.key(Key::Enter, Modifiers::NONE);
|
||||
assert_eq!(rig.value(), Some(12.0), "typing went on from the draft");
|
||||
}
|
||||
|
||||
/// An arrow goes to the next multiple of the step in its direction, Shift moves ten steps, and the range holds.
|
||||
#[trial]
|
||||
fn arrows_step_to_the_next_multiple_and_stay_in_range() {
|
||||
|
||||
Reference in New Issue
Block a user