leptos-use/src/use_preferred_contrast.rs

68 lines
1.8 KiB
Rust
Raw Normal View History

2023-06-10 19:15:41 +01:00
use crate::use_media_query;
use leptos::*;
use std::fmt::Display;
/// Reactive [prefers-contrast](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast) media query.
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::use_preferred_contrast;
/// #
/// # #[component]
2023-07-27 18:06:36 +01:00
/// # fn Demo() -> impl IntoView {
/// #
2023-07-27 18:06:36 +01:00
/// let preferred_contrast = use_preferred_contrast();
/// #
2023-07-27 18:06:36 +01:00
/// # view! { }
/// # }
/// ```
///
2023-07-14 22:43:19 +01:00
/// ## Server-Side Rendering
///
/// On the server this returns a `Signal` that always contains the value `PreferredContrast::NoPreference`.
///
/// ## See also
///
/// * [`use_media_query`]
/// * [`use_preferred_dark`]
2023-07-27 18:06:36 +01:00
pub fn use_preferred_contrast() -> Signal<PreferredContrast> {
let is_more = use_media_query("(prefers-contrast: more)");
let is_less = use_media_query("(prefers-contrast: less)");
let is_custom = use_media_query("(prefers-contrast: custom)");
2023-07-27 18:06:36 +01:00
Signal::derive(move || {
if is_more.get() {
PreferredContrast::More
} else if is_less.get() {
PreferredContrast::Less
} else if is_custom.get() {
PreferredContrast::Custom
} else {
PreferredContrast::NoPreference
}
})
}
/// Return value for [`use_preferred_contrast`]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PreferredContrast {
More,
Less,
Custom,
#[default]
NoPreference,
}
impl Display for PreferredContrast {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
PreferredContrast::More => write!(f, "more"),
PreferredContrast::Less => write!(f, "less"),
PreferredContrast::Custom => write!(f, "custom"),
PreferredContrast::NoPreference => write!(f, "no-preference"),
}
}
}