Files
craft-libs/crates/text/tests/it/notes.rs
T
Dylan M. TaylorandClaude Opus 5.5 f7a7c736cc red-fw-1: framework batch trial fixes
Written by a Codex red fixer; committed by the lead (see runs/codex/red-fw-1.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 06:01:14 +00:00

322 lines
15 KiB
Rust

//! The notes text model: typing keeps the formatting around it.
use craft_text::ui::notes::{
NotesContext, NotesEditor, NotesEditorForm, NotesFlag, NotesFlagPolicy, NotesLabels, NotesParagraph, NotesRun, NotesText,
};
use craft_theme::variant::Tone;
use craft_ui::contract::{Props as _, Show as _};
use craft_ui::primitives::FlagMark;
use craft_ui::runtime::env::{Env, with_env};
use craft_ui::style::StyleCx;
use craft_ui::testing::{Fixture, pointer, trial};
use egui::{Color32, Key, Modifiers, Pos2, Rect, Shape, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
fn run(text: &str, bold: bool) -> NotesRun {
NotesRun::new(text).bold(bold)
}
fn paragraph(runs: Vec<NotesRun>) -> NotesParagraph {
NotesParagraph::new(runs)
}
#[trial]
fn typed_replaces_the_span_between_the_common_prefix_and_suffix() {
let notes = NotesText::new(vec![paragraph(vec![run("bold", true), run(" plain", false)])]);
let replaced = notes.typed("bXYZ plain").expect("a prefix and a suffix are shared");
assert_eq!(replaced.paragraphs[0].runs, vec![run("bXYZ", true), run(" plain", false)]);
let split = notes.typed("bold\r\n plain").expect("shares both ends");
assert_eq!(split.plain(), "bold\n plain");
assert_eq!(split.paragraphs.len(), 2);
}
/// A bullet wider than its hanging indent (none here) pushes the first line's text past it, so the text starts after
/// the marker instead of under it.
#[trial]
fn the_first_line_starts_after_a_marker_wider_than_its_hanging_indent() {
use craft_text::lists::ListMarker;
let bulleted = paragraph(vec![run("Open", false)]).list(0, Some(ListMarker::Bullet("•".into())));
let mut notes = NotesText::new(vec![bulleted]);
let mut fx = Fixture::new(move |ui| {
NotesEditor::new("Notes", &mut notes).show(ui);
});
fx.settle();
let editor = fx.by_label("Notes").expect("the editor is named");
fx.click(&editor).key(Key::Home, Modifiers::NONE).settle();
let caret = fx.ime().expect("the focused editor places the caret").caret;
let marker = fx.texts().iter().find(|painted| painted.text.starts_with('•')).expect("the marker is painted").rect;
assert!(caret.center().x >= marker.right() - 0.5, "the caret before the first char ({caret:?}) sits after the marker ({marker:?})");
}
struct Options {
flags: Vec<NotesFlag>,
policy: NotesFlagPolicy,
form: NotesEditorForm,
zoom: f32,
read_only: bool,
}
struct NotesBed {
fixture: Fixture,
notes: Rc<RefCell<NotesText>>,
options: Rc<RefCell<Options>>,
contexts: Rc<RefCell<Vec<NotesContext>>>,
discard: Rc<Cell<bool>>,
inks: Rc<Cell<[Color32; 2]>>,
}
fn notes_bed(text: &str, flags: Vec<NotesFlag>) -> NotesBed {
let notes = Rc::new(RefCell::new(NotesText::new(text.split('\n').map(|line| paragraph(vec![run(line, false)])).collect())));
let options =
Rc::new(RefCell::new(Options { flags, policy: NotesFlagPolicy::All, form: NotesEditorForm::Document, zoom: 1.0, read_only: false }));
let contexts = Rc::new(RefCell::new(Vec::new()));
let discard = Rc::new(Cell::new(false));
let inks = Rc::new(Cell::new([Color32::TRANSPARENT; 2]));
let (shown_notes, shown_options, seen, rerun, colors) = (notes.clone(), options.clone(), contexts.clone(), discard.clone(), inks.clone());
let mut fixture = Fixture::new(move |ui| {
if rerun.take() {
ui.ctx().request_discard("the trial reruns the pass");
}
with_env(
ui,
|scope| {
scope.values.set(FlagMark::Wave);
},
|ui| {
let env = Env::of(ui);
let style = StyleCx::of_env(ui.ctx(), &env);
colors.set([style.tone(Tone::Bad).egui(), style.tone(Tone::Warn).egui()]);
let options = shown_options.borrow();
let output = NotesEditor::new("Notes", &mut shown_notes.borrow_mut())
.flags(&options.flags)
.flag_policy(options.policy)
.form(options.form)
.zoom(options.zoom)
.read_only(options.read_only)
.show(ui);
seen.borrow_mut().extend(output.context);
},
);
});
fixture.room(Vec2::new(180.0, 500.0)).settle();
NotesBed { fixture, notes, options, contexts, discard, inks }
}
impl NotesBed {
fn point(&mut self, paragraph: &str, char: usize) -> Pos2 {
self.fixture
.frame_shapes()
.iter()
.find_map(|shape| match shape {
Shape::Text(text) if text.galley.text() == paragraph => {
Some(text.pos + text.galley.pos_from_cursor(egui::text::CCursor::new(char)).center().to_vec2())
}
_ => None,
})
.expect("the paragraph's painted character")
}
fn context(&mut self, at: Pos2, rerun: bool) -> NotesContext {
let before = self.contexts.borrow().len();
self.fixture.frame(vec![pointer::moved(at)]).frame(vec![pointer::secondary(at, true)]);
self.discard.set(rerun);
self.fixture.frame(vec![pointer::secondary(at, false)]).settle();
let contexts = self.contexts.borrow();
assert_eq!(contexts.len(), before + 1, "one context request per secondary click, including a two-pass frame");
contexts[before]
}
}
/// Mark coverage is read as coloured geometry, so batching paths or meshes preserves the assertion.
fn mark_segments(shapes: &[Shape], ink: Color32) -> Vec<[Pos2; 2]> {
let mut segments = Vec::new();
for shape in shapes {
match shape {
Shape::LineSegment { points, stroke, .. } if stroke.color == ink => segments.push(*points),
Shape::Path(path) if path.stroke.color == egui::epaint::ColorMode::Solid(ink) => {
segments.extend(path.points.windows(2).map(|pair| [pair[0], pair[1]]));
}
Shape::Mesh(mesh) => {
for triangle in mesh.indices.chunks_exact(3) {
for (a, b) in [(0, 1), (1, 2), (2, 0)] {
let (a, b) = (mesh.vertices[triangle[a] as usize], mesh.vertices[triangle[b] as usize]);
if a.color == ink && b.color == ink {
segments.push([a.pos, b.pos]);
}
}
}
}
_ => {}
}
}
segments
}
/// Flags cross paragraph and soft-wrap boundaries in characters; context requests preserve selection and input order.
#[trial]
fn a_flagged_range_marks_every_row_and_a_secondary_press_on_it_names_it() {
let wrapped = "bc ".repeat(24);
let flagged = format!("éa\n{wrapped}");
let plain = format!("{flagged}\ntail");
let mut bed = notes_bed(&plain, vec![NotesFlag::new(3..flagged.chars().count(), Tone::Bad), NotesFlag::new(2..5, Tone::Warn)]);
let shapes = bed.fixture.frame_shapes();
let segments = mark_segments(&shapes, bed.inks.get()[0]);
let painted = shapes
.iter()
.find_map(|shape| match shape {
Shape::Text(text) if text.galley.text() == wrapped => Some(text),
_ => None,
})
.expect("the wrapped paragraph");
let rows: Vec<Rect> = painted.galley.rows.iter().map(|row| row.rect().translate(painted.pos.to_vec2())).collect();
assert!(rows.len() > 1, "the flagged paragraph wraps");
assert!(
rows.iter().all(|row| segments.iter().any(|segment| row.expand(2.0).intersects(Rect::from_two_pos(segment[0], segment[1])))),
"every wrapped row has mark-coloured geometry"
);
let first = bed.point("éa", 0);
let second = bed.point(&wrapped, 0);
let end = bed.point(&wrapped, 2);
let short_mark = mark_segments(&shapes, bed.inks.get()[1]);
let short_bounds = short_mark.iter().fold(Rect::NOTHING, |bounds, segment| bounds.union(Rect::from_two_pos(segment[0], segment[1])));
assert!(
short_bounds.left() <= second.x + 0.5 && short_bounds.right() >= end.x - 0.5,
"the range crossing the separator marks the second paragraph from its first character"
);
bed.fixture.click_at(second).settle();
let context = bed.context(second, true);
assert_eq!(context.char, "éa\n".chars().count(), "paragraph offsets count characters, including the separator");
assert_eq!(context.flag, Some(0), "the first overlapping input flag wins");
let wrap_offset = painted.galley.rows[0].char_count_excluding_newline().0;
bed.fixture.key(Key::Home, Modifiers::NONE);
for _ in 0..wrap_offset {
bed.fixture.key(Key::ArrowRight, Modifiers::NONE);
}
let wrap_caret = bed.fixture.ime().expect("the caret at the soft wrap").caret;
bed.discard.set(true);
bed.fixture.key(Key::F10, Modifiers::SHIFT).settle();
let wrapped_request = *bed.contexts.borrow().last().expect("the soft-wrap keyboard request");
assert_eq!(wrapped_request.char, context.char + wrap_offset, "the keyboard request uses the live text offset without a hit test");
assert_eq!(wrapped_request.at, wrap_caret.left_bottom());
assert_eq!(wrapped_request.flag, context.flag);
let before = bed.fixture.ime().expect("the context click places a caret").caret;
let outside = bed.point("tail", 1);
let outside_request = bed.context(outside, true);
assert_eq!(outside_request.flag, None);
assert_ne!(bed.fixture.ime().expect("the caret moved outside the selection").caret, before);
let caret = bed.fixture.ime().expect("the live caret").caret;
let count = bed.contexts.borrow().len();
bed.discard.set(true);
bed.fixture.key(Key::F10, Modifiers::SHIFT).settle();
let keyboard = *bed.contexts.borrow().last().expect("the keyboard request");
assert_eq!(bed.contexts.borrow().len(), count + 1, "the second pass does not repeat the keyboard request");
assert_eq!(keyboard.at, caret.left_bottom());
assert_eq!(keyboard.char, outside_request.char);
assert_eq!(keyboard.flag, None);
assert_eq!(bed.fixture.ime().expect("the keyboard request keeps the caret").caret, caret);
bed.fixture.click_at(first).key(Key::Home, Modifiers::NONE).key(Key::End, Modifiers::SHIFT).settle();
let selected_caret = bed.fixture.ime().expect("the selection's caret").caret;
let inside = bed.point("éa", 1);
bed.context(inside, true);
assert_eq!(bed.fixture.ime().expect("a context click inside keeps the selection").caret, selected_caret);
bed.fixture.type_text("X").settle();
assert_eq!(bed.notes.borrow().plain(), plain.replacen("éa", "X", 1), "typing still replaces the selected paragraph");
bed.fixture.key(Key::Home, Modifiers::NONE).key(Key::End, Modifiers::SHIFT);
let outside = bed.point("tail", 1);
bed.context(outside, true);
bed.fixture.type_text("!").settle();
assert_eq!(
bed.notes.borrow().plain(),
plain.replacen("éa", "X", 1).replacen("tail", "t!ail", 1),
"a context click outside the selection collapses it at the pointed character"
);
}
/// A focused editor reports keyboard context requests even when clipping skips its paint.
#[trial]
fn a_clipped_editor_reports_keyboard_context_at_its_caret() {
let clipped = Rc::new(Cell::new(false));
let contexts = Rc::new(RefCell::new(Vec::new()));
let (clip, seen) = (clipped.clone(), contexts.clone());
let mut notes = NotesText::new(vec![paragraph(vec![run("alpha beta", false)])]);
let flags = [NotesFlag::new(0..5, Tone::Bad)];
let mut fixture = Fixture::new(move |ui| {
if clip.get() {
ui.set_clip_rect(Rect::NOTHING);
}
let output = NotesEditor::new("Notes", &mut notes).flags(&flags).show(ui);
seen.borrow_mut().extend(output.context);
});
fixture.settle();
let editor = fixture.by_label("Notes").expect("the editor");
fixture.click(&editor).key(Key::Home, Modifiers::NONE).key(Key::ArrowRight, Modifiers::NONE);
fixture.key(Key::F10, Modifiers::SHIFT);
let visible = *contexts.borrow().last().expect("the visible editor reports its keyboard request");
contexts.borrow_mut().clear();
clipped.set(true);
fixture.key(Key::F10, Modifiers::SHIFT);
let contexts = contexts.borrow();
let context = contexts.last().expect("the clipped editor reports its keyboard request");
assert_eq!(*context, visible, "clipping preserves the caret anchor, character and flag");
}
/// Paint follows the focused caret after this pass's edit; context lookup retains suppressed flags' input indices.
#[trial]
fn outside_caret_flags_follow_edits_without_hiding_context_targets() {
let mut bed = notes_bed("abc def", vec![NotesFlag::new(0..3, Tone::Bad), NotesFlag::new(4..7, Tone::Warn)]);
bed.options.borrow_mut().policy = NotesFlagPolicy::OutsideCaret;
let unfocused = bed.fixture.frame_shapes();
assert!(bed.inks.get().iter().all(|ink| !mark_segments(&unfocused, *ink).is_empty()));
let start = bed.point("abc def", 0);
bed.fixture.click_at(start).key(Key::Home, Modifiers::NONE);
for _ in 0..3 {
bed.fixture.key(Key::ArrowRight, Modifiers::NONE);
}
let before = bed.fixture.frame_shapes();
assert!(mark_segments(&before, bed.inks.get()[0]).is_empty(), "the flag's inclusive end holds the caret");
assert!(!mark_segments(&before, bed.inks.get()[1]).is_empty());
bed.discard.set(true);
bed.fixture.type_text("x");
let after = bed.fixture.frame_shapes();
assert!(!mark_segments(&after, bed.inks.get()[0]).is_empty(), "the edit moved the live caret out of the first flag");
assert!(mark_segments(&after, bed.inks.get()[1]).is_empty(), "the edited caret lies at the second flag's start");
let at = bed.point("abcx def", 5);
assert_eq!(bed.context(at, true).flag, Some(1), "paint suppression preserves the original flag index");
bed.options.borrow_mut().read_only = true;
let at = bed.point("abcx def", 1);
let plain = bed.notes.borrow().plain();
assert_eq!(bed.context(at, true).flag, Some(0), "read-only notes keep their context report");
bed.fixture.type_text("ignored").settle();
assert_eq!(bed.notes.borrow().plain(), plain, "a read-only context request enables no text edit");
}
/// Pane and document minimum heights follow the zoomed body lines; read-only empty notes use the resolved empty word.
#[trial]
fn pane_form_measures_fewer_zoomed_lines_and_read_only_empty_uses_its_word() {
let mut bed = notes_bed("", Vec::new());
let words = Env::of_root(bed.fixture.ctx()).words::<NotesLabels>();
assert!(bed.fixture.texts().iter().any(|text| text.text == words.placeholder.as_str()));
let document = bed.fixture.by_label("Notes").expect("the document editor").rect.height();
bed.options.borrow_mut().form = NotesEditorForm::Pane;
bed.fixture.settle();
let pane = bed.fixture.by_label("Notes").expect("the pane editor").rect.height();
assert!(pane < document);
bed.options.borrow_mut().zoom = 2.0;
bed.fixture.settle();
let zoomed_pane = bed.fixture.by_label("Notes").expect("the zoomed pane editor").rect.height();
assert!(zoomed_pane > pane);
bed.options.borrow_mut().form = NotesEditorForm::Document;
bed.fixture.settle();
assert!(bed.fixture.by_label("Notes").expect("the zoomed document editor").rect.height() > zoomed_pane);
bed.options.borrow_mut().read_only = true;
bed.fixture.settle();
assert!(bed.fixture.texts().iter().any(|text| text.text == words.empty.as_str()));
assert!(!bed.fixture.texts().iter().any(|text| text.text == words.placeholder.as_str()));
}