pdf-forms-w3: net change of 3 commits

- pdf-forms-w3: written from its sheet
- pdf-forms-w3: repair 1
- pdf-forms-w3: finished by an agent
This commit is contained in:
Dylan M. Taylor
2026-11-18 08:07:07 -05:00
parent 59d88050b1
commit 1e60f7ed9b
8 changed files with 247 additions and 42 deletions
-1
View File
@@ -205,7 +205,6 @@ fn drive_fixture(in_modal: bool) -> (craft_ui::testing::Fixture, std::rc::Rc<Ref
let body = |ui: &mut egui::Ui| {
let mut text = query.borrow().clone();
TextField::search("Search", Bind::bound(&mut text)).drives(list_id).show(ui);
// P3(pdf-forms-w3): CH-C24
let out = List::new("Names")
.id(list_id)
.select(SelectMode::Single)
@@ -390,7 +390,6 @@ impl<'a> ListManager<'a> {
list = list.empty(empty.clone());
}
if searchable {
// P3(pdf-forms-w3): L-70 — the closure gives several texts.
list = list.filter(&session.name, |at| vec![Label::from(entries[*at].name.clone())]);
}
let events = list
+87 -22
View File
@@ -14,7 +14,7 @@ use crate::primitives::HAlign;
use crate::runtime::env::{Env, Label};
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{ColumnKey, DisplayOrder, ItemSource, Metrics, Selection, SizeHint, SpanLayout};
use craft_i18n::matcher::Matcher;
use craft_i18n::matcher::{Matcher, Rank};
use egui::{Rect, Ui};
use std::borrow::Cow;
use std::hash::{DefaultHasher, Hash, Hasher};
@@ -34,8 +34,7 @@ pub struct DocumentRows {
impl DocumentRows {
/// Rows whose labels are document text in `font` at `size`, aligned `align`.
pub fn new(font: FontRef, size: f32, align: HAlign) -> Self {
let _ = (font, size, align);
todo!("FM-PF11a")
DocumentRows { font, size, align }
}
}
@@ -105,6 +104,8 @@ pub struct List<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// The kept rows are in order of how well they match the query.
#[prop]
ranked: bool,
/// The rows' labels are document text, set by `document_rows`.
document: Option<DocumentRows>,
}
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
@@ -128,15 +129,16 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
row_menu: false,
filter: None,
ranked: false,
document: None,
}
.label(label)
}
/// The rows' labels are document text at the document's font, size and alignment; UI text keeps its tokens.
#[must_use]
pub fn document_rows(self, rows: DocumentRows) -> Self {
let _ = rows;
todo!("FM-PF11a")
pub fn document_rows(mut self, rows: DocumentRows) -> Self {
self.document = Some(rows);
self
}
/// The options list of a value picker's popup (completions, number presets, `PopupList`): one selection, a click
@@ -155,16 +157,23 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
.listbox()
}
/// Only the rows whose `label` matches `query` reach the item step, folded for the scope's language (case and
/// accents ignored); an empty query keeps every row. The rows stamp folds in the query, so the lead starts over
/// on the first shown row and the layout rebuilds when the query changes. Sets the rows stamp.
/// Only the rows of which one of the `texts` matches `query` reach the item step, folded for the scope's language
/// (case and accents ignored); a row ranks by its best matching text. An empty query keeps every row.
///
/// A `ranked` list shows the matches alone, best first. Any other list keeps its display order and, with each
/// match, the rows it sits under: its ancestors in a tree and the section row heading it. A section row with no
/// match under it goes; a section row never matches by its own text. The row whose rename runs stays, so it is
/// named in place, with its ancestors and heading.
///
/// The rows stamp folds in the query, so the lead starts over on the first shown row and the layout rebuilds when
/// the query changes. Sets the rows stamp.
#[must_use]
pub fn filter(mut self, query: &str, texts: impl Fn(&K) -> Vec<Label> + 'a) -> Self {
let query = query.trim();
let mut hasher = DefaultHasher::new();
query.hash(&mut hasher);
self.items = self.items.rows_stamp(hasher.finish());
self.filter = Some(Filter { query: query.to_owned(), label: Box::new(texts) });
self.filter = Some(Filter { query: query.to_owned(), texts: Box::new(texts) });
self
}
@@ -227,23 +236,27 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
&self.items
}
fn filtered<'s>(&self, source: &'s dyn ItemSource<K>, env: &Env) -> Option<Box<dyn ItemSource<K> + 's>> {
fn filtered<'s>(&self, source: &'s dyn ItemSource<K>, env: &Env, kept: Option<&K>) -> Option<Box<dyn ItemSource<K> + 's>> {
let filter = self.filter.as_ref()?;
let matcher = Matcher::new(&env.folder(), &filter.query);
if matcher.is_empty() {
return None;
}
let mut kept: Vec<(craft_i18n::matcher::Rank, usize)> = (0..source.len())
.filter_map(|at| {
// P3(pdf-forms-w3): CH-C24: a row matches by the best rank of any of its texts.
let texts = (filter.label)(&source.key(at));
texts.iter().filter_map(|text| matcher.score(text.resolved(&env.words).as_str())).map(|found| found.rank).min().map(|rank| (rank, at))
})
let mut matches: Vec<(Rank, usize)> = (0..source.len())
.filter(|&at| !source.is_section(at))
.filter_map(|at| filter.rank(&matcher, &source.key(at), env).map(|rank| (rank, at)))
.collect();
let renamed = kept.and_then(|key| source.index_of(key)).filter(|at| !matches.iter().any(|(_, held)| held == at));
if self.ranked {
kept.sort_by_key(|(rank, _)| *rank);
matches.sort_by_key(|(rank, _)| *rank);
let at = matches.into_iter().map(|(_, at)| at).chain(renamed).collect();
return Some(Box::new(Filtered { source, at }));
}
Some(Box::new(Filtered { source, at: kept.into_iter().map(|(_, at)| at).collect() }))
let mut hit = vec![false; source.len()];
for at in matches.into_iter().map(|(_, at)| at).chain(renamed) {
hit[at] = true;
}
Some(Box::new(Filtered { source, at: with_context(source, &hit) }))
}
fn selection(&mut self) -> Option<BindMut<'_, Selection<K>>> {
@@ -264,10 +277,22 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
}
fn dress<'r>(&self, row: Self::Item<'r>, state: &RowState) -> Self::Item<'r> {
let row = row.rows(self.items.row_height).sub_row(state);
let row = row.rows(self.items.row_height).sub_row(state).document(self.document.clone());
if self.row_menu { row.row_menu() } else { row }
}
/// The row menu and the document text, which `dress` gives every row.
fn dress_inputs(&self) -> u64 {
let mut hasher = DefaultHasher::new();
self.row_menu.hash(&mut hasher);
if let Some(document) = &self.document {
document.font.hash(&mut hasher);
document.size.to_bits().hash(&mut hasher);
(document.align as u8).hash(&mut hasher);
}
hasher.finish()
}
fn rename_draft(&self, key: &K) -> Option<String> {
self.rename_draft.as_ref().and_then(|draft| draft.text(key))
}
@@ -297,10 +322,50 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
}
}
/// What `List::filter` keeps: the query and how a row's key reads as text.
/// What `List::filter` keeps: the query and the texts a row's key matches by.
struct Filter<'a, K> {
query: String,
label: Box<dyn Fn(&K) -> Vec<Label> + 'a>,
texts: Box<dyn Fn(&K) -> Vec<Label> + 'a>,
}
impl<K> Filter<'_, K> {
/// The best rank of any text of `key`; `None` when none matches.
fn rank(&self, matcher: &Matcher, key: &K, env: &Env) -> Option<Rank> {
(self.texts)(key).iter().filter_map(|text| matcher.score(text.resolved(&env.words).as_str())).map(|found| found.rank).min()
}
}
/// The positions of `source` that are `hit`, in display order, with the rows each hit sits under: its ancestors, and
/// the section row heading it.
///
/// The ancestors of a row are the nearest preceding row with a smaller depth, then the nearest row before that with a
/// smaller depth still, down to the root: the threshold lowers at each step, so a sibling's subtree or an earlier root
/// is no ancestor. The rows a section heads are those after it up to the next section row, whatever their depth: a
/// flat source with section rows gives its headings no depth.
fn with_context<K>(source: &dyn ItemSource<K>, hit: &[bool]) -> Vec<usize> {
let mut shown = vec![false; hit.len()];
// The chain of rows above the current one whose depths fall strictly toward the root, as (depth, position).
let mut path: Vec<(usize, usize)> = Vec::new();
let mut heading = None;
for (at, &is_hit) in hit.iter().enumerate() {
let depth = source.depth(at);
while path.last().is_some_and(|&(above, _)| above >= depth) {
path.pop();
}
if source.is_section(at) {
heading = Some(at);
} else if is_hit {
shown[at] = true;
for &(_, above) in &path {
shown[above] = true;
}
if let Some(heading) = heading {
shown[heading] = true;
}
}
path.push((depth, at));
}
shown.iter().enumerate().filter(|(_, shown)| **shown).map(|(at, _)| at).collect()
}
/// The rows of `source` at the positions `at`, in that order.
+1 -1
View File
@@ -208,7 +208,7 @@ impl Component for ComboBox<'_> {
let selection = current.filter(|_| query.trim().is_empty()).map_or_else(Selection::default, Selection::single);
List::<usize>::options(name.clone())
.selection(Bind::given(selection))
.filter(&query, |key| vec![labels[*key].clone()]) // P3(pdf-forms-w3): CH-C24
.filter(&query, |key| vec![labels[*key].clone()])
.ranked(true)
.show_items(ui, &rows, &mut |key, _| rows.row(*key, current, decorate, None))
.events
+1 -1
View File
@@ -341,7 +341,7 @@ impl<T: Value + 'static> Component for Select<'_, T> {
.empty(words.no_matches.clone())
.selection(Bind::given(selection))
.lead_on_open(lead)
.filter(&query, |at| vec![labels[*at].clone()]) // P3(pdf-forms-w3): CH-C24
.filter(&query, |at| vec![labels[*at].clone()])
.show_items(ui, &rows, &mut |at, _| rows.row(*at, held, dress, picture))
.events
});
+8 -9
View File
@@ -50,21 +50,20 @@ impl<'a> PopupList<'a> {
/// Changes the popup's overlay as `Popover::overlay` does; callers hang the list from a part with
/// `Overlay::opener_anchor(Anchor::Rect(..))`.
#[must_use]
pub fn overlay(self, change: impl FnOnce(Overlay) -> Overlay) -> Self {
let _ = change;
todo!("FM-PF12")
}
/// The field the popup hangs from. The popup closes when the opener is no longer shown.
#[must_use]
pub fn opened_by(mut self, opener: &Response) -> Self {
pub fn overlay(mut self, change: impl FnOnce(Overlay) -> Overlay) -> Self {
let overlay = match std::mem::take(&mut self.props.mount) {
Mount::Layer(overlay) => overlay,
_ => Overlay::dropdown(),
};
self.props = self.props.mount(Mount::Layer(overlay.opened_by(opener, Trigger::Manual)));
self.props = self.props.mount(Mount::Layer(change(overlay)));
self
}
/// The field the popup hangs from. The popup closes when the opener is no longer shown.
#[must_use]
pub fn opened_by(self, opener: &Response) -> Self {
self.overlay(|overlay| overlay.opened_by(opener, Trigger::Manual))
}
}
impl Component for PopupList<'_> {
@@ -2,9 +2,12 @@
use super::PopupList;
use crate::buttons::Button;
use crate::contract::overlay::Anchor;
use crate::contract::{Bind, Show as _, ShowCollection as _, ShowContainer as _};
use crate::fonts::FontRef;
use crate::layout_components::Stack;
use crate::list::{List, ListRow};
use crate::list::{DocumentRows, List, ListRow};
use crate::primitives::HAlign;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_behavior::{DisplayOrder, ItemSource};
use egui::Ui;
@@ -52,3 +55,39 @@ fn popup_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
None => shown.output.into(),
}
}
/// The point size of a large document field's text.
const LARGE_DOCUMENT_SIZE: f32 = 24.0;
/// The point size of a document field's usual text.
const DOCUMENT_SIZE: f32 = 12.0;
/// A popup list of document rows hanging from a field inside a page: the page is the opener, the field's rect the
/// anchor, as a form field drawn on a document is.
fn document_popup(ui: &mut Ui, data: &mut StoryData, rows: DocumentRows) -> StoryOutput {
let names = ["Round", "Square", "Chisel", "Fan"];
let page = Stack::new().fill().show(ui, |ui, _| Button::new("Brush tip").show(ui).rect);
let field = page.inner.unwrap_or(page.output.rect);
PopupList::new("Brush tips", Bind::bound(data.value("open", true)))
.opened_by(&page.output)
.overlay(|overlay| overlay.opener_anchor(Anchor::Rect(field)))
.show(ui, |ui, _| {
List::<usize>::options("Brush tips")
.document_rows(rows.clone())
.show_items(ui, &Names(&names), &mut |key, _| ListRow::new(names[*key]).option());
})
.output
.response
.into()
}
/// Rows in a large document font, at the start edge.
#[story(PopupList<'static>, covers = [], drive = Drive::Never)]
fn popup_list_document_large(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
document_popup(ui, data, DocumentRows::new(FontRef::proportional(), LARGE_DOCUMENT_SIZE, HAlign::Start))
}
/// Rows in the document's font, centred as the field centres its value.
#[story(PopupList<'static>, covers = [], drive = Drive::Never)]
fn popup_list_document_centred(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
document_popup(ui, data, DocumentRows::new(FontRef::proportional(), DOCUMENT_SIZE, HAlign::Center))
}
+110 -6
View File
@@ -1,11 +1,17 @@
//! Popups: the dismissal rules.
//! Popups: the dismissal rules, and the wheel and keys of an open popup list.
use crate::overlay::kit::{Leaf, Opened, Opener, Seen};
use craft_ui::contract::{Overlay, Props as _, Show as _, Trigger};
use craft_ui::testing::pointer::{click, moved, press, release};
use craft_ui::testing::{Frames, trial};
use egui::{Pos2, Rect, Ui, Vec2};
use std::cell::RefCell;
use craft_behavior::{DisplayOrder, ItemSource};
use craft_ui::buttons::Button;
use craft_ui::contract::{Bind, CollectionEvent, Overlay, Props as _, Scroll, Show as _, ShowCollection as _, ShowContainer as _, Trigger, clicked};
use craft_ui::layout_components::Stack;
use craft_ui::list::{List, ListRow};
use craft_ui::popover::PopupList;
use craft_ui::testing::pointer::{self, click, moved, press, release};
use craft_ui::testing::{Fixture, Frames, trial};
use egui::{Key, Modifiers, Pos2, Rect, Ui, Vec2};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
const OPENER: Rect = Rect { min: Pos2::new(100.0, 100.0), max: Pos2::new(180.0, 120.0) };
const BELOW: Rect = Rect { min: Pos2::new(300.0, 300.0), max: Pos2::new(360.0, 330.0) };
@@ -70,3 +76,101 @@ fn a_click_on_the_opener_closes_its_open_menu() {
frames.idle(30, &mut show);
assert!(!opened.shown.get(), "the press on the opener reaches it, and its toggle closes the menu");
}
/// The rows of the popup list: more than its share of the window shows.
const ROWS: usize = 40;
/// The buttons below the opener: enough to make the page taller than the window.
const PAGE: usize = 40;
fn row(at: usize) -> String {
format!("Row {at}")
}
struct Rows;
impl DisplayOrder<usize> for Rows {
fn len(&self) -> usize {
ROWS
}
fn key(&self, at: usize) -> usize {
at
}
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
Some(std::borrow::Cow::Owned(row(at)))
}
}
impl ItemSource<usize> for Rows {}
/// A scrolling page taller than the window: an "Open" button that opens a popup list of `ROWS` rows while `open`, then
/// `PAGE` buttons. The rows the list activates go to `activated`.
fn page(open: Rc<Cell<bool>>, activated: Rc<RefCell<Vec<usize>>>) -> Fixture {
let mut fixture = Fixture::new(move |ui| {
Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| {
let opener = Button::new("Open").show(ui);
if clicked(&opener) {
open.set(true);
}
for at in 0..PAGE {
Button::new(format!("Page {at}")).show(ui);
}
let mut shown = open.get();
PopupList::new("Rows", Bind::bound(&mut shown)).opened_by(&opener).show(ui, |ui, _| {
let out = List::<usize>::options("Rows").show_items(ui, &Rows, &mut |at, _| ListRow::new(row(*at)).option());
activated.borrow_mut().extend(out.events.iter().filter_map(|event| match event {
CollectionEvent::Activate(at) => Some(*at),
_ => None,
}));
});
open.set(shown);
});
});
fixture.room(Vec2::new(600.0, 400.0)).settle();
fixture
}
/// The wheel over an open popup list scrolls the list and leaves the page below where it was; over the page, with the
/// list closed, the same wheel scrolls the page.
#[trial]
fn the_wheel_over_an_open_popup_list_scrolls_the_list_and_not_the_surface_below() {
let open = Rc::new(Cell::new(true));
let mut fixture = page(Rc::clone(&open), Rc::default());
let opener = fixture.by_label("Open").expect("the opener shows").rect;
let first = fixture.by_label(&row(0)).expect("the list shows its first row").rect;
let over = fixture.by_label(&row(2)).expect("the list shows its third row").rect.center();
fixture.frame(vec![pointer::moved(over)]);
for _ in 0..3 {
fixture.frame(vec![pointer::wheel(-60.0)]);
}
fixture.settle();
assert!(open.get(), "the wheel leaves the list open");
assert!(fixture.by_label(&row(0)).is_none_or(|shown| shown.rect.min.y < first.min.y - 1.0), "the wheel over the list scrolls it");
assert_eq!(fixture.by_label("Open").map(|shown| shown.rect), Some(opener), "the page below the list stays where it was");
open.set(false);
fixture.settle();
let on_page = fixture.by_label("Page 4").expect("the page shows its buttons").rect.center();
fixture.frame(vec![pointer::moved(on_page)]);
fixture.frame(vec![pointer::wheel(-60.0)]);
fixture.settle();
assert!(fixture.by_label("Open").is_none_or(|shown| shown.rect.min.y < opener.min.y - 1.0), "the wheel over the page scrolls it");
}
/// A pointer resting on the list keeps no hold on the lead: End scrolls another row under it, and Enter picks the row
/// End went to.
#[trial]
fn a_resting_pointer_leaves_the_lead_where_the_keys_moved_it() {
let open = Rc::new(Cell::new(false));
let activated = Rc::new(RefCell::new(Vec::new()));
let mut fixture = page(Rc::clone(&open), Rc::clone(&activated));
let opener = fixture.by_label("Open").expect("the opener shows");
fixture.click(&opener).settle();
assert!(open.get(), "a click on the opener opens the list");
let rest = fixture.by_label(&row(3)).expect("the list shows its fourth row").rect.center();
fixture.frame(vec![pointer::moved(rest)]).settle();
fixture.key(Key::End, Modifiers::NONE).settle();
fixture.key(Key::Enter, Modifiers::NONE).settle();
assert_eq!(*activated.borrow(), [ROWS - 1], "Enter picks the row End went to, not the one under the resting pointer");
}