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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,7 +399,7 @@ pub fn commands() -> Vec<C> {
r##""barOutline"?: {"color"?, "width"?: points, 0 to 5, a wider one held to 5, the keys not given keeping the outline's}|null (null or a width of 0 for none), "##,
r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##,
r##""rows"?, "##,
r##""fields"?: [field names] (table, as in layout.addElement, of the layer it will show; [] returns to every field, null leaves them; another "layer" without them drops them), "##,
r##""fields"?: [field names] (table, as in layout.addElement, of the layer it will show, plus any the table already shows of that layer and it has lost, spelled the same; [] returns to every field, null leaves them; another "layer" without them drops them), "##,
r##""header"?: bool (table, as in layout.addElement; null leaves it as it is), "##,
r##""image"?: base64 (picture: its new image, its file no longer remembered, which is said when it had one), "##,
r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; refused in the browser, which has no file paths: give its image; null leaves each as it is; refused for other elements), "##,
Expand Down
28 changes: 18 additions & 10 deletions crates/engine/src/cmd/layout/elements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,19 +83,27 @@ pub(in crate::cmd::layout) fn table_fields(p: &Value) -> Result<Option<Vec<&str>
}

/// `names` as the fields of `ds` they name, spelled as it spells them: an error for one it hasn't,
/// or one named twice.
pub(in crate::cmd::layout) fn table_columns(ds: &rustgis_data::Dataset, names: &[&str]) -> Result<Vec<String>, String> {
/// or one named twice. A name the table already shows of this layer (`held`, spelled so) that no
/// field is spelled as stays as it is, as the table keeps a field the layer loses and draws one
/// added since under another case as lost too.
pub(in crate::cmd::layout) fn table_columns(ds: &rustgis_data::Dataset, names: &[&str], held: &[String]) -> Result<Vec<String>, String> {
let mut taken = std::collections::HashSet::new();
names
.iter()
.map(|name| {
let at = rustgis_map::layout::table_field(ds, name);
let (i, field) =
at.and_then(|i| ds.fields.get(i).map(|f| (i, f))).ok_or_else(|| format!("no field '{name}' in {}", ds.name))?;
if !taken.insert(i) {
return Err(format!("fields names '{}' twice", field.name));
.map(|&name| {
let exact = ds.fields.iter().find(|f| f.name == name);
let field = match exact {
Some(f) => f.name.as_str(),
None if held.iter().any(|h| h == name) => name,
None => rustgis_map::layout::table_field(ds, name)
.and_then(|i| ds.fields.get(i))
.map(|f| f.name.as_str())
.ok_or_else(|| format!("no field '{name}' in {}", ds.name))?,
};
if !taken.insert(field) {
return Err(format!("fields names '{field}' twice"));
}
Ok(field.name.clone())
Ok(field.to_string())
})
.collect()
}
Expand Down Expand Up @@ -585,7 +593,7 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu
let layer = frame_layer_name(s, l, frame, p)?;
let rows = table_rows(p)?.unwrap_or(12);
let fields = match table_fields(p)? {
Some(names) => table_columns(frame_dataset(s, l, frame, &layer).ok_or("no such layer")?, &names)?,
Some(names) => table_columns(frame_dataset(s, l, frame, &layer).ok_or("no such layer")?, &names, &[])?,
None => Vec::new(),
};
let text_size = text_size_param(p, "textSize", TABLE_TEXT_PT)?.unwrap_or(TABLE_TEXT_PT);
Expand Down
6 changes: 4 additions & 2 deletions crates/engine/src/cmd/layout/update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -981,10 +981,12 @@ fn table_update(
checked: Option<&(String, Option<String>)>,
) -> Result<Option<Vec<String>>, String> {
let Some(l) = s.project.layouts.get(li) else { return Ok(None) };
let Some(ElementKind::Table { frame, .. }) = l.element(id).map(|e| &e.kind) else { return Ok(None) };
let Some(ElementKind::Table { frame, layer: shown, fields, .. }) = l.element(id).map(|e| &e.kind) else { return Ok(None) };
let Some(names) = table_fields(p)? else { return Ok(None) };
let Some((layer, _)) = checked else { return Err("fields need the table's layer".into()) };
Ok(Some(table_columns(frame_dataset(s, l, *frame, layer).ok_or("no such layer")?, &names)?))
// Another layer's fields aren't held for this one.
let held: &[String] = if layer.eq_ignore_ascii_case(shown) { fields } else { &[] };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
Ok(Some(table_columns(frame_dataset(s, l, *frame, layer).ok_or("no such layer")?, &names, held)?))
}

/// Validates a table/chart's effective layer and field before mutation; input binding uses this same choice.
Expand Down
39 changes: 39 additions & 0 deletions crates/engine/src/tests/layout_table.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,45 @@ fn a_field_the_layer_does_not_have_or_named_twice_is_refused() {
}
}

/// A field removed after the table chose it keeps its column through later changes of the list;
/// a name the table doesn't hold is still refused (#3409).
#[test]
fn a_field_the_table_holds_stays_in_a_new_list_after_the_layer_loses_it() {
let (mut s, id) = tabled();
let [b, a] = two_fields(&s);
update(&mut s, id, json!({"fields": [b, a]})).unwrap();
s.run("edit.deleteField", &json!({"layer": "Countries", "field": b})).unwrap();
update(&mut s, id, json!({"fields": [a, b]})).unwrap();
assert_eq!(table(&s, id)["fields"], json!([a, b]));
// Only as the table spells it, once, and no other name the layer lacks.
for (fields, said) in [(json!([a, b.to_uppercase()]), "no field"), (json!([b, b]), "twice"), (json!([b, "nope"]), "no field 'nope'")] {
refused(&mut s, "layout.update", json!({"element": id, "fields": fields}), said);
}
// A new table, or another layer, holds no such name.
refused(&mut s, "layout.addElement", json!({"kind": "table", "layer": "Countries", "fields": [b]}), "no field");
refused(&mut s, "layout.update", json!({"element": id, "layer": "Cities", "fields": [b]}), "no field");
update(&mut s, id, json!({"fields": [a]})).unwrap();
refused(&mut s, "layout.update", json!({"element": id, "fields": [a, b]}), "no field");
}

/// A field added under another case isn't the one a table lost: its column stays as it is, as it
/// is drawn, while a name the table doesn't hold is still read in any case (#3409).
#[test]
fn a_lost_column_is_not_given_to_a_field_of_another_case() {
let (mut s, id) = tabled();
let [b, a] = two_fields(&s);
update(&mut s, id, json!({"fields": [b, a]})).unwrap();
s.run("edit.deleteField", &json!({"layer": "Countries", "field": b})).unwrap();
let other = b.to_uppercase();
s.run("edit.addField", &json!({"layer": "Countries", "name": other, "type": "text"})).unwrap();
update(&mut s, id, json!({"fields": [a, b]})).unwrap();
assert_eq!(table(&s, id)["fields"], json!([a, b]));
update(&mut s, id, json!({"fields": [b, other]})).unwrap();
assert_eq!(table(&s, id)["fields"], json!([b, other]));
update(&mut s, id, json!({"fields": [a.to_uppercase()]})).unwrap();
assert_eq!(table(&s, id)["fields"], json!([a]));
}

#[test]
fn fields_of_the_wrong_type_are_refused() {
let (mut s, id) = tabled();
Expand Down
2 changes: 2 additions & 0 deletions crates/ui-egui/src/layoutview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ mod refused_tests;
mod section;
mod snap;
#[cfg(test)]
mod table_tests;
#[cfg(test)]
mod tests;

pub(crate) use actions::locked_delete;
Expand Down
2 changes: 2 additions & 0 deletions crates/ui-egui/src/layoutview/format.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! The Format pane of the selected layout element; each element's own rows are in its file under `format/`.

mod chart;
mod checklist;
mod colorbar;
mod frame;
mod legend;
Expand Down Expand Up @@ -364,6 +365,7 @@ pub(super) fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li:
});
text_section(app, ui, layout, li, &e, &update);
legend_layers(app, ui, layout, li, &e, &update);
table_columns(app, ui, layout, &e, &update);
frame_sections(app, ui, layout, li, &e, &update);
// Its background (#2257): a box behind its content, which a map frame, drawing its own paper,
// doesn't take.
Expand Down
240 changes: 240 additions & 0 deletions crates/ui-egui/src/layoutview/format/checklist.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,240 @@
//! A section of named rows to tick and to move up or down, below an element's grid: a legend's
//! layers and a table's fields (#3409).

use egui::{Ui, vec2};

/// Over this many rows, the section has a box that filters them by name.
const FILTER_OVER: usize = 8;

/// The height its rows scroll in, in points.
const LIST_HEIGHT: f32 = 320.0;

/// A row of the section.
pub(super) struct Row {
/// What its arrows are named for.
pub(super) name: String,
/// What its focus and its expansion follow as it moves: one per row.
pub(super) key: String,
/// What its checkbox shows.
pub(super) text: String,
/// Another text the filter finds it by, besides its name; empty for none.
pub(super) also: String,
pub(super) ticked: bool,
/// Whether ▲ and ▼ move it, past other movable rows.
pub(super) movable: bool,
}

/// What the section says and allows. Its texts come translated.
pub(super) struct Spec<'a> {
pub(super) title: &'a str,
/// What its ids come from: one per layout and element.
pub(super) id: egui::Id,
pub(super) open: bool,
pub(super) filter: &'a str,
pub(super) no_match: &'a str,
pub(super) tick: &'a str,
pub(super) select_all: &'a str,
pub(super) select_none: &'a str,
/// Reset's hover, while there is something to put back.
pub(super) reset: Option<&'a str>,
/// One row at least stays ticked.
pub(super) keep_one: bool,
}

/// What the section was asked for, by the rows' places.
pub(super) enum Pick {
/// A row ticked (true) or unticked.
Tick(usize, bool),
/// Every row shown, ticked or unticked.
Shown(Vec<usize>, bool),
/// Two rows to change places, the upper first.
Swap(usize, usize),
Reset,
}

/// What a row opens below itself.
pub(super) struct Details<'a> {
/// The hovers of its arrow, closed and open.
pub(super) show: &'a str,
pub(super) hide: &'a str,
/// The name of its arrow, open or closed, for the row named.
pub(super) named: &'a dyn Fn(bool, &str) -> String,
/// Draws what the row at this place opens.
pub(super) body: &'a mut dyn FnMut(&mut Ui, usize),
}

