shell-w5: net change of 1 commits

- shell-w5: written from its sheet
This commit is contained in:
bflatastic
2026-11-21 21:26:00 +07:00
parent af2629217c
commit e5e3b6a303
14 changed files with 192 additions and 50 deletions
+30 -6
View File
@@ -33,14 +33,15 @@ pub fn inspect(host: &DialogHost) -> Value {
/// Runs a `ui.dialog.*` method on `host`; `None` when `method` is not one of them.
///
/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]).
/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field,
/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]).
/// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field
/// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it.
/// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape
/// answer gives that answer, with its tag; any other dialog closes with its children with Cancel.
pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option<Result<Value, String>> {
let fields: &[&str] = match method {
"ui.dialog.set" => &["dialog", "field", "value"],
"ui.dialog.set" => &["dialog", "field", "value", "fields"],
"ui.dialog.confirm" => &["dialog", "choice"],
"ui.dialog.cancel" => &["dialog"],
_ => return None,
@@ -53,10 +54,18 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field
let read = Params(&params);
let id = dialog_id(host, &params)?;
match method {
"ui.dialog.set" => {
let field = read.str_field("field")?.ok_or("missing `field`")?;
host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?;
}
"ui.dialog.set" => match params.get("fields") {
Some(list) => {
if params.get("field").is_some() || params.get("value").is_some() {
return Err("`fields` takes the place of `field` and `value`".to_owned());
}
host.set_json_fields(ctx, id, &field_list(list)?)?;
}
None => {
let field = read.str_field("field")?.ok_or("missing `field`")?;
host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?;
}
},
"ui.dialog.confirm" => {
if let Some(choice) = params.get("choice") {
host.set_json_field(ctx, id, "choice", choice.clone())?;
@@ -84,6 +93,21 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field
Ok(Value::Null)
}
/// The `(field, value)` pairs of a `fields` list, checked whole before anything is set; a missing `value` is `null`.
fn field_list(list: &Value) -> Result<Vec<(String, Value)>, String> {
let items = list.as_array().ok_or("`fields` is not a list")?;
if items.len() > MAX_DIALOG_FIELDS {
return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len()));
}
items
.iter()
.map(|item| {
let field = item.get("field").and_then(Value::as_str).ok_or("an item of `fields` has no string `field`")?;
Ok((field.to_owned(), item.get("value").cloned().unwrap_or(Value::Null)))
})
.collect()
}
/// The open dialog `params.dialog` names: the id `inspect` lists, as a decimal string or a number, or `"top"` for the
/// top dialog of the stack.
pub fn dialog_id(host: &DialogHost, params: &Value) -> Result<DialogId, String> {
+36 -1
View File
@@ -1,6 +1,6 @@
//! `ui.dialog.*` on typed dialogs through one generic path.
use craft_automation::dialogs::{dialog_method, inspect};
use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect};
use craft_ui::contract::{Bind, SaveKey};
use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt};
use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind};
@@ -124,6 +124,41 @@ fn param_dialog_automation_follows_its_rows() {
assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom")));
}
/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that
/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread.
#[trial]
fn a_field_list_sets_every_field_or_none_and_has_a_limit() {
let ctx = Context::default();
let mut host = DialogHost::new();
host.open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| {
ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#)).values(Bind::bound(fields))
}));
let id = inspect(&host)[0]["id"].clone();
let fields = |host: &DialogHost| inspect(host)[0]["fields"].clone();
let set = |host: &mut DialogHost, params: Value| call(host, &ctx, "ui.dialog.set", params);
let listed = json!([{"field": "radius", "value": 4.5}, {"field": "method", "value": "zoom"}]);
assert_eq!(set(&mut host, json!({"dialog": id, "fields": listed})), Ok(Value::Null));
let settled = fields(&host);
assert_eq!((settled["radius"].as_f64(), &settled["method"]), (Some(4.5), &json!("zoom")));
let refused = json!([{"field": "radius", "value": 9}, {"field": "radius", "value": 5000}, {"field": "method", "value": "spin"}]);
assert!(set(&mut host, json!({"dialog": id, "fields": refused})).is_err_and(|e| e.contains("radius")));
assert_eq!(fields(&host), settled, "a refusal in the middle sets nothing");
let too_many: Vec<Value> = (0..=MAX_DIALOG_FIELDS).map(|_| json!({"field": "radius", "value": 2})).collect();
assert!(set(&mut host, json!({"dialog": id, "fields": too_many})).is_err());
assert_eq!(fields(&host), settled, "a list over the limit sets nothing");
let unnamed = json!([{"field": "radius", "value": 9}, {"value": 1}]);
assert!(set(&mut host, json!({"dialog": id, "fields": unnamed})).is_err());
assert_eq!(fields(&host), settled, "an item without a field sets nothing");
let both = json!({"dialog": id, "field": "radius", "value": 9, "fields": [{"field": "radius", "value": 8}]});
assert!(set(&mut host, both).is_err());
assert_eq!(fields(&host), settled, "`field` beside `fields` sets nothing");
}
/// `"top"` names the top dialog of the stack: a child over its parent takes the field, the parent keeps its own; with
/// nothing open the request says so.
#[trial]
@@ -17,10 +17,10 @@ use crate::contract::{
ShowCollection as _, ShowContainer as _, clicked,
};
use crate::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
use crate::display::{Divider, Shade, Text};
use crate::display::{Divider, Picture, PictureSize, Shade, Text};
use crate::layout::RowAlign;
use crate::layout_components::{Row, Stack};
use crate::list::ListRow;
use crate::list::{ListRow, ThumbSize};
use crate::pickers::Select;
use crate::runtime::env::{Env, Label};
use crate::runtime::overlay::CloseReason;
@@ -275,6 +275,9 @@ impl<'a> AboutDialog<'a> {
}
}
/// The texture key of the app's mark; the dialog shows one mark.
const ICON_KEY: u64 = 0xAB07_1C0E;
/// What the tabs read while the dialog shows them.
struct Shown<'s> {
words: &'s AboutWords,
@@ -312,6 +315,13 @@ impl Shown<'_> {
fn about(&self, ui: &mut Ui, link: &RefCell<Option<String>>) {
let (words, info) = (self.words, self.info);
Stack::new().show(ui, |ui, _| {
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
if let Some(icon) = &info.icon {
let image = || (**icon).clone();
Picture::new(info.app_name.clone(), ICON_KEY, &image).extent(PictureSize::Thumb(ThumbSize::Medium)).show(ui);
}
Text::new(info.app_name.clone()).role(TypeRole::Title).show(ui);
});
Text::new(info.blurb.clone()).show(ui);
Text::new(words.version.fill(&[("version", info.version.as_str())])).show(ui);
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
@@ -79,9 +79,9 @@ impl AboutInfo {
/// The application's mark, shown at the start of the About tab's header row.
#[must_use]
pub fn icon(self, image: Arc<egui::ColorImage>) -> Self {
let _ = (self, image);
todo!("sh.K26")
pub fn icon(mut self, image: Arc<egui::ColorImage>) -> Self {
self.icon = Some(image);
self
}
}
@@ -3,14 +3,27 @@
use super::{AboutDialog, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use crate::dialog::stories::hosted;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
use std::sync::LazyLock;
use egui::{Color32, ColorImage, Ui};
use std::sync::{Arc, LazyLock};
fn info(community: bool) -> AboutInfo {
let info = AboutInfo::new("PhotoCraft", "An open-source, native image editor written in Rust.", "0.42.1 (a1b2c3d, 2026-10-30)")
/// A diagonal gradient standing for the app's mark.
fn mark() -> Arc<ColorImage> {
const SIDE: usize = 32;
let pixels = (0..SIDE * SIDE).map(|at| Color32::from_rgb((at % SIDE * 255 / SIDE) as u8, (at / SIDE * 255 / SIDE) as u8, 160)).collect();
Arc::new(ColorImage::new([SIDE, SIDE], pixels))
}
fn info(community: bool, with_mark: bool) -> AboutInfo {
let mut info = AboutInfo::new("PhotoCraft", "An open-source, native image editor written in Rust.", "0.42.1 (a1b2c3d, 2026-10-30)")
.links([AboutLink::new("Website", "https://example.org"), AboutLink::new("Source", "https://example.org/source")])
.built_with("egui · wgpu");
if community { info.community(AboutLink::new("Join us on Discord", "https://discord.example/join")) } else { info }
if community {
info = info.community(AboutLink::new("Join us on Discord", "https://discord.example/join"));
}
if with_mark {
info = info.icon(mark());
}
info
}
const TABS: [(&str, AboutTab); 3] = [("About", AboutTab::About), ("Contributors", AboutTab::Contributors), ("Models", AboutTab::Models)];
@@ -36,12 +49,13 @@ static CREDITS: LazyLock<Credits> = LazyLock::new(|| {
fn about_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let tab = *data.choice("tab", AboutTab::About, &TABS);
let community = *data.value("community_button", true);
hosted(ui, data, (tab, community), || HostedAbout::new(info(community), CREDITS.clone()).tab(tab))
let mark = *data.value("mark", true);
hosted(ui, data, (tab, community, mark), || HostedAbout::new(info(community, mark), CREDITS.clone()).tab(tab))
}
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never)]
fn about_dialog_contributors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let tab = *data.choice("tab", AboutTab::Contributors, &TABS);
let community = *data.value("community_button", true);
hosted(ui, data, (tab, community), || HostedAbout::new(info(community), CREDITS.clone()).tab(tab))
hosted(ui, data, (tab, community), || HostedAbout::new(info(community, false), CREDITS.clone()).tab(tab))
}
@@ -161,7 +161,7 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
}
fn nested(&mut self, ui: &mut Ui) {
self.custom.nested(ui, &mut self.draft); // P3(shell-w5): sh.K30
self.custom.nested(ui, &mut self.draft);
}
fn nested_open(&self) -> bool {
@@ -223,10 +223,8 @@ impl<T: Serialize + DeserializeOwned + Default + Clone + PartialEq, C: CustomSet
let value = lookup(&self.draft.table, &row.key);
let kind = match (&row.shape, value) {
(Shape::Bool, Some(Value::Boolean(on))) => RowKind::Bool(*on),
// P3(shell-w5): sh.K32
(Shape::Int { range, unit }, Some(Value::Integer(n))) => RowKind::Int { value: *n, range: range.clone(), unit: *unit, unit_text: None },
(Shape::Float { range, decimals, unit }, Some(Value::Float(x))) => {
// P3(shell-w5): sh.K32
RowKind::Float { value: *x, range: range.clone(), decimals: *decimals, unit: *unit, unit_text: None }
}
(Shape::Text, Some(Value::String(text))) => RowKind::Text(text),
@@ -246,9 +246,11 @@ impl<'a> RowKind<'a> {
/// A translated unit shown after an integer or number field, for quantities with no `UnitKind`; other kinds
/// ignore it.
#[must_use]
pub fn unit_text(self, text: &'a str) -> Self {
let _ = (self, text);
todo!("sh.K32")
pub fn unit_text(mut self, text: &'a str) -> Self {
if let RowKind::Int { unit_text, .. } | RowKind::Float { unit_text, .. } = &mut self {
*unit_text = Some(text);
}
self
}
/// What an integer or number field counts, shown after it, or what the ids of a choice count (the choice labels its
@@ -7,7 +7,7 @@ use crate::contract::{Bind, Entry, FieldLayout, Props as _, Show as _, ShowConta
use crate::form::{Field, Help};
use crate::layout_components::{Row, Stack};
use crate::pickers::Select;
use crate::runtime::env::{Label, UnitKind, Units};
use crate::runtime::env::{Label, LengthUnits, UnitKind, Units};
use crate::runtime::requests::ColorRequest;
use crate::text::{HexField, NumberField, TextField};
use craft_behavior::NumberCodec;
@@ -31,8 +31,9 @@ pub(super) enum Kind {
Bool(bool),
Choice { value: String, options: Vec<Entry<String>>, unit: Option<UnitKind> },
Color(Rgba),
Int { value: i64, range: RangeInclusive<i64>, unit: Option<UnitKind> },
Float { value: f64, range: RangeInclusive<f64>, decimals: u8, step: Option<f64>, unit: Option<UnitKind> },
Int { value: i64, range: RangeInclusive<i64>, unit: Option<UnitKind>, unit_text: Option<Label> },
Float { value: f64, range: RangeInclusive<f64>, decimals: u8, step: Option<f64>, unit: Option<UnitKind>, unit_text: Option<Label> },
Length { value: f64, range: RangeInclusive<f64>, lengths: LengthUnits },
Text(String),
Custom,
}
@@ -53,12 +54,19 @@ impl ShownRow {
.collect(),
},
RowKind::Color(color) => Kind::Color(*color),
RowKind::Int { value, range, unit, .. } => Kind::Int { value: *value, range: range.clone(), unit: *unit },
RowKind::Float { value, range, decimals, unit, .. } => {
Kind::Float { value: *value, range: range.clone(), decimals: *decimals, step: row.step, unit: *unit }
RowKind::Int { value, range, unit, unit_text } => {
Kind::Int { value: *value, range: range.clone(), unit: *unit, unit_text: unit_text.map(|text| Label::from(text.to_owned())) }
}
RowKind::Float { value, range, decimals, unit, unit_text } => Kind::Float {
value: *value,
range: range.clone(),
decimals: *decimals,
step: row.step,
unit: *unit,
unit_text: unit_text.map(|text| Label::from(text.to_owned())),
},
RowKind::Length { value, range, lengths } => Kind::Length { value: *value, range: range.clone(), lengths: *lengths },
RowKind::Text(text) => Kind::Text((*text).to_owned()),
RowKind::Length { .. } => todo!("sh.K31"),
RowKind::Custom => Kind::Custom,
};
Self {
@@ -86,8 +94,13 @@ pub(super) fn step_for(range: &RangeInclusive<f64>, decimals: u8) -> f64 {
if decimals == 0 || range.end() - range.start() >= 10.0 { 1.0 } else { 10f64.powi(-i32::from(decimals)) }
}
fn number(units: &Units, label: &Label, value: f64, unit: Option<UnitKind>, decimals: usize) -> NumberField<'static> {
NumberField::new(label.clone(), Bind::given(Some(value))).codec(NumberCodec::new(units.reader(unit), decimals))
/// A number field over `value`. A counted `unit` wins over `unit_text`, which is for quantities with no `UnitKind`.
fn number(units: &Units, label: &Label, value: f64, unit: Option<UnitKind>, unit_text: Option<&Label>, decimals: usize) -> NumberField<'static> {
let field = NumberField::new(label.clone(), Bind::given(Some(value))).codec(NumberCodec::new(units.reader(unit), decimals));
match unit_text {
Some(text) if unit.is_none() => field.unit(text.clone()),
_ => field,
}
}
/// `option` labelled as its id counted in `kind`; an option whose id is not a number keeps its label.
@@ -137,24 +150,33 @@ pub(super) fn show_row<H: PreferencesModel + ?Sized>(ui: &mut Ui, host: &mut H,
});
record(next.map(PrefValue::Choice));
}
Kind::Int { value, range, unit } => {
Kind::Int { value, range, unit, unit_text } => {
let mut next = None;
field().show(ui, |ui, _| {
let shown = number(units, label, *value as f64, *unit, 0).range(*range.start() as f64..=*range.end() as f64).step(1.0);
let shown =
number(units, label, *value as f64, *unit, unit_text.as_ref(), 0).range(*range.start() as f64..=*range.end() as f64).step(1.0);
next = shown.show(ui).edit.events.landed().cloned().flatten();
});
record(next.map(|v| PrefValue::Int(v.round() as i64)));
}
Kind::Float { value, range, decimals, step, unit } => {
Kind::Float { value, range, decimals, step, unit, unit_text } => {
let mut next = None;
field().show(ui, |ui, _| {
let shown = number(units, label, *value, *unit, usize::from(*decimals))
let shown = number(units, label, *value, *unit, unit_text.as_ref(), usize::from(*decimals))
.range(range.clone())
.step(step.unwrap_or_else(|| step_for(range, *decimals)));
next = shown.show(ui).edit.events.landed().cloned().flatten();
});
record(next.map(PrefValue::Float));
}
Kind::Length { value, range, lengths } => {
let mut next = None;
field().show(ui, |ui, _| {
let shown = NumberField::length(label.clone(), Bind::given(Some(*value)), *lengths).range(range.clone());
next = shown.show(ui).edit.events.landed().cloned().flatten();
});
record(next.map(PrefValue::Float));
}
Kind::Text(value) => {
let mut next = None;
field().show(ui, |ui, _| {
@@ -54,7 +54,8 @@ pub struct PreferencesState {
/// draft. A failed apply keeps the window open and shows its message in the footer. Enter activates OK and Escape
/// cancels, once the search text, a field's own gesture and a popup have had them.
/// - **Nested dialogs.** While [`PreferencesModel::nested_open`] is true the window takes no input and refuses to
/// close; [`PreferencesModel::nested`] draws the nested dialogs inside the window's own viewport.
/// close; [`PreferencesModel::nested`] draws the nested dialogs with the body's `Ui`, inside the window's own
/// viewport.
/// - **App-modal.** While the window is open the app's other windows take no input, show the blocked cursor and
/// refuse to close, and a press on one raises the window.
/// - **Placement.** The window opens in its own OS window where there are any, else as a modal dialog layer
@@ -214,7 +215,7 @@ impl<'a> PreferencesWindow<'a> {
{
session.host.reset_page(&page.id);
}
session.host.nested(ui); // P3(shell-w5): sh.K29
session.host.nested(ui);
session.page = snap.shown.map(|page| page.id);
session.commit(cx);
});
@@ -3,7 +3,7 @@
use super::{PreferencesState, PreferencesWindow};
use crate::contract::{Bind, Entry};
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, RowKind, RowSpec};
use crate::runtime::env::UnitKind;
use crate::runtime::env::{LengthUnits, UnitKind};
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_theme::Rgba;
use egui::Ui;
@@ -17,11 +17,15 @@ struct Values {
size: i64,
opacity: f64,
tint: Rgba,
/// In points, shown in millimetres.
margin: f64,
/// In seconds.
delay: f64,
}
impl Default for Values {
fn default() -> Self {
Values { snap: true, language: "en".to_owned(), name: "Poster".to_owned(), size: 24, opacity: 0.5, tint: Rgba([0xff, 0x88, 0x00, 0xff]) }
Values { snap: true, language: "en".to_owned(), name: "Poster".to_owned(), size: 24, opacity: 0.5, tint: Rgba([0xff, 0x88, 0x00, 0xff]), margin: 36.0, delay: 0.5 }
}
}
@@ -54,6 +58,12 @@ impl PreferencesModel for Demo {
RowSpec::new("canvas.size", "Brush size", RowKind::int(draft.size, 1..=64).counting(UnitKind::Pixels)),
RowSpec::new("canvas.opacity", "Opacity", RowKind::float(draft.opacity, 0.0..=1.0, 2)),
RowSpec::new("canvas.tint", "Tint", RowKind::Color(draft.tint)),
RowSpec::new(
"canvas.margin",
"Margin",
RowKind::length(draft.margin, 0.0..=720.0, LengthUnits::new(UnitKind::Points, UnitKind::Millimetres, 72.0)),
),
RowSpec::new("canvas.delay", "Preview delay", RowKind::float(draft.delay, 0.0..=10.0, 1).unit_text("s")),
],
)
.footnote("Canvas settings apply to new documents."),
@@ -69,6 +79,8 @@ impl PreferencesModel for Demo {
("canvas.size", PrefValue::Int(size)) => self.draft.size = size,
("canvas.opacity", PrefValue::Float(opacity)) => self.draft.opacity = opacity,
("canvas.tint", PrefValue::Color(tint)) => self.draft.tint = tint,
("canvas.margin", PrefValue::Float(margin)) => self.draft.margin = margin,
("canvas.delay", PrefValue::Float(delay)) => self.draft.delay = delay,
_ => {}
}
}
@@ -97,12 +109,15 @@ impl PreferencesModel for Demo {
let defaults = Values::default();
match page {
"general" => (self.draft.snap, self.draft.language, self.draft.name) = (defaults.snap, defaults.language, defaults.name),
"canvas" => (self.draft.size, self.draft.opacity, self.draft.tint) = (defaults.size, defaults.opacity, defaults.tint),
"canvas" => {
(self.draft.size, self.draft.opacity, self.draft.tint) = (defaults.size, defaults.opacity, defaults.tint);
(self.draft.margin, self.draft.delay) = (defaults.margin, defaults.delay);
}
_ => {}
}
}
fn nested(&mut self, _: &mut Ui) {} // P3(shell-w5): sh.K29
fn nested(&mut self, _: &mut Ui) {}
}
fn window(ui: &mut Ui, data: &mut StoryData, state: PreferencesState, demo: Demo) -> StoryOutput {
@@ -261,7 +261,6 @@ struct TurnOff;
impl CustomSettings<MemoryPrefs> for TurnOff {
fn nested(&mut self, _: &mut egui::Ui, draft: &mut SettingsDraft) {
// P3(shell-w5): sh.K30
draft.remove("memory.percent");
}
}
@@ -271,7 +270,6 @@ impl CustomSettings<MemoryPrefs> for TurnOff {
fn a_removed_draft_value_applies_as_no_value() {
let saved = MemoryPrefs { memory: Memory { percent: Some(70) } };
let mut doc = SettingsDocument::new(saved).expect("serializes").custom(TurnOff);
// P3(shell-w5): sh.K29
let _ = egui::Context::default().run_ui(egui::RawInput::default(), |ui| doc.nested(ui));
doc.apply().expect("the draft fits the struct");
let edits = doc.take_applied_edits().expect("applied");
+9 -3
View File
@@ -128,7 +128,8 @@ impl Outcome for StartOutput {
/// The start screen, shown in a shell's body when no document is open.
///
/// - **Layout.** New and Open (the first Tab stops), then Recent with the view switch and the sort, Pinned Folders
/// when the app gives the list (even an empty one) and Templates when it gives any. The page scrolls as a whole, and each grid and list takes the height of its rows.
/// when the app gives the list (even an empty one), the app's own [`section`](StartScreen::section) when it gives one
/// and Templates when it gives any. The page scrolls as a whole, and each grid and list takes the height of its rows.
/// - **Recent files.** A grid of cards or a list, by the `view` binding, in the order of the `sort` binding. A click or
/// Enter opens a file; arrows move; the context menu (secondary click, the menu key or Shift+F10) and the
/// [`StartRecentCommands`] remove it from the list, clear the list or show it in its folder.
@@ -173,7 +174,6 @@ pub struct StartScreen<'a> {
#[prop(into)]
drop_hint: Option<Label>,
/// One app section, drawn after Recent and Pinned Folders and before Templates.
#[allow(dead_code)] // P3(shell-w5): sh.K28
section: Option<(Label, RefCell<&'a mut dyn FnMut(&mut Ui)>)>,
}
@@ -354,7 +354,7 @@ fn read_events<K: Clone, E>(events: Vec<CollectionEvent<K, E>>, lead: &mut Optio
impl StartScreen<'_> {
/// Shows the page across the available room and reports what the user did.
pub fn show(self, ui: &mut Ui) -> StartOutput {
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint, .. } = self;
let StartScreen { view, sort, recent, pinned, templates, max_recent, now, thumbnails, links, drop_hint, section } = self;
let env = Env::of(ui);
let collator = env.collator();
let words = env.words::<ShellWords>();
@@ -389,6 +389,12 @@ impl StartScreen<'_> {
if let Some(pinned) = pinned {
pinned_section(&page, ui, pinned);
}
if let Some((title, body)) = &section {
let _ = Section::fixed(title.clone()).header_gap(Gap::Section).show(ui, |ui, _| {
let mut body = body.borrow_mut();
(*body)(ui);
});
}
if !templates.is_empty() {
templates_section(&page, ui, templates);
}
+18 -1
View File
@@ -1,7 +1,8 @@
//! Stories of `StartScreen`.
use super::{StartLink, StartScreen};
use crate::contract::Bind;
use crate::buttons::Button;
use crate::contract::{Bind, Show as _};
use crate::primitives::{FakeThumbSource, ThumbnailOptions, Thumbnails};
use crate::runtime::env::Label;
use crate::shell::{RecentFile, RecentSort, RecentView, ScreenModeCommands, Template, ThumbKey};
@@ -84,6 +85,7 @@ struct Extras<'a> {
source: Option<&'a FakeThumbSource<ThumbKey>>,
links: &'a [StartLink],
drop_hint: Option<&'a str>,
section: Option<(&'a str, &'a mut dyn FnMut(&mut Ui))>,
}
fn screen(
@@ -108,6 +110,9 @@ fn screen(
if let Some(hint) = extras.drop_hint {
start = start.drop_hint(Label::from(hint.to_owned()));
}
if let Some((title, body)) = extras.section {
start = start.section(Label::from(title.to_owned()), body);
}
let shown = start.show(ui).into();
*data.value("choice", Choice::default()) = choice;
shown
@@ -119,6 +124,18 @@ fn start_screen(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
screen(ui, data, Choice::default(), &plain_files(), &pinned, &plain_templates(), Extras::default())
}
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
fn start_screen_with_app_section(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let pinned = [PathBuf::from("/home/user/Pictures")];
let mut buttons = |ui: &mut Ui| {
let _ = Button::new(Label::from("Browse Tutorials".to_owned())).id_salt("tutorials").show(ui);
let _ = Button::new(Label::from("What's New".to_owned())).id_salt("whats-new").show(ui);
};
let body: &mut dyn FnMut(&mut Ui) = &mut buttons;
let extras = Extras { section: Some(("Learn", body)), ..Extras::default() };
screen(ui, data, Choice::default(), &plain_files(), &pinned, &plain_templates(), extras)
}
#[story(StartScreen<'static>, covers = [], drive = Drive::Never)]
fn start_screen_with_pictures(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let pinned = [PathBuf::from("/home/ana/Work"), PathBuf::from("/home/ana/Print")];