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