util.rs
⎇
Raw
1//! Formatting + small browser helpers.
2
3use leptos::prelude::*;
4use wasm_bindgen::JsCast;
5use wasm_bindgen::closure::Closure;
6
7use crate::components::toast::{ToastMsg, show, show_error};
8use crate::i18n;
9
10/// Write `text` to the clipboard and confirm it with `msg`.
11///
12/// A rejected write is ignored, so the toast appears even when it failed.
13pub fn copy_to_clipboard(text: &str, msg: &str, toast: ToastMsg) {
14 let Some(win) = web_sys::window() else {
15 show_error(toast, i18n::t(i18n::k::COPY_MANUAL).to_string());
16 return;
17 };
18 let cb = win.navigator().clipboard();
19 let (text, msg) = (text.to_string(), msg.to_string());
20 wasm_bindgen_futures::spawn_local(async move {
21 let _ = wasm_bindgen_futures::JsFuture::from(cb.write_text(&text)).await;
22 show(toast, msg);
23 });
24}
25
26/// A window event listener that is removed when the current owner is disposed.
27///
28/// Leptos' `window_event_listener` returns a `WindowListenerHandle` with no
29/// `Drop` impl — if the owning component is unmounted without an explicit
30/// `remove()`, the listener keeps firing on `window` and panics by reading
31/// the component's now-disposed signals.
32pub fn owned_window_listener<E: leptos::ev::EventDescriptor + 'static>(
33 event: E,
34 cb: impl Fn(E::EventType) + 'static,
35) where
36 E::EventType: wasm_bindgen::JsCast,
37{
38 let handle = window_event_listener(event, cb);
39 on_cleanup(move || handle.remove());
40}
41
42/// A touch long press (500 ms without lifting or moving) that stands in for
43/// a right click. Android fires `contextmenu` on a long press by itself;
44/// iOS Safari does not, so the pointer events are watched directly.
45///
46/// One instance per element. Wire `down`, `up`, `mv` to `pointerdown`,
47/// `pointerup` + `pointercancel` + `pointerleave`, and `pointermove`. The
48/// element's `click` handler must call [`LongPress::swallow_click`] first:
49/// the browser still sends the click of the finger lifting after the menu
50/// opened, and that click would close the menu again.
51#[derive(Clone, Copy)]
52pub struct LongPress {
53 inner: StoredValue<LongPressState, LocalStorage>,
54}
55
56#[derive(Default)]
57struct LongPressState {
58 timer: Option<gloo_timers::callback::Timeout>,
59 start: (i32, i32),
60 fired: bool,
61}
62
63impl LongPress {
64 pub const DELAY_MS: u32 = 500;
65 /// Finger travel that turns the press into a scroll.
66 const SLOP_PX: i32 = 10;
67
68 pub fn new() -> Self {
69 Self {
70 inner: StoredValue::new_local(LongPressState::default()),
71 }
72 }
73
74 /// `pointerdown`: arm the timer for touch pointers; `on_fire` gets the
75 /// client coordinates. Stops propagation so a nested element and its
76 /// container do not both arm.
77 pub fn down(&self, ev: &web_sys::PointerEvent, on_fire: impl Fn(i32, i32) + 'static) {
78 if ev.pointer_type() != "touch" {
79 return;
80 }
81 ev.stop_propagation();
82 let (x, y) = (ev.client_x(), ev.client_y());
83 let inner = self.inner;
84 let timer = gloo_timers::callback::Timeout::new(Self::DELAY_MS, move || {
85 inner.update_value(|st| {
86 st.timer = None;
87 st.fired = true;
88 });
89 on_fire(x, y);
90 });
91 self.inner.update_value(|st| {
92 st.timer = Some(timer);
93 st.start = (x, y);
94 st.fired = false;
95 });
96 }
97
98 /// `pointerup`, `pointercancel`, `pointerleave`: disarm.
99 pub fn up(&self) {
100 self.inner.update_value(|st| st.timer = None);
101 }
102
103 /// `pointermove`: disarm once the finger travels; that is a scroll.
104 pub fn mv(&self, ev: &web_sys::PointerEvent) {
105 self.inner.update_value(|st| {
106 if st.timer.is_none() {
107 return;
108 }
109 let (sx, sy) = st.start;
110 if (ev.client_x() - sx).abs() > Self::SLOP_PX
111 || (ev.client_y() - sy).abs() > Self::SLOP_PX
112 {
113 st.timer = None;
114 }
115 });
116 }
117
118 /// True once, for the click that follows a fired press. The caller
119 /// stops that click instead of handling it.
120 pub fn swallow_click(&self) -> bool {
121 self.inner
122 .try_update_value(|st| std::mem::take(&mut st.fired))
123 .unwrap_or(false)
124 }
125}
126
127/// Same as [`owned_window_listener`], but registered in the capture phase,
128/// so it runs before the bubble-phase window listeners (registration order
129/// otherwise decides, and that depends on component creation order).
130pub fn owned_window_listener_capture<E: leptos::ev::EventDescriptor + 'static>(
131 event: E,
132 cb: impl Fn(E::EventType) + 'static,
133) where
134 E::EventType: wasm_bindgen::JsCast,
135{
136 let closure = Closure::<dyn FnMut(web_sys::Event)>::new({
137 move |e: web_sys::Event| cb(e.unchecked_into::<E::EventType>())
138 });
139 let add_options = web_sys::AddEventListenerOptions::new();
140 add_options.set_capture(true);
141 let remove_options = web_sys::EventListenerOptions::new();
142 remove_options.set_capture(true);
143 let name = event.name();
144 web_sys::window()
145 .expect("window")
146 .add_event_listener_with_callback_and_add_event_listener_options(
147 &name,
148 closure.as_ref().unchecked_ref(),
149 &add_options,
150 )
151 .expect("failed to add window event listener");
152 let closure_js = closure.into_js_value();
153 on_cleanup(move || {
154 let closure: js_sys::Function = closure_js.unchecked_into();
155 let _ = web_sys::window()
156 .expect("window")
157 .remove_event_listener_with_callback_and_event_listener_options(
158 &name,
159 &closure,
160 &remove_options,
161 );
162 });
163}
164
165pub fn format_size(bytes: u64) -> String {
166 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
167 let mut v = bytes as f64;
168 let mut i = 0;
169 while v >= 1024.0 && i < UNITS.len() - 1 {
170 v /= 1024.0;
171 i += 1;
172 }
173 if i == 0 {
174 format!("{bytes} B")
175 } else {
176 format!("{v:.1} {}", UNITS[i])
177 }
178}
179
180/// Format an RFC 3339 timestamp as "YYYY-MM-DD HH:MM" (UTC) for display.
181/// Falls back to the raw string when it does not look like one.
182///
183/// Every timestamp the server sends is UTC with a `Z` suffix, so the display
184/// text is a slice of the input. No date parsing is needed.
185pub fn format_date(rfc3339: &str) -> String {
186 let b = rfc3339.as_bytes();
187 if b.len() >= 16 && b[10] == b'T' {
188 return format!("{} {}", &rfc3339[..10], &rfc3339[11..16]);
189 }
190 rfc3339.to_string()
191}
192
193pub fn storage_get(key: &str) -> Option<String> {
194 let w = web_sys::window()?;
195 let storage_opt = w.local_storage().ok()?;
196 let storage = storage_opt.as_ref()?;
197 storage.get_item(key).ok().flatten()
198}
199
200pub fn storage_set(key: &str, value: &str) {
201 if let Some(s) = web_sys::window().and_then(|w| w.local_storage().ok().flatten()) {
202 let _ = s.set_item(key, value);
203 }
204}
205
206#[derive(Clone, Copy, PartialEq, Debug)]
207pub enum ViewMode {
208 Grid,
209 List,
210}
211
212impl ViewMode {
213 const KEY: &'static str = "fbng.view";
214
215 pub fn load() -> Self {
216 match storage_get(Self::KEY).as_deref() {
217 Some("list") => ViewMode::List,
218 _ => ViewMode::Grid,
219 }
220 }
221
222 pub fn save(self) {
223 storage_set(
224 Self::KEY,
225 if self == ViewMode::List {
226 "list"
227 } else {
228 "grid"
229 },
230 );
231 }
232}
233
234pub use api_types::SortKey;
235
236/// A sort key plus its direction, persisted like [`ViewMode`].
237#[derive(Clone, Copy, PartialEq, Eq, Debug)]
238pub struct SortSpec {
239 pub key: SortKey,
240 pub asc: bool,
241}
242
243impl Default for SortSpec {
244 fn default() -> Self {
245 Self {
246 key: SortKey::Name,
247 asc: true,
248 }
249 }
250}
251
252impl SortSpec {
253 const KEY: &'static str = "fbng.sort";
254
255 pub fn load() -> Self {
256 let raw = storage_get(Self::KEY).unwrap_or_default();
257 let (key, dir) = raw.split_once(':').unwrap_or(("", ""));
258 match SortKey::parse(key) {
259 Some(key) => Self {
260 key,
261 asc: dir != "desc",
262 },
263 None => Self::default(),
264 }
265 }
266
267 pub fn save(self) {
268 let dir = if self.asc { "asc" } else { "desc" };
269 storage_set(Self::KEY, &format!("{}:{dir}", self.key.as_str()));
270 }
271}
272
273/// Rows rendered at once: the search's "show more" step, and the folder
274/// listing's default page size. Rendering a row costs a fixed amount of
275/// reactive-graph setup, so the first paint stays well under a frame and the
276/// user pays for more rows only by asking for them.
277pub const FILE_PAGE: usize = 100;
278
279/// Footer under a paged list: where the user is in the list, and a button
280/// to reveal the next page.
281///
282/// `shown` of `total` is stated plainly rather than only counting what is
283/// hidden — "Showing 100 of 6027" answers "where am I?", which a bare
284/// "5927 more…" does not. The button appears only while more items are
285/// actually retained; past the caller's retain cap the count is all that is
286/// left to say, so the footer becomes a plain line.
287///
288/// Returns nothing at all when everything is on screen.
289pub fn page_footer(
290 shown: usize,
291 retained: usize,
292 total: usize,
293 page: usize,
294 reveal: impl Fn() + 'static,
295) -> AnyView {
296 if total <= shown {
297 return view! {}.into_any();
298 }
299 let label = crate::i18n::t_fmt2(
300 crate::i18n::k::SEARCH_SHOWN_OF,
301 &shown.to_string(),
302 &total.to_string(),
303 );
304 let pageable = retained.saturating_sub(shown);
305 if pageable == 0 {
306 return view! { <div class="page-foot">{label}</div> }.into_any();
307 }
308 let next = pageable.min(page);
309 view! {
310 <div class="page-foot">
311 <span class="pf-count">{label}</span>
312 <button class="pf-more" on:click=move |_| reveal()>
313 {crate::i18n::t_fmt(crate::i18n::k::SEARCH_SHOW_MORE, &next.to_string())}
314 </button>
315 </div>
316 }
317 .into_any()
318}
319
320/// Page sizes the folder listing offers.
321pub const PAGE_SIZES: [usize; 4] = [50, 100, 200, 500];
322
323const PAGE_SIZE_KEY: &str = "fbng.page_size";
324
325pub fn load_page_size() -> usize {
326 storage_get(PAGE_SIZE_KEY)
327 .and_then(|v| v.parse().ok())
328 .filter(|n| PAGE_SIZES.contains(n))
329 .unwrap_or(FILE_PAGE)
330}
331
332pub fn save_page_size(n: usize) {
333 storage_set(PAGE_SIZE_KEY, &n.to_string());
334}
335
336/// The page buttons to show, 0-based: the first, the last, and two on each
337/// side of `cur`. `None` is a gap.
338pub fn page_numbers(cur: usize, pages: usize) -> Vec<Option<usize>> {
339 let mut out = Vec::new();
340 for p in 0..pages {
341 if p == 0 || p + 1 == pages || p.abs_diff(cur) <= 2 {
342 out.push(Some(p));
343 } else if out.last() != Some(&None) {
344 out.push(None);
345 }
346 }
347 out
348}
349
350/// Footer under a server-paged list. Empty when the list fits the smallest
351/// page size, since then no control does anything.
352pub fn pager(
353 offset: usize,
354 shown: usize,
355 total: usize,
356 size: usize,
357 go: Callback<usize>,
358 set_size: Callback<usize>,
359) -> AnyView {
360 use crate::i18n::k;
361 if total <= PAGE_SIZES[0] {
362 return view! {}.into_any();
363 }
364 let cur = offset / size;
365 let pages = total.div_ceil(size);
366 let last = pages - 1;
367 let label = crate::i18n::t_fmt2(
368 k::SEARCH_SHOWN_OF,
369 &format!("{}–{}", offset + 1, offset + shown),
370 &total.to_string(),
371 );
372 let nav = move |glyph: &'static str, title: &'static str, to: usize, off: bool| {
373 view! {
374 <button
375 class="pf-btn"
376 disabled=off
377 title=crate::i18n::tr(title)
378 aria-label=crate::i18n::tr(title)
379 on:click=move |_| go.run(to)
380 >
381 {glyph}
382 </button>
383 }
384 };
385 let numbers = page_numbers(cur, pages)
386 .into_iter()
387 .map(|p| match p {
388 Some(p) => view! {
389 <button
390 class="pf-btn"
391 class:current=p == cur
392 aria-current=(p == cur).then_some("page")
393 on:click=move |_| go.run(p)
394 >
395 {p + 1}
396 </button>
397 }
398 .into_any(),
399 None => view! { <span class="pf-gap">"…"</span> }.into_any(),
400 })
401 .collect_view();
402 view! {
403 <div class="page-foot">
404 <span class="pf-count">{label}</span>
405 <nav class="pf-pages">
406 {nav("«", k::PAGE_FIRST, 0, cur == 0)}
407 {nav("‹", k::PAGE_PREV, cur.saturating_sub(1), cur == 0)}
408 {numbers}
409 {nav("›", k::PAGE_NEXT, (cur + 1).min(last), cur == last)}
410 {nav("»", k::PAGE_LAST, last, cur == last)}
411 </nav>
412 <label class="pf-goto">
413 {crate::i18n::tr(k::PAGE_GOTO)}
414 <input
415 type="number"
416 min="1"
417 max=pages.to_string()
418 prop:value=(cur + 1).to_string()
419 on:change=move |ev| {
420 if let Ok(n) = event_target_value(&ev).trim().parse::<usize>() {
421 go.run(n.clamp(1, pages) - 1);
422 }
423 }
424 />
425 </label>
426 <select
427 class="sort-select"
428 aria-label=crate::i18n::tr(k::PAGE_SIZE)
429 on:change=move |ev| {
430 if let Ok(n) = event_target_value(&ev).parse() {
431 set_size.run(n);
432 }
433 }
434 >
435 {PAGE_SIZES
436 .map(|n| view! {
437 <option value=n.to_string() selected=n == size>
438 {crate::i18n::t_fmt(k::PAGE_SIZE_N, &n.to_string())}
439 </option>
440 })
441 .to_vec()}
442 </select>
443 </div>
444 }
445 .into_any()
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451
452 #[test]
453 fn page_numbers_keep_the_ends_and_the_neighbours() {
454 let n = |cur, pages| page_numbers(cur, pages);
455 assert_eq!(n(0, 1), [Some(0)]);
456 assert_eq!(n(2, 5), [Some(0), Some(1), Some(2), Some(3), Some(4)]);
457 assert_eq!(n(0, 10), [Some(0), Some(1), Some(2), None, Some(9)]);
458 assert_eq!(
459 n(5, 10),
460 [
461 Some(0),
462 None,
463 Some(3),
464 Some(4),
465 Some(5),
466 Some(6),
467 Some(7),
468 None,
469 Some(9)
470 ]
471 );
472 }
473
474 #[test]
475 fn sort_spec_round_trips_through_its_stored_form() {
476 // No localStorage in the test runner, so only the parse half runs
477 // here. `load` falls back to the default.
478 assert_eq!(SortKey::parse("size"), Some(SortKey::Size));
479 assert_eq!(SortKey::parse("bogus"), None);
480 assert_eq!(SortSpec::default().key, SortKey::Name);
481 assert!(SortSpec::default().asc);
482 }
483
484 #[test]
485 fn format_date_drops_seconds_and_zone() {
486 assert_eq!(format_date("2026-09-11T12:34:56Z"), "2026-09-11 12:34");
487 assert_eq!(format_date("nonsense"), "nonsense");
488 }
489}
490