panels-w7: written from its sheet

This commit is contained in:
aiongg
2026-11-14 17:56:00 +00:00
parent 308bba9bf8
commit 39056798ee
11 changed files with 564 additions and 99 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
# craft-color
Colour for Craft apps. With the `ui` feature, `craft_color::ui` has the colour picker (`ColorPicker`, `ColorPopover`, `ColorArea`, `ColorStrip`, `ColorWheel`, `ColorDisc`, `ColorRamp`), the wells (`SwatchPair`, `Well`), `SwatchPalette` tables and the `HexField`. It also has the colour features built on them: the Color Picker dialog (`ColorPickerDialog`), dialog droppers (`DropperButton`, `DropperState`), the Eyedropper's options and ring, Color Sampler points, the screen colour picker (`ScreenColorPicker`), `ColorChoice`, `PaintChip` and `PaintList` (with their `PaintKindLabels` and `PaintListLabels`), the Color and Swatches panels (`ColorPanel`, `SwatchesPanel`), the profile mismatch prompt, the harmony wheel and Color Guide panel, and the `LutPicker`.
Colour for Craft apps. With the `ui` feature, `craft_color::ui` has the colour picker (`ColorPicker`, `ColorPopover`, `ColorArea`, `ColorStrip`, `ColorWheel`, `ColorDisc`, `ColorRamp`), the wells (`SwatchPair`, `Well`), `SwatchPalette` tables and the `HexField`. It also has the colour features built on them: the Color Picker dialog (`ColorPickerDialog`), dialog droppers (`DropperButton`, `DropperState`), the Eyedropper's options and ring, Color Sampler points, the screen colour picker (`ScreenColorPicker`), `ColorChoice`, `PaintChip` and `PaintList` (with their `PaintKindLabels` and `PaintListLabels`), the Color and Swatches panels (`ColorPanel`, `SwatchesPanel`), the Info panel (`InfoPanel`), the HUD Color Picker over a canvas (`ColorHud`), the profile mismatch prompt, the harmony wheel and Color Guide panel, the `LutPicker`, and `ui::gradient` (`GradientEditor`, `GradientStops`, the stop rules, `GradientRamp`).
Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, samplers, paint-chip, choice, harmony, lut-picker, profile-mismatch}` show each of those features in its states. The two dialogs run on a `DialogHost` (a "Show dialog" button in an Overview tile). The screen eyedropper is off in the stories, so none starts a screen capture.
+37 -22
View File
@@ -2,7 +2,7 @@
use super::channels::{QUANTIZE_CELLS, channel_range, channel_step, quantized, settled, snapped, spoken};
use crate::AreaMode;
use craft_behavior::{Metrics, Mixed, Sense};
use craft_behavior::{Metrics, Mixed, Proposal, Sense};
use craft_theme::ModelValues;
use craft_ui::contract::{
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, Sizing, WordSetCx as _,
@@ -11,7 +11,7 @@ use craft_ui::primitives::ContentPainterCx;
use craft_ui::runtime::env::Label;
use craft_ui::style::{ComponentStyle, StyleCx};
use craft_ui::value_drag::{PointMark, PointPicker};
use egui::{Mesh, Rect, Vec2, pos2};
use egui::{Mesh, Pos2, Rect, Vec2, pos2};
#[cfg(feature = "screen-testing")]
mod stories;
@@ -75,10 +75,32 @@ impl<'a> ColorArea<'a> {
/// The values the pointer at `at` picks in `rect`: the picker's own point-to-value mapping, then the settle and
/// quantise steps. `ColorHud` drives it with the host's pointer.
#[allow(dead_code)] // P3(panels-w7): pn.C32
pub(crate) fn value_at(&self, rect: Rect, values: &ModelValues, at: egui::Pos2) -> ModelValues {
let _ = (rect, values, at);
todo!("pn.C32")
pub(crate) fn value_at(&self, rect: Rect, values: &ModelValues, at: Pos2) -> ModelValues {
let mut mine = *values;
if let Some(point) = self.picker(Some(values), false).value_at(rect, at) {
self.settle_into(&mut mine, point.map(Some));
}
mine
}
/// Where `values` stands in `rect`: the picker's own value-to-point mapping.
pub(crate) fn point_in(&self, rect: Rect, values: &ModelValues) -> Pos2 {
let [across, down] = self.channels();
self.picker(Some(values), false).position([values.values[across], values.values[down]].map(f64::from), rect)
}
/// Writes the area's two components from `point` (an axis that is `None` stays) onto `mine`, settled on the
/// channel's step and then on the quantised colour: the one rule for what the area reports.
fn settle_into(&self, mine: &mut ModelValues, point: [Option<f64>; 2]) {
let model = self.mode.model();
for (channel, value) in self.channels().into_iter().zip(point) {
if let Some(value) = value {
mine.values[channel] = settled(model, channel, value as f32);
}
}
if let Some(levels) = self.levels() {
*mine = quantized(model, mine, levels);
}
}
/// The picker over `shown`, whose backdrop paints the field of `base`.
@@ -127,9 +149,14 @@ impl Component for ColorArea<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
// An area that fills its room (the Color panel's, as tall as its group leaves it) keeps no plot size of its own.
// An area that fills its room (the Color panel's, as tall as its group leaves it) is at least a hit target and
// square on the width it is offered.
if cx.resolved.sizing() == Some(Sizing::Fill) {
return Vec2::splat(cx.tokens.size.hit.target);
return match cx.proposal {
Proposal::Min => Vec2::splat(cx.tokens.size.hit.target),
Proposal::Width(width) | Proposal::Size(Vec2 { x: width, .. }) => Vec2::splat(width),
_ => Vec2::splat(cx.tokens.size.plot.width),
};
}
let mut picker = self.picker(cx.value(), false);
cx.child("picker", &mut picker, cx.proposal)
@@ -152,22 +179,10 @@ impl Component for ColorArea<'_> {
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let model = self.mode.model();
let [across, down] = self.channels();
let picker = self.picker(cx.value(), true).label(cx.label());
let edit = ui.inner("picker", cx.rect, picker);
let levels = self.levels();
let start = ModelValues::new(model.id(), &[]);
cx.adopt(&edit, &start, |point, mine| {
for (channel, axis) in [(across, 0), (down, 1)] {
if let Some(value) = point[axis].same() {
mine.values[channel] = settled(model, channel, *value as f32);
}
}
if let Some(levels) = levels {
*mine = quantized(model, mine, levels);
}
});
let start = ModelValues::new(self.mode.model().id(), &[]);
cx.adopt(&edit, &start, |point, mine| self.settle_into(mine, [0, 1].map(|axis| point[axis].same().copied())));
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<ModelValues> {
+224 -15
View File
@@ -1,18 +1,92 @@
//! [`ColorHud`]: the colour area and hue strip in a popover at a point, driven by the host's press.
use craft_behavior::EditEvents;
use super::strip;
use super::{ColorArea, ColorStrip};
use crate::AreaMode;
use craft_behavior::{EditEvents, Metrics, Sense};
use craft_theme::Srgba;
use craft_ui::contract::{Bind, Pattern};
use craft_ui::runtime::env::Label;
use craft_ui::contract::{
Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, EscapeEdit, MeasureCx, Outcome, PaintUi, Pattern, Props as _, Role,
Show as _, ShowContainer as _,
};
use craft_ui::popover::Popover;
use craft_ui::runtime::env::{Env, Label};
use craft_ui::runtime::overlay::CloseReason;
use egui::{Pos2, Response, Ui};
use craft_ui::style::{ComponentStyle, StyleCx, UiTokens};
use egui::{Pos2, Rect, Response, Ui, Vec2, pos2, vec2};
#[cfg(feature = "screen-testing")]
mod stories;
/// The model the HUD picks in: saturation and brightness across and down, hue in the strip.
const MODE: AreaMode = AreaMode::Hue;
/// The colour of a HUD whose binding shows none.
const BLACK: Srgba = Srgba::rgb(0.0, 0.0, 0.0);
/// The sizes of the HUD's content, from tokens, so that nothing is measured in an earlier pass: the area is a plot
/// square, the strip stands to its right.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Geometry {
plot: f32,
strip_width: f32,
gap: f32,
}
impl Geometry {
fn of(tokens: &UiTokens) -> Self {
// The strip's colours are `size.icon.lg` wide with a pointer triangle's room on each side (its own padding).
Geometry { plot: tokens.size.plot.width, strip_width: tokens.size.icon.lg + 2.0 * tokens.size.handle.sm, gap: tokens.space.gap.inline }
}
fn size(self) -> Vec2 {
vec2(self.plot + self.gap + self.strip_width, self.plot)
}
/// The area's rect in content whose top left is `min`.
fn area(self, min: Pos2) -> Rect {
Rect::from_min_size(min, Vec2::splat(self.plot))
}
/// The strip's rect in content whose top left is `min`.
fn strip(self, min: Pos2) -> Rect {
Rect::from_min_size(pos2(min.x + self.plot + self.gap, min.y), vec2(self.strip_width, self.plot))
}
}
/// Where the popover hangs so that the start colour's point in the area sits at `at`.
struct Placement {
/// The popover's top left.
origin: Pos2,
/// The top left of its content.
content: Pos2,
geometry: Geometry,
}
impl Placement {
fn of(tokens: &UiTokens, at: Pos2, start: Option<Srgba>) -> Self {
let geometry = Geometry::of(tokens);
let area = geometry.area(Pos2::ZERO);
let point = match start {
Some(color) => {
let values = MODE.model().from_srgb(color);
ColorArea::new("", MODE, Bind::given(values)).point_in(area, &values)
}
None => area.center(),
};
// The popover's padding is the popup padding (`POPUP_PAD`, the control pad).
let pad = tokens.space.pad.control;
Placement { origin: pos2(at.x - pad - point.x, at.y - pad - point.y), content: pos2(at.x - point.x, at.y - point.y), geometry }
}
}
/// The area and hue strip in a popover at `at`, with the start colour under it, driven by the host's press: the pick
/// maps `pointer` through `ColorArea` and the strip's `value_at`; no pick while `pointer` is still `at`; one gesture
/// per open; Escape or `held(false)` commits and closes. Every input is a prop of the pass; the HUD keeps no state.
///
/// The host shows the HUD while its press is held and stops showing it once `closed` is reported.
#[must_use = "show the HUD with `show`"]
#[derive(Pattern)]
#[allow(dead_code)] // P3(panels-w7): pn.C31
pub struct ColorHud<'a> {
label: Label,
at: Pos2,
@@ -25,35 +99,48 @@ pub struct ColorHud<'a> {
impl<'a> ColorHud<'a> {
/// A HUD named `label` at `at` over `color`.
pub fn new(label: impl Into<Label>, at: Pos2, color: Bind<'a, Srgba>) -> Self {
let _ = (label.into(), at, color);
todo!("pn.C31")
ColorHud { label: label.into(), at, color, start: None, pointer: None, held: true }
}
/// The colour under `at` when the host's press began; the popover is placed so this colour's point sits at `at`.
/// Without it the area's middle sits at `at`.
#[must_use]
pub fn start(mut self, color: Srgba) -> Self {
let _ = (&mut self, color);
todo!("pn.C31")
self.start = Some(color);
self
}
/// The host's pointer, or `None` while it has none.
#[must_use]
pub fn pointer(mut self, at: Option<Pos2>) -> Self {
let _ = (&mut self, at);
todo!("pn.C31")
self.pointer = at;
self
}
/// Whether the host's press is still held.
#[must_use]
pub fn held(mut self, held: bool) -> Self {
let _ = (&mut self, held);
todo!("pn.C31")
self.held = held;
self
}
/// Draws the HUD.
pub fn show(self, ui: &mut Ui) -> ColorHudOutput {
let _ = (self, ui);
todo!("pn.C31")
let ColorHud { label, at, mut color, start, pointer, held } = self;
let placement = Placement::of(&Env::of(ui).tokens, at, start);
let shown = Popover::new(label.clone(), Bind::given(true)).at_point(placement.origin).show(ui, |ui, body| {
// A released press closes the HUD; the pick below commits in this same pass.
if !held {
body.request_close();
}
let live = held && body.is_open();
HudPick::new(label.clone(), color.reborrowed(), at, pointer, live).show(ui)
});
let events = match shown.inner {
Some(edit) => edit.events,
None => EditEvents::new(),
};
ColorHudOutput { response: shown.output.response, events, closed: shown.output.closed }
}
}
@@ -68,3 +155,125 @@ pub struct ColorHudOutput {
/// Why it closed this pass.
pub closed: Option<CloseReason>,
}
impl Outcome for ColorHudOutput {
type Value = Srgba;
fn response(&self) -> &Response {
&self.response
}
#[cfg(feature = "screen-testing")]
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
self.response.story_facts()
}
}
/// The style of the HUD's picking content: its sizes.
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
struct HudPickStyle {
#[style(metrics)]
metrics: Metrics,
plot: f32,
strip_width: f32,
gap: f32,
}
impl HudPickStyle {
fn geometry(&self) -> Geometry {
Geometry { plot: self.plot, strip_width: self.strip_width, gap: self.gap }
}
}
/// The HUD's value component: it shows the area and the strip and owns the colour's gesture. The gesture slot belongs
/// to a value component, which drives it from its props (the host's pointer and press) instead of a press of its own:
/// the first pick begins it, later picks update it, and the host's release or the popover's close commits it. Escape
/// commits too, so the colour stays.
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
struct HudPick<'a> {
#[common]
common: Common,
color: Bind<'a, Srgba>,
at: Pos2,
pointer: Option<Pos2>,
/// Whether the press is held and the popover open.
live: bool,
}
impl<'a> HudPick<'a> {
fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, at: Pos2, pointer: Option<Pos2>, live: bool) -> Self {
HudPick { common: Common::new(), color, at, pointer, live }.label(label)
}
}
impl Component for HudPick<'_> {
const SINGLE_VALUE: bool = true;
const ROLE: Role = Role::GROUP;
const DISABLED: DisabledLook = DisabledLook::Faded;
const ESCAPE: EscapeEdit = EscapeEdit::Commit;
const PARTS: bool = false;
const STOPS: bool = false;
const OVERLAYS: bool = false;
type Style = HudPickStyle;
type Output = EditResponse<Srgba>;
fn style(cx: &StyleCx<'_>, _: HudPickStyleKey) -> HudPickStyle {
let geometry = Geometry::of(cx.tokens);
HudPickStyle { metrics: Metrics::new(), plot: geometry.plot, strip_width: geometry.strip_width, gap: geometry.gap }
}
fn sense(&self) -> Sense {
Sense::empty()
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
Geometry::of(cx.tokens).size()
}
fn bind(&mut self) -> Option<BindMut<'_, Srgba>> {
Some(self.color.reborrow())
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let running = cx.gesture().is_some();
if !self.live {
if running {
cx.commit();
}
return;
}
// The press that opened the HUD picks nothing until the pointer leaves `at`, unless a gesture already runs.
let Some(pointer) = self.pointer.filter(|pointer| *pointer != self.at || running) else { return };
let geometry = cx.style.geometry();
let (area, strip) = (geometry.area(cx.rect.min), geometry.strip(cx.rect.min));
let current = cx.value().copied().unwrap_or(BLACK);
let values = MODE.model().from_srgb(current);
let picked = if area.contains(pointer) {
Some(ColorArea::new("", MODE, Bind::given(values)).value_at(area, &values, pointer))
} else if strip.contains(pointer) {
Some(strip::value_at(strip, MODE, &values, pointer))
} else {
None
};
let Some(picked) = picked else { return };
let mut next = MODE.model().to_srgb(&picked.values);
next.a = current.a;
if next != current {
cx.propose(next);
}
}
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
let geometry = cx.style.geometry();
let model = MODE.model();
let values = model.from_srgb(cx.value().copied().unwrap_or(BLACK));
let area = ColorArea::new(Label::from(MODE.name()), MODE, Bind::given(values));
let _ = ui.inner("area", geometry.area(cx.rect.min), area);
let strip = ColorStrip::new(Label::from(model.channels()[MODE.strip()].name.to_owned()), MODE, Bind::given(values));
let _ = ui.inner("strip", geometry.strip(cx.rect.min), strip);
}
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<Srgba> {
cx.edit_response()
}
}
+23
View File
@@ -0,0 +1,23 @@
//! Stories of `ColorHud`: open with a start colour, and with the pointer moved onto the strip.
use super::{ColorHud, Placement};
use craft_theme::Srgba;
use craft_ui::contract::Bind;
use craft_ui::runtime::env::Env;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::{Ui, pos2};
const START: Srgba = Srgba::rgb(0.4, 0.6, 0.8);
#[story(ColorHud<'static>, covers = [Default], drive = Drive::Never)]
fn color_hud(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
ColorHud::new("Color HUD", pos2(260.0, 200.0), Bind::given(START)).start(START).pointer(Some(pos2(260.0, 200.0))).show(ui).into()
}
#[story(ColorHud<'static>, covers = [], drive = Drive::Never)]
fn color_hud_pointer_on_the_strip(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
let at = pos2(260.0, 200.0);
let placement = Placement::of(&Env::of(ui).tokens, at, Some(START));
let pointer = placement.geometry.strip(placement.content).center();
ColorHud::new("Color HUD", at, Bind::given(START)).start(START).pointer(Some(pointer)).show(ui).into()
}
+81 -22
View File
@@ -2,12 +2,22 @@
use craft_cms::convert::CmykConverter;
use craft_theme::Srgba;
use craft_ui::contract::Pattern;
use craft_ui::runtime::env::Label;
use craft_theme::variant::Tone;
use craft_ui::contract::{Outcome as _, Pattern, Props as _, Show as _, ShowContainer as _};
use craft_ui::display::Text;
use craft_ui::layout_components::{Row, Stack};
use craft_ui::notices::{Notice, NoticeLayout};
use craft_ui::runtime::env::{Env, Label};
use egui::{Response, Ui};
use super::SamplerReadout;
#[cfg(feature = "screen-testing")]
mod stories;
/// What a missing value shows.
const DASH: &str = "–";
craft_ui::words! {
/// The words of the Info panel, in the installed language unless set.
pub struct InfoWords {
@@ -23,7 +33,7 @@ craft_ui::words! {
w: "info.w" = "W";
h: "info.h" = "H";
/// The document size template.
document: "info.document" = "Doc: {width} x {height}";
document: template "info.document" = "Doc: {width} x {height}";
no_document: "info.noDocument" = "No document";
}
}
@@ -39,10 +49,11 @@ pub struct InfoColor {
impl InfoColor {
/// `color` through the document's CMYK converter: the one sRGB-and-CMYK conversion, which `SamplerReadout::new` builds
/// its `rgb` and `cmyk` through.
/// its `rgb` and `cmyk` through. A channel that is not finite reads as 0 and the rest is clamped.
pub fn new(color: Srgba, cmyk: &CmykConverter) -> Self {
let _ = (color, cmyk);
todo!("pn.C33")
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
let rgb = [color.r, color.g, color.b].map(unit);
InfoColor { rgb: rgb.map(|v| (v * 255.0).round() as u8), cmyk: cmyk.from_srgb(rgb).map(|v| (unit(v) * 100.0).round() as u8) }
}
}
@@ -65,42 +76,42 @@ pub struct InfoReadings<'a> {
impl<'a> InfoReadings<'a> {
/// Readings with nothing in them.
pub fn new() -> Self {
todo!("pn.C33")
Self::default()
}
/// Sets the colour.
#[must_use]
pub fn color(mut self, color: Option<InfoColor>) -> Self {
let _ = (&mut self, color);
todo!("pn.C33")
self.color = color;
self
}
/// Sets the position.
#[must_use]
pub fn position(mut self, position: Option<[Label; 2]>) -> Self {
let _ = (&mut self, position);
todo!("pn.C33")
self.position = position;
self
}
/// Sets the extent.
#[must_use]
pub fn extent(mut self, extent: Option<[Label; 2]>) -> Self {
let _ = (&mut self, extent);
todo!("pn.C33")
self.extent = extent;
self
}
/// Sets the document size.
#[must_use]
pub fn document(mut self, document: Option<[u32; 2]>) -> Self {
let _ = (&mut self, document);
todo!("pn.C33")
self.document = document;
self
}
/// Sets the samplers.
#[must_use]
pub fn samplers(mut self, samplers: &'a [(SamplerReadout, [Label; 2])]) -> Self {
let _ = (&mut self, samplers);
todo!("pn.C33")
self.samplers = samplers;
self
}
}
@@ -108,22 +119,70 @@ impl<'a> InfoReadings<'a> {
/// missing value; `document: None` shows "No document" as a centred notice in place of the grid.
#[must_use = "show the panel with `show`"]
#[derive(Pattern)]
#[allow(dead_code)] // P3(panels-w7): pn.C33
pub struct InfoPanel<'a> {
label: Label,
readings: &'a InfoReadings<'a>,
}
/// A name and its value, or `None` for a dash.
type Cell = (Label, Option<Label>);
/// The value of a number, or `None` when it is missing.
fn number(value: Option<impl ToString>) -> Option<Label> {
value.map(|value| Label::from(value.to_string()))
}
/// One line of name and value pairs.
fn line(ui: &mut Ui, cells: Vec<Cell>) {
Row::new().show(ui, |ui, _| {
for (name, value) in cells {
Text::new(name).show(ui);
Text::new(value.unwrap_or_else(|| Label::from(DASH))).show(ui);
}
});
}
impl<'a> InfoPanel<'a> {
/// A panel named `label` over `readings`.
pub fn new(label: impl Into<Label>, readings: &'a InfoReadings<'a>) -> Self {
let _ = (label.into(), readings);
todo!("pn.C33")
InfoPanel { label: label.into(), readings }
}
/// Draws the grid.
pub fn show(self, ui: &mut Ui) -> Response {
let _ = (self, ui);
todo!("pn.C33")
let InfoPanel { label, readings } = self;
let words = Env::of(ui).words::<InfoWords>();
let Some([width, height]) = readings.document else {
return Notice::new(Tone::Neutral, words.no_document.clone()).layout(NoticeLayout::Centred).show(ui).response().clone();
};
let name = |label: &Label| -> Label { label.clone() };
let rgb_names = [name(&words.r), name(&words.g), name(&words.b)];
let cmyk_names = [name(&words.c), name(&words.m), name(&words.y), name(&words.k)];
Stack::new()
.label(label)
.show(ui, |ui, _| {
for (at, cmyk_name) in cmyk_names.iter().enumerate() {
let mut cells = Vec::new();
if let Some(rgb_name) = rgb_names.get(at) {
cells.push((rgb_name.clone(), number(readings.color.map(|color| color.rgb[at]))));
}
cells.push((cmyk_name.clone(), number(readings.color.map(|color| color.cmyk[at]))));
line(ui, cells);
}
let (position, extent) = (readings.position.as_ref(), readings.extent.as_ref());
let axes = [(name(&words.x), name(&words.w)), (name(&words.pos_y), name(&words.h))];
for (axis, (position_name, extent_name)) in axes.into_iter().enumerate() {
line(ui, vec![(position_name, position.map(|at| at[axis].clone())), (extent_name, extent.map(|size| size[axis].clone()))]);
}
let size = words.document.fill(&[("width", &width.to_string()), ("height", &height.to_string())]);
Text::new(Label::from(size)).show(ui);
for (readout, position) in readings.samplers {
Text::new(Label::from(format!("#{}", readout.number))).show(ui);
line(ui, vec![(name(&words.x), Some(position[0].clone())), (name(&words.pos_y), Some(position[1].clone()))]);
line(ui, rgb_names.iter().zip(readout.rgb).map(|(name, value)| (name.clone(), number(Some(value)))).collect());
line(ui, cmyk_names.iter().zip(readout.cmyk).map(|(name, value)| (name.clone(), number(Some(value)))).collect());
}
})
.output
}
}
+38
View File
@@ -0,0 +1,38 @@
//! Stories of `InfoPanel`: a full reading with two samplers, readings with every value missing, and no document.
use super::{InfoColor, InfoPanel, InfoReadings};
use crate::ui::SamplerReadout;
use craft_ui::runtime::env::Label;
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
use egui::Ui;
fn pair(x: &str, y: &str) -> [Label; 2] {
[Label::from(x), Label::from(y)]
}
#[story(InfoPanel<'static>, covers = [Default], drive = Drive::Never)]
fn info_panel(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
let samplers = [
(SamplerReadout::from_values(1, [120, 80], [255, 128, 0], [0, 50, 100, 0]), pair("120", "80")),
(SamplerReadout::from_values(2, [300, 41], [10, 20, 30], [67, 33, 0, 88]), pair("300", "41")),
];
let readings = InfoReadings::new()
.color(Some(InfoColor { rgb: [64, 128, 192], cmyk: [67, 33, 0, 25] }))
.position(Some(pair("512", "384")))
.extent(Some(pair("200", "100")))
.document(Some([1920, 1080]))
.samplers(&samplers);
InfoPanel::new("Info", &readings).show(ui).into()
}
#[story(InfoPanel<'static>, covers = [], drive = Drive::Never)]
fn info_panel_missing_values(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
let readings = InfoReadings::new().document(Some([1920, 1080]));
InfoPanel::new("Info", &readings).show(ui).into()
}
#[story(InfoPanel<'static>, covers = [], drive = Drive::Never)]
fn info_panel_no_document(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput {
let readings = InfoReadings::new();
InfoPanel::new("Info", &readings).show(ui).into()
}
+4 -3
View File
@@ -2,8 +2,9 @@
//!
//! - Fields and strips of a colour model: [`ColorArea`], [`ColorStrip`], [`ColorRamp`], [`ColorDisc`], [`ColorWheel`].
//! - The picker: [`ColorPicker`], its popover and dialog, the hex and readout fields, the choice list and the droppers.
//! - Wells and paints: [`SwatchPair`], [`PaintChip`], [`PaintList`], [`SwatchPalette`], [`SwatchTable`].
//! - Panels: [`ColorPanel`], [`HarmonyPanel`], [`SwatchesPanel`].
//! - Wells and paints: [`SwatchPair`], [`PaintChip`], [`PaintList`], [`SwatchPalette`], `craft_ui::choice::SwatchTable`.
//! - Panels: [`ColorPanel`], [`HarmonyPanel`], [`SwatchesPanel`], [`InfoPanel`]; over a canvas: [`ColorHud`].
//! - Gradients: the [`gradient`] module (`GradientEditor`, `GradientStops`, the stop rules, `GradientRamp`).
//! - Sampling: the eyedropper, colour samplers and the screen picker.
//! - Imaging prompts: [`LutPicker`] and [`ProfileMismatchDialog`].
//!
@@ -64,7 +65,7 @@ pub use paint_chip::{
PaintListOptions, PaintListOutput, PaintRow, PaintWords,
};
pub use pair::{PairWell, SwatchPair, SwatchPairOutput, Well};
pub use palette::{SwatchPalette, SwatchPaletteOutput, SwatchRows, SwatchTable, SwatchTableOutput, SwatchTableStyle};
pub use palette::{SwatchPalette, SwatchPaletteOutput};
pub use panel::{
ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelState, ColorPanelWords, PanelTarget,
};
+29 -17
View File
@@ -82,14 +82,7 @@ impl<'a> ColorStrip<'a> {
/// `values` with the strip's component set to `value`, on its step and the quantised colour.
fn with(&self, values: &ModelValues, value: f64) -> ModelValues {
let model = self.mode.model();
let channel = self.mode.strip();
let mut out = *values;
out.values[channel] = settled(model, channel, value as f32);
match self.levels() {
Some(levels) => quantized(model, &out, levels),
None => out,
}
with_value(self.mode, self.levels(), values, value)
}
/// The value after the key `mv` held with `mods`, from `values`; a quantising strip steps again until the colour
@@ -171,13 +164,11 @@ impl Component for ColorStrip<'_> {
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let model = self.mode.model();
let channel = self.mode.strip();
let drag = ValueDrag::absolute(cx.rect.bottom()..cx.rect.top(), channel_range(model, channel)).axis(Axis::Y);
let start_values = ModelValues::new(model.id(), &[]);
let (rect, mode) = (cx.rect, self.mode);
let start_values = ModelValues::new(mode.model().id(), &[]);
let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or(start_values);
let base = current(&*cx);
cx.follow_press(STRIP, |pos| drag.at(pos, false).map(|value| self.with(&base, value)));
cx.follow_press(STRIP, |pos| picked(rect, mode, pos).map(|value| self.with(&base, value)));
// A running drag is one edit: keys and SetValue wait for it, and are still taken.
let running = cx.gesture().is_some();
while let Some((mv, mods)) = cx.intents().take_move() {
@@ -256,10 +247,31 @@ impl Component for ColorStrip<'_> {
}
}
/// The values the pointer at `at` picks in the strip's `rect` for `mode`: the `ValueDrag` mapping of `update`, which
/// The component value under the pointer at `at` in the strip's `rect`: the one point-to-value mapping, which `update`
/// and `value_at` share.
fn picked(rect: Rect, mode: AreaMode, at: Pos2) -> Option<f64> {
ValueDrag::absolute(rect.bottom()..rect.top(), channel_range(mode.model(), mode.strip())).axis(Axis::Y).at(at, false)
}
/// `values` with the strip component of `mode` set to `value` on its step, and on the quantised colour when `levels` is
/// given.
fn with_value(mode: AreaMode, levels: Option<usize>, values: &ModelValues, value: f64) -> ModelValues {
let model = mode.model();
let channel = mode.strip();
let mut out = *values;
out.values[channel] = settled(model, channel, value as f32);
match levels {
Some(levels) => quantized(model, &out, levels),
None => out,
}
}
/// The values the pointer at `at` picks in the strip's `rect` for `mode`, from `values`: the mapping of `update`, which
/// `ColorHud` drives with the host's pointer.
#[allow(dead_code)] // P3(panels-w7): pn.C32
// PLAN: the contract signature has no quantise levels, so this is the unquantised strip; `update` keeps its own levels.
pub(crate) fn value_at(rect: Rect, mode: AreaMode, values: &ModelValues, at: Pos2) -> ModelValues {
let _ = (rect, mode, values, at);
todo!("pn.C32")
match picked(rect, mode, at) {
Some(value) => with_value(mode, None, values, value),
None => *values,
}
}
+112 -1
View File
@@ -3,12 +3,14 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use craft_behavior::EditEvent;
use craft_color::AreaMode;
use craft_color::ui::{
ColorArea, ColorDisc, ColorRamp, DiscMove, RampKind, RampPick, WheelGeometry, hue_at, triangle_corners, triangle_point, triangle_sv,
ColorArea, ColorDisc, ColorHud, ColorRamp, DiscMove, RampKind, RampPick, WheelGeometry, hue_at, triangle_corners, triangle_point, triangle_sv,
};
use craft_theme::{ColorModel, HsbModel, ModelValues, Srgba};
use craft_ui::contract::{Bind, Show as _};
use craft_ui::runtime::overlay::CloseReason;
use craft_ui::testing::focus::AccessActionKind;
use craft_ui::testing::{Fixture, Story, StoryData, StoryOutput, trial};
use egui::{Key, Modifiers, Pos2, Rect, Ui, pos2, vec2};
@@ -147,3 +149,112 @@ fn alt_with_enter_on_the_ramp_picks_the_other_colour() {
press(&mut fixture, Key::Enter, Modifiers::ALT);
assert_eq!(*picks.borrow(), [false, true, true], "the white box: Alt+Enter");
}
/// Where the host's press began.
const HUD_AT: Pos2 = Pos2::new(300.0, 200.0);
/// A HUD whose host owns the press: it sets the pointer and the held state, and applies the HUD's edits to its colour.
struct HudRig {
fixture: Fixture,
pointer: Rc<Cell<Option<Pos2>>>,
held: Rc<Cell<bool>>,
color: Rc<Cell<Srgba>>,
events: Rc<RefCell<Vec<EditEvent<Srgba>>>>,
closed: Rc<RefCell<Vec<CloseReason>>>,
}
impl HudRig {
fn new(start: Srgba) -> Self {
let pointer = Rc::new(Cell::new(Some(HUD_AT)));
let (held, color) = (Rc::new(Cell::new(true)), Rc::new(Cell::new(start)));
let (events, closed) = (Rc::new(RefCell::new(Vec::new())), Rc::new(RefCell::new(Vec::new())));
let (p, h, c, e, x) = (pointer.clone(), held.clone(), color.clone(), events.clone(), closed.clone());
let mut fixture = Fixture::new(move |ui| {
let out = ColorHud::new("Color HUD", HUD_AT, Bind::given(c.get())).start(start).pointer(p.get()).held(h.get()).show(ui);
for event in out.events {
if let EditEvent::Update { value, .. } = &event {
c.set(*value);
}
e.borrow_mut().push(event);
}
if let Some(reason) = out.closed {
x.borrow_mut().push(reason);
}
});
fixture.room(vec2(600.0, 400.0));
fixture.settle();
HudRig { fixture, pointer, held, color, events, closed }
}
fn count(&self, which: impl Fn(&EditEvent<Srgba>) -> bool) -> usize {
self.events.borrow().iter().filter(|event| which(event)).count()
}
/// Moves the host's pointer to `to` and runs the passes that see it.
fn move_to(&mut self, to: Pos2) {
self.pointer.set(Some(to));
self.fixture.idle(2);
}
fn hsb(&self) -> [f32; 3] {
let values = HsbModel.from_srgb(self.color.get()).values;
[values[0], values[1], values[2]]
}
}
/// The HUD maps the host's pointer through its own parts: the start colour's point sits under `at`, the pointer resting
/// at `at` picks nothing, moving over the area and then the strip picks there, one gesture covers the whole open, and
/// the host's release commits and closes with the colour kept.
#[trial]
fn color_hud_follows_the_hosts_press() {
// Hue 210, saturation 50, brightness 80.
let start = Srgba::rgb(0.4, 0.6, 0.8);
let mut rig = HudRig::new(start);
let area = rig.fixture.by_label(AreaMode::Hue.name()).expect("the area").rect;
let strip = rig.fixture.by_label("Hue").expect("the strip").rect;
assert!((area.left() + 0.5 * area.width() - HUD_AT.x).abs() < 2.0, "the start colour's saturation is under `at` across");
assert!((area.top() + 0.2 * area.height() - HUD_AT.y).abs() < 2.0, "and its brightness down");
rig.fixture.idle(2);
assert!(rig.events.borrow().is_empty(), "no edit while the pointer rests at `at`");
rig.move_to(area.center());
let [hue, saturation, brightness] = rig.hsb();
assert!((hue - 210.0).abs() < 3.0, "the area leaves the hue: {hue}");
assert!((saturation - 50.0).abs() < 3.0, "the area's middle across is half saturation: {saturation}");
assert!((brightness - 50.0).abs() < 3.0, "the area's middle down is half brightness: {brightness}");
rig.move_to(strip.center());
let [hue, saturation, brightness] = rig.hsb();
assert!((hue - 180.0).abs() < 3.0, "the strip's middle is half the hue range: {hue}");
assert!((saturation - 50.0).abs() < 3.0 && (brightness - 50.0).abs() < 3.0, "the strip leaves the rest: {saturation}, {brightness}");
assert_eq!(rig.count(|event| matches!(event, EditEvent::Begin { .. })), 1, "one gesture per open");
assert_eq!(rig.count(|event| matches!(event, EditEvent::Commit { .. })), 0, "it runs while the press is held");
let picked = rig.color.get();
rig.held.set(false);
rig.fixture.idle(2);
assert_eq!(rig.count(|event| matches!(event, EditEvent::Commit { .. })), 1, "the release commits");
assert_eq!(rig.count(|event| matches!(event, EditEvent::Cancel { .. })), 0);
assert_eq!(rig.color.get(), picked, "the picked colour stays");
assert!(!rig.closed.borrow().is_empty(), "and the HUD reports that it closed");
}
/// Escape during the gesture keeps what was picked and closes the HUD.
#[trial]
fn color_hud_escape_keeps_the_picked_colour() {
let start = Srgba::rgb(0.4, 0.6, 0.8);
let mut rig = HudRig::new(start);
let area = rig.fixture.by_label(AreaMode::Hue.name()).expect("the area").rect;
rig.move_to(area.center());
let picked = rig.color.get();
assert_ne!(picked, start, "the pointer picked a colour");
rig.fixture.key(Key::Escape, Modifiers::NONE);
rig.fixture.idle(2);
assert_eq!(rig.count(|event| matches!(event, EditEvent::Begin { .. })), 1);
assert_eq!(rig.count(|event| matches!(event, EditEvent::Commit { .. })), 1, "Escape commits");
assert_eq!(rig.count(|event| matches!(event, EditEvent::Cancel { .. })), 0, "and does not revert");
assert_eq!(rig.color.get(), picked, "the picked colour stays");
assert!(!rig.closed.borrow().is_empty(), "and the HUD reports that it closed");
}
+2
View File
@@ -1,8 +1,10 @@
//! The screen tests of craft-color, folded into the lib's test target.
mod color_parts;
mod gradient_bar;
mod paint_list;
mod pair;
mod panels;
mod picker;
mod profile_prompts;
mod sampling;
@@ -135,11 +135,17 @@ pub struct PointPicker<'a> {
}
impl<'a> PointPicker<'a> {
/// The value pair at `pos` in `rect`: the plot, the two `ValueDrag`s and `point_at` in one function, which the drag
/// then calls, so the picker and the colour HUD share one mapping. `None` when the picker has no area.
/// The value pair at `pos` in `rect`, on the step grid: the plot, the two `ValueDrag`s and the settle in one
/// function, which the drag calls, so the picker and a host that maps its own pointer (the colour HUD) share one
/// mapping. Modifiers change nothing: the point is where the pointer is. `None` when the picker has no area.
pub fn value_at(&self, rect: Rect, pos: Pos2) -> Option<[f64; 2]> {
let _ = (rect, pos);
todo!("pn.C32")
let plot = self.plot(rect);
let drags = [
ValueDrag::absolute(plot.left()..plot.right(), self.along(0)),
ValueDrag::absolute(plot.top()..plot.bottom(), self.along(1)).axis(Axis::Y),
];
let axis = |axis: usize| drags[axis].at(pos, false).map(|value| self.settle(axis, value, self.grid(axis, false)));
Some([axis(0)?, axis(1)?])
}
/// The well: a press on it moves the point there, and a drag from it follows the pointer.
@@ -285,7 +291,7 @@ impl<'a> PointPicker<'a> {
}
/// Where `value` stands in `plot`.
fn position(&self, value: [f64; 2], plot: Rect) -> Pos2 {
pub fn position(&self, value: [f64; 2], plot: Rect) -> Pos2 {
let at = |axis: usize| {
let range = self.ranges()[axis];
let span = range.end() - range.start();
@@ -294,13 +300,6 @@ impl<'a> PointPicker<'a> {
};
pos2(plot.left() + at(0) * plot.width(), plot.top() + at(1) * plot.height())
}
/// The point under the pointer at `pos`, on the step grid. Modifiers change nothing: the point is where the
/// pointer is.
fn point_at(&self, drags: &[ValueDrag; 2], pos: Pos2) -> Option<[Mixed<f64>; 2]> {
let axis = |axis: usize| drags[axis].at(pos, false).map(|value| self.settle(axis, value, self.grid(axis, false)));
Some(Mixed::each([axis(0)?, axis(1)?]))
}
}
/// How far a key moves the point along its axis.
@@ -389,13 +388,9 @@ impl Component for PointPicker<'_> {
}
fn update(&mut self, cx: &mut Cx<'_, Self>) {
let plot = self.plot(cx.rect);
let drags = [
ValueDrag::absolute(plot.left()..plot.right(), self.along(0)),
ValueDrag::absolute(plot.top()..plot.bottom(), self.along(1)).axis(Axis::Y),
];
let rect = cx.rect;
for key in [THUMB, Self::WELL] {
cx.follow_press(key, |pos| self.point_at(&drags, pos));
cx.follow_press(key, |pos| self.value_at(rect, pos).map(Mixed::each));
}
let running = cx.gesture().is_some();
let mut now = cx.value().cloned().unwrap_or(ALL_MIXED);