1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use crate::{use_media_query, use_window};
use leptos::logging::error;
use leptos::*;
use paste::paste;
use std::collections::HashMap;
use std::fmt::Debug;
use std::hash::Hash;

/// Reactive viewport breakpoints.
///
/// ## Demo
///
/// [Link to Demo](https://github.com/Synphonyte/leptos-use/tree/main/examples/use_breakpoints)
///
/// ## Usage
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_breakpoints, BreakpointsTailwind, breakpoints_tailwind};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// #
/// let screen_width = use_breakpoints(breakpoints_tailwind());
///
/// use BreakpointsTailwind::*;
///
/// let sm_and_larger = screen_width.ge(Sm);
/// let larger_than_sm = screen_width.gt(Sm);
/// let lg_and_smaller = screen_width.le(Lg);
/// let smaller_than_lg = screen_width.lt(Lg);
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Breakpoints
///
/// There are many predefined breakpoints for major UI frameworks. The following are provided.
/// * [`breakpoints_tailwind`]
/// * [`breakpoints_bootstrap_v5`]
/// * [`breakpoints_material`]
/// * [`breakpoints_ant_design`]
/// * [`breakpoints_quasar`]
/// * [`breakpoints_semantic`]
/// * [`breakpoints_master_css`]
///
/// You can also provide your own breakpoints.
///
/// ```
/// # use std::collections::HashMap;
/// use leptos::*;
/// # use leptos_use::use_breakpoints;
/// #
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// enum MyBreakpoints {
///     Tablet,
///     Laptop,
///     Desktop,
/// }
///
/// fn my_breakpoints() -> HashMap<MyBreakpoints, u32> {
///     use MyBreakpoints::*;
///
///     HashMap::from([
///         (Tablet, 640),
///         (Laptop, 1024),
///         (Desktop, 1280),
///     ])
/// }
///
/// #[component]
/// fn Demo() -> impl IntoView {
///     let screen_width = use_breakpoints(my_breakpoints());
///
///     use MyBreakpoints::*;
///
///     let laptop = screen_width.between(Laptop, Desktop);
///
///     view! { }
/// }
/// ```
///
/// ## Non-reactive methods
///
/// For every reactive method there is also a non-reactive variant that is prefixed with `is_`
///
/// ```
/// # use leptos::*;
/// # use leptos_use::{use_breakpoints, BreakpointsTailwind, breakpoints_tailwind};
/// #
/// # #[component]
/// # fn Demo() -> impl IntoView {
/// #
/// let screen_width = use_breakpoints(breakpoints_tailwind());
///
/// use BreakpointsTailwind::*;
///
/// let sm_and_larger = screen_width.is_ge(Sm);
/// let larger_than_sm = screen_width.is_gt(Sm);
/// let lg_and_smaller = screen_width.is_le(Lg);
/// let smaller_than_lg = screen_width.is_lt(Lg);
/// #
/// # view! { }
/// # }
/// ```
///
/// ## Server-Side Rendering
///
/// Since internally this uses [`use_media_query`], which returns always `false` on the server,
/// the returned methods also will return `false`.
pub fn use_breakpoints<K: Eq + Hash + Debug + Clone>(
    breakpoints: HashMap<K, u32>,
) -> UseBreakpointsReturn<K> {
    UseBreakpointsReturn { breakpoints }
}

/// Return type of [`use_breakpoints`]
#[derive(Clone)]
pub struct UseBreakpointsReturn<K: Eq + Hash + Debug + Clone> {
    breakpoints: HashMap<K, u32>,
}

macro_rules! query_suffix {
    (>) => {
        ".1"
    };
    (<) => {
        ".9"
    };
    (=) => {
        ""
    };
}

macro_rules! value_expr {
    ($v:ident, >) => {
        $v
    };
    ($v:ident, <) => {
        $v - 1
    };
    ($v:ident, =) => {
        $v
    };
}

macro_rules! format_media_query {
    ($cmp:tt, $suffix:tt, $v:ident) => {
        format!(
            "({}-width: {}{}px)",
            $cmp,
            value_expr!($v, $suffix),
            query_suffix!($suffix)
        )
    };
}

