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

This commit is contained in:
aiongg
2026-11-14 01:46:34 +00:00
parent 7e7a97ed01
commit 3c509c6227
43 changed files with 581 additions and 82 deletions
+5 -4
View File
@@ -314,11 +314,12 @@ impl Default for PressState {
/// The longest gap between presses that still count as one multi-click, in seconds.
pub const MULTI_CLICK_TIME: f64 = 0.3;
/// The click count of a press at `pos` and `time`, given the previous press `(pos, time, clicks)`: one more when
/// it follows within [`MULTI_CLICK_TIME`] and `slop` of the previous one, else 1.
pub fn count_clicks(previous: Option<(Pos2, f64, u32)>, pos: Pos2, time: f64, slop: f32) -> u32 {
/// The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks,
/// mods)`: one more when it follows within [`MULTI_CLICK_TIME`] and `slop` of the previous one with the same
/// modifiers, else 1.
pub fn count_clicks(previous: Option<(Pos2, f64, u32, Mods)>, pos: Pos2, time: f64, mods: Mods, slop: f32) -> u32 {
match previous {
Some((place, when, count)) if time - when <= MULTI_CLICK_TIME && place.distance(pos) <= slop => count + 1,
Some((place, when, count, held)) if held == mods && time - when <= MULTI_CLICK_TIME && place.distance(pos) <= slop => count + 1,
_ => 1,
}
}
+19 -1
View File
@@ -3,7 +3,9 @@
use super::context::{Cx, CxCore};
use crate::contract::{Component, EditResponse, Pointer as _, Validity, ValueOf};
use crate::primitives::Adopted;
use craft_behavior::{CancelReason, EditEvent, Gesture, GesturePhase, Mixed, PartRef, PointerButton, PressCancel, PressPhase, Sense, Value};
use craft_behavior::{
CancelReason, EditEvent, Gesture, GesturePhase, Mixed, PartRef, PointerButton, PressCancel, PressPhase, Sense, Value, WheelPhase,
};
use egui::{Id, Pos2};
use std::sync::Arc;
@@ -334,3 +336,19 @@ impl<C: Component> Cx<'_, C> {
}
}
}
impl<C: Component> Cx<'_, C> {
/// Advances the component's wheel run, one edit gesture through the gesture slot: a `WheelPhase::End` share commits
/// a running run, any other notch with `Some(next)` proposes it.
#[allow(dead_code)] // P3(panels-w4): pn.C23
pub fn wheel_run(&mut self, phase: WheelPhase, next: Option<ValueOf<C>>) {
let _ = (phase, next);
todo!("pn.C23")
}
/// Whether the running gesture is a wheel run.
#[allow(dead_code)] // P3(panels-w4): pn.C23
pub fn in_wheel_run(&self) -> bool {
todo!("pn.C23")
}
}
+1 -1
View File
@@ -233,7 +233,7 @@ pub struct Resolved<'p> {
/// The padding the shape's props add on every side, over the style's: a collection's `ContainerProps::pad`.
pub(crate) pad: f32,
/// `Common.description`.
pub(crate) description: Option<&'p str>,
pub description: Option<&'p str>,
/// `Common.tooltip`.
#[doc(hidden)]
pub tooltip: Option<&'p Tooltip>,
+1 -1
View File
@@ -271,7 +271,7 @@ impl<'a> Draw<'a> {
/// Where `layout` of `run` starts in `rect`'s width: the free room shared out by the run's alignment, the reading
/// start being the right edge in a right-to-left paragraph.
fn text_x(&self, rect: Rect, run: &TextRun<'_>, layout: &TextLayout) -> f32 {
pub fn text_x(&self, rect: Rect, run: &TextRun<'_>, layout: &TextLayout) -> f32 {
let rtl = self.text_direction == Direction::Rtl && !run.ltr;
rect.left() + (rect.width() - layout.size().x).max(0.0) * super::text::free_room_before(run.align, rtl)
}
+3 -3
View File
@@ -84,7 +84,7 @@ pub struct PassPointer {
#[derive(Default)]
pub(crate) struct Memory {
last_press: Option<(Pos2, f64, u32)>,
last_press: Option<(Pos2, f64, u32, craft_keymap::Mods)>,
press_targets: PressTargets,
/// A cancel a service requested for the running pass.
requested: Option<(u64, PressCancel)>,
@@ -128,8 +128,8 @@ pub(crate) fn begin(ctx: &Context, hit: HitSizes, latched: craft_keymap::Mods) {
let mut events = read.events.clone();
for event in &mut events {
if let PointerEvent::Pressed { button: PointerButton::Primary, pos, time, clicks, .. } = event {
*clicks = count_clicks(memory.last_press, *pos, *time, hit.slop);
memory.last_press = Some((*pos, *time, *clicks));
*clicks = count_clicks(memory.last_press, *pos, *time, latched, hit.slop); // P3(top-w2): pn.C14
memory.last_press = Some((*pos, *time, *clicks, latched));
}
}
if read.primary_pressed || other_pressed {
+9 -4
View File
@@ -151,12 +151,13 @@ struct StoryArgs {
disabled_text: Option<Expr>,
title: Option<Expr>,
group: Option<Expr>,
commands: Option<Expr>,
}
impl Parse for StoryArgs {
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let ty: Type = input.parse()?;
let (mut covers, mut drive, mut disabled_text, mut title, mut group) = (Vec::new(), None, None, None, None);
let (mut covers, mut drive, mut disabled_text, mut title, mut group, mut commands) = (Vec::new(), None, None, None, None, None);
while input.peek(Token![,]) {
input.parse::<Token![,]>()?;
if input.is_empty() {
@@ -176,14 +177,16 @@ impl Parse for StoryArgs {
title = Some(input.parse::<Expr>()?);
} else if key == "group" {
group = Some(input.parse::<Expr>()?);
} else if key == "commands" {
commands = Some(input.parse::<Expr>()?);
} else {
return Err(syn::Error::new(
key.span(),
"`story` takes `covers = [..]`, `drive = ..`, `disabled_text = ..`, `title = ..` and `group = ..`",
"`story` takes `covers = [..]`, `drive = ..`, `disabled_text = ..`, `title = ..`, `group = ..` and `commands = ..`",
));
}
}
Ok(StoryArgs { ty, covers, drive, disabled_text, title, group })
Ok(StoryArgs { ty, covers, drive, disabled_text, title, group, commands })
}
}
@@ -192,6 +195,7 @@ impl Parse for StoryArgs {
/// reason to show while disabled, which the story takes from `StoryData::tooltip`. `title = ".."` is the caption a
/// viewer shows over the story. `group = ".."` puts the story in a named group with the type's other stories that
/// name it, in declaration order; a viewer shows a group together, each story under its caption.
/// `commands = <fn>` names a `fn(CommandInput) -> CommandInput` that sets the command states the story runs under.
/// The type's registration and the story meet by the type's registered name.
#[proc_macro_attribute]
pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream {
@@ -205,6 +209,7 @@ pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream {
let disabled_text = args.disabled_text.as_ref().map(|text| quote!(.disabled_text(#text)));
let title = args.title.as_ref().map(|title| quote!(.title(#title)));
let group = args.group.as_ref().map(|group| quote!(.group(#group)));
let commands = args.commands.as_ref().map(|commands| quote!(.commands(#commands)));
quote! {
#func
@@ -213,7 +218,7 @@ pub fn story(attr: TokenStream, item: TokenStream) -> TokenStream {
env!("CARGO_PKG_NAME"),
env!("CARGO_CRATE_NAME"),
::std::any::type_name::<#ty>,
::craft_ui::testing::Story::new(#name, #ident).covers(&[#(::craft_ui::testing::Required::#covers),*]) #drive #disabled_text #title #group,
::craft_ui::testing::Story::new(#name, #ident).covers(&[#(::craft_ui::testing::Required::#covers),*]) #drive #disabled_text #title #group #commands,
)
.at(file!(), line!())
}
+17 -1
View File
@@ -9,7 +9,8 @@ use crate::runtime::overlay::CloseReason;
use crate::runtime::words::CommonWords;
use crate::sections::DialogRole;
use craft_theme::variant::Tone;
use egui::{Response, Ui};
use egui::{Context, Response, Ui};
use serde_json::Value;
/// What an alert reports: its response and how it closed in this pass.
#[derive(Debug)]
@@ -69,6 +70,13 @@ impl<'a> Alert<'a> {
self
}
/// The alert that reports a typed value clamped to its range, worded by the text family's range sentences: the
/// whole-number one when `alert.whole`, the value one when it has a unit, else the number one.
pub fn range(title: impl Into<Label>, alert: &crate::text::RangeAlert, env: &Env) -> Alert<'static> {
let _ = (title.into(), alert, env);
todo!("dl.N1")
}
/// Shows the alert.
pub fn show(self, ui: &mut Ui) -> AlertOutput {
let (content, open) = self.split();
@@ -156,6 +164,14 @@ impl StackDialog for HostedAlert {
shown.closed.map(|_| DialogResult::Ok(()))
}
fn confirm(&mut self, _: &Context) -> Option<()> {
todo!("dl.K5")
}
fn json_fields(&self) -> Option<Value> {
todo!("dl.K5")
}
fn key(&self) -> Option<&str> {
Some(ALERT_KEY)
}
+22
View File
@@ -103,6 +103,28 @@ pub trait StackDialog: Any + Send {
fn cancelled(&mut self, _ctx: &Context) {}
}
/// Why a dialog refused `ui.dialog.set`; each has one wording.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum FieldRefusal<'a> {
/// The dialog has no fields.
NoFields,
/// The dialog has no field of that name.
Unknown,
/// The field's row is hidden or disabled.
Inactive,
/// The field cannot hold this value.
Rejects(&'a serde_json::Value),
}
impl FieldRefusal<'_> {
/// The refusal's wording for `field`.
pub fn message(&self, field: &str) -> String {
let _ = field;
todo!("dl.K1")
}
}
/// The suite's probe of the stack dialog `T`: `#[pattern(dialog)]` registers through it, so only a `StackDialog`
/// takes the attribute.
#[doc(hidden)]
+3 -1
View File
@@ -11,6 +11,7 @@ mod modal;
mod prompt;
mod prompts;
mod recovery;
mod serde_fields;
mod stack;
#[cfg(feature = "testing")]
#[doc(hidden)]
@@ -25,11 +26,12 @@ pub use blocking::{BlockingOverlay, BlockingOverlayStyle};
pub use frame::{DialogFrame, DialogFrameStyle, DialogOutput, FooterCx, FooterHooks};
#[doc(hidden)]
pub use host::dialog_probe;
pub use host::{BesideStep, DialogHost, DialogResult, OpenDialog, StackDialog, StackWalk, StartupStage};
pub use host::{BesideStep, DialogHost, DialogResult, FieldRefusal, OpenDialog, StackDialog, StackWalk, StartupStage};
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 serde_fields::{serde_fields, set_serde_field};
pub use stack::{DialogId, DialogStack, dialog_id};
pub use unsaved::{UnsavedAnswer, UnsavedChangesDialog, UnsavedChangesOutput};
pub use words::DialogWords;
+14 -3
View File
@@ -10,7 +10,7 @@ use crate::runtime::env::{Env, Label};
use crate::runtime::focus::Initial;
use crate::runtime::overlay::CloseReason;
use crate::sections::{DialogRole, FooterButton, Section};
use craft_keymap::mnemonic;
use craft_keymap::{Chord, mnemonic};
use craft_theme::variant::Tone;
use egui::{Response, Ui};
@@ -23,6 +23,7 @@ pub(super) struct Reply {
label: Label,
role: DialogRole,
lettered: bool,
chord: Option<Chord>,
enabled: bool,
reason: Option<Label>,
}
@@ -30,7 +31,7 @@ pub(super) struct Reply {
impl Reply {
/// An answer with a letter.
pub(super) fn new(label: impl Into<Label>, role: DialogRole) -> Self {
Reply { label: label.into(), role, lettered: true, enabled: true, reason: None }
Reply { label: label.into(), role, lettered: true, chord: None, enabled: true, reason: None }
}
/// An answer without a letter.
@@ -38,6 +39,13 @@ impl Reply {
Reply { lettered: false, ..Reply::new(label, role) }
}
/// The chord that answers the prompt.
#[allow(dead_code)] // P3(dialogs-w4): dl.K7
pub(super) fn chord(mut self, chord: Chord) -> Self {
self.chord = Some(chord);
self
}
/// Whether the answer is available; `reason` is what the disabled button tells.
pub(super) fn enabled(mut self, on: bool, reason: Option<Label>) -> Self {
self.enabled = on;
@@ -52,7 +60,7 @@ pub(super) fn buttons(env: &Env, replies: Vec<Reply>) -> Vec<FooterButton> {
let view = env.view();
let labels: Vec<Label> = replies.iter().map(|reply| view.resolve(&reply.label)).collect();
let lettered: Vec<&str> = replies.iter().zip(&labels).filter(|(reply, _)| reply.lettered).map(|(_, label)| label.as_str()).collect();
let mut letters = mnemonic::assign(&lettered).into_iter();
let mut letters = mnemonic::assign(&lettered, &env.folder()).into_iter(); // P3(dialogs-w4): tp.T11
replies
.into_iter()
.zip(labels)
@@ -61,6 +69,9 @@ pub(super) fn buttons(env: &Env, replies: Vec<Reply>) -> Vec<FooterButton> {
if let Some(reason) = reply.reason {
button = button.disabled_reason(reason);
}
if let Some(chord) = reply.chord {
button = button.chord(chord);
}
match reply.lettered.then(|| letters.next().flatten()).flatten() {
Some((letter, _)) => button.letter(letter),
None => button,
+17
View File
@@ -165,6 +165,9 @@ pub struct StandardPrompt {
/// `PromptAnswer::tag` or `PromptAnswer::take_tag`.
#[prop(boxed)]
tag: Option<Box<dyn Any + Send>>,
/// What Escape and the close action answer.
#[allow(dead_code)] // P3(top-w4): tp.T27
escape: PromptChoice,
/// The counted noun of the delete question, as a count word with `{n}` (one and other forms); the default is
/// "{n} item" and "{n} items".
#[prop]
@@ -202,6 +205,7 @@ impl StandardPrompt {
open: true,
chosen: PromptChoice::Proceed,
tag: None,
escape: PromptChoice::Cancel,
noun: None,
title: None,
message: None,
@@ -303,6 +307,19 @@ impl StandardPrompt {
self
}
/// Escape and the close action answer `choice` in place of Cancel.
#[must_use]
pub fn escape(mut self, choice: PromptChoice) -> Self {
self.escape = choice;
self
}
/// The framework's damaged-file prompt for the file `name`.
pub fn damaged_file(name: impl Into<String>) -> Self {
let _ = name.into();
todo!("dl.K74")
}
/// The question this prompt asks.
pub fn kind(&self) -> &PromptKind {
&self.kind
@@ -0,0 +1,17 @@
//! The serde round trip a dialog's `json_fields` and `set_json_field` share.
use serde::Serialize;
use serde::de::DeserializeOwned;
/// The value as a JSON object; `None` when it does not serialise to one.
pub fn serde_fields<T: Serialize>(value: &T) -> Option<serde_json::Value> {
let _ = value;
todo!("dl.K3")
}
/// Replaces the top-level key `field` of `value` with `json`, by serialising the value, replacing the key and reading
/// it back. An unknown key or a value `T` cannot hold gives the refusal's message and leaves `value` unchanged.
pub fn set_serde_field<T: Serialize + DeserializeOwned>(value: &mut T, field: &str, json: serde_json::Value) -> Result<(), String> {
let _ = (value, field, json);
todo!("dl.K3")
}
+10
View File
@@ -82,6 +82,8 @@ pub struct DockConfig {
/// they are on the desktop (not on Wayland) and its panels allow it (`PanelSpec::allow_native`). Elsewhere, and
/// with this off, it shows in the app window.
pub native_windows: bool,
/// Docked groups' menus get Minimize and Move Group Up and Down.
pub group_order_items: bool,
}
impl Default for DockConfig {
@@ -99,11 +101,19 @@ impl Default for DockConfig {
tab_close_buttons: false,
wheel_selects_tabs: false,
native_windows: true,
group_order_items: false,
}
}
}
impl DockConfig {
/// The Minimize and Move Group Up and Down items of docked groups' menus on or off.
#[must_use]
pub fn group_order_items(mut self, on: bool) -> Self {
self.group_order_items = on;
self
}
/// The picture-frame profile on or off.
#[must_use]
pub fn side_edge_zones(mut self, on: bool) -> Self {
+10 -1
View File
@@ -14,6 +14,7 @@ use crate::contract::{
Bind, BindMut, Common, Component, Container, ContainerProps, Cx, DragBand, HeaderRegion, Inner, Mount, NoValue, Outcome, Overlay, Pad,
Pointer as _, Props as _, Role, Show as _, ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::runtime::drag::OsFile;
use crate::runtime::env::{Env, Label};
use crate::runtime::overlay::CloseReason;
use crate::runtime::windows::WindowSpec;
@@ -52,6 +53,8 @@ pub struct FloatingGroupOutput {
pub action: Option<HeaderAction>,
/// Whether a double click on the title band asks to minimize the group, or restore it when it is minimized.
pub minimized_toggled: bool,
/// The files dropped on the group's window that no target there took.
pub files: Vec<OsFile>,
}
impl Outcome for FloatingGroupOutput {
@@ -265,7 +268,13 @@ impl Component for FloatingGroup<'_> {
if let Some(opener) = self.menu_opener {
Popup::toggle(opener, &mut cx);
}
let output = FloatingGroupOutput { response: cx.response.clone(), placed: self.placed, action: self.taken, minimized_toggled: self.toggled };
let output = FloatingGroupOutput {
response: cx.response.clone(),
placed: self.placed,
action: self.taken,
minimized_toggled: self.toggled,
files: Vec::new(),
}; // P3(panels-w1): pn.C8
native::raise(&cx.core.ctx, &output);
native::fade(&cx.core.ctx, &output);
output
+19 -5
View File
@@ -1,6 +1,6 @@
//! `Flyout`: the panel an icon of an iconic column opens beside the column.
use crate::contract::overlay::{Anchor, Dismiss, Place};
use crate::contract::overlay::{Anchor, Dismiss, Place, PlacementChange};
use crate::contract::{BodyCx, Overlay, OverlayUi, PopupHandle};
use craft_behavior::dock::DockEdge;
use craft_behavior::overlay::{Align, Side};
@@ -49,7 +49,7 @@ impl Flyout {
.body_scroll(false)
}
/// Shows the flyout of `popup` while it is open, hung from `anchor`, and returns the rect its body showed in;
/// Shows the flyout of `popup` while it is open, hung from `anchor`, and returns what it showed;
/// `None` while it is closed. `body` returns the height it measures for `GroupAt::Measure`, or `None` to take
/// the flyout's own height.
pub fn show(
@@ -58,17 +58,31 @@ impl Flyout {
popup: PopupHandle,
anchor: Anchor,
mut body: impl FnMut(&mut Ui, &mut BodyCx<'_>, GroupAt) -> Option<f32>,
) -> Option<Rect> {
) -> Option<FlyoutShown> {
let size = self.size;
ui.show(popup, self.overlay(anchor), |ui, cx| {
let rect = ui.show(popup, self.overlay(anchor), |ui, cx| {
let measured = body(ui, cx, GroupAt::Measure(size.x)).map_or(size.y, |height| height.min(ui.available_height()));
let rect = crate::layout::place_in_flow(ui, Vec2::new(size.x, size.y.max(measured)));
body(ui, cx, GroupAt::Show(rect));
rect
})
});
// P3(framework-01-w9): fx.F50 reports the user's placement change and mounts the flyout as a layer of its own.
rect.map(|rect| FlyoutShown { rect, placed: None, dismissed: dismissed(ui, popup) })
}
}
/// What a shown flyout reports.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FlyoutShown {
/// The rect the flyout's body showed in.
pub rect: Rect,
/// The placement the user changed this pass: the flyout's size or top edge.
pub placed: Option<PlacementChange>,
/// The layer closed in this pass.
pub dismissed: bool,
}
/// Whether the layer of `popup` was dismissed in this pass of `ui` (Escape, a press outside, the focus leaving it).
pub(super) fn dismissed(ui: &OverlayUi<'_>, popup: PopupHandle) -> bool {
ui.closed.iter().any(|(id, _)| *id == popup.id())
+17 -1
View File
@@ -80,6 +80,22 @@ pub struct IconicColumnOutput<P> {
pub picked: Option<GroupItem>,
/// The width the user gave the iconic column on its inner edge this pass.
pub width: Option<f32>,
/// The size the user gave the open flyout, with the top edge's offset from the icons when it moved.
pub flyout: Option<FlyoutResize<P>>,
}
/// The size the user gave an open flyout.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FlyoutResize<P> {
/// The panel whose flyout was resized.
pub panel: P,
/// The new width.
pub width: f32,
/// The new height.
pub height: f32,
/// The top edge's offset from the icons' top, when the top edge moved.
pub offset: Option<f32>,
}
impl<P: Value + Hash + 'static> Outcome for IconicColumnOutput<P> {
@@ -508,7 +524,7 @@ impl<P: Value + Hash + 'static> Component for IconicColumn<'_, P> {
fn finish(self, cx: Cx<'_, Self>) -> IconicColumnOutput<P> {
let iconic = self.record.iconic.or(self.expand.then_some(false));
IconicColumnOutput { edit: cx.edit_response(), placed: cx.rect, iconic, picked: self.record.picked, width: self.width }
IconicColumnOutput { edit: cx.edit_response(), placed: cx.rect, iconic, picked: self.record.picked, width: self.width, flyout: None } // P3(framework-01-w9): fx.F51
}
}
+4 -2
View File
@@ -13,6 +13,7 @@ mod group;
mod floating;
mod panels;
mod rail;
mod root;
mod spec;
mod splitter;
@@ -56,8 +57,9 @@ mod iconic;
pub use dock_column::{
DockColumn, DockColumnOutput, DockColumnStyle, GroupSize, GroupView, fit_widths, group_heights, scale_widths, stacked, width_bounds,
};
pub use flyout::{Flyout, GroupAt};
pub use iconic::{IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes};
pub use flyout::{Flyout, FlyoutShown, GroupAt};
pub use iconic::{FlyoutResize, IconicColumn, IconicColumnOutput, IconicColumnStyle, IconicSizes};
pub use rail::{rail_actions, rail_lit};
pub use window_menu::{WindowMenuRows, WindowMenuRowsOutput};
use crate::contract::{
+17
View File
@@ -0,0 +1,17 @@
//! What a rail icon does for a panel and whether it shows lit, from the dock layout.
use craft_behavior::dock::{Action, Layout};
use std::hash::Hash;
/// The actions a click on the rail icon of `panel` takes: minimize a docked and shown panel, restore and activate a
/// minimized one, close a floating one's window, open a hidden one.
pub fn rail_actions<P: Clone + Eq + Hash>(layout: &Layout<P>, panel: &P) -> Vec<Action<P>> {
let _ = (layout, panel);
todo!("pn.C3")
}
/// Whether the rail icon of `panel` shows lit: its group is in the layout and not minimized.
pub fn rail_lit<P: Clone + Eq + Hash>(layout: &Layout<P>, panel: &P) -> bool {
let _ = (layout, panel);
todo!("pn.C4")
}
+9 -3
View File
@@ -8,7 +8,7 @@ use crate::contract::{
PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, Trigger,
};
use crate::menu::{self, Menu, MenuItem};
use crate::runtime::commands::{FireSource, ResolvedCommand};
use crate::runtime::commands::{CommandRef, FireSource, ResolvedCommand};
use crate::runtime::env::Label;
use crate::style::{ComponentStyle, GlyphRole, StyleCx};
use craft_behavior::overlay::{Align, Side};
@@ -96,7 +96,7 @@ struct Laid {
/// One rail button that may stand for a group of tools. The face shows the tool `shown` with a mark at the corner
/// when there is a flyout. A click, Enter or Space selects the shown tool and runs its command; holding the press,
/// dragging it away from the button, a right click or Alt+Down opens the flyout; a press on the corner mark opens it
/// dragging it away from the button, a right click or the Menu key opens the flyout; a press on the corner mark opens it
/// at once; after a press that opened it, releasing over a row picks it. Rows are the tools' commands, the shown tool with the radio mark. A hold selects the shown tool
/// unless `hold_selects` is off, as for a command button.
#[derive(crate::contract::Component, crate::contract::Props)]
@@ -115,6 +115,11 @@ pub struct FlyoutButton<'a, T: Value + 'static> {
/// The button is dragged and takes drops: the toolbar is being edited, and it has no flyout.
#[prop(into)]
edit: Option<SlotEdit>,
/// A click, Enter or Space fires this command in place of selecting the shown tool; the flyout opens by a hold, a
/// drag away, a right click or the Menu key.
#[prop(into)]
#[allow(dead_code)] // P3(panels-w2): pn.N2
click: Option<CommandRef>,
laid: Option<Laid>,
picked: Option<T>,
open: bool,
@@ -132,6 +137,7 @@ impl<'a, T: Value + 'static> FlyoutButton<'a, T> {
hold_selects: true,
opens: Side::End,
edit: None,
click: None,
laid: None,
picked: None,
open: false,
@@ -213,7 +219,7 @@ impl<T: Value + 'static> Component for FlyoutButton<'_, T> {
cx.part(MARK, mark)
.sense(Sense::CLICK)
.priority(HitPriority::new(HitLevel::Handle, 0))
.pointer_only("Alt+Down, the Menu key and a right click open the flyout")
.pointer_only("the Menu key and a right click open the flyout")
.toggles("menu");
}
self.laid = Some(laid);
+9
View File
@@ -64,6 +64,8 @@ pub struct ToolRailOutput<T> {
pub double_clicked: Option<T>,
/// The column toggle was clicked; the host flips its column count.
pub toggle_columns: bool,
/// The side toggle was clicked; the host moves the rail to the other edge.
pub toggle_side: bool,
/// The Edit Toolbar button's response while the rail shows it: a click on it opens the drawer, and the drawer
/// takes it as its opener ([`ToolbarDrawer::opened_by`](crate::rails::ToolbarDrawer::opened_by)).
pub edit_toolbar: Option<Response>,
@@ -127,6 +129,11 @@ pub struct ToolRail<'a, T: Value + 'static> {
/// Shows the column toggle at the top, named by the label.
#[prop(into)]
column_toggle: Option<Label>,
/// Shows a button beside the column toggle, named by the label, that asks the host to move the rail to the other
/// edge.
#[prop(into)]
#[allow(dead_code)] // P3(panels-w2): pn.C15
side_toggle: Option<Label>,
/// Shows the Edit Toolbar button after the last slot, named by the label.
#[prop(into)]
edit_toolbar: Option<Label>,
@@ -163,6 +170,7 @@ impl<'a, T: Value + 'static> ToolRail<'a, T> {
columns: NonZeroU8::MIN,
edge: PaneEdge::Start,
column_toggle: None,
side_toggle: None,
edit_toolbar: None,
editing: false,
hidden: &[],
@@ -294,6 +302,7 @@ impl<T: Value + 'static> Component for ToolRail<'_, T> {
select: None,
double_clicked: None,
toggle_columns: self.toggled,
toggle_side: false, // P3(panels-w2): pn.C15
edit_toolbar: None,
flyout: None,
dropped: None,
+11 -1
View File
@@ -404,6 +404,8 @@ pub struct FooterButton {
label: Label,
role: DialogRole,
letter: Option<char>,
#[allow(dead_code)] // P3(dialogs-w4): dl.K6
chord: Option<Chord>,
enabled: bool,
disabled_reason: Option<Label>,
tooltip: Option<Label>,
@@ -423,7 +425,7 @@ impl FooterButton {
/// A button named `label` with the meaning `role`.
pub fn new(label: impl Into<Label>, role: DialogRole) -> Self {
FooterButton { label: label.into(), role, letter: None, enabled: true, disabled_reason: None, tooltip: None, stays_open: false }
FooterButton { label: label.into(), role, letter: None, chord: None, enabled: true, disabled_reason: None, tooltip: None, stays_open: false }
}
/// The letter that activates the button while its dialog holds focus and no text part owns the keys. The
@@ -434,6 +436,14 @@ impl FooterButton {
self
}
/// A modified chord that presses the button while its dialog is the top modal, whether or not a text part owns
/// plain keys.
#[must_use]
pub fn chord(mut self, chord: Chord) -> Self {
self.chord = Some(chord);
self
}
/// Whether the button can be activated; a disabled button ignores its letter too.
#[must_use]
pub const fn enabled(mut self, on: bool) -> Self {
+7
View File
@@ -74,6 +74,13 @@ impl AlignAction {
AlignAction::AlignBottomEdges,
];
/// The bar's two sections of four buttons: align left, centre, right edges and distribute vertically; align top,
/// centre, bottom edges and distribute horizontally.
pub const BAR: [[AlignAction; 4]; 2] = [
[AlignAction::AlignLeftEdges, AlignAction::AlignHorizontalCenters, AlignAction::AlignRightEdges, AlignAction::DistributeVertically],
[AlignAction::AlignTopEdges, AlignAction::AlignVerticalCenters, AlignAction::AlignBottomEdges, AlignAction::DistributeHorizontally],
];
/// The eight distribute commands, in the order of their buttons and menu rows.
pub const DISTRIBUTE: [AlignAction; 8] = [
AlignAction::DistributeTopEdges,
+31 -2
View File
@@ -3,6 +3,7 @@
use crate::buttons::IconButton;
use crate::contract::{Props as _, Show as _};
use crate::display::{Divider, Elide, Progress, Shade, Text};
use crate::runtime::commands::CommandRef;
use crate::runtime::env::{Env, Label};
use crate::style::TypeRole;
use craft_behavior::IconId;
@@ -18,12 +19,16 @@ pub struct StatusMessage {
pub text: Label,
/// The tone it reads in; `Neutral` reads faint.
pub tone: Tone,
/// The command a click on the message runs; the message then shows as a link.
pub command: Option<CommandRef>,
/// The tooltip the message shows.
pub tooltip: Option<Label>,
}
impl StatusMessage {
/// A neutral message of `text`.
pub fn new(text: impl Into<Label>) -> Self {
StatusMessage { text: text.into(), tone: Tone::Neutral }
StatusMessage { text: text.into(), tone: Tone::Neutral, command: None, tooltip: None }
}
/// Sets the tone the message reads in.
@@ -33,6 +38,20 @@ impl StatusMessage {
self
}
/// Makes the message a link that runs `command` on a click, Enter or Space.
#[must_use]
pub fn command(mut self, command: impl Into<CommandRef>) -> Self {
self.command = Some(command.into());
self
}
/// Sets the tooltip the message shows.
#[must_use]
pub fn tooltip(mut self, text: impl Into<Label>) -> Self {
self.tooltip = Some(text.into());
self
}
/// Shows the message after a rule: faint, or in the colour of its tone, on one line that ends in an ellipsis when
/// it does not fit and then shows whole in a tooltip. The status bar's live region announces it. An empty message
/// shows nothing, its rule included.
@@ -40,6 +59,7 @@ impl StatusMessage {
if self.text.as_str().is_empty() {
return None;
}
let _ = (&self.command, &self.tooltip); // P3(panels-w2): pn.C12 draws a `Link` with the command and tooltip
Divider::vertical().show(ui);
let text = Text::new(self.text.clone()).elide(Elide::End);
let text = if self.tone == Tone::Neutral { text.shade(Shade::Faint) } else { text.tone(self.tone) };
@@ -65,12 +85,13 @@ pub struct StatusProgress {
label: Label,
fraction: Option<f32>,
cancel: Option<Label>,
refused: Option<Label>,
}
impl StatusProgress {
/// A task named `label`, `fraction` done between 0 and 1, or `None` while it has reported nothing.
pub fn new(label: impl Into<Label>, fraction: Option<f32>) -> Self {
StatusProgress { label: label.into(), fraction, cancel: None }
StatusProgress { label: label.into(), fraction, cancel: None, refused: None }
}
/// Adds a cancel button named `label`.
@@ -80,6 +101,13 @@ impl StatusProgress {
self
}
/// Shows the cancel button disabled, with `reason` as the tooltip that says why the task cannot be cancelled.
#[must_use]
pub fn cancel_refused(mut self, reason: impl Into<Label>) -> Self {
self.refused = Some(reason.into());
self
}
/// Shows the name and the bar, the percentage and the cancel button, in reading order.
pub fn show(self, ui: &mut Ui) -> StatusProgressOutput {
Text::new(self.label.clone()).shade(Shade::Muted).show(ui);
@@ -93,6 +121,7 @@ impl StatusProgress {
let percent = Env::of(ui).format().percent(f64::from(Progress::clamped(fraction)), 0);
Text::new(percent).role(TypeRole::Mono).shade(Shade::Muted).show(ui);
}
let _ = &self.refused; // P3(panels-w2): tp.R1 disables the cancel button with `TooltipSpec::disabled_text`
let cancelled = self.cancel.is_some_and(|label| IconButton::new(IconId::new("close")).label(label).show(ui).clicked());
StatusProgressOutput { response, cancelled }
}
+3 -1
View File
@@ -150,6 +150,8 @@ pub struct StatusReadoutOutput {
pub view: EditEvents<CanvasView>,
/// The item chosen in the menu this pass; the host stores it.
pub item: Option<StatusItem>,
/// A typed zoom outside the zoom range was clamped, in the pass it committed.
pub invalid_zoom: Option<crate::text::InvalidZoom>,
}
impl Outcome for StatusReadoutOutput {
@@ -242,6 +244,6 @@ impl<'a> StatusReadout<'a> {
(field.inner.map(|zoom| zoom.edit.response), menu.picked)
});
let (zoom, item) = shown.inner.unzip();
StatusReadoutOutput { response: shown.output, zoom: zoom.flatten(), view: events, item: item.flatten() }
StatusReadoutOutput { response: shown.output, zoom: zoom.flatten(), view: events, item: item.flatten(), invalid_zoom: None } // P3(canvas-widgets-w11): cw.C60
}
}
+3
View File
@@ -6,6 +6,7 @@ use super::RowDragSpot;
use super::thumb::ThumbTarget;
use super::trailing::TrailingPart;
use crate::contract::{ItemOutput, NoValue, OpenChange, Outcome};
use crate::runtime::commands::FireSource;
use craft_keymap::Mods;
use egui::{Rect, Response};
@@ -47,6 +48,8 @@ pub enum RowEvent {
/// The row held the collection's lead when the press began (a press on a part moves the lead to its row);
/// true for a key activation.
was_lead: bool,
/// What activated the part: the pointer, a key or an accessibility action.
source: FireSource,
},
/// A click landed on the leading text ([`ListRow::lead_text`]); an unmodified click also picked the row.
#[non_exhaustive]
+1 -1
View File
@@ -375,7 +375,7 @@ impl Component for ListRow<'_> {
(FireSource::Pointer, _) => false,
_ => true,
};
self.event = Some(RowEvent::Trailing { part: *part, mods: part_mods(cx, key, source), clicks, was_lead });
self.event = Some(RowEvent::Trailing { part: *part, mods: part_mods(cx, key, source), clicks, was_lead, source });
}
}
}
+10 -2
View File
@@ -6,8 +6,8 @@
use super::predicate::{DropTest, RowTest, RowText};
use super::{ListRow, RowEvent};
use crate::contract::{
Access, ActivateOn, Bind, BindMut, Collection, CollectionProps, CollectionResponse, Common, Component, ContainerProps, Cx, DropKind, EdgePress,
EditResponse, LeadOnOpen, ListDrag, Props as _, Role, RowState, SelectMode, Sizing,
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::runtime::env::{Env, Label};
use crate::style::{ComponentStyle, StyleCx};
@@ -44,6 +44,9 @@ pub struct List<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// The selection the caller owns.
#[prop]
selection: Option<Bind<'a, Selection<K>>>,
/// The column arrangement the caller owns: the header starts each pass from it and writes each change into it.
#[prop]
column_layout: Option<Bind<'a, ColumnLayout>>,
/// Scrolls the row of `key` into view once.
#[prop]
reveal: Option<K>,
@@ -90,6 +93,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> List<'a, K> {
props: ContainerProps::new().sizing(Sizing::Fill),
items: CollectionProps::new().select(SelectMode::Multi),
selection: None,
column_layout: None,
reveal: None,
tree: false,
can_rename: None,
@@ -216,6 +220,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for List<'_, K> {
self.selection.as_mut().map(Bind::reborrow)
}
fn column_layout(&mut self) -> Option<BindMut<'_, ColumnLayout>> {
self.column_layout.as_mut().map(Bind::reborrow)
}
fn reveal(&self) -> Option<&K> {
self.reveal.as_ref()
}
+2 -2
View File
@@ -308,8 +308,8 @@ impl<'a> MenuBar<'a> {
fn texts(&self, env: &EnvView<'_>) -> Vec<(String, Option<(char, usize)>)> {
let labels: Vec<Label> = self.titles.iter().map(|title| env.resolve(&title.label)).collect();
let refs: Vec<&str> = labels.iter().map(Label::as_str).collect();
let marks = if env.shell().os.is_mac() { vec![None; refs.len()] } else { mnemonic::assign(&refs) };
refs.iter().zip(marks).map(|(label, mark)| (mnemonic::marked(label).0, mark)).collect()
let marks = if env.shell().os.is_mac() { vec![None; refs.len()] } else { mnemonic::assign(&refs, &env.folder()) }; // P3(top-w2): tp.T11
refs.iter().zip(marks).map(|(label, mark)| (mnemonic::marked(label, &env.folder()).0, mark)).collect() // P3(top-w2): tp.T11
}
fn face(text: &str, lit: bool, mnemonic: Option<usize>) -> TitleFace {
+3 -3
View File
@@ -370,7 +370,7 @@ impl Component for MenuItem<'_> {
}
let columns = self.columns(cx, &level);
let detail = self.detail_size(cx);
let text = mnemonic::marked(cx.resolved.label).0;
let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0; // P3(top-w2): tp.T11
let run = TextRun::new(text.as_str()).role(self.label_look(cx.style).role);
let label = if text.is_empty() { Vec2::ZERO } else { cx.layout_at(&run, f32::INFINITY).size() };
let gap = cx.gap();
@@ -513,7 +513,7 @@ impl Component for MenuItem<'_> {
let level = cx.env.get::<MenuLevel>();
let command = cx.command.as_deref();
let (mark_column, icon_column) = self.lead_columns(&cx.core.ctx, side, gap, command, &level);
let text = mnemonic::marked(cx.resolved.label).0;
let text = mnemonic::marked(cx.resolved.label, &cx.env.folder()).0; // P3(top-w2): tp.T11
let mark = self.mark(command, &level);
let draw = ui.draw();
let detail = self.detail.as_ref().map(|detail| cx.env.resolve(detail));
@@ -568,7 +568,7 @@ impl Component for MenuItem<'_> {
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
let level = cx.env.get::<MenuLevel>();
access.name(Name::Text(mnemonic::marked(cx.resolved.label).0));
access.name(Name::Text(mnemonic::marked(cx.resolved.label, &cx.env.folder()).0)); // P3(top-w2): tp.T11
if self.heading {
access.role(Role::HEADING);
return;
+10 -10
View File
@@ -4,6 +4,7 @@ use super::popup::MenuStep;
use crate::contract::{Component, Cx, Remember as _};
use crate::runtime::env::{AppValues, EnvValue};
use craft_behavior::NavMove;
use craft_i18n::Folder;
use craft_keymap::mnemonic;
use egui::{Id, Pos2, Rect, pos2};
use std::sync::{Arc, Mutex, PoisonError};
@@ -47,7 +48,8 @@ struct LevelState {
pass: u64,
/// The letters of the rows as the user last saw them, for a typed letter that arrives before this pass's rows.
shown: Vec<Assigned>,
lettered: bool,
/// The interface language's folder when rows get access letters; `None` on a Mac menu.
lettered: Option<Folder>,
keyboard: bool,
/// A value menu: every row is a radio item.
values: bool,
@@ -115,8 +117,8 @@ impl MenuLevel {
/// Starts a body run over the level. The rows of this pass register in the measuring run and again in the real
/// run; the first row a pass registers drops the rows of the passes before.
/// Rows get no mnemonic when `lettered` is false: a Mac menu has no access letters.
fn begin(&self, submenu: bool, values: bool, keyboard: bool, lettered: bool, pointer: Option<Pos2>, pad: f32) {
/// Rows get no mnemonic when `lettered` is `None`: a Mac menu has no access letters.
fn begin(&self, submenu: bool, values: bool, keyboard: bool, lettered: Option<Folder>, pointer: Option<Pos2>, pad: f32) {
self.with(|state| {
state.pad = pad;
state.keyboard = keyboard;
@@ -158,9 +160,9 @@ impl MenuLevel {
state.pass = pass;
state.now.clear();
}
let letters = if state.lettered {
let letters = if let Some(folder) = state.lettered {
let labels: Vec<&str> = state.now.iter().map(|row| row.text.as_str()).collect();
mnemonic::assign(&labels)
mnemonic::assign(&labels, &folder) // P3(top-w2): tp.T11
} else {
vec![None; state.now.len()]
};
@@ -183,12 +185,10 @@ impl MenuLevel {
pub(super) fn mnemonic_of(&self, id: Id) -> Option<(char, usize)> {
self.with(|state| {
if !state.lettered {
return None;
}
let folder = state.lettered?; // P3(top-w2): tp.T11
let at = state.now.iter().position(|row| row.id == id)?;
let labels: Vec<&str> = state.now.iter().map(|row| row.text.as_str()).collect();
mnemonic::assign(&labels)[at]
mnemonic::assign(&labels, &folder)[at] // P3(top-w2): tp.T11
})
}
@@ -348,6 +348,6 @@ pub(crate) fn level_env<C: Component>(cx: &Cx<'_, C>, values: &mut AppValues, su
let level = MenuLevel::of(&cx.recall::<LevelMemory>());
let pointer = cx.core.ctx.input(|input| input.pointer.latest_pos());
let keyboard = crate::runtime::focus::keyboard_in_menu(&cx.core.ctx);
level.begin(submenu, valued, keyboard, !cx.env.shell().os.is_mac(), pointer, pad);
level.begin(submenu, valued, keyboard, (!cx.env.shell().os.is_mac()).then(|| cx.env.folder()), pointer, pad);
values.set(level);
}
+3
View File
@@ -51,6 +51,8 @@ pub enum NoticeEnd {
Closed(ToastId),
/// The timeout passed.
Expired(ToastId),
/// The notice left without the user seeing it end: the toast host dropped it.
Dropped(ToastId),
/// "Don't Show Again": the app stores `key` as silenced.
#[non_exhaustive]
Silenced {
@@ -156,6 +158,7 @@ impl NoticeCenter {
(ToastEnd::Action(_), Some(key)) => NoticeEnd::Silenced { id: *id, key: key.clone() },
(ToastEnd::Action(_) | ToastEnd::Dismissed, _) => NoticeEnd::Closed(*id),
(ToastEnd::Expired, _) => NoticeEnd::Expired(*id),
(ToastEnd::Dropped, _) => NoticeEnd::Dropped(*id), // P3(top-w4): tp.T26
});
false
});
+10 -8
View File
@@ -12,7 +12,7 @@ use super::words::PickerWords;
use crate::buttons::IconButton;
use crate::contract::overlay::{Popup, Trigger};
use crate::contract::{
Access, Bind, BindMut, BodyCx, CollectionEvent, Common, Component, Cx, Edit as _, EditResponse, Entry, Focus as _, InBar, LeadOnOpen, LeadSource,
Access, Bind, BindMut, BodyCx, CollectionEvent, Common, Component, Cx, Edit as _, EditResponse, Entry, Focus as _, LeadOnOpen, LeadSource,
MeasureCx, Numeric, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Role, Show as _,
ShowCollection as _, ShowContainer as _, Sizing, WordSetCx as _, step_stop, step_stops,
};
@@ -151,10 +151,9 @@ impl<'a, T: Value + 'static> Select<'a, T> {
}
}
/// Whether a select's faces fit their text: a select sized to its content, or one in a bar, whose members take their
/// content's width.
fn fits(sizing: Option<Sizing>, in_bar: bool) -> bool {
sizing == Some(Sizing::Content) || in_bar
/// Whether a select's faces fit their text: only a select sized to its content.
fn fits(sizing: Option<Sizing>) -> bool {
sizing == Some(Sizing::Content)
}
/// The stop a move over the closed field reaches: `stops` are the positions of the stepped entries and `from` the
@@ -192,7 +191,7 @@ impl<T: Value + 'static> Component for Select<'_, T> {
let mixed = cx.words::<PickerWords>().mixed.clone();
let entries = self.entries.iter().filter(|entry| entry.is_item()).map(|entry| (entry.face_label(), true));
let texts = entries.chain(self.placeholder.iter().map(|text| (text, false))).chain(std::iter::once((&mixed, false)));
let fit = fits(cx.resolved.sizing(), cx.env.get::<InBar>().0);
let fit = fits(cx.resolved.sizing());
texts.map(|(text, picture)| cx.face(self.sized_face(cx.env.resolve(text), picture, fit))).fold(Vec2::ZERO, Vec2::max)
}
@@ -227,7 +226,10 @@ impl<T: Value + 'static> Component for Select<'_, T> {
let labels: Vec<Label> =
self.entries.iter().map(|entry| if entry.is_item() { cx.env.resolve(entry.label()) } else { Label::Empty }).collect();
let typed = text.to_lowercase();
let found = TypeAhead::pick(&typed, held, labels.len(), |at| Cow::Borrowed(labels[at].as_str()));
let folder = cx.env.folder();
// P3(canvas-widgets-w12): cw.C64
let found =
TypeAhead::pick(&typed, held, labels.len(), |at| Cow::Borrowed(labels[at].as_str()), |text| folder.fold(text).as_str().to_owned());
if let Some(value) = found.filter(|&at| self.entries[at].is_enabled()).and_then(|at| self.entries[at].value()) {
cx.propose(value.clone());
list.open(cx);
@@ -345,7 +347,7 @@ impl<T: Value + 'static> Component for Select<'_, T> {
None if cx.value().is_none() => (cx.env.resolve(&cx.words::<PickerWords>().mixed.clone()), true),
None => (self.placeholder.as_ref().map_or(Label::Empty, |text| cx.env.resolve(text)), true),
};
let mut face = SelectFace::new(text).fit(fits(cx.resolved.sizing(), cx.env.get::<InBar>().0));
let mut face = SelectFace::new(text).fit(fits(cx.resolved.sizing()));
if let Some(icon) = held.and_then(|at| self.entries[at].icon_spec()) {
face = face.leading(icon.clone());
}
+11 -3
View File
@@ -5,9 +5,9 @@
use super::words::TableWords;
use crate::contract::overlay::Anchor;
use crate::contract::{
Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnCommands, ColumnRequest, ColumnSpec, Common, Component, ContainerProps, Cx,
DropKind, EditResponse, ListDrag, OverlayUi, Overlays as _, Props as _, Role, RowState, SelectMode, Show as _, ShowContainer as _, Sizing,
WordSetCx as _,
Bind, BindMut, Collection, CollectionProps, CollectionResponse, ColumnCommands, ColumnLayout, ColumnRequest, ColumnSpec, Common, Component,
ContainerProps, Cx, DropKind, EditResponse, ListDrag, OverlayUi, Overlays as _, Props as _, Role, RowState, SelectMode, Show as _,
ShowContainer as _, Sizing, WordSetCx as _,
};
use crate::display::Divider;
use crate::list::{DropTest, ListRow, RowEvent, RowTest, RowText};
@@ -53,6 +53,9 @@ pub struct Table<'a, K: Clone + Eq + Hash + Send + Sync + 'static> {
/// The selection the caller owns.
#[prop]
selection: Option<Bind<'a, Selection<K>>>,
/// The column arrangement the caller owns: the header starts each pass from it and writes each change into it.
#[prop]
column_layout: Option<Bind<'a, ColumnLayout>>,
/// Scrolls the row of `key` into view once.
#[prop]
reveal: Option<K>,
@@ -85,6 +88,7 @@ impl<'a, K: Clone + Eq + Hash + Send + Sync + 'static> Table<'a, K> {
props: ContainerProps::new().sizing(Sizing::Fill),
items: CollectionProps::new().select(SelectMode::Multi).columns(columns),
selection: None,
column_layout: None,
reveal: None,
tree: false,
can_rename: None,
@@ -189,6 +193,10 @@ impl<K: Clone + Eq + Hash + Send + Sync + 'static> Collection for Table<'_, K> {
self.selection.as_mut().map(Bind::reborrow)
}
fn column_layout(&mut self) -> Option<BindMut<'_, ColumnLayout>> {
self.column_layout.as_mut().map(Bind::reborrow)
}
fn reveal(&self) -> Option<&K> {
self.reveal.as_ref()
}
+66 -4
View File
@@ -10,6 +10,7 @@ use crate::contract::{
CollectionEvent, ContextMenuRequest, DropAt, DropKind, DropPlace, ListDrag, ReorderRule, ShowCollection as _, ShowContainer as _,
};
use crate::layout_components::Row;
use crate::runtime::drag::OsFile;
use crate::runtime::env::Label;
use craft_behavior::{EditEvent, SelectionChange, keyed};
use egui::{Pos2, Response, Ui};
@@ -28,12 +29,18 @@ pub struct DocumentTab<D> {
pub modified: bool,
/// The tab shows a close button.
pub closable: bool,
/// How far the document has opened, between 0 and 1; `None` for a document that is open.
pub progress: Option<f32>,
/// A second line of text the tab shows, such as the opening step.
pub detail: Option<Label>,
/// The accessible name of the close button, for a tab whose close cancels the opening.
pub close_label: 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 }
DocumentTab { id, label: label.into(), modified: false, closable: true, progress: None, detail: None, close_label: None }
}
/// Unsaved changes.
@@ -49,13 +56,34 @@ impl<D> DocumentTab<D> {
self.closable = on;
self
}
/// How far the document has opened; a tab with progress is a document still opening, and its close cancels.
#[must_use]
pub fn progress(mut self, fraction: Option<f32>) -> Self {
self.progress = fraction;
self
}
/// A second line of text the tab shows.
#[must_use]
pub fn detail(mut self, text: impl Into<Label>) -> Self {
self.detail = Some(text.into());
self
}
/// The accessible name of the close button.
#[must_use]
pub fn close_label(mut self, label: impl Into<Label>) -> Self {
self.close_label = Some(label.into());
self
}
}
/// What the tabs of a group did this pass, in the order they happened.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum DocumentTabsEvent<D> {
/// The tab was selected: a click or an arrow key.
/// The tab was selected: a click, an arrow key or a drag resting over it.
Selected(D),
/// The tab was activated: Enter, or a double click.
Activated(D),
@@ -89,6 +117,14 @@ pub enum DocumentTabsEvent<D> {
},
/// The tab's context menu is asked for.
ContextMenu(ContextMenuRequest<D>),
/// Files dropped from the operating system on the strip, before the tab `before` (last when `None`).
#[non_exhaustive]
FilesDropped {
/// The dropped files.
files: Vec<OsFile>,
/// The tab they go before.
before: Option<D>,
},
/// The strip's empty room after the tabs was double-clicked: the host opens a new document there.
EmptyDoubleClick,
}
@@ -117,6 +153,8 @@ pub struct DocumentTabs<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug
selected: Option<D>,
reorderable: bool,
tear_off: bool,
large: bool,
takes_files: bool,
leading: Option<Area<'a>>,
trailing: Option<Area<'a>>,
}
@@ -124,7 +162,17 @@ pub struct DocumentTabs<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug
impl<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> DocumentTabs<'a, D> {
/// The tabs of a group named `label`, in the host's order.
pub fn new(label: impl Into<Label>, tabs: &'a [DocumentTab<D>]) -> Self {
DocumentTabs { label: label.into(), tabs, selected: None, reorderable: false, tear_off: false, leading: None, trailing: None }
DocumentTabs {
label: label.into(),
tabs,
selected: None,
reorderable: false,
tear_off: false,
large: false,
takes_files: false,
leading: None,
trailing: None,
}
}
/// The document the group shows.
@@ -145,6 +193,20 @@ impl<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Documen
self
}
/// Every tab takes the strip's taller form.
#[must_use]
pub fn large(mut self, on: bool) -> Self {
self.large = on;
self
}
/// The strip takes files dragged from the operating system and reports them as `FilesDropped`.
#[must_use]
pub fn takes_files(mut self, on: bool) -> Self {
self.takes_files = on;
self
}
/// Host content before the tabs, at the reading start, as wide as it measures.
pub fn leading(mut self, area: impl FnOnce(&mut Ui) + 'a) -> Self {
self.leading = Some(Box::new(area));
@@ -159,7 +221,7 @@ impl<'a, D: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> Documen
/// Shows the group's strip.
pub fn show(self, ui: &mut Ui) -> DocumentTabsOutput<D> {
let DocumentTabs { label, tabs, selected, reorderable, tear_off, leading, trailing } = self;
let DocumentTabs { label, tabs, selected, reorderable, tear_off, leading, trailing, large: _, takes_files: _ } = self; // P3(canvas-widgets-w8): cw.C42
let source = keyed(tabs, |tab: &DocumentTab<D>| tab.id.clone()).with_text(|tab| Cow::Borrowed(tab.label.as_str()));
let mut strip = TabStrip::new(label).takes_drop(DropKind::new(DropPlace::Between, |_: &ListDrag<D>, _| true));
if tear_off {
+10
View File
@@ -99,6 +99,16 @@ impl TabKind {
self == Self::Document
}
/// Whether a drag resting over an unselected tab selects it.
pub const fn selects_under_drag(self) -> bool {
matches!(self, Self::Document)
}
/// Whether tabs draw a divider at their trailing edge, in every theme and density.
pub fn trailing_divider(self) -> bool {
self == Self::Document
}
/// Whether the strip draws a divider at each tab's trailing edge in a theme that divides rows.
pub fn compact_dividers(self) -> bool {
self == Self::Document
+15 -2
View File
@@ -269,7 +269,6 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + '
#[collection]
items: CollectionProps,
/// The kind of strip: its fit rule and overflow menu, and the kind its tabs take.
#[prop]
kind: TabKind,
/// The strip's taller form with the body type.
#[prop(flag)]
@@ -307,12 +306,26 @@ pub struct TabStrip<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + '
}
impl<'a, K: Clone + Eq + Hash + Send + Sync + std::fmt::Debug + 'static> TabStrip<'a, K> {
/// Sets the kind of strip: its fit rule and overflow menu, and the kind its tabs take. A strip of another kind than
/// `Document` does not select the tab a drag rests over.
#[must_use]
pub fn kind(mut self, kind: TabKind) -> Self {
self.kind = kind;
self.items = self.items.select_under_drag(kind.selects_under_drag());
self
}
/// A strip named `label` of document tabs.
pub fn new(label: impl Into<Label>) -> Self {
TabStrip {
common: Common::new(),
props: ContainerProps::new().sizing(Sizing::FillWidth),
items: CollectionProps::new().select(SelectMode::Single).pages(true).arrows_select(false).overflow(craft_behavior::Axis::X),
items: CollectionProps::new()
.select(SelectMode::Single)
.pages(true)
.arrows_select(false)
.overflow(craft_behavior::Axis::X)
.select_under_drag(true),
kind: TabKind::Document,
large: false,
shown: None,
+3 -1
View File
@@ -10,15 +10,17 @@ mod number;
mod selectable_text;
mod text_field;
mod words;
mod zoom_field;
pub use adorn::{Adornment, Placed, place, reserve};
pub use alt_text::{AltText, AltTextField, AltTextFieldStyle, AltTextWords};
pub use chips::{ChipCodec, ChipField, ChipFieldOutput, ChipFieldStyle, ChipWords, PartialChips};
pub use hex::{HexCodec, HexField};
pub use linked::{LinkMode, LinkedFields, LinkedFieldsStyle, LinkedLayout, LinkedOutput, LinkedWords, follow_equal, follow_ratio, link_toggle};
pub use number::{NamedOr, NumberField, NumberName, NumberOutput, NumberPick, NumberStepper, NumberStyle, NumberValue};
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 zoom_field::{InvalidZoom, ZoomField, ZoomFieldOutput};
use crate::contract::{Bind, EditResponse};
use crate::primitives::TextKey;
+10 -2
View File
@@ -33,7 +33,7 @@ mod value;
pub use rule::NumberStepper;
use rule::{Rule, Ruled, key_scale, round_to};
pub use value::{NamedOr, NumberName, NumberOutput, NumberPick, NumberValue};
pub use value::{NamedOr, NumberName, NumberOutput, NumberPick, NumberValue, RangeAlert};
/// The step of an arrow press, the wheel and a scrub when the field sets none.
const DEFAULT_STEP: f64 = 1.0;
@@ -210,6 +210,12 @@ impl<'a, V: NumberValue + 'static> NumberField<'a, V> {
self
}
/// Zoom typing: a Tab rewrites the draft and a press on the field's other parts keeps it unapplied.
#[allow(dead_code)] // P3(panels-w4): cw.C59
pub(super) fn zoom_typing(self) -> Self {
todo!("cw.C59")
}
/// A drag on the field's side label scrubs the value too, with or without the focus in the field.
#[must_use]
pub fn scrub_by_label(mut self) -> Self {
@@ -575,7 +581,9 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
NumberOutput {
edit: cx.edit_response(),
preset: self.picked,
typed_unit: cx.text(&text_part::<V>()).and_then(|outcome| outcome.committed_tag).and_then(UnitKind::from_tag),
typed_unit: cx.text(&text_part::<V>()).and_then(|outcome| outcome.committed).and_then(|note| note.unit).and_then(UnitKind::from_tag), // P3(panels-w4): pn.N1
out_of_range: None, // P3(panels-w4): pn.C22
cut: false, // P3(panels-w4): cw.C59
}
}
}
+6 -4
View File
@@ -3,7 +3,7 @@
use super::value::NumberValue;
use super::{DEFAULT_STEP, ON_GRID};
use craft_behavior::nav::{LARGE_STEPS, snap_to_step};
use craft_behavior::{Codec, MoveMods, NotAValue, NumberCodec, decimals_for_step};
use craft_behavior::{Codec, MoveMods, NotAValue, NumberCodec, ParseNote, decimals_for_step};
use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
@@ -166,17 +166,19 @@ impl<V: NumberValue> Codec for Ruled<V> {
self.parse_tagged(text, start).map(|(value, _)| value)
}
fn parse_tagged(&self, text: &str, start: &V) -> Result<(V, Option<u32>), NotAValue> {
fn parse_tagged(&self, text: &str, start: &V) -> Result<(V, ParseNote), NotAValue> {
// P3(panels-w4): cw.N5
if let Some(name) = self.name_of(text) {
return Ok((name, None));
return Ok((name, ParseNote::default()));
}
if text.trim().is_empty() && (self.mixed || V::blank().is_none()) {
return Err(NotAValue);
}
// P3(panels-w4): cw.N5 sets `held` when the number lies outside the rule's range.
let (read, tag) = self.inner.parse_tagged(text, &self.shown(start))?;
match read {
Some(number) => Ok((V::of_number(self.held(number) / self.scale), tag)),
None => V::blank().map(|blank| (blank, None)).ok_or(NotAValue),
None => V::blank().map(|blank| (blank, ParseNote::default())).ok_or(NotAValue),
}
}
+45 -2
View File
@@ -1,10 +1,10 @@
//! The values a number field holds and reports: NumberValue, NamedOr, NumberPick and NumberOutput.
use crate::contract::{EditResponse, Outcome};
use crate::runtime::env::UnitKind;
use crate::runtime::env::{Label, UnitKind};
use craft_behavior::Value;
use egui::Response;
use std::ops::Deref;
use std::ops::{Deref, RangeInclusive};
/// What a presets row picks: a number the field takes, or a choice that is not a number (Auto, Metrics) and
/// leaves the value alone.
@@ -33,6 +33,28 @@ pub trait NumberValue: Value {
fn from_name(id: u32) -> Option<Self>;
}
impl NumberValue for f32 {
fn number(&self) -> Option<f64> {
Some(f64::from(*self))
}
fn of_number(number: f64) -> Self {
number as f32
}
fn blank() -> Option<Self> {
None
}
fn named(&self) -> Option<u32> {
None
}
fn from_name(_: u32) -> Option<Self> {
None
}
}
impl NumberValue for Option<f64> {
fn number(&self) -> Option<f64> {
*self
@@ -112,6 +134,27 @@ pub struct NumberOutput<V: NumberValue = Option<f64>> {
/// text that named no unit, and in every other pass. The value still holds the number in the field's stored
/// unit.
pub typed_unit: Option<UnitKind>,
/// A typed value committed outside the range and was clamped, in the pass it committed (Enter, Tab, focus loss);
/// never for arrow, wheel, scrub or accessibility steps.
pub out_of_range: Option<RangeAlert>,
/// The committed text held more than the codec reads, in the pass it committed.
pub cut: bool,
}
/// A typed value the field clamped to its range, in shown units.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct RangeAlert {
/// The number typed.
pub typed: f64,
/// The value kept.
pub kept: f64,
/// The range the field holds values to.
pub range: RangeInclusive<f64>,
/// The field commits whole numbers.
pub whole: bool,
/// The unit the field shows after its number.
pub unit: Option<Label>,
}
impl<V: NumberValue> Deref for NumberOutput<V> {
+3 -3
View File
@@ -143,10 +143,10 @@ impl<'a, C: Codec + Clone + 'static> TextField<'a, C> {
self
}
/// The most characters the text holds.
/// The most characters the text holds; `None` clears the limit.
#[must_use]
pub fn limit(mut self, limit: usize) -> Self {
self.options.limit = Some(limit);
pub fn limit(mut self, limit: impl Into<Option<usize>>) -> Self {
self.options.limit = limit.into(); // P3(canvas-widgets-w11): cw.C61 adds the single-line default of 1024
self
}
+3
View File
@@ -7,5 +7,8 @@ craft_ui::words! {
presets: "textField.presets" = "Presets";
automatic: "textField.automatic" = "Auto";
slider: "textField.slider" = "Slider";
range_integer: template "textField.rangeInteger" = "An integer between {low} and {high} is required. Closest value inserted.";
range_value: template "textField.rangeValue" = "A value between {low} and {high} is required. Closest value inserted.";
range_number: template "textField.rangeNumber" = "A number between {low} and {high} is required. Closest value inserted.";
}
}
+92
View File
@@ -0,0 +1,92 @@
//! `ZoomField`: the one zoom field, a number field over a canvas view's zoom in percent.
use crate::contract::{NoValue, Outcome};
use crate::runtime::env::{Env, Label};
use craft_behavior::kurbo::Size;
use craft_behavior::{CanvasView, EditEvents};
use egui::{Response, Ui};
/// A zoom field: a `NumberField` over the view's device zoom in percent, with the zoom codec and the zoom ladder's
/// range. With no view it shows a disabled empty field. An edit writes the zoom about the view's centre; an empty
/// commit keeps the view.
#[derive(crate::contract::Pattern)]
pub struct ZoomField {
label: Label,
view: Option<CanvasView>,
document: Size,
stepper: bool,
scrub: bool,
enabled: bool,
}
impl ZoomField {
/// A zoom field named `label` over `view` (`None` when no view is known) of a document of `document` units.
pub fn new(label: impl Into<Label>, view: Option<CanvasView>, document: Size) -> Self {
ZoomField { label: label.into(), view, document, stepper: false, scrub: false, enabled: true }
}
/// The arrow keys and the wheel step along the zoom ladder.
#[must_use]
pub fn stepper(mut self, on: bool) -> Self {
self.stepper = on;
self
}
/// The caller's side label scrubs the zoom.
#[must_use]
pub fn scrub(mut self, on: bool) -> Self {
self.scrub = on;
self
}
/// Whether the field takes input; it is disabled anyway while there is no view.
#[must_use]
pub fn enabled(mut self, on: bool) -> Self {
self.enabled = on;
self
}
/// Shows the field and reports the view changes it made.
pub fn show(self, ui: &mut Ui) -> ZoomFieldOutput {
let _ = (&self.label, &self.view, self.document, self.stepper, self.scrub, self.enabled, ui);
todo!("cw.C59")
}
}
/// What a zoom field reports.
#[derive(Debug)]
#[non_exhaustive]
pub struct ZoomFieldOutput {
/// The field's response.
pub response: Response,
/// The view changes of this pass.
pub view: EditEvents<CanvasView>,
/// A typed zoom outside the ladder's range was clamped, in the pass it committed.
pub invalid_zoom: Option<InvalidZoom>,
}
impl Outcome for ZoomFieldOutput {
type Value = NoValue;
fn response(&self) -> &Response {
&self.response
}
}
/// The range a typed zoom missed, in percent.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct InvalidZoom {
/// The least zoom the field takes.
pub low: f64,
/// The greatest zoom the field takes.
pub high: f64,
}
impl InvalidZoom {
/// The message that says which zoom range the field takes, in the env's number format.
pub fn message(&self, env: &Env) -> String {
let _ = (self, env);
todo!("cw.C59")
}
}