Color panel look (fix round): channel rows at production density with content-sized fields and the colour band of size.ramp.bar; readout letters and fold; framed edited well; gamut warning beside its swatch; ramp a control tall

- PaintUi::measure: a composite measures a child as PaintUi::child shows it.
- SliderField::field_sizing; the Inline field takes its measured width.
- Slider: the triangle starts under the colour band; TrackLook::ramp is size.ramp.bar.
- NumberField: a field that rounds what it commits is sized at those places; a mixed field is sized as with a value.
- ColorReadout: a wrapping row, the hex field then R, G, B fields after their letters, each content-sized.
- SwatchPair::frame_active; ColorWarningChip::beside.
This commit is contained in:
aiongg
2026-11-13 19:26:50 +00:00
parent c17531be51
commit f04b5867fa
16 changed files with 203 additions and 98 deletions
+6
View File
@@ -208,6 +208,12 @@ impl NumberCodec {
self
}
/// The same codec writing at most `decimals` decimal places.
pub fn at_most(mut self, decimals: usize) -> Self {
self.decimals = self.decimals.min(decimals);
self
}
/// The same codec with `parse` as a second reader: it runs when the reader rejects the text, so words of the
/// field's context ("Auto") can stand for numbers.
pub fn or_parse(mut self, parse: impl Fn(&str) -> Option<f64> + Send + Sync + 'static) -> Self {
+50 -16
View File
@@ -110,6 +110,8 @@ pub struct SwatchPairStyle {
edge: StyleColor,
/// The outline's width: `stroke.thin`.
outline: f32,
/// The frame round the active well where the pair frames it (`frame_active`).
frame: StyleColor,
/// The light line just inside a well's edge, so any colour reads against the surface.
mark: StyleColor,
/// A swatch's look, for the lines that stand out from a ring well's colour.
@@ -180,6 +182,8 @@ impl Outcome for SwatchPairOutput {
/// - The host holds the active well and the colours. A click on a well, or an arrow key while one has the focus,
/// makes it active and returns it as [`SwatchPairOutput::active`]; it is drawn in front with a gap in the colour the
/// pair sits on round it. The wells keep their places.
/// - [`frame_active(true)`](SwatchPair::frame_active), as Photoshop's Color panel: the primary well stays in front
/// and the active well, whichever it is, has a frame round it.
/// - A double-click, or Enter on the focused well, opens a popup with the Compact picker, which edits that well's
/// colour (`edit`, `well`, `open`); a click outside closes it.
/// - Host-picker mode, as PhotoCraft's tool rail: [`popover(false)`](SwatchPair::popover) turns the popup off, so a
@@ -209,6 +213,10 @@ pub struct SwatchPair<'a> {
/// Whether a click or an arrow makes a well active.
#[prop]
click_activates: bool,
/// Whether the active well is shown by a frame round it, the primary well staying in front, instead of by being
/// in front.
#[prop]
frame_active: bool,
/// The host's answer to the picker's screen eyedropper.
#[prop]
sampled: Option<Srgba>,
@@ -236,6 +244,7 @@ impl<'a> SwatchPair<'a> {
default_button: None,
popover: true,
click_activates: true,
frame_active: false,
sampled: None,
picker: None,
clicked: None,
@@ -256,23 +265,34 @@ impl<'a> SwatchPair<'a> {
/// The buttons' rects in logical coordinates from the pair's start edge: default colours at the start, swap at the
/// end.
fn button_rects(style: &SwatchPairStyle) -> [Rect; 2] {
fn button_rects(&self, style: &SwatchPairStyle) -> [Rect; 2] {
let side = Vec2::splat(style.buttons);
[Rect::from_min_size(pos2(0.0, 0.0), side), Rect::from_min_size(pos2(Self::wells(style).x - style.buttons, 0.0), side)]
[Rect::from_min_size(pos2(0.0, 0.0), side), Rect::from_min_size(pos2(self.wells(style).x - style.buttons, 0.0), side)]
}
/// The size of the two wells with the outlines round them.
fn wells(style: &SwatchPairStyle) -> Vec2 {
Vec2::splat(style.well + style.step + 2.0 * style.outline)
/// The room round a well's edge: its outline, and the frame a gap outside it where the pair frames the active well.
fn edge(&self, style: &SwatchPairStyle) -> f32 {
if self.frame_active { 2.0 * style.outline + style.gap } else { style.outline }
}
/// The size of the two wells with the room round their edges.
fn wells(&self, style: &SwatchPairStyle) -> Vec2 {
Vec2::splat(style.well + style.step + 2.0 * self.edge(style))
}
/// The wells' rects in logical coordinates from the pair's start edge, primary first, inside their outlines.
/// The well drawn in front, which takes the pointer where the wells overlap.
fn front(&self, active: Well) -> Well {
if self.frame_active { Well::Primary } else { active }
}
fn well_rects(&self, style: &SwatchPairStyle, size: Vec2) -> [Rect; 2] {
// The buttons' squares hold their glyphs with room round them, so the wells follow without a gap.
let top = if self.has_buttons() { style.buttons } else { 0.0 } + style.outline;
let edge = self.edge(style);
let top = if self.has_buttons() { style.buttons } else { 0.0 } + edge;
let square = Vec2::splat(style.well);
let primary = Rect::from_min_size(pos2(style.outline, top), square);
let end = size.x.min(Self::wells(style).x) - style.outline;
let primary = Rect::from_min_size(pos2(edge, top), square);
let end = size.x.min(self.wells(style).x) - edge;
let secondary = Rect::from_min_size(pos2(end - style.well, top + style.step), square);
[primary, secondary]
}
@@ -301,6 +321,7 @@ impl Component for SwatchPair<'_> {
buttons: cx.control().icon,
edge: cx.color(colors.line.control_edge),
outline: cx.tokens.stroke.thin,
frame: cx.color(colors.text.muted),
mark: cx.color(colors.text.normal),
swatch: Swatch::style(cx, Swatch::new(Label::default(), Srgba::BLACK).style_key()),
}
@@ -312,7 +333,7 @@ impl Component for SwatchPair<'_> {
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
let style = cx.style;
let wells = Self::wells(style);
let wells = self.wells(style);
if self.has_buttons() { vec2(wells.x, wells.y + style.buttons) } else { wells }
}
@@ -324,12 +345,14 @@ impl Component for SwatchPair<'_> {
let flow = Flow::new(rect, cx.flow.is_rtl());
let rects = self.well_rects(cx.style, rect.size());
let active = cx.value().copied().unwrap_or_default();
let on_top = self.front(active);
for (i, logical) in rects.into_iter().enumerate() {
let front = Well::of(i as u64) == active;
let well = Well::of(i as u64);
let front = well == on_top;
let at = flow.to_physical(logical.translate(rect.min.to_vec2()));
let mut flags = Flags::empty();
flags.set(Flags::MIXED, self.wells[i].color.same().is_none());
flags.set(Flags::CHECKED, front);
flags.set(Flags::CHECKED, well == active);
let part = cx
.part(WELL.at(i as u64), at)
.sense(Sense::CLICK | Sense::FOCUS)
@@ -340,7 +363,7 @@ impl Component for SwatchPair<'_> {
part.pointer_only("Enter opens the picker");
}
}
let buttons = Self::button_rects(cx.style);
let buttons = self.button_rects(cx.style);
for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] {
if shown {
let at = flow.to_physical(button.translate(rect.min.to_vec2()));
@@ -434,8 +457,9 @@ impl Component for SwatchPair<'_> {
let rects = self.well_rects(style, cx.rect.size());
let active = cx.value().copied().unwrap_or_default();
let place = |logical: Rect| flow.to_physical(logical.translate(cx.rect.min.to_vec2()));
// The back well first, then the front one with a gap round it: being in front is what shows the active well. The
// gap is a patch of the surface the pair sits on (a panel, a tool rail's chrome), fill only.
// The back well first, then the front one with a gap round it: being in front, or the frame, shows the active well.
// The gap is a patch of the surface the pair sits on (a panel, a tool rail's chrome), fill only. The back well's
// frame is painted before the front well, which covers it where they overlap.
{
let halo = UiTokens::corner(f32::from(style.radius.nw) + style.gap);
let ground = ui.with_style(cx.resolved.variant, |scope| SurfaceStyle {
@@ -445,10 +469,11 @@ impl Component for SwatchPair<'_> {
..scope.surface(cx.env.surface())
});
let draw = ui.draw();
for well in [active.other(), active] {
let front = self.front(active);
for well in [front.other(), front] {
let at = place(rects[well.index() as usize]);
let shown = &self.wells[well.index() as usize];
if well == active {
if well == front {
draw.surface_styled(at.expand(style.gap), &ground);
}
match shown.color.same() {
@@ -459,6 +484,9 @@ impl Component for SwatchPair<'_> {
draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge);
}
}
if self.frame_active && well == active {
draw.stroke(&frame(at, style), StrokeWidth::Thin, style.frame);
}
}
}
// The buttons' glyphs keep the control size whatever glyph role the pair's scope sets (a tool rail's).
@@ -506,6 +534,12 @@ fn paint_ring(draw: &Draw<'_>, at: Rect, color: Srgba, style: &SwatchPairStyle)
draw.stroke(&PaintShape::Rect(hole.expand(line), corner(line)), StrokeWidth::Thin, style.edge);
}
/// The frame round the active well `at`: a gap outside its outline, concentric with its corners.
fn frame(at: Rect, style: &SwatchPairStyle) -> PaintShape {
let out = style.outline + style.gap;
PaintShape::Rect(at.expand(out), UiTokens::corner(f32::from(style.radius.nw) + out))
}
/// The outline just outside the well `at`, concentric with its corners.
fn outline(at: Rect, style: &SwatchPairStyle) -> PaintShape {
PaintShape::Rect(at.expand(style.outline), UiTokens::corner(f32::from(style.radius.nw) + style.outline))
+11 -9
View File
@@ -9,7 +9,8 @@ use craft_cms::convert::CmykConverter;
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Srgba};
use craft_ui::buttons::IconButton;
use craft_ui::contract::{
Bind, CommandSet, Held, LabelScheme, NoValue, Outcome, Pattern, Props as _, Remember as _, Scroll, Show as _, ShowContainer as _, Sizing, clicked,
Bind, CommandSet, Gap, Held, LabelScheme, NoValue, Outcome, Pattern, Props as _, Remember as _, Scroll, Show as _, ShowContainer as _, Sizing,
clicked,
};
use craft_ui::layout::RowAlign;
use craft_ui::layout_components::{Row, Stack};
@@ -275,14 +276,14 @@ struct Kept {
/// The Color panel.
///
/// - Wells: the foreground over the background (`SwatchPair`); a click on the other well makes it the edited one
/// ([`ColorPanelState::background`]); a click on the edited one asks for the picker. The swap and default buttons
/// - Wells: the foreground over the background (`SwatchPair`), the edited one framed; a click on the other well makes
/// it the edited one ([`ColorPanelState::background`]); a click on the edited one asks for the picker. The swap and default buttons
/// are the pair's.
/// - Views: Hue Cube and Brightness Cube are `ColorArea` and `ColorStrip` (hue or brightness in the strip); Color
/// Wheel is `ColorWheel`; the slider modes are the channel rows of that model (Grayscale is [`GrayModel`], CMYK is
/// [`CmykModel`] through the converter, Web Color is RGB with sliders that snap to web colours). Slider values show
/// rounded to whole numbers, as Photoshop's fields.
/// - Warnings: in the slider modes, the out-of-gamut and web-colour chips beside the wells, the cubes the gamut chip
/// - Warnings: in the slider modes, the out-of-gamut and web-colour chips under the wells, the cubes the gamut chip
/// only; a click takes the nearest colour.
/// - Ramp: in the slider modes, a `ColorRamp` of the chosen kind; a press picks for the edited well, Alt picks for the
/// other; Shift-click cycles the kind. A drag keeps the Current Colors ends it began with. A secondary click opens
@@ -558,7 +559,8 @@ impl Body<'_> {
ColorPanelMode::HueCube => self.cube(ui, AreaMode::Hue),
ColorPanelMode::BrightnessCube => self.cube(ui, AreaMode::Brightness),
_ => {
Stack::new().fill_width().labels(LabelScheme::Inspector).show(ui, |ui, _| match mode {
// The channel rows stand as close as Photoshop's.
Stack::new().fill_width().gap(Gap::Tight).labels(LabelScheme::Inspector).show(ui, |ui, _| match mode {
ColorPanelMode::GrayscaleSlider => self.rows(ui, &GrayModel, false),
ColorPanelMode::RgbSliders => self.rows(ui, &RgbModel, false),
ColorPanelMode::CmykSliders => self.rows(ui, &CmykModel::new(self.converter.clone()), false),
@@ -583,7 +585,7 @@ impl Body<'_> {
let was = if self.now.background { Well::Secondary } else { Well::Primary };
let mut active = was;
let wells = [PairWell::new(self.words.foreground.clone(), self.colors[0]), PairWell::new(self.words.background.clone(), self.colors[1])];
let pair = SwatchPair::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).show(ui);
let pair = SwatchPair::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true).show(ui);
self.now.background = active == Well::Secondary;
if pair.clicked.as_ref() == Some(&was) {
let title = match self.target {
@@ -594,7 +596,7 @@ impl Body<'_> {
}
}
/// The out-of-gamut chip and, for Web Color, the web-colour chip under the wells.
/// The out-of-gamut chip and, for Web Color, the web-colour chip under the wells, each its icon beside a small swatch.
fn warnings(&mut self, ui: &mut Ui, web: bool) {
let color = self.color();
let rgb = [color.r, color.g, color.b];
@@ -606,9 +608,9 @@ impl Body<'_> {
if web && let Some(near) = not_web_safe(rgb) {
warnings.push(ColorWarning::web_colors(self.dialog.not_web_color.clone(), nearest(near)));
}
Row::new().show(ui, |ui, _| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
for warning in warnings.clone() {
if ColorWarningChip::new(&warning).show(ui).clicked {
if ColorWarningChip::new(&warning).beside(true).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));
+4 -3
View File
@@ -6,7 +6,7 @@ use std::ops::RangeInclusive;
use craft_behavior::{Axis, Sense};
use craft_theme::{Channel, ColorModel, Srgba};
use craft_ui::contract::{
Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel,
Bind, Common, Component, Cx, DisabledLook, EditResponse, GlyphLabel, LabelKind, MeasureCx, Role, Show as _, ShowContainer as _, SideLabel, Sizing,
};
use craft_ui::form::{Field, SliderField, SliderFieldLayout};
use craft_ui::primitives::{PaintShape, StrokeWidth};
@@ -104,7 +104,7 @@ impl Component for TrackRamp {
metrics: craft_behavior::Metrics::new(),
edge: cx.color(cx.tokens.color.line.control_edge),
length: cx.tokens.size.length.track,
thickness: cx.tokens.size.ramp.groove,
thickness: cx.tokens.size.ramp.bar,
}
}
@@ -157,7 +157,7 @@ pub(crate) fn channel_slider<'a>(
/// One channel on one line, as Photoshop's Color panel draws it: the label at the start (the channel's short label
/// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its
/// track, and the number field with its unit at the end.
/// track, and the number field with its unit at the end, as wide as its widest value.
#[derive(craft_ui::contract::Pattern)]
pub(crate) struct ChannelRow<'a> {
label: Label,
@@ -211,6 +211,7 @@ impl<'a> ChannelRow<'a> {
.show(ui, |ui, _| {
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
.layout(SliderFieldLayout::Inline)
.field_sizing(Sizing::Content)
.thumb(SliderThumb::Triangle)
.show(ui)
})
+24 -7
View File
@@ -63,7 +63,7 @@ impl ColorWarning {
}
}
/// The style of a warning chip: the icon over the chip, and their sizes.
/// 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 {
@@ -93,21 +93,25 @@ impl Outcome for ColorWarningChipOutput {
}
/// 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. The host applies [`ColorWarning::nearest`] when it is clicked. The tip
/// is the tooltip and the accessible name.
/// 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, clicked: false }.label(warning.tip.clone())
ColorWarningChip { common: Common::new(), warning, beside: false, clicked: false }.label(warning.tip.clone())
}
}
@@ -128,13 +132,26 @@ impl Component for ColorWarningChip<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Vec2::new(cx.style.icon.max(cx.style.chip), cx.style.icon + cx.style.gap + cx.style.chip)
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 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));
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;
+2 -1
View File
@@ -354,7 +354,8 @@ impl Component for ColorRamp<'_> {
fn style(cx: &StyleCx<'_>, _: ColorRampStyleKey) -> ColorRampStyle {
let tokens = cx.tokens;
ColorRampStyle {
metrics: Metrics::new().min_size(Vec2::new(tokens.size.length.track, tokens.size.thumb.lg)),
// At least a control tall, as Photoshop's ramp under the channel rows of a short panel.
metrics: Metrics::new().min_size(Vec2::new(tokens.size.length.track, cx.control().height)),
focus: cx.focus_look(),
edge: cx.color(tokens.color.line.control_edge),
boxes: tokens.size.icon.lg,
+49 -42
View File
@@ -3,18 +3,15 @@
#[cfg(feature = "screen-testing")]
mod stories;
use craft_behavior::{ColumnWidth, EditEvent, EditEvents, Mixed};
use craft_theme::Rgba;
use craft_ui::contract::{Bind, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::layout_components::{Grid, Stack};
use craft_behavior::{EditEvent, EditEvents, Mixed};
use craft_theme::{ColorModel as _, RgbModel, Rgba};
use craft_ui::contract::{Bind, GlyphLabel, LabelKind, Outcome, Pattern, Props as _, Show as _, ShowContainer as _, SideLabel, Sizing};
use craft_ui::form::Field;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::runtime::env::{Env, Label};
use craft_ui::text::{NumberField, TextField};
use egui::{Response, Ui};
/// The hex field and the three channel fields share the width of the readout's column equally, so the row fits a
/// narrow panel.
const FIELDS: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 4];
/// The channels the fields edit, in field order.
const CHANNELS: [ReadoutChannel; 3] = [ReadoutChannel::Red, ReadoutChannel::Green, ReadoutChannel::Blue];
@@ -99,7 +96,9 @@ impl Outcome for ColorReadoutOutput {
}
}
/// A colour as a hex field and three number fields (R, G, B, each 0 to 255), in one row. An edit in any field
/// A colour as a hex field (its digits behind the field's own "#") and three number fields (R, G, B, each 0 to 255,
/// after their letters and as wide as their widest value), in one row that folds the R, G and B fields onto a second
/// line where the row does not fit. An edit in any field
/// reports the whole colour, with the other channels and the alpha as given. While the value is mixed, the hex field
/// still sets the whole colour and a channel field reports that channel alone ([`ColorReadoutOutput::channel`]), for
/// the host to set on each item. Each field's gesture is the readout's.
@@ -136,43 +135,51 @@ impl<'a> ColorReadout<'a> {
let held: Mixed<Rgba> = value.reborrow().read(&mut *body).unwrap_or(Mixed::Mixed);
let mut events: Vec<EditEvent<Rgba>> = Vec::new();
let mut channel_edits = Vec::new();
Grid::new(FIELDS).show(ui, |ui, _| {
// A channel's letter is the glyph of the field's side label; the field keeps its name.
let lettered = |name: &Label, letter: &'static str| {
Field::new(name.clone()).side(SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(letter))))).sizing(Sizing::Content)
};
Row::new().wrap(true).show(ui, |ui, _| {
events.clear();
channel_edits.clear();
events.extend(TextField::hex(words.hex.as_str().to_owned(), Bind::given(held)).show(ui).events);
let names = [&words.red, &words.green, &words.blue];
for (i, name) in names.into_iter().enumerate() {
let field = || {
NumberField::new(
name.as_str().to_owned(),
Bind::given(match held {
Mixed::Same(color) => Mixed::Same(Some(f64::from(color.0[i]))),
Mixed::Mixed => match shared[i] {
Mixed::Same(byte) => Mixed::Same(Some(f64::from(byte))),
Mixed::Mixed => Mixed::Mixed,
},
}),
)
.range(0.0..=255.0)
.step(1.0)
.snap_typed(true)
.commit_decimals(0)
};
let byte = |number: Option<f64>| number.map(|number| number.round().clamp(0.0, 255.0) as u8);
let out = field().show(ui);
for event in &out.events {
match held {
Mixed::Same(base) => events.push(event.clone().map(move |number| {
let mut mine = base;
if let Some(byte) = byte(number) {
mine.0[i] = byte;
}
mine
})),
Mixed::Mixed => channel_edits.push(ChannelEdit { channel: CHANNELS[i], event: event.clone().map(byte) }),
events.extend(TextField::hex(words.hex.as_str().to_owned(), Bind::given(held)).sizing(Sizing::Content).show(ui).events);
Row::new().show(ui, |ui, _| {
let names = [&words.red, &words.green, &words.blue];
let channels = RgbModel.channels();
for (i, name) in names.into_iter().enumerate() {
let field = || {
NumberField::new(
name.as_str().to_owned(),
Bind::given(match held {
Mixed::Same(color) => Mixed::Same(Some(f64::from(color.0[i]))),
Mixed::Mixed => match shared[i] {
Mixed::Same(byte) => Mixed::Same(Some(f64::from(byte))),
Mixed::Mixed => Mixed::Mixed,
},
}),
)
.range(0.0..=255.0)
.step(1.0)
.snap_typed(true)
.commit_decimals(0)
.sizing(Sizing::Content)
};
let byte = |number: Option<f64>| number.map(|number| number.round().clamp(0.0, 255.0) as u8);
let Some(out) = lettered(name, channels[i].label).show(ui, |ui, _| field().show(ui)).inner else { continue };
for event in &out.events {
match held {
Mixed::Same(base) => events.push(event.clone().map(move |number| {
let mut mine = base;
if let Some(byte) = byte(number) {
mine.0[i] = byte;
}
mine
})),
Mixed::Mixed => channel_edits.push(ChannelEdit { channel: CHANNELS[i], event: event.clone().map(byte) }),
}
}
}
}
});
});
for event in &events {
let _ = value.reborrow().write(&mut *body, event);
+11 -1
View File
@@ -83,7 +83,8 @@ fn dragging_to_the_bottom_right_keeps_the_knob_there() {
/// The cubes fill the panel's room as Photoshop's field fills its dock group: the field takes the height the readout
/// leaves and the width the wells and the strip leave, so in a short, narrow group the strip and the readout stay in
/// view, and a taller group gives a taller field.
/// view, and a taller group gives a taller field. The readout is one line in a 280 pt group and folds its R, G and B
/// fields under the hex field in a narrower one, never cut at the edge.
#[trial]
fn the_cubes_take_the_room_the_readout_and_the_strip_leave() {
let mut heights = Vec::new();
@@ -113,10 +114,19 @@ fn the_cubes_take_the_room_the_readout_and_the_strip_leave() {
assert!(area.rect.bottom() <= readout.rect.top(), "{case}: the readout under the field");
assert!(readout.rect.bottom() <= room.y + 0.5, "{case}: the readout in view ({:?})", readout.rect);
assert!((area.rect.height() - strip.rect.height()).abs() < 1.0, "{case}: the strip as tall as the field");
let hex = rig.fixture.by_label("Hex color").expect("the hex field");
assert!(readout.rect.right() <= room.x + 0.5, "{case}: the readout fits the width ({:?})", readout.rect);
assert!(hex.rect.y_range().contains(readout.rect.center().y), "{case}: the readout on one line ({:?}, {:?})", hex.rect, readout.rect);
heights.push(area.rect.height());
}
}
assert!(heights[2] > heights[0] + 200.0 && heights[3] > heights[1] + 200.0, "the field grows with the room: {heights:?}");
let narrow = Vec2::new(170.0, 400.0);
let rig = PanelRig::in_room(ColorPanelMode::HueCube, narrow);
let hex = rig.fixture.by_label("Hex color").expect("the hex field");
let blue = rig.fixture.by_label("Blue").expect("the readout's last field");
assert!(blue.rect.top() >= hex.rect.bottom(), "the readout folds in {narrow:?} ({:?}, {:?})", hex.rect, blue.rect);
assert!(blue.rect.right() <= narrow.x + 0.5, "the folded readout fits the width ({:?})", blue.rect);
}
/// The slider modes show each channel on one line: its slider and its number field side by side.
+3 -2
View File
@@ -375,9 +375,10 @@ pub struct RowSizes {
/// Thicknesses of gradient ramps, in logical pixels.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RampSizes {
/// A ramp drawn as a bar of its own: the output bar of a levels editor, a hue or saturation bar.
/// A colour band: a ramp drawn as a bar of its own (the output bar of a levels editor, a gradient's thumb row) or
/// as the face of a value track (the track of a colour channel slider).
pub bar: f32,
/// A ramp drawn as the groove of a value track: the track of a colour channel slider.
/// A thin band laid along a ramp: the span a gradient's thumb row draws between two thumbs.
pub groove: f32,
}
@@ -171,6 +171,12 @@ impl PaintUi<'_> {
self.child_with(self.id.with(key), rect, child, None, None)
}
/// Measures a child under the composite's resolved `enabled` and `size`, as [`child`](Self::child) with the same
/// key will show it: for a composite that places its children by their size.
pub fn measure<C: Show>(&self, key: impl Hash + Debug, child: &mut C, proposal: craft_behavior::Proposal) -> egui::Vec2 {
run::measure_under(child, &*self.ui, Some(self.id.with(key)), proposal, Some(&super::cx::Under::new(self.enabled, self.size)))
}
/// Shows `child` as the owner's own control, such as a picker the owner draws its field with. The child's node
/// folds into the owner's: the owner's node stands for the child's focus stop, carries the child's value text when
/// the owner's `access` sets none, and takes the actions and requests aimed at it, which reach the child. The
+1 -1
View File
@@ -284,7 +284,7 @@ impl<'a> StyleCx<'a> {
edge: Stateful::new(self.color(colors.line.control_edge)),
edge_width: self.tokens.stroke.thin,
thickness: self.tokens.size.groove,
ramp: self.tokens.size.ramp.groove,
ramp: self.tokens.size.ramp.bar,
radius: UiTokens::corner(self.tokens.shape.radius.pill),
mark_length: self.tokens.space.gap.tight,
mark_width: self.tokens.stroke.thin,
+21 -8
View File
@@ -4,7 +4,7 @@
mod stories;
use crate::contract::{
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, MeasureCx, PaintUi, Props as _, Role, SideLabel, Validity,
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, FieldLayout, MeasureCx, PaintUi, Props as _, Role, SideLabel, Sizing, Validity,
WordSetCx as _,
};
use crate::runtime::env::{Label, UnitKind};
@@ -33,14 +33,12 @@ pub enum SliderFieldLayout {
Inline,
}
/// The style of a slider field: the gap between its parts, the line height and the number field's width.
/// The style of a slider field: the gap between its parts, the line height and the stacked number field's width.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
#[non_exhaustive]
pub struct SliderFieldStyle {
#[style(metrics)]
metrics: Metrics,
/// The width of the number field, the same for every row so a column of fields lines up.
field: f32,
/// The gap between the number field and the slider on one line.
inline_gap: f32,
/// The height of the caption line.
@@ -90,6 +88,10 @@ pub struct SliderField<'a> {
/// The shape of the slider's thumb: a knob, or the pointer under the track of a colour channel.
#[prop]
thumb: SliderThumb,
/// The number field's sizing on the `Inline` line: `Sizing::Content` sizes it to its widest value (a dense panel
/// row, the Color panel's channels) instead of the number cell, and the slider takes the room it leaves.
#[prop]
field_sizing: Option<Sizing>,
}
impl<'a> SliderField<'a> {
@@ -108,6 +110,7 @@ impl<'a> SliderField<'a> {
fill: true,
track_face: None,
thumb: SliderThumb::Round,
field_sizing: None,
}
.label(label)
}
@@ -124,6 +127,7 @@ impl<'a> SliderField<'a> {
fill: self.fill,
thumb: self.thumb,
reset: self.value.reset_value().copied(),
field_sizing: self.field_sizing,
}
}
}
@@ -140,6 +144,7 @@ struct Look {
thumb: SliderThumb,
/// The reset value of the composite's own binding, which both children restore on a double click.
reset: Option<f64>,
field_sizing: Option<Sizing>,
}
/// The composite's check on a number, as a child with the same value type reads it.
@@ -204,6 +209,10 @@ impl Look {
Some(kind) => field.unit_kind(kind),
None => field,
};
let field = match self.field_sizing {
Some(sizing) => field.sizing(sizing),
None => field,
};
match &self.unit {
Some(unit) => field.unit(unit.clone()),
None => field,
@@ -234,7 +243,6 @@ impl Component for SliderField<'_> {
let control = cx.control();
SliderFieldStyle {
metrics: Metrics::new().gap(control.gap),
field: control.number,
inline_gap: cx.tokens.space.gap.section,
row: control.height,
width: control.field,
@@ -256,7 +264,7 @@ impl Component for SliderField<'_> {
let slider = cx.child("slider", &mut look.slider(&name, shown, None, None), Proposal::Ideal);
let field = cx.child("field", &mut look.field(&name, shown, None), Proposal::Ideal);
match self.layout {
SliderFieldLayout::Inline => Vec2::new(slider.x + cx.style.inline_gap + cx.style.field, slider.y.max(field.y)),
SliderFieldLayout::Inline => Vec2::new(slider.x + cx.style.inline_gap + field.x, slider.y.max(field.y)),
SliderFieldLayout::Stacked => Vec2::new(slider.x.max(cx.style.width), cx.style.row.max(field.y) + cx.gap() + slider.y),
}
}
@@ -268,15 +276,20 @@ impl Component for SliderField<'_> {
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let shown = shown_of(cx.value());
let name = cx.label();
let look = self.look();
let (track, field) = match self.layout {
SliderFieldLayout::Inline => arrange(cx.rect.size(), cx.style.inline_gap, cx.style.field),
// The field takes the width its own measure gives (a number cell, or its widest value when content-sized),
// so every row of a column with the same range ends its slider at one place.
SliderFieldLayout::Inline => {
let width = ui.measure("field", &mut look.field(&name, shown, None), Proposal::Ideal).x;
arrange(cx.rect.size(), cx.style.inline_gap, width)
}
SliderFieldLayout::Stacked => stack(cx.rect.size(), cx.style.metrics.gap, cx.style.row),
};
let flow = Flow::new(cx.rect, cx.env.direction().is_rtl());
let place = |logical: Rect| flow.to_physical(logical.translate(cx.rect.min.to_vec2()));
// The field is shown first, so it is the first Tab stop.
// The group has no stop, so its tooltip, and with it the reason it is disabled, is carried by the first stop.
let look = self.look();
let face = self.track_face.take();
let bind = self.value.reborrow();
let on_slider = |value: &f64| bind.validity(value);
+5 -4
View File
@@ -24,7 +24,6 @@ use craft_behavior::{
};
use craft_theme::{Stateful, States};
use egui::{Rect, Vec2};
use std::borrow::Cow;
use std::marker::PhantomData;
use std::ops::RangeInclusive;
@@ -378,13 +377,15 @@ impl<V: NumberValue + 'static> Component for NumberField<'_, V> {
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
self.settle_lengths(&cx.env.units());
let codec = self.ruled(&cx.env.units(), false, self.names(|row| cx.env.resolve(&row.label().clone())));
// The value area holds the widest value the field shows (the range's ends at the codec's precision, or the
// value when the range is open) with the caret and the unit, at most one number cell; a longer value scrolls
// The value area holds the widest value the field shows (the range's ends at the codec's precision, or at the
// places it commits when it rounds what it commits, or the value when the range is open) with the caret and the unit, at most one number cell; a longer value scrolls
// inside it. The inside label and the chevrons take their own room beside it, each as `place` gives it. The
// field is never narrower than a cell, so a column of short fields ends at one edge. A content-sized field
// takes its whole value and has no floor; in a column group its value area is the group's widest.
let content = content_sized(cx);
let sample = cx.value().map_or(Cow::Borrowed(""), |value| codec.sample(value));
// A mixed field is sized as it is with a value, so it keeps its width when the selection changes.
let blank = V::blank().unwrap_or_else(|| V::of_number(self.rule().blank()));
let sample = codec.sample(cx.value().unwrap_or(&blank));
let mut text = cx.field_text(&TextRun::new(sample.as_ref()).role(TypeRole::Mono));
if content {
text.x = crate::layout::ambient_width(cx.ui.ctx(), &VALUES, text.x).map_or(text.x, |width| width.max(text.x));
+5 -1
View File
@@ -202,7 +202,11 @@ impl<V: NumberValue> Codec for Ruled<V> {
fn sample(&self, current: &V) -> Cow<'_, str> {
match current.named() {
Some(_) => Cow::Owned(self.format(current)),
None if self.rule.low.is_finite() && self.rule.high.is_finite() => Cow::Owned(self.inner.widest(&(self.rule.low..=self.rule.high))),
// A field that rounds what it commits shows no more places than that.
None if self.rule.low.is_finite() && self.rule.high.is_finite() => {
let codec = self.decimals.map_or_else(|| self.inner.clone(), |places| self.inner.clone().at_most(places));
Cow::Owned(codec.widest(&(self.rule.low..=self.rule.high)))
}
None => Cow::Owned(self.format(current)),
}
}
+3 -1
View File
@@ -347,7 +347,9 @@ impl Component for Slider<'_> {
draw.surface_styled(rect, &knob);
}
SliderThumb::Triangle => {
let (half, top, x) = (style.thumb.x / 2.0, track::groove_rect(&style.track, along.area).bottom(), centre.x);
// The pointer starts under the band it points at: the colour face, or the plain groove.
let band = if faced { track::ramp_rect(&style.track, along) } else { track::groove_rect(&style.track, along.area) };
let (half, top, x) = (style.thumb.x / 2.0, band.bottom(), centre.x);
let points = vec![Pos2::new(x, top), Pos2::new(x + half, top + half), Pos2::new(x - half, top + half)];
style.ring.paint_pointer(&draw, &points, ring);
track::paint_pointer(&draw, points, &knob);
+2 -2
View File
@@ -984,8 +984,8 @@ A theme with its own shape replaces the radii or adds an offset to control, surf
| `size.popup_min` | Least width of a popup surface (menus only; popup lists such as Select and ComboBox take their anchor's width) |
| `size.scroll_fade` | Length of the fade at an edge of a scroll region past which its content continues |
| `size.groove` | Groove of a value track |
| `size.ramp.bar` | Gradient ramp drawn as a bar of its own |
| `size.ramp.groove` | Gradient ramp drawn as the groove of a value track |
| `size.ramp.bar` | Colour band: a gradient ramp drawn as a bar of its own or as the face of a value track |
| `size.ramp.groove` | Thin band along a ramp: the span between two thumbs of a gradient's thumb row |
| `size.rail.width`, `size.rail.button` | Tool rail and panel rail |
| `size.length.field.sm`, `size.length.field.md` | Text or value field, one width per control size: a field in a small options bar is narrower than one in a dialog |
| `size.length.number.sm`, `size.length.number.md` | Number field and the number cell over a slider, one width per control size |