From 097c0bb150737cade34621858280e03eeab2850e Mon Sep 17 00:00:00 2001 From: alehel Date: Tue, 24 Nov 2026 09:02:59 +0100 Subject: [PATCH] ui-contract, ui-widgets: TextField::color_ranges colours stretches of a field's text in theme inks An app hands a field a function from its text to byte ranges, each in a RangeInk (muted, accent, good, warn, bad, info). The text part's layouter gives those ranges their ink and the rest the field's own; layout, editing, caret, selection, scrolling and access are unchanged, and a field without the option takes the old path. Each ink is its token moved to the text contrast minimum on the field's fill, so it reads in every theme. A text past COLORED_TEXT_LIMIT (16 KiB) is not coloured and the function is not called for it; ranges that do not fit the text are skipped. The field knows no language: the app finds the ranges. For storytold/pdfcraft#6942, which coloured JavaScript in the script boxes before they became craft TextFields. Co-Authored-By: Claude Opus 5.5 --- crates/ui-contract/src/primitives/mod.rs | 3 +- .../src/primitives/text_adapter.rs | 2 + .../ui-contract/src/primitives/text_input.rs | 50 +++++ .../ui-contract/src/runtime/egui/text_edit.rs | 84 ++++++- crates/ui-widgets/src/text/text_field.rs | 12 + crates/ui-widgets/tests/it/text/colored.rs | 206 ++++++++++++++++++ crates/ui-widgets/tests/it/text/mod.rs | 1 + 7 files changed, 348 insertions(+), 10 deletions(-) create mode 100644 crates/ui-widgets/tests/it/text/colored.rs diff --git a/crates/ui-contract/src/primitives/mod.rs b/crates/ui-contract/src/primitives/mod.rs index e502566464..c8fd5a1fbf 100644 --- a/crates/ui-contract/src/primitives/mod.rs +++ b/crates/ui-contract/src/primitives/mod.rs @@ -63,7 +63,8 @@ pub(crate) use svg_set::Layer; pub use svg_set::{AppIcons, register_app_icons}; pub use text::{ChordText, HAlign, LayoutRun, LeastLayout, ReadingMeasure, Span, TextLayout, TextRun, Wrap}; pub use text_input::{ - Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, ImeStamp, SubmitKey, TabKey, TextKey, TextOptions, + COLORED_TEXT_LIMIT, ColorRange, ColorRanges, Completer, Completion, EditorLine, EditorPurpose, EditorRun, EditorState, EditorSurrounding, + ImeStamp, RangeInk, SubmitKey, TabKey, TextKey, TextOptions, }; pub use textures::TextureCache; pub use tool::ToolIcon; diff --git a/crates/ui-contract/src/primitives/text_adapter.rs b/crates/ui-contract/src/primitives/text_adapter.rs index 92fd681222..9e9196510f 100644 --- a/crates/ui-contract/src/primitives/text_adapter.rs +++ b/crates/ui-contract/src/primitives/text_adapter.rs @@ -571,6 +571,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut baseline, scroll, line_break: line_break(input.options.submit_key), + colors: input.options.color_ranges.as_deref(), }; // A secondary press inside the selection keeps the selection for the edit menu it opens, as native fields do; // egui's widget moves the caret to any press, so the selection from before the press is put back. @@ -708,6 +709,7 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) { baseline: None, scroll: 0.0, line_break: line_break(SubmitKey::default()), + colors: None, }, ); crate::runtime::pointer::record_text_widget(&ctx, widget, owner); diff --git a/crates/ui-contract/src/primitives/text_input.rs b/crates/ui-contract/src/primitives/text_input.rs index da22da7025..c038c8e532 100644 --- a/crates/ui-contract/src/primitives/text_input.rs +++ b/crates/ui-contract/src/primitives/text_input.rs @@ -52,6 +52,50 @@ pub enum TabKey { /// Whether a pasted text is whole ([`TextOptions::whole_paste`]). type WholePaste = dyn Fn(&str) -> bool; +/// The colour ranges of a text ([`TextOptions::color_ranges`]): called with the text each time the part lays it out, +/// which is every frame the part shows. An app whose ranges are costly to find keeps its own cache. +pub type ColorRanges = dyn Fn(&str) -> Vec; + +/// The longest text, in bytes, a part colours: a longer one is laid out in its plain ink, and its +/// [`ColorRanges`] is not called. It bounds the cost of an app's colouring (a highlighter whose time grows with the +/// square of the length on crafted input) at the size of a long script. +pub const COLORED_TEXT_LIMIT: usize = 16 * 1024; + +/// A theme colour for a stretch of a field's text. Each is the token's colour moved, where it has to be, to the text +/// contrast minimum on the field's fill, so every ink reads in every theme and contrast. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum RangeInk { + /// `text.muted`. + Muted, + /// `accent.text`. + Accent, + /// `status.good.fg`. + Good, + /// `status.warn.fg`. + Warn, + /// `status.bad.fg`. + Bad, + /// `status.info.fg`. + Info, +} + +/// One stretch of a text in an ink of its own: `range` is in bytes of the text the [`ColorRanges`] was given. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ColorRange { + /// The bytes the ink covers. + pub range: Range, + /// Their ink. + pub ink: RangeInk, +} + +impl ColorRange { + /// The bytes `range` in `ink`. + pub fn new(range: Range, ink: RangeInk) -> Self { + ColorRange { range, ink } + } +} + /// How a text part behaves beyond its codec. #[derive(Clone)] pub struct TextOptions { @@ -129,6 +173,11 @@ pub struct TextOptions { /// The key that submits a multi-line text: under `Enter`, plain, Cmd and Ctrl+Enter submit and Shift+Enter breaks /// the line. pub submit_key: SubmitKey, + /// Colours stretches of the text: the ranges it gives, in order, take their inks and the rest the part's ink. A range + /// that is empty, overlaps the one before, ends past the text or splits a character is skipped. Colour is display + /// only: editing, the caret, selection, wrapping and what assistive technology reads are as without it. A masked or + /// disabled part, and a text past [`COLORED_TEXT_LIMIT`], show no colours. + pub color_ranges: Option>, } /// Which Enter chord submits a multi-line text. @@ -175,6 +224,7 @@ impl Default for TextOptions { holds_drafts: false, whole_paste: None, submit_key: SubmitKey::CommandEnter, + color_ranges: None, } } } diff --git a/crates/ui-contract/src/runtime/egui/text_edit.rs b/crates/ui-contract/src/runtime/egui/text_edit.rs index 779684c381..e1deacc7ad 100644 --- a/crates/ui-contract/src/runtime/egui/text_edit.rs +++ b/crates/ui-contract/src/runtime/egui/text_edit.rs @@ -1,5 +1,7 @@ //! Building `TextEdit` and its state: the one caller of egui's text editing. +use crate::primitives::{COLORED_TEXT_LIMIT, ColorRange, ColorRanges, RangeInk}; +use crate::runtime::env::Env; use craft_theme::TypeRole; use egui::text::{CCursor, CCursorRange, LayoutJob, TextFormat}; use egui::text_edit::TextEditState; @@ -52,6 +54,8 @@ pub(crate) struct Edit<'a> { /// before the adapter sees the Enter, so the adapter passes the chord its submit key leaves free: Shift under a plain /// Enter submit, none under Cmd or Ctrl+Enter. pub line_break: egui::Modifiers, + /// The app's colour ranges of the text (`TextOptions::color_ranges`). + pub colors: Option<&'a ColorRanges>, } /// What the widget did in one pass. @@ -99,6 +103,7 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) baseline, scroll, line_break, + colors, } = edit; // The same font and optical size as a label of the same role: one text path. let tokens = &env.tokens; @@ -109,6 +114,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) let optical_size = tokens.optical_size(facts, role, mono); let had_focus = ui.memory(|memory| memory.has_focus(id)); let entered = had_focus && ui.input(|input| input.key_pressed(egui::Key::Enter)); + // A masked text shows dots and a disabled one the disabled colour: neither is coloured. + let colors = colors.filter(|_| !password && enabled); + let inks = colors.map(|_| RANGE_INKS.map(|range_ink| (range_ink, ink_of(env, range_ink)))); + let ink_of_range = |range_ink: RangeInk| inks.iter().flatten().find(|(of, _)| *of == range_ink).map_or(ink, |(_, color)| *color); let mut layouter = |ui: &Ui, text: &dyn egui::TextBuffer, wrap_width: f32| { if let Some(galley) = &galley { return galley.clone(); @@ -128,17 +137,23 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) if let Some(size) = optical_size { plain.coords.push(*b"opsz", size); } - match preedit - .as_ref() + let preedit = preedit + .clone() .filter(|_| !password) - .filter(|range| range.end <= text.len() && text.is_char_boundary(range.start) && text.is_char_boundary(range.end)) - { - Some(range) => { - job.append(&text[..range.start], 0.0, plain.clone()); - job.append(&text[range.clone()], 0.0, TextFormat { underline: egui::Stroke::new(underline, ink), ..plain.clone() }); - job.append(&text[range.end..], 0.0, plain); + .filter(|range| range.end <= text.len() && text.is_char_boundary(range.start) && text.is_char_boundary(range.end)); + if let Some(colors) = colors.filter(|_| !text.is_empty() && text.len() <= COLORED_TEXT_LIMIT) { + for (run, color) in color_runs(text, &colors(text), ink, &ink_of_range) { + append_run(&mut job, text, run, &TextFormat { color, ..plain.clone() }, preedit.as_ref(), underline); + } + } else { + match preedit { + Some(range) => { + job.append(&text[..range.start], 0.0, plain.clone()); + job.append(&text[range.clone()], 0.0, TextFormat { underline: egui::Stroke::new(underline, ink), ..plain.clone() }); + job.append(&text[range.end..], 0.0, plain); + } + None => job.append(text, 0.0, plain), } - None => job.append(text, 0.0, plain), } #[cfg(feature = "testing")] crate::runtime::measure::count_text_layout(ui.ctx()); @@ -264,6 +279,57 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>) } } +/// Every [`RangeInk`]. +const RANGE_INKS: [RangeInk; 6] = [RangeInk::Muted, RangeInk::Accent, RangeInk::Good, RangeInk::Warn, RangeInk::Bad, RangeInk::Info]; + +/// The colour of `ink` on a field: its token moved to the text contrast minimum on the field's fill where it is short of it. +fn ink_of(env: &Env, ink: RangeInk) -> Color32 { + let colors = &env.tokens.color; + let token = match ink { + RangeInk::Muted => colors.text.muted, + RangeInk::Accent => colors.accent.text, + RangeInk::Good => colors.status.good.fg, + RangeInk::Warn => colors.status.warn.fg, + RangeInk::Bad => colors.status.bad.fg, + RangeInk::Info => colors.status.info.fg, + }; + let min = craft_theme::text_contrast_min(env.tokens.contrast()); + crate::style::rgba_color(craft_theme::ensure_contrast(token, colors.surface.sunken, min)) +} + +/// `text` cut into runs that cover it in order, each with its colour: the valid `ranges` in theirs, the gaps in `plain`. +/// A range that is empty, starts before the end of the one before, ends past the text or splits a character is skipped. +fn color_runs(text: &str, ranges: &[ColorRange], plain: Color32, ink: &impl Fn(RangeInk) -> Color32) -> Vec<(Range, Color32)> { + let mut runs = Vec::new(); + let mut at = 0; + for ColorRange { range, ink: range_ink } in ranges { + let Range { start, end } = *range; + if start < at || end <= start || end > text.len() || !text.is_char_boundary(start) || !text.is_char_boundary(end) { + continue; + } + if start > at { + runs.push((at..start, plain)); + } + runs.push((start..end, ink(*range_ink))); + at = end; + } + if at < text.len() { + runs.push((at..text.len(), plain)); + } + runs +} + +/// Appends the bytes `run` of `text` in `format`, the part inside `preedit` underlined in the run's colour. +fn append_run(job: &mut LayoutJob, text: &str, run: Range, format: &TextFormat, preedit: Option<&Range>, underline: f32) { + let composed = preedit.map_or(run.end..run.end, |preedit| preedit.start.clamp(run.start, run.end)..preedit.end.clamp(run.start, run.end)); + let underlined = TextFormat { underline: egui::Stroke::new(underline, format.color), ..format.clone() }; + for (piece, format) in [(run.start..composed.start, format), (composed.clone(), &underlined), (composed.end..run.end, format)] { + if let Some(piece) = text.get(piece).filter(|piece| !piece.is_empty()) { + job.append(piece, 0.0, format.clone()); + } + } +} + /// The selection of the widget as character indices, `(primary, secondary)`. pub(crate) fn selection(ctx: &Context, id: Id) -> Option<(usize, usize)> { TextEditState::load(ctx, id).and_then(|state| state.cursor.char_range()).map(|range| (range.primary.index.0, range.secondary.index.0)) diff --git a/crates/ui-widgets/src/text/text_field.rs b/crates/ui-widgets/src/text/text_field.rs index 729528ab79..77d8ce01c8 100644 --- a/crates/ui-widgets/src/text/text_field.rs +++ b/crates/ui-widgets/src/text/text_field.rs @@ -297,6 +297,18 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> { self } + /// Colours stretches of the text: `ranges` gives them for the text it is called with, as byte ranges in order, + /// each in a theme ink ([`RangeInk`](crate::primitives::RangeInk)) that keeps the text contrast minimum on the + /// field. The rest of the text keeps the field's ink. It is called each frame the field shows, with the text as + /// typed, and not for a text longer than [`COLORED_TEXT_LIMIT`](crate::primitives::COLORED_TEXT_LIMIT), which shows + /// uncoloured. Colour is display only: editing, the caret, selection, wrapping and what assistive technology reads are + /// as without it. The field knows no language: the app finds the ranges (a script's keywords, strings and comments). + #[must_use] + pub fn color_ranges(mut self, ranges: impl Fn(&str) -> Vec + 'static) -> Self { + self.options.color_ranges = Some(Arc::new(ranges)); + self + } + /// `text` replaces the selection in this pass: at the caret it inserts. Set it for one pass only. #[must_use] pub fn replace_selection(mut self, text: impl Into) -> Self { diff --git a/crates/ui-widgets/tests/it/text/colored.rs b/crates/ui-widgets/tests/it/text/colored.rs new file mode 100644 index 0000000000..7a16a183aa --- /dev/null +++ b/crates/ui-widgets/tests/it/text/colored.rs @@ -0,0 +1,206 @@ +//! `TextField::color_ranges`: the ranges an app gives take theme inks that read on the field; colouring changes no +//! layout; typing in a coloured field edits it and colours the new text; a text past the limit, and a range past the +//! text, are not coloured. + +use craft_theme::{Contrast, Mode, Rgba, contrast_ratio, text_contrast_min}; +use craft_ui::contract::{Bind, Show as _}; +use craft_ui::primitives::{COLORED_TEXT_LIMIT, ColorRange, RangeInk}; +use craft_ui::runtime::env::Env; +use craft_ui::testing::{Fixture, trial}; +use craft_ui::text::TextField; +use egui::{Color32, Key, Modifiers, Shape}; +use std::cell::{Cell, RefCell}; +use std::rc::Rc; + +/// Every ink, in the order [`INKED`] names its words. +const INKS: [RangeInk; 6] = [RangeInk::Muted, RangeInk::Accent, RangeInk::Good, RangeInk::Warn, RangeInk::Bad, RangeInk::Info]; + +/// One word per ink, then a plain one. +const INKED: &str = "muted accent good warn bad info plain"; + +/// The ranges of every `var` in `text`, in the accent ink. +fn vars(text: &str) -> Vec { + text.match_indices("var").map(|(at, word)| ColorRange::new(at..at + word.len(), RangeInk::Accent)).collect() +} + +/// The text shapes among `shapes`, those inside a `Shape::Vec` included. +fn text_shapes<'a>(shapes: &'a [Shape], out: &mut Vec<&'a egui::epaint::TextShape>) { + for shape in shapes { + match shape { + Shape::Vec(shapes) => text_shapes(shapes, out), + Shape::Text(text) => out.push(text), + _ => {} + } + } +} + +/// The galley of the field's text, found by a piece of it. +fn galley_with(fixture: &mut Fixture, piece: &str) -> std::sync::Arc { + let shapes = fixture.frame_shapes(); + let mut texts = Vec::new(); + text_shapes(&shapes, &mut texts); + texts + .into_iter() + .find(|text| text.galley.job.text.contains(piece)) + .map(|text| text.galley.clone()) + .unwrap_or_else(|| panic!("the field paints its text holding {piece:?}")) +} + +/// The text of each section of `galley`, with its colour. +fn sections(galley: &egui::Galley) -> Vec<(String, Color32)> { + let text = &galley.job.text; + galley + .job + .sections + .iter() + .map(|section| (text.get(section.byte_range.start.0..section.byte_range.end.0).unwrap_or_default().to_owned(), section.format.color)) + .collect() +} + +/// The colour of each byte of the first `piece` in `galley`'s text, when they share one. Sections of one format merge, +/// so a range is found by its bytes, not as a section of its own. +fn color_of(galley: &egui::Galley, piece: &str) -> Option { + let start = galley.job.text.find(piece)?; + let mut colors = galley.job.sections.iter().filter_map(|section| { + let range = section.byte_range.start.0..section.byte_range.end.0; + (range.start < start + piece.len() && start < range.end).then_some(section.format.color) + }); + let first = colors.next()?; + colors.all(|color| color == first).then_some(first) +} + +/// A fixture showing a three-line monospace field over `text`, coloured by `ranges` when given; the field's fill is +/// written to `fill` each frame. +fn field(text: &str, ranges: Option Vec>, fill: Rc>) -> Fixture { + let value = Rc::new(RefCell::new(text.to_owned())); + Fixture::new(move |ui| { + fill.set(Env::of(ui).tokens.tokens().color.surface.sunken); + let mut text = value.borrow_mut(); + let mut field = TextField::new("Script", Bind::bound(&mut *text)).lines(3).mono(); + if let Some(ranges) = ranges { + field = field.color_ranges(ranges); + } + field.show(ui); + }) +} + +/// Each word in its own ink: the ink is a colour of its own, and keeps the text contrast minimum on the field's fill in +/// every built-in theme, both modes and both contrasts, the status inks included, which the theme holds to it only on panels. +#[trial] +fn ranges_take_inks_that_read_on_the_field_in_every_theme() { + fn inked(text: &str) -> Vec { + let (mut at, mut out) = (0, Vec::new()); + for (word, ink) in text.split(' ').zip(INKS) { + out.push(ColorRange::new(at..at + word.len(), ink)); + at += word.len() + 1; + } + out + } + let modes = [(Mode::Light, Contrast::Standard), (Mode::Dark, Contrast::Standard), (Mode::Light, Contrast::High), (Mode::Dark, Contrast::High)]; + for (theme, (mode, contrast)) in craft_theme::builtins().iter().flat_map(|theme| modes.map(|mode| (theme.id.clone(), mode))) { + let fill = Rc::new(Cell::new(Rgba::BLACK)); + let mut fixture = field(INKED, Some(inked), fill.clone()); + fixture.theme_id(theme.clone()).theme(mode, contrast).settle(); + let galley = galley_with(&mut fixture, "plain"); + let plain = color_of(&galley, "plain"); + for (word, ink) in INKED.split(' ').zip(INKS) { + let color = + color_of(&galley, word).unwrap_or_else(|| panic!("{theme:?} {mode:?} {contrast:?}: {word} is one colour: {:?}", sections(&galley))); + let ratio = contrast_ratio(Rgba::rgb(color.r(), color.g(), color.b()), fill.get()); + assert!(ratio >= text_contrast_min(contrast), "{theme:?} {mode:?} {contrast:?}: {ink:?} at {ratio:.2}:1 on the field"); + } + // High contrast may take an ink as far as the plain text's colour; standard keeps the accent apart. + if contrast == Contrast::Standard { + assert_ne!(color_of(&galley, "accent"), plain, "{theme:?} {mode:?}: the accent ink is not the plain text's"); + } + } +} + +/// The same text with and without ranges lays out alike, glyph for glyph: the ranges change colours and nothing else, +/// and without them the text is one colour. +#[trial] +fn ranges_change_only_the_colors_of_the_text() { + let text = "var a = 1;\n\tvar b = 2; // a long line that wraps inside the field's width at least once or twice"; + let fill = Rc::new(Cell::new(Rgba::BLACK)); + let mut plain = field(text, None, fill.clone()); + let mut colored = field(text, Some(vars), fill); + let (plain, colored) = (galley_with(plain.settle(), "long line"), galley_with(colored.settle(), "long line")); + let glyphs = |galley: &egui::Galley| -> Vec<(egui::Rect, Vec)> { + galley.rows.iter().map(|row| (row.rect(), row.glyphs.iter().map(|glyph| glyph.pos).collect())).collect() + }; + assert!(plain.rows.len() > 2, "the text wraps: {} rows", plain.rows.len()); + assert_eq!(glyphs(&plain), glyphs(&colored), "the coloured text is laid out as the plain one"); + let ink = color_of(&plain, text); + assert!(ink.is_some(), "a field without ranges shows one colour: {:?}", sections(&plain)); + assert_ne!(color_of(&colored, "var"), ink, "the ranges are coloured: {:?}", sections(&colored)); + assert_eq!(color_of(&colored, " a = 1;"), ink, "the text between the ranges keeps the field's ink"); +} + +/// Typing into a coloured field edits its value, Tab inserts there, and the ranges follow the text as typed. +#[trial] +fn typing_in_a_colored_field_edits_it_and_colors_the_new_text() { + let value = Rc::new(RefCell::new(String::new())); + let shown = value.clone(); + let mut fixture = Fixture::new(move |ui| { + TextField::new("Script", Bind::bound(&mut *shown.borrow_mut())).lines(3).mono().tab_inserts(true).color_ranges(vars).show(ui); + }); + fixture.settle(); + fixture.key(Key::Tab, Modifiers::NONE).settle(); + fixture.type_text("x = var"); + fixture.key(Key::Tab, Modifiers::NONE); + fixture.type_text("y").settle(); + assert_eq!(*value.borrow(), "x = var\ty", "the typing reaches the value, with the tab"); + let galley = galley_with(&mut fixture, "x = "); + assert_ne!(color_of(&galley, "var"), color_of(&galley, "x = "), "the typed range is coloured: {:?}", sections(&galley)); +} + +/// A text at the limit is coloured; one byte longer shows in one colour, and its ranges are never asked for. +#[trial] +fn a_text_past_the_limit_is_not_colored() { + let longest = Rc::new(Cell::new(0)); + for (len, colored) in [(COLORED_TEXT_LIMIT, true), (COLORED_TEXT_LIMIT + 1, false)] { + let text = format!("var {}", "x".repeat(len - 4)); + let value = Rc::new(RefCell::new(text)); + let (shown, asked) = (value.clone(), longest.clone()); + let mut fixture = Fixture::new(move |ui| { + let asked = asked.clone(); + TextField::new("Script", Bind::bound(&mut *shown.borrow_mut())) + .lines(3) + .color_ranges(move |text| { + asked.set(asked.get().max(text.len())); + vars(text) + }) + .show(ui); + }); + let sections = sections(&galley_with(fixture.settle(), "var")); + assert_eq!(sections.len() > 1, colored, "{len} bytes: coloured {colored}"); + } + assert!(longest.get() <= COLORED_TEXT_LIMIT, "no text past the limit is handed to the ranges: {}", longest.get()); +} + +/// Ranges that are empty, overlap the one before, split a character or end past the text are skipped, and the valid +/// ones still colour. +#[trial] +fn ranges_that_do_not_fit_the_text_are_skipped() { + fn hostile(text: &str) -> Vec { + let accent = RangeInk::Accent; + // "é" is two bytes: 1..2 splits it. "var" is 3..6. + vec![ + ColorRange::new(1..2, accent), + ColorRange::new(3..6, accent), + ColorRange::new(4..5, accent), + ColorRange::new(7..7, accent), + ColorRange::new(8..text.len() + 9, accent), + ColorRange::new(usize::MAX - 1..usize::MAX, accent), + ] + } + let fill = Rc::new(Cell::new(Rgba::BLACK)); + let mut fixture = field("é var b", Some(hostile), fill); + let galley = galley_with(fixture.settle(), "var"); + let text: String = sections(&galley).into_iter().map(|(text, _)| text).collect(); + assert_eq!(text, "é var b", "the sections cover the text once, in order: {:?}", sections(&galley)); + let plain = color_of(&galley, "é "); + assert!(plain.is_some(), "a range that splits a character is skipped: {:?}", sections(&galley)); + assert_ne!(color_of(&galley, "var"), plain, "the valid range is coloured: {:?}", sections(&galley)); + assert_eq!(color_of(&galley, " b"), plain, "the ranges past the text are skipped: {:?}", sections(&galley)); +} diff --git a/crates/ui-widgets/tests/it/text/mod.rs b/crates/ui-widgets/tests/it/text/mod.rs index b0899ac27d..0bbde496fd 100644 --- a/crates/ui-widgets/tests/it/text/mod.rs +++ b/crates/ui-widgets/tests/it/text/mod.rs @@ -1,6 +1,7 @@ pub(crate) mod access; pub(crate) mod alt_text; pub(crate) mod chips; +pub(crate) mod colored; pub(crate) mod edit_menu; pub(crate) mod fields; pub(crate) mod hex;