day_pieces/colorpicker.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! `day_pieces::colorpicker` is a color chooser bound two-way to a `Signal<Color>`, in two idioms
5//! (docs/colorpicker.md; DESIGN.md §15).
6//!
7//! ```ignore
8//! let tint = Signal::new(Color::hex(0xE86A3C));
9//! row((
10//! vector(gv::nav_animation).tint(move || tint.get()).frame(28.0, 28.0),
11//! color_picker(tint).alpha(), // the platform's chooser where there is one
12//! color_picker(tint).composed(), // Day's own panel, identical everywhere
13//! ))
14//! ```
15//!
16//! Both idioms give the app the same control, a **color well**: a swatch showing the current
17//! color that opens a chooser when pressed. They differ only in who draws the chooser.
18//!
19//! - [`PickerIdiom::Native`] realizes a native leaf: `NSColorWell` onto the shared
20//! `NSColorPanel`, `UIColorWell` onto the iOS color picker, `GtkColorDialogButton`, a swatch
21//! button onto `QColorDialog`, the XAML `ColorPicker` in a button flyout, and
22//! `<input type="color">`. Each is the system chooser, chrome and all.
23//! - [`PickerIdiom::Composed`] builds the whole thing out of ordinary Day pieces: a drawn swatch
24//! opening an [`unrouted`](crate::Cover::unrouted) [`cover`] that holds a canvas
25//! saturation/brightness field, a hue strip, an opacity strip and a preset palette. Every part
26//! of it is Rust that already runs everywhere, so it is the same picker on all nine targets.
27//!
28//! [`PickerIdiom::Automatic`], the default, is `Native` where the toolkit has a chooser and
29//! `Composed` where it does not. Two toolkits have none at any layer: Android ships no color
30//! picker in the framework, in Material, or in `AndroidX`, and HarmonyOS has none in ArkTS or in the
31//! ArkUI NDK. Rather than each of those growing a hand-written dialog in its own language, they
32//! get the composed panel, which is also why an app that wants one picker everywhere can just ask
33//! for it.
34//!
35//! The value is Day's ordinary [`Color`], so the same signal drives `.tint(…)`, `.background(…)`,
36//! a canvas fill or a gradient stop with no conversion; see [color guide](https://daybrite.dev/docs/reference/color/) for what
37//! that currency does and does not carry across from a native pick.
38//!
39//! The native leaf also accepts `Event::TextChanged` carrying any form [`Color::parse`] reads
40//! (`"#e86a3c"`, `"#e86a3c80"`, `"0.91 0.42 0.24 1"`) as a synthetic pick, so dayscript's `input:`
41//! step drives it on every backend.
42
43use crate::prelude::*;
44use crate::{IntoText, TextSource};
45use day_core::{BuildCx, Flex, Piece, RNode, with_tree};
46use day_reactive::{Binding, bind_seeded, watch};
47use day_spec::{Event, Support};
48
49pub use day_spec::controls::colorpicker::*;
50
51/// Which chooser a [`ColorPicker`] opens.
52#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
53pub enum PickerIdiom {
54 /// The platform's own chooser where the toolkit has one; Day's composed panel where it does
55 /// not (android-material and harmony-arkui). The default, and what an app wants unless it has a
56 /// reason to pin the answer.
57 #[default]
58 Automatic,
59 /// The platform's own chooser, on the nose: this realizes the native leaf whatever the
60 /// backend is, so on a toolkit with no renderer for it the app gets Day's visible
61 /// `⟨day.piece.colorpicker⟩` placeholder, the same answer any unrendered kind gives, and a
62 /// gap a screenshot can see. Pin this only behind a [`support`] check; if you want "native
63 /// where there is one", that is [`Automatic`](PickerIdiom::Automatic).
64 Native,
65 /// Day's composed panel, on every target. Ask for this when one identical color experience
66 /// matters more than platform chrome: a design tool, a themed app, a branded editor.
67 Composed,
68}
69
70/// Whether the compiled backend has a native color chooser, which is what
71/// [`PickerIdiom::Automatic`] resolves against.
72///
73/// [`Support::Native`] on appkit, uikit, gtk, qt, xaml and web-dom. [`Support::Emulated`] on
74/// android-material and harmony-arkui, where `Automatic` gives the composed panel instead.
75///
76/// This does not report whether the picker works (there is no target where it does not), so an
77/// app showing a "not supported here" banner from this answer would be wrong. Use it to say
78/// *which* picker the user gets, or ignore it, unless the app pins [`PickerIdiom::Native`]:
79/// that realizes the leaf unconditionally and so does need this checked first.
80#[must_use]
81pub fn support() -> day_spec::Support {
82 let support = day_core::capability(day_spec::Cap::ColorPicker);
83 if support == day_spec::Support::Unsupported {
84 day_spec::Support::Emulated
85 } else {
86 support
87 }
88}
89
90/// The palette the composed panel offers when the app names none: one hue ring at full
91/// saturation, plus the grayscale ends. Ordered by hue so the row reads as a spectrum.
92fn default_presets() -> Vec<Color> {
93 let mut v: Vec<Color> = (0..12)
94 .map(|i| Color::hsv(f64::from(i) * 30.0, 0.78, 0.92))
95 .collect();
96 v.push(Color::WHITE);
97 v.push(Color::rgb(0.6, 0.6, 0.62));
98 v.push(Color::BLACK);
99 v
100}
101
102/// A color well bound two-way to a [`Color`] signal. Build with [`color_picker`].
103#[must_use]
104pub struct ColorPicker<C: Binding<Color>> {
105 color: C,
106 alpha: bool,
107 idiom: PickerIdiom,
108 title: Option<TextSource>,
109 presets: Option<Vec<Color>>,
110 key: day_core::ElementId,
111}
112
113/// `color_picker(color)` is a swatch showing `color` that opens a color chooser. `color` is a
114/// `Signal<Color>` or any other two-way binding (a day-model `Field`, mapped).
115pub fn color_picker<C: Binding<Color>>(color: C) -> ColorPicker<C> {
116 // web-dom's registry is populated at runtime (no `linkme` on wasm), and a constructor always
117 // runs before the node it returns is realized, so this is where the arm registers itself.
118 ColorPicker {
119 color,
120 alpha: false,
121 idiom: PickerIdiom::Automatic,
122 title: None,
123 presets: None,
124 key: day_core::id!(color_picker),
125 }
126}
127
128#[crate::builder(ColorPickerBuilder)]
129impl<C: Binding<Color>> ColorPicker<C> {
130 /// Offer an opacity channel, and let the bound signal carry a non-opaque alpha. Honored by
131 /// the composed panel everywhere, and by every native chooser but one: a browser's
132 /// `<input type="color">` gained an `alpha` attribute only recently, so the web arm sets it
133 /// and stays opaque where the browser has not shipped it (docs/colorpicker.md).
134 pub fn alpha(mut self) -> Self {
135 self.alpha = true;
136 self
137 }
138 /// Which chooser this well opens (see [`PickerIdiom`]).
139 pub fn idiom(mut self, idiom: PickerIdiom) -> Self {
140 self.idiom = idiom;
141 self
142 }
143 /// Pin this well to the platform's chooser, [`PickerIdiom::Native`].
144 pub fn native(self) -> Self {
145 self.idiom(PickerIdiom::Native)
146 }
147 /// Pin this well to Day's composed panel, [`PickerIdiom::Composed`].
148 pub fn composed(self) -> Self {
149 self.idiom(PickerIdiom::Composed)
150 }
151 /// The chooser's heading. Native: the iOS picker's navigation title, the GTK dialog heading,
152 /// `QColorDialog`'s window title, the XAML button's tooltip; AppKit sets the shared color
153 /// panel's title. Composed: the panel's own heading. A constant, `Signal<String>` or closure,
154 /// read once at build.
155 pub fn title<M>(mut self, t: impl IntoText<M>) -> Self {
156 self.title = Some(t.into_text());
157 self
158 }
159 /// The swatch row the composed panel offers below its strips (ignored by the native
160 /// choosers, which each have their own palette). Pass an empty vector to drop the row.
161 pub fn presets(mut self, presets: Vec<Color>) -> Self {
162 self.presets = Some(presets);
163 self
164 }
165 /// The composed well's dayscript id (default `"color-picker"`).
166 ///
167 /// It goes here rather than on `Decorate::id` because what an app can reach from outside is
168 /// the layout wrapper the piece returns, and an id on that tags a node no toolkit realizes;
169 /// a `tap:` against it resolves to nothing while every step still reports ✓. Give two
170 /// composed pickers on one page different keys so a script can tell them apart.
171 ///
172 /// The panel's own parts carry fixed ids (`color-picker-panel`, `-shade`, `-hue`,
173 /// `-opacity`, `-presets`, `-value`, `-cancel`, `-done`); only one panel is ever open, so
174 /// they need no disambiguation.
175 pub fn id(mut self, id: day_core::ElementId) -> Self {
176 self.key = id;
177 self
178 }
179}
180
181impl<C: Binding<Color>> Piece for ColorPicker<C> {
182 fn build(self, cx: &mut BuildCx) -> RNode {
183 let ColorPicker {
184 color,
185 alpha,
186 idiom,
187 title,
188 presets,
189 key,
190 } = self;
191 let title = title.map_or_default(|t| t.initial());
192 let native = match idiom {
193 PickerIdiom::Composed => false,
194 PickerIdiom::Native => true,
195 PickerIdiom::Automatic => support() == Support::Native,
196 };
197 if native {
198 build_native(cx, color, alpha, title, &key)
199 } else {
200 composed_well(
201 color,
202 alpha,
203 title,
204 presets.unwrap_or_else(default_presets),
205 &key,
206 )
207 .build(cx)
208 }
209 }
210}
211
212/// The native idiom: one leaf of [`KIND`], bound two-way.
213fn build_native<C: Binding<Color>>(
214 cx: &mut BuildCx,
215 color: C,
216 alpha: bool,
217 title: String,
218 key: &day_core::ElementId,
219) -> RNode {
220 let initial = color.peek();
221 let node = cx.leaf(
222 KIND,
223 &ColorProps {
224 color: initial,
225 alpha,
226 title,
227 },
228 Flex::default(),
229 );
230 // The leaf's dayscript id: one `.key` serves both idioms (the day-piece-stepper rule:
231 // `Decorate::id` on the piece would tag a wrapper no toolkit realizes).
232 with_tree(|t| t.set_id(node, key.as_str().to_owned()));
233 // App writes → the native well. Every arm no-ops on an unchanged value, so a pick echoing
234 // back through the signal never loops.
235 let c2 = color.clone();
236 bind_seeded(
237 initial,
238 move || c2.read(),
239 move |c: &Color| {
240 with_tree(|t| t.patch(node, Box::new(ColorPatch::SetColor(*c)), false));
241 },
242 );
243 // Native picks (`Custom`, carrying the lossless component form) and dayscript's `input:` step
244 // (`TextChanged`, carrying whatever a human typed) → the signal. Both go through
245 // `Color::parse`, which reads hex and components alike, so there is one decode path.
246 cx.on(node, move |ev| {
247 let picked = match ev {
248 Event::Custom { text, .. } => Color::parse(text),
249 Event::TextChanged(s) => Color::parse(s),
250 _ => None,
251 };
252 if let Some(c) = picked {
253 // An opaque-only picker must not be able to clear the alpha the app set.
254 color.write(if alpha { c } else { c.with_alpha(1.0) });
255 }
256 });
257 node
258}
259
260// ===========================================================================
261// The composed idiom: ordinary Day pieces, no native code, identical on all nine targets.
262// ===========================================================================
263
264/// The saturation/brightness field, in points. Fixed rather than fluid: a picker panel is a
265/// fixed-size object on every platform that has one, and a known size is what lets a press
266/// location become a value without the canvas having to report its own bounds first.
267const FIELD_W: f64 = 264.0;
268const FIELD_H: f64 = 160.0;
269/// The shade field's corner rounding. Drawn inside the canvas rather than asked of the toolkit
270/// as a `corner_radius`, which is a view-level outline clip: on Android that is
271/// `setClipToOutline`, the one thing this panel does that nothing else in the app does, and a
272/// clip a canvas can apply to its own drawing costs the toolkit nothing on any target.
273const FIELD_R: f64 = 10.0;
274/// The hue and opacity strips.
275const STRIP_H: f64 = 20.0;
276/// One preset swatch.
277const SWATCH: f64 = 26.0;
278/// The panel card. `FIELD_W` plus its padding on both sides.
279const CARD_PAD: f64 = 18.0;
280const CARD_W: f64 = FIELD_W + CARD_PAD * 2.0;
281
282/// The panel is a neutral dark surface on every target, light appearance included, and its text
283/// color is stated rather than inherited.
284///
285/// A bright surround biases color judgment (the reason every serious color tool sits its swatches
286/// on a dark neutral), so a picker that flipped to a white card in light mode would make the same
287/// pick look like a different color. And a card whose fill this piece chose cannot then take the
288/// platform's label color for its text: on a light-appearance device that resolves to black, which
289/// is what put dark-on-dark text in the first iOS screenshot of this panel.
290const PANEL_SURFACE: Color = Color::rgb(0.13, 0.14, 0.17);
291const PANEL_TEXT: Color = Color::rgb(0.93, 0.94, 0.96);
292
293/// The well, in points: wide enough for its caption at the caption size: `#rrggbbaa` when the
294/// picker carries alpha, `#rrggbb` when it does not, since a row beside a slider in a narrow
295/// inspector has no width to spare.
296fn well_width(alpha: bool) -> f64 {
297 if alpha { 96.0 } else { 72.0 }
298}
299const WELL_H: f64 = 26.0;
300
301/// The well itself: a drawn swatch showing the current color and its hex, which presents the
302/// panel when pressed.
303///
304/// Drawn rather than a `button(hex).tint(color)`, even though a tinted button is native and
305/// carries press feedback and focus with no extra work. What the composed idiom promises is one
306/// picker, identical on every target, and a tinted button is the opposite of identical: AppKit
307/// composites the color through the bezel, Material draws a filled container with its own
308/// elevation, GTK and Qt apply it through their themes, and the web takes CSS. The color would
309/// read differently on all nine. A canvas draws the color the app asked for.
310///
311/// The trade is keyboard activation: a drawn well takes a press, not a Return key. It carries a
312/// `Button` role and a label so a screen reader still announces it correctly
313/// (docs/colorpicker.md records the gap).
314fn composed_well<C: Binding<Color>>(
315 color: C,
316 alpha: bool,
317 title: String,
318 presets: Vec<Color>,
319 key: &day_core::ElementId,
320) -> AnyPiece {
321 let open: Signal<Option<String>> = Signal::new(None);
322 let open_key = key.as_str().to_owned();
323 // The id goes on the canvas, here, rather than being left to the app: what the app can reach
324 // is the `zstack` this returns, and an id on that tags a layout wrapper the toolkit never
325 // realizes; a dayscript `tap:` against it would resolve to nothing while every step still
326 // reported ✓. The route key doubles as the id, so one name identifies the well both ways.
327 let cw = color.clone();
328 let well = canvas(move |d, size| {
329 let c = cw.read();
330 let r = Rect::new(0.0, 0.0, size.width, size.height);
331 if c.a < 1.0 {
332 checkerboard(d, size);
333 }
334 d.fill(Shape::RoundedRect(r, 7.0), c);
335 d.stroke(
336 Shape::RoundedRect(r.inset(0.5), 7.0),
337 Color::BLACK.with_alpha(0.25),
338 1.0,
339 );
340 d.text(
341 &c.to_hex_string(),
342 Point::new(size.width / 2.0, size.height / 2.0),
343 TextStyle {
344 size: 12.0,
345 // Day's own readable-on-a-fill rule, the one `Button::tint` uses.
346 color: day_spec::props::ButtonStyleSpec::on_tint(c).into(),
347 anchor: TextAnchor::CENTERED,
348 ..Default::default()
349 },
350 );
351 })
352 .on_tap(move || open.set(Some(open_key.clone())))
353 .a11y(|a| {
354 a.role(Role::Button)
355 .label(day_localization::t(day_localization::key::day_color))
356 })
357 .id(key.clone())
358 .frame(well_width(alpha), WELL_H);
359 zstack((
360 well,
361 cover(open, move |_| {
362 panel(color.clone(), alpha, title.clone(), presets.clone(), open)
363 })
364 // The panel's ground. `cover` paints this edge-to-edge (under the status bar and home
365 // indicator); the emulated tier forces it opaque, so a dim scrim would read as flat gray
366 // on six of the nine targets. A near-black ground that the card sits on reads the same
367 // everywhere instead.
368 .background(|_: &String| Color::rgba(0.06, 0.07, 0.09, 0.92))
369 // Kept out of the app's route space. A routed cover over the untyped `String` route
370 // claims every segment (`String::from_key` accepts anything), so mounting this picker
371 // would have made the host app's next `navigate("settings")` present a color panel keyed
372 // "settings" instead of going to settings. A chooser is not a destination; the piece
373 // opens and closes it, and Android's system back still dismisses it (that path is the
374 // cover's own `NavBack` handler, not the route adapter).
375 .unrouted(),
376 ))
377 .any()
378}
379
380/// The presented panel: the card, centered on the cover's surface.
381fn panel<C: Binding<Color>>(
382 color: C,
383 alpha: bool,
384 title: String,
385 presets: Vec<Color>,
386 open: Signal<Option<String>>,
387) -> AnyPiece {
388 // The panel's state is HSV, not the bound color. Deriving hue from RGB on every
389 // change would lose it the moment brightness reached zero (black has no hue), so the sliders
390 // would jump back to red as the user dragged into the corner. Seeded once per presentation.
391 let entry = color.peek();
392 let (h0, s0, v0) = entry.to_hsv();
393 let hue = Signal::new(h0);
394 let sat = Signal::new(s0);
395 let val = Signal::new(v0);
396 let opacity = Signal::new(entry.a);
397
398 // HSV → the bound color, live: the app sees the tint move as the user drags, the same as
399 // every native chooser reports continuously. `watch` skips the initial run, so opening the
400 // panel does not rewrite the signal with a round-tripped copy of what it already holds.
401 watch(
402 move || {
403 Color::hsva(
404 hue.get(),
405 sat.get(),
406 val.get(),
407 if alpha { opacity.get() } else { 1.0 },
408 )
409 },
410 {
411 let color = color.clone();
412 move |c: &Color, _| color.write(*c)
413 },
414 );
415
416 let current = move || {
417 Color::hsva(
418 hue.get(),
419 sat.get(),
420 val.get(),
421 if alpha { opacity.get() } else { 1.0 },
422 )
423 };
424
425 let close = move || open.set(None);
426 let cancel = move || {
427 color.write(entry);
428 open.set(None);
429 };
430
431 let mut rows: Vec<AnyPiece> = Vec::new();
432 if !title.is_empty() {
433 rows.push(label(title).font(Font::Headline).color(PANEL_TEXT).any());
434 }
435 rows.push(shade_field(hue, sat, val));
436 rows.push(hue_strip(hue));
437 if alpha {
438 rows.push(opacity_strip(current, opacity));
439 }
440 rows.push(readout(current));
441 if !presets.is_empty() {
442 rows.push(preset_row(presets, hue, sat, val, opacity, alpha));
443 }
444 rows.push(
445 row((
446 button(day_localization::t(day_localization::key::day_cancel))
447 .action(cancel)
448 .id(day_core::id!(color_picker_cancel)),
449 spacer(),
450 button(day_localization::t(day_localization::key::day_done))
451 .action(close)
452 .id(day_core::id!(color_picker_done)),
453 ))
454 .grow(Dimension::Width)
455 .any(),
456 );
457
458 let card = column(rows)
459 .spacing(12.0)
460 .align(HAlign::Leading)
461 .padding(CARD_PAD)
462 .background(PANEL_SURFACE)
463 .corner_radius(16.0)
464 .width(CARD_W)
465 .id(day_core::id!(color_picker_panel));
466
467 // Centered both ways: spacers above and below push it to the middle vertically, and the
468 // column's own cross-axis alignment centers it horizontally.
469 //
470 // Not `row((spacer(), card, spacer()))` for the horizontal half, which is the obvious
471 // spelling and the wrong one: a cover lays its content out once before the backend reports
472 // the surface's size, so that row measures a 300pt card against a 0pt width and Day's
473 // overflow diagnostic fires, naming this panel's ids on every single open. A cross-aligned
474 // column has nothing to overflow.
475 column((spacer(), card, spacer()))
476 .align(HAlign::Center)
477 .grow(Dimension::Both)
478 .any()
479}
480
481/// The saturation/brightness field for the current hue: the pure hue, washed to white across and
482/// to black down. Three fills, which is exactly how every native picker draws the same square,
483/// and it stays crisp at any size because two of them are gradients rather than a bitmap.
484fn shade_field(hue: Signal<f64>, sat: Signal<f64>, val: Signal<f64>) -> AnyPiece {
485 let pick = move |p: Point| {
486 sat.set((p.x / FIELD_W).clamp(0.0, 1.0));
487 val.set(1.0 - (p.y / FIELD_H).clamp(0.0, 1.0));
488 };
489 canvas(move |d, size| {
490 let r = Rect::new(0.0, 0.0, size.width, size.height);
491 d.clipped(Shape::RoundedRect(r, FIELD_R), |d| {
492 d.fill(Shape::Rect(r), Color::hsv(hue.get(), 1.0, 1.0));
493 d.fill(
494 Shape::Rect(r),
495 LinearGradient::horizontal(Color::WHITE, Color::WHITE.with_alpha(0.0)),
496 );
497 d.fill(
498 Shape::Rect(r),
499 LinearGradient::vertical(Color::BLACK.with_alpha(0.0), Color::BLACK),
500 );
501 marker(
502 d,
503 Point::new(sat.get() * size.width, (1.0 - val.get()) * size.height),
504 7.0,
505 );
506 });
507 })
508 // Gestures go on the canvas, before any wrapper: `Event::Tap`/`Event::Drag` report a point in
509 // the node's own space, and a wrapper's space is not the canvas's. Both are wired because a
510 // press that never moves is a tap on some backends and a zero-length drag on others; they
511 // write the same two values, so a backend that reports both costs nothing.
512 .on_drag(move |drag| pick(drag.location))
513 .on_tap_at(pick)
514 .a11y(|a| a.label(day_localization::t(day_localization::key::day_color_shade)))
515 // The id before the frame, so it names the canvas the gestures live on.
516 .id(day_core::id!(color_picker_shade))
517 .frame(FIELD_W, FIELD_H)
518 .any()
519}
520
521/// The hue strip: one linear gradient through the six primaries and back to red.
522fn hue_strip(hue: Signal<f64>) -> AnyPiece {
523 let pick = move |p: Point| hue.set((p.x / FIELD_W).clamp(0.0, 1.0) * 360.0);
524 canvas(move |d, size| {
525 let r = Rect::new(0.0, 0.0, size.width, size.height);
526 let stops: Vec<(f64, Color)> = (0..=6)
527 .map(|i| {
528 (
529 f64::from(i) / 6.0,
530 Color::hsv(f64::from(i) * 60.0, 1.0, 1.0),
531 )
532 })
533 .collect();
534 d.fill(
535 Shape::RoundedRect(r, size.height / 2.0),
536 LinearGradient::new(UnitPoint::LEADING, UnitPoint::TRAILING, stops),
537 );
538 slider_thumb(d, hue.get() / 360.0, size);
539 })
540 .on_drag(move |drag| pick(drag.location))
541 .on_tap_at(pick)
542 .a11y(|a| a.label(day_localization::t(day_localization::key::day_color_hue)))
543 // The id before the frame, so it names the canvas the gestures live on.
544 .id(day_core::id!(color_picker_hue))
545 .frame(FIELD_W, STRIP_H)
546 .any()
547}
548
549/// The opacity strip: the current color faded across, over the checkerboard that is the only way
550/// to tell "transparent" from "white" on a light ground.
551fn opacity_strip(current: impl Fn() -> Color + 'static, opacity: Signal<f64>) -> AnyPiece {
552 let pick = move |p: Point| opacity.set((p.x / FIELD_W).clamp(0.0, 1.0));
553 canvas(move |d, size| {
554 let r = Rect::new(0.0, 0.0, size.width, size.height);
555 // The checkerboard is the one thing on a strip that has to be CLIPPED: it is a grid of
556 // squares and the pill's caps have to cut it. Everything over it is a rounded fill of
557 // that same pill, which needs no clip of its own.
558 d.clipped(Shape::RoundedRect(r, size.height / 2.0), |d| {
559 checkerboard(d, size);
560 });
561 let opaque = current().with_alpha(1.0);
562 d.fill(
563 Shape::RoundedRect(r, size.height / 2.0),
564 LinearGradient::horizontal(opaque.with_alpha(0.0), opaque),
565 );
566 slider_thumb(d, opacity.get(), size);
567 })
568 .on_drag(move |drag| pick(drag.location))
569 .on_tap_at(pick)
570 .a11y(|a| {
571 a.label(day_localization::t(
572 day_localization::key::day_color_opacity,
573 ))
574 })
575 // The id before the frame, so it names the canvas the gestures live on.
576 .id(day_core::id!(color_picker_opacity))
577 .frame(FIELD_W, STRIP_H)
578 .any()
579}
580
581/// A wrapping row of preset swatches. `RowFit::Wrap` rather than a grid: the palette is however
582/// many colors the app passed, and the row is however wide the card is (docs/size-classes.md).
583fn preset_row(
584 presets: Vec<Color>,
585 hue: Signal<f64>,
586 sat: Signal<f64>,
587 val: Signal<f64>,
588 opacity: Signal<f64>,
589 alpha: bool,
590) -> AnyPiece {
591 let swatches: Vec<AnyPiece> = presets
592 .into_iter()
593 .map(|c| {
594 canvas(move |d, size| {
595 let r = Rect::new(0.0, 0.0, size.width, size.height);
596 if c.a < 1.0 {
597 checkerboard(d, size);
598 }
599 d.fill(Shape::RoundedRect(r, 6.0), c);
600 d.stroke(
601 Shape::RoundedRect(r.inset(0.5), 6.0),
602 Color::WHITE.with_alpha(0.22),
603 1.0,
604 );
605 })
606 .on_tap(move || {
607 let (h, s, v) = c.to_hsv();
608 hue.set(h);
609 sat.set(s);
610 val.set(v);
611 if alpha {
612 opacity.set(c.a);
613 }
614 })
615 .frame(SWATCH, SWATCH)
616 .any()
617 })
618 .collect();
619 row(swatches)
620 .spacing(6.0)
621 .fit(RowFit::Wrap { run_spacing: 6.0 })
622 .grow(Dimension::Width)
623 .id(day_core::id!(color_picker_presets))
624 .any()
625}
626
627/// The current color, large, over a checkerboard, with its hex beside it.
628fn readout(current: impl Fn() -> Color + Copy + 'static) -> AnyPiece {
629 row((
630 canvas(move |d, size| {
631 checkerboard(d, size);
632 d.fill(
633 Shape::RoundedRect(Rect::new(0.0, 0.0, size.width, size.height), 7.0),
634 current(),
635 );
636 })
637 .frame(44.0, 28.0),
638 label(move || current().to_hex_string())
639 .monospace()
640 .color(PANEL_TEXT)
641 .id(day_core::id!(color_picker_value)),
642 ))
643 .spacing(10.0)
644 .align(VAlign::Center)
645 .any()
646}
647
648/// The ring that marks the picked point in the shade field: white over a dark halo, so it stays
649/// visible against both ends of the field it sits on.
650fn marker(d: &mut Draw, at: Point, radius: f64) {
651 let ring = |r: f64| Shape::Ellipse(Rect::new(at.x - r, at.y - r, r * 2.0, r * 2.0));
652 d.stroke(ring(radius + 1.0), Color::BLACK.with_alpha(0.45), 3.0);
653 d.stroke(ring(radius), Color::WHITE, 2.0);
654}
655
656/// The thumb on a strip: a full-height capsule, so it reads at 20 points tall. `t` is the value
657/// it marks, as a fraction of the track.
658///
659/// Its center is held half a thumb-width inside each end, because the strips draw their gradient
660/// as a rounded fill rather than a rect behind a rounded clip, so nothing would cut a thumb that
661/// ran off the cap. Clipping is what used to hide it, at the cost of showing half a thumb at
662/// either extreme; holding it whole reads better and asks the rasterizer for one shape fewer.
663fn slider_thumb(d: &mut Draw, t: f64, size: Size) {
664 const W: f64 = 8.0;
665 // A cover lays its content out once before the surface reports its size, so a strip is drawn
666 // at zero width first (the same first pass `panel` centers its card around). The travel has
667 // to collapse to the middle there rather than invert: `clamp` panics on crossed bounds, and
668 // that panic is contained but leaves the whole panel half-built.
669 let half = W / 2.0;
670 let (lo, hi) = if size.width >= W {
671 (half, size.width - half)
672 } else {
673 (size.width / 2.0, size.width / 2.0)
674 };
675 let x = (t.clamp(0.0, 1.0) * size.width).clamp(lo, hi);
676 let r = Rect::new(x - W / 2.0, 0.0, W, size.height);
677 d.fill(Shape::RoundedRect(r, W / 2.0), Color::WHITE);
678 // The inset rect is a thumb-width minus one, so its corner radius has to come down with it:
679 // the old 4.0 against a 7.0-wide rect asked for radii wider than the shape they round.
680 d.stroke(
681 Shape::RoundedRect(r.inset(0.5), W / 2.0 - 0.5),
682 Color::BLACK.with_alpha(0.4),
683 1.0,
684 );
685}
686
687/// The transparency checkerboard every color tool draws behind a partly transparent swatch.
688fn checkerboard(d: &mut Draw, size: Size) {
689 const CELL: f64 = 6.0;
690 d.fill(
691 Shape::Rect(Rect::new(0.0, 0.0, size.width, size.height)),
692 Color::rgb(0.86, 0.86, 0.88),
693 );
694 let cols = (size.width / CELL).ceil() as i64;
695 let rows = (size.height / CELL).ceil() as i64;
696 for row_i in 0..rows {
697 for col in 0..cols {
698 if (row_i + col) % 2 == 0 {
699 continue;
700 }
701 let x = col as f64 * CELL;
702 let y = row_i as f64 * CELL;
703 d.fill(
704 Shape::Rect(Rect::new(
705 x,
706 y,
707 CELL.min(size.width - x),
708 CELL.min(size.height - y),
709 )),
710 Color::rgb(0.66, 0.66, 0.69),
711 );
712 }
713 }
714}
715
716// ---------------------------------------------------------------------------
717// Per-toolkit native renderers, one file per backend, for the six toolkits that have a color
718// chooser. Every module registers a `Renderer` into its backend's `RENDERERS` slice link-time;
719// `dom` registers at runtime from `color_picker`. android-material and harmony-arkui carry no arm at
720// all: the composed panel above is their picker.
721// ---------------------------------------------------------------------------
722
723// --- Typed builders, forwarded through `Decorated` (docs/api-style.md) ---
724
725/// The color picker's conformance cases (docs/testing.md): the composed panel, identical on
726/// every toolkit.
727#[cfg(feature = "conformance")]
728pub mod conformance {
729 use crate::*;
730 use day_core::conformance::{Case, Drive};
731 use day_reactive::Signal;
732 use day_spec::Color;
733
734 use super::{KIND, color_picker};
735
736 fn hex(c: Color) -> String {
737 let ch = |v: f64| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
738 format!("#{:02x}{:02x}{:02x}", ch(c.r), ch(c.g), ch(c.b))
739 }
740
741 /// The well opens the panel on the current color; a press in the shade field's white corner
742 /// picks white, and Done writes it back.
743 #[day_macros::test(day_core)]
744 fn colorpicker_composed_picks() -> Case {
745 Case::new()
746 .proves(KIND)
747 .page(|| {
748 let tint = Signal::new(Color::rgb(232.0 / 255.0, 106.0 / 255.0, 60.0 / 255.0));
749 column((
750 label(move || format!("tint {}", hex(tint.get())))
751 .id(day_core::id!(colorpicker::tint_value)),
752 color_picker(tint)
753 .composed()
754 .id(day_core::id!(colorpicker::tint)),
755 ))
756 })
757 .drive(|d: Drive| async move {
758 d.tap("colorpicker::tint").await?;
759 d.wait_idle().await?;
760 d.assert_visible("color_picker_panel").await?;
761 d.assert_text("color_picker_value", "#e86a3c").await?;
762 d.tap_at("color_picker_shade", 0.0, 0.0).await?;
763 d.assert_text("color_picker_value", "#ffffff").await?;
764 d.tap("color_picker_done").await?;
765 d.wait_idle().await?;
766 d.assert_text("colorpicker::tint_value", "tint #ffffff")
767 .await
768 })
769 }
770}