/// `text` as the filter compares it: lower case a character at a time, as `str::to_lowercase`
/// turns a capital sigma into one letter or another by its place, and the final sigma as the other.
fn folded(text: &str) -> String {
text.chars().flat_map(char::to_lowercase).map(|c| if c == 'ς' { 'σ' } else { c }).collect()
}

/// The section: collapsible, its filter, Select All and Select None, the rows and Reset. `rows`
/// is called only while it's open; what was asked for comes with the rows it was asked of.
pub(super) fn checklist(
ui: &mut Ui,
spec: &Spec<'_>,
rows: impl FnOnce() -> Vec<Row>,
mut details: Option<Details<'_>>,
) -> Option<(Pick, Vec<Row>)> {
let mut pick = None;
ui.add_space(4.0);
let shown_rows = egui::CollapsingHeader::new(spec.title).id_salt(spec.id).default_open(spec.open).show(ui, |ui| {
let rows = rows();
// The filter is the view's, not the project's: kept by egui, and read only while its box
// shows, so a list grown short again hides nothing.
let mut needle = String::new();
if rows.len() > FILTER_OVER {
let key = spec.id.with("filter");
let mut text = ui.data(|d| d.get_temp::<String>(key)).unwrap_or_default();
let r = ui.add(egui::TextEdit::singleline(&mut text).hint_text(spec.filter).desired_width(f32::INFINITY));
// Named once typed in too, when its hint is gone.
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, spec.filter));
needle = folded(text.trim());
ui.data_mut(|d| d.insert_temp(key, text));
}
// The places of the rows shown.
let found = |r: &Row| needle.is_empty() || folded(&r.name).contains(&needle) || folded(&r.also).contains(&needle);
let shown: Vec<usize> = rows.iter().enumerate().filter(|(_, r)| found(r)).map(|(i, _)| i).collect();
if !needle.is_empty() && shown.is_empty() {
ui.label(spec.no_match);
}
let ticked = rows.iter().filter(|r| r.ticked).count();
// Every row shown at once, the matches alone under a filter.
if !shown.is_empty() {
ui.horizontal(|ui| {
let visible = || shown.iter().filter_map(|&i| rows.get(i));
let some_out = visible().any(|r| !r.ticked);
let ticked_shown = visible().filter(|r| r.ticked).count();
let may_untick = ticked_shown > 0 && (!spec.keep_one || ticked_shown < ticked);
if ui.add_enabled(some_out, egui::Button::new(tl!("Select All"))).on_hover_text(spec.select_all).clicked() {
pick = Some(Pick::Shown(shown.clone(), true));
}
if ui.add_enabled(may_untick, egui::Button::new(tl!("Select None"))).on_hover_text(spec.select_none).clicked() {
pick = Some(Pick::Shown(shown.clone(), false));
}
});
}
// The places a row swaps with the one shown above or below it.
let mut swap = None;
let movable = |&&j: &&usize| rows.get(j).is_some_and(|r| r.movable);
// A bar beside the rows, not floating over their arrows.
ui.scope(|ui| {
ui.spacing_mut().scroll = egui::style::ScrollStyle::solid();
egui::ScrollArea::vertical().id_salt(spec.id.with("scroll")).max_height(LIST_HEIGHT).auto_shrink([false, true]).show(
ui,
|ui| {
for (k, (i, row)) in shown.iter().filter_map(|&i| rows.get(i).map(|r| (i, r))).enumerate() {
// A row that doesn't move looks for neither: a table's fields can be many.
let above = row.movable.then(|| shown.iter().take(k).rev().find(movable).copied()).flatten();
let below = row.movable.then(|| shown.iter().skip(k + 1).find(movable).copied()).flatten();
// Ids from the row's key, not its place (`push_id` would mix it in), so the
// keyboard's focus and the row's expansion move with it.
let row_id = ui.make_persistent_id(&row.key);
ui.scope_builder(egui::UiBuilder::new().scope_id(row_id), |ui| {
let mut opened =
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), row_id.with("details"), false);
// The arrows on the right, the name in what they leave.
let size = vec2(ui.available_width(), ui.spacing().interact_size.y);
ui.allocate_ui_with_layout(size, egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Named for its row, so each row's arrows tell apart to a screen reader.
let arrow = |ui: &mut Ui, glyph: &str, on: bool, hover: &str, label: String| {
let r = ui.add_enabled(on, egui::Button::new(glyph).small());
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, &label));
r.on_hover_text(hover).clicked()
};
let args = [("name", row.name.as_str())];
if arrow(ui, "▼", below.is_some(), tl!("Move down"), crate::i18n::fmt("Move {name} down", &args)) {
swap = below.map(|j| (i, j));
}
if arrow(ui, "▲", above.is_some(), tl!("Move up"), crate::i18n::fmt("Move {name} up", &args)) {
swap = above.map(|j| (j, i));
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
if let Some(d) = &details {
let open = opened.is_open();
let (glyph, hover) = if open { ("▾", d.hide) } else { ("▸", d.show) };
let label = (d.named)(open, &row.name);
let toggle = ui.add(egui::Button::new(glyph).small().frame(false));
toggle.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label));
if toggle.on_hover_text(hover).clicked() {
opened.toggle(ui);
}
}
let mut on = row.ticked;
let free = !(spec.keep_one && row.ticked && ticked == 1);
if ui.add_enabled(free, egui::Checkbox::new(&mut on, &row.text)).on_hover_text(spec.tick).changed() {
pick = Some(Pick::Tick(i, on));
}
});
});
if let Some(d) = &mut details {
if opened.is_open() {
(d.body)(ui, i);
}
opened.store(ui.ctx());
}
});
}
},
);
});
if let Some((a, b)) = swap {
pick = Some(Pick::Swap(a, b));
}
if let Some(hover) = spec.reset
&& ui.button(tl!("Reset")).on_hover_text(hover).clicked()
{
pick = Some(Pick::Reset);
}
rows
});
pick.zip(shown_rows.body_returned)
}

#[cfg(test)]
mod tests {
use super::*;
use egui_kittest::kittest::Queryable;
use std::cell::Cell;
use std::rc::Rc;

/// A collapsed section builds no rows; opened, it does.
#[test]
fn a_collapsed_section_builds_no_rows() {
let built = Rc::new(Cell::new(0));
let count = built.clone();
let mut fonts = false;
let mut h = egui_kittest::Harness::new_ui(move |ui| {
if !fonts {
crate::theme::install_fonts(ui.ctx(), &[], None);
fonts = true;
return;
}
let spec = Spec {
title: "Rows",
id: egui::Id::unique("rows"),
open: false,
filter: "Filter",
no_match: "None",
tick: "Tick",
select_all: "All",
select_none: "None of them",
reset: None,
keep_one: false,
};
let rows = || {
count.set(count.get() + 1);
vec![Row { name: "a".into(), key: "a".into(), text: "a".into(), also: String::new(), ticked: true, movable: true }]
};
checklist(ui, &spec, rows, None);
});
h.run_steps(3);
assert_eq!(built.get(), 0);
h.get_by_label("Rows").click();
h.run_steps(10);
assert!(built.get() > 0);
assert!(h.query_by_label("a").is_some());
}
}
Loading
Loading