macro_rules! impl_cmp_reactively {
    (   #[$attr:meta]
        $fn:ident, $cmp:tt, $suffix:tt) => {
        paste! {
            // Reactive check if
            #[$attr]
            pub fn $fn(&self, key: K) -> Signal<bool> {
                if let Some(value) = self.breakpoints.get(&key) {
                    use_media_query(format_media_query!($cmp, $suffix, value))
                } else {
                    self.not_found_signal(key)
                }
            }

            // Static check if
            #[$attr]
            pub fn [<is_ $fn>](&self, key: K) -> bool {
                if let Some(value) = self.breakpoints.get(&key) {
                    Self::match_(&format_media_query!($cmp, $suffix, value))
                } else {
                    self.not_found(key)
                }
            }
        }
    };
}

impl<K: Eq + Hash + Debug + Clone> UseBreakpointsReturn<K> {
    fn match_(query: &str) -> bool {
        if let Ok(Some(query_list)) = use_window().match_media(query) {
            return query_list.matches();
        }

        false
    }

    fn not_found_signal(&self, key: K) -> Signal<bool> {
        error!("Breakpoint \"{:?}\" not found", key);
        Signal::derive(|| false)
    }

    fn not_found(&self, key: K) -> bool {
        error!("Breakpoint \"{:?}\" not found", key);
        false
    }

    impl_cmp_reactively!(
        /// `[screen size]` > `key`
        gt, "min", >
    );
    impl_cmp_reactively!(
        /// `[screen size]` >= `key`
        ge, "min", =
    );
    impl_cmp_reactively!(
        /// `[screen size]` < `key`
        lt, "max", <
    );
    impl_cmp_reactively!(
        /// `[screen size]` <= `key`
        le, "max", =
    );

    fn between_media_query(min: &u32, max: &u32) -> String {
        format!("(min-width: {min}px) and (max-width: {}.9px)", max - 1)
    }

    /// Reactive check if `min_key` <= `[screen size]` <= `max_key`
    pub fn between(&self, min_key: K, max_key: K) -> Signal<bool> {
        if let Some(min) = self.breakpoints.get(&min_key) {
            if let Some(max) = self.breakpoints.get(&max_key) {
                use_media_query(Self::between_media_query(min, max))
            } else {
                self.not_found_signal(max_key)
            }
        } else {
            self.not_found_signal(min_key)
        }
    }

    /// Static check if `min_key` <= `[screen size]` <= `max_key`
    pub fn is_between(&self, min_key: K, max_key: K) -> bool {
        if let Some(min) = self.breakpoints.get(&min_key) {
            if let Some(max) = self.breakpoints.get(&max_key) {
                Self::match_(&Self::between_media_query(min, max))
            } else {
                self.not_found(max_key)
            }
        } else {
            self.not_found(min_key)
        }
    }

    /// Reactive Vec of all breakpoints that fulfill `[screen size]` >= `key`
    pub fn current(&self) -> Signal<Vec<K>> {
        let breakpoints = self.breakpoints.clone();
        let keys: Vec<_> = breakpoints.keys().cloned().collect();

        let ge = move |key: &K| {
            let value = breakpoints
                .get(key)
                .expect("only used with keys() from the HashMap");

            use_media_query(format_media_query!("min", =, value))
        };

        let signals: Vec<_> = keys.iter().map(ge.clone()).collect();

        Signal::derive(move || {
            keys.iter()
                .cloned()
                .zip(signals.iter().cloned())
                .filter_map(|(key, signal)| signal.get().then_some(key))
                .collect::<Vec<_>>()
        })
    }
}

/// Breakpoint keys for Tailwind V2
///
/// See [https://tailwindcss.com/docs/breakpoints]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsTailwind {
    Sm,
    Md,
    Lg,
    Xl,
    Xxl,
}

/// Breakpoint definitions for Tailwind V2
///
/// See [https://tailwindcss.com/docs/breakpoints]
pub fn breakpoints_tailwind() -> HashMap<BreakpointsTailwind, u32> {
    HashMap::from([
        (BreakpointsTailwind::Sm, 640),
        (BreakpointsTailwind::Md, 768),
        (BreakpointsTailwind::Lg, 1024),
        (BreakpointsTailwind::Xl, 1280),
        (BreakpointsTailwind::Xxl, 1536),
    ])
}

/// Breakpoint keys for Bootstrap V5
///
/// See [https://getbootstrap.com/docs/5.0/layout/breakpoints]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsBootstrapV5 {
    Sm,
    Md,
    Lg,
    Xl,
    Xxl,
}

