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

This commit is contained in:
Martin Ball
2026-11-18 08:15:57 +00:00
parent ec93a52260
commit 53e525ad78
35 changed files with 523 additions and 80 deletions
@@ -6,7 +6,7 @@ mod events;
mod props;
mod response;
pub use columns::{ColumnAlign, ColumnKind, ColumnLayout, ColumnSort, ColumnSpec, ToggleColumn};
pub use columns::{ColumnAlign, ColumnKind, ColumnLayout, ColumnRemove, ColumnSort, ColumnSpec, ToggleColumn};
pub use drops::{DropAt, DropKind, DropPayload, DropPlace, EdgePress};
pub use events::{
CollectionEvent, ColumnEvent, ColumnRequest, ContextMenuRequest, HeaderMenuRequest, ListDrag, OpenChange, Rename, ReorderMove, ToggleEdit,
@@ -95,9 +95,27 @@ pub struct ColumnSpec {
pub max_share: Option<f32>,
/// The header menu has a check for the column, so the user can hide it. A column that can't be hidden always shows.
pub hideable: bool,
/// A remove control at the header's end, which reports `ColumnEvent::Removed`.
pub remove: Option<ColumnRemove>,
}
/// The remove control of a column's header.
#[derive(Clone, Debug, PartialEq)]
pub struct ColumnRemove {
/// The control's accessible name.
pub name: Label,
/// Whether the control can be pressed.
pub enabled: bool,
}
impl ColumnSpec {
/// The column gets a remove control named `name` at its header's end, disabled unless `enabled`.
#[must_use]
pub fn removable(self, name: impl Into<Label>, enabled: bool) -> Self {
let _ = (name.into(), enabled);
todo!("dg.F22")
}
/// A content column with a header and a width; the other settings off.
pub fn new(key: ColumnKey, header: impl Into<Label>, width: ColumnWidth) -> Self {
ColumnSpec {
@@ -116,6 +134,7 @@ impl ColumnSpec {
tip: None,
max_share: None,
hideable: false,
remove: None,
}
}
+10 -4
View File
@@ -53,10 +53,10 @@ pub use body::pad_of;
#[doc(hidden)]
pub use body::{STRIP_BACK, STRIP_FORWARD};
pub use collection::{
ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRequest, ColumnSort,
ColumnSpec, ContextMenuRequest, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest, ItemKeys, LeadOnOpen,
LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, RowState, SelectMode, ShownRow,
SpaceAction, ToggleColumn, ToggleEdit,
ActivateOn, CollectionEvent, CollectionProps, CollectionResponse, ColumnAlign, ColumnEvent, ColumnKind, ColumnLayout, ColumnRemove,
ColumnRequest, ColumnSort, ColumnSpec, ContextMenuRequest, DragPayload, DropAt, DropKind, DropPayload, DropPlace, EdgePress, HeaderMenuRequest,
ItemKeys, LeadOnOpen, LeadSource, ListDrag, OpenChange, PendingDrop, Rename, ReorderMove, ReorderRule, RowHeight, RowPressed, RowState,
SelectMode, ShownRow, SpaceAction, ToggleColumn, ToggleEdit,
};
#[doc(hidden)]
pub use container::InBar;
@@ -651,6 +651,12 @@ pub trait Collection: Component + HasProps + Meta<Shape = shape::Items> {
None
}
/// Hosts a component in the header cell of `column`, in `rect`, and returns whether it did: the header then paints
/// no label for that column.
fn header_cell(&mut self, _ui: &mut Ui, _column: &ColumnKey, _rect: Rect) -> bool {
false
}
/// The text the rename field of the item `key` opens with; `None` for the item's own text.
fn rename_draft(&self, _key: &Self::Key) -> Option<String> {
None
@@ -536,7 +536,6 @@ pub(crate) fn note_pressed_outside(ctx: &Context, id: Id) {
}
/// Whether a primary press landed outside the layer `id` in this pass while its dismissal kept it open.
#[doc(hidden)]
pub fn pressed_outside(ctx: &Context, id: Id) -> bool {
with_pass(ctx, |pass| pass.pressed_outside.contains(&id))
}
+16
View File
@@ -50,6 +50,11 @@ pub trait StackDialog: Any + Send {
/// ([`dialog_id`](super::dialog_id) of the dialog's key).
fn id(&self) -> DialogId;
/// Whether the dialog is modeless now: current state, so a dialog may change it while open.
fn modeless(&self) -> bool {
false
}
/// Shows one pass; `Some` when the dialog finished this pass.
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<Self::Result>>;
@@ -184,6 +189,8 @@ pub enum StartupStage {
/// Type-erased [`StackDialog`] the host stores.
trait AnyStackDialog: Send {
fn id(&self) -> DialogId;
#[allow(dead_code)] // P3(dialogs-w1): dg.F31
fn modeless(&self) -> bool;
fn result_type(&self) -> TypeId;
fn key(&self) -> Option<String>;
fn instance(&self) -> Option<DialogId>;
@@ -203,6 +210,10 @@ trait AnyStackDialog: Send {
}
impl<D: StackDialog> AnyStackDialog for D {
fn modeless(&self) -> bool {
StackDialog::modeless(self)
}
fn id(&self) -> DialogId {
StackDialog::id(self)
}
@@ -346,6 +357,11 @@ impl fmt::Debug for DialogHost {
}
impl DialogHost {
/// Whether its open stack holds a dialog that is not modeless; current state, so a dialog opened this pass counts.
pub fn shows_modal(&self) -> bool {
todo!("dg.F3")
}
/// An empty host with no open or queued dialogs.
pub fn new() -> Self {
Self::default()
+13 -5
View File
@@ -18,7 +18,7 @@ use crate::sections::{DialogRole, FooterButton};
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{CancelRule, Metrics, Sense};
use craft_host::target::WindowState;
use egui::{Context, Id, Pos2, Rangef, Rect, Response, Ui, ViewportId};
use egui::{Align2, Context, Id, Pos2, Rangef, Rect, Response, Ui, ViewportId};
/// The style of a dialog: the surface and padding come from the container.
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
@@ -177,11 +177,19 @@ impl<'a> Dialog<'a> {
})
}
/// Where the dialog first opens, as a screen position of its top-left corner; the middle of the window without
/// it. A saved placement comes first.
/// Where the dialog first opens, as a screen position of its `corner`; the middle of the window without it. A saved
/// placement comes first.
#[must_use]
pub fn first_place(self, at: Pos2) -> Self {
self.overlay(|overlay| overlay.place(Place::Float(FloatPlace::at(at))))
pub fn first_place(self, at: Pos2, corner: Align2) -> Self {
self.overlay(|overlay| overlay.place(Place::Float(FloatPlace::corner_at(at, corner))))
}
/// Shows `reason` as an inline bad-tone notice at the body's end, above the footer: the one display of a held
/// answer's refusal. `None` shows none.
#[must_use]
pub fn refusal(self, reason: Option<&Label>) -> Self {
let _ = reason;
todo!("dg.F1")
}
/// Saves the placement and size under `key`, so a reopened dialog sits where the user left it.
+20 -1
View File
@@ -65,12 +65,31 @@ pub struct UnsavedChangesDialog {
open: bool,
/// What a programmatic OK answers; the accepting answer's when `None`.
chosen: Option<CloseAnswer>,
/// Why the last save failed, shown under the message.
#[allow(dead_code)] // P3(shell-w3): sh.K10
reason: Option<String>,
}
impl UnsavedChangesDialog {
/// The question for the document `document_name`, closing under `scope`; the guard asks about one document.
pub fn new(scope: CloseScope, document_name: impl Into<String>) -> Self {
Self { id: dialog_id("unsaved-changes"), scope, name: document_name.into(), remaining: 1, apply_to_all: false, open: true, chosen: None }
Self {
id: dialog_id("unsaved-changes"),
scope,
name: document_name.into(),
remaining: 1,
apply_to_all: false,
open: true,
chosen: None,
reason: None,
}
}
/// Shows why the last save failed, in the bad tone under the message.
#[must_use]
pub fn reason(self, reason: impl Into<String>) -> Self {
let _ = reason.into();
todo!("sh.K10")
}
/// The answer a host-side `confirm` gives, as pressing that button would; the accepting answer's until set. An
+12 -3
View File
@@ -1,7 +1,9 @@
//! `Button`: a push button with an optional leading and trailing icon and a busy state.
use super::face::{self, FaceLook, FaceSpec};
use crate::contract::{Common, Component, Cx, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _};
use super::face::{self, Arrangement, FaceLook, FaceSpec};
use crate::contract::{
Common, Component, Cx, Hover, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _,
};
use crate::display::Spinner;
use crate::primitives::{HAlign, IconSpec, PaintShape};
use crate::runtime::commands::CommandRef;
@@ -79,6 +81,8 @@ pub struct ButtonOutput {
/// The modifiers held at the activation (with the click for a pointer one); none when the button was not
/// activated.
pub mods: Mods,
/// The pointer's stay over the button: hovered, entered, left and clicked under the pointer.
pub hover: Hover,
}
impl ButtonOutput {
@@ -93,7 +97,7 @@ impl ButtonOutput {
(true, Some(activation)) => activation.mods,
_ => Mods::NONE,
};
ButtonOutput { response: cx.response.clone(), clicks, mods }
ButtonOutput { response: cx.response.clone(), clicks, mods, hover: Hover::default() }
}
/// Whether the button was clicked this pass, by pointer or by key, by the framework's click rule. It stands in
@@ -152,6 +156,9 @@ pub struct Button<'a> {
/// that names an item at the reading start).
#[prop]
align: HAlign,
/// How the icon and label are laid out: beside each other, or the icon over the label.
#[prop]
arrangement: Arrangement,
}
impl<'a> Button<'a> {
@@ -166,6 +173,7 @@ impl<'a> Button<'a> {
tint: None,
least_width: None,
align: HAlign::Center,
arrangement: Arrangement::default(),
}
.label(label)
}
@@ -178,6 +186,7 @@ impl<'a> Button<'a> {
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
let label = self.painted.as_ref().map_or(label, Label::as_str);
FaceSpec {
arrangement: self.arrangement,
label,
role: None,
lead: self.icon.as_ref(),
+14
View File
@@ -31,8 +31,22 @@ pub(super) fn ink(cx: &StyleCx<'_>) -> (TextLook, IconLook) {
(TextLook::new(TypeRole::Label, color.clone()), IconLook::new(cx.control().icon, color))
}
/// How a button lays out its icon and label.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Arrangement {
/// The icon beside the label; no label where the `GroupLevel` is `Compact`.
#[default]
Inline,
/// The icon over a one- or two-line label.
Stacked,
}
/// What a face shows.
pub(crate) struct FaceSpec<'a> {
/// How the icon and label are laid out.
#[allow(dead_code)] // P3(ribbon-w2): rb.R6
pub arrangement: Arrangement,
pub label: &'a str,
pub role: Option<TypeRole>,
pub lead: Option<&'a IconSpec<'a>>,
+19 -1
View File
@@ -10,8 +10,26 @@ mod stories;
pub mod toggle_button;
mod words;
use crate::runtime::env::EnvValue;
pub use button::{Button, ButtonOutput, ButtonStyle};
pub use face::Arrangement;
pub use icon_button::{IconButton, IconButtonStyle, PopupMark};
pub use link::{Link, LinkStyle};
pub use split_button::{SplitButton, SplitButtonStyle, SplitOutput};
pub use split_button::{SplitButton, SplitButtonStyle, SplitMenu, SplitOutput};
pub use toggle_button::{ToggleButton, ToggleButtonStyle};
/// How much of a ribbon group's content is shown. A group sets it for its content through `Overrides::values`, and
/// styles and measurements keyed on the env follow a change.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, EnvValue)]
#[env(style)]
#[non_exhaustive]
pub enum GroupLevel {
/// Every control at full size, with its label.
#[default]
Full,
/// Buttons drop their labels.
Compact,
/// The group is collapsed into one button.
Collapsed,
}
+47 -8
View File
@@ -1,12 +1,13 @@
//! `SplitButton`: an action button whose end part opens a menu of variants or presets.
use super::face::{self, FaceLook, FaceSpec};
use super::face::{self, Arrangement, FaceLook, FaceSpec};
use crate::contract::{
Access, Common, Component, Cx, Entry, Focus as _, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx, Props as _, Role,
ShowContainer as _, Styled as _, WordSetCx as _,
Access, BodyCx, Common, Component, Cx, Entry, Focus as _, Hover, MeasureCx, Name, Outcome, OverlayUi, Overlays as _, PaintUi, PartsCx,
Props as _, Role, ShowContainer as _, Styled as _, WordSetCx as _,
};
use crate::menu::{self, Menu};
use crate::primitives::{IconSpec, PaintShape, RuleKind};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, Corners, FocusLook, IconLook, RuleLook, RuleWidth, Stateful, StyleColor, StyleCx, SurfaceLook, TextLook};
use craft_behavior::{Flow, HitLevel, HitPriority, Metrics, NavMove, PartKey, Sense, Value};
@@ -14,7 +15,7 @@ use craft_theme::{
States, Variant,
variant::{Emphasis, Tone},
};
use egui::{CornerRadius, Pos2, Rect, Response, Vec2};
use egui::{CornerRadius, Pos2, Rect, Response, Ui, Vec2};
const ARROW: PartKey = PartKey::new("arrow");
@@ -59,6 +60,8 @@ pub struct SplitOutput<T> {
pub response: Response,
/// The entry the user picked.
pub chosen: Option<T>,
/// The pointer's stay over the main part: hovered, entered, left and clicked under the pointer.
pub hover: Hover,
}
impl<T: Value> Outcome for SplitOutput<T> {
@@ -69,6 +72,15 @@ impl<T: Value> Outcome for SplitOutput<T> {
}
}
/// What a split button's arrow opens.
#[non_exhaustive]
pub enum SplitMenu<'a, T> {
/// A menu of rows, one per entry.
Entries(&'a [Entry<T>]),
/// A menu whose content the caller draws.
Body(Box<dyn FnMut(&mut Ui, &mut BodyCx<'_>) + 'a>),
}
/// A button whose end opens a menu. A press on the arrow part opens the menu below the button; a press on the main
/// part runs the action and never opens it. The button is one Tab stop: Space and Enter run the action, Alt+Down and
/// Down open the menu with its first row active, Escape closes it with focus back on the button.
@@ -77,24 +89,48 @@ impl<T: Value> Outcome for SplitOutput<T> {
pub struct SplitButton<'a, T: Value + 'static> {
#[common]
common: Common,
entries: &'a [Entry<T>],
menu: SplitMenu<'a, T>,
/// The arrow's accessible name and tooltip ("Tracing Presets"); the label alone names it without one.
#[prop(into)]
arrow_label: Option<Label>,
/// A leading icon on the main part.
#[prop(into)]
icon: Option<IconSpec<'a>>,
/// How the icon and label are laid out: beside each other, or the icon over the label.
#[prop]
arrangement: Arrangement,
chosen: Option<T>,
}
impl<'a, T: Value + 'static> SplitButton<'a, T> {
/// A split button showing `label` whose arrow opens `entries`.
pub fn new(label: impl Into<Label>, entries: &'a [Entry<T>]) -> Self {
SplitButton { common: Common::new(), entries, arrow_label: None, icon: None, chosen: None }.label(label)
SplitButton {
common: Common::new(),
menu: SplitMenu::Entries(entries),
arrow_label: None,
icon: None,
arrangement: Arrangement::default(),
chosen: None,
}
.label(label)
}
/// A split button showing `label` whose arrow opens a menu with `body` as its content.
pub fn body(label: impl Into<Label>, body: impl FnMut(&mut Ui, &mut BodyCx<'_>) + 'a) -> Self {
let _ = (label.into(), body);
todo!("rb.R7")
}
/// A split button bound to `command`: its main part fires the command, its arrow opens `menu`.
pub fn command(command: impl Into<CommandRef>, menu: SplitMenu<'a, T>) -> Self {
let _ = (command.into(), menu);
todo!("rb.R7")
}
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
FaceSpec {
arrangement: self.arrangement,
label,
role: None,
lead: self.icon.as_ref(),
@@ -178,7 +214,10 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
/// menu; a disabled entry takes neither focus-run nor a pick.
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
let popup = cx.popup("menu");
let entries = self.entries;
let entries = match &self.menu {
SplitMenu::Entries(entries) => *entries,
SplitMenu::Body(_) => todo!("rb.R7"),
};
let name = cx.label();
let ran = ui.show(popup, menu::layer(false), |ui, _| {
Menu::inline(name.clone()).values().show(ui, |ui, _| menu::entry_rows(ui, entries)).inner.flatten()
@@ -218,6 +257,6 @@ impl<T: Value + 'static> Component for SplitButton<'_, T> {
}
fn finish(self, cx: Cx<'_, Self>) -> SplitOutput<T> {
SplitOutput { response: cx.response.clone(), chosen: self.chosen }
SplitOutput { response: cx.response.clone(), chosen: self.chosen, hover: Hover::default() }
}
}
@@ -1,6 +1,6 @@
//! `ToggleButton`: a button that stays pressed while on.
use super::face::{self, FaceLook, FaceSpec};
use super::face::{self, Arrangement, FaceLook, FaceSpec};
use crate::contract::{
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Name, PaintUi, Pointer as _, Props, Role,
};
@@ -69,6 +69,9 @@ pub struct ToggleButton<'a> {
/// The name a screen reader hears when it differs from the face (a modifier key's symbol face).
#[prop]
spoken: Option<Label>,
/// How the icon and label are laid out: beside each other, or the icon over the label.
#[prop]
arrangement: Arrangement,
}
impl<'a> ToggleButton<'a> {
@@ -84,6 +87,7 @@ impl<'a> ToggleButton<'a> {
icon_only: false,
escape_disarms: false,
spoken: None,
arrangement: Arrangement::default(),
}
.label(label)
}
@@ -100,6 +104,7 @@ impl<'a> ToggleButton<'a> {
icon_only: false,
escape_disarms: false,
spoken: None,
arrangement: Arrangement::default(),
};
<ToggleButton as Props>::command(button, command)
}
@@ -107,6 +112,7 @@ impl<'a> ToggleButton<'a> {
fn spec<'s>(&'s self, label: &'s str, on: bool) -> FaceSpec<'s> {
let lead = if on { self.on_icon.as_ref().or(self.icon.as_ref()) } else { self.icon.as_ref() };
FaceSpec {
arrangement: self.arrangement,
label: if self.icon_only { "" } else { label },
role: self.role,
lead,
+1 -1
View File
@@ -18,7 +18,7 @@ pub use switch::{Switch, SwitchStyle};
pub use words::ChoiceWords;
pub use swatch::{Swatch, SwatchFace, SwatchMetrics, SwatchOutput, SwatchStyle};
pub use swatch_table::{SwatchRows, SwatchTable, SwatchTableOutput, SwatchTableStyle};
pub use swatch_table::{SwatchArrangement, SwatchRows, SwatchTable, SwatchTableOutput, SwatchTableStyle};
/// The well of a check box, radio button or switch track with `radius` corners: the sunken surface, so a bevelled theme
/// draws its bevel, filled with the off fill or the on accent. A flat theme draws the outline as its edge, in the failure
@@ -185,6 +185,7 @@ impl Segment {
fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
FaceSpec {
arrangement: crate::buttons::Arrangement::Inline, // P3(ribbon-w2): rb.R6
label: if self.icon.is_some() { "" } else { label },
role: None,
lead: self.icon.as_ref(),
@@ -69,6 +69,17 @@ impl Outcome for SwatchTableOutput {
}
}
/// How a [`SwatchTable`] lays out its cells.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SwatchArrangement {
/// Square cells in rows and columns.
#[default]
Grid,
/// Touching hexagon cells; the arrows move between neighbours.
Honeycomb,
}
/// A table of touching colour cells, one per entry, wrapping to the width or to a fixed count per row. Entries are
/// told apart by index, so duplicates select one cell. With [`span`](Self::span) and a count per row, the cells share
/// the table's width edge to edge; [`marked`](Self::marked) cells draw the swatch mark.
@@ -106,6 +117,9 @@ pub struct SwatchTable<'a> {
/// Whether the cells are wells at the control height, as a palette's swatches are, instead of small touching cells.
#[prop]
wells: bool,
/// How the cells lie: a square grid, or touching hexagons.
#[prop]
arrangement: SwatchArrangement,
}
impl<'a> SwatchTable<'a> {
@@ -128,6 +142,7 @@ impl<'a> SwatchTable<'a> {
marked: None,
tips: false,
wells: false,
arrangement: SwatchArrangement::default(),
}
.label(label)
}
+12 -1
View File
@@ -3,7 +3,7 @@
use super::display_sense;
use crate::contract::{Access, Common, Component, Cx, DisabledLook, MeasureCx, PaintUi, Props as _, Role};
use crate::list::{ThumbAspect, ThumbSize};
use crate::primitives::{ContentPainterCx, Revision, TextureStore, TextureStoreOptions, fit_rect};
use crate::primitives::{ContentPainterCx, Revision, TextureStore, TextureStoreOptions, ThumbSource, Thumbnails, fit_rect};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{Metrics, Sense};
@@ -45,6 +45,9 @@ enum Source<'a> {
Image { key: u64, image: &'a dyn Fn() -> ColorImage },
/// A content painter that paints into the picture's rect.
Painter(Paint<'a>),
/// A picture rendered off the frame by a thumbnail source, shown pending until it arrives.
#[allow(dead_code)] // P3(ribbon-w6): rb.R23
Rendered { key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64> },
}
/// A picture of an image the caller makes (`new`) or of what a content painter paints (`painter`); both sit in a rect
@@ -83,6 +86,13 @@ impl<'a> Picture<'a> {
Picture::from_source(label, Source::Painter(Box::new(paint))).aspect(aspect)
}
/// A picture made off the frame by `source` for `key`: pending, with the framework's placeholder, until the
/// source's picture arrives, then fitted as `new`'s texture is. `label` names it for a screen reader.
pub fn rendered(label: impl Into<Label>, key: u64, thumbnails: &'a Thumbnails<u64>, source: &'a dyn ThumbSource<u64>) -> Self {
let _ = (label.into(), key, thumbnails, source);
todo!("rb.R23")
}
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 +147,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::Rendered { .. } => todo!("rb.R23"),
}
}
+6
View File
@@ -97,6 +97,12 @@ impl Text {
text
}
/// Interface text from styled `spans`; the joined text is its accessible name.
pub fn styled(spans: Vec<Span<'static>>) -> Self {
let _ = spans;
todo!("ch.C14b")
}
/// Sets the text in italics: a value set apart from the words around it.
pub fn italic(mut self) -> Self {
self.italic = true;
+10 -4
View File
@@ -114,6 +114,7 @@ impl Component for TitleFace {
face::measure(
cx,
&FaceSpec {
arrangement: crate::buttons::Arrangement::Inline, // P3(ribbon-w2): rb.R6
label: cx.resolved.label,
role: None,
lead: None,
@@ -135,6 +136,7 @@ impl Component for TitleFace {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let spec = FaceSpec {
arrangement: crate::buttons::Arrangement::Inline, // P3(ribbon-w2): rb.R6
label: cx.resolved.label,
role: None,
lead: None,
@@ -400,13 +402,14 @@ impl<'a> MenuBar<'a> {
}
/// The help search's entries as `[label, English label, path]` texts.
fn help_texts(entries: &[HelpEntry], env: &EnvView<'_>, separator: &str) -> Vec<[String; 3]> {
fn help_texts(entries: &[HelpEntry], env: &EnvView<'_>, separator: &str) -> Vec<[String; 4]> {
entries
.iter()
.map(|entry| {
let path: Vec<String> = entry.path().iter().map(|label| env.resolve(label).as_str().to_owned()).collect();
let english = entry.english().map(|label| env.resolve(label).as_str().to_owned());
[env.resolve(entry.label()).as_str().to_owned(), english.unwrap_or_default(), path.join(separator)]
// P3(dialogs-w9): dg.F26 — the fourth text is the command id.
[env.resolve(entry.label()).as_str().to_owned(), english.unwrap_or_default(), path.join(separator), String::new()]
})
.collect()
}
@@ -568,8 +571,11 @@ impl Component for MenuBar<'_> {
}
}
query.1 = query.1.saturating_add(1);
let refs: Vec<[&str; 3]> =
rows.iter().map(|[label, english, path]| [label.as_str(), english.as_str(), path.as_str()]).collect();
// P3(dialogs-w9): dg.F26
let refs: Vec<[&str; 4]> = rows
.iter()
.map(|[label, english, path, id]| [label.as_str(), english.as_str(), path.as_str(), id.as_str()])
.collect();
let mut seen: Vec<&CommandRef> = Vec::new();
let listed: Vec<usize> = search_order(&folder, &query.0, &refs)
.into_iter()
+53 -7
View File
@@ -7,7 +7,7 @@ use crate::contract::{
};
use crate::display::Kbd;
use crate::list::RowStyleCx as _;
use crate::primitives::{IconSpec, StrokeWidth, TextRun, glyph};
use crate::primitives::{ContentPainterCx, IconSpec, StrokeWidth, TextRun, glyph};
use crate::runtime::access::PopupKind;
use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand};
use crate::runtime::env::Label;
@@ -140,6 +140,22 @@ fn label_line(area: Rect, detail: f32) -> Rect {
Rect::from_min_max(area.min, pos2(area.max.x, (area.max.y - detail).max(area.min.y)))
}
/// What a menu row shows as its shortcut.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub enum MenuShortcut {
/// The bound command's chord; none for a row with no command.
#[default]
Command,
/// The caller's text, which wins over the command's chord.
Text(Label),
/// No shortcut.
Hidden,
}
/// What paints a menu row's sample into its rect.
pub type MenuSamplePaint<'a> = Box<dyn FnOnce(&ContentPainterCx, Rect) + 'a>;
/// A row of a menu: a label, an optional icon, a check or radio mark, shortcut text and a detail line under the label.
/// A row bound to a command takes its label, shortcut, enabled and checked state from the command and fires it as a
/// menu row.
@@ -158,6 +174,7 @@ fn label_line(area: Rect, detail: f32) -> Rect {
/// the text readable on (`MenuTint`); the active, open and disabled looks win over it. The row keeps its text, so the
/// colour is never the only cue.
#[derive(crate::contract::Component, crate::contract::Props)]
#[component(content_painter)]
pub struct MenuItem<'a> {
#[common]
common: Common,
@@ -184,9 +201,14 @@ pub struct MenuItem<'a> {
#[style_key]
#[prop(into)]
tint: Option<Rgba>,
/// Shortcut text at the end of the row, written by the caller; a command row shows its chord.
#[prop(into)]
shortcut: Option<Label>,
/// What the row shows as its shortcut: the bound command's chord, the caller's text, or nothing.
shortcut: MenuShortcut,
/// A sample between the label and the shortcut, painted by the closure into its rect.
#[prop(boxed = "FnOnce(&ContentPainterCx, Rect) + 'a", name = "sample")]
sample: Option<MenuSamplePaint<'a>>,
/// The sample is painted in place of the label.
#[prop(flag)]
sample_only: bool,
/// Running the row leaves the menus open.
#[prop]
keep_open: bool,
@@ -213,7 +235,9 @@ impl<'a> MenuItem<'a> {
mnemonic: None,
detail: None,
tint: None,
shortcut: None,
shortcut: MenuShortcut::default(),
sample: None,
sample_only: false,
keep_open: false,
entry: None,
ran: false,
@@ -283,10 +307,32 @@ impl<'a> MenuItem<'a> {
fn keys(&self, command: Option<&ResolvedCommand>) -> Option<Kbd> {
match (&self.command_ref, command) {
(Some(reference), Some(resolved)) if resolved.chord.is_some() => Some(Kbd::command(reference.clone())),
_ => self.shortcut.clone().map(Kbd::new),
_ => self.shortcut_text().cloned().map(Kbd::new), // P3(ribbon-w2): rb.R22
}
}
/// The shortcut text the caller set.
fn shortcut_text(&self) -> Option<&Label> {
match &self.shortcut {
MenuShortcut::Text(text) => Some(text),
MenuShortcut::Command | MenuShortcut::Hidden => None,
}
}
/// Shortcut text at the end of the row, written by the caller; it wins over the bound command's chord.
#[must_use]
pub fn shortcut(mut self, text: impl Into<Label>) -> Self {
self.shortcut = MenuShortcut::Text(text.into());
self
}
/// Shows no shortcut on the row, whatever the bound command's chord is.
#[must_use]
pub fn hide_shortcut(self) -> Self {
let _ = self;
todo!("rb.R22")
}
/// The parts of the label line `line`.
fn place(&self, columns: &Columns, line: Rect, rtl: bool, trail_gap: f32) -> Placed {
let step = |width: f32, gap: f32| if width > 0.0 { width + gap } else { 0.0 };
@@ -596,7 +642,7 @@ impl Component for MenuItem<'_> {
if let Some((letter, _)) = level.mnemonic_of(cx.id) {
access.access_key(letter);
}
if let Some(text) = &self.shortcut {
if let Some(text) = self.shortcut_text() {
access.shortcut(cx.env.resolve(text).as_str().to_owned());
}
if cx.resolved.tooltip.is_none()
+1 -1
View File
@@ -15,7 +15,7 @@ mod words;
pub use bar::{MenuBar, MenuBarOutput, MenuBarStyle, MenuHelp, MenuTitle};
pub(crate) use edit::text_menu;
pub use edit::{EditMenu, EditMenuOutput};
pub use item::{MenuItem, MenuItemOutput, MenuItemStyle};
pub use item::{MenuItem, MenuItemOutput, MenuItemStyle, MenuSamplePaint, MenuShortcut};
pub use panel::{GroupItem, PanelMenu, PanelMenuOutput, PanelRow};
#[doc(hidden)]
pub use popup::entry_rows;
+37 -4
View File
@@ -168,9 +168,20 @@ pub struct Menu<'a> {
back: bool,
/// The Left or Right key a top-level level left unhandled.
step: Option<MenuStep>,
/// The bar shown above the menu in its own modeless layer.
#[allow(dead_code)] // P3(canvas-w8): cv.K40
companion: Option<&'a mut dyn FnMut(&mut Ui)>,
}
impl<'a> Menu<'a> {
/// A modeless bar layer above the menu, in its press family; it closes with the menu, and Escape closes the top
/// layer first.
#[must_use]
pub fn companion(self, bar: &'a mut dyn FnMut(&mut Ui)) -> Self {
let _ = bar;
todo!("cv.K40")
}
/// A menu named `label`. Its open state is the menu's slot until [`open`](Menu::open) binds it.
pub fn new(label: impl Into<Label>) -> Self {
let props = ContainerProps::new()
@@ -182,8 +193,19 @@ impl<'a> Menu<'a> {
.label_column(true)
.scroll(Scroll::vertical().strips())
.mount(Mount::Layer(layer(false)));
Menu { common: Common::new(), props, open: None, closed: None, submenu: false, values: false, opener: None, back: false, step: None }
.label(label)
Menu {
common: Common::new(),
props,
open: None,
closed: None,
submenu: false,
values: false,
opener: None,
back: false,
step: None,
companion: None,
}
.label(label)
}
/// Marks the menu as a value menu: every row is a radio item, whether or not an entry is checked, and the checked
@@ -203,8 +225,19 @@ impl<'a> Menu<'a> {
.roving(Roving::new(NavShape::Flat).arrows(Arrows::Vertical).wrap(true))
.label_column(true)
.scroll(Scroll::vertical().strips());
Menu { common: Common::new(), props, open: None, closed: None, submenu: false, values: false, opener: None, back: false, step: None }
.label(label)
Menu {
common: Common::new(),
props,
open: None,
closed: None,
submenu: false,
values: false,
opener: None,
back: false,
step: None,
companion: None,
}
.label(label)
}
/// A context menu named `label`, hanging from where the pointer was when it opened, with `opener` getting the
+4 -4
View File
@@ -65,9 +65,9 @@ impl HelpEntry {
}
/// The entries matching `query`, best first and in menu order within a rank, at most `MAX_RESULTS`. Each entry is
/// its `[label, english label, menu path]` texts, matched by `folder` (case and accents folded). A label or English
/// label that matches ranks before an entry found only through its path; within each, the matcher's rank decides.
pub fn search_order(folder: &Folder, query: &str, texts: &[[&str; 3]]) -> Vec<usize> {
/// its `[label, english label, menu path, command id]` texts, matched by `folder` (case and accents folded). A label or
/// English label that matches ranks before an entry found only through its path; within each, the matcher's rank decides.
pub fn search_order(folder: &Folder, query: &str, texts: &[[&str; 4]]) -> Vec<usize> {
let query = query.trim();
if query.is_empty() {
return Vec::new();
@@ -76,7 +76,7 @@ pub fn search_order(folder: &Folder, query: &str, texts: &[[&str; 3]]) -> Vec<us
let mut ranked: Vec<_> = texts
.iter()
.enumerate()
.filter_map(|(at, [label, english, path])| {
.filter_map(|(at, [label, english, path, _id])| {
let named = [label, english].into_iter().filter_map(|text| matcher.score(text)).map(|found| found.rank).min();
match named {
Some(found) => Some((0_u8, found, at)),
+32 -8
View File
@@ -12,18 +12,18 @@ use super::rows::EntryRows;
use super::words::PickerWords;
use crate::buttons::IconButton;
use crate::contract::{
Bind, BindMut, CollectionEvent, Common, Component, Cx, Edit as _, EditResponse, Entry, Focus as _, Input, LeadSource, MeasureCx, Overlay,
OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, ShowCollection as _, WordSetCx as _, step_stop,
step_stops,
Bind, BindMut, CollectionEvent, Common, Component, Cx, Edit as _, EditResponse, Entry, Focus as _, Input, LeadSource, MeasureCx, Outcome,
Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, ShowCollection as _, WordSetCx as _,
step_stop, step_stops,
};
use crate::list::{List, ListRow};
use crate::primitives::{TextKey, TextOptions, TextRun};
use crate::runtime::env::Label;
use crate::runtime::overlay::CloseReason;
use crate::text::{Adornment, place, reserve};
use craft_behavior::{HitLevel, HitPriority, NavMove, PartKey, PlainText, Selection, Sense};
use craft_behavior::{HitLevel, HitPriority, NavMove, PartKey, PlainText, Preview, Selection, Sense};
use craft_i18n::matcher::Matcher;
use egui::{Rect, Vec2};
use egui::{Rect, Response, Vec2};
/// The text part.
const TEXT: PartKey = PartKey::new("text");
@@ -50,6 +50,30 @@ struct Keyed {
before: Option<String>,
}
/// What a [`ComboBox`] reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct ComboBoxOutput {
/// The field's edit.
pub edit: EditResponse<String>,
/// What this pass did to the preview of the option under the pointer or the keyboard row of the open list: it ends
/// when the pointer leaves the rows, the list closes or a row is picked. The field's text and value stay.
pub preview: Preview<String>,
}
impl Outcome for ComboBoxOutput {
type Value = String;
fn response(&self) -> &Response {
&self.edit.response
}
#[cfg(feature = "testing")]
fn story_facts(&self) -> crate::testing::StoryOutput {
self.edit.story_facts()
}
}
/// A text field with a list of options. The typed text filters the list by the options' labels: the labels that
/// match it best first, ignoring case and accents. The chevron and Alt+Down open the list on every option. Enter or a
/// click on a row puts the option's text in the field; Escape closes the list, and the next Escape restores the text.
@@ -105,7 +129,7 @@ impl Component for ComboBox<'_> {
const INPUT: Input = Input::Text;
const KEYS: crate::runtime::focus::KeyUse = crate::runtime::focus::KeyUse::of(crate::contract::Input::Text).with_moves();
type Style = crate::text::FieldStyle;
type Output = EditResponse<String>;
type Output = ComboBoxOutput;
fn style(cx: &crate::style::StyleCx<'_>, _: ComboBoxStyleKey) -> crate::text::FieldStyle {
crate::text::FieldStyle::at(cx)
@@ -248,7 +272,7 @@ impl Component for ComboBox<'_> {
ui.face(CHEVRON, IconButton::new(crate::controls::disclosure::DisclosureGlyph::dropdown()).label(name));
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<String> {
cx.edit_response()
fn finish(self, cx: Cx<'_, Self>) -> ComboBoxOutput {
ComboBoxOutput { edit: cx.edit_response(), preview: Preview::default() } // P3(ribbon-w2): rb.R24
}
}
+19 -2
View File
@@ -108,6 +108,23 @@ pub struct IconPicker<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
label: Label,
value: Bind<'a, Option<K>>,
groups: &'a [IconPickerGroup<K>],
/// How the groups show: as headings over their cells, or as a filter row.
#[prop]
group_display: IconPickerGroups,
/// Shown when there are no cells.
#[prop(into)]
empty: Option<Label>,
}
/// How an [`IconPicker`] shows its groups.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum IconPickerGroups {
/// Each group's name is a heading over its cells.
#[default]
Headings,
/// A filter row: All first, then each group.
Filter,
}
/// The visible cells as the grid's source, keyed by position.
@@ -142,12 +159,12 @@ impl<K> ItemSource<usize> for Cells<'_, K> {}
impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> IconPicker<'a, K> {
/// A picker named `label` over `value`, choosing among the cells of `groups`.
pub fn new(label: impl Into<Label>, value: Bind<'a, Option<K>>, groups: &'a [IconPickerGroup<K>]) -> Self {
IconPicker { label: label.into(), value, groups }
IconPicker { label: label.into(), value, groups, group_display: IconPickerGroups::default(), empty: None }
}
/// Shows the picker and returns what the user did this pass.
pub fn show(self, ui: &mut Ui) -> IconPickerOutput<K> {
let IconPicker { label, mut value, groups } = self;
let IconPicker { label, mut value, groups, .. } = self;
let shown = Stack::new().show(ui, |ui, cx| Self::body(ui, cx, &label, &mut value, groups));
shown.inner.unwrap_or_else(|| IconPickerOutput { response: shown.output.clone(), picked: None, search_changed: false })
}
+3 -3
View File
@@ -14,16 +14,16 @@ mod words;
mod reference_point;
pub use combo_box::ComboBox;
pub use combo_box::{ComboBox, ComboBoxOutput};
pub use date::{
Calendar, CalendarOutput, CalendarStyle, CalendarView, DateCodec, DatePicker, DatePrecision, PickedDate, local_month_grid, month_grid,
};
pub use dress::RowDress;
pub use face::{FaceKind, SelectFace, SelectFaceStyle, toggle_on_key};
pub use icon_picker::{IconPicker, IconPickerGroup, IconPickerItem, IconPickerOutput};
pub use icon_picker::{IconPicker, IconPickerGroup, IconPickerGroups, IconPickerItem, IconPickerOutput};
pub use select::{Select, SelectStyle};
pub use tree_picker::{TreeEntry, TreePicker, TreePickerStyle};
pub use unit_select::{UnitSelect, UnitSelectOutput, UnitSelectStyle};
pub use craft_behavior::Anchor9;
pub use reference_point::{ReferencePoint, ReferencePointStyle};
pub use reference_point::{ReferencePoint, ReferencePointKind, ReferencePointStyle};
@@ -60,6 +60,23 @@ pub struct ReferencePointStyle {
arrow: f32,
/// The unpicked dots and the growth arrows.
arrow_ink: Stateful<StyleColor>,
/// The length of a text bar of an alignment cell.
#[allow(dead_code)] // P3(dialogs-w12): dg.F30
bar: f32,
/// The ink of an alignment cell's text bars.
#[allow(dead_code)] // P3(dialogs-w12): dg.F30
bar_ink: Stateful<StyleColor>,
}
/// What a [`ReferencePoint`]'s pick means.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ReferencePointKind {
/// A point of a box: a dot in each cell.
#[default]
Point,
/// The alignment of text in a cell: three text bars in each cell, set to its side and edge.
Alignment,
}
/// The 3 by 3 picker of a box's nine points: the point a transform, a resize or a watermark works about. The nine
@@ -74,7 +91,11 @@ pub struct ReferencePointStyle {
pub struct ReferencePoint<'a> {
#[common]
common: Common,
value: Bind<'a, Anchor9>,
value: Bind<'a, Option<Anchor9>>,
/// What the pick means: a point of a box, or the alignment of text in a cell.
#[style_key]
#[prop]
kind: ReferencePointKind,
/// The change in the box's width and height: the arrows point away from the pick where the box grows and toward
/// it where the box shrinks. Without it the cells show no arrows.
#[prop]
@@ -87,8 +108,8 @@ pub struct ReferencePoint<'a> {
impl<'a> ReferencePoint<'a> {
/// A picker named `label` over `value`.
pub fn new(label: impl Into<Label>, value: Bind<'a, Anchor9>) -> Self {
ReferencePoint { common: Common::new(), value, growth: None, compact: false }.label(label)
pub fn new(label: impl Into<Label>, value: Bind<'a, Option<Anchor9>>) -> Self {
ReferencePoint { common: Common::new(), value, kind: ReferencePointKind::default(), growth: None, compact: false }.label(label)
}
/// The direction of the arrow `cell` shows when the pick is `anchor`, in cell steps (each -1, 0 or 1): away from
@@ -108,7 +129,8 @@ impl<'a> ReferencePoint<'a> {
CELL.at(at as u64)
}
fn position_of(value: Option<&Anchor9>) -> Option<usize> {
fn position_of(value: Option<&Option<Anchor9>>) -> Option<usize> {
let value = value.and_then(Option::as_ref); // P3(dialogs-w12): dg.F30
value.and_then(|value| Anchor9::ALL.iter().position(|point| point == value))
}
@@ -141,7 +163,7 @@ impl Component for ReferencePoint<'_> {
const OVERLAYS: bool = false;
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_activate(ActivateKeys::Both);
type Style = ReferencePointStyle;
type Output = EditResponse<Anchor9>;
type Output = EditResponse<Option<Anchor9>>;
fn style(cx: &StyleCx<'_>, key: ReferencePointStyleKey) -> ReferencePointStyle {
let sunken = cx.surface(SurfaceKind::Sunken);
@@ -163,6 +185,8 @@ impl Component for ReferencePoint<'_> {
ink: look(cx.color(colors.accent.text)),
arrow: cx.tokens.size.icon.sm,
arrow_ink: look(cx.color(colors.text.muted)),
bar: cx.tokens.size.icon.sm,
bar_ink: look(cx.color(colors.text.muted)),
}
}
@@ -187,7 +211,7 @@ impl Component for ReferencePoint<'_> {
cx.roving(Roving::new(NavShape::bounded_grid(GRID)));
}
fn bind(&mut self) -> Option<BindMut<'_, Anchor9>> {
fn bind(&mut self) -> Option<BindMut<'_, Option<Anchor9>>> {
Some(self.value.reborrow())
}
@@ -196,7 +220,7 @@ impl Component for ReferencePoint<'_> {
let current = Self::position_of(cx.value());
let activated = (0..Anchor9::ALL.len()).find(|at| cx.part_activated(Self::part(*at)).is_some());
if let Some(at) = activated.filter(|at| current != Some(*at)) {
cx.set(Anchor9::ALL[at]);
cx.set(Some(Anchor9::ALL[at])); // P3(dialogs-w12): dg.F30
}
}
@@ -230,7 +254,7 @@ impl Component for ReferencePoint<'_> {
}
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<Anchor9> {
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<Option<Anchor9>> {
cx.edit_response()
}
}
@@ -17,29 +17,30 @@ fn pick_top_left(fixture: &mut Fixture) {
/// centre pick shows its arrow.
#[story(ReferencePoint<'static>, covers = [Default], drive = Drive::Custom(pick_top_left))]
fn reference_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound(data.value("point", Anchor9::Centre))).growth((1.0, 1.0)).show(ui).into()
ReferencePoint::new("Reference point", Bind::bound(data.value("point", Some(Anchor9::Centre)))).growth((1.0, 1.0)).show(ui).into()
}
#[story(ReferencePoint<'static>, covers = [Mixed], drive = Drive::Never)]
fn reference_point_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound_mixed(data.value("mixed", Mixed::Mixed))).show(ui).into()
ReferencePoint::new("Reference point", Bind::bound_mixed(data.value("mixed", Mixed::<Option<Anchor9>>::Mixed))).show(ui).into()
}
#[story(ReferencePoint<'static>, covers = [Invalid], drive = Drive::Never)]
fn reference_point_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
let refuse_bottom = |point: &Anchor9| if *point == Anchor9::Bottom { Validity::Refuse(Message::new("Not a corner")) } else { Validity::Ok };
ReferencePoint::new("Reference point", Bind::bound(data.value("bottom", Anchor9::Bottom)).check(refuse_bottom)).show(ui).into()
let refuse_bottom =
|point: &Option<Anchor9>| if *point == Some(Anchor9::Bottom) { Validity::Refuse(Message::new("Not a corner")) } else { Validity::Ok };
ReferencePoint::new("Reference point", Bind::bound(data.value("bottom", Some(Anchor9::Bottom))).check(refuse_bottom)).show(ui).into()
}
/// The canvas grows wider and shrinks shorter: the arrows beside the pick point away along the width and back along
/// the height.
#[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)]
fn reference_point_growth(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound(data.value("grown", Anchor9::TopLeft))).growth((200.0, -100.0)).show(ui).into()
ReferencePoint::new("Reference point", Bind::bound(data.value("grown", Some(Anchor9::TopLeft)))).growth((200.0, -100.0)).show(ui).into()
}
/// The options bar's size: the grid is an icon square and every point is a dot.
#[story(ReferencePoint<'static>, covers = [], drive = Drive::Never)]
fn reference_point_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
ReferencePoint::new("Reference point", Bind::bound(data.value("compact", Anchor9::Centre))).compact().show(ui).into()
ReferencePoint::new("Reference point", Bind::bound(data.value("compact", Some(Anchor9::Centre)))).compact().show(ui).into()
}
+2
View File
@@ -35,6 +35,8 @@ craft_ui::words! {
date_precision: "datePicker.precision" = "Pick by";
/// The name of the icon picker's search field.
icon_search: "iconPicker.search" = "Search icons";
/// The icon picker's filter row entry that shows every group.
all: "iconPicker.all" = "All";
/// Shown in the icon picker when no icon matches the search.
icon_no_match: "iconPicker.noMatch" = "No icons match your search.";
/// The name of the reference point picker's top left point.
+9 -1
View File
@@ -14,7 +14,7 @@ use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText};
use crate::menu::{Menu, MenuItem};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, StyleCx};
use craft_behavior::{ItemSource, Metrics, Selection, SpanLayout};
use craft_behavior::{ColumnKey, ItemSource, Metrics, Selection, SpanLayout};
use egui::{Rect, Ui};
use std::hash::Hash;
@@ -100,6 +100,14 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Table<'a, K> {
.label(label)
}
/// Hosts `field` in the header cell of `column`, in place of its label; `output` gets what the field returns, once
/// per pass.
#[must_use]
pub fn header_field<C: crate::contract::Show + 'a>(self, column: ColumnKey, field: C, output: impl FnOnce(C::Output) + 'a) -> Self {
let _ = (column, field, output);
todo!("dg.F22")
}
/// Takes the drops of `kind` from drags that did not start in the table; kinds given earlier come first.
#[must_use]
pub fn takes_drop(mut self, kind: DropKind<'a, K>) -> Self {
+2 -2
View File
@@ -7,7 +7,7 @@ mod rules;
mod tab;
pub use rules::{CloseSide, FitMode, OverflowMenu, OverflowPlace, TabKind, close_side};
pub use tab::{Tab, TabOutput, TabPartEvent, TabStyle};
pub use tab::{Tab, TabOutput, TabPartEvent, TabRole, TabStyle};
pub use words::TabWords;
// The strip and the document tabs.
@@ -15,5 +15,5 @@ mod document;
mod strip;
pub use document::{DocumentTab, DocumentTabs, DocumentTabsEvent, DocumentTabsOutput};
pub use strip::{StripLayout, TabStrip, TabStripOutput, TabStripStyle, TornOff};
pub use strip::{StripEnd, StripLayout, TabStrip, TabStripOutput, TabStripStyle, TornOff};
pub use words::StripWords;
+11 -3
View File
@@ -15,6 +15,9 @@ pub enum TabKind {
/// Text tabs: only the labels, the selected one in the text colour and the others dimmed, no tab surface,
/// divider or close button. Whole titles, every tab in the overflow menu (a row of categories in a dialog).
Text,
/// Ribbon tabs: label-only tabs, the shown tab in semibold, one sliding accent underline. Whole titles, overflow
/// at the end of the strip.
Ribbon,
}
/// How tab widths are fitted to the strip.
@@ -66,7 +69,7 @@ impl TabKind {
/// How tab widths are fitted: whole titles for document and text tabs, shrinking for panel tabs.
pub fn fit_mode(self) -> FitMode {
match self {
Self::Document | Self::Text => FitMode::Whole,
Self::Document | Self::Text | Self::Ribbon => FitMode::Whole,
Self::Panel => FitMode::Shrink { keep_selected: self.keeps_active_width() },
}
}
@@ -86,7 +89,7 @@ impl TabKind {
/// tabs.
pub fn overflow_place(self) -> OverflowPlace {
match self {
Self::Document | Self::Text => OverflowPlace::StripEnd,
Self::Document | Self::Text | Self::Ribbon => OverflowPlace::StripEnd,
Self::Panel => OverflowPlace::AfterTabs,
}
}
@@ -94,7 +97,7 @@ impl TabKind {
/// Which tabs the overflow menu lists: every tab for document and text tabs, the hidden ones for panel tabs.
pub fn overflow_menu(self) -> OverflowMenu {
match self {
Self::Document | Self::Text => OverflowMenu::AllTabs,
Self::Document | Self::Text | Self::Ribbon => OverflowMenu::AllTabs,
Self::Panel => OverflowMenu::HiddenOnly,
}
}
@@ -109,6 +112,11 @@ impl TabKind {
self == Self::Text
}
/// Whether the shown tab is marked by one accent underline that slides to the newly shown tab (ribbon tabs).
pub fn slides_underline(self) -> bool {
todo!("rb.R1")
}
/// Whether a middle click closes a closable tab.
pub fn middle_click_closes(self) -> bool {
self == Self::Document
+3
View File
@@ -6,9 +6,12 @@
//! `ItemSource::text` is each tab's name in the overflow menu. The drag payload of a tab is `ListDrag<K>`; a dock that
//! carries panels reads the same payload with the panel key as `K`.
mod end;
#[cfg(feature = "testing")]
mod stories;
pub use end::StripEnd;
use super::rules::{FitMode, OverflowMenu, OverflowPlace, TabKind};
use super::words::StripWords;
use super::{Tab, TabPartEvent};
+45
View File
@@ -0,0 +1,45 @@
//! `StripEnd`: an item at the reading end of a tab strip, beside the tabs.
use crate::contract::Entry;
use crate::primitives::IconSpec;
use crate::runtime::commands::CommandRef;
use crate::runtime::env::Label;
use craft_theme::Variant;
/// What an end item does when pressed.
#[allow(dead_code)] // P3(ribbon-w1): rb.R3
enum EndAction<'a> {
Command(CommandRef),
Menu(&'a [Entry<CommandRef>]),
}
/// An item at the reading end of a `TabStrip`: a button that runs a command or opens a menu. It drops its label before
/// the tabs overflow.
#[allow(dead_code)] // P3(ribbon-w1): rb.R3
pub struct StripEnd<'a> {
label: Label,
icon: IconSpec<'a>,
action: EndAction<'a>,
variant: Variant,
}
impl<'a> StripEnd<'a> {
/// An item that runs `command`, named `label`, with `icon`.
pub fn command(label: impl Into<Label>, icon: IconSpec<'a>, command: impl Into<CommandRef>) -> Self {
let _ = (label.into(), icon, command.into());
todo!("rb.R3")
}
/// An item that opens a menu of `entries`, named `label`, with `icon`.
pub fn menu(label: impl Into<Label>, icon: IconSpec<'a>, entries: &'a [Entry<CommandRef>]) -> Self {
let _ = (label.into(), icon, entries);
todo!("rb.R3")
}
/// Sets the button variant of the item.
#[must_use]
pub fn variant(self, variant: Variant) -> Self {
let _ = variant;
todo!("rb.R3")
}
}
+15
View File
@@ -23,6 +23,17 @@ use egui::{Pos2, Rect, Response, Vec2};
#[cfg(feature = "testing")]
mod stories;
/// The role of a tab in its strip.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum TabRole {
/// An ordinary tab.
#[default]
Standard,
/// A tab that appears with a selection: it takes the accent text colour, enters with motion and leaves through `Presence`.
Contextual,
}
/// What a tab's own parts report, besides what the collection reads from the pointer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
@@ -132,6 +143,9 @@ pub struct Tab<'a> {
#[style_key]
#[prop]
kind: TabKind,
/// Whether the tab is a standard one or a contextual one.
#[prop]
role: TabRole,
/// Large Tabs: the strip's taller form with the body type.
#[style_key]
#[prop(flag)]
@@ -167,6 +181,7 @@ impl<'a> Tab<'a> {
Tab {
common: Common::new(),
kind: TabKind::Document,
role: TabRole::default(),
large: false,
detail: None,
icon: None,
+25
View File
@@ -72,6 +72,9 @@ pub struct TextField<'a, C: Codec + Clone + 'static = PlainText> {
/// the id the collection is built with (`Props::id`), so a pattern can name a collection it shows after the field.
#[prop]
drives: Option<Id>,
/// The caret position the caller binds, in characters.
#[allow(dead_code)] // P3(chrome-w6): ch.C16b
caret: Option<Bind<'a, usize>>,
}
impl<'a> TextField<'a, PlainText> {
@@ -106,6 +109,7 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
leading: Vec::new(),
arrow: false,
drives: None,
caret: None,
}
.label(label)
}
@@ -171,6 +175,20 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// A multi-line field grows with its text up to `lines` lines, then scrolls inside with the caret in view.
#[must_use]
pub fn max_lines(self, lines: usize) -> Self {
let _ = lines;
todo!("ch.C16b")
}
/// Binds the caret position, in characters: a changed bound caret is applied at a character boundary and revealed.
#[must_use]
pub fn caret(self, caret: Bind<'a, usize>) -> Self {
let _ = caret;
todo!("ch.C16b")
}
/// The most characters the text holds; `None` clears the limit. A single-line field holds 1024 characters unless
/// this is set; a multi-line field has no limit unless this is set.
#[must_use]
@@ -186,6 +204,13 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// Tab keeps focus and is reported in the edit response: `Some(true)` for Tab, `Some(false)` for Shift+Tab.
#[must_use]
pub fn tab_reports(self) -> Self {
let _ = self;
todo!("dg.F20b")
}
/// The caller hangs a context menu of its own on the field (`Menu::context` over its response): a right click opens
/// that menu instead of the field's edit menu.
#[must_use]