util.rs
⎇
Raw
1//! Formatting + small browser helpers.
2
3use leptos::prelude::*;
4use wasm_bindgen::JsCast;
5use wasm_bindgen::closure::Closure;
6
7/// A window event listener that is removed when the current owner is disposed.
8///
9/// Leptos' `window_event_listener` returns a `WindowListenerHandle` with no
10/// `Drop` impl — if the owning component is unmounted without an explicit
11/// `remove()`, the listener keeps firing on `window` and panics by reading
12/// the component's now-disposed signals.
13pub fn owned_window_listener<E: leptos::ev::EventDescriptor + 'static>(
14 event: E,
15 cb: impl Fn(E::EventType) + 'static,
16) where
17 E::EventType: wasm_bindgen::JsCast,
18{
19 let handle = window_event_listener(event, cb);
20 on_cleanup(move || handle.remove());
21}
22
23/// Same as [`owned_window_listener`], but registered in the capture phase,
24/// so it runs before the bubble-phase window listeners (registration order
25/// otherwise decides, and that depends on component creation order).
26pub fn owned_window_listener_capture<E: leptos::ev::EventDescriptor + 'static>(
27 event: E,
28 cb: impl Fn(E::EventType) + 'static,
29) where
30 E::EventType: wasm_bindgen::JsCast,
31{
32 let closure = Closure::<dyn FnMut(web_sys::Event)>::new({
33 move |e: web_sys::Event| cb(e.unchecked_into::<E::EventType>())
34 });
35 let add_options = web_sys::AddEventListenerOptions::new();
36 add_options.set_capture(true);
37 let remove_options = web_sys::EventListenerOptions::new();
38 remove_options.set_capture(true);
39 let name = event.name();
40 web_sys::window()
41 .expect("window")
42 .add_event_listener_with_callback_and_add_event_listener_options(
43 &name,
44 closure.as_ref().unchecked_ref(),
45 &add_options,
46 )
47 .expect("failed to add window event listener");
48 let closure_js = closure.into_js_value();
49 on_cleanup(move || {
50 let closure: js_sys::Function = closure_js.unchecked_into();
51 let _ = web_sys::window()
52 .expect("window")
53 .remove_event_listener_with_callback_and_event_listener_options(
54 &name,
55 &closure,
56 &remove_options,
57 );
58 });
59}
60
61/// The value of a `<select>` behind an event, when the target is one.
62pub fn select_value(ev: &web_sys::Event) -> Option<String> {
63 ev.target()
64 .and_then(|t| t.dyn_into::<web_sys::HtmlSelectElement>().ok())
65 .map(|s| s.value())
66}
67
68pub fn format_size(bytes: u64) -> String {
69 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
70 let mut v = bytes as f64;
71 let mut i = 0;
72 while v >= 1024.0 && i < UNITS.len() - 1 {
73 v /= 1024.0;
74 i += 1;
75 }
76 if i == 0 {
77 format!("{bytes} B")
78 } else {
79 format!("{v:.1} {}", UNITS[i])
80 }
81}
82
83/// Format an RFC 3339 timestamp as "YYYY-MM-DD HH:MM" (UTC) for display.
84/// Falls back to the raw string when it does not look like one.
85///
86/// Every timestamp the server sends is UTC with a `Z` suffix, so the display
87/// text is a slice of the input. No date parsing is needed.
88pub fn format_date(rfc3339: &str) -> String {
89 let b = rfc3339.as_bytes();
90 if b.len() >= 16 && b[10] == b'T' {
91 return format!("{} {}", &rfc3339[..10], &rfc3339[11..16]);
92 }
93 rfc3339.to_string()
94}
95
96pub fn storage_get(key: &str) -> Option<String> {
97 let w = web_sys::window()?;
98 let storage_opt = w.local_storage().ok()?;
99 let storage = storage_opt.as_ref()?;
100 storage.get_item(key).ok().flatten()
101}
102
103pub fn storage_set(key: &str, value: &str) {
104 if let Some(s) = web_sys::window().and_then(|w| w.local_storage().ok().flatten()) {
105 let _ = s.set_item(key, value);
106 }
107}
108
109#[derive(Clone, Copy, PartialEq, Debug)]
110pub enum ViewMode {
111 Grid,
112 List,
113}
114
115impl ViewMode {
116 const KEY: &'static str = "fbng.view";
117
118 pub fn load() -> Self {
119 match storage_get(Self::KEY).as_deref() {
120 Some("list") => ViewMode::List,
121 _ => ViewMode::Grid,
122 }
123 }
124
125 pub fn save(self) {
126 storage_set(
127 Self::KEY,
128 if self == ViewMode::List {
129 "list"
130 } else {
131 "grid"
132 },
133 );
134 }
135}
136
137/// Entries rendered at once in a listing, and how many more each click of
138/// the "show more" row reveals. Rendering a row costs a fixed amount of
139/// reactive-graph setup, so the first paint stays well under a frame and the
140/// user pays for more rows only by asking for them.
141pub const FILE_PAGE: usize = 100;
142
143/// Footer under a paged list: where the user is in the list, and a button
144/// to reveal the next page.
145///
146/// `shown` of `total` is stated plainly rather than only counting what is
147/// hidden — "Showing 100 of 6027" answers "where am I?", which a bare
148/// "5927 more…" does not. The button appears only while more items are
149/// actually retained; past the caller's retain cap the count is all that is
150/// left to say, so the footer becomes a plain line.
151///
152/// Returns nothing at all when everything is on screen.
153pub fn page_footer(
154 shown: usize,
155 retained: usize,
156 total: usize,
157 page: usize,
158 reveal: impl Fn() + 'static,
159) -> AnyView {
160 if total <= shown {
161 return view! {}.into_view().into_any();
162 }
163 let label = crate::i18n::t_fmt2(
164 crate::i18n::k::SEARCH_SHOWN_OF,
165 &shown.to_string(),
166 &total.to_string(),
167 );
168 let pageable = retained.saturating_sub(shown);
169 if pageable == 0 {
170 return view! { <div class="page-foot">{label}</div> }
171 .into_view()
172 .into_any();
173 }
174 let next = pageable.min(page);
175 view! {
176 <div class="page-foot">
177 <span class="pf-count">{label}</span>
178 <button class="pf-more" on:click=move |_| reveal()>
179 {crate::i18n::t_fmt(crate::i18n::k::SEARCH_SHOW_MORE, &next.to_string())}
180 </button>
181 </div>
182 }
183 .into_view()
184 .into_any()
185}
186
187#[cfg(test)]
188mod tests {
189 use super::*;
190
191 #[test]
192 fn format_date_drops_seconds_and_zone() {
193 assert_eq!(format_date("2026-09-11T12:34:56Z"), "2026-09-11 12:34");
194 assert_eq!(format_date("nonsense"), "nonsense");
195 }
196}
197