A new kit control, `ui_kit::count_field` / `count_row`, is an expression field for a whole-number count with stacked step arrows at its right edge. An arrow steps the evaluated count by one within the field's limits: a plain number is replaced, an expression keeps its parameters and gains or adjusts a trailing `+ n`. The text changes as typing changes it, so the live preview follows. Used by the Quantity rows of the sketch Rectangular (1-500, both directions together at most 500) and Circular (2-500) patterns, and the solid Rectangular, Circular and Path patterns (1-1000). Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
fc3e3b6c8d
commit
1fa0371c75
9 files changed
+308
-20
No files matched your search
@@ -409,3 +409,48 @@ fn face_editor_refills_named_faces_after_sketch_resize() {
|
||||
assert!(h.app.session.model.results.iter().all(|r| r.error.is_none()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solid_pattern_quantity_arrows_step_the_count_the_command_receives() {
|
||||
let mut h = fixture();
|
||||
h.app.run("parameters.add", json!({"name":"copies","expression":"3","unit":""})).unwrap();
|
||||
for (command, key, label) in [
|
||||
("solid.pattern.circular", "count", "Quantity"),
|
||||
("solid.pattern.rectangular", "count1", "Quantity"),
|
||||
("solid.pattern.path", "count", "Quantity"),
|
||||
] {
|
||||
let mut d = representative(&h, command);
|
||||
if command == "solid.pattern.rectangular" {
|
||||
d.inputs[1].items = vec![Sel::Axis { name: "X".into() }];
|
||||
}
|
||||
h.app.dialog = Some(d);
|
||||
h.settle();
|
||||
let sent = |h: &Harness| {
|
||||
let cmds = crate::dialogs::preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap_or_else(|e| panic!("{command}: {e}"));
|
||||
cmds.iter().find(|(id, _)| id == command).map(|(_, p)| p[key].clone()).unwrap_or_else(|| panic!("{command}: {cmds:?}"))
|
||||
};
|
||||
let before = sent(&h).as_str().unwrap().parse::<i64>().unwrap();
|
||||
h.step(&json!({"click":{"handle":format!("dialog:{label} up")}})).unwrap();
|
||||
assert_eq!(sent(&h), json!((before + 1).to_string()), "{command}");
|
||||
let set = |h: &mut Harness, text: &str| {
|
||||
if let Some(Kind::PatternRect { count, .. } | Kind::PatternCirc { count, .. } | Kind::PathPattern { count, .. }) =
|
||||
h.app.dialog.as_mut().map(|d| &mut d.kind)
|
||||
{
|
||||
*count = text.into();
|
||||
}
|
||||
h.frames(2);
|
||||
};
|
||||
// From 1 to the document's 1000 instances.
|
||||
set(&mut h, "1");
|
||||
h.step(&json!({"click":{"handle":format!("dialog:{label} down")}})).unwrap();
|
||||
assert_eq!(sent(&h), json!("1"), "{command}");
|
||||
set(&mut h, "1000");
|
||||
h.step(&json!({"click":{"handle":format!("dialog:{label} up")}})).unwrap();
|
||||
assert_eq!(sent(&h), json!("1000"), "{command}");
|
||||
set(&mut h, "copies");
|
||||
h.step(&json!({"click":{"handle":format!("dialog:{label} up")}})).unwrap();
|
||||
assert_eq!(sent(&h), json!("copies + 1"), "{command}");
|
||||
h.step(&json!({"click":{"handle":"dialog:cancel"}})).unwrap();
|
||||
h.settle();
|
||||
}
|
||||
}
|
||||
@@ -106,6 +106,16 @@ const FILLET_TYPES: [(&str, &str); 5] = [
|
||||
("Spline", "spline"),
|
||||
];
|
||||
|
||||
/// The most instances a solid pattern makes in one direction (the document's own limit).
|
||||
const MAX_PATTERN_INSTANCES: i64 = 1000;
|
||||
|
||||
/// A solid pattern's quantity row, with step arrows from 1 to `MAX_PATTERN_INSTANCES`. The
|
||||
/// count goes to the command as typed, so it is evaluated as the document evaluates it.
|
||||
fn quantity_row(ui: &mut egui::Ui, doc: &solidcraft_engine::doc::Document, label: &str, value: &mut String) -> bool {
|
||||
let eval = |text: &str| doc.eval(text.trim(), solidcraft_engine::doc::expr::Kind::Unitless).ok();
|
||||
ui_kit::count_row(ui, label, value, &ui_kit::Count { min: 1, max: MAX_PATTERN_INSTANCES, eval: &eval })
|
||||
}
|
||||
|
||||
fn fillet_type(extra: &serde_json::Map<String, Value>) -> usize {
|
||||
let value = extra.get("type").and_then(Value::as_str).unwrap_or("constant");
|
||||
if value == "g2" { 3 } else { FILLET_TYPES.iter().position(|(_, key)| *key == value).unwrap_or(0) }
|
||||
@@ -198,7 +208,7 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
|
||||
}
|
||||
}
|
||||
}
|
||||
Kind::SketchModify(k) => enter |= crate::sketch_modify_ui::rows(ui, k),
|
||||
Kind::SketchModify(k) => enter |= crate::sketch_modify_ui::rows(ui, k, &app.session.doc),
|
||||
Kind::Text(k) => enter |= crate::sketch_text::rows(ui, k, &mut d.inputs, &mut d.active),
|
||||
Kind::TextMove(k) => enter |= crate::sketch_text_move::rows(ui, k),
|
||||
Kind::EditParam { name, expr } => {
|
||||
@@ -469,18 +479,18 @@ pub(super) fn rows(app: &mut SolveApp, ctx: &egui::Context, d: &mut Dialog, ui:
|
||||
}
|
||||
}
|
||||
Kind::PatternRect { count, spacing, count2, spacing2 } => {
|
||||
for (l, v) in [("Quantity", count), ("Spacing", spacing), ("Quantity 2", count2), ("Spacing 2", spacing2)] {
|
||||
enter |= expr_row(ui, l, v);
|
||||
}
|
||||
enter |= quantity_row(ui, &app.session.doc, "Quantity", count);
|
||||
enter |= expr_row(ui, "Spacing", spacing);
|
||||
enter |= quantity_row(ui, &app.session.doc, "Quantity 2", count2);
|
||||
enter |= expr_row(ui, "Spacing 2", spacing2);
|
||||
if d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES) {
|
||||
feature_pattern_alignment_row(ui, &mut d.extra, 0);
|
||||
feature_pattern_alignment_row(ui, &mut d.extra, 1);
|
||||
}
|
||||
}
|
||||
Kind::PatternCirc { count, angle } => {
|
||||
for (l, v) in [("Quantity", count), ("Total angle", angle)] {
|
||||
enter |= expr_row(ui, l, v);
|
||||
}
|
||||
enter |= quantity_row(ui, &app.session.doc, "Quantity", count);
|
||||
enter |= expr_row(ui, "Total angle", angle);
|
||||
if d.inputs.first().is_some_and(|i| i.accept == selection::FEATURES) {
|
||||
feature_pattern_alignment_row(ui, &mut d.extra, 0);
|
||||
}
|
||||
@@ -701,9 +711,8 @@ fn additional_rows(app: &mut SolveApp, d: &mut Dialog, ui: &mut egui::Ui) -> boo
|
||||
extra_options(ui, "boundary_options", &mut d.extra, &[("Remove Tools", "remove_tools")]);
|
||||
}
|
||||
Kind::PathPattern { count, spacing } => {
|
||||
for (l, v) in [("Quantity", count), ("Spacing", spacing)] {
|
||||
enter |= expr_row(ui, l, v);
|
||||
}
|
||||
enter |= quantity_row(ui, &app.session.doc, "Quantity", count);
|
||||
enter |= expr_row(ui, "Spacing", spacing);
|
||||
}
|
||||
Kind::Pipe { diameter, wall } => {
|
||||
enter |= expr_row(ui, "Diameter", diameter);
|
||||
|
||||
@@ -207,3 +207,77 @@ fn apply_keeps_the_panel_open_after_asynchronous_evaluation() {
|
||||
assert!(d.inputs.iter().all(|i| i.items.is_empty()));
|
||||
assert!(!d.repeat_after_apply);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn circular_pattern_quantity_arrows_step_the_count_within_its_limits_and_keep_parameters() {
|
||||
let mut h = fixture();
|
||||
h.app.dialog = Some(picked(&h, "sketch.pattern.circular"));
|
||||
h.settle();
|
||||
let count = |h: &Harness| match &h.app.dialog.as_ref().unwrap().kind {
|
||||
Kind::SketchModify(Mod::PatternCirc { count, .. }) => count.clone(),
|
||||
other => panic!("not a sketch pattern window: {other:?}"),
|
||||
};
|
||||
let set = |h: &mut Harness, text: &str| {
|
||||
if let Some(Kind::SketchModify(Mod::PatternCirc { count, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) {
|
||||
*count = text.into();
|
||||
}
|
||||
h.frames(2);
|
||||
};
|
||||
let sent = |h: &Harness| apply_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["count"].clone();
|
||||
let previewed = |h: &Harness| crate::dialogs::preview_commands(&h.app, h.app.dialog.as_ref().unwrap()).unwrap()[0].1["count"].clone();
|
||||
assert_eq!(count(&h), "6");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity up"}})).unwrap();
|
||||
assert_eq!(count(&h), "7");
|
||||
assert_eq!((sent(&h), previewed(&h)), (json!(7), json!(7)), "the preview follows the arrow as it follows typing");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap();
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap();
|
||||
assert_eq!(count(&h), "5");
|
||||
// A circular pattern needs the original and one copy, and makes at most 500.
|
||||
set(&mut h, "2");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap();
|
||||
assert_eq!(count(&h), "2");
|
||||
set(&mut h, "500");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity up"}})).unwrap();
|
||||
assert_eq!(count(&h), "500");
|
||||
// A count typed past the limit steps back inside it.
|
||||
set(&mut h, "900");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap();
|
||||
assert_eq!(count(&h), "500");
|
||||
// An expression keeps its parameter: the arrows adjust a trailing offset.
|
||||
h.app.run("parameters.add", json!({"name":"holes","expression":"4","unit":""})).unwrap();
|
||||
set(&mut h, "holes");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity up"}})).unwrap();
|
||||
assert_eq!((count(&h), sent(&h)), ("holes + 1".into(), json!("holes + 1")), "the command keeps the parameter");
|
||||
for _ in 0..2 {
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap();
|
||||
}
|
||||
assert_eq!((count(&h), sent(&h)), ("holes - 1".into(), json!("holes - 1")));
|
||||
// Text that is not a count leaves the arrows without effect.
|
||||
set(&mut h, "nothing");
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity up"}})).unwrap();
|
||||
assert_eq!(count(&h), "nothing");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rectangular_pattern_quantity_arrows_keep_both_directions_within_the_copy_limit() {
|
||||
let mut h = fixture();
|
||||
h.app.dialog = Some(picked(&h, "sketch.pattern.rectangular"));
|
||||
h.settle();
|
||||
let counts = |h: &Harness| match &h.app.dialog.as_ref().unwrap().kind {
|
||||
Kind::SketchModify(Mod::PatternRect { count, count2, .. }) => (count.clone(), count2.clone()),
|
||||
other => panic!("not a sketch pattern window: {other:?}"),
|
||||
};
|
||||
let (one, _) = counts(&h);
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity 2 up"}})).unwrap();
|
||||
assert_eq!(counts(&h), (one.clone(), "2".into()));
|
||||
if let Some(Kind::SketchModify(Mod::PatternRect { count, count2, .. })) = h.app.dialog.as_mut().map(|d| &mut d.kind) {
|
||||
(*count, *count2) = ("250".into(), "2".into());
|
||||
}
|
||||
h.frames(2);
|
||||
// 250 × 2 is the 500 copies a sketch pattern makes at most.
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity up"}})).unwrap();
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity 2 up"}})).unwrap();
|
||||
assert_eq!(counts(&h), ("250".into(), "2".into()));
|
||||
h.step(&json!({"click":{"handle":"dialog:Quantity down"}})).unwrap();
|
||||
assert_eq!(counts(&h), ("249".into(), "2".into()));
|
||||
}
|
||||
@@ -26,6 +26,7 @@
|
||||
use egui::Pos2;
|
||||
use serde_json::{Map, Value, json};
|
||||
use solidcraft_engine::Sel;
|
||||
use solidcraft_engine::doc::Document;
|
||||
use solidcraft_engine::doc::expr::Kind as ValueKind;
|
||||
use solidcraft_engine::geom::{Vec2, Vec3};
|
||||
use solidcraft_engine::sketch::PatternAlignment;
|
||||
@@ -330,6 +331,20 @@ fn number(ui: &mut egui::Ui, label: &str, value: &mut String) -> bool {
|
||||
ui_kit::row(ui, label, |ui| ui_kit::field(ui, value))
|
||||
}
|
||||
|
||||
/// A pattern quantity row with step arrows. They keep the count from `min` up to `max`
|
||||
/// copies, evaluated against the design's parameters as `whole` evaluates it on OK.
|
||||
fn quantity(ui: &mut egui::Ui, doc: &Document, label: &str, value: &mut String, min: i64, max: i64) -> bool {
|
||||
let eval = |text: &str| doc.eval(text.trim(), ValueKind::Unitless).ok();
|
||||
ui_kit::count_row(ui, label, value, &ui_kit::Count { min, max: max.max(min), eval: &eval })
|
||||
}
|
||||
|
||||
/// How many copies the other direction of a rectangular pattern leaves this one, so that
|
||||
/// both together stay within `MAX_COPIES`. All of them while the other count is not a number.
|
||||
fn copies_left(doc: &Document, other: &str) -> i64 {
|
||||
let other = doc.eval(other.trim(), ValueKind::Unitless).ok().filter(|v| v.is_finite() && *v >= 1.0).map_or(1.0, f64::round);
|
||||
(MAX_COPIES / other).floor() as i64
|
||||
}
|
||||
|
||||
fn icons(ui: &mut egui::Ui, label: &str, labels: &[&'static str], icons: &[&'static str], selected: &mut usize) {
|
||||
ui_kit::row(ui, label, |ui| {
|
||||
let choices: Vec<_> =
|
||||
@@ -356,7 +371,8 @@ fn pattern_hint(ui: &mut egui::Ui) {
|
||||
}
|
||||
|
||||
/// Dense rows after the selection inputs; true when an expression field accepts Enter.
|
||||
pub fn rows(ui: &mut egui::Ui, k: &mut Mod) -> bool {
|
||||
/// `doc` evaluates the pattern counts the step arrows change.
|
||||
pub fn rows(ui: &mut egui::Ui, k: &mut Mod, doc: &Document) -> bool {
|
||||
let mut enter = false;
|
||||
match k {
|
||||
Mod::Scale { factor } => enter |= number(ui, "Factor", factor),
|
||||
@@ -381,12 +397,13 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod) -> bool {
|
||||
ui_kit::options(ui, "move_options", &mut [("Create Copy", copy)]);
|
||||
}
|
||||
Mod::PatternRect { count, spacing, count2, spacing2, alignment: a, alignment2, reversed, reversed2 } => {
|
||||
for (key, title, count, spacing, align, reverse, quantity, distance, align_label) in [
|
||||
("direction1", "Direction 1", count, spacing, a, reversed, "Quantity", "Spacing", "Alignment"),
|
||||
("direction2", "Direction 2", count2, spacing2, alignment2, reversed2, "Quantity 2", "Spacing 2", "Alignment 2"),
|
||||
let (left1, left2) = (copies_left(doc, count2), copies_left(doc, count));
|
||||
for (key, title, count, spacing, align, reverse, label, distance, align_label, left) in [
|
||||
("direction1", "Direction 1", count, spacing, a, reversed, "Quantity", "Spacing", "Alignment", left1),
|
||||
("direction2", "Direction 2", count2, spacing2, alignment2, reversed2, "Quantity 2", "Spacing 2", "Alignment 2", left2),
|
||||
] {
|
||||
ui_kit::section(ui, key, title, true, |ui| {
|
||||
enter |= number(ui, quantity, count);
|
||||
enter |= quantity(ui, doc, label, count, 1, left);
|
||||
enter |= number(ui, distance, spacing);
|
||||
alignment(ui, align_label, align, reverse);
|
||||
});
|
||||
@@ -394,7 +411,7 @@ pub fn rows(ui: &mut egui::Ui, k: &mut Mod) -> bool {
|
||||
pattern_hint(ui);
|
||||
}
|
||||
Mod::PatternCirc { count, angle, alignment: a, reversed } => {
|
||||
enter |= number(ui, "Quantity", count);
|
||||
enter |= quantity(ui, doc, "Quantity", count, 2, MAX_COPIES as i64);
|
||||
enter |= number(ui, "Total angle", angle);
|
||||
alignment(ui, "Alignment", a, reversed);
|
||||
pattern_hint(ui);
|
||||
|
||||
@@ -27,6 +27,87 @@ pub(crate) fn hint_field(ui: &mut Ui, value: &mut String, hint: &str) -> bool {
|
||||
editor(ui, value, hint, true).0
|
||||
}
|
||||
|
||||
/// The whole numbers a count field may hold, and how its text evaluates (parameters and
|
||||
/// expressions included). `eval` returns None for text that is not a value.
|
||||
pub(crate) struct Count<'a> {
|
||||
pub min: i64,
|
||||
pub max: i64,
|
||||
pub eval: &'a dyn Fn(&str) -> Option<f64>,
|
||||
}
|
||||
|
||||
/// Expression editor for a whole-number count (a pattern's quantity), with up and down step
|
||||
/// arrows at its right edge. An arrow steps the evaluated count by one and stays within the
|
||||
/// limits: a plain number is replaced, an expression keeps its parameters and gains or adjusts
|
||||
/// a trailing `+ n`. The text changes as if typed, so previews follow. Returns accepted Enter.
|
||||
/// Tokens: field tokens, `control_border`, `selected_bg`, `form_ink`, `form_dim`.
|
||||
pub(crate) fn count_field(ui: &mut Ui, value: &mut String, limits: &Count<'_>) -> bool {
|
||||
let t = Tokens::get();
|
||||
let reserve = (t.control_height * 0.75).round();
|
||||
let (enter, _, response) = editor_reserving(ui, value, "", true, reserve);
|
||||
let rect = response.rect;
|
||||
let column = egui::Rect::from_min_max(egui::pos2((rect.right() - reserve).max(rect.left()), rect.top()), rect.max);
|
||||
let painter = ui.painter_at(rect);
|
||||
painter.vline(column.left(), column.y_range().shrink(t.space_4), egui::Stroke::new(1.0, t.control_border));
|
||||
let row = label(ui).to_owned();
|
||||
for (delta, half, name) in [(1, column.split_top_bottom_at_fraction(0.5).0, "up"), (-1, column.split_top_bottom_at_fraction(0.5).1, "down")] {
|
||||
let next = step_count(value, delta, limits);
|
||||
let arrow = ui.interact(half, ui.id().with(("sc_count_step", &row, name)), egui::Sense::click());
|
||||
let enabled = ui.is_enabled() && next.is_some();
|
||||
if enabled && arrow.hovered() {
|
||||
painter.rect_filled(half.shrink(1.0), t.control_radius, t.selected_bg);
|
||||
}
|
||||
let ink = if enabled { t.form_ink } else { t.form_dim };
|
||||
let (c, w, h) = (half.center(), (reserve * 0.18).max(2.0), (half.height() * 0.2).max(2.0));
|
||||
let tip = if delta > 0 { -h } else { h };
|
||||
painter.add(egui::Shape::convex_polygon(
|
||||
vec![egui::pos2(c.x, c.y + tip * 0.5), egui::pos2(c.x + w, c.y - tip * 0.5), egui::pos2(c.x - w, c.y - tip * 0.5)],
|
||||
ink,
|
||||
egui::Stroke::NONE,
|
||||
));
|
||||
let sign = if delta > 0 { "+1" } else { "−1" };
|
||||
arrow.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, enabled, format!("{} {sign}", crate::i18n::tr_label(&row))));
|
||||
scenario::publish_handle(&format!("dialog:{row} {name}"), half.center());
|
||||
if let (true, true, Some(next)) = (enabled, arrow.clicked(), next) {
|
||||
*value = next;
|
||||
}
|
||||
}
|
||||
enter
|
||||
}
|
||||
|
||||
/// `text` stepped by `delta` whole numbers within `limits`, or None when it does not evaluate
|
||||
/// or the step would leave the limits. A typed number between whole numbers steps to the next
|
||||
/// one; an expression that evaluates between them is left alone.
|
||||
fn step_count(text: &str, delta: i64, limits: &Count<'_>) -> Option<String> {
|
||||
const SAFE: f64 = 1e15;
|
||||
let trimmed = text.trim();
|
||||
let now = (limits.eval)(trimmed).filter(|v| v.is_finite() && v.abs() < SAFE)?;
|
||||
let from = if delta > 0 { now.floor() } else { now.ceil() } as i64;
|
||||
let target = from.saturating_add(delta).clamp(limits.min, limits.max);
|
||||
let moves = if delta > 0 { target as f64 > now } else { (target as f64) < now };
|
||||
if !moves {
|
||||
return None;
|
||||
}
|
||||
if trimmed.parse::<f64>().is_ok() {
|
||||
return Some(target.to_string());
|
||||
}
|
||||
// An expression: adjust its trailing `+ n` / `- n`, or add one, and check that it now says `target`.
|
||||
let offset = |base: &str, n: i64| match n {
|
||||
0 => base.to_owned(),
|
||||
n if n > 0 => format!("{base} + {n}"),
|
||||
n => format!("{base} - {}", n.unsigned_abs()),
|
||||
};
|
||||
let tail = trimmed.rfind(['+', '-']).and_then(|at| {
|
||||
let (base, number) = (trimmed[..at].trim_end(), trimmed[at + 1..].trim());
|
||||
let n: i64 = number.bytes().all(|b| b.is_ascii_digit()).then(|| number.parse().ok()).flatten()?;
|
||||
let base_ok = !base.is_empty() && !base.ends_with(['+', '-', '*', '/', '^', '(', ',']);
|
||||
base_ok.then(|| (base, if trimmed[at..].starts_with('-') { -n } else { n }))
|
||||
});
|
||||
let step = target - now.round() as i64;
|
||||
let candidates =
|
||||
[tail.map(|(base, n)| offset(base, n.saturating_add(step))), Some(offset(trimmed, step)), Some(offset(&format!("({trimmed})"), step))];
|
||||
candidates.into_iter().flatten().find(|c| (limits.eval)(c).is_some_and(|v| (v - target as f64).abs() < 1e-9))
|
||||
}
|
||||
|
||||
/// Names, thread designations and plain numeric counts do not accept expression completion.
|
||||
/// Plain text editor without expression completion; returns (Enter, changed). Tokens: `same as field`.
|
||||
pub(crate) fn text_field(ui: &mut Ui, value: &mut String, hint: &str) -> (bool, bool) {
|
||||
@@ -141,13 +222,20 @@ pub(crate) fn searchable_dropdown(
|
||||
|
||||
/// Completion/focus implementation shared by field variants. Tokens: `same as field`.
|
||||
fn editor(ui: &mut Ui, value: &mut String, hint: &str, completion: bool) -> (bool, bool, Response) {
|
||||
editor_reserving(ui, value, hint, completion, 0.0)
|
||||
}
|
||||
|
||||
/// `editor` whose text stops `reserve` points short of its right edge, for controls drawn there.
|
||||
fn editor_reserving(ui: &mut Ui, value: &mut String, hint: &str, completion: bool, reserve: f32) -> (bool, bool, Response) {
|
||||
let t = Tokens::get();
|
||||
let width = dimension(ui.available_width());
|
||||
let font = egui::FontId::monospace(t.font_label);
|
||||
let response = ui.add_sized(
|
||||
vec2(width, row_height()),
|
||||
text_input(egui::TextEdit::singleline(value)).hint_text(hint).font(font).background_color(t.input_fill()).clip_text(true),
|
||||
);
|
||||
let mut edit = text_input(egui::TextEdit::singleline(value)).hint_text(hint).font(font).background_color(t.input_fill()).clip_text(true);
|
||||
if reserve > 0.0 {
|
||||
let inset = t.form_inset.round() as i8;
|
||||
edit = edit.margin(egui::Margin { left: inset, right: inset.saturating_add(reserve.round() as i8), top: 0, bottom: 0 });
|
||||
}
|
||||
let response = ui.add_sized(vec2(width, row_height()), edit);
|
||||
crate::theme::TabAccent::number_focus(ui, &response);
|
||||
t.input_bevel(ui, &response);
|
||||
let label = crate::i18n::tr_label(label(ui));
|
||||
|
||||
@@ -240,3 +240,41 @@ fn bounded_name_editor_keeps_unicode_character_cap() {
|
||||
frame(&ctx, vec![egui::Event::Text("åβ界d".into())], &mut draw);
|
||||
assert_eq!(value, "åβ界");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn count_steps_stay_within_limits_and_keep_expressions() {
|
||||
let eval = |text: &str| -> Option<f64> {
|
||||
let text = text.trim();
|
||||
match text {
|
||||
"n" => Some(4.0),
|
||||
"n + 2" => Some(6.0),
|
||||
"n + 3" => Some(7.0),
|
||||
"n + 1" => Some(5.0),
|
||||
"n - 1" => Some(3.0),
|
||||
"half" => Some(2.5),
|
||||
_ => text.parse().ok(),
|
||||
}
|
||||
};
|
||||
let limits = Count { min: 2, max: 10, eval: &eval };
|
||||
let step = |text: &str, delta| super::step_count(text, delta, &limits);
|
||||
assert_eq!(step("6", 1).as_deref(), Some("7"));
|
||||
assert_eq!(step(" 6 ", -1).as_deref(), Some("5"));
|
||||
assert_eq!(step("2", -1), None, "the minimum holds");
|
||||
assert_eq!(step("10", 1), None, "the maximum holds");
|
||||
assert_eq!(step("40", -1).as_deref(), Some("10"), "a typed count past the limit steps back inside it");
|
||||
assert_eq!(step("0", 1).as_deref(), Some("2"));
|
||||
assert_eq!(step("3.5", 1).as_deref(), Some("4"), "between whole numbers: the next one up");
|
||||
assert_eq!(step("3.5", -1).as_deref(), Some("3"));
|
||||
assert_eq!(step("n", 1).as_deref(), Some("n + 1"));
|
||||
assert_eq!(step("n", -1).as_deref(), Some("n - 1"));
|
||||
assert_eq!(step("n + 2", 1).as_deref(), Some("n + 3"));
|
||||
assert_eq!(step("n + 1", -1).as_deref(), Some("n"));
|
||||
assert_eq!(step("half", 1), None, "an expression between whole numbers is left alone");
|
||||
for junk in ["", "abc", "1e400", "-1e300", "NaN"] {
|
||||
assert_eq!(step(junk, 1), None, "{junk}");
|
||||
}
|
||||
let wide = Count { min: i64::MIN, max: i64::MAX, eval: &eval };
|
||||
assert_eq!(super::step_count("1e16", 1, &wide), None, "values past what counts can be are refused");
|
||||
assert_eq!(super::step_count("5", i64::MAX, &wide).as_deref(), Some("9223372036854775807"), "steps saturate rather than overflow");
|
||||
assert_eq!(super::step_count("5", i64::MIN, &wide).as_deref(), Some("-9223372036854775803"));
|
||||
}
|
||||
@@ -774,6 +774,16 @@ const ELEMENTS: &[Element] = &[
|
||||
element!("expr_row", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| {
|
||||
expr_row(ui, "Gallery", &mut s.value);
|
||||
}),
|
||||
element!("count_row", "dialog:row:Gallery", Some("dialog:Gallery up"), |ui, _| {
|
||||
let mut count = "6".to_owned();
|
||||
count_row(ui, "Gallery", &mut count, &Count { min: 1, max: 10, eval: &|text: &str| text.trim().parse().ok() });
|
||||
}),
|
||||
element!("count_field", "dialog:row:Gallery", Some("dialog:Gallery down"), |ui, _| {
|
||||
row(ui, "Gallery", |ui| {
|
||||
let mut count = "1".to_owned();
|
||||
count_field(ui, &mut count, &Count { min: 1, max: 10, eval: &|text: &str| text.trim().parse().ok() });
|
||||
});
|
||||
}),
|
||||
element!("hint_row", "dialog:row:Gallery", Some("dialog:Gallery"), |ui, s| {
|
||||
hint_row(ui, "Gallery", &mut s.value, "Value");
|
||||
}),
|
||||
|
||||
@@ -72,6 +72,11 @@ pub(crate) fn expr_row(ui: &mut Ui, label: &str, value: &mut String) -> bool {
|
||||
row(ui, label, |ui| super::field(ui, value))
|
||||
}
|
||||
|
||||
/// Whole-number count row with step arrows; retains completion and accepted Enter. Tokens: `row, count_field`.
|
||||
pub(crate) fn count_row(ui: &mut Ui, label: &str, value: &mut String, limits: &super::Count<'_>) -> bool {
|
||||
row(ui, label, |ui| super::count_field(ui, value, limits))
|
||||
}
|
||||
|
||||
/// Expression row with an empty-value hint. Tokens: `row, hint_field`.
|
||||
pub(crate) fn hint_row(ui: &mut Ui, label: &str, value: &mut String, hint: &str) -> bool {
|
||||
row(ui, label, |ui| super::hint_field(ui, value, hint))
|
||||
|
||||
@@ -24,6 +24,7 @@ preferences, manager cards, prompts, context menus and the sketch palette. Impor
|
||||
- `expr_row`, `hint_row`, `text_row` and `choice_row` compose `row` with the existing
|
||||
expression, hinted expression, plain text and dropdown controls. They preserve row order,
|
||||
labels, focus IDs and completion; callers keep Enter/change ownership and explicit dropdown IDs.
|
||||
`count_row` composes `row` with `count_field` for pattern quantities.
|
||||
- `Panel` owns bounded windows, feature/palette composition, scrolling bodies,
|
||||
pinned actions, compute status and keyboard routing. `wide()` uses three card
|
||||
widths. `feature_frame` and `palette_frame` retain docked/floating surfaces.
|
||||
@@ -88,6 +89,7 @@ table. Panel/Window/Confirm compositions also have dedicated geometry and intera
|
||||
| `text`, `Text` | Hint, note, report, inline or cell text; see variants below | `font_small/label`, `text/dim/error`, `control_height`, `space_4` |
|
||||
| `text_lines` | Virtualized read-only licence/report lines, horizontal overflow | `font_small`, `text`, `control_height` |
|
||||
| fields: `field`, `hint_field`, `focused_field` | Expression editors, optional empty hint or retained focus; returns accepted Enter | `control_height/fill`, `form_inset`, `font_label` |
|
||||
| `count_field`, `Count` | Expression editor for a whole-number count (a pattern's quantity) with up/down step arrows at its right edge. `Count` gives the limits and the evaluator (the design's parameters); an arrow steps the evaluated count by one within them, replacing a plain number or adjusting an expression's trailing `+ n`, and is dimmed when it can't step. Handles `dialog:<row> up` / `down`; returns accepted Enter | field tokens, `control_border`, `control_radius`, `selected_bg`, `form_ink/dim`, `space_4` |
|
||||
| `text_field`, `focused_text_field` | Plain name editor, optionally retaining focus | field tokens |
|
||||
| `multiline_text_field` | Three-line plain-text row with stable focus ID | field/row tokens |
|
||||
| `password_field` | Stable secret editor; excludes the secret from scenario/accessibility metadata | field tokens |
|
||||
|
||||
Reference in new issue
Block a user