Merge branch 'main' into fix/rail-drawer-spacing

This commit is contained in:
FredApps committed 2026-11-28 23:56:32 +01:00
commit 55c08c627e
30 files changed
+831 -64

No files matched your search

+6 -4
View File
@@ -10,7 +10,7 @@ use craft_ui::contract::{
Bind, Common, Component, Cx, DisabledLook, EditResponse, Gap, GlyphLabel, LabelKind, MeasureCx, NoValue, Outcome, PartsCx, Pointer as _, Role,
Show as _, ShowContainer as _, SideLabel, Sizing,
};
use craft_ui::form::{Field, SliderField, SliderFieldLayout};
use craft_ui::form::{Field, FieldDecimals, SliderField, SliderFieldLayout};
use craft_ui::layout_components::Row;
use craft_ui::primitives::{PaintShape, StrokeWidth};
use craft_ui::runtime::env::{Label, UnitKind};
@@ -149,7 +149,8 @@ impl Component for TrackRamp {
}
}
/// The slider and number field of a channel, over `value`, with `track` colours on the groove.
/// The slider and number field of a channel, over `value`, with `track` colours on the groove. The field shows the
/// decimals the rule declares, a percent channel too ("67", not the percent look's "66.7").
pub(crate) fn channel_slider<'a>(
name: Label,
value: Bind<'a, f64>,
@@ -157,7 +158,7 @@ pub(crate) fn channel_slider<'a>(
unit: ChannelUnit,
track: Option<(Vec<Srgba>, bool)>,
) -> SliderField<'a> {
let field = SliderField::new(name, value, rule.range.clone()).step(rule.step);
let field = SliderField::new(name, value, rule.range.clone()).step(rule.step).field_decimals(FieldDecimals::Fixed(usize::from(rule.decimals)));
let field = match unit {
ChannelUnit::None => field,
ChannelUnit::Percent => field.unit_kind(UnitKind::Percent),
@@ -172,7 +173,8 @@ pub(crate) fn channel_slider<'a>(
/// One channel on one line, as Photoshop's Color panel draws it: the label at the start (the channel's short label
/// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its
/// track, and the number field with its unit at the end, as wide as its widest value.
/// track, and the number field with its unit at the end, as wide as its widest value, showing the channel's declared
/// decimals.
#[derive(craft_ui::contract::Pattern)]
pub struct ChannelRow<'a> {
label: Label,
+30
View File
@@ -685,3 +685,33 @@ fn a_request_for_the_swatches_opens_the_picker_on_its_swatch_view() {
assert!(shows_swatches(request().on_swatches()), "the swatch view shows the library's cells");
assert!(!shows_swatches(request()), "without it the picker opens on the Color Models");
}
/// The number a Compact picker's channel field named `channel` paints, the picker showing HSB `values`.
fn compact_field_number(values: [f32; 3], channel: &str) -> String {
let hsb = ModelValues::new(HsbModel.id(), &values);
let mut fixture = Fixture::new(move |ui| {
let mut color = PickedColor::in_model(HsbModel.to_srgb(&hsb.values), hsb);
let models: [&dyn ColorModel; 2] = [&HsbModel, &RgbModel];
let _ = ColorPicker::new("Color", Bind::bound(&mut color)).layout(ColorPickerLayout::Compact).models(models).show(ui);
});
fixture.room(vec2(600.0, 700.0));
fixture.settle();
let tree = fixture.tree();
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().find(|t| tree.name_of(t.node) == Some(channel));
let field = field.unwrap_or_else(|| panic!("the picker shows a {channel} field")).rect;
let texts = fixture.texts();
let number = texts.iter().find(|run| field.contains(run.rect.center()) && run.text.starts_with(|c: char| c.is_ascii_digit()));
number
.unwrap_or_else(|| panic!("the {channel} field shows its value: {:?}", texts.iter().map(|r| r.text.to_string()).collect::<Vec<_>>()))
.text
.to_string()
}
/// A Compact picker's channel rows, which the Color panel and the harmony brightness row share, show the decimals their
/// channel declares, a percent channel too: HSB saturation declares none, so 66.7 % reads "67", not the percent look's
/// "66.7".
#[trial]
fn the_compact_pickers_percent_channels_show_the_decimals_they_declare() {
assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Saturation"), "67");
assert_eq!(compact_field_number([210.0, 66.7, 60.0], "Hue"), "210", "a degree channel keeps its whole degrees");
}
@@ -1202,6 +1202,17 @@ impl BodyHooks<'_> {
// A measuring run lays out and measures: it registers no instance, focus body, scroll region or body layer,
// and claims no room in a parent flow.
let real = !ui.is_sizing_pass();
// A held container whose width its least width decides, not its content, shows across the width its column
// settles on with its fill children at their measures. It asks the column to sweep again with that width: laid
// out across it its own fill children take it, and its content-sized record was not made across it.
if !self.wide()
&& self.held
&& self.least_width > 0.0
&& matches!(props.layout, layout::BodyLayout::Stack)
&& let Some(ColumnSweep::Count(column)) = env.column
{
crate::layout::report_held(&ctx, column, id, crate::layout::HeldKind::Column, self.room.x);
}
let regions = self.regions(props, inner, pad, room, rtl, self.measured_sizes(), real).below(core.content_rect.min.y + band);
let surface_slot = SurfaceSlot::reserve(ui, matches!(props.mount, Mount::Layer(_)));
let band_slot = ui.painter().add(Shape::Noop);
@@ -87,9 +87,13 @@ impl BodyHooks<'_> {
scoped.inside_label = None;
scoped.cell_fills = false;
// Along a width the container takes from its content, its regions measure at their content widths: a child
// that fills takes what it needs, not the whole room. A container that passes its column's width on measures
// them across it.
if !real && !self.wide() {
// that fills takes what it needs, not the whole room. A container given its width (a rect, a column's width it
// passes on, or the width its column settled on) lays its regions out across it in both runs: its bands are as
// wide as the container, so a child that fills takes the band, whatever column its parent is.
if self.wide() {
scoped.content_column = false;
scoped.content.0 = false;
} else if !real {
scoped.content_column = true;
}
if props.header.is_some_and(|header| header.band == DragBand::Reorder) {
@@ -222,6 +222,9 @@ pub enum LeastWidth {
SideMenu,
/// `size.dock.column`: a fixed side pane is as wide as a dock column.
DockColumn,
/// `size.dialog.wrap`: a command palette's box, as wide as a dialog paragraph's line, so it keeps one width
/// while its results change instead of following its widest row.
Palette,
}
impl LeastWidth {
@@ -236,6 +239,7 @@ impl LeastWidth {
LeastWidth::WideDialog => tokens.size.dialog.least + tokens.size.dialog.wrap,
LeastWidth::SideMenu => tokens.size.rail.width * 5.0,
LeastWidth::DockColumn => tokens.size.dock.column,
LeastWidth::Palette => tokens.size.dialog.wrap,
}
}
}
+1
View File
@@ -676,6 +676,7 @@ pub(crate) fn run<C: Component>(
let caret = adapter::caret_byte(&ctx, widget, state.draft.as_deref().unwrap_or(out.layout.full()));
*cx.core.memory.shown::<TextState>(state_id) = state;
let mut outcome = resolved.outcome;
outcome.origin = out.origin;
outcome.layout = Some(out.layout);
outcome.caret_visible = caret_visible;
outcome.composing = crate::runtime::ime::composing(&ctx, widget);
+28 -12
View File
@@ -157,6 +157,11 @@ pub(crate) enum HeldKind {
/// (`MeasureCx::picture_size`): it shows at the width it sizes at in the column's width, which may be narrower than
/// the column.
Picture,
/// A fill-width container whose least width decides its width, its body a content-sized `Stack` column
/// (`BodyHooks::plan_regions` reports it): it shows across the column's width, and laid out across it its own fill
/// children take that width where its content-sized measure left them at their measures. Whatever width it
/// measured at, the column sweeps again.
Column,
}
/// The held children of each content-sized `Stack` column in its measuring run, by column id: each child's kind and
@@ -170,6 +175,11 @@ pub(crate) fn report_held(ctx: &egui::Context, column: Id, child: Id, kind: Held
pass_state::with::<HeldWidths, _>(ctx, |held| {
if let Some(children) = held.0.get_mut(&column) {
let entry = children.entry(child).or_insert((kind, width));
// A container that lays its content out as a column reports its kind once its own body ran, after the
// width `place_root` reported for it in flow: the kind of the two is its own.
if kind == HeldKind::Column {
entry.0 = HeldKind::Column;
}
entry.1 = entry.1.min(width);
}
});
@@ -1166,14 +1176,15 @@ fn measure_sharing<R>(ui: &mut Ui, env: &Env, id: Id, axis: Axis, layout: egui::
/// is bounded: each sweep is `run_sharing`'s, with the column's sweep (`ColumnSweep`) in its children's env. It adds no
/// `Ui` of its own, so the children have the ids `run_sharing` gives them when the column's width is not bounded.
///
/// A held child (`HeldKind`: a fill-width child, or a picture that took its least for want of room) measures at its
/// own width while the column settles its width from the others, so it may measure narrower than it shows. A
/// measuring run sweeps the children once, each held child reporting the width it measured at (`report_held`). When
/// one of them measured narrower than the column settled on, it sweeps them again with that width, at which the held
/// children measure in the column's width and the others reuse their records; else the first sweep stands, and each
/// held child keeps the record it made at its own width, which is the column's. It records which
/// (`sub(id, "column")`): the real run gives the held children the width the column shows at only after a second
/// sweep, so each shows as its records were made.
/// A held child (`HeldKind`: a fill-width child, a picture that took its least for want of room, or a container that
/// lays its content out as a column) measures at its own width while the column settles its width from the others, so
/// it may measure narrower than it shows. A measuring run sweeps the children once, each held child reporting the width
/// it measured at (`report_held`). When one of them measured narrower than the column settled on, or lays its content
/// out as a column (whose fill children take the column's width where its content-sized measure left them at their
/// measures, whatever it measured at), it sweeps them again with that width, at which the held children measure in the
/// column's width and the others reuse their records; else the first sweep stands, and each held child keeps the record
/// it made at its own width, which is the column's. It records which (`sub(id, "column")`): the real run gives the held
/// children the width the column shows at only after a second sweep, so each shows as its records were made.
// PLAN: the second sweep's need is decided once for the column, not per held container at body/hooks.rs's reuse
// rule: a container that reused its content-sized record there would be laid out across in the real run under records
// not made across.
@@ -1199,11 +1210,16 @@ fn run_column<R>(ui: &mut Ui, env: &Env, id: Id, layout: egui::Layout, mut body:
let installed = Env::install_for(ui, env.clone());
let (inner, rect) = measure_sharing(ui, &env, id, Axis::Y, layout, &mut body);
Env::restore(&ctx, installed);
let narrowest = pass_state::with::<HeldWidths, _>(&ctx, |held| {
held.0.get(&id).map_or(f32::INFINITY, |children| children.values().fold(f32::INFINITY, |least, (_, width)| least.min(*width)))
let (narrowest, laid_out) = pass_state::with::<HeldWidths, _>(&ctx, |held| {
held.0.get(&id).map_or((f32::INFINITY, false), |children| {
children
.values()
.fold((f32::INFINITY, false), |(least, laid_out), (kind, width)| (least.min(*width), laid_out || *kind == HeldKind::Column))
})
});
// Half a point: less than a pixel shows at any scale the box runs.
let again = narrowest < rect.width() - 0.5;
// Half a point: less than a pixel shows at any scale the box runs. A held child that lays its content out as a
// column is swept again whatever it measured at: across the column's width its fill children take it.
let again = narrowest < rect.width() - 0.5 || laid_out;
((inner, rect, again), again)
});
let column = rect.width();
@@ -81,6 +81,9 @@ pub struct TextOutcome<V> {
pub value: Option<V>,
/// The laid-out text, so an editor draws gutters and line numbers beside it.
pub layout: Option<super::TextLayout>,
/// Where the origin of `layout` sits on screen this pass, the text's margin and scroll included: a row of the
/// layout is at its galley position moved by this. The rect's corner until the text is laid out.
pub origin: egui::Pos2,
/// Whether the caret stroke shows this pass (the caret blink).
pub caret_visible: bool,
/// The draft is not a value of the codec.
@@ -103,6 +106,7 @@ impl<V> TextOutcome<V> {
draft: None,
value: None,
layout: None,
origin: rect.min,
caret_visible: true,
invalid: false,
committed: None,
+2 -1
View File
@@ -243,7 +243,8 @@ pub(crate) struct TextEnv<'a> {
/// The baseline of a control's line of `role` whose centre line lies at `centre`: where a one-line text of `role` in
/// its own face sits with its row centred on the centre line, as `Draw::text` centres a line in a taller rect. Every
/// text in the line sits on it, whatever its face or size: a select's face, a field's mono digits and the smaller unit
/// after them.
/// after them. A text part set at a size of the caller's own is the one text that centres its own row on its part
/// instead, since a row taller than the role's would carry the part's text out of it (`TextOptions::size`).
pub(crate) fn line_baseline(ctx: &Context, env: &TextEnv<'_>, role: TypeRole, centre: f32) -> f32 {
let line = TextRun::new("x").role(role).layout(ctx, env, f32::INFINITY);
centre - line.size().y / 2.0 + line.first_baseline
@@ -193,6 +193,8 @@ pub(crate) struct AdapterOut {
pub clicked: bool,
/// The screen y of the first row's baseline; `None` while the text is empty.
pub baseline: Option<f32>,
/// Where the laid-out text's origin sits on screen, after the multi-line scroll.
pub origin: Pos2,
}
/// The rows of a laid-out text as AccessKit lines, with the byte where each starts in the text.
@@ -588,6 +590,8 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
muted_hint: input.options.look == crate::style::FieldLook::Quiet,
mono: input.options.mono,
role: input.options.role,
size: input.options.size,
top: input.options.top,
ink: input.ink,
filter,
char_limit: input.options.limit,
@@ -675,7 +679,7 @@ pub(crate) fn run(state: &mut TextState, mut input: AdapterIn<'_>) -> AdapterOut
let full = display;
let layout = TextLayout::new(shown.galley, false, full);
let baseline = (!layout.full().is_empty()).then_some(shown.galley_pos.y + layout.first_baseline);
AdapterOut { layout, focused: shown.focused, tab, clicked: shown.clicked, baseline }
AdapterOut { layout, focused: shown.focused, tab, clicked: shown.clicked, baseline, origin: shown.galley_pos }
}
/// What [`show_selectable`] shows: the read-only text of a selection part.
@@ -727,6 +731,8 @@ pub(crate) fn show_selectable(ui: &mut Ui, text: Selectable<'_>) {
muted_hint: false,
mono: false,
role: run.role,
size: None,
top: false,
ink,
filter: egui_focus::event_filter(keep, false),
char_limit: None,
@@ -80,6 +80,13 @@ pub struct TextOptions {
pub mono: bool,
/// The type role the text is set in; a monospace text takes the mono role's face and size instead.
pub role: TypeRole,
/// The text size in points in place of the role's, for text whose size is the user's to choose (a document
/// editor's text size); the face stays the role's. `None` takes the role's size. The component sizes the part for
/// it, since a role's line height no longer measures the text: a single-line part centres that row on the part
/// rather than on the role's baseline, which a row taller than the role's would leave.
pub size: Option<f32>,
/// A multi-line text starts at the top of its part; unset, it is centred on the part's height, as a single line is.
pub top: bool,
/// The text colour; `None` takes the surface's ink. A disabled part shows the disabled text colour whatever this is.
pub ink: Option<Ink>,
/// What Tab does in this field.
@@ -174,6 +181,8 @@ impl Default for TextOptions {
keep_on_escape: false,
mono: false,
role: TypeRole::Body,
size: None,
top: false,
ink: None,
tab: TabKey::default(),
caret: None,
@@ -28,6 +28,10 @@ pub(crate) struct Edit<'a> {
pub muted_hint: bool,
pub mono: bool,
pub role: TypeRole,
/// The text size in points in place of the role's (`TextOptions::size`).
pub size: Option<f32>,
/// A multi-line text starts at the top of the rect (`TextOptions::top`).
pub top: bool,
pub ink: Color32,
pub filter: EventFilter,
pub char_limit: Option<usize>,
@@ -46,7 +50,8 @@ pub(crate) struct Edit<'a> {
/// is not clipped to `rect`.
pub galley: Option<std::sync::Arc<egui::Galley>>,
/// The screen y of the baseline a single line without a laid-out galley sits on: its control's line's, which a
/// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line.
/// text in another face (mono digits) shares. `None` centres the line's row on the rect's centre line, and a text
/// whose size is the caller's own is centred there whatever this says.
pub baseline: Option<f32>,
/// How far a multi-line text taller than `rect` is scrolled up inside it, in points; the text part owns the offset
/// (`text_adapter`), and a single line or a laid-out galley ignores it.
@@ -92,6 +97,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
muted_hint,
mono,
role,
size,
top,
ink,
filter,
char_limit,
@@ -112,8 +119,12 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
// Behind selected text and the selected text itself: the field's roles.
let selection = (tokens.color.accent.soft, tokens.color.text.normal);
let facts = crate::fonts::stack_facts(ui.ctx());
let font_id = tokens.font(facts, role, mono);
let optical_size = tokens.optical_size(facts, role, mono);
let mut font_id = tokens.font(facts, role, mono);
// A size of the caller's own keeps the role's face; the optical size follows the size the text is set at.
let optical_size = tokens.optical_size(facts, role, mono).map(|role_size| size.unwrap_or(role_size));
if let Some(size) = size {
font_id.size = size;
}
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.
@@ -164,7 +175,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
let hint_text = hint.map(|hint| egui::RichText::new(hint).font(FontId::proportional(font_id.size)));
// A single-line edit runs in a rect one text row tall, or the part's height when that is taller, placed so the
// text's baseline is `baseline`, else centred on the part's centre line. egui centres the row in the rect, whatever
// row it allocates from the rect's top.
// row it allocates from the rect's top. A text whose size is the caller's own is centred on the part too: its row is
// taller than the role's, so the role's baseline would lift the row and its clip out of the top of the part.
let rect = if multiline || galley.is_some() {
rect
} else {
@@ -179,7 +191,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
};
let row = probe.size().y;
let first_baseline = probe.rows.first().and_then(|placed| placed.row.glyphs.first().map(|glyph| placed.pos.y + glyph.pos.y));
let centre = match baseline.zip(first_baseline) {
// The row sits on the control's baseline, which every text of the line shares. A size of the caller's own sets
// a row taller than the role's that this baseline would carry out of the part's top, so that row is centred on
// the part's centre line instead, where the role's own row sits.
let centre = match baseline.zip(first_baseline).filter(|_| size.is_none()) {
Some((baseline, first)) => baseline - first + row / 2.0,
None => rect.center().y,
};
@@ -229,7 +244,8 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
.event_filter(filter)
.return_key(if multiline { Some(egui::KeyboardShortcut::new(line_break, egui::Key::Enter)) } else { None })
.layouter(&mut layouter)
// A laid-out galley sits at the rect's corner, as a painted run does.
// A laid-out galley sits at the rect's corner, as a painted run does; the lines of a multi-line text
// start at the top of its part when the part asks (`top`), whatever room is left below them.
.align(match (centred, rtl) {
_ if galley.is_some() => egui::Align2::LEFT_TOP,
(centred, rtl) => {
@@ -238,8 +254,10 @@ pub(crate) fn show(ui: &mut Ui, env: &crate::runtime::env::Env, edit: Edit<'_>)
(false, true) => egui::Align::Min,
(false, false) => egui::Align::Max,
};
// A multi-line text starts at the part's top, however many of its lines the text fills.
egui::Align2([across, if multiline { egui::Align::Min } else { egui::Align::Center }])
// A multi-line text starts at the part's top when the part asks (`top`), however many of its
// lines the text fills.
let down = if multiline && top { egui::Align::Min } else { egui::Align::Center };
egui::Align2([across, down])
}
});
if let Some(hint) = hint_text.clone() {
+1
View File
@@ -3,3 +3,4 @@ pub(crate) mod editor;
pub(crate) mod input_cap;
pub(crate) mod memo;
pub(crate) mod resting;
pub(crate) mod sized;
+126
View File
@@ -0,0 +1,126 @@
//! A single-line text part set at a size of the caller's own: its row is taller than the role's and still lies in the
//! part, on the part's centre line where the role's own row sits.
use craft_behavior::{PartKey, PlainText, Sense};
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _,
};
use craft_ui::primitives::{TextKey, TextOptions};
use craft_ui::style::StyleCx;
use craft_ui::testing::{Fixture, trial};
use craft_ui_test_kit::contract::PlainStyle;
use egui::{Rect, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
const TEXT: PartKey = PartKey::new("text");
/// A size of the caller's own, well above the body role's: its row is much taller than the role's.
const LARGE: f32 = 40.0;
/// A part far taller than the text it shows, to read off the row the text takes.
const ROOMY: f32 = 200.0;
/// Half a point: rects compared across passes may round apart by that much.
const SNAP: f32 = 0.5;
/// What the trial's paint read of the text part: the part's rect.
#[derive(Clone, Copy, Debug, Default)]
struct Painted {
part: Option<Rect>,
}
/// A single-line text part showing a value at a size the caller sets.
#[derive(Component)]
struct Sized<'a> {
#[common]
common: Common,
value: Bind<'a, String>,
size: Option<f32>,
height: f32,
painted: &'a RefCell<Painted>,
}
impl Component for Sized<'_> {
const ROLE: Role = Role::TEXT_INPUT;
const INPUT: Input = Input::Text;
const OVERLAYS: bool = false;
type Style = PlainStyle;
type Output = EditResponse<String>;
fn style(_: &StyleCx<'_>, _: SizedStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
}
/// The part's room: a component sizes the part for a text of the caller's own size, as tall as its row.
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::new(240.0, self.height)
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let options = TextOptions { size: self.size, ..TextOptions::default() };
let (shown, rect) = (cx.value().cloned().unwrap_or_default(), cx.content_rect);
cx.text(TextKey::<String>::new(TEXT), rect, &PlainText, &shown, &options);
}
fn bind(&mut self) -> Option<BindMut<'_, String>> {
Some(self.value.reborrow())
}
fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if let Some(outcome) = cx.text(&TextKey::<String>::new(TEXT)) {
self.painted.borrow_mut().part = Some(outcome.rect);
}
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<String> {
cx.edit_response()
}
}
/// The part "42" is shown in at `size` in a part `height` tall, its painted row, and the clip the row is painted under.
fn sized(size: Option<f32>, height: f32) -> (Fixture, Rect, Rect, Rect) {
let (value, painted) = (Rc::new(RefCell::new(String::from("42"))), Rc::new(RefCell::new(Painted::default())));
let (shown, read) = (value.clone(), painted.clone());
let mut fixture = Fixture::new(move |ui| {
let mut held = shown.borrow_mut();
Sized { common: Common::new(), value: Bind::bound(&mut *held), size, height, painted: &read }.id_salt("sized").show(ui);
});
fixture.settle();
let part = painted.borrow().part.expect("the text part is laid out");
let (row, clip) = {
let painted = fixture.texts().iter().find(|text| text.text == "42").expect("the value is painted");
(painted.rect, painted.clip)
};
(fixture, part, row, clip)
}
/// A size of the caller's own sets a row taller than the role's, and the part a component sizes for it is as tall as
/// that row. The row keeps its place in the part, centred on the part's centre line where the role's own row sits, and
/// the clip that follows it stays inside: a baseline taken from the role would carry the taller row above the part's
/// top. Without a size the role's row keeps its place.
#[trial]
fn a_single_line_part_set_at_its_own_size_keeps_its_row_in_its_part() {
// A part far taller than the text shows what the row it lays out takes, and how much room a measure leaves the part.
let (_, roomy, taken, _) = sized(Some(LARGE), ROOMY);
let row_room = taken.height() + (ROOMY - roomy.height());
let (_sized, part, row, clip) = sized(Some(LARGE), row_room);
let (_role, role_part, role_row, _) = sized(None, ROOMY);
assert!((part.height() - row.height()).abs() <= SNAP, "the part is as tall as the sized row: {part:?} vs {row:?}");
assert!(row.height() > role_row.height() * 1.5, "{LARGE} points sets a taller row than the role's: {row:?} vs {role_row:?}");
assert!(
role_row.top() >= role_part.top() - SNAP && role_row.bottom() <= role_part.bottom() + SNAP,
"the role's row lies in its part: {role_row:?} in {role_part:?}"
);
assert!((role_row.center().y - role_part.center().y).abs() <= SNAP, "the role's row is centred on its part: {role_row:?} in {role_part:?}");
assert!(row.top() >= part.top() - SNAP && row.bottom() <= part.bottom() + SNAP, "the sized row lies in its part: {row:?} in {part:?}");
assert!((row.center().y - part.center().y).abs() <= SNAP, "the sized row is centred on its part: {row:?} in {part:?}");
assert!(
clip.top() >= part.top() - SNAP && clip.bottom() <= part.bottom() + SNAP,
"the sized text is not clipped by a rect beyond the part: {clip:?} in {part:?}"
);
}
@@ -4,7 +4,8 @@ use super::words::PanelWords;
use crate::contract::overlay::{Dismiss, Outside, OverlayFit, ViewportShare};
use crate::contract::{
Bind, BodyCx, CollectionEvent, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing, announce, clicked,
Bind, BodyCx, CollectionEvent, LeastWidth, Overlay, Pattern, Politeness, Props, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
announce, clicked,
};
use crate::display::{Shade, Text};
use crate::layout_components::{Row, Stack};
@@ -124,6 +125,8 @@ impl crate::contract::Outcome for PaletteOutput {
/// out, showing the `placeholder`; it opens to the field with the key focus in the pass that opens it and lists the
/// results in a popup under the field. The in-place field is the palette's face, so it is named by the palette's
/// `label`, closed and open; the dialog face's field, inside a box named `label`, keeps the generic search name.
/// - Width (dialog face): at least `least_width` ([`LeastWidth::Palette`] by default), so the box keeps its width as
/// the query changes its rows; at most 60% of the window's width, where a row wider than the box shortens its label.
/// - Empty query: with `suggested`, its heading and those commands; else the commands last run, newest first (the
/// `recents` binding), else the first entries.
/// - Fallback: with `fallback`, a last row follows the matches of a query, or stands alone when nothing matches. Picking
@@ -167,6 +170,9 @@ pub struct CommandPalette<'a> {
/// The row that hands the query back; its text is the template filled with the query as `{text}`.
#[prop]
fallback: Option<WordTemplate>,
/// The least width of the dialog face's content, from a size role; the box stays within its share of the window.
#[prop]
least_width: LeastWidth,
}
impl<'a> CommandPalette<'a> {
@@ -185,6 +191,7 @@ impl<'a> CommandPalette<'a> {
placeholder: None,
suggested: None,
fallback: None,
least_width: LeastWidth::Palette,
}
}
@@ -204,7 +211,7 @@ impl<'a> CommandPalette<'a> {
}
fn show_dialog(self, ui: &mut Ui) -> PaletteOutput {
let CommandPalette { label, entries, index, open, uses, mut recents, placeholder, suggested, fallback, .. } = self;
let CommandPalette { label, entries, index, open, uses, mut recents, placeholder, suggested, fallback, least_width, .. } = self;
let ctx = ui.ctx().clone();
let env = Env::of(ui);
let words = env.words::<PanelWords>();
@@ -213,8 +220,11 @@ impl<'a> CommandPalette<'a> {
let uses: &dyn Fn(&CommandRef) -> u32 = uses.unwrap_or(&never_used);
let hint: Label = placeholder.unwrap_or_else(|| words.palette_placeholder.clone());
let mut chosen = Chosen::default();
// The box's width is its least width, or its widest row when that is wider, within the share of the window: the
// rows a query lists come and go, and a box as wide as them would jump while the user types.
let shown = Popover::new(label.clone(), open)
.collection_body()
.least_width(least_width)
.overlay(|_| {
let mut overlay = Overlay::modal().dismiss(Dismiss::new().outside(Outside::Close));
overlay.fit = OverlayFit::ContentCapped(SHARE);
@@ -228,8 +238,13 @@ impl<'a> CommandPalette<'a> {
let status = RefCell::new(Status::Quiet);
// The field is the stack's header and the status its footer, so the list takes the room left in
// the capped box and scrolls inside it. The three regions share the stack's memory, which is kept by
// its id across a close, so each opening starts a fresh session in the header, the first region.
// its id across a close, so each opening starts a fresh session in the header, the first region. The
// stack, the field and the list span the box's width, which its least width can make wider than its
// widest row: a content-sized stack left them at that row's width, in the box's start half, and the
// stack's regions lie in the stack's own width, so it asks for the least width the box asks for.
Stack::new()
.fill_width()
.least_width(least_width)
.header(|ui, stack| {
let state = stack.memory::<Session>();
if opening {
@@ -238,6 +253,7 @@ impl<'a> CommandPalette<'a> {
TextField::search(words.palette_search.clone(), Bind::bound(&mut state.query))
.placeholder(hint.clone())
.drives(list_id)
.sizing(Sizing::FillWidth)
.show(ui);
})
.footer(|ui, stack| {
+99 -1
View File
@@ -3,7 +3,7 @@
//! remembers what it ran.
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, CommandSet, Overlay, Role, Show as _, ShowContainer as _, clicked};
use craft_ui::contract::{Bind, CommandSet, LeastWidth, Overlay, Role, Show as _, ShowContainer as _, clicked};
use craft_ui::menu::search::{HelpEntry, SearchIndex, SearchWords, Synonyms};
use craft_ui::patterns::panels::{CommandPalette, PaletteFace};
use craft_ui::popover::Popover;
@@ -48,6 +48,17 @@ struct Rig {
/// A palette open over `entries`, inside a modal dialog when `in_dialog`, with `beneath` shown before it in the same
/// window. `recents` binds the palette's recent commands to the rig when given; else the palette keeps them.
fn rig(entries: Vec<HelpEntry>, recents: Option<Vec<CommandRef>>, in_dialog: bool, beneath: impl Fn(&mut Ui) + 'static) -> Rig {
rig_least(entries, recents, in_dialog, None, beneath)
}
/// [`rig`], with the palette's least width `least` when given.
fn rig_least(
entries: Vec<HelpEntry>,
recents: Option<Vec<CommandRef>>,
in_dialog: bool,
least: Option<LeastWidth>,
beneath: impl Fn(&mut Ui) + 'static,
) -> Rig {
let open = Rc::new(Cell::new(true));
let picked = Rc::new(RefCell::new(None::<CommandRef>));
let refused = Rc::new(RefCell::new(None::<CommandRef>));
@@ -62,6 +73,10 @@ fn rig(entries: Vec<HelpEntry>, recents: Option<Vec<CommandRef>>, in_dialog: boo
let view = env.view();
let index = SearchIndex::new(&view, &entries, &Synonyms::of(&view.words::<SearchWords>()));
let palette = CommandPalette::new("Commands", &entries, &index, Bind::bound(&mut is_open));
let palette = match least {
Some(least) => palette.least_width(least),
None => palette,
};
let output = if bound {
let mut recents = shown_held.borrow().clone();
let output = palette.recents(Bind::bound(&mut recents)).show(ui);
@@ -112,6 +127,19 @@ fn disabled(fixture: &Fixture, label: &str) -> bool {
rows(fixture).into_iter().find(|(name, _)| name.starts_with(label)).unwrap_or_else(|| panic!("no row {label}")).1
}
/// What the dialog face laid out, for a failing assertion: the box's width and those of the rows' list, the field and
/// the rows, so a box wider than everything it holds reads apart from a field left at its measure.
fn laid_out(fixture: &Fixture) -> String {
let wide = |role: Role| fixture.by_role(role).iter().map(|node| format!("{:.1}", node.rect.width())).collect::<Vec<_>>().join(", ");
format!(
"the box {:.1} wide, its rows' list [{}] wide, the field [{}] wide, the rows [{}] wide",
fixture.by_role(Role::DIALOG).first().map_or(0.0, |node| node.rect.width()),
wide(Role::LIST_BOX),
wide(Role::TEXT_INPUT),
wide(Role::LIST_BOX_OPTION)
)
}
#[trial]
fn a_picked_command_runs_from_the_palette_and_comes_first_when_it_opens_again() {
let entries = vec![
@@ -529,3 +557,73 @@ fn enter_on_a_disabled_first_match_runs_nothing() {
assert!(open.get(), "the palette stays open");
assert!(take_output(fixture.ctx()).fired.is_empty(), "nothing ran");
}
/// The dialog face is a steady, readable width: over short labels it opens at least the palette's least width, typing a
/// query that drops the widest rows leaves its width as it was, and in a narrow window it keeps to its share of it,
/// where a least width wider than that share gives way to it. The search field and the rows span the box's inner
/// width at either width. Guards against a box as wide as its widest row, which opened narrow and jumped as the results
/// changed, and against a field and rows left at the widest row's width, in the start half of the wider box.
#[trial]
fn the_dialog_face_keeps_a_readable_width_while_the_query_changes_its_rows() {
let entries = || vec![entry("cut", "Cut"), entry("copy", "Copy"), entry("paste", "Paste"), entry("pasteInside", "Paste Inside")];
// A rig whose palette has the least width `role` (the default when `None`), and that width in its tokens.
let rigged = |role: Option<LeastWidth>| {
let least = Rc::new(Cell::new(0.0_f32));
let read = least.clone();
let points = move |ui: &mut Ui| {
read.set(role.unwrap_or(LeastWidth::Palette).points(craft_ui::runtime::env::Env::of(ui).tokens.tokens()));
};
(rig_least(entries(), None, false, role, points), least)
};
let (mut rig, least) = rigged(None);
let width = |fixture: &Fixture| fixture.by_role(Role::DIALOG).first().expect("the palette's box shows").rect.width();
// The field and every row run from the box's start, less its padding, to its end, less the same padding.
let spans = |fixture: &Fixture, when: &str| {
let frame = fixture.by_role(Role::DIALOG).first().expect("the palette's box shows").rect;
let field = fixture.by_role(Role::TEXT_INPUT).first().expect("the search field shows").rect;
let pad = field.left() - frame.left();
assert!(pad >= 0.0 && pad < frame.width() / 10.0, "{when}: the field starts inside the box's padding: {field:?} in {frame:?}");
assert!(
(frame.right() - field.right() - pad).abs() <= 1.0,
"{when}: the field spans the box's inner width: {field:?} in {frame:?}; {}",
laid_out(fixture)
);
let listed = fixture.by_role(Role::LIST_BOX_OPTION);
assert!(!listed.is_empty(), "{when}: the box lists rows");
for row in listed {
let row = row.rect;
assert!(
(row.left() - field.left()).abs() <= 1.0 && (row.right() - field.right()).abs() <= 1.0,
"{when}: a row spans the box's inner width, as the field does: {row:?} under {field:?} in {frame:?}; {}",
laid_out(fixture)
);
}
};
rig.fixture.room(Vec2::new(1400.0, 900.0)).settle();
let opened = width(&rig.fixture);
assert!(opened >= least.get(), "short labels open the box at its least width: {opened} against {}", least.get());
spans(&rig.fixture, "opened");
rig.fixture.type_text("cut").settle();
assert_eq!(names(&rig.fixture).len(), 1, "the query lists one short row: {:?}", names(&rig.fixture));
let typed = width(&rig.fixture);
assert!((typed - opened).abs() <= 0.5, "the box keeps its width as the rows change: {typed} against {opened}");
spans(&rig.fixture, "typed");
// The box's share is of the window, and a fixture's window is never narrower than 800 points, whatever the room
// (`Frames::screen`): the share is read from the window the layer shows in, not from the room.
let narrow = Vec2::new(400.0, 900.0);
rig.fixture.room(narrow).settle();
let window = rig.fixture.ctx().content_rect().width();
let kept = width(&rig.fixture);
assert!(kept <= window * 0.6 + 0.5, "a narrow window keeps the box to its share: {kept} in {window}");
// That share is wider than the palette's least width, which the box keeps there; a least width wider than the
// share gives way to it.
let (mut wide, least) = rigged(Some(LeastWidth::WideDialog));
wide.fixture.room(narrow).settle();
let window = wide.fixture.ctx().content_rect().width();
assert!(least.get() > window * 0.6, "the wide least width {} is wider than the share of {window}", least.get());
let kept = width(&wide.fixture);
assert!(kept <= window * 0.6 + 0.5, "a least width wider than the share gives way to it: {kept} in {window}");
}
+1 -1
View File
@@ -9,4 +9,4 @@ mod words;
pub use field::{Field, FieldRowStyle, Help};
pub use group::{FieldGroup, FieldGroupStyle};
pub use slider_field::{SliderField, SliderFieldLayout, SliderFieldOutput, SliderFieldStyle};
pub use slider_field::{FieldDecimals, SliderField, SliderFieldLayout, SliderFieldOutput, SliderFieldStyle};
+41 -5
View File
@@ -33,6 +33,22 @@ pub enum SliderFieldLayout {
Inline,
}
/// The decimals a slider field's number field shows.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldDecimals {
/// The number field's own look: its unit kind's decimals, or `typed_decimals` at most; a percent shows the decimals
/// its step needs in full, at most one ("67" with a step of 1, "66.7" with a step of 0.1 or finer).
#[default]
Look,
/// Exactly the decimals the step needs, zeros included, a percent too: "66.70" over 66.7 with a step of 0.01, where
/// the percent look shows "66.7"; "0.50" over a plain 0.5 with a step of 0.01.
Step,
/// Exactly this many decimals (at most 12), zeros included, a percent too: the decimals a value declares, such as
/// a colour channel's.
Fixed(usize),
}
/// The style of a slider field: the gap between its parts, the line height and the stacked number field's width.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
@@ -52,11 +68,13 @@ pub struct SliderFieldStyle {
///
/// The step moves the slider's keys and wheel and the field's keys, wheel and scrub; typed values snap to it unless
/// `typed_decimals` sets their independent precision. Without a step the field steps by a hundredth on a range 10 wide
/// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. The field and
/// the slider are Tab stops in the order they are read: the field and then the slider when stacked, the slider and then
/// the field when inline. A click on the row's label focuses the number field in either layout. A log or power scale
/// curves the
/// slider's track only: the field, typing and steps stay linear.
/// or less and by 1 on a longer one, and by default rounds typed values to the places that step needs. The field shows
/// its own look's decimals (for a percent, its step's up to one) unless `field_decimals` asks for the step's or a fixed
/// count, which leaves typing's snap to the step as it was; a scrub keeps the step's decimals either way, so a field
/// showing whole numbers over a hundredth step still moves by hundredths. The field and the slider are Tab stops in the
/// order they are read: the field and then the slider when stacked, the slider and then the field when inline. A click
/// on the row's label focuses the number field in either layout. A log or power scale curves the slider's track only:
/// the field, typing and steps stay linear.
#[derive(crate::contract::Component, crate::contract::Props)]
pub struct SliderField<'a> {
#[common]
@@ -76,6 +94,11 @@ pub struct SliderField<'a> {
/// The decimal places retained and shown for typed values (at most 12), independently of the step; typing no longer snaps to it.
#[prop]
typed_decimals: Option<usize>,
/// The decimals the number field shows: its own look (the default), exactly the step's, or exactly a fixed count,
/// a percent included ("66.70" with a step of 0.01, not the percent look's "66.7"). Typed values snap to the step as
/// they do without it.
#[prop]
field_decimals: FieldDecimals,
/// The change of one wheel notch over the slider where it is coarser than the step.
#[prop(quantity = "step")]
wheel_step: Option<f64>,
@@ -159,6 +182,7 @@ impl<'a> SliderField<'a> {
scale: SliderScale::Linear,
step: None,
typed_decimals: None,
field_decimals: FieldDecimals::Look,
wheel_step: None,
track_press: TrackPress::OnRelease,
unit_kind: None,
@@ -198,6 +222,7 @@ impl<'a> SliderField<'a> {
scale: self.scale,
step: self.step,
typed_decimals: self.typed_decimals,
field_decimals: self.field_decimals,
wheel_step: self.wheel_step,
unit_kind: self.unit_kind,
unit: self.unit.clone(),
@@ -228,6 +253,7 @@ struct Look {
scale: SliderScale,
step: Option<f64>,
typed_decimals: Option<usize>,
field_decimals: FieldDecimals,
wheel_step: Option<f64>,
unit_kind: Option<UnitKind>,
unit: Option<Label>,
@@ -315,6 +341,16 @@ impl Look {
Some(decimals) => field.max_decimals(decimals),
None => field,
};
// Fixed decimals win over the most decimals and over the percent look.
let shown = match self.field_decimals {
FieldDecimals::Look => None,
FieldDecimals::Step => Some(decimals_for_step(step)),
FieldDecimals::Fixed(decimals) => Some(decimals),
};
let field = match shown {
Some(decimals) => field.fixed_decimals(decimals.min(12)),
None => field,
};
let field = if self.select_on_focus { field.select_on_focus() } else { field };
let field = match self.unit_kind {
Some(kind) => field.unit_kind(kind),
+2 -1
View File
@@ -175,7 +175,8 @@ impl Component for AltTextField<'_> {
let check_at = Rect::from_min_size(pos2(content.min.x, area.max.y + inset + cx.gap()), vec2(content.width(), check.y));
let value = shown_of(cx.value());
let placeholder = if value.text.same().is_some() { words.alt_text.clone() } else { words.mixed.clone() };
let options = TextOptions { lines: Some(LINES), placeholder: Some(placeholder), enabled: !value.all_decorative(), ..TextOptions::default() };
let options =
TextOptions { lines: Some(LINES), placeholder: Some(placeholder), enabled: !value.all_decorative(), top: true, ..TextOptions::default() };
cx.text(text_part::<AltText>(), area, &AltCodec, &value, &options);
let mut flags = Flags::empty();
flags.set(Flags::CHECKED, value.all_decorative());
+3 -2
View File
@@ -133,8 +133,9 @@ pub type HexField<'a> = TextField<'a, HexCodec>;
const NOT_HEX: Word = Word::keyed("hexField.unparsed", "Not a hex color");
impl<'a> TextField<'a, HexCodec> {
/// A hex field named `label` that shows and edits `value` as monospace digits. A draft that is no colour says so
/// ("Not a hex color", `TextField::unparsed`). Its row names the digits with [`hash_label`](Self::hash_label).
/// A hex field named `label` that shows and edits `value` as monospace digits; sized `Sizing::Content`, it is as wide
/// as its digits in that face. A draft that is no colour says so ("Not a hex color", `TextField::unparsed`). Its row
/// names the digits with [`hash_label`](Self::hash_label).
pub fn hex(label: impl Into<Label>, value: Bind<'a, Rgba>) -> Self {
let mut field = TextField::with_codec(label, value, HexCodec::default()).mono().unparsed(NOT_HEX);
field.empty = Some(Rgba::rgb(0, 0, 0));
+7 -1
View File
@@ -106,7 +106,13 @@ impl FieldStyle {
/// The width of a field that holds `chars` characters: `chars` times the width of a `0` in the body face (CSS's
/// `ch`), plus the field's padding on both sides. [`held_at`](Self::held_at) takes it as the field's length.
pub fn chars_width(cx: &StyleCx<'_>, chars: u16) -> f32 {
let digit = cx.text_width(crate::style::TypeRole::Body, "0");
Self::chars_width_in(cx, crate::style::TypeRole::Body, chars)
}
/// [`chars_width`](Self::chars_width) with the `0` set in the face of `role`: `TypeRole::Mono` for a field that
/// draws its text in the monospace face.
pub(crate) fn chars_width_in(cx: &StyleCx<'_>, role: crate::style::TypeRole, chars: u16) -> f32 {
let digit = cx.text_width(role, "0");
let digit = if digit.is_finite() && digit > 0.0 { digit } else { 0.0 };
f32::from(chars) * digit + 2.0 * cx.control().pad_x
}
+10 -6
View File
@@ -857,13 +857,17 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
let rule = self.rule();
let step = self.scrub_step.filter(|step| step.is_finite() && *step > 0.0).unwrap_or(rule.step);
let drag = ValueDrag::relative(step, rule.bounds()).warp(true).hide_cursor(true).coarse(LARGE_STEPS).fine(1.0 / LARGE_STEPS);
// Rounded to the field's decimals, so a scrubbed value carries no float noise. The step is not a grid
// here: an Alt drag moves by a share of it.
let decimals = self.decimals();
// Rounded to the field's decimals, and to the step's where the step needs more, so a scrubbed value carries no
// float noise and keeps the step's precision even where the field shows fewer decimals: a field of hundredths
// that shows no decimals still moves by a hundredth, not by nothing. The step is not a grid here: an Alt drag
// moves by a share of it.
let decimals = self.decimals().max(decimals_for_step(step));
let scale = self.scale;
let mut scrub =
Scrub::new(drag, move |value: &V| value.number().unwrap_or(0.0) * scale, move |number| V::of_number(round_to(number, decimals) / scale))
.on_field();
// The rounded value is kept in the range after the rounding: a drag that runs into a range end finer than the
// decimals it rounds to carries the value past it (0.005 to 0.01), and the range holds the write at its end,
// as a typed value does.
let kept = move |number: f64| V::of_number(rule.settle(round_to(number, decimals)) / scale);
let mut scrub = Scrub::new(drag, move |value: &V| value.number().unwrap_or(0.0) * scale, kept).on_field();
if self.scrub {
scrub = scrub.by_label();
}
+27 -10
View File
@@ -11,7 +11,7 @@ use crate::contract::{
};
use crate::primitives::{Completer, IconSpec, SubmitKey, TabKey, TextOptions, TextRun, Wrap};
use crate::runtime::env::{Label, Message};
use crate::style::{FieldLook, Span};
use crate::style::{FieldLook, Span, TypeRole};
use craft_behavior::{Codec, EditEvent, IconId, Mixed, PartKey, PlainText, Proposal, Sense};
use egui::{Id, Rect, Vec2};
use smallvec::SmallVec;
@@ -93,6 +93,10 @@ pub struct TextField<'a, C: Codec + Clone + 'static = PlainText> {
/// length (`size.length.field`).
#[style_key]
width_chars: Option<u16>,
/// The type role whose face the text is drawn in, which `width_chars` counts characters in: the field's role, or
/// `TypeRole::Mono` for a monospace field (`TextField::mono`).
#[style_key]
face: TypeRole,
}
impl<'a> TextField<'a, PlainText> {
@@ -126,11 +130,13 @@ impl<'a> TextField<'a, PlainText> {
impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
/// A field named `label` that shows `value` through `codec`.
pub fn with_codec(label: impl Into<Label>, value: Bind<'a, C::Value>, codec: C) -> Self {
let options = TextOptions::default();
TextField {
common: Common::new(),
value,
codec,
options: TextOptions::default(),
face: options.role,
options,
limit: Limit::Default,
empty: None,
search: false,
@@ -202,10 +208,12 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// Monospace text.
/// Monospace text. The field measures its text, and counts [`width_chars`](Self::width_chars), in the
/// monospace face it draws.
#[must_use]
pub fn mono(mut self) -> Self {
self.options.mono = true;
self.face = TypeRole::Mono;
self
}
@@ -232,7 +240,8 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
}
/// The field asks for the width of `chars` characters instead of the field length (`size.length.field`): `chars`
/// times the width of a `0` in the field's body face, as CSS's `ch` unit, plus the field's padding. The width
/// times the width of a `0` in the face the field draws (the body face, or the monospace face of a
/// [`mono`](Self::mono) field), as CSS's `ch` unit, plus the field's padding. The width
/// follows the text size and the face, as the field length does. It is the width the field asks for, not a fixed
/// one: a row that lacks room still narrows it, and a field sized `Sizing::Content` or `Sizing::FillWidth` takes
/// its own width as before. `0` keeps the field length.
@@ -359,7 +368,7 @@ impl<C: Codec + Clone + 'static> TextField<'_, C> {
}
impl<C: Codec + Clone + 'static> TextField<'_, C> {
/// `text` as the editor sets it.
/// `text` as the field draws it: in its role, in the monospace face for a [`mono`](Self::mono) field.
fn run<'t>(&self, text: impl Into<Cow<'t, str>>) -> TextRun<'t> {
if self.options.mono { TextRun::spans(vec![Span::new(text).mono()]) } else { TextRun::new(text).role(self.options.role) }
}
@@ -380,7 +389,7 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
fn style(cx: &crate::style::StyleCx<'_>, key: TextFieldStyleKey<C>) -> FieldStyle {
let mut style = FieldStyle::at(cx);
if let Some(chars) = key.width_chars {
style = style.held_at(FieldStyle::chars_width(cx, chars));
style = style.held_at(FieldStyle::chars_width_in(cx, key.face, chars));
}
style.metrics = style.metrics.min_size(Vec2::new(0.0, style.metrics.min_size.y));
if key.look == FieldLook::Quiet {
@@ -394,14 +403,20 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
}
/// The text, and the room the adornments take; a search field keeps the room of its clear button while the text is
/// empty, so the field does not change width as the button comes and goes.
/// empty, so the field does not change width as the button comes and goes. The codec's sample is measured in the
/// face the text is drawn in (the monospace face of a [`mono`](Self::mono) field), so a content-sized field shows
/// all of it; the placeholder, which the editor draws in the proportional face, is measured in the field's role.
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let sample: Cow<'_, str> = match cx.value() {
Some(value) => self.codec.sample(value),
None => Cow::Borrowed(""),
};
let text = if sample.is_empty() { self.options.placeholder.as_ref().map_or("", Label::as_str) } else { sample.as_ref() };
let mut size = cx.field_text(&TextRun::new(text).role(self.options.role));
let run = if sample.is_empty() {
TextRun::new(self.options.placeholder.as_ref().map_or("", Label::as_str)).role(self.options.role)
} else {
self.run(sample.as_ref())
};
let mut size = cx.field_text(&run);
// A multi-line field takes the height of its lines, and grows past them with longer text, as the editor does, up
// to `max_lines`; past that its text scrolls inside it (the text part is its scroll owner). The rows are the
// field's own text wrapped as the editor wraps it, not the codec's width sample, which a plain field leaves
@@ -468,7 +483,9 @@ impl<C: Codec + Clone + 'static> Component for TextField<'_, C> {
Some(Mixed::Same(at)) => Some(at),
_ => None,
});
let options = TextOptions { mixed: value.is_none(), limit, caret, look: self.look, ..self.options.clone() };
// A multi-line field's text starts at the top of its box, below the inset its first line keeps.
let options =
TextOptions { mixed: value.is_none(), limit, caret, top: self.options.multiline(), look: self.look, ..self.options.clone() };
cx.text(text_part::<C::Value>(), placed.text, &self.codec, start, &options);
}
}
@@ -5,13 +5,14 @@
use craft_behavior::keyed;
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
use craft_ui::contract::{Bind, LeastWidth, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Sizing};
use craft_ui::display::{Divider, Text};
use craft_ui::layout_components::{Row, Stack};
use craft_ui::list::{List, ListRow};
use craft_ui::popover::Popover;
use craft_ui::table::{MetadataGroup, MetadataRow, MetadataTable};
use craft_ui::testing::{Frames, last_pass_measuring_runs, measuring_runs, trial};
use craft_ui::text::TextField;
use egui::{Rect, Ui};
use std::cell::Cell;
@@ -105,6 +106,49 @@ fn a_content_column_in_a_popover_holds_its_fill_children() {
assert!(hug.button < hug.column, "a button keeps its own width");
}
/// A box the overlay places at its least width lays the column in it out across that width: a search field in the
/// column's header and the list under it span the box's inner width, as they do in a column given its width, and the
/// box keeps its least width rather than its content's.
#[trial]
fn a_box_placed_at_a_least_width_lays_its_column_out_across_it() {
const SEARCH: &str = "Search";
let (frame, column, field, list) = (Cell::new(Rect::NOTHING), Cell::new(0.0), Cell::new(Rect::NOTHING), Cell::new(Rect::NOTHING));
let least = Cell::new(0.0);
let mut query = String::new();
Frames::new().idle(4, |ui| {
least.set(LeastWidth::Palette.points(craft_ui::runtime::env::Env::of(ui).tokens.tokens()));
let shown = Popover::new("Box", Bind::given(true)).least_width(LeastWidth::Palette).show(ui, |ui, _| {
let keys = [0_usize, 1];
let source = keyed(&keys, |key: &usize| *key);
let column_shown = Stack::new()
.fill_width()
.least_width(LeastWidth::Palette)
.id_salt("column")
.header(|ui, _| {
let text = TextField::search(SEARCH, Bind::bound(&mut query)).id_salt("search").sizing(Sizing::FillWidth);
field.set(text.show(ui).response.rect);
})
.show(ui, |ui, _| {
let rows = List::new("Rows").sizing(Sizing::FillWidth).natural_height(true);
list.set(rows.show_items(ui, &source, &mut |key, _| ListRow::new(ROWS[*key])).response.rect);
});
column.set(column_shown.output.rect.width());
});
frame.set(shown.output.response.rect);
});
let (frame, column, field, list) = (frame.get(), column.get(), field.get(), list.get());
assert!(frame.is_positive() && field.is_positive() && list.is_positive(), "the box shows its field and rows: {frame:?} {field:?} {list:?}");
let pad = field.left() - frame.left();
assert!(pad > 0.0 && pad < frame.width() / 10.0, "the field starts inside the box's padding: {field:?} in {frame:?}");
assert!((frame.width() - least.get() - 2.0 * pad).abs() <= SNAP, "the box keeps its least width: {} against {}", frame.width(), least.get());
assert!((field.right() - frame.right() + pad).abs() <= SNAP, "the field spans the box's inner width: {field:?} in {frame:?}");
assert!(
(list.left() - field.left()).abs() <= SNAP && (list.right() - field.right()).abs() <= SNAP,
"the rows span it too: {list:?} under {field:?}"
);
assert!((column - field.width()).abs() <= SNAP, "the column is as wide as the field in it: {column} against {}", field.width());
}
/// Passing the width on runs no measuring run of its own: a content column in a given column measures as often as a
/// fill-width one, and a settled frame measures nothing.
#[trial]
+35 -1
View File
@@ -3,8 +3,9 @@
use craft_theme::Rgba;
use craft_ui::contract::tooltip::DELAY;
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Sizing};
use craft_ui::form::Field;
use craft_ui::layout_components::Row;
use craft_ui::testing::pointer::moved;
use craft_ui::testing::{Fixture, trial};
use craft_ui::text::HexField;
@@ -111,3 +112,36 @@ fn a_pasted_colour_replaces_the_digits_with_or_without_its_hash() {
assert_eq!(text(&fixture), "FF880012", "a paste that is no colour is inserted at the caret");
assert_eq!(*value.borrow(), start, "and the colour stays");
}
/// A content-sized hex field is as wide as its digits in the monospace face it draws them in, not in the body face:
/// all six digits of #336699 and the caret past the last of them lie inside the field's text rect, and none is cut off.
#[trial]
fn a_content_sized_hex_field_shows_all_six_digits() {
let mut fixture = Fixture::new(|ui| {
Row::new().show(ui, |ui, _| {
HexField::hex("Hex", Bind::given(Rgba::rgb(0x33, 0x66, 0x99))).sizing(Sizing::Content).show(ui);
});
});
fixture.settle();
let digits = fixture.texts().iter().find(|run| run.text == "336699").cloned().unwrap_or_else(|| panic!("the field shows its digits"));
// The run's clip is egui's own: its editor clips the text to the laid-out text one point outset (the room of a
// two-point caret centred on the text's end), cut to the field's text part. So the clip shows that no digit is
// cut, but its end edge follows the text, not the field, and cannot prove the field's width.
let clip = digits.clip;
assert!(
digits.rect.min.x >= clip.min.x && digits.rect.max.x <= clip.max.x,
"the digits {:?} are not cut by the clip they are painted under {clip:?}",
digits.rect
);
// The field's box proves it: its text part is the box less the field's padding, the same on both sides, and the
// digits start at the part's start edge. The field measures the whole caret width past the last digit
// (`MeasureCx::field_text`), at least the half of it egui paints past the text's end.
let field = fixture.by_label("Hex").unwrap_or_else(|| panic!("the hex field")).rect;
let text_end = field.max.x - (digits.rect.min.x - field.min.x);
let caret = fixture.ctx().global_style().visuals.text_cursor.stroke.width;
assert!(
digits.rect.max.x + caret <= text_end + 0.01,
"the digits {:?} and the caret past them lie inside the field's text part, which ends at {text_end} in the field {field:?}",
digits.rect
);
}
+1
View File
@@ -16,6 +16,7 @@ pub(crate) mod number_look;
pub(crate) mod number_scrub_step;
pub(crate) mod number_select;
pub(crate) mod number_width;
pub(crate) mod part_layout;
pub(crate) mod rtl_paragraph;
pub(crate) mod selectable;
pub(crate) mod step_arrows;
+84
View File
@@ -776,6 +776,90 @@ fn a_percent_field_reads_one_decimal_then_the_sign() {
assert!(sign.min.x - number.max.x <= 5.0, "the sign follows the number closely: {number:?} {sign:?}");
}
/// The number a slider field paints, and the field's and slider's targets.
fn slider_number(fixture: &craft_ui::testing::Fixture) -> (String, craft_ui::testing::Target, craft_ui::testing::Target) {
use craft_ui::runtime::access::Role;
let field = fixture.by_role(Role::SPIN_BUTTON).into_iter().next().unwrap_or_else(|| panic!("the slider field shows its number field"));
let slider = fixture.by_role(Role::SLIDER).into_iter().next().unwrap_or_else(|| panic!("the slider field shows its slider"));
let texts = fixture.texts();
let number = texts.iter().find(|run| field.rect.contains(run.rect.center()) && run.text.starts_with(|c: char| c.is_ascii_digit()));
let number = number.unwrap_or_else(|| panic!("the field shows its value: {:?}", texts.iter().map(|r| r.text.to_string()).collect::<Vec<_>>()));
(number.text.to_string(), field, slider)
}
/// A slider field over a percent shows its percent look by default, at most one decimal: with a step of a hundredth
/// it shows "66.7" over 66.7, and with `field_decimals(FieldDecimals::Step)` the two decimals its step needs, "66.70".
/// With a step of 1 it shows "67", and a drag and a typed value land on whole steps.
#[trial]
fn a_slider_fields_step_decimals_win_over_the_percent_look_and_keep_the_snap() {
use craft_ui::form::{FieldDecimals, SliderField};
use craft_ui::testing::Fixture;
use std::rc::Rc;
let shown = |step: f64, decimals: FieldDecimals| {
let value = Rc::new(Cell::new(66.7_f64));
let held = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
let mut now = held.get();
SliderField::new("Saturation", Bind::bound(&mut now), 0.0..=100.0)
.step(step)
.unit_kind(UnitKind::Percent)
.field_decimals(decimals)
.show(ui);
held.set(now);
});
fixture.settle();
(fixture, value)
};
// The percent look shows the decimals the field commits, up to one: a step of 1 commits none, so the look alone
// already reads "67" there. A step of a hundredth commits two, past the look's one: that is where the step's
// decimals have to win over the look.
let (look, _) = shown(0.01, FieldDecimals::Look);
assert_eq!(slider_number(&look).0, "66.7", "by default a percent keeps the look's one decimal");
let (fine, _) = shown(0.01, FieldDecimals::Step);
assert_eq!(slider_number(&fine).0, "66.70", "the step's two decimals win over the percent look");
let (mut fixture, value) = shown(1.0, FieldDecimals::Step);
let (number, field, slider) = slider_number(&fixture);
assert_eq!(number, "67", "a step of 1 shows whole numbers");
fixture.drag_at(slider.rect.left_center() + Vec2::new(slider.rect.width() * 0.3, 0.0), Vec2::new(slider.rect.width() * 0.137, 0.0));
fixture.settle();
let dragged = value.get();
assert!((dragged - 66.7).abs() > 0.5, "the drag moved the value: {dragged}");
assert_eq!(dragged, dragged.round(), "a drag lands on a whole step");
assert_eq!(slider_number(&fixture).0, format!("{dragged}"), "and the field shows it whole");
fixture.click(&field).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("40.4");
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(value.get(), 40.0, "a typed value snaps to the step");
}
/// A slider field whose number field shows fewer decimals than its step needs still scrubs by the step: over a step of
/// a hundredth, with `FieldDecimals::Fixed(0)` the field shows "50" and a 40-point drag on it moves the value by 0.4,
/// not by nothing.
#[trial]
fn a_slider_fields_scrub_keeps_the_steps_decimals_where_the_field_shows_fewer() {
use craft_ui::form::{FieldDecimals, SliderField};
use craft_ui::testing::Fixture;
use std::rc::Rc;
let value = Rc::new(Cell::new(50.0_f64));
let held = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
let mut now = held.get();
SliderField::new("Saturation", Bind::bound(&mut now), 0.0..=100.0).step(0.01).field_decimals(FieldDecimals::Fixed(0)).show(ui);
held.set(now);
});
fixture.settle();
let (number, field, _) = slider_number(&fixture);
assert_eq!(number, "50", "the field shows whole numbers over a step of a hundredth");
fixture.drag_at(field.center(), Vec2::new(-40.0, 0.0));
fixture.settle();
let dragged = value.get();
assert!((dragged - 49.6).abs() < 1e-9, "a 40-point drag on the field moves the value by 40 hundredths: {dragged}");
assert_ne!(dragged, dragged.round(), "the value keeps the step's hundredth, not a whole number");
}
/// A percent field whose committed values carry no decimals (`commit_decimals(0)`, a paint bar's Opacity) shows none,
/// "10%"; one that sets no decimals of its own keeps the one-decimal look, "10.0%".
#[trial]
@@ -50,6 +50,34 @@ fn a_separate_scrub_rate_keeps_fine_key_and_wheel_steps() {
assert_eq!(value.get(), Some(80.02), "one wheel notch still adds one hundredth");
}
/// A field of `range`, `step` and `decimals` decimals, shown in its own `Field` so its caption scrubs it.
fn caption_field(start: f64, range: std::ops::RangeInclusive<f64>, step: f64, decimals: usize) -> (Fixture, Rc<Cell<Option<f64>>>) {
let value = Rc::new(Cell::new(Some(start)));
let shown = Rc::clone(&value);
let mut fixture = Fixture::new(move |ui| {
Field::new("Opacity").side(SideLabel::new().scrub(true)).show(ui, |ui, _| {
let mut current = shown.get();
NumberField::new("Opacity", Bind::bound(&mut current)).range(range.clone()).step(step).fixed_decimals(decimals).scrub_by_label().show(ui);
shown.set(current);
});
});
fixture.settle();
(fixture, value)
}
/// A scrub that runs into the end of a range finer than the decimals it rounds to keeps its write in the range: the
/// drag stops at the range's end, 0.005, which the write's decimals (two, from the step) round to 0.01, so the write
/// keeps the range's end after rounding, as a typed value does, rather than sending the value past its range.
#[trial]
fn a_scrub_into_a_range_finer_than_the_precision_keeps_the_range_end() {
let (mut fixture, value) = caption_field(0.0, 0.0..=0.005, 0.01, 0);
let caption = fixture.texts().iter().find(|text| text.text == "Opacity").expect("the visible scrub caption").rect;
fixture.drag_at(caption.center(), vec2(60.0, 0.0)).settle();
let scrubbed = value.get().expect("the field holds a value");
assert!(scrubbed > 0.0, "the drag moved the value to the end of the range: {scrubbed}");
assert!(scrubbed <= 0.005, "a scrub stays in the field's range: {scrubbed}");
}
#[trial]
fn an_omitted_or_invalid_scrub_rate_uses_the_field_step() {
for rate in [None, Some(0.0), Some(-1.0), Some(f64::NAN), Some(f64::INFINITY)] {
@@ -0,0 +1,164 @@
//! A text part's laid-out text for the component that shows it: set at a size of the caller's own, and placed on screen
//! where its rows are drawn, so an editor paints gutters beside them.
use craft_behavior::{Metrics, PartKey, PlainText, Sense};
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, PaintUi, PartsCx, Props as _, Role, Show as _,
};
use craft_ui::primitives::{TextKey, TextOptions};
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers, Pos2, Rect, Vec2};
use std::cell::RefCell;
use std::rc::Rc;
const TEXT: PartKey = PartKey::new("text");
/// Half a point: rects compared across passes may round apart by that much.
const SNAP: f32 = 0.5;
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
struct PlainStyle {
#[style(metrics)]
metrics: Metrics,
}
/// What an editor's paint read of its text part: the part's rect, the layout's origin and each row's screen top and
/// bottom.
#[derive(Clone, Debug, Default)]
struct Painted {
part: Option<Rect>,
origin: Option<Pos2>,
rows: Vec<(f32, f32)>,
}
/// A multi-line text part of a fixed size, whose paint reads the part's outcome as a gutter would.
#[derive(Component)]
struct Editor<'a> {
#[common]
common: Common,
value: Bind<'a, String>,
size: Option<f32>,
top: bool,
painted: &'a RefCell<Painted>,
}
impl Component for Editor<'_> {
const ROLE: Role = Role::TEXT_INPUT;
const INPUT: Input = Input::Text;
const OVERLAYS: bool = false;
type Style = PlainStyle;
// The value is the component's: its output carries the `String` it edits, so the part reads it as `cx.value()`.
type Output = EditResponse<String>;
fn style(_: &StyleCx<'_>, _: EditorStyleKey) -> PlainStyle {
PlainStyle::default()
}
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::new(240.0, 80.0)
}
fn sense(&self) -> Sense {
Sense::CLICK | Sense::FOCUS | Sense::TAKE_FOCUS
}
fn parts(&mut self, _: Rect, cx: &mut PartsCx<'_, Self>) {
let mut options = TextOptions::new();
options.lines = Some(3);
options.size = self.size;
options.top = self.top;
let rect = cx.content_rect;
if let Some(value) = cx.value() {
cx.text(TextKey::new(TEXT), rect, &PlainText, value, &options);
}
}
fn bind(&mut self) -> Option<BindMut<'_, String>> {
Some(self.value.reborrow())
}
fn paint(&mut self, _: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let Some(outcome) = cx.text(&TextKey::<String>::new(TEXT)) else { return };
let Some(layout) = &outcome.layout else { return };
let origin = outcome.origin;
let rows = layout.galley.rows.iter().map(|row| (origin.y + row.min_y(), origin.y + row.max_y())).collect();
*self.painted.borrow_mut() = Painted { part: Some(outcome.rect), origin: Some(origin), rows };
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<String> {
cx.edit_response()
}
}
/// Shows an editor over `text` set at `size` and returns what its paint read after the fixture settles. The text starts at
/// the top of its part as an editor's does.
fn editor(text: &str, size: Option<f32>) -> (Fixture, Rc<RefCell<String>>, Rc<RefCell<Painted>>) {
shown_editor(text, size, true)
}
/// [`editor`], with the text starting at the top of its part or not (`TextOptions::top`).
fn shown_editor(text: &str, size: Option<f32>, top: bool) -> (Fixture, Rc<RefCell<String>>, Rc<RefCell<Painted>>) {
let (value, painted) = (Rc::new(RefCell::new(text.to_owned())), Rc::new(RefCell::new(Painted::default())));
let (shown, read) = (value.clone(), painted.clone());
let mut fixture = Fixture::new(move |ui| {
let mut held = shown.borrow_mut();
Editor { common: Common::new(), value: Bind::bound(&mut *held), size, top, painted: &read }.id_salt("editor").show(ui);
});
fixture.settle();
(fixture, value, painted)
}
/// A size of the caller's own sets the text at that size, not the role's: the rows of a part set at 30 points are
/// taller than those of the same text at its role's size, and still lie in order down the part.
#[trial]
fn a_part_set_at_its_own_size_lays_its_rows_out_at_that_size() {
let row = |painted: &Painted| painted.rows.first().map_or(0.0, |(top, bottom)| bottom - top);
let (_plain, _, at_role) = editor("one\ntwo", None);
let (_large, _, at_size) = editor("one\ntwo", Some(30.0));
let (at_role, at_size) = (at_role.borrow().clone(), at_size.borrow().clone());
assert!(row(&at_role) > 0.0 && at_role.rows.len() == 2, "the role's text lays out two rows: {at_role:?}");
assert!(row(&at_size) > row(&at_role) * 1.5, "30 points sets taller rows than the role's size: {at_size:?} vs {at_role:?}");
assert!(at_size.rows.windows(2).all(|pair| pair[1].0 >= pair[0].1 - SNAP), "the rows lie in order: {at_size:?}");
}
/// A multi-line text shorter than its part starts at the part's top when the part asks for it (`TextOptions::top`): its
/// one row lies in the top half of the part. Without it the text keeps the placement every field had, centred on the
/// part's height.
#[trial]
fn a_short_multi_line_text_starts_at_the_top_of_its_part_when_asked_to() {
let (_fixture, _, painted) = editor("one", None);
let painted = painted.borrow().clone();
let part = painted.part.expect("the part is laid out");
let row = painted.rows.first().copied().expect("the text has a row");
assert!(row.0 >= part.top() - SNAP && row.1 < part.center().y, "the row sits at the top of the part: {painted:?}");
let (_fixture, _, kept) = shown_editor("one", None, false);
let kept = kept.borrow().clone();
let row = kept.rows.first().copied().expect("the text has a row");
assert!(row.0 < part.center().y && row.1 > part.center().y, "without the option the row is centred on the part: {kept:?}");
}
/// The outcome's origin is where the layout is drawn: at rest its rows start inside the part, and once the text is
/// longer than the part and scrolled to the caret at its end, the origin moves up with the text, so the last row is
/// the one in view at the part's bottom.
#[trial]
fn the_origin_follows_the_text_where_it_is_drawn() {
let lines = (1..=12).map(|line| line.to_string()).collect::<Vec<_>>().join("\n");
let (mut fixture, value, painted) = editor(&lines, None);
let rest = painted.borrow().clone();
let part = rest.part.expect("the part is laid out");
let first = rest.rows.first().copied().expect("the text has rows");
assert!(part.expand(SNAP).contains(rest.origin.expect("the layout is placed")), "at rest the layout starts in the part: {rest:?}");
assert!(first.0 >= part.top() - SNAP && first.1 <= part.bottom() + SNAP, "the first row shows in the part: {rest:?}");
// Focus puts the caret at the end of plain text.
fixture.key(Key::Tab, Modifiers::NONE);
fixture.type_text("!");
fixture.idle(3);
assert!(value.borrow().ends_with("12!"), "the typing lands at the end: {:?}", value.borrow());
let scrolled = painted.borrow().clone();
let last = scrolled.rows.last().copied().expect("the text has rows");
assert!(scrolled.origin.is_some_and(|origin| origin.y < part.top()), "the origin moves up with the scrolled text: {scrolled:?}");
assert!(last.1 <= part.bottom() + SNAP && last.0 >= part.top() - SNAP, "the caret's row, the last, is drawn in the part: {scrolled:?}");
}
+3 -3
View File
@@ -2433,7 +2433,7 @@ The component traits, context types, `PaintUi`, `Looks`, the pipeline and its st
- `pub fn show<R>(self, ui: &mut Ui, add: impl FnOnce(&mut Ui) -> R) -> Option<R>`. Runs `add` in a child `Ui` placed in flow in `ui`, or takes the remembered extent there; `None` when it did not
- `craft_ui::contract::LeadOnOpen`: `pub enum LeadOnOpen { Selected, First }`. Where the lead starts when the collection first shows rows.
- `craft_ui::contract::LeadSource`: `pub enum LeadSource { Keys, Pointer }`. What moved the lead.
- `craft_ui::contract::LeastWidth`: `pub enum LeastWidth { Popup, Dialog, DialogButton, DialogSideButton, Rail(std::num::NonZeroU8), WideDialog, SideMenu, DockColumn }`. A size role that sets the least width of a container's content or of a button.
- `craft_ui::contract::LeastWidth`: `pub enum LeastWidth { Popup, Dialog, DialogButton, DialogSideButton, Rail(std::num::NonZeroU8), WideDialog, SideMenu, DockColumn, Palette }`. A size role that sets the least width of a container's content or of a button.
- `pub fn points(self, tokens: &craft_theme::Tokens) -> f32`. The width the role names in `tokens`.
- `craft_ui::contract::LinkLabelInk`: `pub enum LinkLabelInk { Accent, Neutral }`. The ink of a field's label shown as a link ([`SideLabel::link`]), which opens its control's options. An app sets it
- `craft_ui::contract::LinkLabelUnderline`: `pub enum LinkLabelUnderline { Edge, Inside }`. Where a one-line link label ([`SideLabel::link`]) draws its underline. An app sets it once at its root
@@ -3312,9 +3312,9 @@ Painters, `Draw`, the sensing core, the text adapter and `ImeSurface`.
- `pub fn row_lines(&self) -> Vec<(String, egui::Rect, Vec<LayoutRun>)>`. Every row as its text, its rect from the galley's origin and its bidi runs: the one per-row geometry, read by
- `pub fn size(&self) -> egui::Vec2`. The galley size.
- `pub fn char_x(&self, chars: usize) -> f32`. Where a caret before character `chars` (counted from the start of the text) stands, from the layout's left edge:
- `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option<Label>, pub look: crate::style::FieldLook, pub lines: Option<usize>, pub limit: Option<usize>, pub mask: bool, pub live: bool, pub edit_target: Option<egui::IdSalt>, pub clear_on_escape: bool, pub keep_on_escape: bool, pub mono: bool, pub role: TypeRole, pub ink: Option<Ink>, pub tab: TabKey, pub caret: Option<usize>, pub complete: Option<Arc<dyn Completer>>, pub complete_on_enter: bool, pub replace_selection: Option<String>, pub commit_on: &'static [char], pub enabled: bool, pub steps_value: bool, pub select_on_focus: bool, pub keep_caret_on_open: bool, pub select_all: bool, pub submits: bool, pub mixed: bool, pub centred: bool, pub end_aligned: bool, pub arrows_from_end: bool, pub unparsed: Option<Message>, pub own_menu: bool, pub holds_drafts: bool, pub whole_paste: Option<Arc<WholePaste>>, pub submit_key: SubmitKey, pub resting: Option<String> }`. How a text part behaves beyond its codec.
- `craft_ui::primitives::TextOptions`: `pub struct TextOptions { pub placeholder: Option<Label>, pub look: crate::style::FieldLook, pub lines: Option<usize>, pub limit: Option<usize>, pub mask: bool, pub live: bool, pub edit_target: Option<egui::IdSalt>, pub clear_on_escape: bool, pub keep_on_escape: bool, pub mono: bool, pub role: TypeRole, pub size: Option<f32>, pub top: bool, pub ink: Option<Ink>, pub tab: TabKey, pub caret: Option<usize>, pub complete: Option<Arc<dyn Completer>>, pub complete_on_enter: bool, pub replace_selection: Option<String>, pub commit_on: &'static [char], pub enabled: bool, pub steps_value: bool, pub select_on_focus: bool, pub keep_caret_on_open: bool, pub select_all: bool, pub submits: bool, pub mixed: bool, pub centred: bool, pub end_aligned: bool, pub arrows_from_end: bool, pub unparsed: Option<Message>, pub own_menu: bool, pub holds_drafts: bool, pub whole_paste: Option<Arc<WholePaste>>, pub submit_key: SubmitKey, pub resting: Option<String> }`. How a text part behaves beyond its codec.
- `pub fn new() -> Self`. Options with every default.
- `craft_ui::primitives::TextOutcome`: `pub struct TextOutcome<V> { pub rect: Rect, pub draft: Option<String>, pub value: Option<V>, pub layout: Option<super::TextLayout>, pub caret_visible: bool, pub invalid: bool, pub committed: Option<craft_behavior::ParseNote>, pub composing: bool, pub completions: Vec<super::Completion>, pub clicked: bool }`. A text part's result this pass.
- `craft_ui::primitives::TextOutcome`: `pub struct TextOutcome<V> { pub rect: Rect, pub draft: Option<String>, pub value: Option<V>, pub layout: Option<super::TextLayout>, pub origin: egui::Pos2, pub caret_visible: bool, pub invalid: bool, pub committed: Option<craft_behavior::ParseNote>, pub composing: bool, pub completions: Vec<super::Completion>, pub clicked: bool }`. A text part's result this pass.
- `pub const fn new(rect: Rect) -> Self`. An outcome over `rect` with no draft or value.
- `craft_ui::primitives::TextRun`: `pub struct TextRun<'a> { pub spans: Vec<Span<'a>>, pub role: TypeRole, pub color: Option<StyleColor>, pub wrap: Wrap, pub ltr: bool, pub align: HAlign, pub rotation: f32, pub link_color: Option<Color32> }`. The one description of UI text.
- `pub const READABLE_CHARACTERS: usize`. The characters a run that elides keeps before its ellipsis at its least, its readable least: a row narrows