Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 1 addition & 8 deletions crates/text/src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -507,14 +507,7 @@ impl Buffer {
/// Over the spaces, then over one run of word characters or of punctuation; a line end
/// alone is a step.
fn word(&self, at: usize, direction: Direction) -> usize {
// 0 a space, 1 punctuation, 2 a word character.
let class = |c: char| {
if c.is_alphanumeric() || c == '_' {
2
} else {
u8::from(!c.is_whitespace())
}
};
let class = crate::words::class;
let char_at = |i: usize| self.rope.char(i);
let len = self.len();
let mut i = at;
Expand Down
2 changes: 1 addition & 1 deletion crates/text/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ pub use diff::changed_lines;
pub use indent::{TextEdit, indent, outdent, rewrite};
pub use search::{COUNT_CAP, Count, Query, find};
pub use shield::{Shielded, shield_fields, unshield_fields};
pub use words::count_words;
pub use words::{count_words, word_around};
69 changes: 68 additions & 1 deletion crates/text/src/words.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! The words of a Note as it reads, not as its Markdown is spelled (the reference's
//! `word-count.ts`).
//! `word-count.ts`), and what a double click or a step by word takes.

use std::ops::Range;
use std::sync::LazyLock;

use regex::Regex;
Expand All @@ -17,6 +18,41 @@ pub fn count_words(markdown: &str) -> usize {
WORD.find_iter(&read).count()
}

/// What a word is made of, for every editor: 0 a space, 1 punctuation, 2 a word character
/// (a letter, a digit, `_`). A run of one class is one word.
pub(crate) fn class(c: char) -> u8 {
if c.is_alphanumeric() || c == '_' {
2
} else {
u8::from(!c.is_whitespace())
}
}

/// What a double click on the `char` at `at` takes: the run of word characters, punctuation or
/// spaces holding it. Past the end of its line, the line's last run; a line end stops it.
pub fn word_around(text: &str, at: usize) -> Range<usize> {
let chars: Vec<char> = text.chars().collect();
let kind = |i: usize| chars.get(i).filter(|c| **c != '\n').map(|c| class(*c));
let at = at.min(chars.len());
let probe = if kind(at).is_some() {
at
} else if at > 0 && kind(at - 1).is_some() {
at - 1
} else {
return at..at;
};
let run = kind(probe);
let mut start = probe;
while start > 0 && kind(start - 1) == run {
start -= 1;
}
let mut end = probe + 1;
while kind(end) == run {
end += 1;
}
start..end
}

#[cfg(test)]
mod tests {
use super::*;
Expand All @@ -43,6 +79,37 @@ mod tests {
assert_eq!(count_words("l’équipe a re-déployé l'API"), 4);
}

fn word(text: &str, offset: usize) -> &str {
let range = word_around(text, offset);
let start = text
.char_indices()
.nth(range.start)
.map_or(text.len(), |(at, _)| at);
let end = text
.char_indices()
.nth(range.end)
.map_or(text.len(), |(at, _)| at);
&text[start..end]
}

#[test]
fn a_double_click_takes_the_run_it_touches() {
assert_eq!(word("déjà-vu", 3), "déjà");
assert_eq!(word("déjà-vu", 4), "-");
assert_eq!(word("déjà-vu", 5), "vu");
assert_eq!(word("foo_bar baz", 3), "foo_bar");
assert_eq!(word("a.b", 0), "a");
assert_eq!(word("a.b", 1), ".");
assert_eq!(word("a.b", 2), "b");
assert_eq!(word("hello world", 5), " ");
assert_eq!(word("a b", 2), " ");
assert_eq!(word("ok 🙂🙂 go", 3), "🙂🙂");
assert_eq!(word("one\ntwo", 3), "one", "past the end of its line");
assert_eq!(word("one\ntwo", 4), "two");
assert_eq!(word("", 0), "");
assert_eq!(word("end", 9), "end");
}

#[test]
fn says_zero_for_an_empty_note() {
assert_eq!(count_words(""), 0);
Expand Down
93 changes: 83 additions & 10 deletions crates/ui/src/notes/overlays/editor/rich.rs
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,53 @@ impl RichEditor {
}
}

/// The word holding the `char` at `at`, as the code editor reads a word; `extend`, the
/// selection stretched to it.
fn select_word(&mut self, at: Position, extend: bool) {
let text = match tree::leaf(&self.document, &at.path) {
Some(tree::Leaf::Inlines(content)) => inlines::plain(content),
Some(tree::Leaf::Code(text)) => text.clone(),
None => return,
};
let word = text::word_around(&text, at.offset);
let start = Position {
path: at.path.clone(),
offset: word.start,
};
let end = Position {
path: at.path,
offset: word.end,
};
if extend {
let head = if start >= self.selection.anchor {
end
} else {
start
};
self.move_head(head, true);
} else {
self.move_head(start, false);
self.move_head(end, true);
}
self.goal_x = None;
}

/// The whole paragraph, heading, item's line, cell or code block at `path`.
fn select_leaf(&mut self, path: Vec<usize>) {
let Some(len) = tree::leaf(&self.document, &path).map(|leaf| leaf.len()) else {
return;
};
self.move_head(
Position {
path: path.clone(),
offset: 0,
},
false,
);
self.move_head(Position { path, offset: len }, true);
self.goal_x = None;
}

fn move_head(&mut self, head: Position, extend: bool) {
self.picked = None;
if extend {
Expand All @@ -263,20 +310,35 @@ impl RichEditor {
Some(local.translate(laid.origin.to_vec2()))
}

/// The place under a point: the leaf whose lines it is on, or the nearest one.
fn position_at(&self, point: Pos2) -> Option<Position> {
let laid = self
.laid
/// The leaf whose lines a point is on, or the nearest one.
fn laid_at(&self, point: Pos2) -> Option<&Laid> {
self.laid
.iter()
.min_by(|a, b| distance(a, point).total_cmp(&distance(b, point)))?;
let local = point - laid.origin;
let offset = laid.galley.cursor_from_pos(local).index.0;
.min_by(|a, b| distance(a, point).total_cmp(&distance(b, point)))
}

/// The place under a point: the boundary between two `char`s nearest it.
fn position_at(&self, point: Pos2) -> Option<Position> {
let laid = self.laid_at(point)?;
let offset = laid.galley.cursor_from_pos(point - laid.origin).index.0;
Some(Position {
path: laid.path.clone(),
offset,
})
}

/// The `char` under a point: before the nearest boundary when the point is left of it.
fn char_at(&self, point: Pos2) -> Option<Position> {
let laid = self.laid_at(point)?;
let local = point - laid.origin;
let cursor = laid.galley.cursor_from_pos(local);
let before = local.x < laid.galley.pos_from_cursor(cursor).center().x;
Some(Position {
path: laid.path.clone(),
offset: cursor.index.0.saturating_sub(usize::from(before)),
})
}

/// ↓ with nothing under a code block: a paragraph is opened there.
fn leave_code(&mut self) {
let path = &self.selection.head.path;
Expand Down Expand Up @@ -509,14 +571,25 @@ fn describe(ui: &Ui, surface: &egui::Response, view: &RichEditor, language: Lang
});
}

/// A press places the caret, a drag extends it, Shift extends from where it is.
/// The keys stay on the surface.
/// A press places the caret, a drag extends it, Shift extends from where it is; a double click
/// takes the word, a triple the paragraph. The keys stay on the surface.
fn pointer(ui: &Ui, view: &mut RichEditor, surface: &egui::Response) {
let Some(at) = surface.interact_pointer_pos() else {
return;
};
let shift = ui.input(|input| input.modifiers.shift);
if (surface.drag_started() || surface.clicked())
// egui reports the click of a double click too, and both of a triple: the longest first.
if surface.triple_clicked()
&& let Some(position) = view.position_at(at)
{
view.select_leaf(position.path);
surface.request_focus();
} else if surface.double_clicked()
&& let Some(position) = view.char_at(at)
{
view.select_word(position, shift);
surface.request_focus();
} else if (surface.drag_started() || surface.clicked())
&& let Some(position) = view.position_at(at)
{
view.move_head(position, shift);
Expand Down
69 changes: 69 additions & 0 deletions crates/ui/src/notes/overlays/editor/rich/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -672,3 +672,72 @@ fn the_down_arrow_on_the_last_line_of_a_final_code_block_opens_a_paragraph() {
"```rust\nlet x = 1;\nlet y = 2;\n```\n\nAprès"
);
}

/// Where the painted `words` show their char at `offset`, in the window.
fn point_in(harness: &Harness<'_>, words: &str, offset: usize) -> egui::Pos2 {
let shapes = &harness.output().shapes;
let found = shapes.iter().find_map(|clipped| match &clipped.shape {
egui::Shape::Text(text) if text.galley.text() == words => {
let at = text
.galley
.pos_from_cursor(egui::text::CCursor::new(offset));
Some(text.pos + at.center().to_vec2())
}
_ => None,
});
found.unwrap_or_else(|| panic!("{words:?} is painted"))
}

/// `count` clicks at `at`. The bench gives each release a frame of its own, a quarter of a
/// second: egui's delay between two clicks is stretched to count them as one gesture.
fn clicks(harness: &mut Harness<'_>, at: egui::Pos2, count: usize, modifiers: Modifiers) {
harness
.ctx
.options_mut(|options| options.input_options.max_double_click_delay = 0.7);
// A second of frames first: no click before this gesture counts in it.
for _ in 0..4 {
harness.step();
}
harness.event(egui::Event::PointerMoved(at));
harness.event(egui::Event::ModifiersChanged(modifiers));
harness.step();
for _ in 0..count {
for pressed in [true, false] {
harness.event(egui::Event::PointerButton {
pos: at,
button: egui::PointerButton::Primary,
pressed,
modifiers,
});
}
}
settle(harness);
harness.event(egui::Event::ModifiersChanged(Modifiers::NONE));
harness.step();
}

#[test]
fn a_double_click_takes_the_word_and_a_triple_the_paragraph() {
let (mut harness, id) = note("hello world\n\nsecond line");
let world = point_in(&harness, "hello world", 8);
clicks(&mut harness, world, 2, Modifiers::NONE);
type_in(&mut harness, "there");
assert_eq!(surface_text(&harness), "hello there\nsecond line");

let second = point_in(&harness, "second line", 2);
clicks(&mut harness, second, 3, Modifiers::NONE);
type_in(&mut harness, "third");
click_id(&mut harness, "editor-close");
assert_eq!(stored(&harness, &id), "hello there\n\nthird");
}

#[test]
fn shift_and_a_double_click_stretch_the_selection_to_the_word() {
let (mut harness, _) = note("alpha beta gamma");
let alpha = point_in(&harness, "alpha beta gamma", 0);
clicks(&mut harness, alpha, 1, Modifiers::NONE);
let beta = point_in(&harness, "alpha beta gamma", 8);
clicks(&mut harness, beta, 2, Modifiers::SHIFT);
type_in(&mut harness, "Z");
assert_eq!(surface_text(&harness), "Z gamma");
}
3 changes: 2 additions & 1 deletion docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,8 @@ and exporting write a Note as the Markdown it is, where a snippet is fenced.
keymap did: Enter in an empty item leaves the list, Backspace at an item's start lifts it, Tab
nests it under the one above. The view draws through `widgets::rich` (the reader's own
layout), which says where each leaf was laid out: the caret, a click and ↑ ↓ are read from those
galleys. A Note opened and left is written back untouched — the Markdown is rewritten only once
galleys. A double click takes the word under the pointer — `text::word_around`, the code
editor's classes of a word — and a triple click the leaf. A Note opened and left is written back untouched — the Markdown is rewritten only once
something changed. After a toolbar button the text takes the keys back, as the reference's
`mousedown` kept them. A task's box is a control of its own (`rich-task`).
- **A paste reads the clipboard itself**: egui hands the field the text alone, so the editor asks
Expand Down
21 changes: 21 additions & 0 deletions e2e/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,27 @@ impl App {
self.apply(vec![press(false)]);
}

/// Two clicks at `at`, in points from the control's corner, sent together: one double click
/// however slowly the window paints.
pub fn double_click_in(&mut self, author_id: &str, at: (f32, f32)) {
self.wait_for(author_id);
let bounds = self
.tree()
.find(author_id)
.and_then(Node::bounds)
.unwrap_or_else(|| panic!("{author_id} has no place on screen"));
#[expect(clippy::cast_possible_truncation, reason = "points on a screen")]
let pos = Pos2::new(bounds.x0 as f32, bounds.y0 as f32) + at.into();
let press = |pressed| Event::PointerButton {
pos,
button: PointerButton::Primary,
pressed,
modifiers: Modifiers::NONE,
};
self.apply(vec![Event::PointerMoved(pos)]);
self.apply(vec![press(true), press(false), press(true), press(false)]);
}

/// A press at `from` and a release at `to`, in points from the control's corner.
pub fn drag_in(&mut self, author_id: &str, from: (f32, f32), to: (f32, f32)) {
self.wait_for(author_id);
Expand Down
29 changes: 27 additions & 2 deletions e2e/tests/03_editing_a_note.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
//! the code holds, full screen and the folded header keeping the draft, Tab staying in the code
//! and the find bar finding in it. Then a drawing: drawn on its stage, shown on its card from the
//! picture kept beside it, written as a PNG, and Escape stepping back through it. Then Notes:
//! the sample opens formatted and a box ticked there is kept, and one typed from the toolbar
//! keeps « 2 * 3 * 4 » as typed. The editor sits beside the cards: J steps to the next one, and
//! the sample opens formatted and a box ticked there is kept, one typed from the toolbar keeps
//! « 2 * 3 * 4 » as typed, and a double click takes a word to type over. The editor sits beside the cards: J steps to the next one, and
//! Escape leaves full screen before it closes.

use e2e::{App, Tree, step};
Expand Down Expand Up @@ -298,6 +298,31 @@ fn notes(app: &mut App) {
close(app);
},
);

step("a double click in a Note takes the word under it", || {
// A click less than 0.3 s before a double click makes it a triple, for egui: the last
// one is the field's, two searches each wait out its pause, the card opens by the keys.
app.click("search-input");
app.press(Key::A, Modifiers::COMMAND);
app.type_text("nothing matches this");
app.eventually("nothing found", |tree| tree.has("canvas-no-results"));
app.press(Key::A, Modifiers::COMMAND);
app.type_text("fort");
app.eventually("the Note alone", |tree| tree.count("note-card") == 1);
app.press(Key::ArrowDown, Modifiers::NONE);
app.eventually("the card has the focus", |tree| {
tree.focused().starts_with("note-card-open")
});
app.press(Key::Enter, Modifiers::NONE);
app.wait_for("editor-rich");
// The first word: the page's margin is 28 points, 20 above the first line.
app.double_click_in("editor-rich", (31.0, 31.0));
app.type_text("deux");
app.eventually("the word typed over", |tree| {
rich(tree) == "deux * 3 * 4\nfort"
});
close(app);
});
}

#[test]
Expand Down
Loading