/// Breakpoint definitions for Bootstrap V5
///
/// See [https://getbootstrap.com/docs/5.0/layout/breakpoints]
pub fn breakpoints_bootstrap_v5() -> HashMap<BreakpointsBootstrapV5, u32> {
    HashMap::from([
        (BreakpointsBootstrapV5::Sm, 576),
        (BreakpointsBootstrapV5::Md, 768),
        (BreakpointsBootstrapV5::Lg, 992),
        (BreakpointsBootstrapV5::Xl, 1200),
        (BreakpointsBootstrapV5::Xxl, 1400),
    ])
}

/// Breakpoint keys for Material UI V5
///
/// See [https://mui.com/material-ui/customization/breakpoints/]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsMaterial {
    Xs,
    Sm,
    Md,
    Lg,
    Xl,
}

/// Breakpoint definitions for Material UI V5
///
/// See [https://mui.com/material-ui/customization/breakpoints/]
pub fn breakpoints_material() -> HashMap<BreakpointsMaterial, u32> {
    HashMap::from([
        (BreakpointsMaterial::Xs, 1),
        (BreakpointsMaterial::Sm, 600),
        (BreakpointsMaterial::Md, 900),
        (BreakpointsMaterial::Lg, 1200),
        (BreakpointsMaterial::Xl, 1536),
    ])
}

/// Breakpoint keys for Ant Design
///
/// See [https://ant.design/components/layout/#breakpoint-width]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsAntDesign {
    Xs,
    Sm,
    Md,
    Lg,
    Xl,
    Xxl,
}

/// Breakpoint definitions for Ant Design
///
/// See [https://ant.design/components/layout/#breakpoint-width]
pub fn breakpoints_ant_design() -> HashMap<BreakpointsAntDesign, u32> {
    HashMap::from([
        (BreakpointsAntDesign::Xs, 480),
        (BreakpointsAntDesign::Sm, 576),
        (BreakpointsAntDesign::Md, 768),
        (BreakpointsAntDesign::Lg, 992),
        (BreakpointsAntDesign::Xl, 1200),
        (BreakpointsAntDesign::Xxl, 1600),
    ])
}

/// Breakpoint keys for Quasar V2
///
/// See [https://quasar.dev/style/breakpoints]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsQuasar {
    Xs,
    Sm,
    Md,
    Lg,
    Xl,
}

/// Breakpoint definitions for Quasar V2
///
/// See [https://quasar.dev/style/breakpoints]
pub fn breakpoints_quasar() -> HashMap<BreakpointsQuasar, u32> {
    HashMap::from([
        (BreakpointsQuasar::Xs, 1),
        (BreakpointsQuasar::Sm, 600),
        (BreakpointsQuasar::Md, 1024),
        (BreakpointsQuasar::Lg, 1440),
        (BreakpointsQuasar::Xl, 1920),
    ])
}

/// Breakpoint keys for Sematic UI
///
/// See [https://semantic-ui.com/elements/container.html]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsSematic {
    Mobile,
    Tablet,
    SmallMonitor,
    LargeMonitor,
}

/// Breakpoint definitions for Sematic UI
///
/// See [https://semantic-ui.com/elements/container.html]
pub fn breakpoints_sematic() -> HashMap<BreakpointsSematic, u32> {
    HashMap::from([
        (BreakpointsSematic::Mobile, 1),
        (BreakpointsSematic::Tablet, 768),
        (BreakpointsSematic::SmallMonitor, 992),
        (BreakpointsSematic::LargeMonitor, 1200),
    ])
}

/// Breakpoint keys for Master CSS
///
/// See [https://docs.master.co/css/breakpoints]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum BreakpointsMasterCss {
    Xxxs,
    Xxs,
    Xs,
    Sm,
    Md,
    Lg,
    Xl,
    Xxl,
    Xxxl,
    Xxxxl,
}

/// Breakpoint definitions for Master CSS
///
/// See [https://docs.master.co/css/breakpoints]
pub fn breakpoints_master_css() -> HashMap<BreakpointsMasterCss, u32> {
    HashMap::from([
        (BreakpointsMasterCss::Xxxs, 360),
        (BreakpointsMasterCss::Xxs, 480),
        (BreakpointsMasterCss::Xs, 600),
        (BreakpointsMasterCss::Sm, 768),
        (BreakpointsMasterCss::Md, 1024),
        (BreakpointsMasterCss::Lg, 1280),
        (BreakpointsMasterCss::Xl, 1440),
        (BreakpointsMasterCss::Xxl, 1600),
        (BreakpointsMasterCss::Xxxl, 1920),
        (BreakpointsMasterCss::Xxxxl, 2560),
    ])
}