mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-26 04:27:49 +00:00
widgets-w5: net change of 1 commits
- widgets-w5: written from its sheet
This commit is contained in:
+172
-49
@@ -4,7 +4,7 @@
|
||||
use super::channels::{finite, primary};
|
||||
use super::wheel::{hue_at, hue_direction, vertex};
|
||||
use craft_behavior::nav::{Arrows, NavShape, Roving};
|
||||
use craft_behavior::{CancelReason, HitShape, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_behavior::{CancelReason, HitShape, Metrics, NavMove, PartKey, PointerButton, PressPhase, Sense};
|
||||
use craft_theme::{ColorModel, HsbModel, ModelValues, Srgba};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Numeric, Outcome,
|
||||
@@ -36,12 +36,17 @@ const CENTRE: f32 = 0.5;
|
||||
/// Degrees a hue key moves, and percents a saturation key moves; Shift moves ten times as far.
|
||||
const KEY_STEP: f32 = 1.0;
|
||||
const FAR: f32 = 10.0;
|
||||
/// The segmented look: hue sectors round the disc, rings out from its centre, and the degrees one sector spans.
|
||||
const SECTORS: u32 = 24;
|
||||
const PATCH_RINGS: u32 = 5;
|
||||
const SECTOR_DEGREES: f32 = 15.0;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of colour discs.
|
||||
pub struct ColorDiscWords {
|
||||
marker: template "colorDisc.marker" = "Color {n}";
|
||||
value: template "colorDisc.value" = "Hue {hue} degrees, saturation {saturation} %";
|
||||
value_brightness: template "colorDisc.valueBrightness" = "Hue {hue} degrees, brightness {brightness} %";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,8 +115,9 @@ pub enum DiscRadius {
|
||||
/// The centre of the segmented patch at `hue` and `radial`, as `(hue, radial)`: sector `round(h/15) mod 24`, ring
|
||||
/// `floor(r*5).min(4)`.
|
||||
pub fn patch_at(hue: f32, radial: f32) -> (f32, f32) {
|
||||
let _ = (hue, radial);
|
||||
todo!("wg.W43")
|
||||
let sector = (finite(hue).rem_euclid(360.0) / SECTOR_DEGREES).round() as u32 % SECTORS;
|
||||
let ring = ((finite(radial).clamp(0.0, 1.0) * PATCH_RINGS as f32).floor() as u32).min(PATCH_RINGS - 1);
|
||||
(sector as f32 * SECTOR_DEGREES, (ring as f32 + 0.5) / PATCH_RINGS as f32)
|
||||
}
|
||||
|
||||
/// The style of a colour disc.
|
||||
@@ -220,6 +226,8 @@ pub struct ColorDisc<'a> {
|
||||
names: Vec<Label>,
|
||||
pressed: Option<usize>,
|
||||
grabbed: Option<usize>,
|
||||
clicked: Option<DiscHit>,
|
||||
context: Option<DiscHit>,
|
||||
}
|
||||
|
||||
impl<'a> ColorDisc<'a> {
|
||||
@@ -237,6 +245,8 @@ impl<'a> ColorDisc<'a> {
|
||||
names: Vec::new(),
|
||||
pressed: None,
|
||||
grabbed: None,
|
||||
clicked: None,
|
||||
context: None,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
@@ -257,20 +267,50 @@ impl<'a> ColorDisc<'a> {
|
||||
self.chosen.filter(|selected| *selected < self.markers.len()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Marker `index` as the host's colour places it: hue, saturation (0 to 1) and brightness.
|
||||
/// Marker `index` as the host's colour places it: hue, saturation and brightness (0 to 1).
|
||||
fn hsb(&self, index: usize) -> [f32; 3] {
|
||||
let values = self.markers.get(index).map_or([0.0; 3], |color| {
|
||||
let v = HsbModel.from_srgb(*color).values;
|
||||
[finite(v[0]), finite(v[1]), finite(v[2])]
|
||||
});
|
||||
[values[0], values[1] / 100.0, values[2]]
|
||||
[values[0], values[1] / 100.0, values[2] / 100.0]
|
||||
}
|
||||
|
||||
/// Marker `index` where the host has it.
|
||||
/// Marker `index` where the host has it: the radial channel is the one the radius shows.
|
||||
fn resting(&self, index: usize) -> DiscMove {
|
||||
let [hue, saturation, _] = self.hsb(index);
|
||||
DiscMove::new(index, hue, saturation)
|
||||
let [hue, saturation, brightness] = self.hsb(index);
|
||||
let radial = match self.radius {
|
||||
DiscRadius::Saturation => saturation,
|
||||
DiscRadius::Brightness => brightness,
|
||||
};
|
||||
DiscMove::new(index, hue, radial)
|
||||
}
|
||||
|
||||
/// The HSB values (degrees, percents) `moved` stands for: its radial channel on the radius's axis, the other
|
||||
/// channel the host's.
|
||||
fn values_of(&self, moved: &DiscMove) -> [f32; 3] {
|
||||
let [_, saturation, brightness] = self.hsb(moved.marker);
|
||||
match self.radius {
|
||||
DiscRadius::Saturation => [moved.hue, moved.radial * 100.0, brightness * 100.0],
|
||||
DiscRadius::Brightness => [moved.hue, saturation * 100.0, moved.radial * 100.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Where marker `index` lies as the host has it.
|
||||
fn place(&self, index: usize, center: Pos2, radius: f32) -> Pos2 {
|
||||
let at = self.resting(index);
|
||||
Self::marker_pos(center, radius, at.hue, at.radial)
|
||||
}
|
||||
|
||||
/// The channel the radius does not show, 0 to 1; never below a floor on a saturation disc.
|
||||
fn shown_level(&self) -> f32 {
|
||||
let level = if self.level.is_finite() { self.level.clamp(0.0, 1.0) } else { 1.0 };
|
||||
match self.radius {
|
||||
DiscRadius::Saturation => level.max(DISC_FLOOR),
|
||||
DiscRadius::Brightness => level,
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker focus is on.
|
||||
fn focused(&self, cx: &Cx<'_, Self>) -> Option<usize> {
|
||||
(0..self.markers.len()).find(|index| cx.active_part() == Some(MARKER.at(*index as u64)))
|
||||
@@ -314,7 +354,7 @@ impl Component for ColorDisc<'_> {
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let (center, radius) = Self::geometry(rect, cx.style.inset);
|
||||
cx.part(DISC, HitShape::circle(center, radius + cx.style.grab))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK)
|
||||
.pointer_only("the arrow keys move the marker");
|
||||
let stop = self.stop();
|
||||
for index in 0..self.markers.len() {
|
||||
@@ -322,7 +362,7 @@ impl Component for ColorDisc<'_> {
|
||||
Some(moved) => *moved,
|
||||
None => self.resting(index),
|
||||
};
|
||||
let reach = Marker::reach(&cx.style.marker, marker_size(self.chosen == Some(index)));
|
||||
let reach = Marker::reach(&cx.style.marker, marker_size(self.base == Some(index)));
|
||||
let part = cx.part(MARKER.at(index as u64), HitShape::circle(Self::marker_pos(center, radius, at.hue, at.radial), reach));
|
||||
// A marker takes no press of its own: the disc grabs the nearest.
|
||||
let part = part.focusable().focus_shape(FocusShape::Circle);
|
||||
@@ -342,18 +382,14 @@ impl Component for ColorDisc<'_> {
|
||||
let (center, radius) = Self::geometry(cx.rect, cx.style.inset);
|
||||
let grab_reach = cx.style.grab;
|
||||
let press = cx.part(DISC).press;
|
||||
let secondary = press.phase.start().is_some_and(|start| start.button == PointerButton::Secondary);
|
||||
if primary(&press) && matches!(press.phase, PressPhase::Down { .. }) {
|
||||
let origin = press.phase.start().map(|start| start.origin);
|
||||
let near = origin.and_then(|origin| {
|
||||
let distance = |index: usize| {
|
||||
let at = self.resting(index);
|
||||
Self::marker_pos(center, radius, at.hue, at.radial).distance(origin)
|
||||
};
|
||||
(0..self.markers.len()).map(|index| (index, distance(index))).filter(|(_, d)| *d <= grab_reach).min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
let near = press.phase.start().and_then(|start| {
|
||||
nearest_within((0..self.markers.len()).map(|index| self.place(index, center, radius).distance(start.origin)), grab_reach)
|
||||
});
|
||||
cx.memory::<Grab>().marker = near.map(|(index, _)| index);
|
||||
self.pressed = near.map(|(index, _)| index);
|
||||
if let Some((index, _)) = near {
|
||||
cx.memory::<Grab>().marker = near;
|
||||
self.pressed = near;
|
||||
if let Some(index) = near {
|
||||
cx.focus_part(MARKER.at(index as u64));
|
||||
}
|
||||
}
|
||||
@@ -364,7 +400,7 @@ impl Component for ColorDisc<'_> {
|
||||
if running && let Some(marker) = grabbed.filter(|marker| *marker < self.markers.len()) {
|
||||
let last = cx.memory::<Grab>().last.replace(self.markers[marker]);
|
||||
if let Some(moved) = cx.value().filter(|moved| moved.marker == marker) {
|
||||
let echo = HsbModel.to_srgb(&ModelValues::new("hsb", &[moved.hue, moved.radial * 100.0, self.hsb(marker)[2]]).values);
|
||||
let echo = HsbModel.to_srgb(&ModelValues::new("hsb", &self.values_of(moved)).values);
|
||||
if last.is_some_and(|last| last != self.markers[marker]) && !echo.same_rgb8(self.markers[marker]) {
|
||||
cx.cancel(CancelReason::HostChanged);
|
||||
}
|
||||
@@ -372,17 +408,7 @@ impl Component for ColorDisc<'_> {
|
||||
}
|
||||
let value_at = |cx: &Cx<'_, Self>, marker: usize, pos: Pos2| {
|
||||
let base = cx.value().filter(|moved| moved.marker == marker && cx.gesture().is_some()).copied().unwrap_or_else(|| self.resting(marker));
|
||||
let offset = pos - center;
|
||||
let mut out = base;
|
||||
if offset.length().is_finite() {
|
||||
out.radial = ((offset.length() / radius).clamp(0.0, 1.0) * 100.0).round() / 100.0;
|
||||
if offset.length() >= CENTRE
|
||||
&& let Some(hue) = hue_at(center, pos)
|
||||
{
|
||||
out.hue = hue;
|
||||
}
|
||||
}
|
||||
out
|
||||
moved_to(base, center, radius, pos)
|
||||
};
|
||||
if primary(&press)
|
||||
&& let Some(marker) = grabbed
|
||||
@@ -404,6 +430,20 @@ impl Component for ColorDisc<'_> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let PressPhase::Release { pos, click: true, .. } = press.phase {
|
||||
let point = moved_to(DiscMove::new(0, 0.0, 0.0), center, radius, pos);
|
||||
if primary(&press) {
|
||||
self.clicked = Some(DiscHit::new(grabbed, None, point.hue, point.radial));
|
||||
} else if secondary && pos.distance(center) <= radius {
|
||||
let places: Vec<Pos2> = (0..self.markers.len()).map(|index| self.place(index, center, radius)).collect();
|
||||
let marker = nearest_within(places.iter().map(|place| place.distance(pos)), grab_reach);
|
||||
let spoke = match marker {
|
||||
Some(_) => None,
|
||||
None => nearest_within(places.iter().map(|place| segment_distance(center, *place, pos)), grab_reach),
|
||||
};
|
||||
self.context = Some(DiscHit::new(marker, spoke, point.hue, point.radial));
|
||||
}
|
||||
}
|
||||
if matches!(press.phase, PressPhase::Release { .. } | PressPhase::Cancel { .. }) {
|
||||
*cx.memory::<Grab>() = Grab::default();
|
||||
}
|
||||
@@ -446,20 +486,36 @@ impl Component for ColorDisc<'_> {
|
||||
None => words.marker.fill(&[("n", (index + 1).to_string().as_str())]),
|
||||
};
|
||||
let hue = format!("{:.0}", live.hue.rem_euclid(360.0));
|
||||
let saturation = format!("{:.0}", live.radial * 100.0);
|
||||
let radial = format!("{:.0}", live.radial * 100.0);
|
||||
let node = access.node(MARKER.at(index as u64), Role::SLIDER);
|
||||
node.name = Name::Text(name);
|
||||
let text = words.value.fill(&[("hue", hue.as_str()), ("saturation", saturation.as_str())]);
|
||||
let text = match self.radius {
|
||||
DiscRadius::Saturation => words.value.fill(&[("hue", hue.as_str()), ("saturation", radial.as_str())]),
|
||||
DiscRadius::Brightness => words.value_brightness.fill(&[("hue", hue.as_str()), ("brightness", radial.as_str())]),
|
||||
};
|
||||
node.numeric = Some(Numeric::new(f64::from(live.hue.rem_euclid(360.0)), 0.0..=360.0).step(f64::from(KEY_STEP)).wraps(true).text(text));
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let (center, radius) = Self::geometry(cx.rect, cx.style.inset);
|
||||
let brightness = if self.level.is_finite() { self.level.clamp(0.0, 1.0).max(DISC_FLOOR) } else { 1.0 };
|
||||
let level = self.shown_level();
|
||||
let painter = ui.content_painter(cx);
|
||||
painter.painter.add(disc_mesh(center, radius, brightness));
|
||||
let patches = match self.look {
|
||||
DiscLook::Segmented => {
|
||||
let (mesh, edges) = patch_mesh(center, radius, level, self.radius);
|
||||
painter.painter.add(mesh);
|
||||
edges
|
||||
}
|
||||
_ => {
|
||||
painter.painter.add(disc_mesh(center, radius, level, self.radius));
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let draw = ui.draw();
|
||||
for edge in patches {
|
||||
draw.stroke(&PaintShape::Polygon(edge), StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, cx.style.edge);
|
||||
let places: Vec<Pos2> = (0..self.markers.len())
|
||||
.map(|index| {
|
||||
@@ -470,30 +526,97 @@ impl Component for ColorDisc<'_> {
|
||||
for place in &places {
|
||||
draw.stroke(&PaintShape::Path(vec![center, *place]), StrokeWidth::Thin, cx.style.spoke);
|
||||
}
|
||||
let selected = self.chosen.filter(|selected| *selected < places.len());
|
||||
let order = (0..places.len()).filter(|index| Some(*index) != selected).chain(selected);
|
||||
let base = self.base.filter(|base| *base < places.len());
|
||||
let chosen = self.chosen.filter(|chosen| *chosen < places.len());
|
||||
// The base is drawn last, over the chosen marker, over the rest.
|
||||
let order = (0..places.len())
|
||||
.filter(|index| Some(*index) != chosen && Some(*index) != base)
|
||||
.chain(chosen.filter(|chosen| Some(*chosen) != base))
|
||||
.chain(base);
|
||||
for index in order {
|
||||
let marker = Marker::filled(places[index], Color32::from(self.markers[index])).size(marker_size(Some(index) == selected));
|
||||
let marker = Marker::filled(places[index], Color32::from(self.markers[index]))
|
||||
.size(marker_size(Some(index) == base))
|
||||
.selected(Some(index) == chosen && Some(index) != base);
|
||||
draw.marker(&cx.style.marker, &marker);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorDiscOutput {
|
||||
let (pressed, grabbed) = (self.pressed, self.grabbed);
|
||||
ColorDiscOutput { edit: cx.edit_response(), pressed, grabbed, clicked: None, context: None }
|
||||
let (pressed, grabbed, clicked, context) = (self.pressed, self.grabbed, self.clicked, self.context);
|
||||
ColorDiscOutput { edit: cx.edit_response(), pressed, grabbed, clicked, context }
|
||||
}
|
||||
}
|
||||
|
||||
/// The disc at `brightness`: a centre vertex and rings out to the rim, hue around.
|
||||
fn disc_mesh(center: Pos2, radius: f32, brightness: f32) -> Mesh {
|
||||
/// `base` moved to the pointer at `pos`: the hue is the pointer's angle (kept at the centre), the radial channel its
|
||||
/// distance over `radius`, in whole percents.
|
||||
fn moved_to(base: DiscMove, center: Pos2, radius: f32, pos: Pos2) -> DiscMove {
|
||||
let offset = pos - center;
|
||||
let mut out = base;
|
||||
if offset.length().is_finite() {
|
||||
out.radial = ((offset.length() / radius).clamp(0.0, 1.0) * 100.0).round() / 100.0;
|
||||
if offset.length() >= CENTRE
|
||||
&& let Some(hue) = hue_at(center, pos)
|
||||
{
|
||||
out.hue = hue;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The index of the least of `distances` that is within `reach`.
|
||||
pub(super) fn nearest_within(distances: impl Iterator<Item = f32>, reach: f32) -> Option<usize> {
|
||||
distances.enumerate().filter(|(_, distance)| *distance <= reach).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// The distance from `p` to the segment `a` to `b`.
|
||||
fn segment_distance(a: Pos2, b: Pos2, p: Pos2) -> f32 {
|
||||
let along = b - a;
|
||||
let length_sq = along.length_sq();
|
||||
let t = if length_sq > 0.0 { ((p - a).dot(along) / length_sq).clamp(0.0, 1.0) } else { 0.0 };
|
||||
p.distance(a + along * t)
|
||||
}
|
||||
|
||||
/// The colour at `hue` and `radial` on a disc whose radius shows `kind`, the other channel at `level`.
|
||||
fn disc_color(kind: DiscRadius, hue: f32, radial: f32, level: f32) -> Color32 {
|
||||
let (saturation, brightness) = match kind {
|
||||
DiscRadius::Saturation => (radial, level),
|
||||
DiscRadius::Brightness => (level, radial),
|
||||
};
|
||||
vertex(hue, saturation * 100.0, brightness * 100.0)
|
||||
}
|
||||
|
||||
/// The segmented disc: a solid patch per sector and ring, centred on `patch_at`'s colour, and each patch's outline.
|
||||
fn patch_mesh(center: Pos2, radius: f32, level: f32, kind: DiscRadius) -> (Mesh, Vec<Vec<Pos2>>) {
|
||||
let mut mesh = Mesh::default();
|
||||
let b = brightness * 100.0;
|
||||
mesh.colored_vertex(center, vertex(0.0, 0.0, b));
|
||||
let mut edges = Vec::new();
|
||||
for sector in 0..SECTORS {
|
||||
for ring in 0..PATCH_RINGS {
|
||||
let (hue, radial) = patch_at(sector as f32 * SECTOR_DEGREES, (ring as f32 + 0.5) / PATCH_RINGS as f32);
|
||||
let color = disc_color(kind, hue, radial, level);
|
||||
let corners = [(-1.0, ring), (1.0, ring), (1.0, ring + 1), (-1.0, ring + 1)].map(|(side, edge)| {
|
||||
ColorDisc::marker_pos(center, radius, hue + side * SECTOR_DEGREES / 2.0, edge as f32 / PATCH_RINGS as f32)
|
||||
});
|
||||
let first = mesh.vertices.len() as u32;
|
||||
for corner in corners {
|
||||
mesh.colored_vertex(corner, color);
|
||||
}
|
||||
mesh.add_triangle(first, first + 1, first + 2);
|
||||
mesh.add_triangle(first, first + 2, first + 3);
|
||||
edges.push(corners.to_vec());
|
||||
}
|
||||
}
|
||||
(mesh, edges)
|
||||
}
|
||||
|
||||
/// The smooth disc at `level`: a centre vertex and rings out to the rim, hue around.
|
||||
fn disc_mesh(center: Pos2, radius: f32, level: f32, kind: DiscRadius) -> Mesh {
|
||||
let mut mesh = Mesh::default();
|
||||
mesh.colored_vertex(center, disc_color(kind, 0.0, 0.0, level));
|
||||
for ring in 1..=RINGS {
|
||||
let s = ring as f32 / RINGS as f32;
|
||||
for k in 0..SEGMENTS {
|
||||
let hue = k as f32 * 360.0 / SEGMENTS as f32;
|
||||
mesh.colored_vertex(ColorDisc::marker_pos(center, radius, hue, s), vertex(hue, s * 100.0, b));
|
||||
mesh.colored_vertex(ColorDisc::marker_pos(center, radius, hue, s), disc_color(kind, hue, s, level));
|
||||
}
|
||||
}
|
||||
let at = |ring: u32, k: u32| if ring == 0 { 0 } else { 1 + (ring - 1) * SEGMENTS + k % SEGMENTS };
|
||||
@@ -510,7 +633,7 @@ fn disc_mesh(center: Pos2, radius: f32, brightness: f32) -> Mesh {
|
||||
mesh
|
||||
}
|
||||
|
||||
/// The size of a marker: large while it is the selected one.
|
||||
fn marker_size(selected: bool) -> MarkerSize {
|
||||
if selected { MarkerSize::Large } else { MarkerSize::Regular }
|
||||
/// The size of a marker: large while it is the base.
|
||||
fn marker_size(base: bool) -> MarkerSize {
|
||||
if base { MarkerSize::Large } else { MarkerSize::Regular }
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `ColorDisc`: three markers with one selected.
|
||||
|
||||
use super::{ColorDisc, DiscMove, MARKER};
|
||||
use super::{ColorDisc, DiscLook, DiscMove, DiscRadius, MARKER};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
@@ -12,19 +12,37 @@ const MARKERS: [Srgba; 3] = [Srgba::rgb(0.9, 0.2, 0.2), Srgba::rgb(0.2, 0.7, 0.4
|
||||
#[story(ColorDisc<'static>, covers = [Default], drive = Drive::Drag(Grip::part(MARKER.at(1))))]
|
||||
fn color_disc(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let moved = data.value("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).chosen(1).show(ui).into()
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Segmented")]
|
||||
fn color_disc_segmented(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let moved = data.value("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).look(DiscLook::Segmented).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Brightness radius")]
|
||||
fn color_disc_brightness(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let moved = data.value("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).radius(DiscRadius::Brightness).level(0.8).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Base marker")]
|
||||
fn color_disc_base(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
// The base is large; the chosen marker, another one, wears the selection ring.
|
||||
let moved = data.value("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).base(0).chosen(2).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_disc_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
// P3(widgets-w5): wg.W43
|
||||
let refuse_pale = |moved: &DiscMove| if moved.radial < 0.5 { Validity::Refuse(Message::new("Too pale")) } else { Validity::Ok };
|
||||
let moved = Bind::bound(data.value("pale", DiscMove::new(1, 0.0, 0.2))).check(refuse_pale);
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).chosen(1).show(ui).into()
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Disabled")]
|
||||
fn color_disc_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let moved = data.value("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).chosen(1).enabled(false).show(ui).into()
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).base(1).chosen(1).enabled(false).show(ui).into()
|
||||
}
|
||||
|
||||
@@ -13,11 +13,13 @@ use craft_ui::runtime::commands::{CommandRef, CommandState};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use egui::{Response, Ui};
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::marker::PhantomData;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::picker::{ChannelRow, ChannelRule};
|
||||
use super::{ColorDisc, DiscLook, DiscRadius};
|
||||
use crate::harmony::{Guide, GuideOptions, Harmony, Variation};
|
||||
use craft_ui::choice::{SwatchTable, SwatchTableOutput};
|
||||
use craft_ui::choice::{CellMarks, SwatchTable, SwatchTableOutput};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
@@ -28,6 +30,7 @@ craft_ui::words! {
|
||||
pub struct HarmonyWords {
|
||||
rule: "harmony.rule" = "Rule";
|
||||
brightness: "harmony.brightness" = "Brightness";
|
||||
saturation: "harmony.saturation" = "Saturation";
|
||||
set_base: "harmony.setBase" = "Set base color to the current color";
|
||||
harmony: "harmony.harmony" = "Harmony colors";
|
||||
variations: "harmony.variations" = "Variations";
|
||||
@@ -127,12 +130,14 @@ pub struct HarmonyWheel<'a> {
|
||||
label: Label,
|
||||
colors: &'a [Srgba],
|
||||
selected: Option<usize>,
|
||||
look: DiscLook,
|
||||
radius: DiscRadius,
|
||||
}
|
||||
|
||||
impl<'a> HarmonyWheel<'a> {
|
||||
/// A wheel named `label` over `colors`.
|
||||
pub fn new(label: impl Into<Label>, colors: &'a [Srgba]) -> Self {
|
||||
HarmonyWheel { label: label.into(), colors, selected: None }
|
||||
HarmonyWheel { label: label.into(), colors, selected: None, look: DiscLook::Smooth, radius: DiscRadius::Saturation }
|
||||
}
|
||||
|
||||
/// Marks the colour at this index as selected; none by default.
|
||||
@@ -143,25 +148,29 @@ impl<'a> HarmonyWheel<'a> {
|
||||
|
||||
/// How the wheel draws its colours; smooth by default.
|
||||
#[must_use]
|
||||
pub fn look(self, look: DiscLook) -> Self {
|
||||
let _ = look;
|
||||
todo!("wg.W44")
|
||||
pub fn look(mut self, look: DiscLook) -> Self {
|
||||
self.look = look;
|
||||
self
|
||||
}
|
||||
|
||||
/// The channel the wheel's radius shows; its slider shows the other. Saturation by default.
|
||||
#[must_use]
|
||||
pub fn radius(self, radius: DiscRadius) -> Self {
|
||||
let _ = radius;
|
||||
todo!("wg.W44")
|
||||
pub fn radius(mut self, radius: DiscRadius) -> Self {
|
||||
self.radius = radius;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the wheel and the Brightness row.
|
||||
pub fn show(self, ui: &mut Ui) -> HarmonyWheelOutput {
|
||||
let HarmonyWheel { label, colors, selected } = self;
|
||||
let HarmonyWheel { label, colors, selected, look, radius } = self;
|
||||
let words = Env::of(ui).words::<HarmonyWords>();
|
||||
let selected = selected.filter(|&i| i < colors.len());
|
||||
let hsb = selected.map(|i| colors[i].to_hsb());
|
||||
let brightness = hsb.map_or(1.0, |c| c.b);
|
||||
// The disc shows one channel outwards; the selected colour's other channel is the disc's level and the slider's value.
|
||||
let (level, slider_name) = match radius {
|
||||
DiscRadius::Saturation => (hsb.map_or(1.0, |c| c.b), words.brightness.clone()),
|
||||
DiscRadius::Brightness => (hsb.map_or(1.0, |c| c.s), words.saturation.clone()),
|
||||
};
|
||||
let names: Vec<Label> = colors.iter().map(|c| Label::from(c.to_hex())).collect();
|
||||
let mut pressed = None;
|
||||
let mut edits = Vec::new();
|
||||
@@ -170,27 +179,45 @@ impl<'a> HarmonyWheel<'a> {
|
||||
pressed = None;
|
||||
let mut disc = ColorDisc::new(label.clone(), colors, Bind::kept());
|
||||
if let Some(selected) = selected {
|
||||
disc = disc.chosen(selected);
|
||||
disc = disc.base(selected).chosen(selected);
|
||||
}
|
||||
// P3(widgets-w5): wg.W43
|
||||
let disc = disc.level(brightness).names(names.clone()).show(ui);
|
||||
let disc = disc.look(look).radius(radius).level(level).names(names.clone()).show(ui);
|
||||
pressed = disc.pressed;
|
||||
let grabbed = disc.grabbed;
|
||||
for event in disc.edit.events {
|
||||
let marker = event.value().map(|m| m.marker).or(grabbed).or(selected);
|
||||
if let Some(marker) = marker {
|
||||
// P3(widgets-w5): wg.W43
|
||||
edits.push((marker, event.map(|m| [Some(m.hue), Some(m.radial), None])));
|
||||
edits.push((
|
||||
marker,
|
||||
event.map(|m| match radius {
|
||||
DiscRadius::Saturation => [Some(m.hue), Some(m.radial), None],
|
||||
DiscRadius::Brightness => [Some(m.hue), None, Some(m.radial)],
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
let track = hsb.map(|c| vec![Srgba::from_hsb(Hsb { b: 0.0, ..c }), Srgba::from_hsb(Hsb { b: 1.0, ..c })]).unwrap_or_default();
|
||||
let value = (f64::from(brightness) * 100.0).round();
|
||||
let track = hsb
|
||||
.map(|c| match radius {
|
||||
DiscRadius::Saturation => vec![Srgba::from_hsb(Hsb { b: 0.0, ..c }), Srgba::from_hsb(Hsb { b: 1.0, ..c })],
|
||||
DiscRadius::Brightness => vec![Srgba::from_hsb(Hsb { s: 0.0, ..c }), Srgba::from_hsb(Hsb { s: 1.0, ..c })],
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let value = (f64::from(level) * 100.0).round();
|
||||
let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 };
|
||||
Stack::new().enabled(selected.is_some()).show(ui, |ui, _| {
|
||||
let row = ChannelRow::new(words.brightness.clone(), Bind::given(value), rule.clone()).track(track.clone()).show(ui);
|
||||
let row = ChannelRow::new(slider_name.clone(), Bind::given(value), rule.clone()).track(track.clone()).show(ui);
|
||||
if let (Some(i), Some(row)) = (selected, row) {
|
||||
for event in row.events {
|
||||
edits.push((i, event.map(|v| [None, None, Some((v / 100.0) as f32)])));
|
||||
edits.push((
|
||||
i,
|
||||
event.map(|v| {
|
||||
let level = Some((v / 100.0) as f32);
|
||||
match radius {
|
||||
DiscRadius::Saturation => [None, None, level],
|
||||
DiscRadius::Brightness => [None, level, None],
|
||||
}
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -282,6 +309,40 @@ impl Outcome for HarmonyPanelOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives a swatch table the host's drag payload for the cells it shows.
|
||||
trait CellDrag: Send + Sync {
|
||||
/// `table` dragging the payload of the cell it grabbed, `cells` indexed as the table's items.
|
||||
fn attach<'t>(&self, table: SwatchTable<'t>, cells: Arc<[GuideCell]>) -> SwatchTable<'t>;
|
||||
}
|
||||
|
||||
/// The host's payload map for cells, with the payload type it erases.
|
||||
struct CellPayload<P>(Arc<dyn Fn(&GuideCell) -> Option<P> + Send + Sync>, PhantomData<fn() -> P>);
|
||||
|
||||
impl<P: Send + Sync + 'static> CellDrag for CellPayload<P> {
|
||||
fn attach<'t>(&self, table: SwatchTable<'t>, cells: Arc<[GuideCell]>) -> SwatchTable<'t> {
|
||||
let map = Arc::clone(&self.0);
|
||||
table.drag_payload(move |drag| cells.get(drag.grabbed).and_then(|cell| map(cell)))
|
||||
}
|
||||
}
|
||||
|
||||
/// `table` with the host's drag payload, when it gave one.
|
||||
fn dragging<'t>(table: SwatchTable<'t>, payload: Option<&Arc<dyn CellDrag>>, cells: &[GuideCell]) -> SwatchTable<'t> {
|
||||
match payload {
|
||||
Some(payload) => payload.attach(table, Arc::from(cells)),
|
||||
None => table,
|
||||
}
|
||||
}
|
||||
|
||||
/// The table items of `cells`: the colour each shows, named by its hex.
|
||||
fn entries(cells: &[GuideCell]) -> Vec<(Label, Srgba)> {
|
||||
cells.iter().map(|cell| (Label::from(cell.color.to_hex()), cell.color)).collect()
|
||||
}
|
||||
|
||||
/// Where flat index `index` of the variation grid, `columns` wide, lies.
|
||||
fn grid_at(index: usize, columns: usize) -> GuideCellAt {
|
||||
GuideCellAt::Grid { row: index / columns, column: index % columns }
|
||||
}
|
||||
|
||||
/// What the guide is made from.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct GuideKey {
|
||||
@@ -332,26 +393,28 @@ pub struct HarmonyPanel<'a> {
|
||||
picked: Bind<'a, HarmonyPicked>,
|
||||
base: Srgba,
|
||||
limit: Option<&'a [Srgba]>,
|
||||
cell_color: Option<Box<dyn Fn(&GuideCell) -> Srgba + 'a>>,
|
||||
payload: Option<Arc<dyn CellDrag>>,
|
||||
}
|
||||
|
||||
impl<'a> HarmonyPanel<'a> {
|
||||
/// The guide for `base`.
|
||||
pub fn new(state: Bind<'a, HarmonyPanelState>, picked: Bind<'a, HarmonyPicked>, base: Srgba) -> Self {
|
||||
HarmonyPanel { state, picked, base, limit: None }
|
||||
HarmonyPanel { state, picked, base, limit: None, cell_color: None, payload: None }
|
||||
}
|
||||
|
||||
/// The colour the host shows in each cell (spot tints), drawn instead of the guide's.
|
||||
#[must_use]
|
||||
pub fn cell_color(self, color: impl Fn(&GuideCell) -> Srgba + 'a) -> Self {
|
||||
let _ = color;
|
||||
todo!("co.K38")
|
||||
pub fn cell_color(mut self, color: impl Fn(&GuideCell) -> Srgba + 'a) -> Self {
|
||||
self.cell_color = Some(Box::new(color));
|
||||
self
|
||||
}
|
||||
|
||||
/// The payload a cell drags, through the swatch table's `drag_payload`.
|
||||
#[must_use]
|
||||
pub fn drag_payload<P: Send + Sync + 'static>(self, map: impl Fn(&GuideCell) -> Option<P> + Send + Sync + 'static) -> Self {
|
||||
let _ = map;
|
||||
todo!("co.K38")
|
||||
pub fn drag_payload<P: Send + Sync + 'static>(mut self, map: impl Fn(&GuideCell) -> Option<P> + Send + Sync + 'static) -> Self {
|
||||
self.payload = Some(Arc::new(CellPayload(Arc::new(map), PhantomData)));
|
||||
self
|
||||
}
|
||||
|
||||
/// Limit to Library: every colour snaps to the nearest of `palette`.
|
||||
@@ -362,7 +425,7 @@ impl<'a> HarmonyPanel<'a> {
|
||||
|
||||
/// Shows the panel.
|
||||
pub fn show(self, ui: &mut Ui) -> HarmonyPanelOutput {
|
||||
let HarmonyPanel { state, picked, base, limit } = self;
|
||||
let HarmonyPanel { state, picked, base, limit, cell_color, payload } = self;
|
||||
let words = Env::of(ui).words::<HarmonyWords>();
|
||||
let mut held_state = Held::new(state);
|
||||
let mut held_picked = Held::new(picked);
|
||||
@@ -383,43 +446,44 @@ impl<'a> HarmonyPanel<'a> {
|
||||
}
|
||||
});
|
||||
|
||||
let strip: Vec<(Label, Srgba)> = guide.colors.iter().map(|c| (Label::from(c.to_hex()), *c)).collect();
|
||||
// The cell as the host colours it: its colour in place of the guide's.
|
||||
let colored = |at: GuideCellAt, color: Srgba| {
|
||||
let cell = GuideCell { at, color };
|
||||
cell_color.as_ref().map_or(cell, |color_of| GuideCell { color: color_of(&cell), ..cell })
|
||||
};
|
||||
let strip_cells: Vec<GuideCell> = guide.colors.iter().enumerate().map(|(i, c)| colored(GuideCellAt::Strip(i), *c)).collect();
|
||||
let strip = entries(&strip_cells);
|
||||
let mut strip_selection = Selection::default();
|
||||
let out = SwatchTable::new(words.harmony.clone(), &strip)
|
||||
let table = SwatchTable::new(words.harmony.clone(), &strip)
|
||||
.per_row(strip.len().max(1))
|
||||
.span(true)
|
||||
.selection(Bind::bound(&mut strip_selection))
|
||||
.show_all(ui);
|
||||
.selection(Bind::bound(&mut strip_selection));
|
||||
let out = dragging(table, payload.as_ref(), &strip_cells).show_all(ui);
|
||||
if let Some(i) = out.selected {
|
||||
// P3(widgets-w5): co.K38
|
||||
chosen = strip.get(i).map(|(_, c)| GuideCell { at: GuideCellAt::Strip(i), color: *c });
|
||||
chosen = strip_cells.get(i).copied();
|
||||
}
|
||||
|
||||
let columns = guide.grid.first().map_or(1, Vec::len).max(1);
|
||||
let centre = guide.centre();
|
||||
let flat: Vec<(Label, Srgba)> = guide.grid.iter().flatten().map(|c| (Label::from(c.to_hex()), *c)).collect();
|
||||
let grid_cells: Vec<GuideCell> = guide.grid.iter().flatten().enumerate().map(|(i, c)| colored(grid_at(i, columns), *c)).collect();
|
||||
let flat = entries(&grid_cells);
|
||||
let mut selection = if before_picked.guide == stamp { before_picked.selection.clone() } else { Selection::default() };
|
||||
let SwatchTableOutput { selected, chosen: cells, .. } = SwatchTable::new(words.variations.clone(), &flat)
|
||||
let table = SwatchTable::new(words.variations.clone(), &flat)
|
||||
.multiple(true)
|
||||
.per_row(columns)
|
||||
.span(true)
|
||||
.marked(move |&at| at % columns == centre)
|
||||
.selection(Bind::bound(&mut selection))
|
||||
.show_all(ui);
|
||||
.marks(move |&at| CellMarks::default().edge(at % columns == centre))
|
||||
.selection(Bind::bound(&mut selection));
|
||||
let SwatchTableOutput { selected, chosen: clicked, .. } = dragging(table, payload.as_ref(), &grid_cells).show_all(ui);
|
||||
if let Some(i) = selected
|
||||
&& cells.len() == 1
|
||||
&& clicked.len() == 1
|
||||
{
|
||||
// P3(widgets-w5): co.K38
|
||||
chosen = flat.get(i).map(|(_, c)| GuideCell { at: GuideCellAt::Grid { row: i / columns, column: i % columns }, color: *c });
|
||||
chosen = grid_cells.get(i).copied();
|
||||
}
|
||||
let mut cells = selection.items.clone();
|
||||
cells.sort_unstable();
|
||||
cells.dedup();
|
||||
// P3(widgets-w5): co.K38
|
||||
let cells: Vec<GuideCell> = cells
|
||||
.iter()
|
||||
.filter_map(|&i| flat.get(i).map(|(_, c)| GuideCell { at: GuideCellAt::Grid { row: i / columns, column: i % columns }, color: *c }))
|
||||
.collect();
|
||||
let mut indexes = selection.items.clone();
|
||||
indexes.sort_unstable();
|
||||
indexes.dedup();
|
||||
let cells: Vec<GuideCell> = indexes.iter().filter_map(|&i| grid_cells.get(i).copied()).collect();
|
||||
let after_picked = HarmonyPicked { selection, guide: stamp, cells };
|
||||
|
||||
let (left, right) = match before.options.variation {
|
||||
@@ -509,7 +573,6 @@ impl HarmonyMenu {
|
||||
HarmonyCommand::WarmCool => state.options.variation = Variation::WarmCool,
|
||||
HarmonyCommand::VividMuted => state.options.variation = Variation::VividMuted,
|
||||
HarmonyCommand::SaveAsSwatches => {
|
||||
// P3(widgets-w5): co.K38
|
||||
return (!picked.cells().is_empty())
|
||||
.then(|| HarmonyMenuAction::SaveAsSwatches(picked.cells().iter().map(|cell| cell.color).collect()));
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `HarmonyWheel` and `HarmonyPanel`.
|
||||
|
||||
use super::{HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel};
|
||||
use super::{DiscLook, GuideCellAt, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel};
|
||||
use crate::harmony::Harmony;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
@@ -24,6 +24,28 @@ fn harmony_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The spot tint the host shows in the strip's cells.
|
||||
const SPOT: Srgba = Srgba::rgb(0.95, 0.65, 0.1);
|
||||
|
||||
#[story(HarmonyPanel<'static>, covers = [], drive = Drive::Never, title = "Host cell colors")]
|
||||
fn harmony_panel_host_cells(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (state, picked) = data.value("guide", (triad(), HarmonyPicked::default()));
|
||||
HarmonyPanel::new(Bind::bound(&mut *state), Bind::bound(&mut *picked), BASE)
|
||||
.cell_color(|cell| match cell.at {
|
||||
GuideCellAt::Strip(_) => SPOT,
|
||||
GuideCellAt::Grid { .. } => cell.color,
|
||||
})
|
||||
.drag_payload(|cell| Some(cell.color))
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(HarmonyWheel<'static>, covers = [], drive = Drive::Never, title = "Segmented")]
|
||||
fn harmony_wheel_segmented(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let colors = Harmony::Triad.apply(BASE);
|
||||
HarmonyWheel::new("Harmony", &colors).look(DiscLook::Segmented).selected_marker(Some(1)).show(ui).into()
|
||||
}
|
||||
|
||||
/// The panel set to a triad.
|
||||
fn triad() -> HarmonyPanelState {
|
||||
HarmonyPanelState { rule: Harmony::Triad, ..HarmonyPanelState::default() }
|
||||
|
||||
+191
-54
@@ -1,28 +1,36 @@
|
||||
//! [`ColorWheel`]: a hue ring round a saturation and brightness triangle that turns with the hue, as PhotoCraft's
|
||||
//! Color Wheel.
|
||||
|
||||
use super::area::{AreaShape, ColorArea};
|
||||
use super::channels::{channel_step, finite, primary, settled, spoken};
|
||||
use super::disc::nearest_within;
|
||||
use super::ramp::Gamut;
|
||||
use craft_behavior::{HitLevel, HitPriority, HitShape, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use crate::AreaMode;
|
||||
use craft_behavior::nav::{NavShape, Roving};
|
||||
use craft_behavior::{HitLevel, HitPriority, HitShape, Metrics, Mixed, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_theme::{ColorModel, HsbModel, ModelValues, Srgba};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Numeric, Outcome,
|
||||
PaintUi, PartsCx, Pointer as _, Props as _, Role, WordSetCx as _,
|
||||
PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{Marker, PaintShape, StrokeWidth};
|
||||
use craft_ui::primitives::{Marker, MarkerSize, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeepKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, MarkerLook, StyleColor, StyleCx};
|
||||
use egui::{Mesh, Pos2, Rect, Response, Vec2, vec2};
|
||||
use std::f32::consts::TAU;
|
||||
use egui::{Color32, Mesh, Pos2, Rect, Response, Vec2, vec2};
|
||||
use std::f32::consts::{SQRT_2, TAU};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The hue ring: a press on it sets the hue to the pointer's angle.
|
||||
const RING: PartKey = PartKey::new("ring");
|
||||
/// The triangle: a press on it sets saturation and brightness.
|
||||
/// The triangle: a press on it sets saturation and brightness. With a square inside the ring it is the catch area
|
||||
/// round the square: a press there sets the square's closest point.
|
||||
const TRIANGLE: PartKey = PartKey::new("triangle");
|
||||
/// A marker on the ring: `MARKER.at(i)`, a member of the markers' roving group.
|
||||
const MARKER: PartKey = PartKey::new("marker");
|
||||
|
||||
/// Steps round the hue ring's mesh (PhotoCraft's 96).
|
||||
const RING_STEPS: u32 = 96;
|
||||
@@ -38,6 +46,8 @@ const BRIGHTNESS_PAGE: f32 = 10.0;
|
||||
const FAR: f32 = 10.0;
|
||||
/// The last hue a key reaches: the hue wraps at 360 and has no 360 of its own.
|
||||
const HUE_LAST: f32 = 359.0;
|
||||
/// Degrees a ring drag with Shift snaps the hue to.
|
||||
const HUE_SNAP: f32 = 45.0;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of colour wheels.
|
||||
@@ -121,8 +131,9 @@ impl WheelGeometry {
|
||||
}
|
||||
|
||||
/// The largest square inside the ring, a `space.gap.tight` inside its inner edge: where `WheelInner::Square` lies.
|
||||
/// The square's corners lie on the circle `triangle` is the radius of, which the style insets by that gap.
|
||||
pub fn square(&self) -> Rect {
|
||||
todo!("wg.W45")
|
||||
Rect::from_center_size(self.center, Vec2::splat(self.triangle * SQRT_2))
|
||||
}
|
||||
|
||||
/// The part a press at `pos` takes: nothing beyond the ring's outer edge plus `grab_outer`,
|
||||
@@ -204,7 +215,7 @@ pub struct ColorWheelStyle {
|
||||
ring_max: f32,
|
||||
/// The gap between the area's edge and the ring.
|
||||
outer_inset: f32,
|
||||
/// The gap between the ring's inner edge and the triangle's circle.
|
||||
/// The gap between the ring's inner edge and the circle round the triangle's corners or the square's.
|
||||
triangle_inset: f32,
|
||||
/// A press this far outside the ring still takes it, and this far inside its inner edge.
|
||||
grab: f32,
|
||||
@@ -226,14 +237,19 @@ pub struct ColorWheelStyle {
|
||||
/// - Pointer (primary button): the part under the press is kept for the whole drag, so a drag that leaves the ring
|
||||
/// keeps turning the hue; a press further outside the ring than `size.hit.target` starts nothing. A press sets the
|
||||
/// value under the pointer (whole degrees, whole percents) and a drag follows it; Esc cancels. A press focuses the
|
||||
/// part.
|
||||
/// part. A ring drag with Shift snaps the hue to 45 degrees.
|
||||
/// - Keys on the focused ring: Left and Down lower the hue by 1 degree, Right and Up raise it, wrapping at 360;
|
||||
/// Shift steps ten; Page Up and Page Down 36 degrees; Home 0, End 359. On the triangle: Left and Right saturation,
|
||||
/// Up and Down brightness; Shift ten; Page keys a tenth of brightness; Home and End saturation 0 and 100. The
|
||||
/// directions are not screen directions: the triangle turns with the hue.
|
||||
/// - Two Tab stops, the ring and then the triangle.
|
||||
/// - Two Tab stops, the ring and then the triangle; then the markers, one roving stop, when there are any.
|
||||
/// - [`WheelInner::Square`]: the largest square inside the ring is a `ColorArea` with its own stop, keys and node; a
|
||||
/// press between the square and the ring sets the square's closest point.
|
||||
/// - Markers: a click, Enter or Space on one reports [`picked`](ColorWheelOutput::picked); a press on one still drags
|
||||
/// the ring and reports it as [`held`](ColorWheelOutput::held).
|
||||
/// - AccessKit: a `Group` named `label` holding a `Slider` for the hue (0 to 360, step 1, increment, decrement and
|
||||
/// set value) and a `Slider` for saturation and brightness (value text, no numeric value).
|
||||
/// set value; no numeric value while the value is mixed), a `Slider` for saturation and brightness (value text, no
|
||||
/// numeric value) on the triangle, and a `Button` per marker.
|
||||
/// - Right to left nothing mirrors: red stays at 3 o'clock.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
@@ -254,20 +270,42 @@ pub struct ColorWheel<'a> {
|
||||
/// The markers' accessible names, in order.
|
||||
#[prop(into)]
|
||||
marker_names: Vec<Label>,
|
||||
picked: Option<usize>,
|
||||
held: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a> ColorWheel<'a> {
|
||||
/// A wheel named `label` ("Color wheel") showing `values`, HSB values.
|
||||
pub fn new(label: impl Into<Label>, values: Bind<'a, ModelValues>) -> Self {
|
||||
ColorWheel { common: Common::new(), values, gamut: None, inner: WheelInner::Triangle, markers: &[], marker_names: Vec::new() }
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
ColorWheel {
|
||||
common: Common::new(),
|
||||
values,
|
||||
gamut: None,
|
||||
inner: WheelInner::Triangle,
|
||||
markers: &[],
|
||||
marker_names: Vec::new(),
|
||||
picked: None,
|
||||
held: None,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
}
|
||||
|
||||
/// Where the wheel lies in `area`.
|
||||
pub fn geometry(style: &ColorWheelStyle, area: Rect) -> WheelGeometry {
|
||||
WheelGeometry::new(area, style.outer_inset, (style.ring_min, style.ring_max), RING_RATIO, style.triangle_inset)
|
||||
}
|
||||
|
||||
/// Where each marker lies on the ring: at its colour's hue.
|
||||
fn places(&self, geometry: &WheelGeometry) -> Vec<Pos2> {
|
||||
self.markers.iter().map(|color| geometry.ring_knob(finite(HsbModel.from_srgb(*color).values[0]))).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker a press holds, kept until the press ends.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Held {
|
||||
marker: Option<usize>,
|
||||
}
|
||||
|
||||
/// The HSB values the wheel shows when the host gives none.
|
||||
@@ -275,22 +313,35 @@ fn blank() -> ModelValues {
|
||||
ModelValues::new(HsbModel.id(), &[])
|
||||
}
|
||||
|
||||
/// `base` with what a press at `pos` in `part` picks: the hue for the ring, saturation and brightness for the
|
||||
/// triangle (turned to `base`'s hue); `base` when `pos` picks nothing.
|
||||
fn value_at(geometry: &WheelGeometry, base: &ModelValues, part: WheelPart, pos: Pos2) -> ModelValues {
|
||||
/// The square's area over `values`: the one point-to-value mapping of the square, for the child and for a press
|
||||
/// between it and the ring.
|
||||
fn square_area(label: impl Into<Label>, values: impl Into<Mixed<ModelValues>>) -> ColorArea<'static> {
|
||||
ColorArea::new(label, AreaMode::Hue, Bind::given(values)).shape(AreaShape::Square)
|
||||
}
|
||||
|
||||
/// `hue` rounded to the nearest multiple of [`HUE_SNAP`] degrees.
|
||||
fn snapped(hue: f32) -> f32 {
|
||||
((hue / HUE_SNAP).round() * HUE_SNAP).rem_euclid(360.0)
|
||||
}
|
||||
|
||||
/// `base` with what a press at `pos` in `part` picks: the hue for the ring (to a multiple of 45 degrees when `snap`),
|
||||
/// saturation and brightness for the triangle (turned to `base`'s hue) or the square's closest point; `base` when
|
||||
/// `pos` picks nothing.
|
||||
fn value_at(geometry: &WheelGeometry, base: &ModelValues, part: WheelPart, inner: WheelInner, pos: Pos2, snap: bool) -> ModelValues {
|
||||
let mut out = *base;
|
||||
match part {
|
||||
WheelPart::Ring => {
|
||||
match (part, inner) {
|
||||
(WheelPart::Ring, _) => {
|
||||
if let Some(hue) = hue_at(geometry.center, pos) {
|
||||
out.values[0] = hue;
|
||||
out.values[0] = if snap { snapped(hue) } else { hue };
|
||||
}
|
||||
}
|
||||
WheelPart::Triangle => {
|
||||
(WheelPart::Triangle, WheelInner::Triangle) => {
|
||||
if let Some((s, b)) = triangle_sv(geometry.corners(finite(base.values[0]), 0.0), pos) {
|
||||
out.values[1] = (s * 100.0).round();
|
||||
out.values[2] = (b * 100.0).round();
|
||||
}
|
||||
}
|
||||
(WheelPart::Triangle, WheelInner::Square) => out = square_area("", *base).value_at(geometry.square(), base, pos),
|
||||
}
|
||||
out
|
||||
}
|
||||
@@ -340,12 +391,12 @@ impl Component for ColorWheel<'_> {
|
||||
const DISABLED: DisabledLook = DisabledLook::Faded;
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Both);
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorWheelStyle;
|
||||
type Output = ColorWheelOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorWheelStyleKey) -> ColorWheelStyle {
|
||||
fn style(cx: &StyleCx<'_>, key: ColorWheelStyleKey) -> ColorWheelStyle {
|
||||
let tokens = cx.tokens;
|
||||
ColorWheelStyle {
|
||||
metrics: Metrics::new(),
|
||||
@@ -355,7 +406,10 @@ impl Component for ColorWheel<'_> {
|
||||
ring_min: tokens.size.icon.sm,
|
||||
ring_max: tokens.size.control.md,
|
||||
outer_inset: tokens.space.gap.tight,
|
||||
triangle_inset: tokens.stroke.thin,
|
||||
triangle_inset: match key.inner {
|
||||
WheelInner::Triangle => tokens.stroke.thin,
|
||||
WheelInner::Square => tokens.space.gap.tight,
|
||||
},
|
||||
grab: tokens.size.hit.target,
|
||||
edge: cx.color(tokens.color.line.control_edge),
|
||||
knob: cx.marker(),
|
||||
@@ -380,12 +434,26 @@ impl Component for ColorWheel<'_> {
|
||||
.sense(Sense::DRAG | Sense::SETS_ON_PRESS | Sense::CLICK)
|
||||
.focusable()
|
||||
.focus_shape(FocusShape::Circle);
|
||||
cx.part(TRIANGLE, HitShape::circle(geometry.center, (geometry.inner - reach).max(0.0)))
|
||||
let triangle = cx
|
||||
.part(TRIANGLE, HitShape::circle(geometry.center, (geometry.inner - reach).max(0.0)))
|
||||
.sense(Sense::DRAG | Sense::SETS_ON_PRESS | Sense::CLICK)
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0))
|
||||
.focusable()
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0));
|
||||
// The square is a child with its own stop; only the triangle is a stop of the wheel's.
|
||||
if self.inner == WheelInner::Triangle {
|
||||
// The triangle turns with the hue, so its ring is rebuilt each pass.
|
||||
.focus_shape(FocusShape::Polygon(geometry.corners(hue, 0.0).to_vec()));
|
||||
triangle.focusable().focus_shape(FocusShape::Polygon(geometry.corners(hue, 0.0).to_vec()));
|
||||
}
|
||||
let marker_reach = Marker::reach(&cx.style.knob, MarkerSize::Regular);
|
||||
for (index, place) in self.places(&geometry).into_iter().enumerate() {
|
||||
// A marker takes no press of its own: the ring takes it and drags on.
|
||||
let part = cx.part(MARKER.at(index as u64), HitShape::circle(place, marker_reach)).focusable().focus_shape(FocusShape::Circle);
|
||||
if index == 0 {
|
||||
part.selected();
|
||||
}
|
||||
}
|
||||
if !self.markers.is_empty() {
|
||||
cx.roving(Roving::new(NavShape::Flat));
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, ModelValues>> {
|
||||
@@ -394,6 +462,9 @@ impl Component for ColorWheel<'_> {
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let geometry = ColorWheel::geometry(cx.style, cx.rect);
|
||||
let inner = self.inner;
|
||||
let marker_reach = Marker::reach(&cx.style.knob, MarkerSize::Regular);
|
||||
let places = self.places(&geometry);
|
||||
let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or_else(blank);
|
||||
for (key, part) in [(RING, WheelPart::Ring), (TRIANGLE, WheelPart::Triangle)] {
|
||||
let press = cx.part(key).press;
|
||||
@@ -401,10 +472,31 @@ impl Component for ColorWheel<'_> {
|
||||
continue;
|
||||
}
|
||||
if matches!(press.phase, PressPhase::Down { .. }) {
|
||||
cx.focus_part(key);
|
||||
if part == WheelPart::Ring {
|
||||
cx.memory::<Held>().marker =
|
||||
press.phase.start().and_then(|start| nearest_within(places.iter().map(|place| place.distance(start.origin)), marker_reach));
|
||||
}
|
||||
if part == WheelPart::Ring || inner == WheelInner::Triangle {
|
||||
cx.focus_part(key);
|
||||
}
|
||||
}
|
||||
let now = current(&*cx);
|
||||
cx.follow_press(key, |pos| Some(value_at(&geometry, &now, part, pos)));
|
||||
let snap = press.mods.shift;
|
||||
cx.follow_press(key, |pos| Some(value_at(&geometry, &now, part, inner, pos, snap)));
|
||||
}
|
||||
let held = cx.memory::<Held>().marker;
|
||||
self.held = held;
|
||||
let ring = cx.part(RING).press;
|
||||
if primary(&ring) && matches!(ring.phase, PressPhase::Release { click: true, .. }) {
|
||||
self.picked = held;
|
||||
}
|
||||
if matches!(ring.phase, PressPhase::Release { .. } | PressPhase::Cancel { .. }) {
|
||||
*cx.memory::<Held>() = Held::default();
|
||||
}
|
||||
for index in 0..self.markers.len() {
|
||||
if matches!(cx.part_activated(MARKER.at(index as u64)), Some(FireSource::Key | FireSource::Access)) {
|
||||
self.picked = Some(index);
|
||||
}
|
||||
}
|
||||
let running = cx.gesture().is_some();
|
||||
let focused = match cx.active_part() {
|
||||
@@ -413,12 +505,16 @@ impl Component for ColorWheel<'_> {
|
||||
_ => None,
|
||||
};
|
||||
let mut now = current(&*cx);
|
||||
while let Some((mv, mods)) = cx.intents().take_move() {
|
||||
if let Some(part) = focused.filter(|_| !running)
|
||||
&& let Some(next) = keyed(&now, part, mv, mods.extend)
|
||||
{
|
||||
now = next;
|
||||
cx.set(now);
|
||||
// The moves are the focused part's; with a marker focused they are the markers' group's.
|
||||
if let Some(part) = focused {
|
||||
while let Some((mv, mods)) = cx.intents().take_move() {
|
||||
if running {
|
||||
continue;
|
||||
}
|
||||
if let Some(next) = keyed(&now, part, mv, mods.extend) {
|
||||
now = next;
|
||||
cx.set(now);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(value) = cx.intents().take_set_value_at(RING).filter(|value| value.is_finite() && !running) {
|
||||
@@ -429,38 +525,79 @@ impl Component for ColorWheel<'_> {
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<ColorWheelWords>();
|
||||
let values = cx.value().copied().unwrap_or_else(blank);
|
||||
let [hue, saturation, brightness] = [0, 1, 2].map(|channel| finite(values.values[channel]));
|
||||
// A mixed value has no number to speak.
|
||||
let shown = cx.value().copied();
|
||||
let ring = access.node(RING, Role::SLIDER);
|
||||
ring.name = Name::Text(words.hue.as_str().to_owned());
|
||||
ring.numeric = Some(Numeric::new(f64::from(hue.rem_euclid(360.0)), 0.0..=360.0).step(1.0).wraps(true));
|
||||
let model = &HsbModel as &dyn ColorModel;
|
||||
let text =
|
||||
format!("{}, {}", spoken(words.saturation.as_str(), model, 1, saturation), spoken(words.brightness.as_str(), model, 2, brightness));
|
||||
let triangle = access.node(TRIANGLE, Role::GROUP);
|
||||
triangle.name = Name::Text(words.triangle.as_str().to_owned());
|
||||
triangle.value(text);
|
||||
if let Some(values) = shown {
|
||||
ring.numeric = Some(Numeric::new(f64::from(finite(values.values[0]).rem_euclid(360.0)), 0.0..=360.0).step(1.0).wraps(true));
|
||||
}
|
||||
if self.inner == WheelInner::Triangle {
|
||||
let triangle = access.node(TRIANGLE, Role::GROUP);
|
||||
triangle.name = Name::Text(words.triangle.as_str().to_owned());
|
||||
if let Some(values) = shown {
|
||||
let [saturation, brightness] = [1, 2].map(|channel| finite(values.values[channel]));
|
||||
let model = &HsbModel as &dyn ColorModel;
|
||||
triangle.value(format!(
|
||||
"{}, {}",
|
||||
spoken(words.saturation.as_str(), model, 1, saturation),
|
||||
spoken(words.brightness.as_str(), model, 2, brightness)
|
||||
));
|
||||
}
|
||||
}
|
||||
for (index, color) in self.markers.iter().enumerate() {
|
||||
let node = access.node(MARKER.at(index as u64), Role::BUTTON);
|
||||
node.name = Name::Text(match self.marker_names.get(index) {
|
||||
Some(name) => cx.env.resolve(name).as_str().to_owned(),
|
||||
None => color.to_hex(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let geometry = ColorWheel::geometry(cx.style, cx.rect);
|
||||
let values = cx.value().copied().unwrap_or_else(blank);
|
||||
let shown = cx.value().copied();
|
||||
let values = shown.unwrap_or_else(blank);
|
||||
let [hue, saturation, brightness] = [0, 1, 2].map(|channel| finite(values.values[channel]));
|
||||
let corners = geometry.corners(hue, 0.0);
|
||||
let painter = ui.content_painter(cx);
|
||||
painter.painter.add(ring_mesh(&geometry));
|
||||
painter.painter.add(triangle_mesh(corners, hue));
|
||||
{
|
||||
let painter = ui.content_painter(cx);
|
||||
painter.painter.add(ring_mesh(&geometry));
|
||||
if self.inner == WheelInner::Triangle {
|
||||
painter.painter.add(triangle_mesh(corners, hue));
|
||||
}
|
||||
}
|
||||
if self.inner == WheelInner::Square {
|
||||
let words = cx.words::<ColorWheelWords>();
|
||||
// `Gamut` is not `Clone`: the wheel is built anew every pass, so the child takes it.
|
||||
let area = square_area(words.triangle.clone(), shown.map_or(Mixed::Mixed, Mixed::from));
|
||||
let area = match self.gamut.take() {
|
||||
Some(gamut) => area.gamut(gamut),
|
||||
None => area,
|
||||
};
|
||||
let edit = ui.child("square", geometry.square(), area);
|
||||
cx.adopt(&edit, &blank(), |point, mine| *mine = *point);
|
||||
}
|
||||
let draw = ui.draw();
|
||||
draw.stroke(&PaintShape::Circle(geometry.center, geometry.outer), StrokeWidth::Thin, cx.style.edge);
|
||||
draw.stroke(&PaintShape::Polygon(corners.to_vec()), StrokeWidth::Thin, cx.style.edge);
|
||||
let knobs = [geometry.ring_knob(hue), triangle_point(corners, saturation / 100.0, brightness / 100.0)];
|
||||
for at in knobs {
|
||||
draw.marker(&cx.style.knob, &Marker::hollow(at));
|
||||
if self.inner == WheelInner::Triangle {
|
||||
draw.stroke(&PaintShape::Polygon(corners.to_vec()), StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
// A mixed value draws no knob.
|
||||
if shown.is_some() {
|
||||
draw.marker(&cx.style.knob, &Marker::hollow(geometry.ring_knob(hue)));
|
||||
if self.inner == WheelInner::Triangle {
|
||||
draw.marker(&cx.style.knob, &Marker::hollow(triangle_point(corners, saturation / 100.0, brightness / 100.0)));
|
||||
}
|
||||
}
|
||||
for (place, color) in self.places(&geometry).into_iter().zip(self.markers) {
|
||||
draw.marker(&cx.style.knob, &Marker::filled(place, Color32::from(*color)));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorWheelOutput {
|
||||
ColorWheelOutput { edit: cx.edit_response(), picked: None, held: None }
|
||||
let (picked, held) = (self.picked, self.held);
|
||||
ColorWheelOutput { edit: cx.edit_response(), picked, held }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,19 @@
|
||||
//! Stories of `ColorWheel`.
|
||||
|
||||
use super::ColorWheel;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use super::{ColorWheel, Gamut, WheelInner};
|
||||
use craft_theme::{ColorModel, Hsb, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::runtime::env::{Label, Message};
|
||||
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
const MARKERS: [Srgba; 3] = [Srgba::rgb(0.9, 0.2, 0.2), Srgba::rgb(0.2, 0.7, 0.4), Srgba::rgb(0.3, 0.4, 0.9)];
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::RING)))]
|
||||
fn color_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
let shown = ColorWheel::new("Color wheel", Bind::bound(values)).show(ui);
|
||||
let last = data.note("last", String::new());
|
||||
// P3(widgets-w5): wg.W46
|
||||
if let Some(event) = shown.edit.events.last() {
|
||||
*last = format!("{event:?}");
|
||||
}
|
||||
@@ -20,6 +21,42 @@ fn color_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
StoryOutput::from(shown).readout(readout)
|
||||
}
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [], drive = Drive::Drag(Grip::new(super::RING)), title = "Square")]
|
||||
fn color_wheel_square(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorWheel::new("Color wheel", Bind::bound(values)).inner(WheelInner::Square).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [], drive = Drive::Never, title = "Square with markers")]
|
||||
fn color_wheel_square_markers(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
let names = ["Warm", "Green", "Cool"].map(|name| Label::from(name.to_owned())).to_vec();
|
||||
let shown = ColorWheel::new("Color wheel", Bind::bound(values)).inner(WheelInner::Square).markers(&MARKERS).marker_names(names).show(ui);
|
||||
let picked = data.note("picked", String::new());
|
||||
if let Some(index) = shown.picked {
|
||||
*picked = format!("Picked: {index}");
|
||||
}
|
||||
let readout = picked.clone();
|
||||
StoryOutput::from(shown).readout(readout)
|
||||
}
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [], drive = Drive::Never, title = "Square with a gamut")]
|
||||
fn color_wheel_square_gamut(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
// A gamut that cannot reach full saturation: the square shades what it cannot show.
|
||||
let gamut = Gamut::new(|color| {
|
||||
let hsb = color.to_hsb();
|
||||
Srgba::from_hsb(Hsb { s: hsb.s.min(0.6), ..hsb })
|
||||
});
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorWheel::new("Color wheel", Bind::bound(values)).inner(WheelInner::Square).gamut(gamut).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [Mixed], drive = Drive::Never, title = "Square, mixed")]
|
||||
fn color_wheel_square_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("mixed", craft_ui::contract::Mixed::<craft_theme::ModelValues>::Mixed);
|
||||
ColorWheel::new("Color wheel", Bind::bound_mixed(values)).inner(WheelInner::Square).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_wheel_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_dim =
|
||||
|
||||
@@ -7,7 +7,8 @@ use craft_behavior::kurbo::{Point, Size};
|
||||
use craft_behavior::{CancelReason, CanvasView, EditEvent, PointerButton};
|
||||
use craft_color_ui::AreaMode;
|
||||
use craft_color_ui::ui::{
|
||||
ColorArea, ColorDisc, ColorHud, ColorRamp, DiscMove, RampKind, RampPick, WheelGeometry, hue_at, triangle_corners, triangle_point, triangle_sv,
|
||||
ColorArea, ColorDisc, ColorHud, ColorRamp, ColorWheel, DiscMove, DiscRadius, RampKind, RampPick, WheelGeometry, WheelInner, hue_at,
|
||||
hue_direction, patch_at, triangle_corners, triangle_point, triangle_sv,
|
||||
};
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::{ColorModel, HsbModel, ModelValues, Srgba};
|
||||
@@ -128,6 +129,176 @@ fn the_disc_markers_take_focus_from_tab_a_press_and_assistive_technology() {
|
||||
assert_eq!(rig.focused().as_deref(), Some("Color 1"), "and leave focus on it");
|
||||
}
|
||||
|
||||
/// The segmented disc's patch centres: 24 sectors by 5 rings, each hue and radius in one patch, the hue wrapping; and the
|
||||
/// brightness radius puts a marker at its brightness.
|
||||
#[trial]
|
||||
fn segmented_disc_patches_and_brightness_radius() {
|
||||
let mut centres: Vec<(u32, u32)> = Vec::new();
|
||||
for sector in 0..24 {
|
||||
for ring in 0..5 {
|
||||
let (hue, radial) = patch_at(sector as f32 * 15.0 + 3.0, (ring as f32 + 0.3) / 5.0);
|
||||
centres.push((hue.to_bits(), radial.to_bits()));
|
||||
}
|
||||
}
|
||||
centres.sort_unstable();
|
||||
centres.dedup();
|
||||
assert_eq!(centres.len(), 120, "every sector and ring has its own patch");
|
||||
assert_eq!(patch_at(7.0, 1.0), (0.0, 0.9), "7 degrees is still the red sector; the rim is the last ring");
|
||||
assert_eq!(patch_at(8.0, 0.0).0, 15.0, "8 degrees is the next sector");
|
||||
assert_eq!(patch_at(355.0, 0.5).0, 0.0, "the hue wraps to the red sector");
|
||||
assert_eq!(patch_at(-10.0, 0.5).0, 345.0, "a negative hue wraps");
|
||||
|
||||
// A saturated red at 80 % brightness: on the rim of a saturation disc, 0.8 of the way on a brightness disc.
|
||||
let markers = [Srgba::rgb(0.8, 0.0, 0.0), Srgba::BLACK];
|
||||
let distance = |radius: DiscRadius| {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let _ = ColorDisc::new("Harmony", &markers, Bind::given(DiscMove::new(0, 0.0, 0.0))).radius(radius).show(ui);
|
||||
});
|
||||
fixture.room(vec2(320.0, 240.0));
|
||||
fixture.settle();
|
||||
let red = fixture.by_label("Color 1").expect("marker 1").center();
|
||||
let centre = fixture.by_label("Color 2").expect("marker 2").center();
|
||||
red.distance(centre)
|
||||
};
|
||||
let ratio = distance(DiscRadius::Brightness) / distance(DiscRadius::Saturation);
|
||||
assert!((ratio - 0.8).abs() < 0.02, "the brightness radius places the marker at its brightness: {ratio}");
|
||||
}
|
||||
|
||||
/// A square wheel's rig: the host keeps the values the wheel reports and the marker it picked and holds.
|
||||
struct WheelRig {
|
||||
fixture: Fixture,
|
||||
values: Rc<Cell<ModelValues>>,
|
||||
picked: Rc<Cell<Option<usize>>>,
|
||||
held: Rc<Cell<Option<usize>>>,
|
||||
}
|
||||
|
||||
impl WheelRig {
|
||||
fn new(inner: WheelInner, markers: usize) -> Self {
|
||||
let colors = [Srgba::rgb(0.9, 0.2, 0.2), Srgba::rgb(0.2, 0.9, 0.2), Srgba::rgb(0.2, 0.2, 0.9)];
|
||||
let names = ["Warm", "Green", "Cool"].map(|name| craft_ui::runtime::env::Label::from(name.to_owned())).to_vec();
|
||||
let values = Rc::new(Cell::new(ModelValues::new("hsb", &[200.0, 50.0, 50.0])));
|
||||
let (picked, held) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(None)));
|
||||
let (v, p, h) = (values.clone(), picked.clone(), held.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = ColorWheel::new("Color wheel", Bind::given(v.get())).inner(inner).markers(&colors[..markers]).marker_names(names.clone()).show(ui);
|
||||
if let Some(values) = out.edit.value() {
|
||||
v.set(*values);
|
||||
}
|
||||
if out.picked.is_some() {
|
||||
p.set(out.picked);
|
||||
}
|
||||
if out.held.is_some() {
|
||||
h.set(out.held);
|
||||
}
|
||||
});
|
||||
fixture.room(vec2(320.0, 320.0));
|
||||
fixture.settle();
|
||||
WheelRig { fixture, values, picked, held }
|
||||
}
|
||||
|
||||
fn hue(&self) -> f32 {
|
||||
self.values.get().values[0]
|
||||
}
|
||||
}
|
||||
|
||||
/// A square wheel hands a press between the square and the ring to the square; its markers pick on a click and a press
|
||||
/// held on one still drags the ring; Shift snaps a ring drag to 45 degrees, in both variants.
|
||||
#[trial]
|
||||
fn a_square_wheel_hands_the_inner_press_to_the_square_and_its_markers_pick() {
|
||||
let mut rig = WheelRig::new(WheelInner::Square, 3);
|
||||
let square = rig.fixture.by_label("Saturation and brightness").expect("the square").rect;
|
||||
rig.fixture.click_at(pos2(square.right() + 2.0, square.center().y));
|
||||
rig.fixture.idle(2);
|
||||
let [hue, saturation, brightness] = rig.values.get().values;
|
||||
assert_eq!(hue, 200.0, "the square leaves the hue");
|
||||
assert_eq!(saturation, 100.0, "beside the square's right edge is full saturation");
|
||||
assert!((brightness - 50.0).abs() < 4.0, "level with the square's middle is half brightness: {brightness}");
|
||||
|
||||
let warm = rig.fixture.by_label("Warm").expect("marker").center();
|
||||
rig.fixture.click_at(warm);
|
||||
rig.fixture.idle(2);
|
||||
assert_eq!(rig.picked.get(), Some(0), "a click on a marker picks it");
|
||||
|
||||
let green = rig.fixture.by_label("Green").expect("marker").center();
|
||||
rig.fixture.drag_hold_at(green, egui::Vec2::ZERO);
|
||||
assert_eq!(rig.held.get(), Some(1), "a press on a marker holds it");
|
||||
assert!((rig.hue() - 120.0).abs() <= 1.0, "and the ring takes the press: {}", rig.hue());
|
||||
rig.fixture.release_at(green);
|
||||
rig.fixture.idle(2);
|
||||
|
||||
for inner in [WheelInner::Triangle, WheelInner::Square] {
|
||||
let mut rig = WheelRig::new(inner, 0);
|
||||
let wheel = rig.fixture.by_label("Color wheel").expect("the wheel").rect;
|
||||
let (centre, reach) = (wheel.center(), wheel.width().min(wheel.height()) / 2.0 - 8.0);
|
||||
let from = centre + hue_direction(0.0) * reach;
|
||||
let to = centre + hue_direction(25.0) * reach;
|
||||
rig.fixture.hold(Modifiers::SHIFT);
|
||||
rig.fixture.drag_at(from, to - from);
|
||||
rig.fixture.idle(2);
|
||||
rig.fixture.hold(Modifiers::NONE);
|
||||
assert_eq!(rig.hue(), 45.0, "{inner:?}: Shift snaps 25 degrees to 45");
|
||||
let mut free = WheelRig::new(inner, 0);
|
||||
free.fixture.drag_at(from, to - from);
|
||||
free.fixture.idle(2);
|
||||
assert!((free.hue() - 25.0).abs() <= 1.0, "{inner:?}: without Shift the hue follows the pointer: {}", free.hue());
|
||||
}
|
||||
}
|
||||
|
||||
/// A primary click reports the grabbed marker and the point under the release; a secondary click reports the marker in
|
||||
/// reach, else the marker whose spoke it is on, else neither, and nothing outside the circle.
|
||||
#[trial]
|
||||
fn a_disc_click_reports_its_point_and_a_secondary_click_what_it_hit() {
|
||||
let markers = [Srgba::rgb(0.8, 0.0, 0.0), Srgba::rgb(0.0, 0.8, 0.8), Srgba::rgb(0.0, 0.8, 0.0)];
|
||||
let (clicked, context) = (Rc::new(Cell::new(None)), Rc::new(Cell::new(None)));
|
||||
let (k, c) = (clicked.clone(), context.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let out = ColorDisc::new("Harmony", &markers, Bind::given(DiscMove::new(0, 0.0, 0.0))).show(ui);
|
||||
if out.clicked.is_some() {
|
||||
k.set(out.clicked);
|
||||
}
|
||||
if out.context.is_some() {
|
||||
c.set(out.context);
|
||||
}
|
||||
});
|
||||
fixture.room(vec2(320.0, 240.0));
|
||||
fixture.settle();
|
||||
// Red at 0 degrees and cyan at 180 are on the rim, opposite: their midpoint is the centre.
|
||||
let (red, cyan) = (fixture.by_label("Color 1").expect("marker").center(), fixture.by_label("Color 2").expect("marker").center());
|
||||
let (centre, radius) = (red.lerp(cyan, 0.5), red.distance(cyan) / 2.0);
|
||||
let at = |hue: f32, share: f32| centre + hue_direction(hue) * (radius * share);
|
||||
|
||||
let up = at(90.0, 0.5);
|
||||
fixture.click_at(up);
|
||||
fixture.idle(2);
|
||||
let hit = clicked.get().expect("a click reports");
|
||||
assert_eq!(hit.marker, None, "a press away from every marker grabs none");
|
||||
assert!((hit.hue - 90.0).abs() <= 1.0 && (hit.radial - 0.5).abs() < 0.05, "the point under the release: {hit:?}");
|
||||
clicked.set(None);
|
||||
fixture.click_at(red);
|
||||
fixture.idle(2);
|
||||
assert_eq!(clicked.get().map(|hit| hit.marker), Some(Some(0)), "a click on a marker reports it");
|
||||
|
||||
let secondary = |fixture: &mut Fixture, at: Pos2| {
|
||||
context.set(None);
|
||||
for pressed in [true, false] {
|
||||
fixture.frame(vec![
|
||||
Event::PointerMoved(at),
|
||||
Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: Modifiers::NONE },
|
||||
]);
|
||||
}
|
||||
fixture.idle(2);
|
||||
context.get()
|
||||
};
|
||||
let on_marker = secondary(&mut fixture, red).expect("a secondary click in the circle reports");
|
||||
assert_eq!((on_marker.marker, on_marker.spoke), (Some(0), None), "the marker in reach");
|
||||
let on_spoke = secondary(&mut fixture, at(120.0, 0.5)).expect("reports");
|
||||
assert_eq!((on_spoke.marker, on_spoke.spoke), (None, Some(2)), "else the marker whose spoke it is on");
|
||||
let between = secondary(&mut fixture, at(300.0, 0.5)).expect("reports");
|
||||
assert_eq!((between.marker, between.spoke), (None, None), "else neither");
|
||||
assert!((between.hue - 300.0).abs() <= 1.0, "with the point: {between:?}");
|
||||
assert!(secondary(&mut fixture, centre + vec2(radius * 1.05, radius * 0.5)).is_none(), "nothing outside the circle");
|
||||
}
|
||||
|
||||
/// Alt with Enter on the focused bar or a box picks for the colour the host is not editing, as Alt with a click does.
|
||||
#[trial]
|
||||
fn alt_with_enter_on_the_ramp_picks_the_other_colour() {
|
||||
|
||||
Reference in New Issue
Block a user