Skip to main content

day_spec/
ink.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! The color a view is drawn in (docs/color.md): [`Ink`], which is a fixed [`Color`], a
5//! light/dark pair or a [`SystemColor`] role, and the [`Palette`] every role resolves against.
6//!
7//! `Color` stays the concrete sRGB value an app computes with. `Ink` is what every color
8//! parameter of a view takes, so a color that differs by appearance is a value, written once,
9//! and the toolkit follows the appearance with no app code running: a dynamic `NSColor` or
10//! `UIColor`, a CSS custom property, or a re-apply when a toolkit without dynamic colors sees
11//! the theme change.
12
13use std::cell::Cell;
14
15use crate::Color;
16
17/// A platform color role: what a color means, which each toolkit answers with its own
18/// palette (docs/color.md "System colors"). Pass a role wherever a color is taken
19/// (`.background(SystemColor::Surface)`, `label(..).color(SystemColor::Link)`) and the view
20/// follows the appearance, the accent and the contrast setting.
21///
22/// Every role maps to a real platform color on every toolkit, or to the documented
23/// light/dark pair in [`SystemColor::fallback`] where a platform has none.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25#[repr(u8)]
26pub enum SystemColor {
27    /// The app's accent: selection, the prominent button, a focus ring.
28    Accent,
29    /// Primary text.
30    Text,
31    /// De-emphasized text: a caption, a detail line.
32    SecondaryText,
33    /// The window's content background.
34    Background,
35    /// A region set off from the background: a panel, a card, a sidebar.
36    Surface,
37    /// Text a step quieter than secondary: a disabled-looking hint, a footnote.
38    TertiaryText,
39    /// A text field's placeholder.
40    Placeholder,
41    /// A link in running text.
42    Link,
43    /// A hairline between items: a rule, a list separator, a grid line.
44    Separator,
45    /// The fill of a control's track or well: a slider's track, a segmented control's
46    /// background, a search field.
47    ControlFill,
48    /// The background behind grouped sections (an inset grouped list, a settings page).
49    GroupedBackground,
50    /// A surface raised above the content: a popover, a menu, a sheet in dark appearance.
51    ElevatedSurface,
52    /// The highlight behind selected text or selected content the app draws itself. Text
53    /// keeps its own color on it.
54    Selection,
55    /// A destructive action or an error.
56    Destructive,
57    /// Success, a value that rose.
58    Success,
59    /// A warning, something to notice.
60    Warning,
61}
62
63impl SystemColor {
64    /// How many roles there are: the length of [`SystemColor::ALL`] and of a [`Palette`].
65    pub const COUNT: usize = 16;
66
67    /// All roles, in discriminant order (the wire order: a role crosses JNI, C++ and JS as its
68    /// position here).
69    pub const ALL: [Self; Self::COUNT] = [
70        Self::Accent,
71        Self::Text,
72        Self::SecondaryText,
73        Self::Background,
74        Self::Surface,
75        Self::TertiaryText,
76        Self::Placeholder,
77        Self::Link,
78        Self::Separator,
79        Self::ControlFill,
80        Self::GroupedBackground,
81        Self::ElevatedSurface,
82        Self::Selection,
83        Self::Destructive,
84        Self::Success,
85        Self::Warning,
86    ];
87
88    /// The role as its wire number: its position in [`SystemColor::ALL`].
89    #[must_use]
90    pub const fn wire(self) -> u8 {
91        self as u8
92    }
93
94    /// The role with wire number `n`, if there is one.
95    #[must_use]
96    pub const fn from_wire(n: u8) -> Option<SystemColor> {
97        if (n as usize) < Self::COUNT {
98            Some(Self::ALL[n as usize])
99        } else {
100            None
101        }
102    }
103
104    /// This role at opacity `alpha`, replacing the role's own alpha: a wash of the accent
105    /// behind a selected chip (`SystemColor::Accent.with_alpha(0.14)`).
106    #[must_use]
107    pub const fn with_alpha(self, alpha: f64) -> Ink {
108        Ink::System {
109            role: self,
110            alpha: Some(alpha),
111        }
112    }
113
114    /// Day's own light/dark pair for the role: what a toolkit answers where its platform has
115    /// no such color, and what [`Palette::fallback`] holds. Fixed sRGB colors, close to the
116    /// Apple system palette, not an approximation of a user-chosen accent.
117    #[must_use]
118    pub const fn fallback(self, dark: bool) -> Color {
119        match (self, dark) {
120            (Self::Accent, false) => Color::hex(0x000a_66ff),
121            (Self::Accent, true) => Color::hex(0x003f_83ff),
122            (Self::Text, false) => Color::hex(0x001d_1d1f),
123            (Self::Text, true) => Color::hex(0x00f5_f5f7),
124            (Self::SecondaryText, false) => Color::hex(0x006e_6e73),
125            (Self::SecondaryText, true) => Color::hex(0x0098_989d),
126            (Self::Background | Self::ElevatedSurface, false) => Color::hex(0x00ff_ffff),
127            (Self::Background, true) => Color::hex(0x001e_1e20),
128            (Self::Surface, false) => Color::hex(0x00f3_f2f7),
129            (Self::Surface, true) => Color::hex(0x002c_2c2e),
130            (Self::TertiaryText | Self::Placeholder, false) => rgba8(60, 60, 67, 0.3),
131            (Self::TertiaryText | Self::Placeholder, true) => rgba8(235, 235, 245, 0.3),
132            (Self::Link, false) => Color::hex(0x0000_66cc),
133            (Self::Link, true) => Color::hex(0x004d_a3ff),
134            (Self::Separator, false) => rgba8(60, 60, 67, 0.29),
135            (Self::Separator, true) => rgba8(84, 84, 88, 0.6),
136            (Self::ControlFill, false) => rgba8(120, 120, 128, 0.2),
137            (Self::ControlFill, true) => rgba8(120, 120, 128, 0.36),
138            (Self::GroupedBackground, false) => Color::hex(0x00f2_f2f7),
139            (Self::GroupedBackground, true) => Color::hex(0x0016_1618),
140            (Self::ElevatedSurface, true) => Color::hex(0x003a_3a3c),
141            (Self::Selection, false) => rgba8(10, 102, 255, 0.25),
142            (Self::Selection, true) => rgba8(63, 131, 255, 0.35),
143            (Self::Destructive, false) => Color::hex(0x00ff_3b30),
144            (Self::Destructive, true) => Color::hex(0x00ff_453a),
145            (Self::Success, false) => Color::hex(0x0034_c759),
146            (Self::Success, true) => Color::hex(0x0030_d158),
147            (Self::Warning, false) => Color::hex(0x00ff_9500),
148            (Self::Warning, true) => Color::hex(0x00ff_9f0a),
149        }
150    }
151}
152
153/// An sRGB color from 8-bit channels and a float alpha, for the translucent fallbacks.
154const fn rgba8(r: u8, g: u8, b: u8, a: f64) -> Color {
155    Color::rgba(r as f64 / 255.0, g as f64 / 255.0, b as f64 / 255.0, a)
156}
157
158/// The color a view is drawn in: a fixed color, a light/dark pair, or a platform role
159/// (docs/color.md). Every color parameter of a view takes `impl Into<Ink>`, so
160/// `Color::rgb(..)`, `SystemColor::Separator` and `Ink::adaptive(light, dark)` go anywhere a
161/// color does, and an `Ink` is a `const`:
162///
163/// ```
164/// use day_spec::{Color, Ink, SystemColor};
165/// const INSET: Ink = Ink::adaptive(Color::rgba(0.0, 0.0, 0.0, 0.045), Color::rgba(0.0, 0.0, 0.0, 0.26));
166/// const HAIRLINE: Ink = Ink::system(SystemColor::Separator);
167/// const BRAND: Ink = Ink::Fixed(Color::hex(0x00e8_6a3c));
168/// ```
169///
170/// A view keeps the ink, not a color resolved from it: the toolkit resolves it natively and
171/// follows an appearance switch with no app code running. Code that needs the numbers (a
172/// canvas, a contrast check) resolves an ink with `day::resolve(ink)`, a tracked read that
173/// re-runs the reader when the appearance changes.
174#[derive(Clone, Copy, Debug, PartialEq)]
175pub enum Ink {
176    /// The same color in every appearance.
177    Fixed(Color),
178    /// `light` in the light appearance, `dark` in the dark one.
179    Adaptive { light: Color, dark: Color },
180    /// A platform role, resolved by the toolkit. `alpha`, when set, replaces the role's own
181    /// opacity.
182    System {
183        role: SystemColor,
184        alpha: Option<f64>,
185    },
186}
187
188impl Default for Ink {
189    /// Transparent.
190    fn default() -> Self {
191        Ink::Fixed(Color::CLEAR)
192    }
193}
194
195impl From<Color> for Ink {
196    fn from(c: Color) -> Self {
197        Ink::Fixed(c)
198    }
199}
200
201impl From<SystemColor> for Ink {
202    fn from(role: SystemColor) -> Self {
203        Ink::system(role)
204    }
205}
206
207impl Ink {
208    /// Transparent.
209    pub const CLEAR: Ink = Ink::Fixed(Color::CLEAR);
210
211    /// `light` in the light appearance and `dark` in the dark one.
212    #[must_use]
213    pub const fn adaptive(light: Color, dark: Color) -> Ink {
214        Ink::Adaptive { light, dark }
215    }
216
217    /// The platform's color for `role`.
218    #[must_use]
219    pub const fn system(role: SystemColor) -> Ink {
220        Ink::System { role, alpha: None }
221    }
222
223    /// The same ink at opacity `alpha` in every appearance: both colors of a pair, and the
224    /// role's color with its own alpha replaced.
225    #[must_use]
226    pub const fn with_alpha(self, alpha: f64) -> Ink {
227        match self {
228            Ink::Fixed(c) => Ink::Fixed(Color::rgba(c.r, c.g, c.b, alpha)),
229            Ink::Adaptive { light, dark } => Ink::Adaptive {
230                light: Color::rgba(light.r, light.g, light.b, alpha),
231                dark: Color::rgba(dark.r, dark.g, dark.b, alpha),
232            },
233            Ink::System { role, .. } => Ink::System {
234                role,
235                alpha: Some(alpha),
236            },
237        }
238    }
239
240    /// The color, when it is the same in every appearance.
241    #[must_use]
242    pub const fn fixed(self) -> Option<Color> {
243        match self {
244            Ink::Fixed(c) => Some(c),
245            _ => None,
246        }
247    }
248
249    /// Whether the ink depends on the appearance or the platform: a pair or a role.
250    #[must_use]
251    pub const fn is_dynamic(self) -> bool {
252        !matches!(self, Ink::Fixed(_))
253    }
254
255    /// The color this ink is in `palette`'s appearance.
256    #[must_use]
257    pub fn resolve(self, palette: &Palette) -> Color {
258        match self {
259            Ink::Fixed(c) => c,
260            Ink::Adaptive { light, dark } => {
261                if palette.dark {
262                    dark
263                } else {
264                    light
265                }
266            }
267            Ink::System { role, alpha } => {
268                let c = palette.color(role);
269                alpha.map_or(c, |a| c.with_alpha(a))
270            }
271        }
272    }
273
274    /// The color this ink is right now, against the [`Palette::current`] Day keeps for the
275    /// app's appearance. What a toolkit without dynamic colors applies, and re-applies when
276    /// the appearance changes (docs/color.md "How a toolkit follows the appearance"). Not
277    /// tracked: app code reads `day::resolve(ink)` instead.
278    #[must_use]
279    pub fn resolved(self) -> Color {
280        self.resolve(&Palette::current())
281    }
282
283    /// The ink as three numbers for a shim in another language (Java, C++, JS): `[kind, a, b]`.
284    ///
285    /// | kind | `a` | `b` |
286    /// | --- | --- | --- |
287    /// | `0` fixed | the color as `0xAARRGGBB` | `0` |
288    /// | `1` pair | the light color as `0xAARRGGBB` | the dark color |
289    /// | `2` role | the role's [wire number](SystemColor::wire) | the alpha override as `0..=255`, or `256` for none |
290    ///
291    /// Channels are rounded to 8 bits. [`Ink::from_wire`] reads it back.
292    #[must_use]
293    pub fn wire(self) -> [u32; 3] {
294        match self {
295            Ink::Fixed(c) => [0, argb32(c), 0],
296            Ink::Adaptive { light, dark } => [1, argb32(light), argb32(dark)],
297            Ink::System { role, alpha } => [2, u32::from(role.wire()), alpha.map_or(256, channel8)],
298        }
299    }
300
301    /// The ink [`Ink::wire`] encoded, if the numbers are one.
302    #[must_use]
303    pub fn from_wire(wire: [u32; 3]) -> Option<Ink> {
304        match wire {
305            [0, c, _] => Some(Ink::Fixed(from_argb32(c))),
306            [1, l, d] => Some(Ink::adaptive(from_argb32(l), from_argb32(d))),
307            [2, role, alpha] => Some(Ink::System {
308                role: SystemColor::from_wire(u8::try_from(role).ok()?)?,
309                alpha: (alpha <= 255).then(|| f64::from(alpha) / 255.0),
310            }),
311            _ => None,
312        }
313    }
314
315    /// The pair this ink resolves to in the light and the dark appearance, roles answered
316    /// from `light` and `dark`. What a toolkit builds one dynamic native color from.
317    #[must_use]
318    pub fn pair(self, light: &Palette, dark: &Palette) -> (Color, Color) {
319        (self.resolve(light), self.resolve(dark))
320    }
321
322    /// A new ink made by applying `f` to this one's color in each appearance: the readable
323    /// text color on a fill, a darker shade of a brand color. A fixed ink stays fixed; a pair
324    /// maps both sides; a role is resolved against [`Palette::both`] first, so the result is a
325    /// pair that no longer follows a later change of the system accent.
326    #[must_use]
327    pub fn map(self, f: impl Fn(Color) -> Color) -> Ink {
328        match self {
329            Ink::Fixed(c) => Ink::Fixed(f(c)),
330            Ink::Adaptive { light, dark } => Ink::adaptive(f(light), f(dark)),
331            Ink::System { .. } => {
332                let (light, dark) = Palette::both();
333                let (l, d) = self.pair(&light, &dark);
334                Ink::adaptive(f(l), f(d))
335            }
336        }
337    }
338}
339
340/// A `0..=1` channel as `0..=255`.
341fn channel8(v: f64) -> u32 {
342    // In range by the clamp, so the cast cannot truncate or wrap.
343    #[expect(
344        clippy::cast_possible_truncation,
345        clippy::cast_sign_loss,
346        reason = "the value is clamped to 0..=255 and rounded first"
347    )]
348    let byte = (v.clamp(0.0, 1.0) * 255.0).round() as u32;
349    byte
350}
351
352/// A color as `0xAARRGGBB`.
353fn argb32(c: Color) -> u32 {
354    (channel8(c.a) << 24) | (channel8(c.r) << 16) | (channel8(c.g) << 8) | channel8(c.b)
355}
356
357/// `0xAARRGGBB` as a color.
358fn from_argb32(v: u32) -> Color {
359    let ch = |shift: u32| f64::from((v >> shift) & 0xff) / 255.0;
360    Color::rgba(ch(16), ch(8), ch(0), ch(24))
361}
362
363/// Gradient stops resolved for the current appearance ([`Ink::resolved`] on each): the form a
364/// toolkit hands a native gradient that takes concrete colors.
365#[must_use]
366pub fn resolved_stops(stops: &[(f64, Ink)]) -> Vec<(f64, Color)> {
367    stops
368        .iter()
369        .map(|(at, ink)| (*at, ink.resolved()))
370        .collect()
371}
372
373/// The color of every [`SystemColor`] role in one appearance: what an [`Ink`] resolves
374/// against. Day keeps the toolkit's answer for the app's current appearance as
375/// [`Palette::current`] and refreshes it when the appearance changes.
376#[derive(Clone, Copy, Debug, PartialEq)]
377pub struct Palette {
378    /// Whether this is the dark appearance.
379    pub dark: bool,
380    /// One color per role, in [`SystemColor::ALL`] order.
381    pub colors: [Color; SystemColor::COUNT],
382}
383
384thread_local! {
385    static CURRENT: Cell<Option<Palette>> = const { Cell::new(None) };
386}
387
388impl Palette {
389    /// Day's own palette for one appearance ([`SystemColor::fallback`] for every role).
390    #[must_use]
391    pub const fn fallback(dark: bool) -> Palette {
392        let mut colors = [Color::CLEAR; SystemColor::COUNT];
393        let mut i = 0;
394        while i < SystemColor::COUNT {
395            colors[i] = SystemColor::ALL[i].fallback(dark);
396            i += 1;
397        }
398        Palette { dark, colors }
399    }
400
401    /// The color of `role`.
402    #[must_use]
403    pub const fn color(&self, role: SystemColor) -> Color {
404        self.colors[role as usize]
405    }
406
407    /// The palette of the app's current appearance. Day sets it when the tree is installed and
408    /// whenever the toolkit reports an appearance change; before that it is Day's light
409    /// fallback (or the dark one under `DAY_THEME=dark`).
410    #[must_use]
411    pub fn current() -> Palette {
412        CURRENT.with(Cell::get).unwrap_or_else(|| {
413            Palette::fallback(std::env::var("DAY_THEME").ok().as_deref() == Some("dark"))
414        })
415    }
416
417    /// A light and a dark palette: the [current](Palette::current) one for its own appearance
418    /// and Day's [fallback](Palette::fallback) for the other, the best answer for an appearance
419    /// the toolkit is not showing.
420    #[must_use]
421    pub fn both() -> (Palette, Palette) {
422        let current = Palette::current();
423        if current.dark {
424            (Palette::fallback(false), current)
425        } else {
426            (current, Palette::fallback(true))
427        }
428    }
429
430    /// Make `palette` the current one. Called by Day's core when it reads the toolkit's
431    /// palette; a toolkit does not call it.
432    pub fn set_current(palette: Palette) {
433        CURRENT.with(|c| c.set(Some(palette)));
434    }
435}
436
437#[cfg(test)]
438mod tests {
439    use super::*;
440
441    #[test]
442    fn roles_round_trip_their_wire_numbers() {
443        for (i, role) in SystemColor::ALL.iter().enumerate() {
444            assert_eq!(role.wire() as usize, i);
445            assert_eq!(SystemColor::from_wire(role.wire()), Some(*role));
446        }
447        assert_eq!(SystemColor::from_wire(SystemColor::COUNT as u8), None);
448    }
449
450    #[test]
451    fn inks_resolve_per_appearance() {
452        let (light, dark) = (Palette::fallback(false), Palette::fallback(true));
453        let pair = Ink::adaptive(Color::WHITE, Color::BLACK);
454        assert_eq!(pair.resolve(&light), Color::WHITE);
455        assert_eq!(pair.resolve(&dark), Color::BLACK);
456        let role = Ink::from(SystemColor::Text);
457        assert_eq!(role.resolve(&dark), SystemColor::Text.fallback(true));
458        let wash = SystemColor::Accent.with_alpha(0.25).resolve(&light);
459        assert!((wash.a - 0.25).abs() < 1e-12);
460        assert_eq!(
461            Ink::from(Color::BLACK).with_alpha(0.5),
462            Ink::Fixed(Color::rgba(0.0, 0.0, 0.0, 0.5))
463        );
464        assert_eq!(pair.with_alpha(0.0).resolve(&dark).a, 0.0);
465        assert!(!Ink::from(Color::WHITE).is_dynamic() && pair.is_dynamic());
466    }
467
468    #[test]
469    fn inks_round_trip_their_wire_form() {
470        for ink in [
471            Ink::Fixed(Color::rgba(1.0, 0.0, 0.0, 0.5)),
472            Ink::adaptive(Color::WHITE, Color::BLACK),
473            Ink::system(SystemColor::Separator),
474            SystemColor::Accent.with_alpha(0.2),
475        ] {
476            let back = Ink::from_wire(ink.wire()).expect("decodes");
477            let (light, dark) = (Palette::fallback(false), Palette::fallback(true));
478            for p in [light, dark] {
479                let (a, b) = (ink.resolve(&p), back.resolve(&p));
480                assert!(
481                    (a.r - b.r).abs() < 0.003 && (a.a - b.a).abs() < 0.003,
482                    "{ink:?}"
483                );
484            }
485        }
486        assert_eq!(Ink::system(SystemColor::Link).wire(), [2, 7, 256]);
487        assert_eq!(Ink::from_wire([3, 0, 0]), None);
488        assert_eq!(Ink::from_wire([2, 99, 256]), None);
489    }
490
491    #[test]
492    fn the_current_palette_is_what_resolved_reads() {
493        let dark = Palette::fallback(true);
494        Palette::set_current(dark);
495        assert_eq!(
496            Ink::system(SystemColor::Background).resolved(),
497            SystemColor::Background.fallback(true)
498        );
499        Palette::set_current(Palette::fallback(false));
500        assert_eq!(
501            Ink::system(SystemColor::Background).resolved(),
502            Color::WHITE
503        );
504    }
505}