use std::time::Duration;
use dioxus::prelude::*;
use crate::time::sleep;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MotionDuration {
Fast,
Standard,
#[default]
Slow,
Entrance,
Scene,
}
impl MotionDuration {
pub fn as_str(self) -> &'static str {
match self {
Self::Fast => "fast",
Self::Standard => "standard",
Self::Slow => "slow",
Self::Entrance => "entrance",
Self::Scene => "scene",
}
}
pub fn milliseconds(self) -> u64 {
match self {
Self::Fast => 120,
Self::Standard => 160,
Self::Slow => 300,
Self::Entrance => 700,
Self::Scene => 1000,
}
}
pub(crate) fn class(self) -> String {
format!("ui-motion-duration-{}", self.as_str())
}
}
pub(crate) fn js_number(value: f64) -> String {
if value.is_nan() {
return "NaN".to_string();
}
if value.is_infinite() {
return if value > 0.0 { "Infinity" } else { "-Infinity" }.to_string();
}
if value == 0.0 {
return "0".to_string();
}
let magnitude = value.abs();
if (1e-6..1e21).contains(&magnitude) {
return format!("{value}");
}
let exponent = format!("{value:e}");
match exponent.split_once('e') {
Some((mantissa, power)) if !power.starts_with('-') => format!("{mantissa}e+{power}"),
_ => exponent,
}
}
pub(crate) fn js_round(value: f64) -> f64 {
(value + 0.5).floor()
}
pub(crate) fn merge_style(user: Option<&str>, own: &str) -> String {
let user = user
.map(|style| style.trim().trim_end_matches(';').trim_end())
.filter(|style| !style.is_empty());
match user {
Some(user) if own.is_empty() => user.to_string(),
Some(user) => format!("{user}; {own}"),
None => own.to_string(),
}
}
pub(crate) fn is_blank(value: &str) -> bool {
value.chars().all(|c| c.is_whitespace() || c == '\u{feff}')
}
const COMBINING_MARKS: &[(u32, u32)] = &[
(0x0300, 0x036F),
(0x0483, 0x0489),
(0x0591, 0x05BD),
(0x05BF, 0x05BF),
(0x05C1, 0x05C2),
(0x05C4, 0x05C5),
(0x05C7, 0x05C7),
(0x0610, 0x061A),
(0x064B, 0x065F),
(0x0670, 0x0670),
(0x06D6, 0x06DC),
(0x06DF, 0x06E4),
(0x06E7, 0x06E8),
(0x06EA, 0x06ED),
(0x0900, 0x0903),
(0x093A, 0x093C),
(0x093E, 0x094F),
(0x0951, 0x0957),
(0x0962, 0x0963),
(0x0981, 0x0983),
(0x09BC, 0x09BC),
(0x09BE, 0x09C4),
(0x09C7, 0x09C8),
(0x09CB, 0x09CD),
(0x09D7, 0x09D7),
(0x09E2, 0x09E3),
(0x0E31, 0x0E31),
(0x0E34, 0x0E3A),
(0x0E47, 0x0E4E),
(0x1AB0, 0x1AFF),
(0x1DC0, 0x1DFF),
(0x20D0, 0x20FF),
(0x3099, 0x309A),
(0xFE20, 0xFE2F),
];
fn is_combining_mark(code: u32) -> bool {
COMBINING_MARKS
.iter()
.any(|(start, end)| (*start..=*end).contains(&code))
}
fn is_regional_indicator(code: u32) -> bool {
(0x1F1E6..=0x1F1FF).contains(&code)
}
fn extends_cluster(code: u32) -> bool {
code == 0x200D
|| (0xFE00..=0xFE0F).contains(&code)
|| (0x1F3FB..=0x1F3FF).contains(&code)
|| (0xE0020..=0xE007F).contains(&code)
|| (0xE0100..=0xE01EF).contains(&code)
|| is_combining_mark(code)
}
pub(crate) fn graphemes(text: &str) -> Vec<&str> {
let mut clusters = Vec::new();
let mut start: Option<usize> = None;
let mut join_next = false;
let mut pending_regional = false;
for (index, character) in text.char_indices() {
let code = u32::from(character);
let regional = is_regional_indicator(code);
match start {
Some(_) if join_next || extends_cluster(code) || (regional && pending_regional) => {
pending_regional = false;
}
Some(begin) => {
clusters.push(&text[begin..index]);
start = Some(index);
pending_regional = regional;
}
None => {
start = Some(index);
pending_regional = regional;
}
}
join_next = code == 0x200D;
}
if let Some(begin) = start {
clusters.push(&text[begin..]);
}
clusters
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum MotionSupport {
Pending,
Unsupported,
Browser {
reduced: bool,
observer: bool,
random: f64,
},
}
impl MotionSupport {
pub(crate) fn observes(self) -> bool {
matches!(
self,
Self::Browser {
reduced: false,
observer: true,
..
}
)
}
pub(crate) fn reduced(self) -> bool {
matches!(self, Self::Browser { reduced: true, .. })
}
}
const MOTION_PROBE: &str = "return [matchMedia('(prefers-reduced-motion: reduce)').matches ? 1 : 0, typeof IntersectionObserver === 'function' ? 1 : 0, Math.random()];";
pub(crate) async fn probe_motion() -> MotionSupport {
match document::eval(MOTION_PROBE).join::<Vec<f64>>().await {
Ok(values) => match values.as_slice() {
[reduced, observer, random] => MotionSupport::Browser {
reduced: *reduced > 0.5,
observer: *observer > 0.5,
random: *random,
},
_ => MotionSupport::Unsupported,
},
Err(_) => MotionSupport::Unsupported,
}
}
pub(crate) fn use_motion_support() -> Signal<MotionSupport> {
let mut support = use_signal(|| MotionSupport::Pending);
use_effect(move || {
spawn(async move {
support.set(probe_motion().await);
});
});
support
}
const REVEAL_SETTLE: Duration = Duration::from_millis(32);
#[derive(Clone, Copy)]
pub(crate) struct Reveal {
bound: Signal<bool>,
revealed: Signal<bool>,
in_view: CopyValue<bool>,
finished: CopyValue<bool>,
once: CopyValue<bool>,
}
impl Reveal {
pub(crate) fn bound_attribute(self) -> Option<&'static str> {
(self.bound)().then_some("true")
}
pub(crate) fn revealed(self) -> bool {
(self.revealed)()
}
fn show_without_animation(mut self) {
self.finished.set(true);
self.bound.set(false);
if !*self.revealed.peek() {
self.revealed.set(true);
}
}
fn show(mut self, visible: bool) {
if *self.revealed.peek() != visible {
self.revealed.set(visible);
}
if visible && *self.once.peek() {
self.finished.set(true);
}
}
pub(crate) fn on_visible(mut self, event: &VisibleEvent) {
let visible = event.is_intersecting().unwrap_or(false);
self.in_view.set(visible);
if *self.bound.peek() && !*self.finished.peek() {
self.show(visible);
}
}
pub(crate) fn on_focus_in(self) {
if *self.bound.peek() && !*self.finished.peek() {
self.show_without_animation();
}
}
}
pub(crate) fn use_reveal(once: bool, enabled: bool, on_bind: Option<fn()>) -> Reveal {
let bound = use_signal(|| false);
let revealed = use_signal(|| false);
let in_view = use_hook(|| CopyValue::new(false));
let finished = use_hook(|| CopyValue::new(false));
let mut once_store = use_hook(|| CopyValue::new(once));
let mut enabled_store = use_hook(|| CopyValue::new(enabled));
if *once_store.peek() != once {
once_store.set(once);
}
if *enabled_store.peek() != enabled {
enabled_store.set(enabled);
}
let reveal = Reveal {
bound,
revealed,
in_view,
finished,
once: once_store,
};
use_effect(move || {
spawn(async move {
let support = probe_motion().await;
if !*enabled_store.peek() {
return;
}
if !support.observes() {
reveal.show_without_animation();
return;
}
let mut bound = reveal.bound;
bound.set(true);
if let Some(callback) = on_bind {
callback();
}
sleep(REVEAL_SETTLE).await;
if *reveal.in_view.peek() && !*reveal.finished.peek() {
reveal.show(true);
}
});
});
reveal
}
#[cfg(test)]
mod tests {
use super::{MotionDuration, graphemes, is_blank, js_number, js_round, merge_style};
#[test]
fn numbers_print_like_javascript() {
assert_eq!(js_number(6.0), "6");
assert_eq!(js_number(-6.0), "-6");
assert_eq!(js_number(-0.0), "0");
assert_eq!(js_number(0.15), "0.15");
assert_eq!(js_number(12.25), "12.25");
assert_eq!(js_number(1e21), "1e+21");
assert_eq!(js_number(1.5e-7), "1.5e-7");
assert_eq!(js_number(0.000_001), "0.000001");
assert_eq!(js_number(f64::NAN), "NaN");
assert_eq!(js_number(f64::NEG_INFINITY), "-Infinity");
}
#[test]
fn rounding_matches_math_round() {
assert!((js_round(2.5) - 3.0).abs() < f64::EPSILON);
assert!((js_round(-2.5) - -2.0).abs() < f64::EPSILON);
assert!((js_round(-2.6) - -3.0).abs() < f64::EPSILON);
}
#[test]
fn styles_merge_after_the_user_style() {
assert_eq!(merge_style(None, "--a: 1"), "--a: 1");
assert_eq!(
merge_style(Some("color: red; "), "--a: 1"),
"color: red; --a: 1"
);
assert_eq!(merge_style(Some(" "), "--a: 1"), "--a: 1");
assert_eq!(merge_style(Some("color: red"), ""), "color: red");
}
#[test]
fn blank_text_includes_unicode_spaces() {
assert!(is_blank(""));
assert!(is_blank(" \u{a0}\u{3000}\u{feff}"));
assert!(!is_blank(" a "));
}
#[test]
fn graphemes_keep_clusters_whole() {
assert_eq!(graphemes("abc"), vec!["a", "b", "c"]);
assert_eq!(graphemes("e\u{301}x"), vec!["e\u{301}", "x"]);
assert_eq!(
graphemes("\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}!"),
vec!["\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}", "!"]
);
assert_eq!(
graphemes("\u{1F1FA}\u{1F1F8}\u{1F1E8}\u{1F1E6}"),
vec!["\u{1F1FA}\u{1F1F8}", "\u{1F1E8}\u{1F1E6}"]
);
assert_eq!(graphemes("\u{1F44D}\u{1F3FD}"), vec!["\u{1F44D}\u{1F3FD}"]);
assert_eq!(graphemes(""), Vec::<&str>::new());
}
#[test]
fn graphemes_stay_linear_on_long_input() {
let text = "e\u{301}".repeat(50_000);
assert_eq!(graphemes(&text).len(), 50_000);
let joiners = "\u{200D}".repeat(100_000);
assert_eq!(graphemes(&joiners).len(), 1);
}
#[test]
fn durations_follow_the_tokens() {
assert_eq!(MotionDuration::default(), MotionDuration::Slow);
assert_eq!(MotionDuration::Slow.class(), "ui-motion-duration-slow");
assert_eq!(MotionDuration::Scene.milliseconds(), 1000);
}
}