mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 19:47:53 +00:00
Merge pull request #2091 from aiongg/picker-full
Colour picker: Photoshop's fixed Full arrangement, dialog buttons in a body slot
This commit is contained in:
@@ -39,8 +39,9 @@ pub struct ColorAreaStyle {
|
||||
/// The area keeps its axes right to left: across still grows to the right. Its value text names both components
|
||||
/// ("Saturation 40 %, Brightness 70 %", from [`names`](ColorArea::names)).
|
||||
///
|
||||
/// It is at least `size.plot` and fills the width its row leaves; with `Props::sizing(Sizing::Fill)` it takes the room
|
||||
/// on both axes, however small (the Color panel's field, as tall as its dock group leaves it).
|
||||
/// Its size comes from its [`shape`](ColorArea::shape), never from the room: the compact pickers' field at plot
|
||||
/// proportions, or the Color Picker dialog's square. With `Props::sizing(Sizing::Fill)` it takes the room on both axes
|
||||
/// instead, however small (the Color panel's field, as tall as its dock group leaves it).
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct ColorArea<'a> {
|
||||
#[common]
|
||||
@@ -56,12 +57,27 @@ pub struct ColorArea<'a> {
|
||||
/// The names of the across and down components in the value text; the model's channel names without them.
|
||||
#[prop]
|
||||
names: Option<[Label; 2]>,
|
||||
/// The size of an area that does not fill its room; plot proportions by default.
|
||||
#[prop]
|
||||
shape: AreaShape,
|
||||
}
|
||||
|
||||
/// The size of a [`ColorArea`] that does not fill its room.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum AreaShape {
|
||||
/// `size.plot.width` wide and `size.plot.height` tall: the field of the Color panel's popover and the compact
|
||||
/// pickers, wider than tall.
|
||||
#[default]
|
||||
Plot,
|
||||
/// A square `size.plot.width` on a side: the Color Picker dialog's field, as Photoshop's.
|
||||
Square,
|
||||
}
|
||||
|
||||
impl<'a> ColorArea<'a> {
|
||||
/// An area named `label` ("Saturation and brightness") showing `values`, values of `mode`'s model.
|
||||
pub fn new(label: impl Into<Label>, mode: AreaMode, values: Bind<'a, ModelValues>) -> Self {
|
||||
ColorArea { common: Common::new(), mode, values, quantize: None, names: None }.label(label).ltr_axis()
|
||||
ColorArea { common: Common::new(), mode, values, quantize: None, names: None, shape: AreaShape::Plot }.label(label).ltr_axis()
|
||||
}
|
||||
|
||||
/// The across and down channels of the mode's model.
|
||||
@@ -159,8 +175,11 @@ impl Component for ColorArea<'_> {
|
||||
_ => Vec2::splat(cx.tokens.size.plot.width),
|
||||
};
|
||||
}
|
||||
let mut picker = self.picker(cx.value(), false);
|
||||
cx.child("picker", &mut picker, cx.proposal)
|
||||
let plot = &cx.tokens.size.plot;
|
||||
match self.shape {
|
||||
AreaShape::Plot => Vec2::new(plot.width, plot.height),
|
||||
AreaShape::Square => Vec2::splat(plot.width),
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, ModelValues>> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `ColorArea`: a hue-mode area and a web-safe one.
|
||||
//! Stories of `ColorArea`: its two shapes, a web-safe area, a refused value and a disabled one.
|
||||
|
||||
use super::ColorArea;
|
||||
use super::{AreaShape, ColorArea};
|
||||
use crate::AreaMode;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, Validity};
|
||||
@@ -9,13 +9,21 @@ use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
|
||||
use craft_ui::value_drag::PointPicker;
|
||||
use egui::Ui;
|
||||
|
||||
/// The value changes through the drag of the point picker the area shows inside itself.
|
||||
/// The compact pickers' field at plot proportions. The value changes through the drag of the point picker the area
|
||||
/// shows inside itself.
|
||||
#[story(ColorArea<'static>, covers = [Default], drive = Drive::DragChild(Grip::new(PointPicker::WELL)))]
|
||||
fn color_area(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).show(ui).into()
|
||||
}
|
||||
|
||||
/// The Color Picker dialog's field: a square, `size.plot.width` on a side.
|
||||
#[story(ColorArea<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_area_square(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).shape(AreaShape::Square).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorArea<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_area_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8)));
|
||||
|
||||
@@ -0,0 +1,205 @@
|
||||
//! [`CompareSwatch`]: the Color Picker's compare block, the colour being edited over the colour it started from.
|
||||
|
||||
use craft_behavior::{Metrics, Mixed, PartKey, Sense};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Access, Common, Component, Cx, MeasureCx, Name, Outcome, PaintUi, PartsCx, Props as _, Role};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx, TypeRole};
|
||||
use egui::{CornerRadius, Rect, Response, Vec2, pos2};
|
||||
|
||||
use super::picker::ColorPickerWords;
|
||||
use super::warning::{ColorWarning, ColorWarningChip};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The style of a compare block: the size of the block and of each half, the edge round it and the gap between a
|
||||
/// caption and the block.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct CompareSwatchStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The focus ring of the current half.
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The block's width: `size.thumb.sample.md`.
|
||||
width: f32,
|
||||
/// Each half's height: `size.thumb.sample.sm`, so the block is taller than wide.
|
||||
half: f32,
|
||||
/// The one edge round the block.
|
||||
edge: StyleColor,
|
||||
/// Between a caption and the block, the block and the warnings column, and two warnings.
|
||||
gap: f32,
|
||||
/// The warnings column's width, and the side of a warning's icon and of its chip: `size.icon.sm`.
|
||||
warning: f32,
|
||||
}
|
||||
|
||||
/// What a [`CompareSwatch`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct CompareSwatchOutput {
|
||||
/// The block's response.
|
||||
pub response: Response,
|
||||
/// The current half was activated by click, Enter or Space: the host sets the current colour again.
|
||||
pub restore: bool,
|
||||
/// The index of the warning whose chip was activated: the host sets its nearest colour.
|
||||
pub warning: Option<usize>,
|
||||
}
|
||||
|
||||
impl Outcome for CompareSwatchOutput {
|
||||
type Value = craft_ui::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
craft_ui::testing::StoryOutput { id: Some(self.response.id), clicked: self.restore || self.warning.is_some(), ..Default::default() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Photoshop's compare block beside the Color Picker's field: one block of two touching halves inside one edge, the
|
||||
/// colour being edited (`new`) over the colour the picker started from (`current`), with the caption "new" above it
|
||||
/// and "current" under it. A translucent colour shows over the checkerboard; a mixed one shows the mixed face.
|
||||
///
|
||||
/// After the block stands its warnings column, `size.icon.sm` wide whether or not a warning shows, so a warning that
|
||||
/// appears moves nothing: each [`warning`](CompareSwatch::warnings) is a [`ColorWarningChip`] (its icon over its chip),
|
||||
/// the first level with the block's top.
|
||||
///
|
||||
/// - The new half is a picture: AccessKit names the block by its label ("New color") and gives the new colour's hex
|
||||
/// as its value.
|
||||
/// - The current half is a part of the block that is a button named "Restore current color", which is also its
|
||||
/// tooltip: a click, Enter or Space on it reports [`restore`](CompareSwatchOutput::restore), and the host sets the
|
||||
/// current colour again.
|
||||
#[must_use = "show the block with `show`"]
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct CompareSwatch<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
new: Mixed<Srgba>,
|
||||
current: Mixed<Srgba>,
|
||||
warnings: &'a [ColorWarning],
|
||||
restore: bool,
|
||||
warning: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a> CompareSwatch<'a> {
|
||||
/// A block named `label` ("New color", the new half's name) showing `new` over `current`.
|
||||
pub fn new(label: impl Into<Label>, new: impl Into<Mixed<Srgba>>, current: impl Into<Mixed<Srgba>>) -> Self {
|
||||
CompareSwatch { common: Common::new(), new: new.into(), current: current.into(), warnings: &[], restore: false, warning: None }.label(label)
|
||||
}
|
||||
|
||||
/// The warnings in the column after the block, top to bottom.
|
||||
pub fn warnings(mut self, warnings: &'a [ColorWarning]) -> Self {
|
||||
self.warnings = warnings;
|
||||
self
|
||||
}
|
||||
|
||||
/// The height of one caption line.
|
||||
fn caption_height(cx: &MeasureCx<'_, Self>, text: &str) -> f32 {
|
||||
cx.layout(&TextRun::new(text).role(TypeRole::Caption)).size().y
|
||||
}
|
||||
}
|
||||
|
||||
/// The current half: a button that restores the current colour.
|
||||
const CURRENT: PartKey = PartKey::new("current");
|
||||
|
||||
/// The height of each caption in a block of height `height`: the captions share what the halves leave evenly.
|
||||
fn caption_of(height: f32, style: &CompareSwatchStyle) -> f32 {
|
||||
((height - 2.0 * style.half) / 2.0 - style.gap).max(0.0)
|
||||
}
|
||||
|
||||
/// The block's rect and its two halves at the start of `rect`, under a caption `caption` high and the gap, in reading
|
||||
/// order (the caller mirrors them right to left).
|
||||
fn halves(rect: Rect, style: &CompareSwatchStyle, caption: f32) -> (Rect, Rect, Rect) {
|
||||
let top = rect.top() + caption + style.gap;
|
||||
let left = rect.left();
|
||||
let new = Rect::from_min_size(pos2(left, top), Vec2::new(style.width, style.half));
|
||||
let current = Rect::from_min_size(pos2(left, new.bottom()), Vec2::new(style.width, style.half));
|
||||
(new.union(current), new, current)
|
||||
}
|
||||
|
||||
impl Component for CompareSwatch<'_> {
|
||||
const ROLE: Role = Role::IMAGE;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = CompareSwatchStyle;
|
||||
type Output = CompareSwatchOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: CompareSwatchStyleKey) -> CompareSwatchStyle {
|
||||
let tokens = cx.tokens;
|
||||
CompareSwatchStyle {
|
||||
metrics: Metrics::new(),
|
||||
focus: cx.focus_look(),
|
||||
width: tokens.size.thumb.sample.md,
|
||||
half: tokens.size.thumb.sample.sm,
|
||||
edge: cx.color(tokens.color.line.control_edge),
|
||||
gap: tokens.space.gap.tight,
|
||||
warning: tokens.size.icon.sm,
|
||||
}
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let words = cx.env.words::<ColorPickerWords>();
|
||||
let caption = Self::caption_height(cx, words.new_caption.as_str()).max(Self::caption_height(cx, words.current_caption.as_str()));
|
||||
let style = cx.style;
|
||||
Vec2::new(style.width + style.gap + style.warning, 2.0 * (caption + style.gap + style.half))
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let restore = cx.env.words::<ColorPickerWords>().restore.as_str().to_owned();
|
||||
let flow = craft_behavior::Flow::new(rect, cx.flow.is_rtl());
|
||||
let (_, _, current) = halves(rect, cx.style, caption_of(rect.height(), cx.style));
|
||||
cx.part(CURRENT, flow.to_physical(current)).sense(Sense::CLICK | Sense::FOCUS).focusable().tooltip(restore);
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
self.restore = cx.part_activated(CURRENT).is_some();
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
if let Some(color) = self.new.same() {
|
||||
access.value(color.to_hex());
|
||||
}
|
||||
access.node(CURRENT, Role::BUTTON).name = Name::Text(cx.env.words::<ColorPickerWords>().restore.as_str().to_owned());
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let words = cx.env.words::<ColorPickerWords>();
|
||||
let style = cx.style;
|
||||
let caption = caption_of(cx.rect.height(), style);
|
||||
let flow = craft_behavior::Flow::new(cx.rect, cx.flow.is_rtl());
|
||||
let (block, new, current) = halves(cx.rect, style, caption);
|
||||
let caption_text = |text: &str| Text::new(Label::from(text.to_owned())).role(TypeRole::Caption).shade(Shade::Muted);
|
||||
let above = Rect::from_min_max(pos2(block.left(), cx.rect.top()), pos2(block.right(), block.top() - style.gap));
|
||||
let under = Rect::from_min_max(pos2(block.left(), block.bottom() + style.gap), pos2(block.right(), cx.rect.bottom()));
|
||||
let (block, new, current, above, under) =
|
||||
(flow.to_physical(block), flow.to_physical(new), flow.to_physical(current), flow.to_physical(above), flow.to_physical(under));
|
||||
let _ = ui.child("new_caption", above, caption_text(words.new_caption.as_str()));
|
||||
ui.draw().swatch_well(new, CornerRadius::ZERO, self.new.same().copied());
|
||||
ui.draw().swatch_well(current, CornerRadius::ZERO, self.current.same().copied());
|
||||
let _ = ui.child("current_caption", under, caption_text(words.current_caption.as_str()));
|
||||
ui.draw().stroke(&PaintShape::Rect(block, CornerRadius::ZERO), StrokeWidth::Thin, style.edge);
|
||||
// The warnings column: each chip its icon over its swatch, the first level with the block's top.
|
||||
let column = cx.rect.left() + style.width + style.gap;
|
||||
let tall = style.warning + style.gap + style.warning;
|
||||
for (at, warning) in self.warnings.iter().enumerate() {
|
||||
let top = block.top() + at as f32 * (tall + style.gap);
|
||||
let chip = flow.to_physical(Rect::from_min_size(pos2(column, top), Vec2::new(style.warning, tall)));
|
||||
if ui.child(("warning", at), chip, ColorWarningChip::new(warning)).clicked {
|
||||
self.warning = Some(at);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> CompareSwatchOutput {
|
||||
CompareSwatchOutput { response: cx.response.clone(), restore: self.restore, warning: self.warning }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! Stories of `CompareSwatch`: an opaque pair with both warnings, and a translucent pair.
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::CompareSwatch;
|
||||
use crate::ui::ColorWarning;
|
||||
|
||||
/// The colour being edited over the one the picker started from, with the out-of-gamut and web-colour warnings.
|
||||
#[story(CompareSwatch<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn compare_swatch(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let warnings = [
|
||||
ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9)),
|
||||
ColorWarning::web_colors("Not a web color", Srgba::rgb(1.0, 0.0, 0.8)),
|
||||
];
|
||||
CompareSwatch::new("New color", Srgba::rgb(1.0, 0.0, 1.0), Srgba::rgb(0.9, 0.2, 0.1)).warnings(&warnings).show(ui).into()
|
||||
}
|
||||
|
||||
/// Translucent colours over the checkerboard.
|
||||
#[story(CompareSwatch<'static>, covers = [], drive = Drive::Never)]
|
||||
fn compare_swatch_translucent(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let new = Srgba { r: 0.2, g: 0.5, b: 0.8, a: 0.5 };
|
||||
let current = Srgba { r: 0.9, g: 0.6, b: 0.1, a: 0.25 };
|
||||
CompareSwatch::new("New color", new, current).show(ui).into()
|
||||
}
|
||||
@@ -14,6 +14,7 @@
|
||||
mod area;
|
||||
mod channels;
|
||||
mod choice;
|
||||
mod compare;
|
||||
mod disc;
|
||||
mod droppers;
|
||||
mod eyedropper;
|
||||
@@ -41,12 +42,14 @@ mod swatches;
|
||||
/// The stories and trials this crate registers for the integration binary.
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub mod testing;
|
||||
mod warning;
|
||||
mod wheel;
|
||||
|
||||
pub use crate::AreaMode;
|
||||
pub use area::{ColorArea, ColorAreaStyle};
|
||||
pub use area::{AreaShape, ColorArea, ColorAreaStyle};
|
||||
pub use channels::finite_values;
|
||||
pub use choice::{ChosenColor, ColorChoice, ColorChoiceOutput, ColorChoiceWords, NamedColor};
|
||||
pub use compare::{CompareSwatch, CompareSwatchOutput, CompareSwatchStyle};
|
||||
pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscMove};
|
||||
pub use droppers::{DropperButton, DropperButtonOutput, DropperKind, DropperTool};
|
||||
pub use eyedropper::{
|
||||
@@ -69,10 +72,7 @@ pub use palette::{SwatchPalette, SwatchPaletteOutput};
|
||||
pub use panel::{
|
||||
ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelState, ColorPanelWords, PanelTarget,
|
||||
};
|
||||
pub use picker::{
|
||||
ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, ColorWarning, ColorWarningChip, ColorWarningChipOutput,
|
||||
PickedColor, ScreenPickGesture,
|
||||
};
|
||||
pub use picker::{ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, ScreenPickGesture};
|
||||
pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult};
|
||||
pub use popover::{ColorPopover, ColorPopoverOutput};
|
||||
pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords};
|
||||
@@ -89,6 +89,7 @@ pub use swatches::{
|
||||
MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchEdit, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput,
|
||||
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords, swatch_rows,
|
||||
};
|
||||
pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle};
|
||||
pub use wheel::{
|
||||
ColorWheel, ColorWheelStyle, ColorWheelWords, WheelGeometry, WheelPart, hue_at, hue_direction, triangle_corners, triangle_point, triangle_sv,
|
||||
};
|
||||
|
||||
@@ -24,8 +24,8 @@ use egui::{Response, Ui};
|
||||
use super::channels::finite_values;
|
||||
use super::picker::{ChannelRow, ChannelRule, ChannelUnit, channel_name};
|
||||
use super::{
|
||||
AreaMode, ColorArea, ColorPickerDialogWords, ColorRamp, ColorReadout, ColorStrip, ColorWarning, ColorWarningChip, ColorWheel, PairWell,
|
||||
PickedColor, RampKind, SwatchPair, Well,
|
||||
AreaMode, ColorArea, ColorPickerDialogWords, ColorRamp, ColorReadout, ColorStrip, ColorWarning, ColorWarningArrangement, ColorWarningChip,
|
||||
ColorWheel, PairWell, PickedColor, RampKind, SwatchPair, Well,
|
||||
};
|
||||
use crate::{CmykModel, GrayModel, not_web_safe};
|
||||
|
||||
@@ -621,7 +621,7 @@ impl Body<'_> {
|
||||
}
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
for warning in warnings.clone() {
|
||||
if ColorWarningChip::new(&warning).beside(true).show(ui).clicked {
|
||||
if ColorWarningChip::new(&warning).arrangement(ColorWarningArrangement::Beside).show(ui).clicked {
|
||||
let picked = PickedColor { color: warning.nearest().with_alpha(color.a), model: None };
|
||||
let name = self.words.title.as_str();
|
||||
self.push(self.target, EditEvent::set(Mixed::Same(PickedColor { color, model: None }), picked, name.into(), None));
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
//! The picker's body: the Compact layout, and the parts both layouts show (the area and strip, the hex field and the
|
||||
//! screen-pick button). The Full layout is in `full.rs`.
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::ColorModel;
|
||||
use craft_ui::contract::{Bind, Entry, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::contract::{Bind, Entry, Gap, LabelScheme, Props as _, Show as _, ShowContainer as _, Sizing};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
@@ -14,22 +14,19 @@ use egui::Ui;
|
||||
|
||||
use super::channel::{ChannelRow, ChannelRule, ChannelUnit, channel_name};
|
||||
use super::screen_pick::ScreenPickButton;
|
||||
use super::{Collected, ColorPickerLayout, ColorPickerWords, ColorWarning, Pass, PickedColor};
|
||||
use super::{Collected, ColorPickerLayout, ColorPickerWords, Pass};
|
||||
use crate::ui::channels::WEB_LEVELS;
|
||||
use crate::ui::{AreaMode, ColorArea, ColorStrip};
|
||||
use crate::ui::{AreaMode, AreaShape, ColorArea, ColorStrip, ColorWarning};
|
||||
|
||||
/// What the body shows.
|
||||
pub(super) struct Body<'a> {
|
||||
pub layout: ColorPickerLayout,
|
||||
pub models: Vec<&'a dyn ColorModel>,
|
||||
pub warnings: Vec<ColorWarning>,
|
||||
pub compare: Option<Mixed<PickedColor>>,
|
||||
pub alpha: bool,
|
||||
pub dynamic_tracks: bool,
|
||||
pub eyedropper: bool,
|
||||
pub eyedropper_busy: bool,
|
||||
/// Whether the host holds Only Web Colors, so the Full layout shows its check box.
|
||||
pub has_web_check: bool,
|
||||
}
|
||||
|
||||
impl<'a> Body<'a> {
|
||||
@@ -41,12 +38,13 @@ impl<'a> Body<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The area and strip over the channel rows of one model, the model switch, the hex row and the opacity row.
|
||||
/// The area at plot proportions and the strip, which set the width, over rows across it: the channel rows of one
|
||||
/// model, the opacity row, the model switch, and the hex row with the screen-pick button at its end.
|
||||
fn compact(&self, ui: &mut Ui, pass: &Pass<'a>, got: &mut Collected) {
|
||||
let words = Env::of(ui).words::<ColorPickerWords>();
|
||||
let model = self.models.iter().copied().find(|m| Some(m.id()) == pass.model);
|
||||
let visible: Vec<&dyn ColorModel> = model.into_iter().chain([pass.mode.model()]).collect();
|
||||
self.area_and_strip(ui, pass, &visible, got);
|
||||
self.area_and_strip(ui, pass, &visible, AreaShape::Plot, got);
|
||||
if let Some(model) = model {
|
||||
FieldGroup::new(words.channels.as_str().to_owned()).labels(LabelScheme::Inspector).show(ui, |ui, _| {
|
||||
let values = pass.shown.values_in(model);
|
||||
@@ -76,22 +74,24 @@ impl<'a> Body<'a> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
// The hex field at the row's start; the rest of the row puts the screen-pick button at its end.
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
Field::new(words.hex.as_str().to_owned()).side(HexField::hash_label()).show(ui, |ui, _| self.hex_field(ui, pass, &words, None, got));
|
||||
self.sample_button(ui, &words, got);
|
||||
Row::new().fill_width().align(RowAlign::End).show(ui, |ui, _| self.sample_button(ui, &words, got));
|
||||
});
|
||||
}
|
||||
|
||||
/// The area and the strip beside it, for the mode of the pass.
|
||||
pub(super) fn area_and_strip(&self, ui: &mut Ui, pass: &Pass<'a>, visible: &[&dyn ColorModel], got: &mut Collected) {
|
||||
/// The area in `shape` and the strip beside it, as tall as the area, for the mode of the pass.
|
||||
pub(super) fn area_and_strip(&self, ui: &mut Ui, pass: &Pass<'a>, visible: &[&dyn ColorModel], shape: AreaShape, got: &mut Collected) {
|
||||
let mode: AreaMode = pass.mode;
|
||||
let model = mode.model();
|
||||
let [across, down] = mode.area();
|
||||
let values = pass.shown.values_in(model);
|
||||
let levels = pass.rules.web.then_some(WEB_LEVELS);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Row::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
let mut area = ColorArea::new(Label::from(mode.name()), mode, Bind::given(values))
|
||||
.names([channel_name(model, across, visible), channel_name(model, down, visible)]);
|
||||
.names([channel_name(model, across, visible), channel_name(model, down, visible)])
|
||||
.shape(shape);
|
||||
let mut strip = ColorStrip::new(channel_name(model, mode.strip(), visible), mode, Bind::given(values));
|
||||
if let Some(levels) = levels {
|
||||
area = area.quantize(levels);
|
||||
@@ -119,7 +119,7 @@ impl<'a> Body<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The hex field, at `sizing` when given. The Full layout's first show focuses it.
|
||||
/// The hex field, at `sizing` when given. The picker's first show focuses it, its text selected.
|
||||
pub(super) fn hex_field(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, sizing: Option<Sizing>, got: &mut Collected) {
|
||||
let field =
|
||||
TextField::hex(words.hex.as_str().to_owned(), Bind::given(pass.shows(pass.shown.color.to_rgba()))).empty(pass.shown.color.to_rgba());
|
||||
|
||||
@@ -1,34 +1,25 @@
|
||||
//! The Full layout of `ColorPicker` (the Color Picker dialog), and the warnings beside its compare swatch.
|
||||
//! The Full layout of `ColorPicker`: the Color Picker dialog's fixed arrangement.
|
||||
|
||||
use craft_behavior::{ColumnWidth, IconId, Metrics, Mixed, NavShape, Sense};
|
||||
use craft_theme::{ColorModel, HsbModel, OklchModel, RgbModel, Srgba};
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup, Swatch};
|
||||
use craft_ui::contract::{
|
||||
Bind, Common, Component, Cx, FieldLayout, Gap, LabelKind, MeasureCx, Outcome, PaintUi, Props as _, Role, Show as _, ShowContainer as _,
|
||||
SideLabel, Sizing,
|
||||
};
|
||||
use craft_ui::display::{Icon, Shade, Text};
|
||||
use craft_behavior::{ColumnWidth, Mixed, NavShape};
|
||||
use craft_theme::{ColorModel, HsbModel, RgbModel};
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, FieldLayout, FooterSlot, Gap, GlyphLabel, LabelKind, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing};
|
||||
use craft_ui::display::{Shade, Text};
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::layout::{CellAlign, GridFit, RowAlign, empty_cell};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Env, Label, UnitKind};
|
||||
use craft_ui::style::{ComponentStyle, StyleCx, TypeRole};
|
||||
use craft_ui::text::{HexField, NumberField, UnitPlacement};
|
||||
use egui::{Rect, Response, Ui, Vec2};
|
||||
use egui::Ui;
|
||||
|
||||
use super::channel::{ChannelRule, ChannelUnit, channel_name};
|
||||
use super::compact::Body;
|
||||
use super::{Collected, ColorPicker, ColorPickerWords, Pass, PickedColor};
|
||||
use crate::ui::AreaMode;
|
||||
use crate::ui::{AreaMode, AreaShape, CompareSwatch};
|
||||
|
||||
/// A warning the host shows beside the Full picker's compare swatch, as the out-of-gamut and web-colour warnings of
|
||||
/// Photoshop's Color Picker: an icon over a chip of the nearest colour that passes. A click on it sets that colour;
|
||||
/// AccessKit and the tooltip name it by its tip.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ColorWarning {
|
||||
tip: Label,
|
||||
nearest: Srgba,
|
||||
icon: IconId,
|
||||
}
|
||||
/// Two columns that never stack: the two halves of the picker, the right half (compare block and actions over the two
|
||||
/// field groups), and each field group (the radio cell, then the channel's letter, field and unit).
|
||||
const TWO_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// The models the picker shows and the area modes it offers.
|
||||
#[derive(Clone, Copy)]
|
||||
@@ -38,232 +29,52 @@ struct ModelChoice<'m> {
|
||||
words: &'m ColorPickerWords,
|
||||
}
|
||||
|
||||
impl ColorWarning {
|
||||
/// A warning that says `tip` ("Out of gamut for printing") and offers `nearest`.
|
||||
pub fn new(tip: impl Into<Label>, nearest: Srgba) -> Self {
|
||||
ColorWarning { tip: tip.into(), nearest, icon: IconId::new("warning") }
|
||||
}
|
||||
|
||||
/// A warning that the colour is not a web-safe colour (the cube Photoshop's Color Picker shows), offering
|
||||
/// `nearest`, the nearest web colour.
|
||||
pub fn web_colors(tip: impl Into<Label>, nearest: Srgba) -> Self {
|
||||
Self::new(tip, nearest).icon(IconId::new("web_colors"))
|
||||
}
|
||||
|
||||
/// The colour that passes, nearest the warned one: what a click on the warning sets.
|
||||
pub fn nearest(&self) -> Srgba {
|
||||
self.nearest
|
||||
}
|
||||
|
||||
/// The icon over the chip.
|
||||
#[must_use]
|
||||
pub fn icon(mut self, icon: IconId) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a warning chip: the icon over the chip or beside it, and their sizes.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWarningChipStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
icon: f32,
|
||||
chip: f32,
|
||||
gap: f32,
|
||||
}
|
||||
|
||||
/// What a [`ColorWarningChip`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWarningChipOutput {
|
||||
/// The chip's response.
|
||||
pub response: Response,
|
||||
/// The chip was activated by click, Enter or Space: the host applies [`ColorWarning::nearest`].
|
||||
pub clicked: bool,
|
||||
}
|
||||
|
||||
impl Outcome for ColorWarningChipOutput {
|
||||
type Value = craft_ui::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ColorWarning`] as the Full picker draws it, for a host that draws it beside its own swatch: the warning's icon
|
||||
/// over a swatch of the nearest passing colour, or with [`beside`](ColorWarningChip::beside) the icon and a swatch of
|
||||
/// its size on one line, as Photoshop's Color panel shows it under the wells. The host applies
|
||||
/// [`ColorWarning::nearest`] when it is clicked. The tip is the tooltip and the accessible name.
|
||||
#[must_use = "show the chip with `show`"]
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct ColorWarningChip<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
warning: &'a ColorWarning,
|
||||
/// The icon and a swatch of the icon's size on one line, in place of the icon over a control-sized swatch.
|
||||
#[prop]
|
||||
beside: bool,
|
||||
clicked: bool,
|
||||
}
|
||||
|
||||
impl<'a> ColorWarningChip<'a> {
|
||||
/// A chip for `warning`.
|
||||
pub fn new(warning: &'a ColorWarning) -> Self {
|
||||
ColorWarningChip { common: Common::new(), warning, beside: false, clicked: false }.label(warning.tip.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorWarningChip<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorWarningChipStyle;
|
||||
type Output = ColorWarningChipOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorWarningChipStyleKey) -> ColorWarningChipStyle {
|
||||
ColorWarningChipStyle { metrics: Metrics::new(), icon: cx.tokens.size.icon.md, chip: cx.control().height, gap: cx.tokens.space.gap.tight }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let style = cx.style;
|
||||
if self.beside {
|
||||
return Vec2::new(style.icon + style.gap + style.icon, style.icon);
|
||||
}
|
||||
Vec2::new(style.icon.max(style.chip), style.icon + style.gap + style.chip)
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let style = cx.style;
|
||||
let flow = craft_behavior::Flow::new(cx.rect, cx.flow.is_rtl());
|
||||
let (icon, chip) = if self.beside {
|
||||
let side = Vec2::splat(style.icon);
|
||||
let icon = Rect::from_min_size(cx.rect.min, side);
|
||||
let chip = Rect::from_min_size(egui::pos2(cx.rect.min.x + style.icon + style.gap, cx.rect.min.y), side);
|
||||
(flow.to_physical(icon), flow.to_physical(chip))
|
||||
} else {
|
||||
let icon = Rect::from_center_size(egui::pos2(cx.rect.center().x, cx.rect.top() + style.icon / 2.0), Vec2::splat(style.icon));
|
||||
let chip = Rect::from_center_size(egui::pos2(cx.rect.center().x, cx.rect.bottom() - style.chip / 2.0), Vec2::splat(style.chip));
|
||||
(icon, chip)
|
||||
};
|
||||
let _ = ui.child("icon", icon, Icon::new(IconSpec::svg(self.warning.icon.clone())));
|
||||
let swatch = Swatch::new(self.warning.tip.clone(), self.warning.nearest).tooltip(self.warning.tip.clone());
|
||||
self.clicked = ui.child("chip", chip, swatch).clicked;
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorWarningChipOutput {
|
||||
ColorWarningChipOutput { response: cx.response.clone(), clicked: self.clicked }
|
||||
}
|
||||
}
|
||||
|
||||
/// The columns of one channel group: radio, letter, and the value cell (field and unit), each as wide as its content.
|
||||
const THREE_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// A grid column of the Full layout: HSB and RGB, then Lab and the host's models, then OKLCH.
|
||||
fn column_of(model: &dyn ColorModel) -> usize {
|
||||
match model.id() {
|
||||
id if id == HsbModel.id() || id == RgbModel.id() => 0,
|
||||
id if id == OklchModel.id() => 2,
|
||||
_ => 1,
|
||||
}
|
||||
/// Whether `model` stands in the first field group: HSB and RGB. Lab, OKLCH and the host's models stand in the second.
|
||||
fn in_first_group(model: &dyn ColorModel) -> bool {
|
||||
model.id() == HsbModel.id() || model.id() == RgbModel.id()
|
||||
}
|
||||
|
||||
impl<'a> Body<'a> {
|
||||
/// The Color Picker dialog: the area and strip over the check box, the opacity row and the screen-pick button;
|
||||
/// beside them the compare swatch and the warnings over the channel grid, where radios choose what the area shows.
|
||||
/// The Color Picker dialog, one arrangement in every room: the square area and the strip over Only Web Colors and
|
||||
/// the screen-pick button; beside them the compare block with its warnings and the actions cell (the dialog's
|
||||
/// buttons, empty outside a dialog), over the two field groups, where radios choose what the area shows.
|
||||
pub(super) fn full(&self, ui: &mut Ui, pass: &Pass<'a>, got: &mut Collected) {
|
||||
let words = Env::of(ui).words::<ColorPickerWords>();
|
||||
let visible: Vec<&dyn ColorModel> = self.models.iter().copied().chain([pass.mode.model()]).collect();
|
||||
Row::new().wrap(true).gap(Gap::Section).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
self.area_and_strip(ui, pass, &visible, got);
|
||||
if self.has_web_check {
|
||||
// The two halves in a grid that never stacks or squeezes, so each keeps its width in any room: the Only Web Colors
|
||||
// row spans the area and the strip, its button under the strip's end.
|
||||
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| {
|
||||
Stack::new().gap(Gap::Item).show(ui, |ui, _| {
|
||||
self.area_and_strip(ui, pass, &visible, AreaShape::Square, got);
|
||||
// The check box at the row's start; the rest of the row puts the screen-pick button at its end, under the
|
||||
// strip.
|
||||
Row::new().fill_width().show(ui, |ui, _| {
|
||||
let check = Checkbox::new(Bind::given(pass.web)).label(words.only_web_colors.as_str().to_owned()).show(ui);
|
||||
if let Some(on) = check.value() {
|
||||
got.web_pick = Some(*on);
|
||||
}
|
||||
}
|
||||
self.alpha_row(ui, pass, &words, got);
|
||||
self.sample_button(ui, &words, got);
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if self.compare.is_some() || !self.warnings.is_empty() {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
if let Some(current) = self.compare {
|
||||
self.compare_swatch(ui, pass, current, &words, got);
|
||||
}
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for warning in &self.warnings {
|
||||
if ColorWarningChip::new(warning).show(ui).clicked {
|
||||
got.clicks.push(PickedColor { color: warning.nearest, model: None });
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
self.grid(ui, pass, &visible, &words, got);
|
||||
Row::new().fill_width().align(RowAlign::End).show(ui, |ui, _| self.sample_button(ui, &words, got));
|
||||
});
|
||||
});
|
||||
self.right_half(ui, pass, &visible, &words, got);
|
||||
});
|
||||
}
|
||||
|
||||
/// The compare swatch: the colour being edited over the current one, with their captions; a click on the current
|
||||
/// half sets it.
|
||||
fn compare_swatch(&self, ui: &mut Ui, pass: &Pass<'a>, current: Mixed<PickedColor>, words: &ColorPickerWords, got: &mut Collected) {
|
||||
let caption = |text: &str| Text::new(text.to_owned()).role(TypeRole::Caption).shade(Shade::Muted);
|
||||
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
|
||||
caption(words.new_caption.as_str()).show(ui);
|
||||
Stack::new().gap(Gap::None).show(ui, |ui, _| {
|
||||
Swatch::new(words.new_color.as_str().to_owned(), pass.shows(pass.shown.color)).sizing(Sizing::FillWidth).show(ui);
|
||||
let restore = words.restore.as_str().to_owned();
|
||||
let shown = match current {
|
||||
Mixed::Same(current) => Mixed::Same(current.color),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
};
|
||||
if Swatch::new(restore.clone(), shown).tooltip(restore).sizing(Sizing::FillWidth).show(ui).clicked
|
||||
&& let Mixed::Same(current) = current
|
||||
{
|
||||
got.clicks.push(current);
|
||||
}
|
||||
});
|
||||
caption(words.current_caption.as_str()).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The channel grid: one column of fields per group of models, each column sharing its label column, with the
|
||||
/// radios of "Field shows" in front of the channels that choose an area mode, and the hex field under the first.
|
||||
fn grid(&self, ui: &mut Ui, pass: &Pass<'a>, visible: &[&dyn ColorModel], words: &ColorPickerWords, got: &mut Collected) {
|
||||
/// The compare block and the actions cell over the two field groups, in a grid whose columns never stack: the
|
||||
/// actions cell stands over the second group, and both groups start under the taller of the two cells. The radios
|
||||
/// of "Field shows" are one group across both.
|
||||
fn right_half(&self, ui: &mut Ui, pass: &Pass<'a>, visible: &[&dyn ColorModel], words: &ColorPickerWords, got: &mut Collected) {
|
||||
let offered = ColorPicker::offered(&self.models);
|
||||
let choice = ModelChoice { visible, offered: &offered, words };
|
||||
let (first, second): (Vec<&'a dyn ColorModel>, Vec<&'a dyn ColorModel>) = self.models.iter().copied().partition(|m| in_first_group(*m));
|
||||
let group = RadioGroup::new(words.field_shows.as_str().to_owned(), Bind::given(pass.mode)).nav(NavShape::Spatial);
|
||||
let picked = group
|
||||
.show(ui, |ui, _| {
|
||||
let columns: Vec<Vec<&'a dyn ColorModel>> = (0..3)
|
||||
.map(|column| self.models.iter().copied().filter(|m| column_of(*m) == column).collect::<Vec<_>>())
|
||||
.enumerate()
|
||||
.filter(|(column, models)| *column == 0 || !models.is_empty())
|
||||
.map(|(_, models)| models)
|
||||
.collect();
|
||||
// The groups sit side by side from the top; each is its own grid of radio, letter and value cells, so the
|
||||
// fields of a group share one x whether or not their row has a radio.
|
||||
Row::new().gap(Gap::Section).show(ui, |ui, _| {
|
||||
for (column, models) in columns.iter().enumerate() {
|
||||
Grid::new(THREE_COLUMNS).show(ui, |ui, _| {
|
||||
for model in models {
|
||||
self.model_fields(ui, pass, *model, ModelChoice { visible, offered: &offered, words }, got);
|
||||
}
|
||||
if column == 0 {
|
||||
Text::new(Label::from("")).show(ui);
|
||||
Text::new(Label::from(HexField::HASH)).shade(Shade::Muted).show(ui);
|
||||
self.hex_field(ui, pass, words, Some(Sizing::Content), got);
|
||||
Text::new(Label::from("")).show(ui);
|
||||
}
|
||||
});
|
||||
}
|
||||
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| {
|
||||
self.compare_block(ui, pass, words, got);
|
||||
let _ = FooterSlot::new().show(ui);
|
||||
self.field_group(ui, pass, &first, choice, true, got);
|
||||
self.field_group(ui, pass, &second, choice, false, got);
|
||||
});
|
||||
})
|
||||
.output;
|
||||
@@ -272,17 +83,54 @@ impl<'a> Body<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of one model's channels, three cells each: the radio that chooses the area mode (an empty cell where the
|
||||
/// channel offers none), the channel's letter and its number field. The radio's name stays its accessible name.
|
||||
fn model_fields(&self, ui: &mut Ui, pass: &Pass<'a>, model: &'a dyn ColorModel, choice: ModelChoice<'_>, got: &mut Collected) {
|
||||
/// The compare block, the colour being edited over the one the picker started from, with the warnings column after
|
||||
/// it; a click on the current half or on a warning sets that colour.
|
||||
fn compare_block(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, got: &mut Collected) {
|
||||
let current = match pass.compare {
|
||||
Mixed::Same(current) => Mixed::Same(current.color),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
};
|
||||
let shown = CompareSwatch::new(words.new_color.as_str().to_owned(), pass.shows(pass.shown.color), current).warnings(&self.warnings).show(ui);
|
||||
if shown.restore
|
||||
&& let Mixed::Same(current) = pass.compare
|
||||
{
|
||||
got.clicks.push(current);
|
||||
}
|
||||
if let Some(warning) = shown.warning.and_then(|at| self.warnings.get(at)) {
|
||||
got.clicks.push(PickedColor::rgb(warning.nearest()));
|
||||
}
|
||||
}
|
||||
|
||||
/// One field group: a grid of the radio cell and the channel cell (letter, field, unit), one row per channel of
|
||||
/// each of `models`, an empty row between two models, and in the first group the hex row: "#" in the radio column
|
||||
/// and the hex field, six digits wide, from the letter column on.
|
||||
fn field_group(&self, ui: &mut Ui, pass: &Pass<'a>, models: &[&'a dyn ColorModel], choice: ModelChoice<'_>, hex: bool, got: &mut Collected) {
|
||||
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).gap(Gap::Row).show(ui, |ui, _| {
|
||||
for (at, model) in models.iter().enumerate() {
|
||||
// An empty row stands between two models, as Photoshop's gap between HSB and RGB.
|
||||
if at > 0 {
|
||||
empty_cell(ui);
|
||||
empty_cell(ui);
|
||||
}
|
||||
self.model_rows(ui, pass, *model, choice, got);
|
||||
}
|
||||
if hex {
|
||||
Text::new(Label::from(HexField::HASH)).shade(Shade::Muted).show(ui);
|
||||
// Six digits wide from the letter column on; the content-sized row keeps it from stretching to the cell.
|
||||
Row::new().show(ui, |ui, _| self.hex_field(ui, pass, choice.words, Some(Sizing::Content), got));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The rows of one model's channels, two cells each: the radio that chooses the area mode (empty where the channel
|
||||
/// offers none), then the channel's number field with its letter before it and its unit after it. The radio's
|
||||
/// accessible name is the channel's name.
|
||||
fn model_rows(&self, ui: &mut Ui, pass: &Pass<'a>, model: &'a dyn ColorModel, choice: ModelChoice<'_>, got: &mut Collected) {
|
||||
let ModelChoice { visible, offered, words } = choice;
|
||||
let values = pass.shown.values_in(model);
|
||||
for (i, channel) in model.channels().iter().enumerate() {
|
||||
let name = channel_name(model, i, visible);
|
||||
let letter = words.grid_label.fill(&[("label", channel.label)]);
|
||||
let letter: &str = &letter;
|
||||
let mode = offered.iter().find(|mode| mode.model().id() == model.id() && mode.strip() == i).copied();
|
||||
match mode {
|
||||
match offered.iter().find(|mode| mode.model().id() == model.id() && mode.strip() == i).copied() {
|
||||
Some(mode) => {
|
||||
// A grid cell takes one child that is a component: the Row is the cell, the labelled radio its content.
|
||||
Row::new().show(ui, |ui, cx| {
|
||||
@@ -295,38 +143,50 @@ impl<'a> Body<'a> {
|
||||
);
|
||||
});
|
||||
}
|
||||
None => {
|
||||
Text::new(Label::from("")).show(ui);
|
||||
}
|
||||
None => empty_cell(ui),
|
||||
}
|
||||
Text::new(Label::from(letter.to_owned())).shade(Shade::Muted).show(ui);
|
||||
let letter = words.grid_label.fill(&[("label", channel.label)]);
|
||||
let letter: &str = &letter;
|
||||
let rule = ChannelRule::of(channel);
|
||||
let value = f64::from(values.values[i]);
|
||||
// The unit is the field's kind (typed units, decimals) and sits in its own cell after the field.
|
||||
let (kind, text) = match ChannelUnit::of(channel.unit) {
|
||||
// The unit is the field's kind (typed units, decimals) and its text stands after the field.
|
||||
let (kind, unit) = match ChannelUnit::of(channel.unit) {
|
||||
ChannelUnit::None => (None, None),
|
||||
ChannelUnit::Percent => (Some(UnitKind::Percent), Some(Env::of(ui).units().symbol(UnitKind::Percent))),
|
||||
ChannelUnit::Degrees => (Some(UnitKind::Degrees), Some(Env::of(ui).units().symbol(UnitKind::Degrees))),
|
||||
ChannelUnit::Text(text) => (None, Some(text.to_owned())),
|
||||
};
|
||||
let field = NumberField::new(name.clone(), Bind::given(pass.shows(Some(value))))
|
||||
.range(rule.range.clone())
|
||||
.step(rule.step)
|
||||
.snap_typed(true)
|
||||
.commit_decimals(usize::from(rule.decimals))
|
||||
.fixed_decimals(usize::from(rule.decimals))
|
||||
.unit_placement(UnitPlacement::After)
|
||||
.sizing(Sizing::Content);
|
||||
let field = match kind {
|
||||
Some(kind) => field.unit_kind(kind),
|
||||
None => field,
|
||||
};
|
||||
got.adopt(field.show(ui).edit, pass.shown, |v, mine| {
|
||||
if let Some(v) = v {
|
||||
*mine = mine.with_channel(model, i, *v, &pass.rules);
|
||||
// The letter is the field's glyph label, so the letters of a group share a column and the fields (one width
|
||||
// through the number fields' value column) start at one x, their units after them; the content-sized row
|
||||
// keeps the field from stretching to the cell, which the hex field spans.
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let side = SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(letter.to_owned()))));
|
||||
let edit = Field::new(name.clone()).side(side).sizing(Sizing::Content).show(ui, |ui, _| {
|
||||
let field = NumberField::new(name.clone(), Bind::given(pass.shows(Some(value))))
|
||||
.range(rule.range.clone())
|
||||
.step(rule.step)
|
||||
.snap_typed(true)
|
||||
.commit_decimals(usize::from(rule.decimals))
|
||||
.fixed_decimals(usize::from(rule.decimals))
|
||||
.unit_placement(UnitPlacement::After)
|
||||
.sizing(Sizing::Content);
|
||||
let field = match kind {
|
||||
Some(kind) => field.unit_kind(kind),
|
||||
None => field,
|
||||
};
|
||||
field.show(ui).edit
|
||||
});
|
||||
if let Some(unit) = &unit {
|
||||
Text::new(Label::from(unit.clone())).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
if let Some(edit) = edit.inner {
|
||||
got.adopt(edit, pass.shown, |v, mine| {
|
||||
if let Some(v) = v {
|
||||
*mine = mine.with_channel(model, i, *v, &pass.rules);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
Text::new(Label::from(text.unwrap_or_default())).shade(Shade::Muted).show(ui);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,9 +19,8 @@ use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::AreaMode;
|
||||
use super::{AreaMode, ColorWarning};
|
||||
pub(crate) use channel::{ChannelRow, ChannelRule, ChannelUnit, channel_name};
|
||||
pub use full::{ColorWarning, ColorWarningChip, ColorWarningChipOutput};
|
||||
pub use value::ColorConstraint;
|
||||
use value::Rules;
|
||||
|
||||
@@ -57,17 +56,19 @@ impl PickedColor {
|
||||
}
|
||||
}
|
||||
|
||||
/// How a [`ColorPicker`] lays out its parts.
|
||||
/// How a [`ColorPicker`] lays out its parts. Each layout has one arrangement, the same in every room, theme and
|
||||
/// density; the host's options choose what fills its cells, never where they stand.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPickerLayout {
|
||||
/// The Color panel and compact popup: the area over the channel slider rows of one model, a model switch, the hex
|
||||
/// row and the optional alpha row.
|
||||
/// The compact popup of a colour well (Photoshop's and Illustrator's Color panel in a popover): the area at plot
|
||||
/// proportions and the strip, which set the width, over the channel slider rows of one model, the opacity row, a
|
||||
/// model switch and the hex row with the screen-pick button at its end.
|
||||
#[default]
|
||||
Compact,
|
||||
/// The Color Picker dialog: the square area and the strip, the compare swatch and the host's warnings beside them
|
||||
/// over the channel grid, every model's channels at once with radios choosing what the area shows, and the hex
|
||||
/// field.
|
||||
/// The Color Picker dialog every app's "choose a colour" modal shows (Photoshop's): the square area and the strip
|
||||
/// over Only Web Colors; beside them the compare block with its warnings column and the actions cell (the dialog's
|
||||
/// buttons), over two field groups, every model's channels at once with radios choosing what the area shows.
|
||||
Full,
|
||||
}
|
||||
|
||||
@@ -161,7 +162,11 @@ struct Memo {
|
||||
model: Option<&'static str>,
|
||||
/// What the area and strip show while the host holds no mode.
|
||||
mode: AreaMode,
|
||||
/// The Full layout has taken the focus for the hex field.
|
||||
/// Only Web Colors while the host holds none.
|
||||
web: bool,
|
||||
/// The colour at the picker's first show: the compare block's current half when the host gives none.
|
||||
first: Option<PickedColor>,
|
||||
/// The picker has shown, and taken the focus for the hex field.
|
||||
opened: bool,
|
||||
/// The running gesture of a child and the colour when it began, for the `before` of its end.
|
||||
gesture: Option<(GestureId, PickedColor)>,
|
||||
@@ -219,9 +224,11 @@ struct Pass<'a> {
|
||||
mode: AreaMode,
|
||||
/// The model of the Compact rows.
|
||||
model: Option<&'static str>,
|
||||
/// Only Web Colors, as the host holds it.
|
||||
/// Only Web Colors, as the host or the picker holds it.
|
||||
web: bool,
|
||||
/// Whether the hex field takes the focus in this pass: the Full layout's first show.
|
||||
/// The compare block's current half: the host's colour, or the colour at the first show.
|
||||
compare: Mixed<PickedColor>,
|
||||
/// Whether the hex field takes the focus in this pass: the picker's first show.
|
||||
focus_hex: bool,
|
||||
}
|
||||
|
||||
@@ -233,26 +240,30 @@ impl Pass<'_> {
|
||||
}
|
||||
|
||||
/// A colour picker's body: a [`ColorArea`](super::ColorArea) and a [`ColorStrip`](super::ColorStrip), the channel
|
||||
/// fields of its [`ColorModel`]s, the hex field and the host's hooks, in the Color panel and compact popup layout
|
||||
/// ([`ColorPickerLayout::Compact`]) or the Color Picker dialog's ([`ColorPickerLayout::Full`]).
|
||||
/// fields of its [`ColorModel`]s, the hex field and the host's hooks, in the compact popup layout
|
||||
/// ([`ColorPickerLayout::Compact`]) or the Color Picker dialog's ([`ColorPickerLayout::Full`]). Every size comes from
|
||||
/// tokens and content, never from the room, so neither layout wraps, stacks or stretches.
|
||||
///
|
||||
/// - Compact: the area over the channel rows of one model (a label that scrubs, a slider whose track shows the
|
||||
/// channel's colours, a number field), a model switch, the hex row with the screen-pick button, and with
|
||||
/// [`alpha`](ColorPicker::alpha) an "Opacity" row over the checkerboard.
|
||||
/// - Full: the area square, the strip at its reading end, the opacity row and the screen-pick button under them.
|
||||
/// Beside them the [`compare`](ColorPicker::compare) swatch (new over current) and the host's
|
||||
/// [`warnings`](ColorPicker::warnings), over the channel grid: H S B, R G B, then "#" and the hex field; L a b and
|
||||
/// the host's models; OKLCH in a column of its own when the host turns it on. A radio before each built-in
|
||||
/// channel's label chooses the [`AreaMode`]; it edits no colour. The hex field takes the focus, its text selected,
|
||||
/// when the layout first shows ([`focus_on_open`](ColorPicker::focus_on_open)).
|
||||
/// - Compact: the area at plot proportions and the strip, then rows as wide as they are: the channel rows of one
|
||||
/// model (a label that scrubs, a slider whose track shows the channel's colours, a number field), with
|
||||
/// [`alpha`](ColorPicker::alpha) an "Opacity" row over the checkerboard, a model switch when there is more than one
|
||||
/// model, and the hex row with the screen-pick button at its end.
|
||||
/// - Full: the square area and the strip at its reading end, over Only Web Colors with the screen-pick button at the
|
||||
/// row's end. Beside them the [`CompareSwatch`](super::CompareSwatch) (new over current: the
|
||||
/// [`compare`](ColorPicker::compare) colour, else the colour at the first show) with the host's
|
||||
/// [`warnings`](ColorPicker::warnings) in its column, and the actions cell, a `FooterSlot` where a dialog that puts
|
||||
/// its buttons in its body (`ButtonPlace::Body`) shows them; under both the two field groups: H S B, R G B, then "#"
|
||||
/// and the hex field; L a b, OKLCH when the host offers it, and the host's other models (CMYK). A radio before a
|
||||
/// channel's letter chooses the [`AreaMode`]; it edits no colour. Full has no opacity row.
|
||||
/// - The hex field takes the focus, its text selected, when the picker first shows.
|
||||
/// - Edits: every child's gesture is the picker's, with the whole colour as its value: an area or strip drag, a slider
|
||||
/// drag, a scrub or a typing run is one Begin to Commit (or Cancel); keys, the wheel, Enter, a sample, a compare or
|
||||
/// warning click are `Set`s.
|
||||
/// - Kept components: the picker keeps the values the user last edited, in that model, while they still give the
|
||||
/// colour's 8-bit sRGB: greys keep their hue, black its hue and saturation, a typed Lab colour outside sRGB its
|
||||
/// values. [`PickedColor::model`] carries them, and the host's binding holds them between passes.
|
||||
/// - Only Web Colors ([`web_colors`](ColorPicker::web_colors)): every colour reported has each of red, green and blue
|
||||
/// on a multiple of 0x33, whichever child made it. The Full layout shows the check box.
|
||||
/// - Only Web Colors ([`web_colors`](ColorPicker::web_colors), else kept by the picker): every colour reported has each
|
||||
/// of red, green and blue on a multiple of 0x33, whichever child made it. The Full layout shows the check box.
|
||||
///
|
||||
/// AccessKit: a `Group` named by the label; channel fields and sliders are named by the channel's name ("Hue"), or
|
||||
/// `<model> <channel>` ("OKLCH hue") while another shown model has a channel of that name.
|
||||
@@ -268,14 +279,15 @@ pub struct ColorPicker<'a> {
|
||||
/// What the area and the strip show, held by the host; kept per picker without it.
|
||||
#[prop]
|
||||
mode: Option<Bind<'a, AreaMode>>,
|
||||
/// Only Web Colors, held by the host (kept across opens). The Full layout shows its check box; the Compact layout
|
||||
/// has none, the host sets it.
|
||||
/// Only Web Colors, held by the host (kept across opens); the picker keeps it itself without one. The Full layout
|
||||
/// shows its check box; the Compact layout has none, the host sets it.
|
||||
#[prop]
|
||||
web_colors: Option<Bind<'a, bool>>,
|
||||
/// Whether the picker edits the alpha: an "Opacity" row, and eight hex digits.
|
||||
/// Compact only: whether the picker edits the alpha, with an "Opacity" row and eight hex digits.
|
||||
#[prop]
|
||||
alpha: bool,
|
||||
/// Whether the channel sliders' tracks show the channel's colours with the others fixed (Dynamic Color Sliders).
|
||||
/// Compact only: whether the channel sliders' tracks show the channel's colours with the others fixed (the Color
|
||||
/// panel's Dynamic Color Sliders).
|
||||
#[prop]
|
||||
dynamic_tracks: bool,
|
||||
/// Shows the screen-pick button.
|
||||
@@ -284,8 +296,9 @@ pub struct ColorPicker<'a> {
|
||||
/// Disables the screen-pick button while the host samples.
|
||||
#[prop]
|
||||
eyedropper_busy: bool,
|
||||
/// The Full layout's compare swatch: the colour being edited over this one, the colour the host started from; a
|
||||
/// click on it sets it again, with the model values it carries.
|
||||
/// The Full layout's compare block: the colour being edited over this one, the colour the host started from; a
|
||||
/// click on it sets it again, with the model values it carries. Without it the block shows the colour at the
|
||||
/// picker's first show.
|
||||
#[prop(into)]
|
||||
compare: Option<Mixed<PickedColor>>,
|
||||
warnings: Vec<ColorWarning>,
|
||||
@@ -295,9 +308,6 @@ pub struct ColorPicker<'a> {
|
||||
/// The host's answer to a screen or canvas pick, for this pass; a `Set` that keeps the picker's alpha.
|
||||
#[prop]
|
||||
sampled: Option<Srgba>,
|
||||
/// Whether the Full layout focuses its hex field when it first shows; on by default.
|
||||
#[prop]
|
||||
focus_on_open: bool,
|
||||
}
|
||||
|
||||
impl<'a> ColorPicker<'a> {
|
||||
@@ -318,7 +328,6 @@ impl<'a> ColorPicker<'a> {
|
||||
warnings: Vec::new(),
|
||||
constrain: None,
|
||||
sampled: None,
|
||||
focus_on_open: true,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -345,8 +354,8 @@ impl<'a> ColorPicker<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The warnings beside the Full layout's compare swatch (out-of-gamut and web-colour warnings); a click on one
|
||||
/// sets its nearest passing colour. The host gives this pass's warnings for the colour it shows.
|
||||
/// The warnings in the column beside the Full layout's compare block (out-of-gamut and web-colour warnings); a
|
||||
/// click on one sets its nearest passing colour. The host gives this pass's warnings for the colour it shows.
|
||||
pub fn warnings(mut self, warnings: impl IntoIterator<Item = ColorWarning>) -> Self {
|
||||
self.warnings = warnings.into_iter().collect();
|
||||
self
|
||||
@@ -376,22 +385,11 @@ impl<'a> ColorPicker<'a> {
|
||||
warnings,
|
||||
constrain,
|
||||
sampled,
|
||||
focus_on_open,
|
||||
} = self;
|
||||
let full = layout == ColorPickerLayout::Full;
|
||||
let models: Vec<&'a dyn ColorModel> = models
|
||||
.unwrap_or_else(|| builtin_models().into_iter().filter(|m| if full { m.default_on().full } else { m.default_on().compact }).collect());
|
||||
let parts = compact::Body {
|
||||
layout,
|
||||
models: models.clone(),
|
||||
warnings,
|
||||
compare,
|
||||
alpha,
|
||||
dynamic_tracks,
|
||||
eyedropper,
|
||||
eyedropper_busy,
|
||||
has_web_check: web_colors.is_some(),
|
||||
};
|
||||
let parts = compact::Body { layout, models: models.clone(), warnings, alpha, dynamic_tracks, eyedropper, eyedropper_busy };
|
||||
let mut run = Run {
|
||||
name: Arc::from(label.as_str()),
|
||||
full,
|
||||
@@ -401,7 +399,7 @@ impl<'a> ColorPicker<'a> {
|
||||
web: web_colors.as_mut().map(|held| held.reborrow()),
|
||||
constrain,
|
||||
sampled,
|
||||
focus_on_open,
|
||||
compare,
|
||||
parts: &parts,
|
||||
latest: PickedColor::rgb(Srgba::BLACK),
|
||||
empty: false,
|
||||
@@ -425,7 +423,8 @@ struct Run<'s, 'a> {
|
||||
web: Option<BindMut<'s, bool>>,
|
||||
constrain: Option<ColorConstraint<'a>>,
|
||||
sampled: Option<Srgba>,
|
||||
focus_on_open: bool,
|
||||
/// The host's compare colour.
|
||||
compare: Option<Mixed<PickedColor>>,
|
||||
parts: &'s compact::Body<'a>,
|
||||
/// The colour after the edits landed so far.
|
||||
latest: PickedColor,
|
||||
@@ -440,7 +439,10 @@ impl<'a> Run<'_, 'a> {
|
||||
let memo = body.memory::<Memo>().clone();
|
||||
let held_mode = self.mode.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied());
|
||||
let mut mode = held_mode.unwrap_or(memo.mode);
|
||||
let held_web = self.web.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied()).unwrap_or(false);
|
||||
let held_web = match self.web.as_ref() {
|
||||
Some(held) => held.read(&mut *body).and_then(|held| held.same().copied()).unwrap_or(false),
|
||||
None => memo.web,
|
||||
};
|
||||
let rules = Rules { web: held_web, constrain: self.constrain.clone() };
|
||||
|
||||
// The Full layout shows a mode its models offer.
|
||||
@@ -455,14 +457,17 @@ impl<'a> Run<'_, 'a> {
|
||||
|
||||
let first_show = !memo.opened;
|
||||
let model = memo.model.filter(|id| self.models.iter().any(|m| m.id() == *id)).or_else(|| self.models.first().map(|m| m.id()));
|
||||
let focus_hex = first_show && body.resolved.enabled;
|
||||
let held = self.value.read(&mut *body).and_then(|held| held.same().copied());
|
||||
let first = if first_show { held } else { memo.first };
|
||||
{
|
||||
let memo = body.memory::<Memo>();
|
||||
memo.mode = mode;
|
||||
memo.model = model;
|
||||
memo.opened = true;
|
||||
memo.first = first;
|
||||
}
|
||||
let focus_hex = self.full && self.focus_on_open && first_show && body.resolved.enabled;
|
||||
let held = self.value.read(&mut *body).and_then(|held| held.same().copied());
|
||||
let compare = self.compare.unwrap_or_else(|| first.map_or(Mixed::Mixed, Mixed::Same));
|
||||
let empty = held.is_none();
|
||||
self.empty = empty;
|
||||
self.latest = held.unwrap_or(PickedColor::rgb(Srgba::BLACK));
|
||||
@@ -471,7 +476,7 @@ impl<'a> Run<'_, 'a> {
|
||||
self.set(body, next);
|
||||
}
|
||||
|
||||
let pass = Pass { shown: self.latest, empty, rules: rules.clone(), mode, model, web: held_web, focus_hex };
|
||||
let pass = Pass { shown: self.latest, empty, rules: rules.clone(), mode, model, web: held_web, compare, focus_hex };
|
||||
let mut got = Collected { empty, ..Collected::default() };
|
||||
self.parts.run(ui, &pass, &mut got);
|
||||
|
||||
@@ -486,9 +491,12 @@ impl<'a> Run<'_, 'a> {
|
||||
body.memory::<Memo>().mode = next;
|
||||
}
|
||||
if let Some(on) = got.web_pick.filter(|on| *on != held_web) {
|
||||
if let Some(held) = self.web.as_mut() {
|
||||
let event = EditEvent::set(Mixed::Same(held_web), on, Arc::from("Only Web Colors"), None);
|
||||
let _ = held.write(&mut *body, &event);
|
||||
match self.web.as_mut() {
|
||||
Some(held) => {
|
||||
let event = EditEvent::set(Mixed::Same(held_web), on, Arc::from("Only Web Colors"), None);
|
||||
let _ = held.write(&mut *body, &event);
|
||||
}
|
||||
None => body.memory::<Memo>().web = on,
|
||||
}
|
||||
if on {
|
||||
let snapped_rules = Rules { web: true, constrain: self.constrain.clone() };
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Stories of `ColorPicker` and `ColorWarningChip`: Compact with alpha, Compact with Only Web Colors, Full with the
|
||||
//! compare swatch and a warning, and Full with the host's CMYK model and OKLCH.
|
||||
//! Stories of `ColorPicker` and `ColorPickerDialog`: Compact, Compact with opacity, Compact with Only Web Colors, Full
|
||||
//! with Photoshop's models and both warnings, Full with an InDesign-like model set, and the dialog behind its button.
|
||||
|
||||
use craft_theme::{Channel, ColorModel, DefaultOn, HsbModel, LabModel, MAX_CHANNELS, ModelValues, OklchModel, RgbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
@@ -8,8 +8,9 @@ use egui::Ui;
|
||||
|
||||
use super::channel::{ChannelRow, ChannelRule, TrackRamp};
|
||||
use super::screen_pick::ScreenPickButton;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorWarning, ColorWarningChip, PickedColor};
|
||||
use crate::ui::AreaMode;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, PickedColor};
|
||||
use crate::ui::{AreaMode, ColorPickerDialog, ColorWarning};
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
|
||||
/// A naive CMYK in percent, without a working space: a host's model for the stories. A real host converts through its
|
||||
/// CMYK profile.
|
||||
@@ -67,13 +68,23 @@ fn start() -> PickedColor {
|
||||
PickedColor::rgb(Srgba::rgb(0.2, 0.5, 0.8))
|
||||
}
|
||||
|
||||
/// The compact popup's picker: the default models and the screen-pick button.
|
||||
#[story(ColorPicker<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_picker_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", start());
|
||||
let shown = ColorPicker::new("Foreground color", Bind::bound(color)).eyedropper(true).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
/// The compact picker with the opacity row.
|
||||
#[story(ColorPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_compact_alpha(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", start());
|
||||
let shown = ColorPicker::new("Foreground color", Bind::bound(color)).alpha(true).eyedropper(true).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
/// The compact picker with Only Web Colors on: the field and strip show flat cells of the web colours.
|
||||
#[story(ColorPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_web_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let web = *data.value("web", true);
|
||||
@@ -83,34 +94,42 @@ fn color_picker_web_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
/// Photoshop's Color Picker body: HSB, RGB, Lab and the host's CMYK, the compare block with both warnings, Only Web
|
||||
/// Colors and the screen-pick button; outside a dialog the actions cell is empty.
|
||||
#[story(ColorPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_full(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut mode = *data.value("mode", AreaMode::default());
|
||||
let current = Srgba::rgb(0.9, 0.2, 0.1);
|
||||
let color = data.value("color", PickedColor::rgb(Srgba::rgb(1.0, 0.0, 1.0)));
|
||||
let models: [&'static dyn ColorModel; 4] = [&HsbModel, &RgbModel, &LabModel, &CMYK_MODEL];
|
||||
let shown = ColorPicker::new("Foreground color", Bind::bound(color))
|
||||
.layout(ColorPickerLayout::Full)
|
||||
.models(models)
|
||||
.mode(Bind::bound(&mut mode))
|
||||
.compare(PickedColor::rgb(current))
|
||||
.warnings([ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9))])
|
||||
.warnings([
|
||||
ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9)),
|
||||
ColorWarning::web_colors("Not a web color", Srgba::rgb(1.0, 0.0, 0.8)),
|
||||
])
|
||||
.eyedropper(true)
|
||||
.show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
/// An InDesign-like model set: RGB in the first group; Lab, OKLCH (with its radios) and the host's CMYK in the second.
|
||||
#[story(ColorPicker<'static>, covers = [Many], drive = Drive::Never)]
|
||||
fn color_picker_full_models(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", start());
|
||||
let models: [&'static dyn ColorModel; 5] = [&HsbModel, &RgbModel, &LabModel, &CMYK_MODEL, &OklchModel];
|
||||
let shown = ColorPicker::new("Foreground color", Bind::bound(color)).layout(ColorPickerLayout::Full).models(models).alpha(true).show(ui);
|
||||
let models: [&'static dyn ColorModel; 4] = [&RgbModel, &LabModel, &OklchModel, &CMYK_MODEL];
|
||||
let shown = ColorPicker::new("Foreground color", Bind::bound(color)).layout(ColorPickerLayout::Full).models(models).show(ui);
|
||||
with_readout(data, shown)
|
||||
}
|
||||
|
||||
#[story(ColorWarningChip<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_warning_chip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
static WARNING: std::sync::LazyLock<ColorWarning> =
|
||||
std::sync::LazyLock::new(|| ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9)));
|
||||
ColorWarningChip::new(&WARNING).show(ui).into()
|
||||
/// The Color Picker dialog (`ColorPickerDialog`) behind its button: OK, Cancel and Add to Swatches stand in the
|
||||
/// picker's actions cell.
|
||||
#[story(ColorPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || ColorPickerDialog::foreground(Srgba::rgb(0.2, 0.5, 0.8)))
|
||||
}
|
||||
|
||||
#[story(ScreenPickButton, covers = [Default], drive = Drive::Never)]
|
||||
|
||||
@@ -16,7 +16,9 @@ use craft_host::target::Caps;
|
||||
use craft_settings::Remembered;
|
||||
use craft_theme::{ColorModel, Srgba, builtin_models};
|
||||
use craft_ui::contract::{Bind, CanvasGesture, Sampler as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field};
|
||||
use craft_ui::dialog::{
|
||||
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
|
||||
};
|
||||
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::Initial;
|
||||
@@ -79,9 +81,10 @@ enum Title {
|
||||
Given(Label),
|
||||
}
|
||||
|
||||
/// Photoshop's Color Picker dialog on the `DialogHost`: the Full `ColorPicker` with the compare swatch, the
|
||||
/// Photoshop's Color Picker dialog on the `DialogHost`: the Full `ColorPicker` with the compare block, the
|
||||
/// out-of-gamut and web-colour warnings, Only Web Colors and the eyedroppers, and OK, Cancel and Add to Swatches as the
|
||||
/// dialog's buttons.
|
||||
/// dialog's buttons, which stand in the picker's actions cell over its second field group (`ButtonPlace::Body`). The
|
||||
/// dialog takes the picker's size: one arrangement in every room.
|
||||
///
|
||||
/// - **Opening:** the hex field has the focus with its text selected, so typing replaces it. The field shows the
|
||||
/// component it showed last time and Only Web Colors is as it was left ([`ColorPickerMemory`]); with Only Web Colors
|
||||
@@ -203,7 +206,8 @@ impl ColorPickerDialog {
|
||||
self
|
||||
}
|
||||
|
||||
/// The compare swatch beside the field; on by default.
|
||||
/// Whether the compare block's current half shows the colour the dialog opened with; on by default. Off, it shows the
|
||||
/// colour at the picker's first show.
|
||||
#[must_use]
|
||||
pub fn compare(mut self, on: bool) -> ColorPickerDialog {
|
||||
self.compare = on;
|
||||
@@ -454,7 +458,7 @@ impl StackDialog for ColorPickerDialog {
|
||||
let shown = Dialog::new(title.clone())
|
||||
.opened(Bind::bound(open))
|
||||
.buttons(buttons)
|
||||
.side_buttons(true)
|
||||
.button_place(ButtonPlace::Body)
|
||||
.close_on_enter(true)
|
||||
.initial_focus(Initial::Keep)
|
||||
.roomy(true)
|
||||
@@ -488,8 +492,7 @@ impl StackDialog for ColorPickerDialog {
|
||||
.web_colors(Bind::bound(&mut memory.web_colors))
|
||||
.warnings(warnings)
|
||||
.eyedropper(screen)
|
||||
.eyedropper_busy(busy)
|
||||
.focus_on_open(true);
|
||||
.eyedropper_busy(busy);
|
||||
if let Some(sampled) = sampled {
|
||||
picker = picker.sampled(sampled);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, PickedColor, Scre
|
||||
mod stories;
|
||||
|
||||
/// The setup closure of the picker in the popover.
|
||||
type Setup<'a> = Box<dyn for<'b> FnOnce(ColorPicker<'b>) -> ColorPicker<'b> + 'a>;
|
||||
type Setup<'a> = Box<dyn for<'b> Fn(ColorPicker<'b>) -> ColorPicker<'b> + 'a>;
|
||||
|
||||
/// The popover's own state while its well is shown.
|
||||
#[derive(Clone, Default)]
|
||||
@@ -79,8 +79,8 @@ impl<'a> ColorPopover<'a> {
|
||||
}
|
||||
|
||||
/// Sets up the picker in the popover (alpha, eyedropper, constraint, models): `setup` gets the Compact picker the
|
||||
/// popover made.
|
||||
pub fn picker(mut self, setup: impl for<'b> FnOnce(ColorPicker<'b>) -> ColorPicker<'b> + 'a) -> Self {
|
||||
/// popover made, in each run of the popover's body, so the measuring run and the real run show the same picker.
|
||||
pub fn picker(mut self, setup: impl for<'b> Fn(ColorPicker<'b>) -> ColorPicker<'b> + 'a) -> Self {
|
||||
self.setup = Some(Box::new(setup));
|
||||
self
|
||||
}
|
||||
@@ -94,9 +94,9 @@ impl<'a> ColorPopover<'a> {
|
||||
|
||||
/// Shows the well and, while open, the popover.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorPopoverOutput {
|
||||
let ColorPopover { label, mut value, mut setup, anchor } = self;
|
||||
let ColorPopover { label, mut value, setup, anchor } = self;
|
||||
if let Some((opener, mut open)) = anchor {
|
||||
let (events, screen_pick, shown) = popover(ui, &label, &mut value, &mut setup, &opener, open.reborrowed());
|
||||
let (events, screen_pick, shown) = popover(ui, &label, &mut value, setup.as_ref(), &opener, open.reborrowed());
|
||||
return ColorPopoverOutput { response: opener, events, screen_pick, open: shown };
|
||||
}
|
||||
let shown = Stack::new().show(ui, |ui, cx| {
|
||||
@@ -106,7 +106,7 @@ impl<'a> ColorPopover<'a> {
|
||||
if well.clicked {
|
||||
state.open = !state.open;
|
||||
}
|
||||
let (events, screen_pick, open) = popover(ui, &label, &mut value, &mut setup, &well.response, Bind::bound(&mut state.open));
|
||||
let (events, screen_pick, open) = popover(ui, &label, &mut value, setup.as_ref(), &well.response, Bind::bound(&mut state.open));
|
||||
ColorPopoverOutput { response: well.response, events, screen_pick, open }
|
||||
});
|
||||
match shown.inner {
|
||||
@@ -121,13 +121,13 @@ fn popover(
|
||||
ui: &mut Ui,
|
||||
label: &Label,
|
||||
value: &mut Bind<'_, PickedColor>,
|
||||
setup: &mut Option<Setup<'_>>,
|
||||
setup: Option<&Setup<'_>>,
|
||||
opener: &Response,
|
||||
open: Bind<'_, bool>,
|
||||
) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>, bool) {
|
||||
let shown = Popover::new(label.clone(), open).opened_by(opener).show(ui, |ui, _| {
|
||||
let mut picker = compact_picker(label.clone(), value.reborrowed(), None).focus_on_open(true);
|
||||
if let Some(setup) = setup.take() {
|
||||
let mut picker = compact_picker(label.clone(), value.reborrowed(), None);
|
||||
if let Some(setup) = setup {
|
||||
picker = setup(picker);
|
||||
}
|
||||
picker.show(ui)
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
//! [`ColorWarning`] and [`ColorWarningChip`]: a warning about the colour shown beside a swatch (out of the printing
|
||||
//! gamut, not a web colour), with a chip of the nearest colour that passes.
|
||||
|
||||
use craft_behavior::{IconId, Metrics, Sense};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::Swatch;
|
||||
use craft_ui::contract::{Common, Component, Cx, MeasureCx, Outcome, PaintUi, Props as _, Role};
|
||||
use craft_ui::display::Icon;
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use egui::{Rect, Response, Vec2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// A warning the host shows beside a colour's swatch, as the out-of-gamut and web-colour warnings of Photoshop's Color
|
||||
/// Picker and Color panel: an icon and a chip of the nearest colour that passes. A click on it sets that colour;
|
||||
/// AccessKit and the tooltip name it by its tip.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ColorWarning {
|
||||
pub(crate) tip: Label,
|
||||
nearest: Srgba,
|
||||
icon: IconId,
|
||||
}
|
||||
|
||||
impl ColorWarning {
|
||||
/// A warning that says `tip` ("Out of gamut for printing") and offers `nearest`.
|
||||
pub fn new(tip: impl Into<Label>, nearest: Srgba) -> Self {
|
||||
ColorWarning { tip: tip.into(), nearest, icon: IconId::new("warning") }
|
||||
}
|
||||
|
||||
/// A warning that the colour is not a web-safe colour (the cube Photoshop's Color Picker shows), offering
|
||||
/// `nearest`, the nearest web colour.
|
||||
pub fn web_colors(tip: impl Into<Label>, nearest: Srgba) -> Self {
|
||||
Self::new(tip, nearest).icon(IconId::new("web_colors"))
|
||||
}
|
||||
|
||||
/// The colour that passes, nearest the warned one: what a click on the warning sets.
|
||||
pub fn nearest(&self) -> Srgba {
|
||||
self.nearest
|
||||
}
|
||||
|
||||
/// The icon with the chip.
|
||||
#[must_use]
|
||||
pub fn icon(mut self, icon: IconId) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// How a [`ColorWarningChip`] arranges its icon and its chip.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorWarningArrangement {
|
||||
/// The icon over the chip, both `size.icon.sm`: the column beside the Color Picker's compare swatch.
|
||||
#[default]
|
||||
Stacked,
|
||||
/// The icon (`size.icon.md`) and the chip (`size.icon.sm`) on one line: the Color panel, under its wells.
|
||||
Beside,
|
||||
}
|
||||
|
||||
/// The style of a warning chip: the sizes of its icon and chip, and the gap between them.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWarningChipStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
icon: f32,
|
||||
chip: f32,
|
||||
gap: f32,
|
||||
}
|
||||
|
||||
/// What a [`ColorWarningChip`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWarningChipOutput {
|
||||
/// The chip's response.
|
||||
pub response: Response,
|
||||
/// The chip was activated by click, Enter or Space: the host applies [`ColorWarning::nearest`].
|
||||
pub clicked: bool,
|
||||
}
|
||||
|
||||
impl Outcome for ColorWarningChipOutput {
|
||||
type Value = craft_ui::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ColorWarning`] as a picker or panel draws it beside its swatch: the warning's icon and a swatch of the nearest
|
||||
/// passing colour, in its [`arrangement`](ColorWarningChip::arrangement). The host applies [`ColorWarning::nearest`]
|
||||
/// when it is clicked. The tip is the tooltip and the accessible name.
|
||||
#[must_use = "show the chip with `show`"]
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct ColorWarningChip<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
warning: &'a ColorWarning,
|
||||
/// How the icon and the chip are arranged; the icon over the chip by default.
|
||||
#[style_key]
|
||||
#[prop]
|
||||
arrangement: ColorWarningArrangement,
|
||||
clicked: bool,
|
||||
}
|
||||
|
||||
impl<'a> ColorWarningChip<'a> {
|
||||
/// A chip for `warning`.
|
||||
pub fn new(warning: &'a ColorWarning) -> Self {
|
||||
ColorWarningChip { common: Common::new(), warning, arrangement: ColorWarningArrangement::Stacked, clicked: false }.label(warning.tip.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorWarningChip<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorWarningChipStyle;
|
||||
type Output = ColorWarningChipOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, key: ColorWarningChipStyleKey) -> ColorWarningChipStyle {
|
||||
let size = &cx.tokens.size.icon;
|
||||
let icon = match key.arrangement {
|
||||
ColorWarningArrangement::Stacked => size.sm,
|
||||
ColorWarningArrangement::Beside => size.md,
|
||||
};
|
||||
ColorWarningChipStyle { metrics: Metrics::new(), icon, chip: size.sm, gap: cx.tokens.space.gap.tight }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let style = cx.style;
|
||||
match self.arrangement {
|
||||
ColorWarningArrangement::Stacked => Vec2::new(style.icon.max(style.chip), style.icon + style.gap + style.chip),
|
||||
ColorWarningArrangement::Beside => Vec2::new(style.icon + style.gap + style.chip, style.icon.max(style.chip)),
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let style = cx.style;
|
||||
let flow = craft_behavior::Flow::new(cx.rect, cx.flow.is_rtl());
|
||||
let (icon, chip) = match self.arrangement {
|
||||
ColorWarningArrangement::Stacked => {
|
||||
let icon = Rect::from_center_size(egui::pos2(cx.rect.center().x, cx.rect.top() + style.icon / 2.0), Vec2::splat(style.icon));
|
||||
let chip = Rect::from_center_size(egui::pos2(cx.rect.center().x, cx.rect.bottom() - style.chip / 2.0), Vec2::splat(style.chip));
|
||||
(icon, chip)
|
||||
}
|
||||
ColorWarningArrangement::Beside => {
|
||||
let middle = cx.rect.center().y;
|
||||
let icon = Rect::from_min_size(egui::pos2(cx.rect.min.x, middle - style.icon / 2.0), Vec2::splat(style.icon));
|
||||
let chip =
|
||||
Rect::from_min_size(egui::pos2(cx.rect.min.x + style.icon + style.gap, middle - style.chip / 2.0), Vec2::splat(style.chip));
|
||||
(flow.to_physical(icon), flow.to_physical(chip))
|
||||
}
|
||||
};
|
||||
let _ = ui.child("icon", icon, Icon::new(IconSpec::svg(self.warning.icon.clone())));
|
||||
let swatch = Swatch::new(self.warning.tip.clone(), self.warning.nearest).tooltip(self.warning.tip.clone());
|
||||
self.clicked = ui.child("chip", chip, swatch).clicked;
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorWarningChipOutput {
|
||||
ColorWarningChipOutput { response: cx.response.clone(), clicked: self.clicked }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//! Stories of `ColorWarningChip`: its two arrangements.
|
||||
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Show as _;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{ColorWarning, ColorWarningArrangement, ColorWarningChip};
|
||||
|
||||
static WARNING: LazyLock<ColorWarning> = LazyLock::new(|| ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9)));
|
||||
|
||||
/// The icon over the chip, as the Color Picker's warnings column shows it.
|
||||
#[story(ColorWarningChip<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_warning_chip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
ColorWarningChip::new(&WARNING).show(ui).into()
|
||||
}
|
||||
|
||||
/// The icon beside the chip, as the Color panel shows it under its wells.
|
||||
#[story(ColorWarningChip<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_warning_chip_beside(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
ColorWarningChip::new(&WARNING).arrangement(ColorWarningArrangement::Beside).show(ui).into()
|
||||
}
|
||||
@@ -4,13 +4,15 @@ use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_color_ui::ui::{ColorPicker, ColorPickerDialog, ColorPickerLayout, ColorReadout, PickedColor};
|
||||
use craft_color_ui::ui::{ColorPicker, ColorPickerDialog, ColorPickerLayout, ColorPopover, ColorReadout, ColorWarning, PickedColor};
|
||||
use craft_host::{AppInfo, Host};
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Rgba, Srgba};
|
||||
use craft_ui::contract::{Bind, Role};
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, OklchModel, RgbModel, Rgba, Size, Srgba, ThemeId};
|
||||
use craft_ui::contract::{Bind, Role, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogHost, DialogResult, dialog_id};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, vec2};
|
||||
use egui::{Key, Modifiers, Rect, vec2};
|
||||
|
||||
fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
|
||||
let field = fixture.by_label(label).unwrap_or_else(|| panic!("the picker shows a {label} field"));
|
||||
@@ -118,46 +120,265 @@ fn a_dialog_reopened_keeps_only_web_colors_and_recalls_the_values_kept_on_ok() {
|
||||
assert_eq!(edited(&dialogs), Some(values), "Reset returns the typed values");
|
||||
}
|
||||
|
||||
/// The Full picker lays its channels out as Photoshop's Color Picker does: a letter after each radio and no channel words,
|
||||
/// the number fields of a group at one x (the hex field, which has no radio, included), a unit after its field and
|
||||
/// outside it, and the second group (Lab, CMYK) starting on the first row of the first.
|
||||
#[trial]
|
||||
fn the_full_pickers_channel_rows_show_letters_and_align_their_fields() {
|
||||
let mut fixture = Fixture::new(|ui| {
|
||||
let models: [&dyn ColorModel; 3] = [&HsbModel, &RgbModel, &LabModel];
|
||||
/// The densities and themes every layout trial runs in: compact and comfortable, a Pro and a Studio theme.
|
||||
const LOOKS: [(Size, &str); 4] =
|
||||
[(Size::Compact, "craft.pro"), (Size::Comfortable, "craft.pro"), (Size::Compact, "craft.studio"), (Size::Comfortable, "craft.studio")];
|
||||
|
||||
/// Half a point: less than a pixel at any scale.
|
||||
const SLACK: f32 = 0.5;
|
||||
|
||||
fn near(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < SLACK
|
||||
}
|
||||
|
||||
fn overlap(a: Rect, b: Rect) -> bool {
|
||||
let both = a.intersect(b);
|
||||
both.width() > SLACK && both.height() > SLACK
|
||||
}
|
||||
|
||||
/// The rect of every node named `name` together: a warning chip and its swatch share the warning's tip, so this is the
|
||||
/// whole chip, icon over swatch.
|
||||
fn named(fixture: &Fixture, name: &str) -> Rect {
|
||||
let tree = fixture.tree();
|
||||
let rects = tree.keys().into_iter().filter(|key| tree.name_of(*key) == Some(name)).filter_map(|key| tree.bounds_of(key));
|
||||
rects.reduce(Rect::union).unwrap_or_else(|| panic!("the picker shows {name}"))
|
||||
}
|
||||
|
||||
/// The Full picker's parts, as AccessKit and the painted text show them.
|
||||
#[derive(Debug, PartialEq)]
|
||||
struct FullParts {
|
||||
area: Rect,
|
||||
strip: Rect,
|
||||
/// The compare block with its captions and warnings column.
|
||||
block: Rect,
|
||||
/// The compare block's current half.
|
||||
current: Rect,
|
||||
new_caption: Rect,
|
||||
radios: Vec<Rect>,
|
||||
fields: Vec<Rect>,
|
||||
hex: Rect,
|
||||
hash: Rect,
|
||||
web: Rect,
|
||||
sample: Rect,
|
||||
warnings: Vec<Rect>,
|
||||
/// The unit texts ("°", "%").
|
||||
units: Vec<Rect>,
|
||||
}
|
||||
|
||||
impl FullParts {
|
||||
fn of(fixture: &Fixture, warnings: usize) -> FullParts {
|
||||
let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the picker shows {label}")).rect;
|
||||
let text = |text: &str| fixture.texts().iter().filter(|run| run.text == text).map(|run| run.rect).collect::<Vec<_>>();
|
||||
let area = rect("Saturation and brightness");
|
||||
// The area's point picker reports its two axes as sliders; the strip is the slider after the area.
|
||||
let strips: Vec<Rect> = fixture.by_role(Role::SLIDER).into_iter().map(|t| t.rect).filter(|r| r.left() >= area.right() - SLACK).collect();
|
||||
assert_eq!(strips.len(), 1, "one slider, the strip, stands after the area: {strips:?}");
|
||||
let tips = ["Out of gamut for printing", "Not a web color"];
|
||||
FullParts {
|
||||
area,
|
||||
strip: strips[0],
|
||||
block: rect("New color"),
|
||||
current: rect("Restore current color"),
|
||||
new_caption: *text("new").first().expect("the new caption"),
|
||||
radios: fixture.by_role(Role::RADIO_BUTTON).into_iter().map(|t| t.rect).collect(),
|
||||
fields: fixture.by_role(Role::SPIN_BUTTON).into_iter().map(|t| t.rect).collect(),
|
||||
hex: rect("Hex color"),
|
||||
hash: *text("#").first().expect("the # before the hex field"),
|
||||
web: rect("Only Web Colors"),
|
||||
sample: rect("Sample color from the screen"),
|
||||
warnings: tips[..warnings].iter().map(|tip| named(fixture, tip)).collect(),
|
||||
units: [text("\u{b0}"), text("%")].concat(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Every part's rect, for the pairwise overlap check.
|
||||
fn all(&self) -> Vec<Rect> {
|
||||
let one = [self.area, self.strip, self.block, self.hex, self.hash, self.web, self.sample];
|
||||
one.into_iter().chain(self.radios.iter().copied()).chain(self.fields.iter().copied()).chain(self.units.iter().copied()).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Every part a Full picker shows, found by role and name without requiring any: what a narrow room leaves of it.
|
||||
fn fixture_parts(fixture: &Fixture) -> Vec<Rect> {
|
||||
let labelled = ["Saturation and brightness", "New color", "Hex color", "Only Web Colors", "Sample color from the screen"];
|
||||
let named = labelled.iter().filter_map(|label| fixture.by_label(label)).map(|t| t.rect);
|
||||
let roles = [Role::SLIDER, Role::RADIO_BUTTON, Role::SPIN_BUTTON].into_iter().flat_map(|role| fixture.by_role(role)).map(|t| t.rect);
|
||||
let texts = fixture.texts().iter().filter(|run| ["#", "\u{b0}", "%"].contains(&run.text.as_str())).map(|run| run.rect);
|
||||
let mut all: Vec<Rect> = named.chain(roles).chain(texts).collect();
|
||||
all.sort_by(|a, b| a.min.x.total_cmp(&b.min.x).then(a.min.y.total_cmp(&b.min.y)));
|
||||
all
|
||||
}
|
||||
|
||||
/// A Full picker with HSB, RGB, Lab and OKLCH in a room `width` wide, at `density` in `theme`, with the first
|
||||
/// `warnings` of the out-of-gamut and web-colour warnings.
|
||||
fn full_picker(width: f32, (density, theme): (Size, &str), warnings: usize) -> Fixture {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let models: [&dyn ColorModel; 4] = [&HsbModel, &RgbModel, &LabModel, &OklchModel];
|
||||
let mut color = PickedColor::rgb(Srgba::rgb(0.2, 0.4, 0.6));
|
||||
let _ = ColorPicker::new("Color", Bind::bound(&mut color)).layout(ColorPickerLayout::Full).models(models).show(ui);
|
||||
let all = [
|
||||
ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.2, 0.4, 0.5)),
|
||||
ColorWarning::web_colors("Not a web color", Srgba::rgb(0.2, 0.4, 0.6)),
|
||||
];
|
||||
let _ = ColorPicker::new("Color", Bind::bound(&mut color))
|
||||
.layout(ColorPickerLayout::Full)
|
||||
.models(models)
|
||||
.compare(PickedColor::rgb(Srgba::rgb(0.9, 0.2, 0.1)))
|
||||
.warnings(all.into_iter().take(warnings))
|
||||
.eyedropper(true)
|
||||
.show(ui);
|
||||
});
|
||||
fixture.room(vec2(900.0, 600.0));
|
||||
fixture.density(density).theme_id(ThemeId::parse(theme).expect("a theme id")).room(vec2(width, 700.0));
|
||||
fixture.settle();
|
||||
let texts = fixture.texts();
|
||||
for word in ["Hue", "Saturation", "Brightness", "Red", "Lightness"] {
|
||||
assert!(texts.iter().all(|run| run.text != word), "{word} is not shown beside its radio");
|
||||
fixture
|
||||
}
|
||||
|
||||
/// The Full picker has one arrangement, Photoshop's, in every room, density and theme: nothing wraps, stacks or
|
||||
/// stretches; the area is square with the strip beside it; the compare block's halves are one block taller than wide
|
||||
/// with its warnings column after it from its top; both field groups start under the compare block on one row; the
|
||||
/// fields of a group share x and width with their units after them; the "#" stands before the hex field in the radio
|
||||
/// column; Only Web Colors and the screen-pick button share the row under the area; and no two parts overlap.
|
||||
#[trial]
|
||||
fn the_full_picker_keeps_photoshops_arrangement_in_every_room_density_and_theme() {
|
||||
for look in LOOKS {
|
||||
let wide = full_picker(600.0, look, 2);
|
||||
let parts = FullParts::of(&wide, 2);
|
||||
the_arrangement_holds_in_other_rooms(look, &wide, &parts);
|
||||
the_area_strip_and_compare_block_stand_as_in_photoshop(look, &parts);
|
||||
the_field_groups_stand_under_the_compare_block(look, &parts);
|
||||
the_hex_field_and_the_rows_under_the_area_stand_as_in_photoshop(look, &parts);
|
||||
for (i, a) in parts.all().iter().enumerate() {
|
||||
for b in &parts.all()[i + 1..] {
|
||||
assert!(!overlap(*a, *b), "{look:?}: no two parts overlap: {a:?} {b:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
for letter in ["H:", "S:", "R:", "L:"] {
|
||||
assert!(texts.iter().any(|run| run.text == letter), "{letter} is shown");
|
||||
}
|
||||
assert_eq!(fixture.by_role(Role::RADIO_BUTTON).len(), 9, "every channel keeps its radio");
|
||||
let fields = fixture.by_role(Role::SPIN_BUTTON);
|
||||
assert_eq!(fields.len(), 9);
|
||||
// The groups are found by x, not by tree order: HSB and RGB fields share the first, Lab's the second.
|
||||
}
|
||||
|
||||
type Look = (Size, &'static str);
|
||||
|
||||
/// Wider and narrower rooms leave the arrangement alone, and the warnings move no other part.
|
||||
fn the_arrangement_holds_in_other_rooms(look: Look, wide: &Fixture, parts: &FullParts) {
|
||||
assert_eq!(&FullParts::of(&full_picker(1200.0, look, 2), 2), parts, "{look:?}: the same arrangement in a room 1200 wide");
|
||||
// A room narrower than the picker clips it: every part it shows stands where it stands in a wide room.
|
||||
let inside = |rects: Vec<Rect>| rects.into_iter().filter(|r| r.right() <= 320.0).collect::<Vec<_>>();
|
||||
let narrow = inside(fixture_parts(&full_picker(320.0, look, 2)));
|
||||
assert!(!narrow.is_empty(), "{look:?}: a narrow room shows the picker's start");
|
||||
assert_eq!(narrow, inside(fixture_parts(wide)), "{look:?}: the same arrangement in a room 320 wide, clipped");
|
||||
let without = FullParts::of(&full_picker(600.0, look, 0), 0);
|
||||
assert_eq!(&FullParts { warnings: parts.warnings.clone(), ..without }, parts, "{look:?}: the warnings move no other part");
|
||||
}
|
||||
|
||||
fn the_area_strip_and_compare_block_stand_as_in_photoshop(look: Look, parts: &FullParts) {
|
||||
let FullParts { area, strip, block, current, new_caption, ref fields, ref warnings, .. } = *parts;
|
||||
assert!(near(area.width(), area.height()), "{look:?}: the area is square: {area:?}");
|
||||
assert!(near(strip.top(), area.top()) && near(strip.height(), area.height()), "{look:?}: the strip is as tall as the area: {strip:?}");
|
||||
assert!(strip.left() >= area.right() - SLACK, "{look:?}: the strip stands after the area");
|
||||
|
||||
// The compare block: the current half is the lower of two halves of one block, wider than a control is high.
|
||||
let control = fields[0].height();
|
||||
assert!(current.width() > control, "{look:?}: the block is wider than one control: {current:?}");
|
||||
assert!(2.0 * current.height() > current.width(), "{look:?}: two halves make it taller than wide: {current:?}");
|
||||
assert!(near(block.top(), area.top()), "{look:?}: the new caption stands level with the area's top: {block:?} {area:?}");
|
||||
assert!(new_caption.bottom() <= current.top() - current.height() + SLACK, "{look:?}: the new caption is over the new half");
|
||||
let new_top = current.top() - current.height();
|
||||
assert!(near(warnings[0].top(), new_top), "{look:?}: the first warning is level with the block's top: {:?}", warnings[0]);
|
||||
assert!(warnings.iter().all(|w| w.left() >= current.right() - SLACK), "{look:?}: the warnings stand after the block");
|
||||
assert!(warnings[0].bottom() <= warnings[1].top() + SLACK, "{look:?}: one warning under the other");
|
||||
}
|
||||
|
||||
/// Two groups: HSB and RGB at one x, Lab and OKLCH at another, starting on one row under the compare block.
|
||||
fn the_field_groups_stand_under_the_compare_block(look: Look, parts: &FullParts) {
|
||||
let FullParts { current, ref fields, ref units, .. } = *parts;
|
||||
let mut starts: Vec<f32> = Vec::new();
|
||||
for field in &fields {
|
||||
if !starts.iter().any(|start| (start - field.rect.min.x).abs() < 0.5) {
|
||||
starts.push(field.rect.min.x);
|
||||
for field in fields {
|
||||
if !starts.iter().any(|start| near(*start, field.left())) {
|
||||
starts.push(field.left());
|
||||
}
|
||||
}
|
||||
starts.sort_by(f32::total_cmp);
|
||||
let rects: Vec<_> = fields.iter().map(|field| field.rect).collect();
|
||||
assert_eq!(starts.len(), 2, "the fields start in two groups: {rects:?}");
|
||||
let hex = fixture.by_label("Hex color").expect("the hex field");
|
||||
assert!((hex.rect.min.x - starts[0]).abs() < 0.5, "the hex field, which has no radio, starts in the first group: {:?}", hex.rect);
|
||||
let first = fields.iter().filter(|field| (field.rect.min.x - starts[0]).abs() < 0.5).map(|field| field.rect.min.y).fold(f32::MAX, f32::min);
|
||||
let second = fields.iter().filter(|field| (field.rect.min.x - starts[1]).abs() < 0.5).map(|field| field.rect.min.y).fold(f32::MAX, f32::min);
|
||||
assert!((first - second).abs() < 0.5, "the second group starts on the first group's first row: {first} against {second}");
|
||||
let widest = fields.iter().map(|field| field.rect.width()).fold(0.0_f32, f32::max);
|
||||
let hue = fields.iter().min_by(|a, b| a.rect.min.y.total_cmp(&b.rect.min.y).then(a.rect.min.x.total_cmp(&b.rect.min.x))).expect("the hue field");
|
||||
let degrees = texts.iter().find(|run| run.text == "\u{b0}").expect("the degree unit is shown as text");
|
||||
assert!(degrees.rect.min.x >= hue.rect.max.x - 0.5, "the unit sits after the field, outside it: {:?} against {:?}", degrees.rect, hue.rect);
|
||||
assert!(widest < starts[1] - starts[0], "the fields are short, not the width of the room");
|
||||
assert_eq!(starts.len(), 2, "{look:?}: the fields start in two groups: {fields:?}");
|
||||
let group = |at: usize| fields.iter().filter(|f| near(f.left(), starts[at])).copied().collect::<Vec<_>>();
|
||||
let (first, second) = (group(0), group(1));
|
||||
let top = |rects: &[Rect]| rects.iter().map(|r| r.top()).fold(f32::MAX, f32::min);
|
||||
assert!(near(top(&first), top(&second)), "{look:?}: the second group starts on the first group's first row");
|
||||
assert!(top(fields) >= current.bottom(), "{look:?}: the groups start under the compare block");
|
||||
for group in [&first, &second] {
|
||||
assert!(group.iter().all(|f| near(f.width(), group[0].width())), "{look:?}: a group's fields share a width: {group:?}");
|
||||
assert!(group[0].width() < parts.hex.width(), "{look:?}: the fields are narrower than the hex field");
|
||||
}
|
||||
for unit in units {
|
||||
assert!(
|
||||
fields.iter().any(|f| near(f.center().y, unit.center().y) && unit.left() >= f.right() - SLACK),
|
||||
"{look:?}: a unit stands after its field, outside it: {unit:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn the_hex_field_and_the_rows_under_the_area_stand_as_in_photoshop(look: Look, parts: &FullParts) {
|
||||
let FullParts { area, ref radios, ref fields, hex, hash, web, sample, .. } = *parts;
|
||||
let first_left = fields.iter().map(|f| f.left()).fold(f32::MAX, f32::min);
|
||||
let first_radio = radios.iter().map(|r| r.left()).fold(f32::MAX, f32::min);
|
||||
assert!(hash.left() >= first_radio - SLACK && hash.right() <= first_left, "{look:?}: the # stands in the radio column: {hash:?}");
|
||||
assert!(hex.left() > hash.right() && hex.left() < first_left, "{look:?}: the hex field starts in the letter column: {hex:?}");
|
||||
|
||||
assert!(web.top() >= area.bottom() && near(web.left(), area.left()), "{look:?}: Only Web Colors stands under the area at its start");
|
||||
assert!(sample.left() > web.right() && near(sample.center().y, web.center().y), "{look:?}: the screen-pick button ends Only Web Colors' row");
|
||||
}
|
||||
|
||||
/// The Color Picker dialog takes the picker's size, its buttons in the picker's actions cell over the second field
|
||||
/// group, no end column beside it: in Photoshop's proportions, about twice as wide as the area and one and a half
|
||||
/// times as tall.
|
||||
#[trial]
|
||||
fn the_color_picker_dialog_stands_its_buttons_over_the_second_group_in_photoshops_proportions() {
|
||||
for look in LOOKS {
|
||||
let dialogs = Rc::new(RefCell::new(DialogHost::new()));
|
||||
let shown = Rc::clone(&dialogs);
|
||||
let mut fixture = Fixture::new(move |ui| shown.borrow_mut().run(ui));
|
||||
fixture.density(look.0).theme_id(ThemeId::parse(look.1).expect("a theme id")).room(vec2(1200.0, 900.0));
|
||||
dialogs.borrow_mut().open(ColorPickerDialog::new("fill", "Fill", Srgba::rgb(0.2, 0.4, 0.6)));
|
||||
fixture.idle(6);
|
||||
let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("the dialog shows {label}")).rect;
|
||||
let dialog = fixture.by_role(Role::DIALOG).first().expect("the dialog").rect;
|
||||
let (area, ok, cancel, add) = (rect("Saturation and brightness"), rect("OK"), rect("Cancel"), rect("Add to Swatches"));
|
||||
let radios: Vec<Rect> = fixture.by_role(Role::RADIO_BUTTON).into_iter().map(|t| t.rect).collect();
|
||||
let fields: Vec<Rect> = fixture.by_role(Role::SPIN_BUTTON).into_iter().map(|t| t.rect).collect();
|
||||
let second = radios.iter().map(|r| r.left()).fold(f32::MIN, f32::max);
|
||||
assert!(ok.bottom() <= cancel.top() && cancel.bottom() <= add.top(), "{look:?}: OK, Cancel, then Add to Swatches");
|
||||
assert!(near(ok.left(), second), "{look:?}: the buttons start at the second group's edge: {ok:?} against {second}");
|
||||
assert!(fields.iter().all(|f| f.top() >= add.bottom()), "{look:?}: the groups start under the buttons");
|
||||
assert!(ok.right() <= dialog.right() && dialog.right() - ok.right() < ok.width(), "{look:?}: no button column stands beside the body");
|
||||
let wide = dialog.width() / area.width();
|
||||
let tall = dialog.height() / area.width();
|
||||
assert!((1.9..=2.3).contains(&wide), "{look:?}: the dialog is about twice as wide as the area: {wide}");
|
||||
assert!((1.4..=1.8).contains(&tall), "{look:?}: and about one and a half times as tall: {tall}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The Compact picker's width is set by the area and the strip, and its rows take that width; its popover is as wide
|
||||
/// wherever the well stands and whatever the room.
|
||||
#[trial]
|
||||
fn the_compact_picker_is_as_wide_as_its_area_and_strip_wherever_it_opens() {
|
||||
let span = |width: f32, align: RowAlign| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut color = PickedColor::rgb(Srgba::rgb(0.2, 0.4, 0.6));
|
||||
Row::new().fill_width().align(align).show(ui, |ui, _| {
|
||||
let _ = ColorPopover::new("Fill", Bind::bound(&mut color)).picker(|picker| picker.eyedropper(true)).show(ui);
|
||||
});
|
||||
});
|
||||
fixture.room(vec2(width, 700.0));
|
||||
fixture.settle();
|
||||
let well = fixture.by_label("Fill").expect("the well");
|
||||
fixture.click(&well).idle(4);
|
||||
let area = fixture.by_label("Saturation and brightness").expect("the popover's area").rect;
|
||||
let hex = fixture.by_label("Hex color").expect("the hex field").rect;
|
||||
let sample = fixture.by_label("Sample color from the screen").expect("the screen-pick button").rect;
|
||||
assert!(hex.left() >= area.left() - SLACK, "the hex row starts under the area");
|
||||
(area.size(), sample.right() - area.left())
|
||||
};
|
||||
let first = span(600.0, RowAlign::Start);
|
||||
for (width, align) in [(600.0, RowAlign::End), (1200.0, RowAlign::Start), (1200.0, RowAlign::End)] {
|
||||
assert_eq!(span(width, align), first, "the popover is as wide in a room {width} wide with the well at {align:?}");
|
||||
}
|
||||
assert!(first.0.x > first.0.y, "the compact area is wider than tall");
|
||||
assert!(first.1 > first.0.x, "the rows reach past the area, to the strip's end");
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use std::cell::Cell;
|
||||
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, BodyCx, Entry, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
@@ -126,7 +126,7 @@ impl StackDialog for ContourEditorDialog {
|
||||
.outer_gesture(true)
|
||||
.history(true)
|
||||
.extra_buttons(extras.iter().map(|(_, label)| FooterButton::new((*label).clone(), DialogRole::Other)))
|
||||
.shaped(|dialog| dialog.side_buttons(true))
|
||||
.shaped(|dialog| dialog.button_place(ButtonPlace::Side))
|
||||
.show(ui, |ui, _, draft| {
|
||||
FieldGroup::new(words.preset.clone()).show(ui, |ui, _| {
|
||||
Field::new(words.preset.clone()).show(ui, |ui, _| {
|
||||
|
||||
@@ -10,7 +10,7 @@ use craft_ui::choice::SwatchMetrics;
|
||||
use craft_ui::contract::{
|
||||
Bind, CanvasGesture, Common, Component, Cx, DisabledLook, Entry, MeasureCx, PaintUi, Props as _, Role, Sampler as _, Show as _,
|
||||
};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
use craft_ui::patterns::presets::{PresetRow, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
@@ -363,7 +363,7 @@ impl StackDialog for HostedLayerStyle {
|
||||
let shown = FormDialog::new(label.clone(), Bind::bound(&mut *draft))
|
||||
.opened(Bind::bound(open))
|
||||
.preview(Some(Bind::bound(&mut preview)))
|
||||
.side_buttons(true)
|
||||
.button_place(ButtonPlace::Side)
|
||||
.extra_buttons([FooterButton::new(new_style, DialogRole::Other)])
|
||||
.footer_extra(|ui| {
|
||||
if let (Some(paint), Some(draft)) = (preview_thumb.as_deref(), snapshot.as_ref()) {
|
||||
|
||||
@@ -18,7 +18,7 @@ use crate::ui::length::{DocUnit, length_field, shown};
|
||||
use craft_behavior::{Axis, EditEvent, Metrics, Mixed, NumberCodec};
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::{Bind, Common, Component, Cx, Entry, MeasureCx, PaintUi, Props as _, Role, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::form::{Field, FieldGroup, Help};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::primitives::TextRun;
|
||||
@@ -600,7 +600,7 @@ impl StackDialog for ParagraphDialog {
|
||||
FooterButton::new(words.tabs.clone(), DialogRole::Other),
|
||||
];
|
||||
let shown = Dialog::new(words.title.clone())
|
||||
.side_buttons(true)
|
||||
.button_place(ButtonPlace::Side)
|
||||
.buttons(buttons)
|
||||
.settle_buttons(|_, buttons| {
|
||||
for (at, button) in buttons.iter_mut().enumerate() {
|
||||
|
||||
@@ -6,7 +6,7 @@ use craft_behavior::{SelectionChange, keyed};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, CollectionEvent, Entry, Props as _, Show as _, ShowCollection as _, ShowContainer as _, Trigger, clicked};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::menu::Menu;
|
||||
use craft_ui::pickers::Select;
|
||||
@@ -249,7 +249,7 @@ impl StackDialog for FindReplaceDialog {
|
||||
buttons.push(FooterButton::new(words.close_button.clone(), DialogRole::Cancel));
|
||||
let close_at = buttons.len() - 1;
|
||||
|
||||
let shown = Dialog::new(words.title.clone()).modeless().side_buttons(true).buttons(buttons).show(ui, |ui, _| {
|
||||
let shown = Dialog::new(words.title.clone()).modeless().button_place(ButtonPlace::Side).buttons(buttons).show(ui, |ui, _| {
|
||||
if word {
|
||||
let tabs = [
|
||||
(FindTab::Find, words.find_tab.as_str().to_owned()),
|
||||
|
||||
@@ -6,7 +6,7 @@ use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{
|
||||
Bind, FieldLayout, NoValue, Outcome, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, SideLabel, Sizing,
|
||||
};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
@@ -347,13 +347,16 @@ impl HyperlinkDialog {
|
||||
if editing {
|
||||
buttons.push(FooterButton::new(words.remove.clone(), DialogRole::Destructive));
|
||||
}
|
||||
let dialog = Dialog::new(title).side_buttons(true).buttons(buttons).initial_focus(Initial::Default).opened(Bind::bound(open)).settle_buttons(
|
||||
|_, buttons| {
|
||||
let dialog = Dialog::new(title)
|
||||
.button_place(ButtonPlace::Side)
|
||||
.buttons(buttons)
|
||||
.initial_focus(Initial::Default)
|
||||
.opened(Bind::bound(open))
|
||||
.settle_buttons(|_, buttons| {
|
||||
if let Some(accept) = buttons.get_mut(OK) {
|
||||
accept.set_enabled(valid.get());
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
let given_ref = &*given;
|
||||
let shown = dialog.show(ui, |ui, _| {
|
||||
body(ui, given_ref, form, &words);
|
||||
|
||||
@@ -27,7 +27,7 @@ use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{
|
||||
Bind, CollectionEvent, NoValue, Outcome, Pad, Props as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _, Sizing,
|
||||
};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, Dialog, DialogId, DialogOutput, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::list::{List, ListRow};
|
||||
@@ -254,7 +254,7 @@ impl CheckSpellingDialog {
|
||||
];
|
||||
let buttons = std::iter::once(FooterButton::new(words.done.clone(), DialogRole::Accept))
|
||||
.chain(actions.iter().map(|(label, _)| FooterButton::new((*label).clone(), DialogRole::Other).stays_open(true).enabled(has_item)));
|
||||
let dialog = Dialog::new(words.title.clone()).side_buttons(true).buttons(buttons).opened(Bind::bound(open));
|
||||
let dialog = Dialog::new(words.title.clone()).button_place(ButtonPlace::Side).buttons(buttons).opened(Bind::bound(open));
|
||||
let shown = dialog.show(ui, |ui, _| {
|
||||
let word = item.as_ref().map_or_else(String::new, |i| i.word.clone());
|
||||
Field::new(words.not_in_dictionary.clone()).id_salt("word").show(ui, |ui, _| {
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use craft_ui::choice::{RadioGroup, Swatch};
|
||||
use craft_ui::contract::{Bind, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::patterns::form_dialogs::FormDialog;
|
||||
@@ -113,7 +113,7 @@ impl StackDialog for MarkerDialog {
|
||||
let shown = FormDialog::new(words.title.clone(), Bind::bound(&mut self.draft))
|
||||
.outer_gesture(true)
|
||||
.extra_buttons(extras.iter().map(|(_, label)| FooterButton::new((*label).clone(), DialogRole::Other)))
|
||||
.shaped(|dialog| dialog.side_buttons(true))
|
||||
.shaped(|dialog| dialog.button_place(ButtonPlace::Side))
|
||||
.show(ui, |ui, form, draft| {
|
||||
let timeline_words = Env::of(ui).words::<TimelineWords>();
|
||||
let palette = label_palette(&form.env);
|
||||
|
||||
@@ -4,8 +4,8 @@ use super::inherit::{BodyScope, register_instances};
|
||||
use super::open::open_now;
|
||||
use super::placement::{Placement, measure_layer, overlay_of, shown_placement};
|
||||
use super::regions::{
|
||||
LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_end, footer_rule_under, gap_of,
|
||||
header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
|
||||
LabelColumns, LabelsFound, RegionFrame, RegionSizes, Regions, RuleBands, end_full_height, footer_in_body, footer_in_end, footer_rule_under,
|
||||
gap_of, header_gap_of, label_extra_of, least_of, pad_of, paint_edge_rule, paint_rules, rect_of, shared_labels, shared_line,
|
||||
};
|
||||
use super::reorder::REORDER_BAND;
|
||||
use super::scroll::{
|
||||
@@ -25,7 +25,7 @@ use crate::runtime::access::scope;
|
||||
use crate::runtime::access::{self, Politeness, Role};
|
||||
use crate::runtime::commands;
|
||||
use crate::runtime::egui::{alloc, areas, child, repaint, response, style};
|
||||
use crate::runtime::env::{AppValues, ArenaId, ColumnSweep, Env, Installed, Message, RowLine};
|
||||
use crate::runtime::env::{AppValues, ArenaId, ColumnSweep, Env, FooterSlotOf, Installed, Message, RowLine};
|
||||
use crate::runtime::focus::FocusPolicy;
|
||||
use crate::runtime::memory::{MemoryStage, sub};
|
||||
use crate::runtime::motion::{Driver, Presence, spec};
|
||||
@@ -572,6 +572,10 @@ impl<C: Container> ShapeHooks<C> for BodyHooks<'_> {
|
||||
if !plan.real && plan.is_open && props.end.is_some() {
|
||||
self.end_step(comp, ui, cx, &mut plan);
|
||||
}
|
||||
// A footer the body places is measured before the body, as the end region is.
|
||||
if footer_in_body(&props) {
|
||||
self.footer_slot_step(comp, ui, cx, &mut plan);
|
||||
}
|
||||
// B2 label: the control gets the rect the label leaves; the label column adds to the container's extent.
|
||||
self.label_step(ui, env, cx, &mut plan);
|
||||
// B3 body, if open, under the body env; the gate is read after the header changed it.
|
||||
@@ -1097,8 +1101,9 @@ impl BodyHooks<'_> {
|
||||
});
|
||||
}
|
||||
// A footer in the end region is part of a column sized from its content: a fill-width child takes its
|
||||
// measured width there and shows across the column, so it never sets the column's width.
|
||||
if footer_in_end(props) {
|
||||
// measured width there and shows across the column, so it never sets the column's width. A footer the body
|
||||
// places shows across its slot the same way.
|
||||
if footer_in_end(props) || footer_in_body(props) {
|
||||
plan.footer_env = plan.region_env.derive_local(|scoped| scoped.content_column = true);
|
||||
}
|
||||
if plan.real {
|
||||
@@ -1198,10 +1203,16 @@ impl BodyHooks<'_> {
|
||||
let (room, content_column, scroll, beside, label_width) =
|
||||
(plan.room, plan.content_column, plan.scroll, plan.regions.beside, plan.label_extra.x);
|
||||
let first_body = plan.first.1;
|
||||
// The slot of a footer the body places takes the size the measuring run's footer took.
|
||||
let footer_slot = footer_in_body(props)
|
||||
.then(|| FooterSlotOf { owner: id, size: if real { self.measured_footer } else { self.footer_size.unwrap_or(Vec2::ZERO) } });
|
||||
plan.body_env = Some(plan.line_env.derive_local(|scoped| {
|
||||
self.scope_body(scoped, props, id, BodyScope { room, real, content_column, scroll, label_width, beside });
|
||||
scoped.inside_label = inside.map(|inside| inside as crate::runtime::env::Held);
|
||||
scoped.cell_fills = cell_fills;
|
||||
if footer_slot.is_some() {
|
||||
scoped.footer_slot = footer_slot;
|
||||
}
|
||||
// A scrolling body shows its first child wherever the view is: the container has no first line there.
|
||||
scoped.first_line = (!real && scroll.is_none()).then_some(first_body);
|
||||
}));
|
||||
@@ -1479,10 +1490,59 @@ impl BodyHooks<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// B4: the footer region.
|
||||
/// A footer the body places: a measuring run of an open body measures it before the body, in a content column of
|
||||
/// unbounded room, so it takes its content's size and the slot takes that; the real run takes the size from the
|
||||
/// measuring run's record and draws the footer in the slot after the body, in the footer step.
|
||||
fn footer_slot_step<C: Container>(&mut self, comp: &mut C, ui: &mut Ui, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) {
|
||||
if plan.real {
|
||||
crate::contract::footer_slot::clear(&plan.ctx, plan.id);
|
||||
return;
|
||||
}
|
||||
if !plan.is_open {
|
||||
return;
|
||||
}
|
||||
let at = Rect::from_min_size(plan.regions.body.min, Vec2::INFINITY);
|
||||
let mut footer_ui = plan.frame().region(ui, "footer", at);
|
||||
let share = plan.share(false);
|
||||
let mut bcx = BodyCx::new(
|
||||
plan.body_id,
|
||||
plan.region_env.view(),
|
||||
plan.resolved,
|
||||
at,
|
||||
&mut *cx.core.memory,
|
||||
&mut plan.open,
|
||||
plan.gate.as_mut(),
|
||||
Some(share),
|
||||
);
|
||||
let installed = Env::install_for(&footer_ui, plan.footer_env.clone());
|
||||
comp.footer(&mut footer_ui, &mut bcx);
|
||||
Env::restore(&plan.ctx, installed);
|
||||
plan.close = plan.close.or(bcx.close_requested());
|
||||
self.footer_size = Some(self.region_size(&footer_ui));
|
||||
}
|
||||
|
||||
/// B4: the footer region. A footer the body places is drawn at the slot the body showed, keeping the size it
|
||||
/// measured before the body: it stretched to its cell, not to the footer.
|
||||
fn footer_step<C: Container>(&mut self, comp: &mut C, ui: &mut Ui, env: &Env, cx: &mut Cx<'_, C>, plan: &mut BodyPlan<'_>) {
|
||||
let props = plan.props;
|
||||
let (mut footer_rect, offset) = self.place_footer(props, &mut plan.regions, plan.inner, plan.body_rect, plan.rtl);
|
||||
let in_body = footer_in_body(props);
|
||||
let slot = (in_body && plan.real).then(|| crate::contract::footer_slot::take(&plan.ctx, plan.id)).flatten();
|
||||
if in_body {
|
||||
debug_assert!(
|
||||
!(plan.real && plan.is_open) || slot.is_some(),
|
||||
"a container whose footer stands in its body (FooterPlace::Body) shows one FooterSlot in it"
|
||||
);
|
||||
if plan.real {
|
||||
self.footer_size = Some(self.measured_footer);
|
||||
}
|
||||
if slot.is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
let (mut footer_rect, offset) = match slot {
|
||||
Some(slot) => (slot, 0.0),
|
||||
None => self.place_footer(props, &mut plan.regions, plan.inner, plan.body_rect, plan.rtl),
|
||||
};
|
||||
// The region's size counts the rule's band, the gap and the inset (they are part of what the footer took), so
|
||||
// the content starts below the band and the gap and stays the inset away from the sides and the foot.
|
||||
let lead = props.footer.and_then(|footer| footer.gap).map_or(0.0, |gap| gap_of(&env.tokens, gap));
|
||||
@@ -1493,6 +1553,10 @@ impl BodyHooks<'_> {
|
||||
footer_rect.min.x += inset;
|
||||
footer_rect.max.x = (footer_rect.max.x - inset).max(footer_rect.min.x);
|
||||
let mut footer_ui = plan.frame().region(ui, "footer", footer_rect);
|
||||
// A footer in the body shows only where the body's view does.
|
||||
if let (Some(_), Some(view)) = (slot, self.view) {
|
||||
footer_ui.set_clip_rect(view.intersect(footer_ui.clip_rect()));
|
||||
}
|
||||
let share = plan.share(false);
|
||||
let mut bcx = BodyCx::new(
|
||||
plan.body_id,
|
||||
@@ -1517,7 +1581,9 @@ impl BodyHooks<'_> {
|
||||
took.y += lead + inset;
|
||||
}
|
||||
took.y += self.rules.footer;
|
||||
self.footer_size = Some(took);
|
||||
if slot.is_none() {
|
||||
self.footer_size = Some(took);
|
||||
}
|
||||
}
|
||||
|
||||
/// The open and gate state the regions left, the scroll bars, the surface at the final rect and the rules.
|
||||
|
||||
@@ -25,6 +25,12 @@ pub(super) fn footer_in_end(props: &ContainerProps) -> bool {
|
||||
props.end.is_some() && props.footer.is_some_and(|footer| footer.place.in_end())
|
||||
}
|
||||
|
||||
/// Whether the body places the footer (`FooterPlace::Body`): the footer takes no band, and its size is inside the
|
||||
/// body's.
|
||||
pub(super) fn footer_in_body(props: &ContainerProps) -> bool {
|
||||
props.footer.is_some_and(|footer| footer.place == FooterPlace::Body)
|
||||
}
|
||||
|
||||
/// Whether the end region takes the full height under the header: it asks to, or the footer sits in it.
|
||||
pub(super) fn end_full_height(props: &ContainerProps) -> bool {
|
||||
props.end.is_some_and(|end| end.full_height) || footer_in_end(props)
|
||||
@@ -354,7 +360,7 @@ impl<'b> BodyHooks<'b> {
|
||||
let inline = props.header.is_some_and(|header| header.inline);
|
||||
let (in_end, full) = (footer_in_end(props), end_full_height(props));
|
||||
let header_h = if props.header.is_some() { sizes.header.unwrap_or(Vec2::ZERO).y } else { 0.0 };
|
||||
let footer_h = if props.footer.is_some() { sizes.footer.y } else { 0.0 };
|
||||
let footer_h = if props.footer.is_some() && !footer_in_body(props) { sizes.footer.y } else { 0.0 };
|
||||
// A footer in the end region takes no band across the container: it stacks with the end region's content.
|
||||
let across_h = if in_end { 0.0 } else { footer_h };
|
||||
let end_h = sizes.end.map_or(0.0, |end| end.y) + if in_end { footer_h } else { 0.0 };
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use super::BodyHooks;
|
||||
use super::placement::overlay_of;
|
||||
use super::regions::{RegionSizes, end_full_height, footer_in_end};
|
||||
use super::regions::{RegionSizes, end_full_height, footer_in_body, footer_in_end};
|
||||
use super::scroll::scroll_of;
|
||||
use crate::contract::run::ShowAt;
|
||||
use crate::contract::{ContainerProps, Mount, PadEdges, ShellPane, Sizing};
|
||||
@@ -218,6 +218,8 @@ impl<'b> BodyHooks<'b> {
|
||||
/// stacks with its content; a full-height end region stands beside the body and the footer.
|
||||
pub(super) fn regions_size(&self, props: &ContainerProps, body: Vec2, header: Vec2, footer: Vec2, end: Vec2) -> Vec2 {
|
||||
let in_end = footer_in_end(props);
|
||||
// A footer the body places is inside the body's size.
|
||||
let footer = if footer_in_body(props) { Vec2::ZERO } else { footer };
|
||||
let end = if in_end { Vec2::new(end.x.max(footer.x), end.y + footer.y) } else { end };
|
||||
let across = if in_end { Vec2::ZERO } else { footer };
|
||||
let gap = |width: f32, gap: f32| if width > 0.0 { width + gap } else { 0.0 };
|
||||
|
||||
@@ -426,12 +426,17 @@ pub enum FooterPlace {
|
||||
EndBottom,
|
||||
/// At the top of the end region, above its content; otherwise as `EndBottom`.
|
||||
EndTop,
|
||||
/// In the body, at the cell where the body shows a [`FooterSlot`](crate::contract::FooterSlot): the footer takes no
|
||||
/// band of its own, and the slot is as large as the footer measured. The container still runs the footer, so its
|
||||
/// controls stay the container's (a dialog's buttons, their keys and their order); the body only chooses where
|
||||
/// they stand. The body shows exactly one slot.
|
||||
Body,
|
||||
}
|
||||
|
||||
impl FooterPlace {
|
||||
/// Whether the footer sits in the end region.
|
||||
pub const fn in_end(self) -> bool {
|
||||
!matches!(self, FooterPlace::Across)
|
||||
matches!(self, FooterPlace::EndBottom | FooterPlace::EndTop)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! `FooterSlot`: the cell where a container's body places the container's footer (`FooterPlace::Body`).
|
||||
|
||||
use crate::contract::{Common, Component, Cx, MeasureCx, Role};
|
||||
use crate::runtime::pass_state;
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
use craft_behavior::{Axis, Metrics, Sense};
|
||||
use egui::{Context, Id, IdMap, Rect, Response, Vec2};
|
||||
|
||||
/// The style of a footer slot: no look of its own.
|
||||
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct FooterSlotStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
/// The cell where a container whose footer stands in its body (`FooterPlace::Body`) draws that footer: a dialog's
|
||||
/// buttons in the cell its body's arrangement keeps for them, as the Color Picker keeps one above its second field
|
||||
/// group. The slot is as large as the footer measured and takes the width of its cell, so the footer spans the cell.
|
||||
/// The container runs the footer after the body and draws it at the slot, so the footer's controls, their keys and
|
||||
/// their order stay the container's. Under no such container the slot takes no room, so a component that offers the
|
||||
/// cell shows it whether or not a container fills it.
|
||||
#[derive(crate::contract::Component)]
|
||||
#[component(sample = FooterSlot::new)]
|
||||
pub struct FooterSlot {
|
||||
#[common]
|
||||
common: Common,
|
||||
}
|
||||
|
||||
impl FooterSlot {
|
||||
/// A slot for the footer of the container around it.
|
||||
pub fn new() -> Self {
|
||||
FooterSlot { common: Common::new() }
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for FooterSlot {
|
||||
fn default() -> Self {
|
||||
FooterSlot::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for FooterSlot {
|
||||
const ROLE: Role = Role::None;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = FooterSlotStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: FooterSlotStyleKey) -> FooterSlotStyle {
|
||||
FooterSlotStyle::default()
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
/// As wide as its cell: the footer spans it.
|
||||
fn fills(&self) -> Option<Axis> {
|
||||
Some(Axis::X)
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
cx.env.footer_slot().map_or(Vec2::ZERO, |slot| slot.size)
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
if let Some(slot) = cx.core.env.footer_slot()
|
||||
&& !crate::runtime::measure::active(&cx.core.ctx)
|
||||
{
|
||||
pass_state::with::<Slots, _>(&cx.core.ctx, |slots| slots.0.insert(slot.owner, cx.core.rect));
|
||||
}
|
||||
cx.core.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The rect the footer slot of each container whose footer its body places took in this run, by container.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Slots(IdMap<Rect>);
|
||||
|
||||
/// Forgets the slot of `owner` before its body runs, so the footer step reads only a slot this run placed.
|
||||
pub(crate) fn clear(ctx: &Context, owner: Id) {
|
||||
pass_state::with::<Slots, _>(ctx, |slots| slots.0.remove(&owner));
|
||||
}
|
||||
|
||||
/// The rect the body of `owner` placed its footer slot at in this run.
|
||||
pub(crate) fn take(ctx: &Context, owner: Id) -> Option<Rect> {
|
||||
pass_state::with::<Slots, _>(ctx, |slots| slots.0.remove(&owner))
|
||||
}
|
||||
@@ -7,6 +7,7 @@ mod cx;
|
||||
pub(crate) mod editor;
|
||||
mod entry;
|
||||
mod faces;
|
||||
pub(crate) mod footer_slot;
|
||||
pub mod ghost;
|
||||
mod group;
|
||||
mod held;
|
||||
@@ -72,10 +73,11 @@ pub use cx::{
|
||||
Accessible, Activation, BodyCx, Cx, CxCore, Edit, Focus, ItemCx, ItemOpener, MeasureCx, PartBuilder, PartsCx, Pointer, Styled, WordSetCx,
|
||||
};
|
||||
pub use entry::{Entry, step_stop, step_stops};
|
||||
#[doc(hidden)]
|
||||
pub use footer_slot::FooterSlot;
|
||||
pub use group::{GroupHandle, GroupKind, GroupState};
|
||||
pub use held::Held;
|
||||
pub use hosted::{Hosted, HostedKey, Hosting};
|
||||
#[doc(hidden)]
|
||||
pub use items::lead_position;
|
||||
#[doc(hidden)]
|
||||
pub use items::put_toggle_names;
|
||||
|
||||
@@ -32,9 +32,37 @@ pub enum BodyLayout {
|
||||
Grid {
|
||||
/// The width rule of each column.
|
||||
columns: Cow<'static, [ColumnWidth]>,
|
||||
/// What the grid does when its columns do not fit beside each other.
|
||||
fit: GridFit,
|
||||
/// Where a cell shorter than its row stands in it.
|
||||
cells: CellAlign,
|
||||
},
|
||||
}
|
||||
|
||||
/// Where a `Grid` sets a cell that is shorter than its row.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum CellAlign {
|
||||
/// In the row's middle: a form's label beside a taller control.
|
||||
#[default]
|
||||
Center,
|
||||
/// At the row's top: panels of different heights side by side whose first lines stand level (the Color Picker's
|
||||
/// field groups, its buttons beside its compare block).
|
||||
Top,
|
||||
}
|
||||
|
||||
/// What a `Grid` does when the least widths of its columns do not fit beside each other in its room.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum GridFit {
|
||||
/// The cells go one under another across the room, so no column is cut: a form that reflows in a narrow panel.
|
||||
#[default]
|
||||
Stack,
|
||||
/// The columns stay beside each other at their least widths and the grid overflows its room: a component whose
|
||||
/// arrangement is fixed (the Color Picker's channel groups), which a narrow room must not rearrange.
|
||||
Fixed,
|
||||
}
|
||||
|
||||
/// Where a `Row` places its block of children along the row.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
@@ -65,7 +93,23 @@ impl BodyLayout {
|
||||
|
||||
/// Children row-major over `columns`: a `'static` slice, or columns built in the pass.
|
||||
pub fn grid(columns: impl Into<Cow<'static, [ColumnWidth]>>) -> Self {
|
||||
BodyLayout::Grid { columns: columns.into() }
|
||||
BodyLayout::Grid { columns: columns.into(), fit: GridFit::Stack, cells: CellAlign::Center }
|
||||
}
|
||||
|
||||
/// A `Grid` with `fit`; any other layout is unchanged.
|
||||
pub fn fit(self, fit: GridFit) -> Self {
|
||||
match self {
|
||||
BodyLayout::Grid { columns, cells, .. } => BodyLayout::Grid { columns, fit, cells },
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Grid` with `cells`; any other layout is unchanged.
|
||||
pub fn cells(self, cells: CellAlign) -> Self {
|
||||
match self {
|
||||
BodyLayout::Grid { columns, fit, .. } => BodyLayout::Grid { columns, fit, cells },
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Row` that wraps; any other layout is unchanged.
|
||||
@@ -954,7 +998,7 @@ pub(crate) fn place_in_cell(ui: &mut Ui, size: Vec2, child: InFlow) -> Rect {
|
||||
Some(_) => (above, (rect.height() - above - size.y).max(0.0)),
|
||||
None => {
|
||||
let spare = (rect.height() - size.y).max(0.0);
|
||||
(spare / 2.0, spare / 2.0)
|
||||
if env.grid_top { (0.0, spare) } else { (spare / 2.0, spare / 2.0) }
|
||||
}
|
||||
};
|
||||
Rect::from_min_max(egui::pos2(rect.min.x, rect.min.y + above), egui::pos2(rect.max.x, rect.max.y - below))
|
||||
@@ -980,6 +1024,17 @@ pub(crate) fn take_in_flow(ui: &mut Ui, size: Vec2) -> (Rect, bool) {
|
||||
take_in(ui, Env::of(ui).grid, size)
|
||||
}
|
||||
|
||||
/// Leaves the next cell of the `Grid` body that encloses `ui` directly empty: the next child takes the cell after it.
|
||||
/// A row of a grid whose first column holds a control in some rows (a radio) leaves it empty in the others, so the
|
||||
/// cells after it stay in their columns. Outside a grid it does nothing.
|
||||
pub fn empty_cell(ui: &mut Ui) {
|
||||
let env = Env::of(ui);
|
||||
let grid = env.grid.filter(|body| pass_state::with::<Cursors, _>(ui.ctx(), |cursors| matches!(cursors.0.get(body), Some(Cursor::Grid(_)))));
|
||||
if grid.is_some() {
|
||||
take_in(ui, grid, Vec2::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
/// `take_in_flow`, with `grid` the body of `ui`'s env that places its children itself.
|
||||
fn take_in(ui: &mut Ui, grid: Option<Id>, size: Vec2) -> (Rect, bool) {
|
||||
let cell = grid.and_then(|body| pass_state::with::<Cursors, _>(ui.ctx(), |cursors| cursors.0.get_mut(&body).map(|cursor| cursor.cell(size))));
|
||||
@@ -1107,9 +1162,17 @@ const STACKED: &[ColumnWidth] = &[ColumnWidth::fill(1.0)];
|
||||
/// as a probe, every leaf at its least and no column bounded, which gives each column its least, and then once more:
|
||||
/// each column keeps at least its least, a `Content` column measuring in the room the others leave at theirs. When
|
||||
/// the leasts do not fit beside each other, that last sweep lays the cells out one under another across the room
|
||||
/// instead, so no column is cut. The real run places the cells from the widths, leasts and layout the measuring run
|
||||
/// recorded.
|
||||
fn run_grid<R>(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec2, mut body: impl FnMut(&mut Ui) -> R) -> R {
|
||||
/// instead, so no column is cut. A `GridFit::Fixed` grid sweeps its cells once at their own sizes in unbounded room,
|
||||
/// whatever the room and the probe, and overflows the room. The real run places the cells from the widths, leasts and
|
||||
/// layout the measuring run recorded.
|
||||
fn run_grid<R>(
|
||||
ui: &mut Ui,
|
||||
env: &Env,
|
||||
id: Id,
|
||||
(columns, fit, cells): (&[ColumnWidth], GridFit, CellAlign),
|
||||
gap: Vec2,
|
||||
mut body: impl FnMut(&mut Ui) -> R,
|
||||
) -> R {
|
||||
let ctx = ui.ctx().clone();
|
||||
let rtl = env.direction.is_rtl();
|
||||
let layout = child::column_layout(rtl);
|
||||
@@ -1121,7 +1184,13 @@ fn run_grid<R>(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec
|
||||
let cursor = make(Flow::new(ui.available_rect_before_wrap(), rtl));
|
||||
let count = columns.len();
|
||||
pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.insert(id, Cursor::Grid(cursor)));
|
||||
let installed = Env::install_for(ui, scoped.derive_local(|scoped| scoped.grid = Some(id)));
|
||||
let installed = Env::install_for(
|
||||
ui,
|
||||
scoped.derive_local(|scoped| {
|
||||
scoped.grid = Some(id);
|
||||
scoped.grid_top = cells == CellAlign::Top;
|
||||
}),
|
||||
);
|
||||
let (inner, unsettled) = ColumnGroup::grid(ui, id, count, seed, &mut body);
|
||||
Env::restore(&ctx, installed);
|
||||
let cursor = match pass_state::with::<Cursors, _>(&ctx, |cursors| cursors.0.remove(&id)) {
|
||||
@@ -1140,7 +1209,51 @@ fn run_grid<R>(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec
|
||||
let stacked = this_pass(&ctx, false, sub(id, "stacked")).is_some_and(|stacked| stacked.x > 0.0);
|
||||
let columns = if stacked { STACKED } else { columns };
|
||||
let last = measured_tracks(&ctx, false, id, columns.len());
|
||||
return child::block(ui, None, layout, |ui| sweep(ui, env, None, columns, &|flow| GridCursor::new(flow, columns, gap, &last)).0).0;
|
||||
// A fixed grid lays its cells out over a room at least as wide as its columns, whatever room it was given.
|
||||
let at = (fit == GridFit::Fixed).then(|| fixed_room(ui, &last.columns, gap.x, rtl));
|
||||
return child::block(ui, at, layout, |ui| sweep(ui, env, None, columns, &|flow| GridCursor::new(flow, columns, gap, &last)).0).0;
|
||||
}
|
||||
// A fixed grid's columns are its cells' own widths, never their leasts, also inside a parent's probe for its least:
|
||||
// a probe in unbounded room finds them, settled across the cells' column groups, and the grid lays its cells out
|
||||
// over a room at least that wide, so it neither stacks nor squeezes them and its least width is its width. The room
|
||||
// then clips or scrolls it.
|
||||
if fit == GridFit::Fixed {
|
||||
let natural = env.derive_local(|scoped| {
|
||||
scoped.unbounded.0 = true;
|
||||
scoped.least = false;
|
||||
});
|
||||
let mut probe = |ui: &mut Ui, seed: Option<Vec<Columns>>| {
|
||||
crate::contract::keeping_ids(&ctx, || {
|
||||
let found = layout_memory::probing(&ctx, || {
|
||||
let mut probe = laid_out_child(ui, layout);
|
||||
let (_, measured, _, unsettled) = sweep(&mut probe, &natural, seed, columns, &|flow| GridCursor::unbounded(flow, columns, gap));
|
||||
(measured.columns, unsettled)
|
||||
});
|
||||
(found, true)
|
||||
})
|
||||
};
|
||||
let (mut widths, settled) = probe(ui, None);
|
||||
if let Some(seed) = settled.clone() {
|
||||
widths = probe(ui, Some(seed)).0;
|
||||
}
|
||||
let at = fixed_room(ui, &widths, gap.x, rtl);
|
||||
let own = env.derive_local(|scoped| scoped.least = false);
|
||||
let last = GridMeasure::default().with_least(widths.clone());
|
||||
let (inner, measured, ..) =
|
||||
child::block(ui, Some(at), layout, |ui| sweep(ui, &own, settled, columns, &|flow| GridCursor::new(flow, columns, gap, &last))).0;
|
||||
let room = ui.available_rect_before_wrap().size();
|
||||
for (i, width) in measured.columns.iter().enumerate() {
|
||||
found(&ctx, true, column_id(id, i), room, Vec2::new(*width, 0.0));
|
||||
}
|
||||
for (i, width) in widths.iter().enumerate() {
|
||||
found(&ctx, true, least_id(id, i), room, Vec2::new(*width, 0.0));
|
||||
}
|
||||
for (i, height) in measured.rows.iter().enumerate() {
|
||||
found(&ctx, true, row_id(id, i), room, Vec2::new(0.0, *height));
|
||||
}
|
||||
found(&ctx, true, sub(id, "rows"), room, Vec2::new(measured.rows.len() as f32, 0.0));
|
||||
found(&ctx, true, sub(id, "stacked"), room, Vec2::ZERO);
|
||||
return inner;
|
||||
}
|
||||
// A measuring run under a body sized from its content gives each fill column the width its cells take, as a
|
||||
// content column: the room it would share is not the body's to claim.
|
||||
@@ -1223,6 +1336,18 @@ fn run_grid<R>(ui: &mut Ui, env: &Env, id: Id, columns: &[ColumnWidth], gap: Vec
|
||||
inner
|
||||
}
|
||||
|
||||
/// The room a fixed grid of columns `widths` lays its cells out over in `ui`: the room `ui` offers, widened to the
|
||||
/// columns and the gaps between them at the reading start.
|
||||
fn fixed_room(ui: &Ui, widths: &[f32], gap: f32, rtl: bool) -> Rect {
|
||||
let room = ui.available_rect_before_wrap();
|
||||
let width = room.width().max(widths.iter().sum::<f32>() + gap * widths.len().saturating_sub(1) as f32);
|
||||
if rtl {
|
||||
Rect::from_min_max(egui::pos2(room.max.x - width, room.min.y), room.max)
|
||||
} else {
|
||||
Rect::from_min_size(room.min, Vec2::new(width, room.height()))
|
||||
}
|
||||
}
|
||||
|
||||
/// What this pass's measuring run found under `id`. A measuring run itself reads nothing.
|
||||
fn this_pass(ctx: &egui::Context, sizing: bool, id: Id) -> Option<Vec2> {
|
||||
if sizing { None } else { layout_memory::measured(ctx, id).map(|found| found.took) }
|
||||
@@ -1349,7 +1474,7 @@ pub(crate) fn run_body_measured<R>(
|
||||
BodyLayout::Row { wrap: false, align: RowAlign::SpaceBetween } => run_spread_row(ui, env, &line, body),
|
||||
BodyLayout::Row { wrap: false, align: RowAlign::Start } => (run_start_row(ui, env, &line, body), None),
|
||||
BodyLayout::Row { wrap, align } => run_row(ui, env, &line, (*wrap, *align), body),
|
||||
BodyLayout::Grid { columns } => (run_grid(ui, env, id, columns, gap, body), None),
|
||||
BodyLayout::Grid { columns, fit, cells } => (run_grid(ui, env, id, (&columns[..], *fit, *cells), gap, body), None),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1389,6 +1514,7 @@ fn run_spread_row<R>(ui: &mut Ui, env: &Env, at: &RowIn, mut body: impl FnMut(&m
|
||||
ui,
|
||||
env.derive_local(|scoped| {
|
||||
scoped.grid = Some(id);
|
||||
scoped.grid_top = false;
|
||||
scoped.row_line = Some(line);
|
||||
scoped.first_line = None;
|
||||
}),
|
||||
|
||||
@@ -7,7 +7,7 @@ mod label;
|
||||
mod slot;
|
||||
|
||||
pub use arrange::{Placed, arrange};
|
||||
pub use body::{BodyLayout, RowAlign, ShrinkOrder, ShrinkUnit, shrink_widths};
|
||||
pub use body::{BodyLayout, CellAlign, GridFit, RowAlign, ShrinkOrder, ShrinkUnit, empty_cell, shrink_widths};
|
||||
pub use column_group::ColumnGroup;
|
||||
#[doc(hidden)]
|
||||
pub use column_group::ambient_width;
|
||||
|
||||
@@ -68,6 +68,13 @@ impl Deref for Env {
|
||||
}
|
||||
}
|
||||
|
||||
/// A container's footer that its body places (`FooterPlace::Body`): the container and the size the footer measured.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) struct FooterSlotOf {
|
||||
pub owner: Id,
|
||||
pub size: egui::Vec2,
|
||||
}
|
||||
|
||||
/// The values of an env.
|
||||
#[derive(Clone)]
|
||||
#[non_exhaustive]
|
||||
@@ -109,6 +116,8 @@ pub struct Scoped {
|
||||
pub transform: Option<CanvasTransform>,
|
||||
/// The `Grid` or spread `Row` body whose cursor places the children in flow.
|
||||
pub(crate) grid: Option<Id>,
|
||||
/// The `Grid` body of `grid` sets its cells at the top of their row (`CellAlign::Top`), not in its middle.
|
||||
pub(crate) grid_top: bool,
|
||||
/// The body that encloses the scope is a content-sized column: it takes its width from its widest child that is
|
||||
/// not fill-width, so a fill-width child takes the width the others settle on and never sets it. Such a column
|
||||
/// exists only where the width comes from content: under a content-sized mount, a row or a grid.
|
||||
@@ -127,6 +136,9 @@ pub struct Scoped {
|
||||
/// Where the first child the scope places in flow reports its first line: a container's header or body
|
||||
/// (`layout::FirstLines`). `None` in the children of a `Row` body, which reports its line itself.
|
||||
pub(crate) first_line: Option<Id>,
|
||||
/// The container whose footer stands in its body (`FooterPlace::Body`) and the size that footer measured: a
|
||||
/// `FooterSlot` shown under it takes that size and is where the footer is drawn.
|
||||
pub(crate) footer_slot: Option<FooterSlotOf>,
|
||||
/// The `Stack` or `Row` body that encloses the scope and the axis it runs along, when a child that fills that
|
||||
/// axis shares the room its siblings leave (set only where the body is given the axis).
|
||||
pub(crate) fill_body: Option<(Id, craft_behavior::Axis)>,
|
||||
@@ -353,12 +365,14 @@ impl Scoped {
|
||||
self.item_facts = None;
|
||||
self.ink = Ink::default();
|
||||
self.surface = SurfaceKind::Background;
|
||||
self.footer_slot = None;
|
||||
self.inherited_mut().values.set(InBar(false));
|
||||
}
|
||||
|
||||
/// Ends the layout room of the enclosing body: its flow grid and content column.
|
||||
pub(crate) fn start_room(&mut self) {
|
||||
self.grid = None;
|
||||
self.grid_top = false;
|
||||
self.content_column = false;
|
||||
self.given_column = false;
|
||||
self.content = (false, false);
|
||||
@@ -485,12 +499,14 @@ impl Env {
|
||||
roving: None,
|
||||
transform: None,
|
||||
grid: None,
|
||||
grid_top: false,
|
||||
content_column: false,
|
||||
given_column: false,
|
||||
content: (false, false),
|
||||
row_room: None,
|
||||
row_line: None,
|
||||
first_line: None,
|
||||
footer_slot: None,
|
||||
fill_body: None,
|
||||
fill_share: None,
|
||||
shrink: None,
|
||||
|
||||
+5
@@ -22,6 +22,11 @@ pub struct EnvView<'a> {
|
||||
}
|
||||
|
||||
impl<'a> EnvView<'a> {
|
||||
/// The footer a `FooterSlot` under this scope places, if a container offers one.
|
||||
pub(crate) fn footer_slot(&self) -> Option<super::FooterSlotOf> {
|
||||
self.scoped.footer_slot
|
||||
}
|
||||
|
||||
/// The height, icon side, padding, gap and field widths of a control of `size`.
|
||||
pub(crate) fn control(&self, size: craft_theme::ControlSize) -> craft_behavior::ControlMetrics {
|
||||
self.scoped.control(size)
|
||||
|
||||
@@ -96,6 +96,7 @@ pass_state! {
|
||||
first_lines: crate::layout::body::FirstLines,
|
||||
row_lines: crate::layout::body::RowLines,
|
||||
cursors: crate::layout::body::Cursors,
|
||||
footer_slots: crate::contract::footer_slot::Slots,
|
||||
column_groups: crate::layout::column_group::Open,
|
||||
popups: crate::contract::overlay::popups::Popups,
|
||||
access_reported: crate::runtime::egui::access::Reported,
|
||||
|
||||
@@ -29,7 +29,7 @@ pub use held::{HeldAnswer, HeldOk};
|
||||
#[doc(hidden)]
|
||||
pub use host::dialog_probe;
|
||||
pub use host::{DialogHost, DialogResult, FieldRefusal, OpenDialog, StackDialog, StartupStage};
|
||||
pub use modal::{Dialog, DialogStyle};
|
||||
pub use modal::{ButtonPlace, Dialog, DialogStyle};
|
||||
pub use prompt::{Prompt, PromptOutput};
|
||||
pub use prompts::{PromptAnswer, PromptChoice, PromptKind, StandardPrompt, StandardPromptOutput};
|
||||
pub use recovery::{RecoveredDocument, RecoveryAnswer, RecoveryDialog, RecoveryOutput};
|
||||
|
||||
@@ -34,6 +34,22 @@ type OnPickFn<'a> = Box<dyn FnMut(&FooterButton, &mut BodyCx<'_>) + 'a>;
|
||||
|
||||
type SettleFn<'a> = Box<dyn FnMut(&mut BodyCx<'_>, &mut [FooterButton]) + 'a>;
|
||||
|
||||
/// Where a dialog's buttons stand. Wherever they stand, the dialog shows them: their roles, the platform's order,
|
||||
/// Enter and Escape, access keys, the close guard and `on_pick` are the dialog's.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ButtonPlace {
|
||||
/// Across the dialog's foot, in a row at the end edge.
|
||||
#[default]
|
||||
Foot,
|
||||
/// In a column at the end edge, beside the whole body and at its top: `Accept`, `Cancel`, then the others, each as
|
||||
/// wide as the widest, with the footer content under them.
|
||||
Side,
|
||||
/// In a column at the cell the body keeps for them with a `FooterSlot`, as wide as the cell: the Color Picker's
|
||||
/// buttons above its second field group. The body shows exactly one slot.
|
||||
Body,
|
||||
}
|
||||
|
||||
/// A dialog on its own layer. It opens in the middle of the window, moves by its title band, scrolls its body when the
|
||||
/// window is smaller and traps the keyboard focus while it is open.
|
||||
///
|
||||
@@ -75,8 +91,8 @@ pub struct Dialog<'a> {
|
||||
/// Whether the title row has a close action.
|
||||
#[prop]
|
||||
closable: bool,
|
||||
/// The footer stands in a column at the end edge, beside the whole body.
|
||||
side: bool,
|
||||
/// Where the buttons stand.
|
||||
place: ButtonPlace,
|
||||
closed: Option<CloseReason>,
|
||||
picked: Option<usize>,
|
||||
/// The body ran in this pass: the header region marks it.
|
||||
@@ -113,7 +129,7 @@ impl<'a> Dialog<'a> {
|
||||
buttons: Vec::new(),
|
||||
enter: false,
|
||||
closable: true,
|
||||
side: false,
|
||||
place: ButtonPlace::Foot,
|
||||
closed: None,
|
||||
picked: None,
|
||||
body_shown: false,
|
||||
@@ -245,8 +261,8 @@ impl<'a> Dialog<'a> {
|
||||
self.route_enter()
|
||||
}
|
||||
|
||||
/// The footer's content: the closure fills the start of the buttons' line (under the buttons with
|
||||
/// [`side_buttons`](Dialog::side_buttons)), or a line of its own when there are no buttons.
|
||||
/// The footer's content: the closure fills the start of the buttons' line (under the buttons' column with
|
||||
/// [`ButtonPlace::Side`] and [`ButtonPlace::Body`]), or a line of its own when there are no buttons.
|
||||
#[must_use]
|
||||
pub fn footer(mut self, content: impl FnMut(&mut Ui, &mut FooterCx<'_, '_, '_>) + 'a) -> Self {
|
||||
let region = self.footer_region();
|
||||
@@ -255,13 +271,11 @@ impl<'a> Dialog<'a> {
|
||||
self.overlay(|overlay| overlay)
|
||||
}
|
||||
|
||||
/// The footer stands in a column at the end edge, beside the whole body and at its top, instead of across the
|
||||
/// dialog's foot: the buttons go `Accept`, `Cancel`, then the others, each as wide as the widest, and the footer
|
||||
/// content sits under them.
|
||||
/// Where the buttons and the footer content stand; across the foot by default.
|
||||
#[must_use]
|
||||
pub fn side_buttons(mut self, on: bool) -> Self {
|
||||
self.side = on;
|
||||
self.props.end = on.then_some(SIDE_BUTTONS);
|
||||
pub fn button_place(mut self, place: ButtonPlace) -> Self {
|
||||
self.place = place;
|
||||
self.props.end = (place == ButtonPlace::Side).then_some(SIDE_BUTTONS);
|
||||
if self.props.footer.is_some() {
|
||||
let region = self.footer_region();
|
||||
self.props = self.props.footer(region);
|
||||
@@ -269,9 +283,13 @@ impl<'a> Dialog<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The footer region: in the end region's column, else across the foot.
|
||||
/// The footer region: in the end region's column, in the body's slot, or across the foot.
|
||||
fn footer_region(&self) -> FooterRegion {
|
||||
if self.side { FooterRegion::new().place(FooterPlace::EndTop) } else { FOOTER }
|
||||
match self.place {
|
||||
ButtonPlace::Foot => FOOTER,
|
||||
ButtonPlace::Side => FooterRegion::new().place(FooterPlace::EndTop),
|
||||
ButtonPlace::Body => FooterRegion::new().place(FooterPlace::Body),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -476,7 +494,7 @@ impl Container for Dialog<'_> {
|
||||
&self.buttons,
|
||||
self.enter,
|
||||
frame::FooterHost { picked: &mut self.picked, guard: &mut self.guard, on_pick: &mut self.on_pick, settle: &mut self.settle },
|
||||
self.side,
|
||||
self.place != ButtonPlace::Foot,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,17 @@
|
||||
//! Stories of the dialog shells.
|
||||
|
||||
use super::modal::ModalDragStrip;
|
||||
use super::{BlockingOverlay, Dialog, DialogFrame, DialogHost, StackDialog};
|
||||
use super::{BlockingOverlay, ButtonPlace, Dialog, DialogFrame, DialogHost, StackDialog};
|
||||
use crate::buttons::Button;
|
||||
use crate::choice::Checkbox;
|
||||
use crate::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use crate::contract::{Bind, FooterSlot, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use crate::display::Text;
|
||||
use crate::layout::GridFit;
|
||||
use crate::layout_components::{Grid, Row};
|
||||
use crate::runtime::focus::Initial;
|
||||
use crate::sections::{DialogRole, FooterButton};
|
||||
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use craft_behavior::ColumnWidth;
|
||||
use egui::Ui;
|
||||
|
||||
/// What the story dialogs hold: two check boxes whose values the story keeps between passes.
|
||||
@@ -116,7 +120,7 @@ fn dialog_with_side_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut checks = *data.value("checks", [true, false]);
|
||||
let shown: StoryOutput = Dialog::new("Grid options")
|
||||
.opened(Bind::bound(opener(ui, data, GRID_OPTIONS)))
|
||||
.side_buttons(true)
|
||||
.button_place(ButtonPlace::Side)
|
||||
.buttons([
|
||||
FooterButton::new("OK", DialogRole::Accept),
|
||||
FooterButton::new("Cancel", DialogRole::Cancel),
|
||||
@@ -131,6 +135,37 @@ fn dialog_with_side_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
shown
|
||||
}
|
||||
|
||||
/// The two columns of the body-buttons story: the grid choices, and the column the buttons head.
|
||||
const TWO_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// A dialog whose body keeps the cell its buttons stand in (`ButtonPlace::Body`): the buttons head the second column,
|
||||
/// over its controls, as Photoshop's Color Picker puts OK and Cancel over its second field group.
|
||||
#[story(FooterSlot, covers = [Default], drive = Drive::Never)]
|
||||
fn dialog_with_body_buttons(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut checks = *data.value("checks", [true, false]);
|
||||
let [snap, rulers] = &mut checks;
|
||||
let shown: StoryOutput = Dialog::new("Grid options")
|
||||
.opened(Bind::bound(opener(ui, data, GRID_OPTIONS)))
|
||||
.button_place(ButtonPlace::Body)
|
||||
.buttons([
|
||||
FooterButton::new("OK", DialogRole::Accept),
|
||||
FooterButton::new("Cancel", DialogRole::Cancel),
|
||||
FooterButton::new("Add to Swatches", DialogRole::Other).stays_open(true),
|
||||
])
|
||||
.show(ui, |ui, _| {
|
||||
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).show(ui, |ui, _| {
|
||||
Text::new("Lines every 10 mm, in 4 subdivisions.").show(ui);
|
||||
let _ = FooterSlot::new().show(ui);
|
||||
// A labelled control in a grid takes a cell for its label: each check box is a row, one cell.
|
||||
Row::new().show(ui, |ui, _| Checkbox::new(Bind::bound(&mut *snap)).label("Snap to grid").show(ui));
|
||||
Row::new().show(ui, |ui, _| Checkbox::new(Bind::bound(&mut *rulers)).label("Show rulers").show(ui));
|
||||
});
|
||||
})
|
||||
.into();
|
||||
*data.value("checks", [true, false]) = checks;
|
||||
shown
|
||||
}
|
||||
|
||||
#[story(Dialog<'static>, covers = [], drive = Drive::Never)]
|
||||
fn dialog_resizable_with_initial_focus(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut checks = *data.value("checks", [true, false]);
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
//! Trials of the dialog shells' layer behaviour: initial focus, Escape and a closed dialog's keys.
|
||||
#![allow(clippy::panic, clippy::expect_used, reason = "trials assert by panicking")]
|
||||
|
||||
use super::{BlockingOverlay, Dialog};
|
||||
use super::{BlockingOverlay, ButtonPlace, Dialog};
|
||||
use crate::buttons::Button;
|
||||
use crate::choice::Checkbox;
|
||||
use crate::contract::{Bind, Props as _, Role, Show as _, ShowContainer as _};
|
||||
use crate::contract::{Bind, FooterSlot, Props as _, Role, Show as _, ShowContainer as _};
|
||||
use crate::display::Text;
|
||||
use crate::layout::GridFit;
|
||||
use crate::layout_components::Grid;
|
||||
use crate::layout_components::Row;
|
||||
use crate::runtime::overlay::CloseReason;
|
||||
use crate::sections::{DialogRole, FooterButton};
|
||||
use crate::testing::input::key_press;
|
||||
use crate::testing::relations::{apart_above, grows_with, inside, off_foot, same_column};
|
||||
use crate::testing::relations::{aligned_left, apart_above, grows_with, inside, off_foot, same_column};
|
||||
use crate::testing::{Fixture, Frames, trial};
|
||||
use crate::text::TextField;
|
||||
use craft_behavior::ColumnWidth;
|
||||
use egui::{Key, Modifiers, Rect, Ui};
|
||||
use std::cell::Cell;
|
||||
|
||||
@@ -184,7 +187,7 @@ fn side_buttons_stand_in_one_column_beside_the_body() {
|
||||
let (mut open, mut snap, mut preview) = (true, false, true);
|
||||
Dialog::new("Options")
|
||||
.opened(Bind::bound(&mut open))
|
||||
.side_buttons(true)
|
||||
.button_place(ButtonPlace::Side)
|
||||
.buttons([
|
||||
FooterButton::new("Add to Swatches", DialogRole::Other),
|
||||
FooterButton::new("Cancel", DialogRole::Cancel),
|
||||
@@ -268,3 +271,59 @@ fn a_progress_overlay_shows_a_spinner_and_its_message_and_escape_cancels_it() {
|
||||
fixture.settle();
|
||||
assert!(!open.get(), "Escape closed the overlay that has a Cancel button");
|
||||
}
|
||||
|
||||
/// A dialog whose buttons stand in its body (`ButtonPlace::Body`) shows them in the slot its body keeps, in the
|
||||
/// column's role order, and keeps their keys: Enter is OK and Escape cancels.
|
||||
#[trial]
|
||||
fn body_buttons_stand_in_the_slot_the_body_keeps_and_keep_their_keys() {
|
||||
const COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
|
||||
let run = |key: Option<Key>| {
|
||||
let seen = std::rc::Rc::new(Cell::new((None, None)));
|
||||
let sink = seen.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let (mut open, mut snap, mut rulers) = (true, false, true);
|
||||
let shown = Dialog::new("Options")
|
||||
.opened(Bind::bound(&mut open))
|
||||
.button_place(ButtonPlace::Body)
|
||||
.close_on_enter(true)
|
||||
.buttons([
|
||||
FooterButton::new("Add to Swatches", DialogRole::Other).stays_open(true),
|
||||
FooterButton::new("Cancel", DialogRole::Cancel),
|
||||
FooterButton::new("OK", DialogRole::Accept),
|
||||
])
|
||||
.show(ui, |ui, _| {
|
||||
Grid::new(COLUMNS).fit(GridFit::Fixed).show(ui, |ui, _| {
|
||||
Text::new("Lines every 10 mm").show(ui);
|
||||
let _ = FooterSlot::new().show(ui);
|
||||
// A labelled control in a grid takes a cell for its label: each check box is a row, one cell.
|
||||
Row::new().show(ui, |ui, _| Checkbox::new(Bind::bound(&mut snap)).label("Snap to the grid").show(ui));
|
||||
Row::new().show(ui, |ui, _| Checkbox::new(Bind::bound(&mut rulers)).label("Show rulers").show(ui));
|
||||
});
|
||||
});
|
||||
if shown.output.closed.is_some() {
|
||||
sink.set((shown.output.closed, shown.output.picked));
|
||||
}
|
||||
});
|
||||
fixture.idle(30);
|
||||
if let Some(key) = key {
|
||||
fixture.key(key, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
}
|
||||
(fixture, seen.get())
|
||||
};
|
||||
let (fixture, _) = run(None);
|
||||
let rect = |label: &str| fixture.by_label(label).unwrap_or_else(|| panic!("{label} is shown")).rect;
|
||||
let (ok, cancel, other, snap, rulers) = (rect("OK"), rect("Cancel"), rect("Add to Swatches"), rect("Snap to the grid"), rect("Show rulers"));
|
||||
let dialog = fixture.by_role(Role::DIALOG).into_iter().next().expect("the dialog is shown").rect;
|
||||
assert!(ok.max.y <= cancel.min.y && cancel.max.y <= other.min.y, "OK, Cancel, then the other button, top to bottom");
|
||||
for button in [cancel, other] {
|
||||
assert!(same_column(ok, button), "one column, one width: {ok:?} {button:?}");
|
||||
}
|
||||
assert!(ok.min.x >= snap.max.x, "the buttons head the second column, past the first: {ok:?} {snap:?}");
|
||||
assert!(aligned_left(ok, rulers), "the buttons start at the second column's edge: {ok:?} {rulers:?}");
|
||||
assert!(other.max.y <= rulers.min.y, "the buttons stand over the second column's controls: {other:?} {rulers:?}");
|
||||
assert!(inside(ok, dialog) && inside(other, dialog), "the buttons are inside the dialog");
|
||||
assert_eq!(run(Some(Key::Enter)).1, (Some(CloseReason::Activated), Some(2)), "Enter picks OK");
|
||||
let (escaped, _) = run(Some(Key::Escape)).1;
|
||||
assert_eq!(escaped, Some(CloseReason::Escape), "Escape cancels");
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ use super::rows::{ParamRows, ParamRowsOutput};
|
||||
|
||||
use crate::contract::{Bind, BodyCx, CanvasGesture, NoValue, Outcome, Remember as _, Sampler as _, SaveKey, Show as _, ShowContainer as _};
|
||||
|
||||
use crate::dialog::{Alert, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, FooterHooks, HeldAnswer, HeldOk, StackDialog, dialog_id};
|
||||
use crate::dialog::{
|
||||
Alert, ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, FooterHooks, HeldAnswer, HeldOk, StackDialog, dialog_id,
|
||||
};
|
||||
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::form::SliderFieldLayout;
|
||||
@@ -67,9 +69,9 @@ pub enum ParamLayout {
|
||||
}
|
||||
|
||||
impl ParamLayout {
|
||||
/// Whether a dialog that previews stands its buttons in a column beside the body.
|
||||
fn side_buttons(self) -> bool {
|
||||
!matches!(self, ParamLayout::Stacked)
|
||||
/// Where a dialog that previews stands its buttons: in a column beside the body, or across the foot.
|
||||
fn button_place(self) -> ButtonPlace {
|
||||
if matches!(self, ParamLayout::Stacked) { ButtonPlace::Foot } else { ButtonPlace::Side }
|
||||
}
|
||||
|
||||
/// How the range rows arrange their slider and number field.
|
||||
@@ -482,7 +484,7 @@ impl<'a> ParamDialog<'a> {
|
||||
form = form.opened(open);
|
||||
}
|
||||
if previews {
|
||||
form = form.preview(preview_on).side_buttons(layout.side_buttons());
|
||||
form = form.preview(preview_on).button_place(layout.button_place());
|
||||
}
|
||||
// The pane shows only in a dialog that previews.
|
||||
let preview = preview.filter(|_| previews);
|
||||
|
||||
@@ -9,7 +9,7 @@ use crate::contract::{Bind, BodyCx, Props as _, Remember as _, Show as _, ShowCo
|
||||
use crate::runtime::commands::Commands as _;
|
||||
use crate::runtime::requests::HostAnswer;
|
||||
|
||||
use crate::dialog::{Dialog, DialogOutput};
|
||||
use crate::dialog::{ButtonPlace, Dialog, DialogOutput};
|
||||
|
||||
use crate::runtime::env::{Env, Label};
|
||||
|
||||
@@ -159,7 +159,7 @@ type ResetWithFn<'a, V> = Box<dyn Fn(&V, &V) -> V + 'a>;
|
||||
/// - With [`history`](FormDialog::history), Cmd/Ctrl+Z and Shift+Cmd/Ctrl+Z step the dialog's own value; a drag or a
|
||||
/// typing run is one step.
|
||||
/// - The footer goes across the foot, the Preview check box and the footer controls at its start edge; with
|
||||
/// [`side_buttons`](FormDialog::side_buttons) the buttons stand in a column beside the body, with the Preview check
|
||||
/// [`button_place`](FormDialog::button_place) `ButtonPlace::Side` the buttons stand in a column beside the body, with the Preview check
|
||||
/// box and the footer controls under them.
|
||||
#[must_use = "show the dialog with `show`"]
|
||||
#[derive(crate::contract::Pattern)]
|
||||
@@ -180,7 +180,7 @@ pub struct FormDialog<'a, V: Value + Default> {
|
||||
closable: bool,
|
||||
accept_stays_open: bool,
|
||||
enter_confirms: bool,
|
||||
side_buttons: bool,
|
||||
button_place: ButtonPlace,
|
||||
footer_extra: Option<FooterExtraFn<'a>>,
|
||||
/// The Preview check box when shown, over its owner's bind or (`None`) the footer's memory.
|
||||
preview: Option<Option<Bind<'a, bool>>>,
|
||||
@@ -212,7 +212,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
|
||||
closable: true,
|
||||
accept_stays_open: false,
|
||||
enter_confirms: true,
|
||||
side_buttons: false,
|
||||
button_place: ButtonPlace::Foot,
|
||||
footer_extra: None,
|
||||
preview: None,
|
||||
extra_buttons: Vec::new(),
|
||||
@@ -319,10 +319,11 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the buttons stand in a column beside the body, with the Preview check box and the footer controls under
|
||||
/// them (`Dialog::side_buttons`), instead of across the foot: Photoshop's button-column dialogs.
|
||||
pub fn side_buttons(mut self, on: bool) -> Self {
|
||||
self.side_buttons = on;
|
||||
/// Where the buttons stand (`Dialog::button_place`): across the foot by default; `ButtonPlace::Side` puts them in a
|
||||
/// column beside the body, with the Preview check box and the footer controls under them, as Photoshop's
|
||||
/// button-column dialogs.
|
||||
pub fn button_place(mut self, place: ButtonPlace) -> Self {
|
||||
self.button_place = place;
|
||||
self
|
||||
}
|
||||
|
||||
@@ -384,7 +385,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
|
||||
closable,
|
||||
accept_stays_open,
|
||||
enter_confirms,
|
||||
side_buttons,
|
||||
button_place,
|
||||
footer_extra,
|
||||
preview,
|
||||
extra_buttons,
|
||||
@@ -427,7 +428,7 @@ impl<'a, V: Value + Default> FormDialog<'a, V> {
|
||||
.closable(closable)
|
||||
.close_on_enter(ok_enabled && enter_confirms)
|
||||
.outer_gesture(outer_gesture)
|
||||
.side_buttons(side_buttons);
|
||||
.button_place(button_place);
|
||||
dialog = reset.install(dialog, accept, restore);
|
||||
if let Some(open) = open {
|
||||
dialog = dialog.opened(open);
|
||||
|
||||
@@ -28,7 +28,7 @@ use crate::canvas_data::{Guide, GuideColor};
|
||||
use crate::choice::Checkbox;
|
||||
use crate::contract::{Bind, EditResponse, Entry, NoValue, Outcome, Props as _, Remember as _, Show as _, ShowContainer as _, Sizing};
|
||||
|
||||
use crate::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
use crate::dialog::{ButtonPlace, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id};
|
||||
|
||||
use crate::display::Text;
|
||||
use crate::form::{Field, FieldGroup};
|
||||
@@ -331,7 +331,8 @@ impl<'a> GuideLayoutDialog<'a> {
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<GuideDialogWords>();
|
||||
let number_units = env.units();
|
||||
let mut dialog = FormDialog::new(words.layout_title.clone(), values).outer_gesture(true).answers(answers).preview(preview).side_buttons(true);
|
||||
let mut dialog =
|
||||
FormDialog::new(words.layout_title.clone(), values).outer_gesture(true).answers(answers).preview(preview).button_place(ButtonPlace::Side);
|
||||
if let Some(open) = open {
|
||||
dialog = dialog.opened(open);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use crate::contract::{
|
||||
Bind, CollectionEvent, NoValue, Outcome, Props as _, Remember as _, SelectMode, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
};
|
||||
use crate::dialog::{Dialog, DialogOutput};
|
||||
use crate::dialog::{ButtonPlace, Dialog, DialogOutput};
|
||||
use crate::display::{Shade, Text};
|
||||
use crate::form::Field;
|
||||
use crate::layout_components::Stack;
|
||||
@@ -334,15 +334,16 @@ impl<'a> ListManager<'a> {
|
||||
})
|
||||
.collect();
|
||||
buttons.push(FooterButton::new(common.cancel.clone(), DialogRole::Cancel));
|
||||
let mut dialog = Dialog::new(title.clone()).collection_body().close_on_enter(false).side_buttons(true).buttons(buttons).settle_buttons(
|
||||
move |cx, buttons| {
|
||||
let folder = cx.env.folder();
|
||||
let typed = cx.memory::<Session>().name.clone();
|
||||
for (button, action) in buttons.iter_mut().zip(actions) {
|
||||
button.set_enabled(is_enabled(action, entries, &folder, &typed));
|
||||
}
|
||||
},
|
||||
);
|
||||
let mut dialog =
|
||||
Dialog::new(title.clone()).collection_body().close_on_enter(false).button_place(ButtonPlace::Side).buttons(buttons).settle_buttons(
|
||||
move |cx, buttons| {
|
||||
let folder = cx.env.folder();
|
||||
let typed = cx.memory::<Session>().name.clone();
|
||||
for (button, action) in buttons.iter_mut().zip(actions) {
|
||||
button.set_enabled(is_enabled(action, entries, &folder, &typed));
|
||||
}
|
||||
},
|
||||
);
|
||||
if let Some(open) = open {
|
||||
dialog = dialog.opened(open);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::contract::{
|
||||
Access, BodyCx, Common, Component, Container, ContainerProps, Cx, EndRegion, FooterPlace, FooterRegion, Gap, HeaderRegion, LabelScheme, Pad,
|
||||
Role, Scroll, Sizing, ThemeScope,
|
||||
};
|
||||
use crate::layout::{BodyLayout, RowAlign};
|
||||
use crate::layout::{BodyLayout, CellAlign, GridFit, RowAlign};
|
||||
use crate::style::{ComponentStyle, StyleCx};
|
||||
use craft_behavior::{ColumnWidth, Insets, Metrics, Sense};
|
||||
use egui::{Response, Ui};
|
||||
@@ -320,4 +320,19 @@ impl Grid {
|
||||
senses_surface: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// What the grid does when its columns do not fit beside each other: [`GridFit::Stack`] (the default) puts the
|
||||
/// cells one under another; [`GridFit::Fixed`] keeps the columns and overflows the room. Leave a cell empty with
|
||||
/// `layout::empty_cell`.
|
||||
pub fn fit(mut self, fit: GridFit) -> Self {
|
||||
self.props.layout = std::mem::replace(&mut self.props.layout, BodyLayout::Stack).fit(fit);
|
||||
self
|
||||
}
|
||||
|
||||
/// Where a cell shorter than its row stands in it: [`CellAlign::Center`] (the default) in the row's middle,
|
||||
/// [`CellAlign::Top`] at its top.
|
||||
pub fn cells(mut self, cells: CellAlign) -> Self {
|
||||
self.props.layout = std::mem::replace(&mut self.props.layout, BodyLayout::Stack).cells(cells);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::{Grid, Row, Stack};
|
||||
use crate::contract::{Gap, Pad, ShowContainer as _};
|
||||
use crate::layout::{CellAlign, GridFit, empty_cell};
|
||||
use crate::story_kit::sample::{outlined, words};
|
||||
use crate::testing::{StoryData, StoryOutput, story};
|
||||
use craft_behavior::ColumnWidth;
|
||||
@@ -37,3 +38,39 @@ static COLUMNS: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Fixed(60.
|
||||
fn grid(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
outlined(ui, |ui| Grid::new(&COLUMNS).pad(Pad::Regular).show(ui, |ui, _| words(ui, 0..4)).into())
|
||||
}
|
||||
|
||||
static FIXED: [ColumnWidth; 3] = [ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// A grid whose arrangement is fixed: in a room narrower than its columns it keeps them beside each other and
|
||||
/// overflows, and its second row leaves the first cell empty, so the cells after it stay in their columns.
|
||||
#[story(Grid, covers = [])]
|
||||
fn grid_fixed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
outlined(ui, |ui| {
|
||||
Grid::new(&FIXED)
|
||||
.fit(GridFit::Fixed)
|
||||
.pad(Pad::Regular)
|
||||
.show(ui, |ui, _| {
|
||||
words(ui, 0..3);
|
||||
empty_cell(ui);
|
||||
words(ui, 2..4);
|
||||
})
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
static TOP: [ColumnWidth; 2] = [ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// A grid whose cells stand at the top of their row: a short column of words beside a taller one starts level with it.
|
||||
#[story(Grid, covers = [])]
|
||||
fn grid_cells_top(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
outlined(ui, |ui| {
|
||||
Grid::new(&TOP)
|
||||
.cells(CellAlign::Top)
|
||||
.pad(Pad::Regular)
|
||||
.show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| words(ui, 0..1));
|
||||
Stack::new().show(ui, |ui, _| words(ui, 0..4));
|
||||
})
|
||||
.into()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ Grouped by gallery level, then shape, then name.
|
||||
| `CropOverlay` | Leaf | `craft_ui_canvas::canvas::crop` | The crop frame of a document, edited by dragging it as Photoshop's Classic crop does (or moving and turning the image behind it in image mode) and by the keyboard |
|
||||
| `Divider` | Leaf | `craft_ui_widgets::display::divider` | A separator line in the divider colour, snapped to the pixel grid |
|
||||
| `FalloffPreview` | Leaf | `craft_ui_canvas::canvas_controls::brush::falloff` | A tip's falloff centred at a document point, with the circle of the brush's size round it: the preview a brush resize and a hover show |
|
||||
| `FooterSlot` | Leaf | `craft_ui_contract::contract::footer_slot` | The cell where a container whose footer stands in its body (`FooterPlace::Body`) draws that footer: a dialog's buttons in the cell its body's arrangement keeps for them, as the Color Picker keeps one above its second field group |
|
||||
| `Guides` | Leaf | `craft_ui_canvas::canvas_controls::guides` | The ruler guides of a canvas: drawn, taken by the pointer and moved with the keyboard |
|
||||
| `HeaderText` | Leaf | `craft_ui_contract::contract::items::header` | A header cell's label |
|
||||
| `HoverOutline` | Leaf | `craft_ui_canvas::canvas_controls::outline` | The outline of the object under the pointer: decoration over the canvas, drawn after the document and before the tool's own marks |
|
||||
|
||||
Reference in New Issue
Block a user