Contract stubs: craft-ui-widgets, craft-ui-panels

This commit is contained in:
Dylan M. Taylor
2026-11-17 22:47:05 -05:00
parent aafc82051e
commit 2d343ecbdf
41 changed files with 809 additions and 67 deletions
+3 -2
View File
@@ -138,7 +138,8 @@ pub struct FooterHost<'s, 'a> {
/// Fills the header region: the title and, for a closable shell, the close action.
#[doc(hidden)]
pub fn header(ui: &mut Ui, cx: &mut BodyCx<'_>, actions: &[HeaderAction]) {
pub fn header(ui: &mut Ui, cx: &mut BodyCx<'_>, actions: &[HeaderAction], note: Option<&Label>) {
let _ = note;
let shown = TitleRow::new(cx.label()).strength(HeaderStrength::Heading).level(TITLE_LEVEL).actions(actions.iter().copied()).show(ui);
if shown.action == Some(HeaderAction::Close) {
cx.request_close();
@@ -318,7 +319,7 @@ impl Component for DialogFrame<'_> {
impl Container for DialogFrame<'_> {
fn header(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
header(ui, cx, close_action(self.closable));
header(ui, cx, close_action(self.closable), None); // P3(pdf-comments-w6): CM-C27
}
fn footer(&mut self, ui: &mut Ui, cx: &mut BodyCx<'_>) {
+1 -1
View File
@@ -32,7 +32,7 @@ pub use host::{DialogHost, DialogResult, FieldRefusal, OpenDialog, StackDialog,
pub use modal::{Dialog, DialogStyle};
pub use prompt::{Prompt, PromptOutput};
pub use prompts::{PromptAnswer, PromptChoice, PromptKind, StandardPrompt, StandardPromptOutput};
pub use recovery::{RecoveredDocument, RecoveryAnswer, RecoveryDialog, RecoveryOutput};
pub use recovery::{RecoveredDocument, RecoveryAnswer, RecoveryChoice, RecoveryDialog, RecoveryOutput};
pub use serde_fields::{serde_fields, set_serde_field};
pub use stack::{DialogId, DialogStack, dialog_id};
pub use unsaved::{UnsavedAnswer, UnsavedChangesDialog, UnsavedChangesOutput};
+5 -1
View File
@@ -75,6 +75,9 @@ pub struct Dialog<'a> {
/// Whether the title row has a close action.
#[prop]
closable: bool,
/// A muted note after the title.
#[prop(into)]
title_note: Option<Label>,
/// The footer stands in a column at the end edge, beside the whole body.
side: bool,
closed: Option<CloseReason>,
@@ -113,6 +116,7 @@ impl<'a> Dialog<'a> {
buttons: Vec::new(),
enter: false,
closable: true,
title_note: None,
side: false,
closed: None,
picked: None,
@@ -464,7 +468,7 @@ impl Container for Dialog<'_> {
if self.holds_outer_gesture() {
outer::keep(ui.ctx(), cx);
}
frame::header(ui, cx, frame::close_action(self.closable));
frame::header(ui, cx, frame::close_action(self.closable), self.title_note.as_ref());
self.keep_window_draggable(ui);
}
+8
View File
@@ -275,6 +275,14 @@ impl StandardPrompt {
Self::new(PromptKind::Custom).message(message)
}
/// The answer Enter gives and the button drawn as default: Proceed unless set. A choice with no button leaves
/// Proceed.
#[must_use]
pub fn default_choice(self, choice: PromptChoice) -> Self {
let _ = choice;
todo!("DG-C16")
}
/// Adds a paragraph after the message, a label of its own.
#[must_use]
pub fn paragraph(mut self, paragraph: impl Into<Label>) -> Self {
+43 -8
View File
@@ -25,12 +25,20 @@ pub struct RecoveredDocument {
pub age: Duration,
/// Why Recover is disabled now ("Stop recording first"), the tooltip of the disabled button; `None` enables it.
pub blocked: Option<String>,
/// The copy is password-protected: the dialog says so, and Recover stays available (a flag apart from `blocked`).
pub protected: bool,
}
impl RecoveredDocument {
/// A document autosaved `age` ago, with Recover available.
pub fn new(key: impl Into<String>, name: impl Into<String>, age: Duration) -> Self {
RecoveredDocument { key: key.into(), name: name.into(), age, blocked: None }
RecoveredDocument { key: key.into(), name: name.into(), age, blocked: None, protected: false }
}
/// Marks the copy password-protected.
#[must_use]
pub fn protected(self) -> Self {
todo!("SH-C34")
}
/// Disables Recover for `reason`.
@@ -43,7 +51,7 @@ impl RecoveredDocument {
/// What the user chose for one document. Closing the dialog (Escape, the close action) is `DialogResult::Cancel`:
/// the copy stays and is offered again at the next launch.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum RecoveryAnswer {
/// Open the autosaved copy as an unsaved document.
@@ -52,6 +60,17 @@ pub enum RecoveryAnswer {
Discard,
}
/// The answer the recovery dialog gives: what to do with the document, and whether to do it for the documents
/// still waiting.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct RecoveryChoice {
/// What to do with the document.
pub answer: RecoveryAnswer,
/// Apply the answer to every remaining document (the Apply to All box was ticked).
pub apply_to_all: bool,
}
/// What the recovery dialog reports: its response, how it closed and the answer given.
#[derive(Debug)]
#[non_exhaustive]
@@ -62,7 +81,7 @@ pub struct RecoveryOutput {
pub closed: Option<CloseReason>,
/// Discard or Recover, the pass a button or Enter answers; `None` when the dialog stays open or was dismissed
/// (Escape, the close action): the copy stays and is offered again at the next launch.
pub answer: Option<RecoveryAnswer>,
pub answer: Option<RecoveryChoice>,
}
impl Outcome for RecoveryOutput {
@@ -82,12 +101,25 @@ pub struct RecoveryDialog {
id: DialogId,
document: RecoveredDocument,
open: bool,
/// The documents still waiting, this one included: the Apply to All box shows while it is above 1.
#[allow(dead_code)] // P3(pdf-shell-w5): SH-C34
remaining: usize,
/// The state of the Apply to All box.
#[allow(dead_code)] // P3(pdf-shell-w5): SH-C34
apply_to_all: bool,
}
impl RecoveryDialog {
/// A dialog offering to recover `document`.
pub fn new(document: RecoveredDocument) -> Self {
Self { id: dialog_id("recovery"), document, open: true }
Self { id: dialog_id("recovery"), document, open: true, remaining: 1, apply_to_all: false }
}
/// The documents still waiting, this one included; the Apply to All box shows while it is above 1.
#[must_use]
pub fn remaining(self, n: usize) -> Self {
let _ = n;
todo!("SH-C34")
}
/// The document asked about; the app reads its key with the answer.
@@ -118,6 +150,8 @@ impl RecoveryDialog {
(Some(CloseReason::Activated | CloseReason::Enter), Some(_)) => Some(RecoveryAnswer::Recover),
_ => None,
};
// P3(pdf-shell-w5): SH-C34: the Apply to All box is not shown yet.
let answer = answer.map(|answer| RecoveryChoice { answer, apply_to_all: false });
RecoveryOutput { response: shown.response, closed: shown.closed, answer }
}
@@ -129,20 +163,21 @@ impl RecoveryDialog {
}
impl StackDialog for RecoveryDialog {
type Result = RecoveryAnswer;
type Result = RecoveryChoice;
fn id(&self) -> DialogId {
self.id
}
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<RecoveryAnswer>> {
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<RecoveryChoice>> {
let shown = self.present(ui, true);
shown.closed?;
Some(shown.answer.map_or(DialogResult::Cancel, DialogResult::Ok))
}
/// Recover, the accepting answer; `None` while recovery is blocked.
fn confirm(&mut self, _: &Context) -> Option<RecoveryAnswer> {
self.document.blocked.is_none().then_some(RecoveryAnswer::Recover)
fn confirm(&mut self, _: &Context) -> Option<RecoveryChoice> {
// P3(pdf-shell-w5): SH-C34
self.document.blocked.is_none().then_some(RecoveryChoice { answer: RecoveryAnswer::Recover, apply_to_all: self.apply_to_all })
}
}
+2
View File
@@ -17,6 +17,7 @@ craft_ui::words! {
changed_on_disk_message: template "prompt.changedOnDiskMessage" = "“{name}” was changed by another app after it was opened or saved here.";
changed_on_disk_detail: "prompt.changedOnDiskDetail" = "Replace it with this document, or cancel and use Save As to keep both.";
replace: "prompt.replace" = "Replace";
save_as: "prompt.saveAs" = "Save As…";
replace_file_title: "prompt.replaceFileTitle" = "Replace file";
replace_file_message: template "prompt.replaceFileMessage" = "“{name}” already exists. Replace it?";
replace_file_detail: template "prompt.replaceFileDetail" = "The name in the save dialog was “{answered}”.";
@@ -43,6 +44,7 @@ craft_ui::words! {
recovery_message: template "recovery.message" = "“{name}” has unsaved changes from an earlier run, autosaved {age}.";
recovery_recover: "recovery.recover" = "Recover";
recovery_discard: "recovery.discard" = "Discard";
recovery_protected: "recovery.protected" = "Password-protected";
// full-window parts
full_window_title_zoom: template "fullWindowTitle.zoomed" = "{name} ({subject}, {zoom})";
full_window_title_subject: template "fullWindowTitle.subject" = "{name} ({subject})";
+11 -1
View File
@@ -67,6 +67,7 @@ use crate::contract::{
Access, Bind, BindMut, BodyCx, Common, Component, Container, ContainerProps, Cx, Edit as _, EditResponse, Focus as _, Outcome, Pad, PaintUi,
PartsCx, Props as _, Role, Sizing, WordSetCx as _,
};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use crate::runtime::focus::KeyUse;
use crate::runtime::memory::sub;
@@ -110,12 +111,21 @@ pub struct PanelTitle {
pub title: Label,
/// Whether the panel's tab shows a close button, where the group's tabs close.
pub closable: bool,
/// The panel's toggle command: the tab resolves it for its marker and its hint.
pub command: Option<CommandRef>,
}
impl PanelTitle {
/// A panel `key` titled `title`, not closable from its tab.
pub fn new(key: PanelKey, title: impl Into<Label>) -> Self {
PanelTitle { key, title: title.into(), closable: false }
PanelTitle { key, title: title.into(), closable: false, command: None }
}
/// The panel's toggle command.
#[must_use]
pub fn command(self, command: Option<CommandRef>) -> Self {
let _ = command;
todo!("CH-C19")
}
/// Whether the panel's tab shows a close button.
+12
View File
@@ -2,6 +2,7 @@
use crate::contract::SizeLimits;
use crate::primitives::IconSpec;
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use craft_host::target::WindowKind;
use egui::Vec2;
@@ -130,6 +131,9 @@ pub struct PanelSpec {
/// The grid the panel lays its content in, which makes a column with steps whole content columns wide and as
/// tall as its content. `None` for a panel that fills the width it gets.
pub grid: Option<DockGrid>,
/// The panel's toggle command: an iconic cell's face is `IconButton::command` of it, so the marker and the hint
/// follow the command.
pub command: Option<CommandRef>,
}
impl PanelSpec {
@@ -145,9 +149,17 @@ impl PanelSpec {
window_kind: WindowKind::Tool,
canvas: false,
grid: None,
command: None,
}
}
/// The panel's toggle command.
#[must_use]
pub fn command(self, command: impl Into<CommandRef>) -> Self {
let _ = command;
todo!("CH-C19")
}
/// The panel's icon.
#[must_use]
pub fn icon(mut self, icon: IconSpec<'static>) -> Self {
+18 -2
View File
@@ -137,13 +137,28 @@ pub struct ToolbarDrawer<'a, T: Value + 'static> {
opens: Side,
dropped: Option<ToolDropped>,
opener: Option<Response>,
/// Whether the drawer searches: a searchable drawer shows a search field under its title and filters its tool rows.
#[prop]
kind: DrawerKind,
}
/// What a `ToolbarDrawer` offers besides its list.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum DrawerKind {
/// The list alone.
#[default]
Plain,
/// A `TextField::search` under the title filters the tool rows; the query lives in the popover's kept state and
/// clears on close.
Searchable,
}
impl<'a, T: Value + 'static> ToolbarDrawer<'a, T> {
/// A drawer beside `rail` (the rail's rect), listing `groups`, over a toolbar of `toolbar` slots. `dropped` is the
/// drag the rail took in this pass (`ToolRailOutput::dropped`); the drawer turns it into an edit.
pub fn new(rail: Rect, groups: &'a [DrawerGroup<T>], toolbar: &'a [ToolSlot<T>], dropped: Option<ToolDropped>) -> Self {
ToolbarDrawer { rail, groups, toolbar, opens: Side::End, dropped, opener: None }
ToolbarDrawer { rail, groups, toolbar, opens: Side::End, dropped, opener: None, kind: DrawerKind::Plain }
}
/// The control that opened the drawer, the rail's Edit Toolbar button (`ToolRailOutput::edit_toolbar`): the focus
@@ -216,7 +231,8 @@ fn on_toolbar<T: PartialEq>(toolbar: &[ToolSlot<T>], id: &T) -> bool {
impl<T: Value + 'static> ToolbarDrawer<'_, T> {
/// Shows the drawer and reports what the user changed.
pub fn show(self, ui: &mut Ui) -> ToolbarDrawerOutput<T> {
let ToolbarDrawer { rail, groups, toolbar, opens, dropped, opener } = self;
let ToolbarDrawer { rail, groups, toolbar, opens, dropped, opener, kind } = self;
let _ = kind; // P3(pdf-chrome-w6): CH-C20
let env = Env::of(ui);
let words = env.words::<RailWords>();
let os = os_of(ui.ctx());
+1 -1
View File
@@ -9,7 +9,7 @@ mod drawer;
mod flyout;
mod tool;
pub use drawer::{DrawerGroup, ToolbarDrawer, ToolbarDrawerOutput, ToolbarEdit, apply_toolbar_edit, drop_edit};
pub use drawer::{DrawerGroup, DrawerKind, ToolbarDrawer, ToolbarDrawerOutput, ToolbarEdit, apply_toolbar_edit, drop_edit};
pub use flyout::{FlyoutButton, FlyoutButtonStyle, FlyoutOutput, SlotEdit};
pub use tool::{
DropAt, LastUsed, RailFooter, RailTool, SlotId, ToolDrag, ToolDropped, ToolRail, ToolRailOutput, ToolRailStyle, ToolSlot, drop_in_slot,
+6 -5
View File
@@ -205,11 +205,12 @@ 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);
let out = List::new("Names").id(list_id).select(SelectMode::Single).filter(&text, |key: &usize| Label::from(NAMES[*key])).show_items(
ui,
&Names,
&mut |key, _| ListRow::new(NAMES[*key]),
);
// P3(pdf-forms-w3): CH-C24
let out = List::new("Names")
.id(list_id)
.select(SelectMode::Single)
.filter(&text, |key: &usize| vec![Label::from(NAMES[*key])])
.show_items(ui, &Names, &mut |key, _| ListRow::new(NAMES[*key]));
sink.borrow_mut().extend(out.events.iter().filter_map(|event| match event {
CollectionEvent::Activate(key) => Some(*key),
_ => None,
+22
View File
@@ -19,6 +19,17 @@ use std::ops::Deref;
/// The part a loading button shows its spinner in.
const SPINNER: PartKey = PartKey::new("spinner");
/// The form of a button's face.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum ButtonForm {
/// The ordinary push button.
#[default]
Push,
/// The command-search opener: a text field's face with the search glyph, the placeholder and the command's chord.
Search,
}
/// The style of a push button.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[style(variants = [Variant::SECONDARY, Variant::PRIMARY, Variant::GHOST, Variant::DANGER, Variant::look(Emphasis::Outline, Tone::Accent)])]
@@ -152,6 +163,10 @@ pub struct Button<'a> {
/// that names an item at the reading start).
#[prop]
align: HAlign,
/// The face: a push button, or the command-search opener.
#[style_key]
#[prop]
form: ButtonForm,
}
impl<'a> Button<'a> {
@@ -166,10 +181,17 @@ impl<'a> Button<'a> {
tint: None,
least_width: None,
align: HAlign::Center,
form: ButtonForm::Push,
}
.label(label)
}
/// The command-search opener: a search field's face showing `placeholder` and the chord of `command`.
pub fn search(command: impl Into<CommandRef>, placeholder: impl Into<Label>) -> Self {
let _ = (command, placeholder);
todo!("CH-C8")
}
/// A button bound to `command`: its label, enabled state and activation follow the command.
pub fn command(command: impl Into<CommandRef>) -> Self {
<Button as Props>::command(Button::new(Label::Empty), command)
+37 -2
View File
@@ -4,8 +4,8 @@ use super::button::ButtonOutput;
use super::face::{self, tinted};
use crate::contract::{Access, Common, Component, Cx, MeasureCx, PaintUi, PopupKind, Props, Role, Styled as _};
use crate::controls::disclosure::DisclosureGlyph;
use crate::primitives::{IconSpec, PaintShape, StrokeWidth};
use crate::runtime::commands::CommandRef;
use crate::primitives::{Draw, IconSpec, PaintShape, StrokeWidth};
use crate::runtime::commands::{CommandRef, ResolvedCommand};
use crate::style::{ComponentStyle, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook};
use craft_behavior::{Metrics, Sense};
use craft_i18n::Direction;
@@ -15,6 +15,34 @@ use craft_theme::{
};
use egui::{Pos2, Vec2};
/// The marker dot's look: the one reading of the tokens that `IconButton` and `Tab` paint it from.
#[derive(Clone, Copy, Debug, PartialEq)]
#[allow(dead_code)] // P3(pdf-chrome-w2): CH-C7
pub(crate) struct MarkerStyle {
/// The dot's diameter.
pub(crate) side: f32,
/// The dot's fill.
pub(crate) color: StyleColor,
/// The dot's edge.
pub(crate) edge: StyleColor,
}
impl MarkerStyle {
/// The marker look from the tokens.
#[allow(dead_code)] // P3(pdf-chrome-w2): CH-C7
pub(crate) fn of(cx: &StyleCx<'_>) -> MarkerStyle {
let _ = cx;
todo!("CH-C7")
}
}
/// Paints the marker dot centred on `center`.
#[allow(dead_code)] // P3(pdf-chrome-w2): CH-C7
pub(crate) fn paint_marker(draw: &Draw<'_>, center: Pos2, style: &MarkerStyle) {
let _ = (draw, center, style);
todo!("CH-C7")
}
/// The style of an icon button.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[style(variants = [
@@ -96,6 +124,13 @@ impl<'a> IconButton<'a> {
pub fn command(icon: impl Into<IconSpec<'a>>, command: impl Into<CommandRef>) -> Self {
<IconButton as Props>::command(IconButton::new(icon), command)
}
/// Whether `command`'s marker shows: it is marked and its content is not shown.
#[allow(dead_code)] // P3(pdf-chrome-w2): CH-C7
pub fn shows_marker(command: &ResolvedCommand) -> bool {
let _ = command;
todo!("CH-C7")
}
}
impl Component for IconButton<'_> {
+1 -1
View File
@@ -10,7 +10,7 @@ mod stories;
pub mod toggle_button;
mod words;
pub use button::{Button, ButtonOutput, ButtonStyle};
pub use button::{Button, ButtonForm, ButtonOutput, ButtonStyle};
pub use icon_button::{IconButton, IconButtonStyle, PopupMark};
pub use link::{Link, LinkStyle};
pub use split_button::{SplitButton, SplitButtonStyle, SplitOutput};
+45 -13
View File
@@ -7,7 +7,7 @@ use crate::contract::{
Access, Activation, Common, Component, Cx, DisabledLook, GroupHandle, MeasureCx, Meta as _, Outcome, PaintUi, Pointer as _, Props as _, Role,
Sizing, Styled as _, WordSetCx as _,
};
use crate::primitives::{ContentPainterCx, Draw, PaintShape, StrokeWidth};
use crate::primitives::{ContentPainterCx, Draw, PaintShape, StrokeWidth, WellFill};
use crate::runtime::requests::ColorRequest;
use crate::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, UiTokens, resolve_style};
use craft_behavior::{Metrics, Mixed, Sense, Value};
@@ -129,7 +129,7 @@ impl<E> crate::contract::ItemOutput<E> for SwatchOutput {
pub struct Swatch<T: Value + 'static = ()> {
#[common]
common: Common,
color: Mixed<Srgba>,
color: Mixed<Option<Srgba>>,
/// The value this swatch stands for in its `RadioGroup`.
member: Option<T>,
/// A cell of a table of touching swatches: `size.icon.md` square with square corners.
@@ -155,7 +155,7 @@ impl Swatch<()> {
pub fn new(label: impl Into<crate::runtime::env::Label>, color: impl Into<Mixed<Srgba>>) -> Self {
Swatch {
common: Common::new(),
color: color.into(),
color: some_color(color.into()),
member: None,
cell: false,
well: false,
@@ -166,6 +166,20 @@ impl Swatch<()> {
}
.label(label)
}
/// A swatch that can be "no colour": `None` paints the empty well and reads as "None".
pub fn optional(label: impl Into<crate::runtime::env::Label>, color: impl Into<Mixed<Option<Srgba>>>) -> Swatch<()> {
let _ = (label, color);
todo!("CM-C25b")
}
}
/// A colour as one that may also be "no colour".
fn some_color(color: Mixed<Srgba>) -> Mixed<Option<Srgba>> {
match color {
Mixed::Same(color) => Mixed::Same(Some(color)),
Mixed::Mixed => Mixed::Mixed,
}
}
impl<T: Value + 'static> Swatch<T> {
@@ -250,10 +264,13 @@ impl<T: Value + 'static> Component for Swatch<T> {
} else if self.cell {
access.role(Role::LIST_BOX_OPTION);
}
match self.color.same() {
Some(color) => {
match self.color.same().copied() {
Some(Some(color)) => {
access.value(color.to_hex());
access.color(*color);
access.color(color);
}
Some(None) => {
access.value(cx.words::<ChoiceWords>().swatch_none.as_str());
}
None => {
access.value(cx.words::<ChoiceWords>().swatch_mixed.as_str());
@@ -266,17 +283,25 @@ impl<T: Value + 'static> Component for Swatch<T> {
}
fn finish(self, cx: Cx<'_, Self>) -> SwatchOutput {
let pick_color =
self.picker.filter(|_| self.activation.is_some()).map(|key| ColorRequest::new(key, self.color.same().copied()).title(cx.label()));
let pick_color = self
.picker
.filter(|_| self.activation.is_some())
.map(|key| ColorRequest::new(key, self.color.same().copied().flatten()).title(cx.label()));
SwatchOutput { response: cx.response.clone(), clicked: self.activation.is_some(), activation: self.activation, pick_color }
}
}
/// The one swatch face painter: the well of `color` in `well` (a checkerboard behind a translucent colour, the dash
/// of a mixed one), then the outline ring, the mark when `marked`, and the selection ring, in `state`.
fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed<Srgba>, marked: bool) {
fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet, color: Mixed<Option<Srgba>>, marked: bool) {
let shape = PaintShape::Rect(well, style.radius);
draw.swatch_well(well, style.radius, color.same().copied());
// P3(pdf-comments-w5): CM-C25a
let fill = match color {
Mixed::Same(Some(color)) => WellFill::Color(color),
Mixed::Same(None) => WellFill::None,
Mixed::Mixed => WellFill::Mixed,
};
draw.swatch_well(well, style.radius, fill);
draw.stroke(&shape, StrokeWidth::Thin, state.resolve(&style.edge));
if marked {
let inside = PaintShape::Rect(well.shrink(draw.width(StrokeWidth::Thin)), style.radius);
@@ -290,14 +315,20 @@ fn paint_face(draw: &Draw<'_>, well: Rect, style: &SwatchStyle, state: &StateSet
/// ring when `selected`.
#[derive(Clone, Copy, Debug)]
pub struct SwatchFace {
color: Mixed<Srgba>,
color: Mixed<Option<Srgba>>,
selected: bool,
}
impl SwatchFace {
/// The face of `color`, not selected.
pub fn new(color: impl Into<Mixed<Srgba>>) -> Self {
SwatchFace { color: color.into(), selected: false }
SwatchFace { color: some_color(color.into()), selected: false }
}
/// The face of a colour that can be "no colour": `None` paints the empty well.
pub fn optional(color: impl Into<Mixed<Option<Srgba>>>) -> SwatchFace {
let _ = color;
todo!("CM-C25b")
}
/// Whether the selected ring shows.
@@ -309,7 +340,8 @@ impl SwatchFace {
/// Paints the face filling `rect`.
pub fn paint(&self, cx: &ContentPainterCx<'_>, rect: Rect) {
let key = Swatch::new("", self.color).style_key();
// P3(pdf-comments-w5): CM-C25b: the key does not read the colour.
let key = Swatch::new("", Mixed::<Srgba>::Mixed).style_key();
let scope = cx.style_cx();
let style = resolve_style(&scope, key, cx.painter.ctx(), Swatch::<()>::style);
let (flags, on) = if self.selected { (Flags::SELECTED, 1.0) } else { (Flags::empty(), 0.0) };
+1
View File
@@ -5,6 +5,7 @@ craft_ui::words! {
pub struct ChoiceWords {
unrated: "choice.ratingUnrated" = "Unrated";
swatch_mixed: "choice.swatchMixed" = "Mixed";
swatch_none: "choice.swatchNone" = "None";
stars: count "choice.ratingStars" = "{n} star" | "{n} stars";
}
}
+9
View File
@@ -45,6 +45,8 @@ enum Source<'a> {
Image { key: u64, image: &'a dyn Fn() -> ColorImage },
/// A content painter that paints into the picture's rect.
Painter(Paint<'a>),
/// An SVG asset, rasterised at the picture's drawn size.
Svg(#[allow(dead_code)] &'static [u8]), // P3(pdf-chrome-w2): CH-C26
}
/// A picture of an image the caller makes (`new`) or of what a content painter paints (`painter`); both sit in a rect
@@ -83,6 +85,12 @@ impl<'a> Picture<'a> {
Picture::from_source(label, Source::Painter(Box::new(paint))).aspect(aspect)
}
/// A picture of the SVG asset `svg`, rasterised through `craft-svg` at the picture's drawn size; a malformed or
/// oversized SVG draws nothing. `label` names it for a screen reader; an empty one leaves it decorative.
pub fn svg(label: impl Into<Label>, svg: &'static [u8]) -> Self {
Picture::from_source(label, Source::Svg(svg))
}
fn from_source(label: impl Into<Label>, source: Source<'a>) -> Self {
Picture { common: Common::new(), revision: Revision::default(), source, aspect: ThumbAspect::SQUARE, extent: PictureSize::Icon }.label(label)
}
@@ -137,6 +145,7 @@ impl Component for Picture<'_> {
ui.content_painter(cx).picture(texture.id, target, whole, 0.0);
}
Source::Painter(paint) => paint(&ui.content_painter(cx), cx.content_rect),
Source::Svg(_) => todo!("CH-C26"),
}
}
+3 -3
View File
@@ -21,12 +21,12 @@ pub use findings::{Finding, Findings, FindingsList, FindingsListStyle, FindingsS
pub use predicate::{DropTest, RowTest, RowText};
pub(crate) use row::RowThumb;
pub use row::{
ListRow, ListRowStyle, RowDragSpot, RowEvent, RowInk, RowOutput, RowStyleCx, ThumbAspect, ThumbPaint, ThumbSize, ThumbTarget, ThumbTargets,
TrailingFace, TrailingPart, label_color_label, tree_steps,
CellStatus, HueTarget, ListRow, ListRowStyle, RowDragSpot, RowEvent, RowInk, RowLines, RowOutput, RowStyleCx, ThumbAspect, ThumbPaint, ThumbSize,
ThumbTarget, ThumbTargets, TrailingFace, TrailingPart, label_color_label, tree_steps,
};
pub use toggle::{ToggleCell, ToggleFace, ToggleState};
pub use tree::OpenSet;
pub use undo::{UndoList, UndoListStyle, UndoMark, UndoRows, footer_text, undo_count};
pub use view::{List, ListStyle};
pub use view::{DocumentRows, List, ListStyle};
pub use view_words::{EventWords, FindingsWords, UndoWords};
pub use words::ListWords;
+140 -2
View File
@@ -8,14 +8,18 @@
//! collection that shows the row; the row draws the look the item step gives it and reports what its own parts do.
use super::toggle::ToggleCell;
use super::view::DocumentRows;
use super::words::ListWords;
use crate::contract::{Common, OpenChange, RowHeight, RowPressed, RowState, Show};
use crate::primitives::{ContentPainterCx, HAlign, IconSpec};
use crate::primitives::{ContentPainterCx, HAlign, IconSpec, Span};
use crate::runtime::env::Label;
use crate::style::DataColor;
use craft_behavior::{ColumnKey, Cursor};
use craft_i18n::Word;
use craft_theme::variant::Tone;
use craft_theme::{LabelColor, TypeRole};
use egui::Rect;
use std::borrow::Cow;
use std::sync::Arc;
mod output;
@@ -88,6 +92,110 @@ pub enum RowInk {
Dimmed,
}
/// The part of a row that a colour from data inks.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum HueTarget {
/// The row's icon.
#[default]
Icon,
/// The row's label.
Label,
}
/// The wrapped text under a row's label: one run, or styled spans such as a search match.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub enum RowLines {
/// Plain text.
Plain(Label),
/// Spans, which paint as `TextRun::spans` does.
Spans(Vec<Span<'static>>),
}
impl RowLines {
// P3(pdf-chrome-w3): CH-C11: the text where the body still reads a plain label.
/// The text as one string: the label, or the spans joined.
pub(super) fn text(&self) -> Cow<'_, str> {
match self {
RowLines::Plain(label) => Cow::Borrowed(label.as_str()),
RowLines::Spans(spans) => Cow::Owned(spans.iter().map(|span| span.text.as_ref()).collect()),
}
}
}
impl From<Label> for RowLines {
fn from(label: Label) -> Self {
RowLines::Plain(label)
}
}
impl From<&'static str> for RowLines {
fn from(text: &'static str) -> Self {
RowLines::Plain(text.into())
}
}
impl From<String> for RowLines {
fn from(text: String) -> Self {
RowLines::Plain(text.into())
}
}
impl From<Arc<str>> for RowLines {
fn from(text: Arc<str>) -> Self {
RowLines::Plain(text.into())
}
}
impl From<Word> for RowLines {
fn from(word: Word) -> Self {
RowLines::Plain(word.into())
}
}
impl From<Vec<Span<'static>>> for RowLines {
fn from(spans: Vec<Span<'static>>) -> Self {
RowLines::Spans(spans)
}
}
/// A status in a table cell: a tone icon, toned text, a tip and an action link.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub struct CellStatus {
/// The tone of the icon and the text.
pub tone: Tone,
/// The status text.
pub text: Label,
/// A multi-line tip.
pub tip: Option<Label>,
/// The focusable action link's text.
pub action: Option<Label>,
}
impl CellStatus {
/// A status of `tone` reading `text`.
pub fn new(tone: Tone, text: impl Into<Label>) -> Self {
let _ = (tone, text);
todo!("WF-W8")
}
/// The multi-line tip shown over the cell.
#[must_use]
pub fn tip(self, tip: impl Into<Label>) -> Self {
let _ = tip;
todo!("WF-W8")
}
/// The focusable action link; activating it reports `RowEvent::CellAction`.
#[must_use]
pub fn action(self, action: impl Into<Label>) -> Self {
let _ = action;
todo!("WF-W8")
}
}
/// A text shown in one column of a row: the body role in the row's ink, on one elided line or wrapped.
pub(super) struct TextCell {
pub column: ColumnKey,
@@ -195,11 +303,17 @@ pub struct ListRow<'a> {
/// Secondary text under the detail line, wrapped to the label band's width. The row's height follows the
/// wrapped lines.
#[prop(into)]
pub(super) lines: Option<Label>,
pub(super) lines: Option<RowLines>,
/// The most lines of `lines` the row shows: longer text is cut with an ellipsis at the end of the last one, and
/// the row is no taller than with exactly that many lines. A screen reader reads all of the text.
#[prop(quantity = "count")]
pub(super) line_limit: Option<u8>,
/// The colour from data that inks a part of the row.
#[allow(dead_code)] // P3(pdf-chrome-w3): CH-C10a
pub(super) hue: Option<(DataColor, HueTarget)>,
/// The row's label is document text at the list's font, size and alignment.
#[allow(dead_code)] // P3(pdf-chrome-w3): FM-PF11b
pub(super) document: Option<DocumentRows>,
/// A progress bar under the label, `fraction` full (clamped to 0..=1), in a line of its own below the detail. The
/// row is one caption line taller than its detail makes it, so a list with fixed row heights adds one
/// (`ListRow::row_height` counts the detail only). A screen reader reads the percentage in the row's description.
@@ -313,6 +427,8 @@ impl<'a> ListRow<'a> {
detail: None,
lines: None,
line_limit: None,
hue: None,
document: None,
progress: None,
accessible_name: None,
spacer: false,
@@ -401,6 +517,28 @@ impl<'a> ListRow<'a> {
self
}
/// A colour from data inks `target` of the row in place of its tone or ink, read against the row's surface; a
/// selected row keeps the selection ink and a dimmed or disabled row its ink.
#[must_use]
pub fn hue(self, color: DataColor, target: HueTarget) -> Self {
let _ = (color, target);
todo!("CH-C10a")
}
/// A status cell in `column`: a tone icon, toned text, a multi-line tip and a focusable action link.
#[must_use]
pub fn cell_status(self, column: ColumnKey, status: CellStatus) -> Self {
let _ = (column, status);
todo!("WF-W8")
}
/// A tooltip over the text cell of `column`.
#[must_use]
pub fn cell_tip(self, column: ColumnKey, tip: impl Into<Label>) -> Self {
let _ = (column, tip);
todo!("WF-W9")
}
/// The column `column` reads in the muted look: its text cell, or the label when it is the label column.
#[must_use]
pub fn cell_muted(mut self, column: ColumnKey) -> Self {
+7
View File
@@ -7,6 +7,7 @@ use super::thumb::ThumbTarget;
use super::trailing::TrailingPart;
use crate::contract::{ItemOutput, NoValue, OpenChange, Outcome};
use crate::runtime::commands::FireSource;
use craft_behavior::ColumnKey;
use craft_keymap::Mods;
use egui::{Rect, Response};
@@ -59,6 +60,12 @@ pub enum RowEvent {
/// The press count of the click, as [`ThumbClicked`](Self::ThumbClicked) counts it.
clicks: u32,
},
/// The action of a status cell ([`ListRow::cell_status`]) was activated.
#[non_exhaustive]
CellAction {
/// The column of the cell.
column: ColumnKey,
},
}
/// What a row returns.
+2 -1
View File
@@ -159,8 +159,9 @@ impl ListRow<'_> {
let style = cx.style;
let sizes = &style.sizes;
let rtl = cx.env.direction().is_rtl();
// P3(pdf-chrome-w3): CH-C11: spans paint as their joined text until the writer lays them out as spans.
let wrapped = self.lines.as_ref().map(|text| {
let run = TextRun::new(text.as_str()).role(style.detail.role).color(cx.resolve(&style.detail.color)).wrap(self.lines_wrap());
let run = TextRun::new(text.text()).role(style.detail.role).color(cx.resolve(&style.detail.color)).wrap(self.lines_wrap());
draw.layout(&run, self.text_block(label, sizes, 0.0).0.width())
});
let lines = wrapped.as_ref().map_or(0.0, |layout| sizes.gap + layout.size().y);
+6 -4
View File
@@ -130,8 +130,9 @@ impl Component for ListRow<'_> {
let probe = self.place_in(&[], sizes, &widths, Rect::from_min_size(Pos2::ZERO, Vec2::new(room, height)), rtl);
let probe_min = probe.min_width + toggles;
let band = cx.room.map_or(f32::INFINITY, |_| (probe.label.width() - toggles).max(0.0));
// P3(pdf-chrome-w3): CH-C11: spans measure as their joined text until the writer measures them as spans.
let wrapped = self.lines.as_ref().map_or(0.0, |text| {
let run = TextRun::new(text.as_str()).role(cx.style.detail.role).wrap(self.lines_wrap());
let run = TextRun::new(text.text()).role(cx.style.detail.role).wrap(self.lines_wrap());
sizes.gap + cx.layout_at(&run, band).size().y
});
let detail = if self.detail_line() { sizes.detail_line } else { 0.0 };
@@ -231,14 +232,15 @@ impl Component for ListRow<'_> {
// row does not hide.
if let Some(text) = self.lines.as_ref().filter(|_| self.line_limit.is_some()) {
let sizes = &cx.style.sizes;
let run = TextRun::new(text.as_str()).role(cx.style.detail.role).wrap(self.lines_wrap());
// P3(pdf-chrome-w3): CH-C11
let run = TextRun::new(text.text()).role(cx.style.detail.role).wrap(self.lines_wrap());
let layout = cx.layout_at(&run, self.text_block(placed.label, sizes, 0.0).0.width());
if layout.elided {
let (band, top) = self.text_block(placed.label, sizes, sizes.gap + layout.size().y);
let detail = if self.detail_line() { sizes.detail_line } else { 0.0 };
let lines_top = top + sizes.label_line + detail + sizes.gap;
let rect = Rect::from_x_y_ranges(band.x_range(), lines_top..=lines_top + layout.size().y);
cx.part(LINES, rect).tooltip(text.clone());
cx.part(LINES, rect).tooltip(Label::from(text.text().into_owned())); // P3(pdf-chrome-w3): CH-C11
}
}
let mut focusable = false;
@@ -409,7 +411,7 @@ impl Component for ListRow<'_> {
.then(|| words.clipped.as_str().to_owned())
.into_iter()
.chain(self.common.description.clone())
.chain(self.lines.as_ref().filter(|_| self.line_limit.is_some()).map(|text| text.as_str().to_owned()))
.chain(self.lines.as_ref().filter(|_| self.line_limit.is_some()).map(|text| text.text().into_owned())) // P3(pdf-chrome-w3): CH-C11
.chain(percent)
.chain(icons)
.collect();
+35 -5
View File
@@ -9,6 +9,8 @@ use crate::contract::{
Access, ActivateOn, Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnLayout, Common, Component, ContainerProps, Cx,
DropKind, EdgePress, EditResponse, LeadOnOpen, ListDrag, Props as _, Role, RowState, SelectMode, Sizing,
};
use crate::fonts::FontRef;
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};
@@ -17,6 +19,26 @@ use egui::{Rect, Ui};
use std::borrow::Cow;
use std::hash::{DefaultHasher, Hash, Hasher};
/// How the rows of a list show their labels as document text: the document's font, size and alignment.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq)]
pub struct DocumentRows {
/// The font of the labels.
pub font: FontRef,
/// The size of the labels.
pub size: f32,
/// The alignment of the labels.
pub align: HAlign,
}
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")
}
}
/// The style of the list: it has no look of its own beyond its container's surface.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
@@ -110,6 +132,13 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
.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")
}
/// The options list of a value picker's popup (completions, number presets, `PopupList`): one selection, a click
/// activates, the lead starts on the first row and follows the pointer, typed letters move it, and a press leaves
/// the key focus on the opener, whose list keys the host forwards while the popup is open. Its rows are
@@ -130,12 +159,12 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
/// 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.
#[must_use]
pub fn filter(mut self, query: &str, label: impl Fn(&K) -> Label + 'a) -> Self {
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(label) });
self.filter = Some(Filter { query: query.to_owned(), label: Box::new(texts) });
self
}
@@ -206,8 +235,9 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
}
let mut kept: Vec<(craft_i18n::matcher::Rank, usize)> = (0..source.len())
.filter_map(|at| {
let label = (filter.label)(&source.key(at)).resolved(&env.words);
matcher.score(label.as_str()).map(|found| (found.rank, 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))
})
.collect();
if self.ranked {
@@ -270,7 +300,7 @@ 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.
struct Filter<'a, K> {
query: String,
label: Box<dyn Fn(&K) -> Label + 'a>,
label: Box<dyn Fn(&K) -> Vec<Label> + 'a>,
}
/// The rows of `source` at the positions `at`, in that order.
+59
View File
@@ -0,0 +1,59 @@
//! `MenuIconRow`: one stop in a menu that holds a row of icons.
use crate::primitives::IconSpec;
use crate::runtime::env::Label;
use egui::{Response, Ui};
/// One icon of a `MenuIconRow`.
#[allow(dead_code)] // P3(pdf-edit-w5): ED-F11
pub struct MenuIcon<'a> {
icon: IconSpec<'a>,
label: Label,
enabled: bool,
}
impl<'a> MenuIcon<'a> {
/// An icon `icon` named `label`.
pub fn new(icon: impl Into<IconSpec<'a>>, label: impl Into<Label>) -> Self {
let _ = (icon, label);
todo!("ED-F11")
}
/// Whether the icon can be picked.
#[must_use]
pub fn enabled(self, enabled: bool) -> Self {
let _ = enabled;
todo!("ED-F11")
}
}
/// A menu row of icons that is one stop: Left and Right rove among the icons, Up and Down leave the row to the
/// neighbouring menu rows as from any row. Picking an icon runs it and closes the menu chain by the menu item rule.
#[allow(dead_code)] // P3(pdf-edit-w5): ED-F11
pub struct MenuIconRow<'a> {
label: Label,
icons: &'a [MenuIcon<'a>],
}
impl<'a> MenuIconRow<'a> {
/// A row named `label` of `icons`.
pub fn new(label: impl Into<Label>, icons: &'a [MenuIcon<'a>]) -> Self {
let _ = (label, icons);
todo!("ED-F11")
}
/// Shows the row in the menu.
pub fn show(self, ui: &mut Ui) -> MenuIconRowOutput {
let _ = ui;
todo!("ED-F11")
}
}
/// What a `MenuIconRow` returns.
#[non_exhaustive]
pub struct MenuIconRowOutput {
/// The row's response.
pub response: Response,
/// The index of the icon picked in this pass.
pub picked: Option<usize>,
}
+2
View File
@@ -2,6 +2,7 @@
pub mod bar;
mod edit;
mod icon_row;
pub(crate) mod item;
#[doc(hidden)]
pub mod level;
@@ -15,6 +16,7 @@ mod words;
pub use bar::{MenuBar, MenuBarOutput, MenuBarStyle, MenuHelp, MenuTitle};
pub(crate) use edit::text_menu;
pub use edit::{EditMenu, EditMenuOutput};
pub use icon_row::{MenuIcon, MenuIconRow, MenuIconRowOutput};
pub use item::{MenuItem, MenuItemOutput, MenuItemStyle};
pub use panel::{GroupItem, PanelMenu, PanelMenuOutput, PanelRow};
#[doc(hidden)]
+28 -1
View File
@@ -34,12 +34,30 @@ pub struct PostedNotice {
/// Stays until dismissed, whatever the center's timeout (an error the user must read).
#[prop(flag)]
sticky: bool,
/// How far the job has got, between 0 and 1: the card shows a progress bar and the percentage.
#[prop]
progress: Option<f32>,
/// The notice's own action; activating it ends the notice as `NoticeEnd::Action`.
#[prop(into)]
action: Option<Label>,
/// The message under the title: a title and a message on one card.
#[prop(into)]
message: Option<String>,
}
impl PostedNotice {
/// A notice titled `title` in the neutral tone.
pub fn new(title: impl Into<String>) -> Self {
PostedNotice { title: title.into(), lines: Vec::new(), tone: Tone::Neutral, dismiss_key: None, sticky: false }
PostedNotice {
title: title.into(),
lines: Vec::new(),
tone: Tone::Neutral,
dismiss_key: None,
sticky: false,
progress: None,
action: None,
message: None,
}
}
}
@@ -53,6 +71,8 @@ pub enum NoticeEnd {
Expired(ToastId),
/// The window's card limit removed the notice to make room for a newer one.
Dropped(ToastId),
/// The notice's own action ([`PostedNotice::action`]) was activated.
Action(ToastId),
/// "Don't Show Again": the app stores `key` as silenced.
#[non_exhaustive]
Silenced {
@@ -148,6 +168,13 @@ impl NoticeCenter {
toast::keep(ctx, id);
}
/// Sets how far the job of notice `id` has got, `fraction` between 0 and 1, and its message; the center keeps
/// tracking the id.
pub fn set_progress(&self, ctx: &Context, id: ToastId, fraction: f32, message: Option<Label>) {
let _ = (ctx, id, fraction, message);
todo!("CH-C16")
}
/// Removes a notice the app no longer needs (the job it reported on was cancelled).
pub fn remove(&self, ctx: &Context, id: ToastId) {
toast::dismiss(ctx, id);
+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| labels[*key].clone())
.filter(&query, |key| vec![labels[*key].clone()]) // P3(pdf-forms-w3): CH-C24
.ranked(true)
.show_items(ui, &rows, &mut |key, _| rows.row(*key, current, decorate, None))
.events
+2
View File
@@ -7,11 +7,13 @@
mod calendar;
mod codec;
mod popover;
#[cfg(feature = "testing")]
mod stories;
pub use calendar::{Calendar, CalendarOutput, CalendarStyle, CalendarView, local_month_grid, month_grid};
pub use codec::DateCodec;
pub use popover::{CalendarPopover, CalendarPopoverStyle};
use super::words::PickerWords;
use crate::buttons::{IconButton, Link};
@@ -0,0 +1,98 @@
//! `CalendarPopover`: the calendar of a `DatePicker` hung from any rect.
use super::{DatePrecision, PickedDate};
use crate::contract::{Bind, BindMut, Common, Component, Container, ContainerProps, Cx, Overlay, Role};
use crate::popover::PopoverOutput;
use crate::runtime::env::Label;
use crate::runtime::overlay::CloseReason;
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{Metrics, Sense};
use egui::Response;
/// The style of a calendar popover: the surface comes from the container.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct CalendarPopoverStyle {
#[style(metrics)]
metrics: Metrics,
}
/// A calendar hung from any rect that shares `DatePicker`'s overlay body: the precision switch, Today, Clear and the
/// hover preview, so there is one calendar body.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(container)]
#[allow(dead_code)] // P3(pdf-forms-w4): FM-PF14
pub struct CalendarPopover<'a> {
#[common]
common: Common,
#[container]
props: ContainerProps,
open: Bind<'a, bool>,
closed: Option<CloseReason>,
value: Bind<'a, Option<PickedDate>>,
/// The precisions offered; the first is the popup's page when the value has none of them.
#[prop]
precisions: &'a [DatePrecision],
/// The earliest value allowed.
#[prop]
min: Option<PickedDate>,
/// The latest value allowed.
#[prop]
max: Option<PickedDate>,
/// What today is: the calendar rings its cell and the Today link picks it.
#[prop]
today: Option<PickedDate>,
}
impl<'a> CalendarPopover<'a> {
/// A calendar popover named `label`, open while `open` is true, reading and writing `value`.
pub fn new(label: impl Into<Label>, open: Bind<'a, bool>, value: Bind<'a, Option<PickedDate>>) -> Self {
let _ = (label, open, value);
todo!("FM-PF14")
}
/// The rect the calendar hangs from; the popover closes when the opener is no longer shown.
#[must_use]
pub fn opened_by(self, opener: &Response) -> Self {
let _ = opener;
todo!("FM-PF14")
}
/// Changes the popover's overlay as `Popover::overlay` does.
#[must_use]
pub fn overlay(self, change: impl FnOnce(Overlay) -> Overlay) -> Self {
let _ = change;
todo!("FM-PF14")
}
}
impl Component for CalendarPopover<'_> {
const ROLE: Role = Role::GROUP;
const PARTS: bool = false;
const STOPS: bool = false;
type Style = CalendarPopoverStyle;
type Output = PopoverOutput;
fn style(_: &StyleCx<'_>, _: CalendarPopoverStyleKey) -> CalendarPopoverStyle {
CalendarPopoverStyle::default()
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn finish(self, cx: Cx<'_, Self>) -> PopoverOutput {
let _ = cx;
todo!("FM-PF14")
}
}
impl Container for CalendarPopover<'_> {
fn open(&mut self) -> Option<BindMut<'_, bool>> {
Some(self.open.reborrow())
}
fn closed(&mut self, why: CloseReason) {
self.closed.get_or_insert(why);
}
}
+2 -1
View File
@@ -16,7 +16,8 @@ mod reference_point;
pub use combo_box::ComboBox;
pub use date::{
Calendar, CalendarOutput, CalendarStyle, CalendarView, DateCodec, DatePicker, DatePrecision, PickedDate, local_month_grid, month_grid,
Calendar, CalendarOutput, CalendarPopover, CalendarPopoverStyle, CalendarStyle, CalendarView, DateCodec, DatePicker, DatePrecision, PickedDate,
local_month_grid, month_grid,
};
pub use dress::RowDress;
pub use face::{FaceKind, SelectFace, SelectFaceStyle, toggle_on_key};
+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| labels[*at].clone())
.filter(&query, |at| vec![labels[*at].clone()]) // P3(pdf-forms-w3): CH-C24
.show_items(ui, &rows, &mut |at, _| rows.row(*at, held, dress, picture))
.events
});
@@ -47,6 +47,14 @@ impl<'a> PopupList<'a> {
PopupList { common: Common::new(), props, open, closed: None }.label(label)
}
/// 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 {
+10 -1
View File
@@ -35,12 +35,14 @@ pub struct DocumentTab<D> {
pub detail: Option<Label>,
/// The accessible name of the close button, for a tab whose close cancels the opening.
pub close_label: Option<Label>,
/// Hover text; `DocumentTabs::show` passes it as the tab's tooltip. A tab whose label is cut shows the full label, then this text on the next line.
pub tooltip: Option<Label>,
}
impl<D> DocumentTab<D> {
/// A closable, unmodified tab for document `id` named `label`.
pub fn new(id: D, label: impl Into<Label>) -> Self {
DocumentTab { id, label: label.into(), modified: false, closable: true, progress: None, detail: None, close_label: None }
DocumentTab { id, label: label.into(), modified: false, closable: true, progress: None, detail: None, close_label: None, tooltip: None }
}
/// Unsaved changes.
@@ -77,6 +79,13 @@ impl<D> DocumentTab<D> {
self.close_label = Some(label.into());
self
}
/// Hover text for the tab.
#[must_use]
pub fn tooltip(self, text: impl Into<Label>) -> Self {
let _ = text;
todo!("CH-C6")
}
}
/// What the tabs of a group did this pass, in the order they happened.
+4
View File
@@ -153,6 +153,9 @@ pub struct Tab<'a> {
/// The close button's name and tooltip in place of "Close {tab}" (a tab still opening names it "Cancel opening").
#[prop(into)]
close_label: Option<Label>,
/// The marker dot after the last text: the tab's content has something to show.
#[prop]
marked: bool,
/// The tab's place in its set when it is shown alone; inside a strip the item step gives it.
#[prop]
position: Option<SetPosition>,
@@ -173,6 +176,7 @@ impl<'a> Tab<'a> {
closable: None,
progress: None,
close_label: None,
marked: false,
position: None,
placed: None,
event: None,
+2
View File
@@ -9,6 +9,7 @@ mod linked;
mod number;
mod selectable_text;
mod text_field;
mod word_run;
mod words;
mod zoom_field;
@@ -20,6 +21,7 @@ pub use linked::{LinkMode, LinkedFields, LinkedFieldsStyle, LinkedLayout, Linked
pub use number::{NamedOr, NumberField, NumberName, NumberOutput, NumberPick, NumberStepper, NumberStyle, NumberValue, RangeAlert};
pub use selectable_text::{SelectableStyle, SelectableText};
pub use text_field::TextField;
pub use word_run::{RunWord, WordRun, WordRunOutput, WordState};
pub use words::TextWords;
pub use zoom_field::{InvalidZoom, ZoomField, ZoomFieldOutput};
+8 -1
View File
@@ -9,7 +9,7 @@ use crate::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, OverlayUi, PaintUi, PartsCx, Pointer as _, Props as _, Role, Sizing,
Styled as _, WordSetCx as _,
};
use crate::primitives::{Completer, IconSpec, TextOptions, TextRun};
use crate::primitives::{Completer, IconSpec, SubmitKey, TextOptions, TextRun};
use crate::runtime::env::{Label, Message};
use craft_behavior::{Codec, IconId, PartKey, PlainText, Proposal, Sense};
use egui::{Id, Rect, Vec2};
@@ -204,6 +204,13 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// The key that submits a multi-line field (`TextOptions::submit_key`).
#[must_use]
pub fn submit_key(self, key: SubmitKey) -> Self {
let _ = key;
todo!("CM-C24b")
}
/// Completion candidates for the text before the caret. The text adapter owns the list and the keys it takes.
#[must_use]
pub fn complete(mut self, completer: impl Completer + 'static) -> Self {
+60
View File
@@ -0,0 +1,60 @@
//! `WordRun`: a wrapping run of pickable words in one Tab stop.
use crate::contract::Bind;
use crate::runtime::env::Label;
use egui::{Response, Ui};
/// How a word of a `WordRun` shows.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum WordState {
/// Plain.
#[default]
Normal,
/// Struck through.
Struck,
/// Underlined.
Underlined,
}
/// A word of a `WordRun`.
#[derive(Clone, Debug, PartialEq)]
pub struct RunWord<K> {
/// What the word is picked as.
pub key: K,
/// The word's text.
pub text: String,
/// How the word shows.
pub state: WordState,
}
/// A wrapping run of pickable words in one Tab stop.
#[allow(dead_code)] // P3(pdf-print-ocr-w2): PO-P15
pub struct WordRun<'a, K> {
label: Label,
words: &'a [RunWord<K>],
selected: Bind<'a, Option<K>>,
}
impl<'a, K> WordRun<'a, K> {
/// A run named `label` of `words`; the picked word's key is `selected`.
pub fn new(label: impl Into<Label>, words: &'a [RunWord<K>], selected: Bind<'a, Option<K>>) -> Self {
let _ = (label, words, selected);
todo!("PO-P15")
}
/// Shows the run.
pub fn show(self, ui: &mut Ui) -> WordRunOutput<K> {
let _ = ui;
todo!("PO-P15")
}
}
/// What a `WordRun` returns.
#[non_exhaustive]
pub struct WordRunOutput<K> {
/// The run's response.
pub response: Response,
/// The key of the word picked in this pass.
pub picked: Option<K>,
}
+53 -5
View File
@@ -11,7 +11,7 @@ mod stories;
use super::headers::Outline;
use super::layout::{Around, ArrangeSpacing, GridLayout, Recipe, Slot, TailRow, TileGroup, Tiling, arrange, aspects_of, slot_at};
use super::tile::AroundPicture;
use super::{CaptionPlace, Tile, TilePartEvent, ZoomStep};
use super::{CaptionPlace, Tile, TileActionPlace, TilePartEvent, TileZoom, ZoomStep};
use crate::contract::{
Access, Bind, BindMut, Collection, CollectionEvent, CollectionProps, CollectionResponse, ColumnKind, ColumnSpec, Common, Component,
ContainerProps, Cx, DropKind, EditResponse, Focus as _, ListDrag, Meta as _, NoValue, Notch, Outcome, PaintUi, PartsCx, Pointer as _, Props as _,
@@ -55,6 +55,22 @@ pub enum RatingKeys {
CommandDigits,
}
/// The size of a grid's tiles.
#[non_exhaustive]
pub enum GridZoom<'a> {
/// A picture side factor the host holds.
Fixed(f64),
/// A factor the grid steps itself: Cmd/Ctrl `=`, `-` and `0` and Ctrl/Cmd with the wheel or a pinch, through
/// `TileZoom::step`, keeping the tile under the pointer in place.
Bound(Bind<'a, f64>, TileZoom),
}
impl Default for GridZoom<'_> {
fn default() -> Self {
GridZoom::Fixed(1.0)
}
}
/// What the grid reports besides the collection's events.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
@@ -87,6 +103,12 @@ pub enum GridEvent<K> {
/// Cmd/Ctrl with `=` or `+`, `-` or `0` on a grid that `zooms`: a step of the tile size. Cmd/Ctrl+0 is a rating key
/// under `RatingKeys::CommandDigits`, so it clears the rating there instead of resetting the size.
Zoom(ZoomStep),
/// The insert gap before display position `at` was activated ([`TileGrid::insert_gaps`]).
#[non_exhaustive]
Insert {
/// The display position the insertion goes before.
at: usize,
},
/// A group header asks for its context menu: a secondary click, the context-menu key or Shift+F10.
#[non_exhaustive]
GroupMenu {
@@ -217,8 +239,11 @@ pub struct TileGrid<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
#[prop(quantity = "aspect ratio")]
aspect: f32,
/// The picture side as a multiple of the thumbnail side the grid sizes from; 1 is that side.
#[prop(quantity = "zoom factor")]
zoom: f32,
zoom: GridZoom<'a>,
/// Where every tile's hover actions sit.
#[allow(dead_code)] // P3(pdf-workflows-w2): CV-C25
#[prop]
action_place: TileActionPlace,
/// The thumbnail size the zoom is a factor of; `None` is the card thumbnail.
#[prop]
thumb_size: Option<ThumbSize>,
@@ -304,7 +329,8 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
justified: false,
fill_row: false,
aspect: 1.0,
zoom: 1.0,
zoom: GridZoom::Fixed(1.0),
action_place: TileActionPlace::Corner,
thumb_size: None,
content_cells: false,
card_columns: 0,
@@ -330,6 +356,21 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
.label(label)
}
/// The size of the tiles: a factor the host holds, or one the grid steps itself through a binding.
#[must_use]
pub fn zoom(self, zoom: GridZoom<'a>) -> Self {
let _ = zoom;
todo!("WF-W12")
}
/// Insert gaps between tiles, keyed by display position; `label` names the gap before a position. None show
/// while a drag is held. A press on one reports [`GridEvent::Insert`].
#[must_use]
pub fn insert_gaps(self, label: &'a dyn Fn(usize) -> Label) -> Self {
let _ = label;
todo!("CV-C26")
}
/// Which keys rate the selected tiles. Digit keys reach the grid as digits only while this is on.
#[must_use]
pub fn rating_keys(mut self, keys: RatingKeys) -> Self {
@@ -447,7 +488,14 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> TileGrid<'a, K> {
fn picture_side(&self, style: &GridSizes, item: Option<Vec2>, around: Around) -> f32 {
match item.filter(|_| self.content_cells) {
Some(item) => (item.x - around.size().x).max(1.0),
None => style.picture_side(self.zoom, self.thumb_size),
None => {
// P3(pdf-workflows-w2): CV-C27: a bound zoom reads its binding's value.
let zoom = match &self.zoom {
GridZoom::Fixed(factor) => *factor as f32,
_ => 1.0,
};
style.picture_side(zoom, self.thumb_size)
}
}
}
@@ -1,6 +1,6 @@
//! Stories of `TileGrid`.
use super::{GridEvent, RatingKeys, TileGrid, TileGridOutput, TileGroup};
use super::{GridEvent, GridZoom, RatingKeys, TileGrid, TileGridOutput, TileGroup};
use crate::contract::{ShowCollection as _, SpaceAction};
use crate::list::ThumbAspect;
use crate::testing::pictures::StoryPictures;
@@ -103,7 +103,7 @@ impl ItemSource<usize> for Photos {
fn grid(ui: &mut Ui, data: &mut StoryData, grid: TileGrid<'_, usize>, count: usize, zoom: f64) -> TileGridOutput<usize> {
let pictures = StoryPictures::of(ui.ctx());
let zoom = data.value("zoom", zoom);
let grid = grid.rating_keys(RatingKeys::CommandDigits).space(SpaceAction::Preview).zooms().zoom(*zoom as f32);
let grid = grid.rating_keys(RatingKeys::CommandDigits).space(SpaceAction::Preview).zooms().zoom(GridZoom::Fixed(*zoom)); // P3(pdf-workflows-w2): WF-W12
let mut ratings = Ratings::of(data, count);
let out = grid.show_items(ui, &Photos(count), &mut |key, _| photo(&pictures, *key, ratings.0[*key]));
ratings.apply(&out.events);
+2 -2
View File
@@ -16,10 +16,10 @@ use crate::runtime::env::Label;
use craft_behavior::IconId;
use craft_theme::variant::Tone;
pub use grid::{GridEvent, RatingKeys, TileGrid, TileGridOutput, TileGridStyle};
pub use grid::{GridEvent, GridZoom, RatingKeys, TileGrid, TileGridOutput, TileGridStyle};
pub use layout::{Around, ArrangeSpacing, GridLayout, TailRow, TileArrangement, TileGroup, TileRow, Tiling, arrange, aspects_of};
pub use slider::{ThumbnailSlider, ThumbnailSliderStyle, TileZoom, ZoomStep};
pub use tile::{Tile, TileOutput, TilePartEvent, TileStyle};
pub use tile::{StackLook, Tile, TileActionPlace, TileOutput, TilePartEvent, TileStyle};
pub use words::TileWords;
/// Where a tile's caption goes.
+49
View File
@@ -48,6 +48,30 @@ pub enum TilePartEvent {
Scrub(f32),
/// An activation of the corner action ([`Tile::corner_action`]).
CornerAction,
/// An activation of the `i`-th hover action ([`Tile::action`]), counted from 0 in the order added.
Action(usize),
}
/// Where a tile's hover actions sit.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum TileActionPlace {
/// In the picture's end-top corner.
#[default]
Corner,
/// In a band along the picture's edge.
Band,
}
/// How a stacked tile shows its stack.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum StackLook {
/// The ×N badge in the end-top corner.
#[default]
Badge,
/// Two offset sheets inside the cell.
Sheets,
}
/// What a tile returns.
@@ -357,6 +381,14 @@ pub struct Tile<'a> {
/// The check box, in check mode; `None` outside it.
#[prop]
check: Option<ToggleState>,
/// Where the hover actions sit: the grid's, applied to its tiles.
#[allow(dead_code)] // P3(pdf-workflows-w2): CV-C25
#[prop]
action_place: TileActionPlace,
/// The icon face reads in this colour from data in place of the face colour.
#[allow(dead_code)] // P3(pdf-workflows-w2): CH-C10b
#[prop]
hue: Option<DataColor>,
aspect: ThumbAspect,
first: Option<ThumbPaint<'a>>,
icon: Option<IconSpec<'static>>,
@@ -395,6 +427,8 @@ impl<'a> Tile<'a> {
icon: None,
renaming: false,
check: None,
action_place: TileActionPlace::Corner,
hue: None,
aspect: ThumbAspect::SQUARE,
first: None,
badges: Vec::new(),
@@ -427,6 +461,21 @@ impl<'a> Tile<'a> {
self
}
/// A hover action: an `IconButton::command` face shown while the pointer is over the tile or it has visible focus;
/// repeatable. Its activation is [`TilePartEvent::Action`] with its index.
#[must_use]
pub fn action(self, icon: IconId, command: impl Into<CommandRef>) -> Self {
let _ = (icon, command);
todo!("CV-C25")
}
/// How the stack of a stacked tile shows.
#[must_use]
pub fn stack_look(self, look: StackLook) -> Self {
let _ = look;
todo!("WF-W11")
}
/// A corner badge.
#[must_use]
pub fn badge(mut self, badge: TileBadge) -> Self {