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