pdf-dialogs-w3: net change of 2 commits

- pdf-dialogs-w3: written by an agent
- pdf-dialogs-w3: review fixes (review-1)
This commit is contained in:
Dylan M. Taylor
2026-11-18 05:31:31 -05:00
parent c968881b8e
commit 11ff86b244
14 changed files with 372 additions and 88 deletions
+4 -1
View File
@@ -19,7 +19,7 @@ workspace = true
[features]
default = []
# The page widgets (`craft_pages::ui`), on craft-ui.
ui = ["dep:craft-behavior", "dep:craft-ui", "dep:craft-theme", "dep:egui"]
ui = ["dep:craft-behavior", "dep:craft-ui", "dep:craft-theme", "dep:egui", "dep:serde_json"]
# The stories and the integration tests (`tests/it`).
screen-testing = ["ui", "craft-ui/testing"]
@@ -28,6 +28,8 @@ screen-testing = ["ui", "craft-ui/testing"]
craft-text = { path = "../text", default-features = false }
kurbo = { workspace = true }
serde = { workspace = true }
# `ui::range` keeps a page-range row's value as a dialog's JSON field.
serde_json = { workspace = true, optional = true }
craft-behavior = { workspace = true, optional = true }
craft-ui = { workspace = true, optional = true }
craft-theme = { workspace = true, optional = true }
@@ -37,3 +39,4 @@ egui = { workspace = true, optional = true }
craft-ui = { workspace = true, features = ["testing"] }
egui = { workspace = true }
craft-i18n = { workspace = true }
serde_json = { workspace = true }
+25 -8
View File
@@ -52,7 +52,12 @@ pub fn parse_pages(text: &str, count: usize) -> Result<Vec<usize>, PageRangeErro
return Ok(Vec::new());
}
let number = |token: &str| {
let page = token.trim().parse::<usize>().map_err(|_| PageRangeError::NotAPage(token.into()))?;
// `usize::from_str` takes a leading `+`; a page number is digits only, as PdfCraft reads it.
let digits = token.trim();
if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
return Err(PageRangeError::NotAPage(token.into()));
}
let page = digits.parse::<usize>().map_err(|_| PageRangeError::NotAPage(token.into()))?;
if page == 0 || page > count { Err(PageRangeError::OutOfRange { page, count }) } else { Ok(page - 1) }
};
let mut pages = BTreeSet::new();
@@ -105,6 +110,7 @@ pub enum Subset {
/// Which pages a [`PageRange`] starts from.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum PageScope {
/// All pages; `from` and `to` are kept but not applied.
@@ -142,18 +148,29 @@ impl Default for PageRange {
impl PageRange {
/// The pages (0-based) the range selects in a document of `count` pages, with `current` the current page and
/// `selection` the selected pages.
/// `selection` the selected pages (all 0-based). The scope picks the pages, then the subset keeps the even or odd
/// page numbers among them; a page past the document is never returned.
// pdfcraft: crates/ui-egui/src/dialogs/marks_ui.rs:46 `PageRange::pages`.
pub fn pages(&self, count: usize, current: usize, selection: &[usize]) -> Vec<usize> {
let _ = (current, selection); // P3(pdf-dialogs-w3): DG-C17
let (from, to) = if self.scope == PageScope::All { (1, count) } else { (self.from.max(1), self.to.map_or(count, |to| to.min(count))) };
(from..=to)
let picked: Vec<usize> = match self.scope {
PageScope::All => (0..count).collect(),
PageScope::Current => vec![current],
PageScope::Selection if selection.is_empty() => vec![current],
PageScope::Selection => {
let mut seen = BTreeSet::new();
selection.iter().copied().filter(|page| seen.insert(*page)).collect()
}
// `from` and `to` are 1-based and inclusive: pages `from - 1` up to, not including, `to`.
PageScope::Range => (self.from.max(1) - 1..self.to.map_or(count, |to| to.min(count))).collect(),
};
picked
.into_iter()
.filter(|&page| page < count)
.filter(|page| match self.subset {
Subset::All => true,
Subset::Even => page % 2 == 0,
Subset::Odd => page % 2 == 1,
Subset::Even => (page + 1) % 2 == 0,
Subset::Odd => (page + 1) % 2 == 1,
})
.map(|page| page - 1)
.collect()
}
}
+29
View File
@@ -10,9 +10,38 @@ fn range_text_parses_sorted_unique_and_bounded() {
assert_eq!(parse_pages("0", 9), Err(PageRangeError::OutOfRange { page: 0, count: 9 }));
assert_eq!(parse_pages("12", 9), Err(PageRangeError::OutOfRange { page: 12, count: 9 }));
assert_eq!(parse_pages("x", 9), Err(PageRangeError::NotAPage("x".into())));
// A page number is ASCII digits only: no sign, no other script's digits.
assert_eq!(parse_pages("+3", 9), Err(PageRangeError::NotAPage("+3".into())));
assert_eq!(parse_pages("-3", 9), Err(PageRangeError::NotAPage("".into())));
assert_eq!(parse_pages("1-+3", 9), Err(PageRangeError::NotAPage("+3".into())));
assert_eq!(parse_pages("\u{0663}", 9), Err(PageRangeError::NotAPage("\u{0663}".into())));
assert_eq!(parse_pages(" ", 9), Ok(vec![]));
assert_eq!(parse_pages(&"1,".repeat(10_000), 9), Err(PageRangeError::TooLong));
let overlaps = ["1-100000"; 11].join(",");
assert_eq!(parse_pages(&overlaps, 100_000), Err(PageRangeError::TooLong));
assert_eq!(PageRangeError::OutOfRange { page: 12, count: 9 }.to_string(), "page 12 is out of range (1\u{2013}9)");
}
/// The scope picks the pages and the subset filters them by page number: a slip sends a dialog's command to the
/// wrong pages without a word.
#[trial]
fn page_range_scopes_pick_pages_then_apply_the_subset() {
let range = |scope, from, to, subset| PageRange { scope, from, to, subset };
let all = PageRange::default();
assert_eq!(all.pages(4, 2, &[]), vec![0, 1, 2, 3], "All is every page");
assert_eq!(range(PageScope::All, 1, None, Subset::Even).pages(5, 0, &[]), vec![1, 3], "Even keeps pages 2 and 4");
assert_eq!(range(PageScope::Current, 1, None, Subset::All).pages(9, 4, &[1, 2]), vec![4], "Current is the current page");
let selection = range(PageScope::Selection, 1, None, Subset::All);
assert_eq!(selection.pages(9, 0, &[5, 2, 5, 7, 2]), vec![5, 2, 7], "the selection keeps its order without repeats");
assert_eq!(selection.pages(9, 3, &[]), vec![3], "an empty selection falls back to the current page");
let odd_selection = range(PageScope::Selection, 1, None, Subset::Odd);
assert_eq!(odd_selection.pages(9, 0, &[3, 0, 2, 1]), vec![0, 2], "the subset applies after the scope, by page number");
assert_eq!(range(PageScope::Range, 3, None, Subset::All).pages(6, 0, &[]), vec![2, 3, 4, 5], "no `to` ends at the last page");
assert_eq!(range(PageScope::Range, 2, Some(5), Subset::All).pages(9, 0, &[]), vec![1, 2, 3, 4], "`from` and `to` are inclusive");
assert_eq!(range(PageScope::Range, 2, Some(50), Subset::All).pages(4, 0, &[]), vec![1, 2, 3], "`to` past the document is clamped");
assert_eq!(range(PageScope::Range, 7, Some(9), Subset::All).pages(4, 0, &[]), Vec::<usize>::new(), "`from` past the document is no pages");
assert_eq!(range(PageScope::Range, 1, Some(6), Subset::Odd).pages(9, 0, &[]), vec![0, 2, 4], "Odd keeps pages 1, 3 and 5 of the range");
}
+23 -22
View File
@@ -6,15 +6,14 @@
mod stories;
use super::view::PageSource;
use craft_behavior::IconId;
use craft_behavior::{Input, Metrics, PartKey, Proposal, Sense};
use craft_ui::buttons::{Button, IconButton};
use craft_ui::buttons::Button;
use craft_ui::contract::{
Bind, BindMut, BodyCx, CommandSet, Common, Component, Container, ContainerProps, Cx, DisabledLook, FooterRegion, MeasureCx, Mount, NoValue,
Outcome, Pad, PaintUi, PartsCx, Props as _, Role, RowAlign, Show as _, ShowContainer, clicked,
};
use craft_ui::display::Text;
use craft_ui::layout_components::Row;
use craft_ui::patterns::form_dialogs::{PagerStep, PanePager};
use craft_ui::primitives::textures::{
MAX_TEXTURE, Priority, TextureState, TextureStoreOptions, TextureWords, ThumbPaint, ThumbRequest, ThumbnailOptions, Thumbnails,
};
@@ -30,9 +29,6 @@ use std::cell::Cell;
craft_ui::words! {
/// The preview's words (PdfCraft's strings).
pub struct PagePreviewWords {
page_of: template "pagePreview.pageOf" = "Page {p} of {n}";
previous: "pagePreview.previous" = "Previous page";
next: "pagePreview.next" = "Next page";
close: "pagePreview.close" = "Close";
unavailable: "pagePreview.unavailable" = "Preview unavailable";
}
@@ -114,14 +110,21 @@ impl<'a> PagePreview<'a> {
*at = (*at).min(last);
let env = Env::of(ui);
let words = env.words::<PagePreviewWords>();
let format = env.format();
let page = pages[*at];
let title =
Label::from(words.page_of.fill(&[("p", source.page_label(page).as_str()), ("n", format.integer(source.page_count() as u64).as_str())]));
// The pager counts the document's pages, as the caption names the page shown, though it steps through `pages`.
let pager = PanePager {
shown: page + 1,
count: source.page_count(),
shown_label: Some(Label::from(source.page_label(page))),
back: *at > 0,
next: *at < last,
..PanePager::default()
};
let title = pager.caption(&env);
let step = Cell::new(0_isize);
let side = if env.direction.is_rtl() { -1 } else { 1 };
let mut open = true;
let layer = PreviewLayer::new(&words, title.clone(), *at, last, &step, Bind::bound(&mut open));
let layer = PreviewLayer::new(&words, title, pager, &step, Bind::bound(&mut open));
let shown = ShowContainer::show(layer, ui, |ui, cx| {
while let Some((command, _)) = cx.take_command::<PagePreviewCommands>() {
let by = match command {
@@ -173,16 +176,15 @@ struct PreviewLayer<'b> {
#[container()]
props: ContainerProps,
words: &'b PagePreviewWords,
title: Label,
shown: usize,
last: usize,
pager: PanePager,
step: &'b Cell<isize>,
open: Bind<'b, bool>,
closed: Option<CloseReason>,
}
impl<'b> PreviewLayer<'b> {
fn new(words: &'b PagePreviewWords, title: Label, shown: usize, last: usize, step: &'b Cell<isize>, open: Bind<'b, bool>) -> Self {
/// The layer named `title` (the pager's caption) with `pager` under the page; a pager press adds to `step`.
fn new(words: &'b PagePreviewWords, title: Label, pager: PanePager, step: &'b Cell<isize>, open: Bind<'b, bool>) -> Self {
let props = ContainerProps::new()
.mount(Mount::FullWindow)
.surface(SurfaceKind::Scrim)
@@ -190,7 +192,7 @@ impl<'b> PreviewLayer<'b> {
.footer(FooterRegion::new())
.focus(FocusPolicy::DIALOG.initial(Initial::Default))
.command_scope(PagePreviewCommands::SCOPE);
PreviewLayer { common: Common::new(), props, words, title: title.clone(), shown, last, step, open, closed: None }.label(title)
PreviewLayer { common: Common::new(), props, words, pager, step, open, closed: None }.label(title)
}
}
@@ -221,15 +223,14 @@ impl Container for PreviewLayer<'_> {
/// Previous, the page's place, next and Close, centred under the page.
fn footer(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
let (words, shown, last, step) = (self.words, self.shown, self.last, self.step);
let (words, step) = (self.words, self.step);
let pager = self.pager.clone();
let mut close = false;
Row::new().fill_width().align(RowAlign::Center).show(ui, |ui, _| {
if clicked(&IconButton::new(IconId::new("chevron_left")).label(words.previous.clone()).enabled(shown > 0).show(ui)) {
step.set(step.get() - 1);
}
Text::new(self.title.clone()).show(ui);
if clicked(&IconButton::new(IconId::new("chevron_right")).label(words.next.clone()).enabled(shown < last).show(ui)) {
step.set(step.get() + 1);
match pager.show(ui) {
Some(PagerStep::Back) => step.set(step.get() - 1),
Some(PagerStep::Next) => step.set(step.get() + 1),
None => {}
}
close = clicked(&Button::new(words.close.clone()).default_stop().show(ui));
});
+3 -1
View File
@@ -5,6 +5,7 @@ use crate::ui::fixtures::{DemoPages, PAPER};
use crate::ui::thumbnails::PageThumbnails;
use craft_behavior::Selection;
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer};
use craft_ui::patterns::form_dialogs::PanePager;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -53,7 +54,8 @@ fn preview_layer(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let words = Env::of(ui).words::<PagePreviewWords>();
let step = Cell::new(0);
let pages = DemoPages::new(5);
let layer = PreviewLayer::new(&words, Label::from("Page 2 of 5"), 1, 4, &step, Bind::bound(data.value("open", true)));
let pager = PanePager { shown: 2, count: 5, back: true, next: true, ..PanePager::default() };
let layer = PreviewLayer::new(&words, Label::from("Page 2 of 5"), pager, &step, Bind::bound(data.value("open", true)));
ShowContainer::show(layer, ui, |ui, cx| {
PagePicture::new(&pages, 1, "Page unavailable", PAPER).label("Page 2").show_at(ui, cx.rect);
})
+70 -27
View File
@@ -42,6 +42,9 @@ craft_ui::words! {
pub struct PageRangeOptionsWords {
page_range: "pageRangeOptions.pageRange" = "Page range";
all_pages: "pageRangeOptions.allPages" = "All pages";
/// `{page}` is the current page's number.
current_page: template "pageRangeOptions.currentPage" = "Current page ({page})";
selection: "pageRangeOptions.selection" = "Selected pages";
pages_from: "pageRangeOptions.pagesFrom" = "Pages from";
to: "pageRangeOptions.to" = "to";
subset: "pageRangeOptions.subset" = "Subset";
@@ -218,9 +221,9 @@ impl Outcome for PageRangeOptionsOutput {
}
}
/// The All pages / Pages from [ ] to [ ] / Subset [ ] rows over a dialog's [`PageRange`]: a radio group for All pages
/// and the from-to range, whole-number fields for From and To (1 to the page count, off with All pages) and a list for
/// the subset.
/// The All pages / Pages from [ ] to [ ] / Subset [ ] rows over a dialog's [`PageRange`]: a radio group over the
/// range's [`PageScope`], whole-number fields for From and To (1 to the page count, on only for the from-to range) and
/// a list for the subset. [`PageRangeChoices`] adds Current page and Selected pages, or leaves out the subset.
#[must_use = "show the options with `show`"]
#[derive(Pattern)]
pub struct PageRangeOptions {
@@ -248,6 +251,23 @@ pub enum PageRangeChoices {
CurrentFromTo,
}
impl PageRangeChoices {
/// Whether the rows offer Current page.
fn current(self) -> bool {
matches!(self, PageRangeChoices::Current | PageRangeChoices::Selection | PageRangeChoices::CurrentFromTo)
}
/// Whether the rows offer Selected pages.
fn selection(self) -> bool {
self == PageRangeChoices::Selection
}
/// Whether the rows end with the Subset list.
fn subset(self) -> bool {
matches!(self, PageRangeChoices::Acrobat | PageRangeChoices::Current | PageRangeChoices::Selection)
}
}
impl PageRangeOptions {
/// The options named `label` over `range` in a document of `count` pages.
pub fn new(label: impl Into<Label>, range: PageRange, count: usize) -> Self {
@@ -268,27 +288,40 @@ impl PageRangeOptions {
/// The one page-range row for every `ParamDialog`: a custom row named `label` that keeps its [`PageRange`] under
/// `key` as JSON, in a document of `count` pages with `current` the current page.
///
/// The row opens on All pages. A value under `key` that is not a range shows as All pages until the user picks.
pub fn param(key: impl Into<String>, label: impl Into<Label>, count: usize, current: usize, choices: PageRangeChoices) -> Param {
let _ = (key.into(), label.into(), count, current, choices);
todo!("DG-C19")
let key = key.into();
let label = label.into();
let (row_key, row_label) = (key.clone(), label.clone());
Param::custom(key, label, move |ui, fields, _| {
let range = Self::value(fields, &row_key).unwrap_or_default();
let shown = PageRangeOptions::new(row_label.clone(), range, count).choices(choices).current(current).show(ui);
if let Some(next) = shown.changed {
fields.set(row_key.clone(), Self::field_value(&next));
}
shown.response
})
.opens_with(Self::field_value(&PageRange::default()))
}
/// The range the row `key` holds in `fields`; `None` when absent or not a range.
pub fn value(fields: &DialogFields, key: &str) -> Option<PageRange> {
let _ = (fields, key);
todo!("DG-C19")
match fields.get(key)? {
FieldValue::Json(value) => serde_json::from_value(value.clone()).ok(),
_ => None,
}
}
/// The row's stored form of `range`, for the row's `opens_with`.
pub fn field_value(range: &PageRange) -> FieldValue {
let _ = range;
todo!("DG-C19")
// A `PageRange` is plain fields and enums, which always serialize; `Null` would read back as no range.
FieldValue::Json(serde_json::to_value(range).unwrap_or_default())
}
/// Shows the options.
pub fn show(self, ui: &mut Ui) -> PageRangeOptionsOutput {
let PageRangeOptions { label, range, count, choices, current } = self;
let _ = (choices, current); // P3(pdf-dialogs-w3): DG-C18
let env = Env::of(ui);
let words = env.words::<PageRangeOptionsWords>();
let numbers = NumberCodec::new(env.units().reader(None), 0);
@@ -302,16 +335,24 @@ impl PageRangeOptions {
let whole = |value: &EditResponse<Option<f64>>, shown: usize| {
value.value().copied().flatten().map(|v| (v.round() as usize).clamp(1, last)).filter(|v| *v != shown)
};
let page = env.format().integer(current.saturating_add(1) as u64);
let current_page = Label::from(words.current_page.fill(&[("page", page.as_str())]));
let mut from = None;
let mut to = None;
let group = RadioGroup::new(label, Bind::given(range.scope == PageScope::All)).show(ui, |ui, cx| {
let group = RadioGroup::new(label, Bind::given(range.scope)).show(ui, |ui, cx| {
Stack::new().show(ui, |ui, _| {
cx.labelled(ui, "all", words.all_pages.clone(), after.clone(), Radio::new(true));
cx.labelled(ui, "all", words.all_pages.clone(), after.clone(), Radio::new(PageScope::All));
if choices.current() {
cx.labelled(ui, "current", current_page.clone(), after.clone(), Radio::new(PageScope::Current));
}
if choices.selection() {
cx.labelled(ui, "selection", words.selection.clone(), after.clone(), Radio::new(PageScope::Selection));
}
// Two themed fields don't fit beside the radio in a narrow panel: "to" and its field wrap together.
Row::new().wrap(true).show(ui, |ui, _| {
cx.labelled(ui, "range", words.pages_from.clone(), after.clone(), Radio::new(false));
cx.labelled(ui, "range", words.pages_from.clone(), after.clone(), Radio::new(PageScope::Range));
let field = |label: &Label, shown: usize| {
NumberField::new(label.clone(), Bind::given(Some(shown as f64))).codec(numbers.clone()).enabled(range.scope != PageScope::All)
NumberField::new(label.clone(), Bind::given(Some(shown as f64))).codec(numbers.clone()).enabled(range.scope == PageScope::Range)
};
from = whole(&field(&words.pages_from, shown_from).show(ui).edit, shown_from);
Row::new().show(ui, |ui, _| {
@@ -321,8 +362,8 @@ impl PageRangeOptions {
});
});
});
if let Some(all) = group.output.value().copied() {
next.scope = if all { PageScope::All } else { PageScope::Range }; // P3(pdf-dialogs-w3): DG-C17
if let Some(scope) = group.output.value().copied() {
next.scope = scope;
}
if let Some(value) = from {
next.from = value;
@@ -332,17 +373,19 @@ impl PageRangeOptions {
next.to = Some(value);
next.from = next.from.min(value);
}
let entries = [
Entry::new(Subset::All, words.all_in_range.clone()),
Entry::new(Subset::Even, words.even_only.clone()),
Entry::new(Subset::Odd, words.odd_only.clone()),
];
Field::new(words.subset.clone()).show(ui, |ui, _| {
let picked = Select::new(words.subset.clone(), Bind::given(range.subset), &entries).show(ui);
if let Some(subset) = picked.value().copied() {
next.subset = subset;
}
});
if choices.subset() {
let entries = [
Entry::new(Subset::All, words.all_in_range.clone()),
Entry::new(Subset::Even, words.even_only.clone()),
Entry::new(Subset::Odd, words.odd_only.clone()),
];
Field::new(words.subset.clone()).show(ui, |ui, _| {
let picked = Select::new(words.subset.clone(), Bind::given(range.subset), &entries).show(ui);
if let Some(subset) = picked.value().copied() {
next.subset = subset;
}
});
}
PageRangeOptionsOutput { response: group.output.response.clone(), changed: (next != range).then_some(next) }
}
}
+43 -3
View File
@@ -1,8 +1,9 @@
//! Stories of the page range field and options.
use super::{PageRangeField, PageRangeOptions, PageRangeOptionsWords};
use super::{PageRangeChoices, PageRangeField, PageRangeOptions, PageRangeOptionsWords};
use crate::range::{PageRange, PageScope, Subset};
use craft_ui::contract::Entry;
use craft_ui::contract::{Bind, Entry};
use craft_ui::patterns::form_dialogs::{DialogFields, ParamRows};
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -29,8 +30,47 @@ fn page_range_field(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
#[story(PageRangeOptions, covers = [], drive = Drive::Never)]
fn page_range_options(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = PageRange { scope: PageScope::Range, from: 3, to: Some(9), subset: Subset::Odd };
options(ui, data, start, PageRangeChoices::Acrobat)
}
#[story(PageRangeOptions, covers = [], drive = Drive::Never)]
fn page_range_options_current(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = PageRange { scope: PageScope::Current, ..PageRange::default() };
options(ui, data, start, PageRangeChoices::Current)
}
#[story(PageRangeOptions, covers = [], drive = Drive::Never)]
fn page_range_options_selection(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = PageRange { scope: PageScope::Selection, ..PageRange::default() };
options(ui, data, start, PageRangeChoices::Selection)
}
#[story(PageRangeOptions, covers = [], drive = Drive::Never)]
fn page_range_options_from_to(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let start = PageRange { scope: PageScope::Range, from: 2, to: Some(5), subset: Subset::All };
options(ui, data, start, PageRangeChoices::FromTo)
}
#[story(PageRangeOptions, covers = [], drive = Drive::Never)]
fn page_range_options_current_from_to(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
options(ui, data, PageRange::default(), PageRangeChoices::CurrentFromTo)
}
/// The page-range row as a `ParamDialog` shows it, among the dialog's rows, keeping its range in the dialog's fields.
#[story(PageRangeOptions, covers = [], drive = Drive::Never)]
fn page_range_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let params = [PageRangeOptions::param("pages", "Page range", PAGES, CURRENT, PageRangeChoices::Current)];
let fields = data.value("fields", DialogFields::new());
StoryOutput::from(ParamRows::new("Options", &params, Bind::bound(fields)).show(ui))
}
/// The page the stories' Current page names (0-based).
const CURRENT: usize = 3;
/// The options over the story's range, opening on `start`, in the arrangement `choices`.
fn options(ui: &mut Ui, data: &mut StoryData, start: PageRange, choices: PageRangeChoices) -> StoryOutput {
let range = *data.value("range", start);
let out = PageRangeOptions::new("Page range", range, PAGES).show(ui);
let out = PageRangeOptions::new("Page range", range, PAGES).choices(choices).current(CURRENT).show(ui);
if let Some(next) = out.changed {
*data.value("range", start) = next;
}
+48 -3
View File
@@ -1,8 +1,12 @@
//! The page range field's menu of the app's page choices.
//! The page range field's menu of the app's page choices, and the page-range row of a parameter dialog.
use craft_pages::ui::PageRangeField;
use craft_ui::contract::Entry;
use craft_pages::ui::{PageRangeChoices, PageRangeField, PageRangeOptions};
use craft_pages::{PageRange, PageScope, Subset};
use craft_ui::contract::{Bind, Entry};
use craft_ui::patterns::form_dialogs::{DialogFields, FieldValue, Param, ParamRows, set_param_field};
use craft_ui::testing::{Fixture, trial};
use egui::{Key, Modifiers};
use serde_json::json;
use std::cell::RefCell;
use std::rc::Rc;
@@ -31,3 +35,44 @@ fn the_menu_lists_the_apps_entries_and_a_field_without_entries_has_no_button() {
bare.settle();
assert!(bare.by_label("Select pages").is_none(), "no entries, no button");
}
/// The page-range row of a parameter dialog, over a document of 12 pages.
fn page_range_row() -> Vec<Param> {
vec![PageRangeOptions::param("pages", "Page range", 12, 2, PageRangeChoices::FromTo)]
}
/// The page-range row keeps the range the user picks in the dialog's fields as JSON and reads back what automation
/// sets there; an absent or unreadable value is no range. A slip in the stored form loses the user's range silently.
#[trial]
fn a_page_range_row_keeps_its_range_as_json_and_reads_it_back() {
let values = Rc::new(RefCell::new(DialogFields::new()));
let shown = values.clone();
let rows = page_range_row();
let mut fixture = Fixture::new(move |ui| {
let _ = ParamRows::new("Form", &rows, Bind::bound(&mut *shown.borrow_mut())).show(ui);
});
fixture.settle();
let range = fixture.by_label("Pages from").expect("the from-to radio");
fixture.click(&range).settle();
let to = fixture.by_label("to").expect("the To field");
fixture.click(&to).settle();
fixture.key(Key::A, Modifiers::COMMAND).type_text("5").key(Key::Enter, Modifiers::NONE).settle();
assert!(matches!(values.borrow().get("pages"), Some(FieldValue::Json(_))), "the row keeps its range as JSON");
let typed = PageRangeOptions::value(&values.borrow(), "pages").expect("the row's value reads back as a range");
assert_eq!((typed.scope, typed.from, typed.to), (PageScope::Range, 1, Some(5)), "the typed To lands in the fields");
assert_eq!(typed.pages(12, 2, &[]), vec![0, 1, 2, 3, 4]);
let set = PageRange { scope: PageScope::Range, from: 3, to: Some(7), subset: Subset::Odd };
let automation = json!({"scope": "range", "from": 3, "to": 7, "subset": "odd"});
set_param_field(&page_range_row(), &mut values.borrow_mut(), "pages", automation).expect("the row takes a JSON value");
fixture.settle();
assert_eq!(PageRangeOptions::value(&values.borrow(), "pages"), Some(set), "a range set by automation reads back");
let stored = DialogFields::from_pairs([("pages", PageRangeOptions::field_value(&set))]);
assert_eq!(PageRangeOptions::value(&stored, "pages"), Some(set), "the row's stored form reads back as the same range");
assert_eq!(PageRangeOptions::value(&DialogFields::new(), "pages"), None, "no value is no range");
set_param_field(&page_range_row(), &mut values.borrow_mut(), "pages", json!("all pages")).expect("a custom row keeps any JSON");
fixture.settle();
assert_eq!(PageRangeOptions::value(&values.borrow(), "pages"), None, "a value that is not a range reads as none");
}
@@ -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;
@@ -31,7 +31,7 @@ use crate::table::Table;
use crate::tabs::{Tab, TabKind, TabStrip};
use contributors::{Writer, sorted_indices};
use craft_behavior::{ColumnKey, ColumnWidth, EditEvent, IconId, Mixed, SelectionChange, keyed};
use craft_theme::Variant;
use craft_theme::{Mode, Variant};
use egui::{Response, Ui};
use serde_json::{Value, json};
use std::borrow::Cow;
@@ -195,7 +195,8 @@ impl Outcome for AboutOutput {
/// Help > About: tabs About, Contributors and Models over the app's [`AboutInfo`] and [`Credits`], with an OK button.
///
/// - **About.** The blurb, the version, the community button and the link row centred, the built-with line faint.
/// - **About.** The app's mark when it has one, the blurb, the version, the community button and the link row
/// centred, then "Part of" with the suite's logo when it has one, the built-with line faint.
/// - **Contributors.** Show (Username, Display name, Real name), Sort (the list, with a button to reverse) and View
/// (Grab bag or Table). The grab bag flows the names as links: a click reports the contributor's profile URL as the
/// link (nothing for one without a profile), and the link's tooltip is the summary. The table has every figure; a
@@ -312,7 +313,13 @@ impl Shown<'_> {
/// The About tab.
fn about(&self, ui: &mut Ui, link: &RefCell<Option<String>>) {
let (words, info) = (self.words, self.info);
let dark = Env::of(ui).view().mode() == Mode::Dark;
Stack::new().show(ui, |ui, _| {
if let Some(mark) = &info.mark {
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
Picture::svg(mark.label.clone(), mark.source(dark)).extent(PictureSize::Thumb(ThumbSize::Small)).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, _| {
@@ -332,6 +339,12 @@ impl Shown<'_> {
}
}
});
if let Some(logo) = &info.part_of {
Row::new().align(RowAlign::Center).show(ui, |ui, _| {
Text::new(words.part_of.clone()).shade(Shade::Muted).show(ui);
Picture::svg(logo.label.clone(), logo.source(dark)).show(ui);
});
}
Text::new(info.built_with.clone()).shade(Shade::Faint).show(ui);
});
}
@@ -36,15 +36,19 @@ pub struct AboutImage {
impl AboutImage {
/// The picture `svg` draws, named `label`.
pub fn svg(label: impl Into<Label>, svg: &'static [u8]) -> Self {
let _ = (label, svg);
todo!("DG-C20")
AboutImage { label: label.into(), svg, dark: None }
}
/// The SVG that replaces the picture when the theme mode is dark.
#[must_use]
pub fn dark(self, svg: &'static [u8]) -> Self {
let _ = svg;
todo!("DG-C20")
pub fn dark(mut self, svg: &'static [u8]) -> Self {
self.dark = Some(svg);
self
}
/// The SVG source to draw: `dark` in a dark theme mode when there is one, else `svg`.
pub(super) fn source(&self, dark: bool) -> &'static [u8] {
self.dark.filter(|_| dark).unwrap_or(self.svg)
}
}
@@ -93,16 +97,16 @@ impl AboutInfo {
/// The application's mark, centred above the blurb.
#[must_use]
pub fn mark(self, image: AboutImage) -> Self {
let _ = image;
todo!("DG-C20")
pub fn mark(mut self, image: AboutImage) -> Self {
self.mark = Some(image);
self
}
/// The suite's logo on a centred "Part of" line above the built-with line.
#[must_use]
pub fn part_of(self, logo: AboutImage) -> Self {
let _ = logo;
todo!("DG-C20")
pub fn part_of(mut self, logo: AboutImage) -> Self {
self.part_of = Some(logo);
self
}
/// The prominent button under the blurb.
@@ -1,6 +1,6 @@
//! Stories of `AboutDialog`: the About tab and the Contributors tab with a PR-only contributor.
use super::{AboutDialog, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use super::{AboutDialog, AboutImage, AboutInfo, AboutLink, AboutTab, Contributor, Credits, HostedAbout, ModelCredit};
use crate::dialog::stories::hosted;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
@@ -39,6 +39,23 @@ fn about_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
hosted(ui, data, (tab, community), || HostedAbout::new(info(community), CREDITS.clone()).tab(tab))
}
/// The story's app mark: a rounded square with a page corner folded down.
const MARK: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48"><rect x="4" y="4" width="40" height="40" rx="10" fill="#3b6fd8"/><path d="M16 12h12l8 8v16H16z" fill="#ffffff"/><path d="M28 12v8h8z" fill="#c9d8f7"/></svg>"##;
/// The story's suite logo: a dot and a bar, dark ink for a light theme.
const SUITE: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="5" cy="8" r="4" fill="#202124"/><rect x="10" y="4" width="4" height="8" rx="1" fill="#202124"/></svg>"##;
/// The suite logo in light ink, for a dark theme.
const SUITE_DARK: &[u8] = br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="5" cy="8" r="4" fill="#f1f3f4"/><rect x="10" y="4" width="4" height="8" rx="1" fill="#f1f3f4"/></svg>"##;
#[story(AboutDialog<'static>, covers = [], drive = Drive::Never, title = "About with a mark and suite logo")]
fn about_dialog_with_mark(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
hosted(ui, data, AboutTab::About, || {
let marked = info(true).mark(AboutImage::svg("PhotoCraft", MARK)).part_of(AboutImage::svg("Craft Suite", SUITE).dark(SUITE_DARK));
HostedAbout::new(marked, CREDITS.clone())
})
}
#[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);
@@ -51,16 +51,17 @@ impl<'a> PageSpec<'a> {
Self { id, title, groups: vec![GroupSpec::new(None, rows)], footnote: None, keywords: "", custom: false }
}
/// A page the host draws.
/// A page the host draws ([`PreferencesModel::custom_page`]). Its [`group`](PageSpec::group)s follow the host's
/// part, drawn and searched as a plain page's groups are.
pub fn custom(id: &'a str, title: &'a str) -> Self {
Self { id, title, groups: Vec::new(), footnote: None, keywords: "", custom: true }
}
/// Adds `group` under a custom page's own part, where the search sees its rows.
#[must_use]
pub fn group(self, group: GroupSpec<'a>) -> Self {
let _ = group;
todo!("DG-C21")
pub fn group(mut self, group: GroupSpec<'a>) -> Self {
self.groups.push(group);
self
}
/// Sets the note shown under the last group.
@@ -2,7 +2,7 @@
use super::{PreferencesState, PreferencesWindow};
use crate::contract::{Bind, Entry};
use crate::patterns::preferences::{PageSpec, PrefValue, PreferencesModel, RowKind, RowSpec};
use crate::patterns::preferences::{GroupSpec, PageSpec, PrefValue, PreferencesModel, RowKind, RowSpec};
use crate::runtime::env::UnitKind;
use crate::testing::{Drive, StoryData, StoryOutput, story};
use craft_theme::Rgba;
@@ -17,11 +17,22 @@ struct Values {
size: i64,
opacity: f64,
tint: Rgba,
load_plugins: bool,
plugin_folder: String,
}
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]),
load_plugins: true,
plugin_folder: "Plug-ins".to_owned(),
}
}
}
@@ -57,7 +68,14 @@ impl PreferencesModel for Demo {
],
)
.footnote("Canvas settings apply to new documents."),
PageSpec::new("plugins", "Plug-ins", Vec::new()),
// The host draws the page's own part (nothing here); the group under it is drawn and searched as rows.
PageSpec::custom("plugins", "Plug-ins").group(GroupSpec::new(
Some("Loading"),
vec![
RowSpec::new("plugins.load", "Load plug-ins at launch", RowKind::Bool(draft.load_plugins)),
RowSpec::new("plugins.folder", "Plug-in folder", RowKind::Text(&draft.plugin_folder)),
],
)),
]
}
@@ -69,6 +87,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,
("plugins.load", PrefValue::Bool(on)) => self.draft.load_plugins = on,
("plugins.folder", PrefValue::Text(text)) => self.draft.plugin_folder = text,
_ => {}
}
}
@@ -98,6 +118,7 @@ impl PreferencesModel for Demo {
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),
"plugins" => (self.draft.load_plugins, self.draft.plugin_folder) = (defaults.load_plugins, defaults.plugin_folder),
_ => {}
}
}
@@ -124,6 +145,13 @@ fn preferences_window_without_matches(ui: &mut Ui, data: &mut StoryData) -> Stor
window(ui, data, state, Demo::default())
}
/// The custom Plug-ins page: the host's part, then the page's own titled group.
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
fn preferences_window_custom_page(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state = PreferencesState { selected: "plugins".to_owned(), ..PreferencesState::default() };
window(ui, data, state, Demo::default())
}
#[story(PreferencesWindow<'static>, covers = [], drive = Drive::Never)]
fn preferences_window_with_error(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let state =
@@ -40,6 +40,47 @@ fn a_click_on_a_name_in_the_grab_bag_reports_its_profile() {
assert!(!fixture.by_role(Role::TABLE).is_empty(), "Table shows the contributors as a table");
}
/// The names of the grab bag, in the order it shows them.
fn grab_bag(fixture: &Fixture) -> Vec<String> {
fixture.by_role(Role::LINK).iter().filter_map(|link| fixture.tree().name_of(link.node).map(str::to_owned)).collect()
}
/// Picks `entry` from the Sort list.
fn sort_by(fixture: &mut Fixture, entry: &str) {
let sort = fixture.by_label("Sort").expect("the Sort list");
fixture.click(&sort).idle(4);
let pick = fixture.by_label(entry).unwrap_or_else(|| panic!("the Sort list offers {entry}"));
fixture.click(&pick).idle(10);
}
// The name order ignores the `@` of a username and the case, so display names and usernames interleave; someone
// with no commit date sorts after everyone with one, by first and by last commit. A slip reorders the credits.
#[trial]
fn contributors_sort_by_name_without_at_or_case_and_undated_last() {
let credits = Credits::new(
vec![
Contributor::new("carl").counts(0, 9).active("2025-01-01T10:00:00Z", "2026-01-01T10:00:00Z"),
Contributor::new("zed").display_name("Bea").counts(1, 0),
Contributor::new("alice").counts(0, 3).active("2025-03-01T10:00:00Z", "2025-04-01T10:00:00Z"),
],
Vec::new(),
12,
);
let mut fixture = Fixture::new(move |ui| {
let _ = AboutDialog::new(&INFO, &credits).tab(Bind::given(AboutTab::Contributors)).show(ui);
});
fixture.room(Vec2::new(1400.0, 1000.0)).idle(30);
assert_eq!(grab_bag(&fixture), ["@carl", "@alice", "@zed"], "oldest first commit first, the undated last");
sort_by(&mut fixture, "Last commit");
assert_eq!(grab_bag(&fixture), ["@alice", "@carl", "@zed"], "oldest last commit first, the undated last");
let display = fixture.by_label("Display name").expect("Show offers Display name");
fixture.click(&display).idle(10);
sort_by(&mut fixture, "Name (A\u{2013}Z)");
assert_eq!(grab_bag(&fixture), ["@alice", "Bea", "@carl"], "names compare without the `@` and the case");
}
#[trial]
fn about_tab_is_a_field() {
let host = Rc::new(RefCell::new(DialogHost::new()));