search.rs
⎇
Raw
1//! The search view (`#/search`): index-free name and content search with
2//! streamed results, an explicit stop button, a start-folder picker, and
3//! collapsible per-file match lists.
4//!
5//! Results arrive as they are found (SSE, see `api::search_stream`). The
6//! client caps only what it *renders* (name rows a page of [`FILE_PAGE`] at a
7//! time, match lines per file at [`RENDER_LINE_CAP`]) — the search itself is
8//! unbounded and ends when the walk is done or the user stops it. Stopping
9//! closes the event source; the server notices the dropped connection and
10//! unwinds its walk.
11
12use std::collections::HashMap;
13use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
14use std::sync::{Arc, Mutex};
15
16use api_types::{FileKind, SearchEvent};
17use gloo_timers::future::TimeoutFuture;
18use leptos::prelude::*;
19use wasm_bindgen::JsCast;
20
21use crate::api;
22use crate::components::icon::{Icon, icon_svg};
23use crate::components::toast::{ToastMsg, show_error};
24use crate::editor::EditTarget;
25use crate::i18n::{self, k};
26use crate::icons::{IconName, icon_for};
27use crate::preview::{PreviewTarget, preview_kind};
28use crate::router::{Location, Section, navigate};
29use crate::util::format_size;
30use crate::views::dialogs::Dialog;
31use crate::views::file_view::{FileView, UnsupportedTarget};
32
33/// Name rows rendered at once, and how many more each click of the "show
34/// more" row reveals. Small on purpose: rendering a row costs a fixed amount
35/// of reactive-graph setup, so the initial paint stays well under a frame and
36/// the user pays for more rows only by asking for them.
37const FILE_PAGE: usize = 100;
38/// Name hits kept for paging. The search keeps running and counting past
39/// this; hits beyond it are reported as a plain remainder that cannot be
40/// paged to, since holding every hit of a one-character query would grow
41/// without bound.
42const RETAIN_FILE_CAP: usize = 2000;
43/// Render cap for match lines per file.
44const RENDER_LINE_CAP: usize = 500;
45/// Match cards rendered at once, and how many more each click reveals. Lower
46/// than [`FILE_PAGE`] because a card is much taller than a row — it carries a
47/// header and its matched lines — so a page of them already fills the screen.
48const CARD_PAGE: usize = 20;
49/// Files with content matches kept for paging. As with [`RETAIN_FILE_CAP`],
50/// the search counts past this; the surplus is reported but cannot be paged
51/// to.
52const RETAIN_MATCH_FILE_CAP: usize = 500;
53/// Stream events are applied in batches this many milliseconds apart, not
54/// per event: an open search can emit thousands of events and applying them
55/// one by one would re-render per event and peg the main thread.
56///
57/// A flush applies its whole batch, but in chunks that yield to the browser
58/// between them (see [`apply_chunked`]) rather than in one go.
59const FLUSH_MS: u32 = 120;
60/// Events folded between yields, and items written per chunk.
61///
62// ponytail: two fixed sizes, not a feedback controller. `<For>` re-runs
63// `each` over the whole list per write, so a write costs roughly
64// `CHUNK + list_len` and a slow machine can still overrun a frame. Measure
65// before replacing this with anything adaptive.
66const EVENTS_PER_SLICE: usize = 2048;
67const CHUNK: usize = 64;
68
69/// Hands the main thread back to the browser, then resumes.
70///
71/// A plain macrotask, deliberately, after measuring the two obvious
72/// alternatives:
73///
74/// * `requestAnimationFrame` only fires while the browser is producing
75/// frames. Under a throttled compositor it dropped to 2 fps and the result
76/// list took tens of seconds to fill; a backgrounded tab would stall it
77/// outright.
78/// * `scheduler.yield()` resumes at user-blocking priority, ahead of the
79/// browser's own rendering update. Chunks then pile up unpainted and style
80/// and layout land in one lump at the end — measurably worse (a 110 ms task
81/// versus 85 ms, and settle 630 ms versus 390 ms).
82///
83/// A macrotask lets a rendering update happen between chunks, which is the
84/// point. The cost is `setTimeout`'s 4 ms clamp past nesting depth 5.
85async fn yield_to_browser() {
86 TimeoutFuture::new(0).await;
87}
88
89/// Applies `items` to `write` in chunks, yielding to the browser between
90/// them. One signal write per chunk, so a chunk costs one `<For>` pass.
91async fn apply_chunked<T, F>(items: Vec<T>, my_gen: u64, ctx: &FlushCtx, mut write: F)
92where
93 F: FnMut(Vec<T>),
94{
95 let mut rest = items;
96 while !rest.is_empty() {
97 // A new search (or an unmount) makes the remaining items obsolete.
98 if ctx.stale(my_gen) {
99 return;
100 }
101 let take = CHUNK.min(rest.len());
102 write(rest.drain(..take).collect());
103 yield_to_browser().await;
104 }
105}
106
107#[derive(Clone, Copy, PartialEq, Eq)]
108enum Scope {
109 Name,
110 Content,
111 Both,
112}
113
114impl Scope {
115 const fn param(self) -> &'static str {
116 match self {
117 Scope::Name => "name",
118 Scope::Content => "content",
119 Scope::Both => "both",
120 }
121 }
122}
123
124/// `text` is an `Arc<str>` because `<For each>` clones the whole line vector
125/// on every append; a refcount bump keeps that clone O(1) per line.
126#[derive(Clone)]
127struct MatchLine {
128 line: u64,
129 text: Arc<str>,
130}
131
132/// A file with content matches, kept in arrival order. The card's lines
133/// live in the view-level registry ([`CardState`]) under the same key; the
134/// vector only drives the keyed `<For>`.
135///
136/// `search_gen` stamps the search generation: the `<For>` key includes it so a new
137/// search's items can never match a previous search's nodes (a position
138/// match would keep the old node, with the old search's line state).
139#[derive(Clone)]
140struct MatchFile {
141 root_id: i64,
142 path: Arc<str>,
143 search_gen: u64,
144}
145
146/// Live state of a match card, owned by the search view (the registry
147/// `RwSignal`), not by the card's `<For>` node: one owner per path, and the
148/// lines survive the card being remounted. New lines and collapse toggles
149/// only touch the card that owns them.
150#[derive(Clone, Copy)]
151struct CardState {
152 lines: RwSignal<Vec<MatchLine>>,
153 collapsed: RwSignal<bool>,
154}
155
156/// `path` is an `Arc<str>` for the same reason as [`MatchLine::text`].
157#[derive(Clone)]
158struct FileHit {
159 root_id: i64,
160 path: Arc<str>,
161 size: u64,
162 is_dir: bool,
163 kind: FileKind,
164}
165
166/// The server's closing summary of a finished walk.
167#[derive(Clone, Copy, PartialEq)]
168struct Summary {
169 scanned: usize,
170 skipped: usize,
171 elapsed_ms: u64,
172}
173
174#[derive(Clone, Copy, PartialEq)]
175enum Status {
176 Idle,
177 Searching,
178 /// The walk ended. `stopped` marks an early end: the user pressed Stop,
179 /// or the server hit its match cap. `summary` is `None` when the user
180 /// stopped, because the connection is gone before the summary arrives.
181 Done {
182 stopped: bool,
183 summary: Option<Summary>,
184 },
185}
186
187/// Render `text` with every query hit wrapped in `<mark class="hl-hit">`, as
188/// one HTML string for `inner_html`.
189///
190/// One element per text instead of one per fragment. A fragment used to be a
191/// `#[component]`, and a component costs a reactive owner plus arena slots:
192/// 1000 name rows are ~9000 fragments, which measured at ~700 ms of the
193/// render (the same DOM built from plain JS takes 25 ms).
194///
195/// Both file names and file contents are untrusted, so every character of
196/// `text` goes through [`push_escaped`] and the only markup in the output is
197/// the `<mark>` this function writes.
198///
199/// Matching is case-insensitive: the text is lowercased into a copy with one
200/// lowercase character per original character, so a hit's offsets in the
201/// copy map straight back onto the original.
202///
203// ponytail: `lower` keeps that 1:1 map by taking only the first character of
204// each `to_lowercase()`. A character whose lowercase expands (`İ`) therefore
205// matches on its first character only. Use a real case-folding table if that
206// ever matters.
207fn highlight_html(text: &str, words: &[String]) -> String {
208 let mut out = String::with_capacity(text.len() + 16);
209 let needles: Vec<String> = words
210 .iter()
211 .filter(|w| !w.is_empty())
212 .map(|w| lower(w))
213 .collect();
214 if needles.is_empty() || text.is_empty() {
215 push_escaped(&mut out, text);
216 return out;
217 }
218 // The lowered copy, plus the original byte offset behind every byte of
219 // it. `orig_at[i]` is meaningful at each character boundary `i`, and
220 // carries `text.len()` as its final sentinel.
221 let mut lowered = String::with_capacity(text.len());
222 let mut orig_at: Vec<usize> = Vec::with_capacity(text.len() + 1);
223 for (b, c) in text.char_indices() {
224 let lc = c.to_lowercase().next().unwrap_or(c);
225 lowered.push(lc);
226 for _ in 0..lc.len_utf8() {
227 orig_at.push(b);
228 }
229 }
230 orig_at.push(text.len());
231
232 let mut pos = 0usize;
233 while pos < lowered.len() {
234 // Earliest hit of any word at or after `pos`.
235 let Some((start, n)) = needles
236 .iter()
237 .filter_map(|w| lowered[pos..].find(w.as_str()).map(|i| (pos + i, w.len())))
238 .min_by_key(|(i, _)| *i)
239 else {
240 break;
241 };
242 push_escaped(&mut out, &text[orig_at[pos]..orig_at[start]]);
243 out.push_str("<mark class=\"hl-hit\">");
244 push_escaped(&mut out, &text[orig_at[start]..orig_at[start + n]]);
245 out.push_str("</mark>");
246 pos = start + n;
247 }
248 push_escaped(&mut out, &text[orig_at[pos]..]);
249 out
250}
251
252/// Lowercase, one character out per character in — see [`highlight_html`].
253fn lower(s: &str) -> String {
254 s.chars()
255 .map(|c| c.to_lowercase().next().unwrap_or(c))
256 .collect()
257}
258
259/// Append `s` to `out` with the five HTML-significant characters escaped.
260fn push_escaped(out: &mut String, s: &str) {
261 for c in s.chars() {
262 match c {
263 '&' => out.push_str("&amp;"),
264 '<' => out.push_str("&lt;"),
265 '>' => out.push_str("&gt;"),
266 '"' => out.push_str("&quot;"),
267 '\'' => out.push_str("&#39;"),
268 _ => out.push(c),
269 }
270 }
271}
272
273/// Parse `#/search?q=...&scope=...&root=...&path=...` (the part after `?`).
274/// Returns the query, the scope and the start folder `(root, dir)` when a
275/// root is given.
276fn parse_search_url() -> (String, Scope, Option<(i64, String)>) {
277 let hash = web_sys::window()
278 .and_then(|w| w.location().hash().ok())
279 .unwrap_or_default();
280 let params = hash
281 .split_once('?')
282 .and_then(|(_, qs)| web_sys::UrlSearchParams::new_with_str(qs).ok());
283 let Some(p) = params else {
284 return (String::new(), Scope::Both, None);
285 };
286 let scope = match p.get("scope").as_deref() {
287 Some("name") => Scope::Name,
288 Some("content") => Scope::Content,
289 _ => Scope::Both,
290 };
291 let folder = p
292 .get("root")
293 .and_then(|s| s.trim().parse().ok())
294 .map(|root| (root, p.get("path").unwrap_or_default()));
295 (p.get("q").unwrap_or_default(), scope, folder)
296}
297
298fn search_hash(q: &str, scope: Scope, root: i64, dir: &str) -> String {
299 format!(
300 "#/search?q={}&scope={}&root={root}&path={}",
301 js_sys::encode_uri_component(q),
302 scope.param(),
303 js_sys::encode_uri_component(dir),
304 )
305}
306
307/// Open the search view with `dir` of `root` as the start folder and an
308/// empty query (the browser's "search in this folder").
309pub fn open_search_in(root: i64, dir: &str) {
310 if let Some(w) = web_sys::window() {
311 let _ = w
312 .location()
313 .set_hash(&search_hash("", Scope::Both, root, dir));
314 }
315}
316
317/// Current vertical window scroll, 0 when there is no window.
318fn scroll_y() -> f64 {
319 web_sys::window()
320 .and_then(|w| w.scroll_y().ok())
321 .unwrap_or(0.0)
322}
323
324fn scroll_to_y(y: f64) {
325 if let Some(w) = web_sys::window() {
326 w.scroll_to_with_x_and_y(0.0, y);
327 }
328}
329
330/// Navigate to the folder `path` sits in, so the hit can be seen in context.
331/// A top-level entry goes to the root itself.
332fn goto_parent(root_id: i64, path: &str) {
333 let mut parts = split_rel(path);
334 parts.pop();
335 navigate(&Location {
336 root_id: Some(root_id),
337 path: parts,
338 share_token: None,
339 section: Section::Files,
340 });
341}
342
343#[component]
344pub fn SearchView(
345 me: ReadSignal<Option<api_types::Me>>,
346 open_file: WriteSignal<Option<FileView>>,
347 // While a file view is open it covers the content area, so the search
348 // UI hides (the view stays mounted: an in-flight search keeps running).
349 file_view: ReadSignal<Option<FileView>>,
350 /// The start-folder picker is a shell-level dialog.
351 set_dialog: WriteSignal<Option<Dialog>>,
352) -> impl IntoView {
353 let toast = use_context::<ToastMsg>().expect("toast context");
354 // ---- state -------------------------------------------------------------
355 let (query, set_query) = RwSignal::<String>::new(String::new()).split();
356 let (scope, set_scope) = RwSignal::<Scope>::new(Scope::Both).split();
357 // The running search's query words, for highlighting. Not reactive: rows
358 // read it while they render, and it only changes with a new search.
359 let words = StoredValue::new(Vec::<String>::new());
360 // The folder a search starts in: `(root id, dir relative to the root)`.
361 // Defaults to the top of the caller's first root.
362 let (folder, set_folder) = RwSignal::<Option<(i64, String)>>::new(
363 me.get_untracked()
364 .and_then(|m| m.roots.first().map(|r| (r.id, String::new()))),
365 )
366 .split();
367 let status = RwSignal::new(Status::Idle);
368 let files_sig = RwSignal::<Vec<FileHit>>::new(Vec::new());
369 let (files_r, files_w) = files_sig.split();
370 let files_total = RwSignal::new(0usize);
371 // How many of the retained name hits are rendered. Grows a page at a
372 // time when the user clicks the "show more" row.
373 let shown_files = RwSignal::new(FILE_PAGE);
374 let shown_cards = RwSignal::new(CARD_PAGE);
375 let match_files_sig = RwSignal::<Vec<MatchFile>>::new(Vec::new());
376 let (match_files_r, match_files_w) = match_files_sig.split();
377 let matches_total = RwSignal::new(0usize);
378 // True count of files that had at least one match (the rendered list is
379 // capped), plus the set of seen paths. Non-reactive: the set only feeds
380 // a counter, and it outlives the flush batch it is used in.
381 let match_files_total = RwSignal::new(0usize);
382 let seen_match_files: Arc<Mutex<std::collections::HashSet<Arc<str>>>> =
383 Arc::new(Mutex::new(std::collections::HashSet::new()));
384 // Per-path card state for this view: created in `apply_batch` when a
385 // path is first seen, read by the card's `<For>` child, removed on card
386 // unmount. One owner per path, so the lines survive the card being
387 // remounted. Component-scoped (no static): it is disposed with the view
388 // and reset on every new search.
389 let registry: RwSignal<HashMap<Arc<str>, CardState>> = RwSignal::new(HashMap::new());
390
391 // The open event source, so Stop and unmount can both reach it.
392 // Deliberately *not* reactive: the stream outlives the component and
393 // touching a disposed signal panics.
394 let source: Arc<Mutex<Option<web_sys::EventSource>>> = Arc::new(Mutex::new(None));
395 // Stream events are buffered and applied in batches (see FLUSH_MS).
396 // `search_gen` is bumped on every new search *and on unmount*, so one
397 // check covers both "a stale flush from a previous run" and "the view is
398 // gone, do not touch its signals".
399 let pending: Arc<Mutex<Vec<SearchEvent>>> = Arc::new(Mutex::new(Vec::new()));
400 let flushing: Arc<AtomicBool> = Arc::new(AtomicBool::new(false));
401 let search_gen: Arc<AtomicU64> = Arc::new(AtomicU64::new(0));
402
403 // ---- actions -----------------------------------------------------------
404 let stop_search = Callback::new({
405 let source = source.clone();
406 let pending = pending.clone();
407 let search_gen = search_gen.clone();
408 move |_| {
409 if let Some(s) = source.lock().unwrap().take() {
410 s.close();
411 }
412 // Stop should stop the UI too: discard buffered events and
413 // invalidate the in-flight flush so nothing keeps landing. The
414 // totals are left alone — they count what the server found, and
415 // the "N more" rows report the difference to what is rendered.
416 pending.lock().unwrap().clear();
417 search_gen.fetch_add(1, Ordering::SeqCst);
418 // The server can no longer send its summary (the connection is
419 // gone), so settle the UI here.
420 status.set(Status::Done {
421 stopped: true,
422 summary: None,
423 });
424 }
425 });
426
427 // Buffer stream events, apply them in batches. The first buffered event
428 // schedules the flush; a late flush for an unmounted view or a replaced
429 // search is discarded.
430 let flush_ctx = FlushCtx {
431 pending: pending.clone(),
432 flushing: flushing.clone(),
433 search_gen: search_gen.clone(),
434 files: files_sig,
435 files_total,
436 match_files: match_files_sig,
437 matches_total,
438 match_files_total,
439 seen: seen_match_files.clone(),
440 registry,
441 status,
442 };
443 let on_stream_event = Callback::new({
444 let ctx = flush_ctx;
445 move |ev: SearchEvent| {
446 ctx.pending.lock().unwrap().push(ev);
447 if ctx
448 .flushing
449 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
450 .is_err()
451 {
452 return; // a flush is already pending
453 }
454 let my_gen = ctx.search_gen.load(Ordering::SeqCst);
455 wasm_bindgen_futures::spawn_local(run_flush(FLUSH_MS, my_gen, ctx.clone()));
456 }
457 });
458
459 let start_search = Callback::new({
460 let stop = stop_search;
461 let source = source.clone();
462 let search_gen = search_gen.clone();
463 move |()| {
464 // Untracked reads: starting a search must never register reactive
465 // dependencies (this callback can run from any context).
466 let q = query.get_untracked();
467 let scope = scope.get_untracked();
468 if q.trim().is_empty() {
469 return;
470 }
471 stop.run(()); // stop any in-flight search first
472 *source.lock().unwrap() = None;
473 pending.lock().unwrap().clear();
474 let my_gen = search_gen.fetch_add(1, Ordering::SeqCst) + 1;
475
476 // Exactly one start folder. Falls back to the first root when
477 // nothing is selected yet (a deep link with an unknown id, or
478 // `me` not loaded when the view was built).
479 let Some((root, dir)) = folder.get_untracked().or_else(|| {
480 me.get_untracked()
481 .and_then(|m| m.roots.first().map(|r| (r.id, String::new())))
482 }) else {
483 return;
484 };
485 set_folder.set(Some((root, dir.clone())));
486
487 // Fresh state for this run.
488 files_w.set(Vec::new());
489 files_total.set(0);
490 shown_files.set(FILE_PAGE);
491 shown_cards.set(CARD_PAGE);
492 match_files_w.set(Vec::new());
493 matches_total.set(0);
494 match_files_total.set(0);
495 seen_match_files.lock().unwrap().clear();
496 registry.set(HashMap::new());
497 status.set(Status::Searching);
498 // Write the search into the hash without adding a history entry.
499 if let Some(Ok(hist)) = web_sys::window().map(|w| w.history()) {
500 let _ = hist.replace_state_with_url(
501 &wasm_bindgen::JsValue::NULL,
502 "",
503 Some(&search_hash(&q, scope, root, &dir)),
504 );
505 }
506 words.set_value(query_words(&q));
507
508 let src = match api::search_stream(
509 q.clone(),
510 scope.param(),
511 root,
512 &dir,
513 on_stream_event,
514 // A plain closure, not a `Callback`: this also runs from the
515 // Search button's render closure, whose owner is disposed
516 // when the status re-renders. A `Callback` created there is
517 // gone by the time the stream fails, and the search never
518 // leaves "searching". Ignored once the search is replaced
519 // or the view unmounted (both bump the generation).
520 {
521 let search_gen = search_gen.clone();
522 move |msg| {
523 if search_gen.load(Ordering::SeqCst) != my_gen {
524 return;
525 }
526 show_error(toast, msg);
527 status.set(Status::Idle);
528 }
529 },
530 ) {
531 Ok(s) => s,
532 Err(e) => {
533 show_error(toast, e.to_string());
534 status.set(Status::Idle);
535 return;
536 }
537 };
538 *source.lock().unwrap() = Some(src);
539 }
540 });
541
542 // The search view's owner is the shell's view tree; a stream event can
543 // arrive on the main thread after unmount, so bumping the generation here
544 // makes every stream-side callback bail, and the stream is closed.
545 {
546 let source = source.clone();
547 let search_gen = search_gen.clone();
548 on_cleanup(move || {
549 search_gen.fetch_add(1, Ordering::SeqCst);
550 if let Some(s) = source.lock().unwrap().take() {
551 s.close();
552 }
553 });
554 }
555
556 // Collapse/expand all cards. Whether the group is fully collapsed is
557 // derived from the cards themselves (no counter to keep in sync).
558 let collapse_all: Callback<(), ()> = {
559 Callback::new(move |_| {
560 // Copy the states out before writing them: writing an inner
561 // signal while the registry's own borrow is held would rely on
562 // leptos deferring effects to a microtask.
563 let states: Vec<CardState> = registry.with_untracked(|m| m.values().copied().collect());
564 let target =
565 !(!states.is_empty() && states.iter().all(|c| c.collapsed.get_untracked()));
566 for c in states {
567 c.collapsed.set(target);
568 }
569 })
570 };
571
572 // Enter in the query field starts the search.
573 let on_query_key = move |ev: web_sys::KeyboardEvent| {
574 if ev.key() == "Enter" {
575 start_search.run(());
576 }
577 };
578
579 // Deep link: `#/search?root=…&path=…` sets the start folder (the
580 // browser's "search in this folder" arrives like this, with no query);
581 // with a `q` the search also re-runs.
582 {
583 let (q0, s0, f0) = parse_search_url();
584 // Only honour a root the caller actually has; otherwise keep the
585 // default so a stale link still searches something.
586 if let Some((id, dir)) = f0
587 && me
588 .get_untracked()
589 .is_some_and(|m| m.roots.iter().any(|r| r.id == id))
590 {
591 set_folder.set(Some((id, dir)));
592 }
593 if !q0.is_empty() {
594 set_query.set(q0);
595 set_scope.set(s0);
596 // Run the search from setup (an untracked context), not from an
597 // `Effect`: the effect would track `start_search`'s signal reads
598 // and retrigger on the very signal it writes (`folder`),
599 // re-running the search in a loop and pegging the main thread.
600 start_search.run(());
601 }
602 }
603
604 // The start-folder button opens the shared folder picker.
605 let pick_folder = move |_| {
606 let Some(m) = me.get_untracked() else {
607 return;
608 };
609 let Some((root, dir)) = folder
610 .get_untracked()
611 .or_else(|| m.roots.first().map(|r| (r.id, String::new())))
612 else {
613 return;
614 };
615 set_dialog.set(Some(Dialog::Picker {
616 title: i18n::t(k::SEARCH_IN).to_string(),
617 confirm: i18n::t(k::SEARCH_HERE).to_string(),
618 roots: m.roots,
619 root,
620 dir,
621 for_write: false,
622 on_pick: Callback::new(move |(root, dir): (i64, String)| {
623 set_folder.set(Some((root, dir)));
624 }),
625 }));
626 };
627
628 // Keep the scroll position across opening a result. The window is the
629 // scroller, and while a file is open the search UI is hidden, so the
630 // document shrinks to one viewport and the browser clamps the scroll to
631 // 0. Saving it on open and restoring on close is the only way back —
632 // hiding rather than unmounting is necessary but not sufficient.
633 // Saved by the handlers that open a result, *not* by the effect below:
634 // hiding the search UI is itself an effect, and if it ran first the
635 // scroll was already clamped to 0 by the time we read it.
636 let saved_scroll = StoredValue::new(0.0f64);
637 Effect::new(move |was_open: Option<bool>| {
638 let open = file_view.get().is_some();
639 if was_open == Some(true) && !open {
640 let y = saved_scroll.get_value();
641 // Only once the display flip has been laid out; before that the
642 // document is one viewport tall and the scroll is clamped away
643 // again.
644 wasm_bindgen_futures::spawn_local(async move {
645 yield_to_browser().await;
646 scroll_to_y(y);
647 });
648 }
649 open
650 });
651
652 // One delegated handler for the whole name list, instead of a `Callback`
653 // per row: a callback is an arena entry plus a closure allocation, and at
654 // a thousand rows that is a measurable slice of the render. The row
655 // carries its identity in data attributes; the hit itself is looked up in
656 // the list, which is a linear scan of at most `RETAIN_FILE_CAP` on a
657 // click.
658 let on_row_click = move |ev: web_sys::MouseEvent| {
659 let Some(target) = ev
660 .target()
661 .and_then(|t| t.dyn_into::<web_sys::Element>().ok())
662 else {
663 return;
664 };
665 let Some(row) = target.closest(".srow").ok().flatten() else {
666 return;
667 };
668 let Some(path) = row.get_attribute("data-path") else {
669 return;
670 };
671 let Some(root_id) = row
672 .get_attribute("data-root")
673 .and_then(|s| s.parse::<i64>().ok())
674 else {
675 return;
676 };
677 // The goto button is inside the row, so it is handled here rather
678 // than with its own callback per row.
679 if target.closest(".goto-btn").ok().flatten().is_some() {
680 goto_parent(root_id, &path);
681 return;
682 }
683 let Some(hit) = files_r.with_untracked(|v| {
684 v.iter()
685 .find(|h| h.root_id == root_id && *h.path == *path)
686 .cloned()
687 }) else {
688 return;
689 };
690 if hit.is_dir {
691 navigate(&Location {
692 root_id: Some(root_id),
693 path: split_rel(&path),
694 share_token: None,
695 section: Section::Files,
696 });
697 return;
698 }
699 let name = path.rsplit('/').next().unwrap_or(&path).to_string();
700 saved_scroll.set_value(scroll_y());
701 open_file.set(Some(open_file_view(
702 root_id,
703 path,
704 name,
705 hit.kind,
706 is_writable(me, root_id),
707 )));
708 };
709
710 // ---- render ------------------------------------------------------------
711 view! {
712 // Hidden with `display` rather than unmounted while a file is open
713 // (the same treatment the browser view gets). Unmounting would throw
714 // away every rendered row and rebuild it on close, and the document
715 // would lose its scroll position — see `keep_scroll` above.
716 <div
717 class="search-view"
718 style:display=move || if file_view.get().is_some() { "none" } else { "flex" }
719 >
720 <div class="query-bar">
721 <div class="query-input">
722 <Icon name=IconName::Search class="qi-icon".to_string()/>
723 <input
724 type="text"
725 placeholder=move || i18n::t(k::SEARCH_PLACEHOLDER).to_string()
726 value=move || query.get()
727 on:input=move |ev: web_sys::Event| {
728 if let Some(t) = ev
729 .target()
730 .and_then(|t| t.dyn_into::<web_sys::HtmlInputElement>().ok())
731 {
732 set_query.set(t.value());
733 }
734 }
735 on:keydown=on_query_key
736 autocomplete="off"
737 />
738 </div>
739 <div class="seg">
740 <button
741 class:on=move || scope.get() == Scope::Name
742 on:click=move |_| set_scope.set(Scope::Name)
743 >
744 {i18n::tr(k::SEARCH_NAME)}
745 </button>
746 <button
747 class:on=move || scope.get() == Scope::Content
748 on:click=move |_| set_scope.set(Scope::Content)
749 >
750 {i18n::tr(k::SEARCH_CONTENT)}
751 </button>
752 <button
753 class:on=move || scope.get() == Scope::Both
754 on:click=move |_| set_scope.set(Scope::Both)
755 >
756 {i18n::tr(k::SEARCH_BOTH)}
757 </button>
758 </div>
759 // A search covers one folder (and everything below it). The
760 // button shows it as "Root/dir" and opens the folder picker.
761 <button
762 class="folder-pick"
763 title=move || i18n::t(k::SEARCH_IN).to_string()
764 on:click=pick_folder
765 >
766 <Icon name=IconName::Folder class="fp-icon".to_string()/>
767 <span class="fp-path">
768 {move || {
769 let Some((root, dir)) = folder.get() else {
770 return String::new();
771 };
772 let name = me
773 .get()
774 .and_then(|m| m.roots.into_iter().find(|r| r.id == root))
775 .map(|r| r.name)
776 .unwrap_or_default();
777 if dir.is_empty() { name } else { format!("{name}/{dir}") }
778 }}
779 </span>
780 </button>
781 {move || {
782 if status.get() == Status::Searching {
783 view! {
784 <button class="btn-stop" on:click=move |_| stop_search.run(())>
785 <Icon name=IconName::Stop class="ic-stop".to_string()/>
786 {i18n::t(k::SEARCH_STOP)}
787 </button>
788 }
789 .into_view()
790 .into_any()
791 } else {
792 view! {
793 <button class="btn-run" on:click=move |_| start_search.run(())>
794 {i18n::t(k::SEARCH_RUN)}
795 </button>
796 }
797 .into_view()
798 .into_any()
799 }
800 }}
801
802 </div>
803 {move || match status.get() {
804 Status::Idle => view! {}.into_view().into_any(),
805 Status::Searching => view! {
806 <div class="status-line">
807 <span class="dot"></span>
808 <span>
809 {i18n::t(k::SEARCHING)}
810 {" · "}
811 {i18n::t_fmt(
812 k::SEARCH_N_RESULTS,
813 &(files_total.get() + matches_total.get()).to_string(),
814 )}
815 </span>
816 </div>
817 }
818 .into_view()
819 .into_any(),
820 Status::Done { stopped, summary } => {
821 let n = (files_total.get() + matches_total.get()).to_string();
822 let head = if stopped {
823 i18n::t_fmt(k::SEARCH_STOPPED, &n)
824 } else {
825 i18n::t_fmt(k::SEARCH_N_RESULTS, &n)
826 };
827 view! {
828 <div class="status-line finished">
829 <span>
830 {head}
831 {summary
832 .map(|s| {
833 view! {
834 <>
835 {" · "}
836 {i18n::t_fmt(k::SEARCH_TOOK, &s.elapsed_ms.to_string())}
837 {" · "}
838 {i18n::t_fmt(k::SEARCH_SCANNED, &s.scanned.to_string())}
839 {(s.skipped > 0)
840 .then(|| {
841 view! {
842 <span class="skip">
843 {" · "}
844 {i18n::t_fmt(
845 k::SEARCH_SKIPPED,
846 &s.skipped.to_string(),
847 )}
848 </span>
849 }
850 })}
851 </>
852 }
853 })}
854 </span>
855 </div>
856 }
857 .into_view()
858 .into_any()
859 }
860 }}
861
862 // The groups are hidden with `display` instead of unmounted:
863 // toggling scope must not rebuild the rows/cards (and the cards'
864 // line signals live in the registry, but keeping the DOM stable
865 // makes the toggle a single attribute write).
866 <div
867 class="result-group"
868 style:display=move || {
869 let show = matches!(scope.get(), Scope::Name | Scope::Both)
870 && (files_total.get() > 0 || status.get() != Status::Idle);
871 if show {
872 "flex"
873 } else {
874 "none"
875 }
876 }
877 >
878 <div class="group-label">
879 <Icon name=IconName::File class="gl-icon".to_string()/>
880 <span>{i18n::tr(k::FILES)}</span>
881 <span class="n">{"· "}{files_total}</span>
882 </div>
883 <div class="entries-list" on:click=on_row_click>
884 <For
885 // Slice inside `with`, so a page's worth is cloned
886 // rather than every retained hit.
887 each=move || {
888 let n = shown_files.get();
889 files_r.with(|v| v.iter().take(n).cloned().collect::<Vec<_>>())
890 }
891 key=move |h: &FileHit| (h.root_id, h.path.clone())
892 children=move |h: FileHit| {
893 // Note: only the first `shown_files` hits reach
894 // here; `each` above slices before cloning.
895 let (dir, name) = split_name(&h.path);
896 let icon = if h.is_dir {
897 IconName::Folder
898 } else {
899 icon_for(h.kind, name)
900 };
901 // Only the name is highlighted. The server matches
902 // the entry's own name, not its path, so a mark
903 // in the directory line would point at text that
904 // was never matched.
905 let name_h = words.with_value(|w| highlight_html(name, w));
906 let dir_s = dir.to_string();
907 let size = if h.is_dir {
908 "—".to_string()
909 } else {
910 format_size(h.size)
911 };
912 // `icon_svg`, not `<Icon/>`: no component owner
913 // per row. Click handling is delegated to the
914 // list (see `on_row_click`), so the row only
915 // carries data attributes.
916 view! {
917 <div
918 class="srow"
919 data-root=h.root_id.to_string()
920 data-path=h.path.to_string()
921 >
922 {icon_svg(icon, "srow-icon")}
923 <div class="srow-main">
924 <span class="srow-name" inner_html=name_h></span>
925 <span class="srow-dir">{dir_s}</span>
926 </div>
927 <span class="ssize">{size}</span>
928 <button
929 class="goto-btn"
930 title=move || i18n::t(k::SEARCH_GOTO).to_string()
931 aria-label=move || i18n::t(k::SEARCH_GOTO).to_string()
932 >
933 {icon_svg(IconName::FolderOpen, "goto-ic")}
934 </button>
935 </div>
936 }
937 }
938 />
939 {move || {
940 let retained = files_r.with(|v| v.len());
941 page_footer(
942 shown_files.get().min(retained),
943 retained,
944 files_total.get(),
945 FILE_PAGE,
946 move || shown_files.update(|n| *n += FILE_PAGE),
947 )
948 }}
949 </div>
950 </div>
951
952 <div
953 class="result-group"
954 style:display=move || {
955 let show = matches!(scope.get(), Scope::Content | Scope::Both)
956 && (!match_files_r.get().is_empty() || status.get() != Status::Idle);
957 if show {
958 "flex"
959 } else {
960 "none"
961 }
962 }
963 >
964 <div class="group-label">
965 <Icon name=IconName::Text class="gl-icon".to_string()/>
966 <span>{i18n::tr(k::SEARCH_CONTENT)}</span>
967 // Closures, not bare calls: these have to re-read the
968 // totals as the search streams in.
969 <span class="n">
970 {"· "}
971 {move || {
972 i18n::t_fmt(k::SEARCH_N_MATCHES, &matches_total.get().to_string())
973 }}
974 {" "}
975 {move || {
976 i18n::t_fmt(k::SEARCH_IN_N_FILES, &match_files_total.get().to_string())
977 }}
978 </span>
979 <span class="grow"></span>
980 <button class="collapse-all" on:click=move |_| collapse_all.run(())>
981 {move || {
982 let all_collapsed = registry.with(|m| {
983 !m.is_empty()
984 && m.values().all(|c| c.collapsed.get())
985 });
986 i18n::t(if all_collapsed {
987 k::SEARCH_EXPAND_ALL
988 } else {
989 k::SEARCH_COLLAPSE_ALL
990 })
991 }}
992 </button>
993 </div>
994 <For
995 // Sliced inside `with`, as for the name rows: a page's
996 // worth is cloned rather than every retained match file.
997 each=move || {
998 let n = shown_cards.get();
999 match_files_r.with(|v| v.iter().take(n).cloned().collect::<Vec<_>>())
1000 }
1001 key=move |f: &MatchFile| (f.search_gen, f.root_id, f.path.clone())
1002 children=move |f: MatchFile| {
1003 // The card's live state is created in `apply_batch`
1004 // (when the path was first seen) and owned by the
1005 // view-level registry: one owner per path, and the
1006 // lines survive this node being remounted (e.g. by a
1007 // keyed reorder mid-search). The child only reads
1008 // the entry; it never removes it, so an unmount
1009 // racing a new search cannot delete a fresh entry.
1010 // Entries of a finished search are wiped by the next
1011 // `start_search` or with the view itself.
1012 //
1013 // The entry is always there (`apply_batch` inserts it
1014 // before the path reaches `match_files`), but render
1015 // an empty card rather than panic the whole view if
1016 // that ordering ever changes.
1017 let Some(st) = registry.with_untracked(|m| m.get(&f.path).copied()) else {
1018 return view! {}.into_view().into_any();
1019 };
1020 let lines_r = st.lines;
1021 let collapsed = st.collapsed;
1022 let key = f.path.clone();
1023 let root_id = f.root_id;
1024 let (dir, name) = split_name(&f.path);
1025 // A content match came out of the grep, which only
1026 // reads text files, so the kind is known without
1027 // asking the server.
1028 let icon = icon_for(FileKind::Text, name);
1029 // The card's path is *not* highlighted: a content hit
1030 // was found in the file's text, not in its name, so
1031 // marking the name would claim a match that is not
1032 // there and duplicate what the name results show.
1033 let dir_s = dir.to_string();
1034 let name_s = name.to_string();
1035 // One open-callback per card (Copy). The header opens
1036 // the file; the matched lines are text to read, not
1037 // buttons.
1038 let open_file_cb = open_match_cb(root_id, key.clone(), me, open_file);
1039 let goto_path = key.clone();
1040 view! {
1041 <div class="match-card">
1042 // The whole header opens the file, so the two
1043 // buttons in it stop their clicks here.
1044 <div class="match-head" on:click=move |_| {
1045 saved_scroll.set_value(scroll_y());
1046 open_file_cb.run(());
1047 }>
1048 {icon_svg(icon, "mi")}
1049 <span class="mpath">
1050 <span>{dir_s}</span>
1051 {" / "}
1052 <b>{name_s}</b>
1053 </span>
1054 <span class="mcount">
1055 {move || {
1056 let n = lines_r.with(|v| v.len());
1057 i18n::t_fmt(k::SEARCH_N_MATCHES, &n.to_string())
1058 }}
1059 </span>
1060 <button
1061 class="goto-btn"
1062 title=move || i18n::t(k::SEARCH_GOTO).to_string()
1063 aria-label=move || i18n::t(k::SEARCH_GOTO).to_string()
1064 on:click=move |ev: web_sys::MouseEvent| {
1065 ev.stop_propagation();
1066 goto_parent(root_id, &goto_path);
1067 }
1068 >
1069 {icon_svg(IconName::FolderOpen, "goto-ic")}
1070 </button>
1071 <button
1072 class="chev"
1073 on:click=move |ev: web_sys::MouseEvent| {
1074 ev.stop_propagation();
1075 collapsed.update(|v| *v = !*v);
1076 }
1077 >
1078 <span class=move || {
1079 if collapsed.get() {
1080 "chev chev-up".to_string()
1081 } else {
1082 "chev chev-down".to_string()
1083 }
1084 }></span>
1085 </button>
1086 </div>
1087 <div
1088 class="match-lines"
1089 style:display=move || {
1090 if collapsed.get() {
1091 "none"
1092 } else {
1093 "block"
1094 }
1095 }
1096 >
1097 <For
1098 each=move || lines_r.get().into_iter().enumerate()
1099 key=move |p: &(usize, MatchLine)| (p.1.line, p.0)
1100 children=move |p: (usize, MatchLine)| {
1101 let l = p.1;
1102 let text_h = words
1103 .with_value(|w| highlight_html(&l.text, w));
1104 view! {
1105 <div class="mline">
1106 <span class="ln">{l.line}</span>
1107 <span class="tx" inner_html=text_h></span>
1108 </div>
1109 }
1110 }
1111 />
1112 </div>
1113 </div>
1114 }
1115 .into_view()
1116 .into_any()
1117 }
1118 />
1119 {move || {
1120 let retained = match_files_r.with(|v| v.len());
1121 page_footer(
1122 shown_cards.get().min(retained),
1123 retained,
1124 match_files_total.get(),
1125 CARD_PAGE,
1126 move || shown_cards.update(|n| *n += CARD_PAGE),
1127 )
1128 }}
1129 </div>
1130
1131 {move || {
1132 let done = matches!(status.get(), Status::Done { .. });
1133 if done && files_total.get() == 0 && matches_total.get() == 0 {
1134 view! {
1135 <div class="search-empty">{i18n::t(k::SEARCH_NO_RESULTS)}</div>
1136 }
1137 .into_view()
1138 .into_any()
1139 } else {
1140 view! {}.into_view().into_any()
1141 }
1142 }}
1143 </div>
1144 }
1145}
1146
1147/// Everything a flush needs: the shared event queue and the view signals.
1148#[derive(Clone)]
1149struct FlushCtx {
1150 pending: Arc<Mutex<Vec<SearchEvent>>>,
1151 flushing: Arc<AtomicBool>,
1152 search_gen: Arc<AtomicU64>,
1153 files: RwSignal<Vec<FileHit>>,
1154 files_total: RwSignal<usize>,
1155 match_files: RwSignal<Vec<MatchFile>>,
1156 matches_total: RwSignal<usize>,
1157 match_files_total: RwSignal<usize>,
1158 seen: Arc<Mutex<std::collections::HashSet<Arc<str>>>>,
1159 registry: RwSignal<HashMap<Arc<str>, CardState>>,
1160 status: RwSignal<Status>,
1161}
1162
1163impl FlushCtx {
1164 /// True once a new search has started or the view was unmounted — both
1165 /// bump the generation, and after either the view signals must not be
1166 /// written any more.
1167 fn stale(&self, my_gen: u64) -> bool {
1168 self.search_gen.load(Ordering::SeqCst) != my_gen
1169 }
1170}
1171
1172/// Waits `delay_ms`, then applies every event buffered in the meantime.
1173///
1174/// `flushing` is held for the whole (yielding) apply, so only one flush ever
1175/// writes the view state; events arriving during it buffer in `pending` and
1176/// the next flush picks them up right away instead of waiting `FLUSH_MS`.
1177async fn run_flush(delay_ms: u32, my_gen: u64, ctx: FlushCtx) {
1178 TimeoutFuture::new(delay_ms).await;
1179 if !ctx.stale(my_gen) {
1180 let batch: Vec<SearchEvent> = ctx.pending.lock().unwrap().drain(..).collect();
1181 if !batch.is_empty() {
1182 apply_batch(&ctx, batch, my_gen).await;
1183 }
1184 // Applying yields, so more events may have arrived meanwhile. They
1185 // are already `FLUSH_MS` old, so pick them up on the next tick —
1186 // keeping `flushing` held, so no second flush can start.
1187 if !ctx.stale(my_gen) && !ctx.pending.lock().unwrap().is_empty() {
1188 wasm_bindgen_futures::spawn_local(run_flush(0, my_gen, ctx.clone()));
1189 return;
1190 }
1191 }
1192 ctx.flushing.store(false, Ordering::SeqCst);
1193}
1194
1195/// Folds one batch into the view state with a single render per signal:
1196/// events are aggregated into locals first, then each signal is written
1197/// once. (Writing per event would trigger a re-render per event, which is
1198/// what froze the page.)
1199///
1200/// A file seen for the first time gets its registry entry here, before its
1201/// path reaches `match_files`, so the card's `<For>` child always finds it.
1202/// Lines for a file that already has a card are appended to that card's own
1203/// line signal, which leaves every other card's DOM untouched.
1204///
1205/// Counters and the finished status are applied at once — they are cheap and
1206/// the status line should tell the truth immediately. Only the parts that
1207/// build DOM go through [`apply_chunked`], which yields between chunks.
1208async fn apply_batch(ctx: &FlushCtx, batch: Vec<SearchEvent>, my_gen: u64) {
1209 let mut new_files: Vec<FileHit> = Vec::new();
1210 // Rows still allowed in the name list: it must never grow past the cap,
1211 // no matter how events are batched. `with_untracked` is a signposted
1212 // non-reactive, clone-free read of the length (this runs outside any
1213 // tracking context).
1214 let mut file_budget = RETAIN_FILE_CAP.saturating_sub(ctx.files.with_untracked(|v| v.len()));
1215 let mut file_count = 0usize;
1216 let mut mt = 0usize;
1217 let mut mft = 0usize;
1218 let mut new_match_files: Vec<MatchFile> = Vec::new();
1219 let mut mf_len = ctx.match_files.with_untracked(|v| v.len());
1220 // Generation stamp for the card keys (see `MatchFile::search_gen`).
1221 let search_gen = my_gen;
1222 let mut done: Option<Status> = None;
1223
1224 // Group the batch's match events per file, so a new card is seeded with
1225 // all of its lines at once. Grouped through an index rather than by
1226 // comparing against the last entry: several walker threads share one
1227 // channel, so two files grepped concurrently interleave in the stream.
1228 let mut acc: Vec<(i64, Arc<str>, Vec<MatchLine>)> = Vec::new();
1229 let mut acc_at: HashMap<Arc<str>, usize> = HashMap::new();
1230 {
1231 // Folded in slices with a yield between them. This loop allocates and
1232 // hashes a path per *event*, and a one-character query can emit tens
1233 // of thousands of them, so its cost tracks events received rather
1234 // than items rendered — it needs its own yield points, independent of
1235 // `apply_chunked` below. (Measured as a 133 ms task before this.)
1236 let mut since_yield = 0usize;
1237 for ev in batch {
1238 since_yield += 1;
1239 if since_yield >= EVENTS_PER_SLICE {
1240 since_yield = 0;
1241 yield_to_browser().await;
1242 if ctx.stale(my_gen) {
1243 return;
1244 }
1245 }
1246 match ev {
1247 SearchEvent::Done {
1248 stopped,
1249 files: _,
1250 matches: _,
1251 scanned,
1252 skipped,
1253 elapsed_ms,
1254 } => {
1255 done = Some(Status::Done {
1256 stopped,
1257 summary: Some(Summary {
1258 scanned,
1259 skipped,
1260 elapsed_ms,
1261 }),
1262 });
1263 }
1264 SearchEvent::File {
1265 root_id,
1266 path,
1267 size,
1268 is_dir,
1269 kind,
1270 } => {
1271 file_count += 1;
1272 if file_budget > 0 {
1273 file_budget -= 1;
1274 new_files.push(FileHit {
1275 root_id,
1276 path: path.into(),
1277 size,
1278 is_dir,
1279 kind,
1280 });
1281 }
1282 }
1283 SearchEvent::Match {
1284 root_id,
1285 path,
1286 line,
1287 text,
1288 } => {
1289 mt += 1;
1290 let path: Arc<str> = path.into();
1291 // Locked per event rather than for the whole fold: the
1292 // fold yields, and holding the guard across an await
1293 // would keep it locked over a suspension point.
1294 if ctx.seen.lock().unwrap().insert(path.clone()) {
1295 mft += 1;
1296 }
1297 let ml = MatchLine {
1298 line,
1299 text: text.into(),
1300 };
1301 match acc_at.get(&path) {
1302 Some(&i) => acc[i].2.push(ml),
1303 None => {
1304 acc_at.insert(path.clone(), acc.len());
1305 acc.push((root_id, path, vec![ml]));
1306 }
1307 }
1308 }
1309 }
1310 }
1311 }
1312
1313 // One owner per path: a card's lines live in the registry, not in the
1314 // card's `<For>` node, so remounting a card never loses them. Appends to
1315 // existing cards are collected and applied after the registry's borrow
1316 // is released — writing an inner signal from inside `update` would rely
1317 // on leptos deferring effects to a microtask.
1318 let mut appends: Vec<(CardState, Vec<MatchLine>)> = Vec::new();
1319 ctx.registry.update(|reg| {
1320 for (root_id, path, mut lines) in acc {
1321 match reg.get(&path) {
1322 Some(st) => appends.push((*st, lines)),
1323 None => {
1324 if mf_len >= RETAIN_MATCH_FILE_CAP {
1325 // The file will never get a card; its matches are
1326 // counted above and dropped here.
1327 continue;
1328 }
1329 // Seed a new card's collapse state from the group's
1330 // current all-collapsed state, so a live "collapse all"
1331 // is not undone by arriving cards.
1332 let all_collapsed =
1333 !reg.is_empty() && reg.values().all(|c| c.collapsed.get_untracked());
1334 lines.truncate(RENDER_LINE_CAP);
1335 reg.insert(
1336 path.clone(),
1337 CardState {
1338 lines: RwSignal::new(lines),
1339 collapsed: RwSignal::new(all_collapsed),
1340 },
1341 );
1342 mf_len += 1;
1343 new_match_files.push(MatchFile {
1344 root_id,
1345 path,
1346 search_gen,
1347 });
1348 }
1349 }
1350 }
1351 });
1352 // Cheap, so applied immediately: the counters and the finished status.
1353 if file_count > 0 {
1354 ctx.files_total.update(|n| *n += file_count);
1355 }
1356 if mt > 0 {
1357 ctx.matches_total.update(|n| *n += mt);
1358 if mft > 0 {
1359 ctx.match_files_total.update(|n| *n += mft);
1360 }
1361 }
1362 if let Some(s) = done {
1363 ctx.status.set(s);
1364 }
1365
1366 // Expensive, so chunked: everything that builds DOM. Cards first, so a
1367 // file's lines have somewhere to land, then the lines, then the name
1368 // rows.
1369 let files = ctx.files;
1370 let match_files = ctx.match_files;
1371 apply_chunked(new_match_files, my_gen, ctx, move |head| {
1372 match_files.update(|v| v.extend(head));
1373 })
1374 .await;
1375 for (st, lines) in appends {
1376 let room = RENDER_LINE_CAP.saturating_sub(st.lines.with_untracked(|v| v.len()));
1377 if room == 0 {
1378 continue;
1379 }
1380 let lines: Vec<MatchLine> = lines.into_iter().take(room).collect();
1381 apply_chunked(lines, my_gen, ctx, move |head| {
1382 st.lines.update(|v| v.extend(head));
1383 })
1384 .await;
1385 }
1386 apply_chunked(new_files, my_gen, ctx, move |head| {
1387 files.update(|v| v.extend(head));
1388 })
1389 .await;
1390}
1391
1392/// Whether the signed-in user may write to `root_id`.
1393fn is_writable(me: ReadSignal<Option<api_types::Me>>, root_id: i64) -> bool {
1394 me.get_untracked().is_some_and(|m| {
1395 m.roots
1396 .iter()
1397 .find(|r| r.id == root_id)
1398 .is_some_and(|r| r.mode.is_writable())
1399 })
1400}
1401
1402fn open_file_view(
1403 root_id: i64,
1404 path: String,
1405 name: String,
1406 kind: FileKind,
1407 is_rw: bool,
1408) -> FileView {
1409 if kind == FileKind::Text {
1410 return FileView::Editor(EditTarget {
1411 root_id,
1412 path,
1413 name,
1414 readonly: !is_rw,
1415 });
1416 }
1417 match preview_kind(kind) {
1418 Some(pk) => FileView::Preview(
1419 PreviewTarget {
1420 root_id,
1421 path,
1422 name,
1423 },
1424 pk,
1425 ),
1426 None => FileView::Unsupported(UnsupportedTarget {
1427 root_id,
1428 path,
1429 name,
1430 kind,
1431 }),
1432 }
1433}
1434
1435/// Open a content match: always a text file (the grep only reads those). One
1436/// callback per card, shared by all of its lines. Free function rather than a
1437/// component closure so the card's `<For>` children closure only captures
1438/// `Copy` signal handles (the surrounding closures must be re-runnable, and
1439/// `move` closures may only move `Copy` captures out of that environment).
1440fn open_match_cb(
1441 root_id: i64,
1442 path: Arc<str>,
1443 me: ReadSignal<Option<api_types::Me>>,
1444 open_file: WriteSignal<Option<FileView>>,
1445) -> Callback<()> {
1446 Callback::new(move |_| {
1447 let name = path.rsplit('/').next().unwrap_or(&path).to_string();
1448 let fv = open_file_view(
1449 root_id,
1450 path.to_string(),
1451 name,
1452 FileKind::Text,
1453 is_writable(me, root_id),
1454 );
1455 open_file.set(Some(fv));
1456 })
1457}
1458
1459/// Footer under a result list: where the user is in the results, and a button
1460/// to reveal the next page.
1461///
1462/// `shown` of `total` is stated plainly rather than only counting what is
1463/// hidden — "Showing 100 of 6027" answers "where am I?", which a bare
1464/// "5927 more…" does not. The button appears only while more results are
1465/// actually retained; past [`RETAIN_FILE_CAP`] the count is all that is left
1466/// to say, so the footer becomes a plain line.
1467///
1468/// Returns nothing at all when everything found is on screen.
1469fn page_footer(
1470 shown: usize,
1471 retained: usize,
1472 total: usize,
1473 page: usize,
1474 reveal: impl Fn() + 'static,
1475) -> AnyView {
1476 if total <= shown {
1477 return view! {}.into_view().into_any();
1478 }
1479 let label = i18n::t_fmt2(k::SEARCH_SHOWN_OF, &shown.to_string(), &total.to_string());
1480 let pageable = retained.saturating_sub(shown);
1481 if pageable == 0 {
1482 return view! { <div class="page-foot">{label}</div> }
1483 .into_view()
1484 .into_any();
1485 }
1486 let next = pageable.min(page);
1487 view! {
1488 <div class="page-foot">
1489 <span class="pf-count">{label}</span>
1490 <button class="pf-more" on:click=move |_| reveal()>
1491 {i18n::t_fmt(k::SEARCH_SHOW_MORE, &next.to_string())}
1492 </button>
1493 </div>
1494 }
1495 .into_view()
1496 .into_any()
1497}
1498
1499/// Lowercased whitespace-split words of the query.
1500fn query_words(query: &str) -> Vec<String> {
1501 query.split_whitespace().map(lower).collect()
1502}
1503
1504fn split_rel(path: &str) -> Vec<String> {
1505 path.split('/')
1506 .filter(|s| !s.is_empty())
1507 .map(String::from)
1508 .collect()
1509}
1510
1511/// `("docs/notes", "runbook.md")` from a relative path.
1512fn split_name(path: &str) -> (&str, &str) {
1513 match path.rfind('/') {
1514 Some(i) if i > 0 => (&path[..i], &path[i + 1..]),
1515 _ => ("", path),
1516 }
1517}
1518
1519#[cfg(test)]
1520mod tests {
1521 use super::*;
1522
1523 fn hl(text: &str, words: &[&str]) -> String {
1524 let w: Vec<String> = words.iter().map(|s| s.to_string()).collect();
1525 highlight_html(text, &w)
1526 }
1527
1528 /// `<mark class="hl-hit">x</mark>` written as `<x>`, so the expectations
1529 /// stay readable.
1530 fn short(html: &str) -> String {
1531 html.replace("<mark class=\"hl-hit\">", "<")
1532 .replace("</mark>", ">")
1533 }
1534
1535 #[test]
1536 fn highlight_marks_hits() {
1537 assert_eq!(short(&hl("Hello world", &["world"])), "Hello <world>");
1538 }
1539
1540 #[test]
1541 fn highlight_is_case_insensitive() {
1542 assert_eq!(short(&hl("HeLLo there", &["hello"])), "<HeLLo> there");
1543 }
1544
1545 #[test]
1546 fn highlight_marks_all_words() {
1547 assert_eq!(
1548 short(&hl("foo bar foo", &["foo", "bar"])),
1549 "<foo> <bar> <foo>"
1550 );
1551 }
1552
1553 #[test]
1554 fn highlight_no_hit_is_plain() {
1555 assert_eq!(hl("abc", &["xyz"]), "abc");
1556 }
1557
1558 #[test]
1559 fn highlight_empty_words_is_plain() {
1560 assert_eq!(hl("abc", &[]), "abc");
1561 assert_eq!(hl("", &["a"]), "");
1562 }
1563
1564 #[test]
1565 fn highlight_escapes_markup() {
1566 // File names and file contents are untrusted: the only markup in the
1567 // output must be the `<mark>` wrapper.
1568 assert_eq!(
1569 hl("<script>alert(1)</script>", &["script"]),
1570 "&lt;<mark class=\"hl-hit\">script</mark>&gt;alert(1)&lt;/\
1571 <mark class=\"hl-hit\">script</mark>&gt;"
1572 );
1573 // Escaping applies inside the highlighted span too.
1574 assert_eq!(hl("a<b", &["<b"]), "a<mark class=\"hl-hit\">&lt;b</mark>");
1575 assert_eq!(hl(r#"& " ' < >"#, &[]), "&amp; &quot; &#39; &lt; &gt;");
1576 }
1577
1578 #[test]
1579 fn highlight_handles_non_ascii() {
1580 // Ö and ö are 2 bytes each: the hit slices must follow character
1581 // boundaries of the original text.
1582 assert_eq!(short(&hl("AÖ aö b", &["ö"])), "A<Ö> a<ö> b");
1583 }
1584}
1585