One path row: PathRow, a path field and a Browse button that reports the press; ParamRows and Watermark ask with a PathRequest, PathField picks through the file service

This commit is contained in:
aiongg
2026-11-12 14:32:50 +00:00
parent 8de5a82799
commit b54195e805
9 changed files with 182 additions and 49 deletions
+10 -24
View File
@@ -2,12 +2,11 @@
use craft_behavior::{EditEvent, Mixed};
use craft_host::target::Caps;
use craft_host::{PickId, PickKind, PickRequest};
use craft_host::{PickId, PickRequest};
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Remember as _, ShowContainer as _, Validity};
use craft_ui::layout_components::Stack;
use craft_ui::patterns::form_dialogs::OutputPathRow;
use craft_ui::form::Field;
use craft_ui::patterns::form_dialogs::PathRow;
use craft_ui::runtime::env::{Env, Label, Message};
use craft_ui::runtime::requests::PathKind;
use egui::{Response, Ui};
use std::path::Path;
@@ -44,10 +43,10 @@ impl Outcome for PathFieldOutput {
}
}
/// A label, a text field with the path and a Browse button in one row, over the bound path. Typing commits on Enter or
/// focus loss; Browse queues `request` through `host.files()` and the answer fills the field on a later pass (the field
/// matches tickets, so several fields can browse in turn). Tab order: field, then Browse. With `must_exist` set, a path
/// that does not exist shows the not-found message under the field.
/// A label, then the path row (a text field with the path and a Browse button) over the bound path. Typing commits on
/// Enter or focus loss; Browse queues `request` through `host.files()` and the answer fills the field on a later pass
/// (the field matches tickets, so several fields can browse in turn). Tab order: field, then Browse. With `must_exist`
/// set, a path that does not exist shows the not-found message under the field.
#[must_use = "show the field with `show`"]
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
pub struct PathField<'a> {
@@ -70,11 +69,10 @@ impl<'a> PathField<'a> {
pub fn show(self, ui: &mut Ui) -> PathFieldOutput {
let PathField { label, value, request, must_exist } = self;
let words = Env::of(ui).words::<PathFieldWords>();
let kind = path_kind(&request);
let mut held = Held::new(value);
let mut edit = None;
let mut browsing = None;
let shown = Stack::new().show(ui, |ui, cx| {
let shown = Field::new(label.clone()).show(ui, |ui, cx| {
let before = held.read(cx).unwrap_or_default();
let host = cx.env.host().cloned();
let looks = must_exist && cx.env.shell().caps.contains(Caps::FILE_SYSTEM);
@@ -89,8 +87,8 @@ impl<'a> PathField<'a> {
cx.memory::<Ticket>().0 = None;
answered = picked.first_path().map(|path| path.to_string_lossy().into_owned());
}
let row = OutputPathRow::new(Bind::given(before.clone()).check(check)).label(label.clone()).kind(kind.clone()).key("path").show(ui);
if row.browse.is_some()
let row = PathRow::new(label.clone(), Bind::given(before.clone()).check(check)).show(ui);
if row.browse
&& let Some(host) = &host
{
let id = host.files().pick(request.clone());
@@ -123,18 +121,6 @@ impl<'a> PathField<'a> {
}
}
/// What Browse asks the output row to pick, from the host's request.
fn path_kind(request: &PickRequest) -> PathKind {
match request.kind {
PickKind::Folder => PathKind::Folder,
PickKind::Save => PathKind::SaveFile,
PickKind::Open | PickKind::OpenMany => {
let extensions: Vec<&str> = request.filters.iter().flat_map(|filter| filter.extensions.iter().map(String::as_str)).collect();
PathKind::open_file(&extensions)
}
}
}
/// Whether a non-empty `path` names nothing on disk. An empty field is not flagged.
fn path_is_missing(path: &str) -> bool {
!path.trim().is_empty() && !Path::new(path.trim()).exists()
+32 -1
View File
@@ -1,6 +1,6 @@
//! The file list, the path field and the picker tickets they keep, against a file service that records its requests.
use craft_dialogs::ui::{FileList, FileListPicker};
use craft_dialogs::ui::{FileList, FileListPicker, PathField};
use craft_host::{AppInfo, FileError, Files, Host, PickAnswer, PickId, PickRequest, Picked};
use craft_ui::contract::Bind;
use craft_ui::testing::{Fixture, trial};
@@ -107,3 +107,34 @@ fn browse_answer_is_taken_and_written_once() {
assert_eq!(names(&list.borrow()), ["a.png", "b.png"]);
assert_eq!(changes.get(), 1, "the answer is written to the binding once");
}
/// The path field's Browse queues a pick through the file service, and the answer lands in the field's path once.
#[trial]
fn path_field_browse_fills_the_path() {
let files = Arc::new(StubFiles::default());
let path = Rc::new(RefCell::new(String::new()));
let sets = Rc::new(Cell::new(0usize));
let ticket = Rc::new(Cell::new(None::<PickId>));
let (held, counted, issued) = (Rc::clone(&path), Rc::clone(&sets), Rc::clone(&ticket));
let mut fixture = Fixture::new(move |ui| {
let mut path = held.borrow_mut();
let out = PathField::new("PDF file", Bind::bound(&mut *path), PickRequest::open("import")).show(ui);
if out.browsing.is_some() {
issued.set(out.browsing);
}
if out.edit.is_some() {
counted.set(counted.get() + 1);
}
});
fixture.host(host_with(&files));
fixture.settle();
let browse = fixture.by_label("Browse…").expect("the Browse button");
fixture.click(&browse);
fixture.settle();
sets.set(0);
files.answer(ticket.get().expect("Browse issued a ticket"), Picked::Paths(paths(&["brochure.pdf"])));
fixture.idle(3);
assert_eq!(*path.borrow(), "/photos/brochure.pdf");
assert_eq!(sets.get(), 1, "the answer lands once");
}
@@ -14,6 +14,7 @@ pub use words::ParamWords;
mod dialog;
mod form;
mod host_requests;
mod path_row;
mod preview;
pub use dialog::{
@@ -21,6 +22,7 @@ pub use dialog::{
};
pub use form::{FormCx, FormDialog, FormOutput};
pub use host_requests::{HostRequests, PreviewRequest};
pub use path_row::{PathRow, PathRowOutput, PathRowWords};
pub use preview::{
PaneOverlay, PreviewOutput, PreviewPane, PreviewPaneStyle, PreviewState, PreviewView, PreviewWords, PreviewZoom, PreviewZoomOutput,
};
@@ -0,0 +1,80 @@
//! `PathRow`: a path typed in a text field, with a Browse button that asks the host to pick one.
#[cfg(feature = "testing")]
mod stories;
use crate::buttons::Button;
use crate::contract::{Bind, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
use crate::layout_components::Row;
use crate::runtime::env::{Env, Label};
use crate::text::TextField;
use craft_behavior::EditEvents;
use egui::{Response, Ui};
craft_ui::words! {
/// The words of the path row.
pub struct PathRowWords {
browse: "pathRow.browse" = "Browse…";
}
}
/// What a path row reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct PathRowOutput {
/// The row's response.
pub response: Response,
/// The text field's edits of the path in this pass; a given value is applied by the caller.
pub edit: EditEvents<String>,
/// Browse was pressed this pass: the host asks for a path by its own route and writes the answer into the value.
pub browse: bool,
}
impl Outcome for PathRowOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// A text field with the path, taking the row's room, and a Browse button after it, for a row whose enclosing `Field`
/// shows the label. Typing edits the bound path; the binding's check shows under the field (a file that is not there).
/// A press on Browse is reported, and the host files its pick request: a `PathRequest` in a form dialog, or a pick from
/// the host's file service. Tab order: the field, then Browse.
#[must_use = "show the row with `show`"]
#[derive(crate::contract::Pattern, crate::contract::Props)]
pub struct PathRow<'a> {
name: Label,
value: Bind<'a, String>,
/// The button's text; the words' "Browse…" without one.
#[prop(into)]
button: Option<Label>,
/// Shown in the empty field.
#[prop(into)]
placeholder: Option<Label>,
}
impl<'a> PathRow<'a> {
/// A row over the path `value`, its field named `name`.
pub fn new(name: impl Into<Label>, value: Bind<'a, String>) -> Self {
PathRow { name: name.into(), value, button: None, placeholder: None }
}
/// Shows the row.
pub fn show(self, ui: &mut Ui) -> PathRowOutput {
let PathRow { name, mut value, button, placeholder } = self;
let button = button.unwrap_or_else(|| Env::of(ui).words::<PathRowWords>().browse.clone());
let mut edit = EditEvents::new();
let mut browse = false;
let shown = Row::new().show(ui, |ui, _| {
let mut field = TextField::new(name.clone(), value.reborrowed()).fill_width(true).id_salt("path");
if let Some(placeholder) = placeholder.clone() {
field = field.placeholder(placeholder);
}
edit = field.show(ui).events;
browse = clicked(&Button::new(button.clone()).id_salt("browse").show(ui));
});
PathRowOutput { response: shown.output, edit, browse }
}
}
@@ -0,0 +1,26 @@
//! Stories of `PathRow`.
use super::PathRow;
use crate::contract::{Bind, ShowContainer as _};
use crate::form::Field;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
/// The row in its labelled field, over `path`.
fn row(ui: &mut Ui, path: &mut String) -> StoryOutput {
let mut shown = StoryOutput::default();
Field::new("Image").show(ui, |ui, _| {
shown = PathRow::new("Image", Bind::bound(&mut *path)).placeholder("No file chosen").show(ui).into();
});
shown
}
#[story(PathRow<'static>, covers = [Default], drive = Drive::Never)]
fn path_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
row(ui, data.value("path", "/photos/trip/sunrise.png".to_owned()))
}
#[story(PathRow<'static>, covers = [], drive = Drive::Never)]
fn path_row_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
row(ui, data.value("empty", String::new()))
}
@@ -4,6 +4,7 @@ use super::fields::{DialogFields, FieldValue};
use crate::runtime::requests::{ColorRequest, EyedropperRequest, PathRequest};
use super::param::{CustomContext, Param, ParamKind, fill_defaults, rounded};
use super::path_row::PathRow;
use super::words::ParamWords;
use crate::buttons::{Button, ToggleButton};
use crate::choice::{Checkbox, Radio, RadioGroup, Swatch};
@@ -546,20 +547,29 @@ impl<'p> Pass<'p> {
let value = self.work.text(line.key).unwrap_or(default).to_owned();
let browse = line.param.browse.clone();
line.show(ui, |ui| {
beside(ui, |ui| {
let mut field = TextField::new(line.name.clone(), Bind::given(value.clone())).id_salt("text");
if let Some(hint) = line.param.hint_text() {
field = field.placeholder(hint.clone());
let typed = match &browse {
Some(kind) => {
let mut row = PathRow::new(line.name.clone(), Bind::given(value.clone()));
if let Some(hint) = line.param.hint_text() {
row = row.placeholder(hint.clone());
}
let shown = row.show(ui);
if shown.browse {
self.path = Some(PathRequest::new(line.key, kind.clone()));
}
shown.edit.value().cloned()
}
if let Some(v) = field.show(ui).value().cloned() {
self.work.set(line.key, FieldValue::Text(v));
None => {
let mut field = TextField::new(line.name.clone(), Bind::given(value.clone())).id_salt("text");
if let Some(hint) = line.param.hint_text() {
field = field.placeholder(hint.clone());
}
field.show(ui).value().cloned()
}
if let Some(kind) = &browse
&& clicked(&Button::new(self.words.browse.clone()).id_salt("browse").show(ui))
{
self.path = Some(PathRequest::new(line.key, kind.clone()));
}
});
};
if let Some(v) = typed {
self.work.set(line.key, FieldValue::Text(v));
}
});
}
@@ -2,15 +2,14 @@
//! orientation, the position, the rotation, the size, the opacity, the insets and the shadow.
use super::host_requests::HostRequests;
use crate::buttons::Button;
use crate::choice::{Checkbox, Segmented};
use crate::runtime::requests::{IMAGE_EXTENSIONS, PathKind, PathRequest};
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
use crate::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _};
use crate::form::{Field, FieldGroup, SliderField, SliderFieldLayout};
use crate::layout_components::Row;
use super::path_row::PathRow;
use crate::pickers::{Anchor9, ReferencePoint, Select};
use crate::runtime::env::{Env, Label, UnitKind, Units};
@@ -239,14 +238,13 @@ fn rows(ui: &mut Ui, words: &WatermarkWords, units: &Units, now: &mut WatermarkS
match now.style.clone() {
WatermarkStyle::Graphic(path) => {
Field::new(words.image.clone()).id_salt("image").show(ui, |ui, _| {
Row::new().show(ui, |ui, _| {
if let Some(path) = TextField::new(words.image.clone(), Bind::given(path.clone())).id_salt("path").show(ui).value().cloned() {
now.style = WatermarkStyle::Graphic(path);
}
if clicked(&Button::new(words.choose.clone()).id_salt("choose").show(ui)) {
requests.request_path(PathRequest::new(WATERMARK_IMAGE_KEY, PathKind::open_file(&IMAGE_EXTENSIONS)));
}
});
let row = PathRow::new(words.image.clone(), Bind::given(path.clone())).button(words.choose.clone()).show(ui);
if let Some(path) = row.edit.value().cloned() {
now.style = WatermarkStyle::Graphic(path);
}
if row.browse {
requests.request_path(PathRequest::new(WATERMARK_IMAGE_KEY, PathKind::open_file(&IMAGE_EXTENSIONS)));
}
});
}
WatermarkStyle::Text(text) => {
@@ -4,7 +4,6 @@ craft_ui::words! {
/// The words of the parameter rows: the buttons and names a row adds beside its control. Each id is prefixed by
/// its module. `{name}` stands for the row's label, `{row}` and `{column}` for a grid cell's place.
pub struct ParamWords {
browse: "param.browse" = "Browse…";
randomize: "param.randomize" = "Random";
eyedropper: "param.eyedropper" = "Eyedropper";
custom: "param.custom" = "Custom";
+1
View File
@@ -84,6 +84,7 @@ Generated by `cargo run -p craft-ui-gallery --bin components-index`; edit the do
| `NavigatorOptionsDialog<'_>` | Pattern | `craft_ui_patterns::patterns::form_dialogs::navigator_options` | Panel Options of the Navigator: the colour of the proxy rectangle |
| `NewDocumentDialog<'_>` | Pattern | `craft_ui_patterns::patterns::form_dialogs::new_document` | File > New: category tabs over a grid of preset cards, a details column and Create and Close |
| `PasswordDialog<'_>` | Pattern | `craft_ui_patterns::patterns::form_dialogs::password` | A question with a lock icon, the message, the masked field and the buttons |
| `PathRow<'_>` | Pattern | `craft_ui_patterns::patterns::form_dialogs::path_row` | A text field with the path, taking the row's room, and a Browse button after it, for a row whose enclosing `Field` shows the label |
| `PdfExportDialog<'_>` | Pattern | `craft_ui_patterns::patterns::form_dialogs::pdf_export` | File > Save as PDF: a preset row, Standard and Compatibility, and a list of sections (General, Compression, Marks and Bleeds, Output, Advanced, Security and Summary) beside the shown section |
| `PreviewPane<'_>` | Leaf | `craft_ui_patterns::patterns::form_dialogs::preview` | A picture in a well, over a checkerboard where it is transparent |
| `PreviewZoom` | Pattern | `craft_ui_patterns::patterns::form_dialogs::preview` | The zoom row of a preview: a zoom-out button, the zoom as a percentage field and a zoom-in button |