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
165/// Select the whole value of the `<input>` behind an event, so one click
166/// leaves the link ready to copy by hand.
167pub fn select_input(ev: &web_sys::Event) {
168 if let Some(i) = ev
169 .target()
170 .and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
171 {
172 i.select();
173 }
174}
175
176/// The value of a `<select>` behind an event, when the target is one.
177pub fn select_value(ev: &web_sys::Event) -> Option<String> {
178 ev.target()
179 .and_then(|t| t.dyn_into::<web_sys::HtmlSelectElement>().ok())
180 .map(|s| s.value())
181}
182
183pub fn format_size(bytes: u64) -> String {
184 const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
185 let mut v = bytes as f64;
186 let mut i = 0;
187 while v >= 1024.0 && i < UNITS.len() - 1 {
188 v /= 1024.0;
189 i += 1;
190 }
191 if i == 0 {
192 format!("{bytes} B")
193 } else {
194 format!("{v:.1} {}", UNITS[i])
195 }
196}
197
198/// Format an RFC 3339 timestamp as "YYYY-MM-DD HH:MM" (UTC) for display.
199/// Falls back to the raw string when it does not look like one.
200///
201/// Every timestamp the server sends is UTC with a `Z` suffix, so the display
202/// text is a slice of the input. No date parsing is needed.
203pub fn format_date(rfc3339: &str) -> String {
204 let b = rfc3339.as_bytes();
205 if b.len() >= 16 && b[10] == b'T' {
206 return format!("{} {}", &rfc3339[..10], &rfc3339[11..16]);
207 }
208 rfc3339.to_string()
209}
210
211pub fn storage_get(key: &str) -> Option<String> {
212 let w = web_sys::window()?;
213 let storage_opt = w.local_storage().ok()?;
214 let storage = storage_opt.as_ref()?;
215 storage.get_item(key).ok().flatten()
216}
217
218pub fn storage_set(key: &str, value: &str) {
219 if let Some(s) = web_sys::window().and_then(|w| w.local_storage().ok().flatten()) {
220 let _ = s.set_item(key, value);
221 }
222}
223
224#[derive(Clone, Copy, PartialEq, Debug)]
225pub enum ViewMode {
226 Grid,
227 List,
228}
229
230impl ViewMode {
231 const KEY: &'static str = "fbng.view";
232
233 pub fn load() -> Self {
234 match storage_get(Self::KEY).as_deref() {
235 Some("list") => ViewMode::List,
236 _ => ViewMode::Grid,
237 }
238 }
239
240 pub fn save(self) {
241 storage_set(
242 Self::KEY,
243 if self == ViewMode::List {
244 "list"
245 } else {
246 "grid"
247 },
248 );
249 }
250}
251
252pub use api_types::SortKey;
253
254/// A sort key plus its direction, persisted like [`ViewMode`].
255#[derive(Clone, Copy, PartialEq, Eq, Debug)]
256pub struct SortSpec {
257 pub key: SortKey,
258 pub asc: bool,
259}
260
261impl Default for SortSpec {
262 fn default() -> Self {
263 Self {
264 key: SortKey::Name,
265 asc: true,
266 }
267 }
268}
269
270impl SortSpec {
271 const KEY: &'static str = "fbng.sort";
272
273 pub fn load() -> Self {
274 let raw = storage_get(Self::KEY).unwrap_or_default();
275 let (key, dir) = raw.split_once(':').unwrap_or(("", ""));
276 match SortKey::parse(key) {
277 Some(key) => Self {
278 key,
279 asc: dir != "desc",
280 },
281 None => Self::default(),
282 }
283 }
284
285 pub fn save(self) {
286 let dir = if self.asc { "asc" } else { "desc" };
287 storage_set(Self::KEY, &format!("{}:{dir}", self.key.as_str()));
288 }
289}
290
291/// Rows rendered at once: the search's "show more" step, and the folder
292/// listing's default page size. Rendering a row costs a fixed amount of
293/// reactive-graph setup, so the first paint stays well under a frame and the
294/// user pays for more rows only by asking for them.
295pub const FILE_PAGE: usize = 100;
296
297/// Footer under a paged list: where the user is in the list, and a button
298/// to reveal the next page.
299///
300/// `shown` of `total` is stated plainly rather than only counting what is
301/// hidden — "Showing 100 of 6027" answers "where am I?", which a bare
302/// "5927 more…" does not. The button appears only while more items are
303/// actually retained; past the caller's retain cap the count is all that is
304/// left to say, so the footer becomes a plain line.
305///
306/// Returns nothing at all when everything is on screen.
307pub fn page_footer(
308 shown: usize,
309 retained: usize,
310 total: usize,
311 page: usize,
312 reveal: impl Fn() + 'static,
313) -> AnyView {
314 if total <= shown {
315 return view! {}.into_view().into_any();
316 }
317 let label = crate::i18n::t_fmt2(
318 crate::i18n::k::SEARCH_SHOWN_OF,
319 &shown.to_string(),
320 &total.to_string(),
321 );
322 let pageable = retained.saturating_sub(shown);
323 if pageable == 0 {
324 return view! { <div class="page-foot">{label}</div> }
325 .into_view()
326 .into_any();
327 }
328 let next = pageable.min(page);
329 view! {
330 <div class="page-foot">
331 <span class="pf-count">{label}</span>
332 <button class="pf-more" on:click=move |_| reveal()>
333 {crate::i18n::t_fmt(crate::i18n::k::SEARCH_SHOW_MORE, &next.to_string())}
334 </button>
335 </div>
336 }
337 .into_view()
338 .into_any()
339}
340
341/// Page sizes the folder listing offers.
342pub const PAGE_SIZES: [usize; 4] = [50, 100, 200, 500];
343
344const PAGE_SIZE_KEY: &str = "fbng.page_size";
345
346pub fn load_page_size() -> usize {
347 storage_get(PAGE_SIZE_KEY)
348 .and_then(|v| v.parse().ok())
349 .filter(|n| PAGE_SIZES.contains(n))
350 .unwrap_or(FILE_PAGE)
351}
352
353pub fn save_page_size(n: usize) {
354 storage_set(PAGE_SIZE_KEY, &n.to_string());
355}
356
357/// The page buttons to show, 0-based: the first, the last, and two on each
358/// side of `cur`. `None` is a gap.
359pub fn page_numbers(cur: usize, pages: usize) -> Vec<Option<usize>> {
360 let mut out = Vec::new();
361 for p in 0..pages {
362 if p == 0 || p + 1 == pages || p.abs_diff(cur) <= 2 {
363 out.push(Some(p));
364 } else if out.last() != Some(&None) {
365 out.push(None);
366 }
367 }
368 out
369}
370
371/// Footer under a server-paged list. Empty when the list fits the smallest
372/// page size, since then no control does anything.
373pub fn pager(
374 offset: usize,
375 shown: usize,
376 total: usize,
377 size: usize,
378 go: Callback<usize>,
379 set_size: Callback<usize>,
380) -> AnyView {
381 use crate::i18n::k;
382 if total <= PAGE_SIZES[0] {
383 return view! {}.into_view().into_any();
384 }
385 let cur = offset / size;
386 let pages = total.div_ceil(size);
387 let last = pages - 1;
388 let label = crate::i18n::t_fmt2(
389 k::SEARCH_SHOWN_OF,
390 &format!("{}–{}", offset + 1, offset + shown),
391 &total.to_string(),
392 );
393 let nav = move |glyph: &'static str, title: &'static str, to: usize, off: bool| {
394 view! {
395 <button
396 class="pf-btn"
397 disabled=off
398 title=crate::i18n::tr(title)
399 aria-label=crate::i18n::tr(title)
400 on:click=move |_| go.run(to)
401 >
402 {glyph}
403 </button>
404 }
405 };
406 let numbers = page_numbers(cur, pages)
407 .into_iter()
408 .map(|p| match p {
409 Some(p) => view! {
410 <button
411 class="pf-btn"
412 class:current=p == cur
413 aria-current=(p == cur).then_some("page")
414 on:click=move |_| go.run(p)
415 >
416 {p + 1}
417 </button>
418 }
419 .into_any(),
420 None => view! { <span class="pf-gap">"…"</span> }.into_any(),
421 })
422 .collect_view();
423 view! {
424 <div class="page-foot">
425 <span class="pf-count">{label}</span>
426 <nav class="pf-pages">
427 {nav("«", k::PAGE_FIRST, 0, cur == 0)}
428 {nav("‹", k::PAGE_PREV, cur.saturating_sub(1), cur == 0)}
429 {numbers}
430 {nav("›", k::PAGE_NEXT, (cur + 1).min(last), cur == last)}
431 {nav("»", k::PAGE_LAST, last, cur == last)}
432 </nav>
433 <label class="pf-goto">
434 {crate::i18n::tr(k::PAGE_GOTO)}
435 <input
436 type="number"
437 min="1"
438 max=pages.to_string()
439 prop:value=(cur + 1).to_string()
440 on:change=move |ev| {
441 if let Ok(n) = event_target_value(&ev).trim().parse::<usize>() {
442 go.run(n.clamp(1, pages) - 1);
443 }
444 }
445 />
446 </label>
447 <select
448 class="sort-select"
449 aria-label=crate::i18n::tr(k::PAGE_SIZE)
450 on:change=move |ev| {
451 if let Some(n) = select_value(&ev).and_then(|v| v.parse().ok()) {
452 set_size.run(n);
453 }
454 }
455 >
456 {PAGE_SIZES
457 .map(|n| view! {
458 <option value=n.to_string() selected=n == size>
459 {crate::i18n::t_fmt(k::PAGE_SIZE_N, &n.to_string())}
460 </option>
461 })
462 .to_vec()}
463 </select>
464 </div>
465 }
466 .into_view()
467 .into_any()
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473
474 #[test]
475 fn page_numbers_keep_the_ends_and_the_neighbours() {
476 let n = |cur, pages| page_numbers(cur, pages);
477 assert_eq!(n(0, 1), [Some(0)]);
478 assert_eq!(n(2, 5), [Some(0), Some(1), Some(2), Some(3), Some(4)]);
479 assert_eq!(n(0, 10), [Some(0), Some(1), Some(2), None, Some(9)]);
480 assert_eq!(
481 n(5, 10),
482 [
483 Some(0),
484 None,
485 Some(3),
486 Some(4),
487 Some(5),
488 Some(6),
489 Some(7),
490 None,
491 Some(9)
492 ]
493 );
494 }
495
496 #[test]
497 fn sort_spec_round_trips_through_its_stored_form() {
498 // No localStorage in the test runner, so only the parse half runs
499 // here. `load` falls back to the default.
500 assert_eq!(SortKey::parse("size"), Some(SortKey::Size));
501 assert_eq!(SortKey::parse("bogus"), None);
502 assert_eq!(SortSpec::default().key, SortKey::Name);
503 assert!(SortSpec::default().asc);
504 }
505
506 #[test]
507 fn format_date_drops_seconds_and_zone() {
508 assert_eq!(format_date("2026-09-11T12:34:56Z"), "2026-09-11 12:34");
509 assert_eq!(format_date("nonsense"), "nonsense");
510 }
511}
512