diff --git a/src/features/search/__tests__/findSession.test.ts b/src/features/search/__tests__/findSession.test.ts index 4a253d6ea..50bfabf47 100644 --- a/src/features/search/__tests__/findSession.test.ts +++ b/src/features/search/__tests__/findSession.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc"; import { FindSession, @@ -149,6 +149,49 @@ describe("FindSession", () => { expect(last()).toMatchObject({ status: "done", stale: false, files: [], matchCount: 0 }); }); + describe("while results stream in", () => { + afterEach(() => vi.useRealTimers()); + + it("publishes a burst of files as a few updates, showing the first at once and the last without waiting for done", async () => { + vi.useFakeTimers(); + const { session, running, states, last } = setup(); + void session.search(q("foo")); + await vi.advanceTimersByTimeAsync(0); + const before = states.length; + // 1000 files, one per millisecond: 1s of streaming. + running[0]!.onFile(file("f0.kt", [1])); + await vi.advanceTimersByTimeAsync(0); + expect(last().files).toHaveLength(1); + for (let i = 1; i < 1000; i++) { + running[0]!.onFile(file(`f${i}.kt`, [1])); + await vi.advanceTimersByTimeAsync(1); + } + await vi.advanceTimersByTimeAsync(100); + expect(last().files).toHaveLength(1000); + expect(last().matchCount).toBe(1000); + expect(last().status).toBe("searching"); + // One per 50 ms plus the first: far below the one-per-file of an unbatched stream. + expect(states.length - before).toBeLessThanOrEqual(30); + running[0]!.finish(summary(1000)); + await vi.advanceTimersByTimeAsync(0); + expect(last().status).toBe("done"); + }); + + it("does not publish a pending update after dispose", async () => { + vi.useFakeTimers(); + const { session, running, states } = setup(); + void session.search(q("foo")); + await vi.advanceTimersByTimeAsync(0); + running[0]!.onFile(file("a.kt", [1])); + await vi.advanceTimersByTimeAsync(0); + running[0]!.onFile(file("b.kt", [1])); + session.dispose(); + const seen = states.length; + await vi.advanceTimersByTimeAsync(200); + expect(states.length).toBe(seen); + }); + }); + it("reports invalid patterns without starting a search", async () => { const { session, deps, last } = setup(); await session.search(q("(", { isRegex: true })); diff --git a/src/features/search/__tests__/findStream.test.tsx b/src/features/search/__tests__/findStream.test.tsx new file mode 100644 index 000000000..3067d666f --- /dev/null +++ b/src/features/search/__tests__/findStream.test.tsx @@ -0,0 +1,188 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { act, render, screen } from "@testing-library/react"; +import type { FileMatches, SearchQuery, SearchSummary } from "@/platform/ipc"; +import { FindToolWindow } from "../find/FindToolWindow"; +import { FindTreeBuilder, buildFindTree } from "../find/findTree"; +import type { FindDeps } from "../find/session"; +import { disposeFindWindow, openInFindWindow, useFindViewOptions } from "../find/windowStore"; + +const query: SearchQuery = { + pattern: "needle", + isRegex: false, + caseSensitive: false, + wholeWord: false, + include: [], + exclude: [], + scope: { kind: "project" }, + maxMatches: 0, +}; + +/** A deterministic pseudo-random order, so batches interleave paths and directories. */ +const shuffled = (items: readonly T[], seed = 7): T[] => { + const out = [...items]; + let s = seed; + for (let i = out.length - 1; i > 0; i--) { + s = (s * 1103515245 + 12345) & 0x7fffffff; + const j = s % (i + 1); + [out[i], out[j]] = [out[j]!, out[i]!]; + } + return out; +}; + +const file = (i: number): FileMatches => { + const dir = i % 9 === 0 ? "" : `src/pkg${i % 13}/sub${i % 4}`; + const relPath = `${dir ? `${dir}/` : ""}${i % 5 === 0 ? "File" : "file"}${i}.ts`; + return { + path: `/proj/${relPath}`, + relPath, + matches: [ + { line: 1, text: ` needle ${i}`, ranges: [[2, 8]], textOffset: 0 }, + { + line: 4 + (i % 3), + text: "needle needle", + ranges: [ + [0, 6], + [7, 13], + ], + textOffset: 0, + }, + ], + }; +}; + +afterEach(disposeFindWindow); + +describe("FindTreeBuilder", () => { + const files = shuffled(Array.from({ length: 300 }, (_, i) => file(i))); + + /** The files in their final order, by the same rule the view documents: sorted by path. */ + const sortedRels = (list: readonly FileMatches[]) => + [...list].map((f) => f.relPath).sort((a, b) => a.localeCompare(b)); + + for (const group of [false, true]) { + it(`builds the same tree incrementally as from scratch (${group ? "grouped by directory" : "flat"})`, () => { + const builder = new FindTreeBuilder(group); + let roots = builder.sync([]); + // Uneven batch sizes, including a batch that changes nothing. + for (const end of [1, 2, 2, 30, 31, 100, 299, 300]) roots = builder.sync(files.slice(0, end)); + expect(roots).toEqual(buildFindTree(files, group)); + expect(builder.sync(files)).toBe(roots); + + if (group) { + expect(roots.map((n) => (n.kind === "dir" ? n.label : ""))).toEqual( + [...new Set(files.map((f) => f.relPath.split("/").slice(0, -1).join("/") || "/"))].sort((a, b) => + a.localeCompare(b), + ), + ); + expect(roots.reduce((n, r) => n + (r.kind === "dir" ? r.count : 0), 0)).toBe(300 * 3); + } else { + expect(roots.map((n) => (n.kind === "file" ? n.path : ""))).toEqual( + sortedRels(files).map((rel) => `/proj/${rel}`), + ); + } + }); + } + + it("keeps the lookup tables in step with the roots", () => { + const builder = new FindTreeBuilder(true); + builder.sync(files.slice(0, 120)); + const roots = builder.sync(files); + const fresh = new FindTreeBuilder(true); + fresh.sync(files); + expect([...builder.byKey.keys()].sort()).toEqual([...fresh.byKey.keys()].sort()); + expect([...builder.expandable].sort()).toEqual([...fresh.expandable].sort()); + expect(builder.filesByPath.size).toBe(300); + for (const root of roots) expect(builder.byKey.get(root.key)).toBe(root); + }); + + it("replaces only the directories that gained files", () => { + const builder = new FindTreeBuilder(true); + const list = [file(1), file(2), file(3)]; + const before = builder.sync(list); + const after = builder.sync([...list, file(53)]); // same dir as file(1) + const byLabel = (roots: typeof before) => new Map(roots.map((n) => [n.kind === "dir" ? n.label : "", n])); + const [a, b] = [byLabel(before), byLabel(after)]; + expect(b.get("src/pkg1/sub1")).not.toBe(a.get("src/pkg1/sub1")); + expect(b.get("src/pkg1/sub1")).toMatchObject({ count: 6 }); + expect(b.get("src/pkg2/sub2")).toBe(a.get("src/pkg2/sub2")); + expect(b.get("src/pkg3/sub3")).toBe(a.get("src/pkg3/sub3")); + }); + + it("rebuilds when the list is not an extension of the previous one", () => { + const builder = new FindTreeBuilder(false); + builder.sync(files.slice(0, 50)); + const other = files.slice(100, 120); + expect(builder.sync(other)).toEqual(buildFindTree(other, false)); + expect(builder.sync([])).toEqual([]); + expect(builder.byKey.size).toBe(0); + const swapped = [...files.slice(0, 5)]; + builder.sync(swapped); + swapped[4] = files[40]!; + expect(builder.sync(swapped)).toEqual(buildFindTree(swapped, false)); + }); +}); + +describe("streaming results into the Find tool window", () => { + const F = 2000; + const BATCHES = 40; + + beforeEach(() => { + vi.useFakeTimers(); + useFindViewOptions.setState({ preview: false, groupByDirectory: false }); + }); + afterEach(() => vi.useRealTimers()); + + /** Files whose `matches` list counts how often a consumer reads it, i.e. how often a file is processed. */ + const counted = (reads: { n: number }) => + Array.from({ length: F }, (_, i) => { + const { matches, ...rest } = file(i); + return Object.defineProperty({ ...rest } as FileMatches, "matches", { + get() { + reads.n++; + return matches; + }, + enumerable: true, + }); + }); + + it("processes each streamed file a bounded number of times, not once per update", async () => { + const reads = { n: 0 }; + const all = counted(reads); + let push!: (f: FileMatches) => void; + let finish!: (s: SearchSummary) => void; + const deps: FindDeps = { + validate: async () => {}, + start: (_id, _q, onFile) => + new Promise((resolve) => { + push = onFile; + finish = resolve; + }), + cancel: () => {}, + nextRequestId: () => 1, + }; + openInFindWindow(query, "needle", { deps }); + render(); + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + + let updates = 0; + for (let b = 0; b < BATCHES; b++) { + await act(async () => { + for (const f of all.slice((b * F) / BATCHES, ((b + 1) * F) / BATCHES)) push(f); + await vi.advanceTimersByTimeAsync(60); + }); + updates++; + } + await act(async () => { + finish({ files: F, matches: F * 3, limitHit: false, cancelled: false, elapsedMs: 1 }); + await vi.advanceTimersByTimeAsync(0); + }); + + expect(updates).toBe(BATCHES); + expect(screen.getByText(/6.?000 matches in 2.?000 files/)).toBeInTheDocument(); + // Counting matches and building nodes read each file's matches once each; rebuilding the tree on + // every one of the 40 updates would read them about 20 times each. + expect(reads.n).toBeLessThanOrEqual(3 * F); + }); +}); diff --git a/src/features/search/__tests__/findWindow.test.ts b/src/features/search/__tests__/findWindow.test.ts index 25d4e9b40..cb7cd3331 100644 --- a/src/features/search/__tests__/findWindow.test.ts +++ b/src/features/search/__tests__/findWindow.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { provideToolWindowService, type ToolWindowService } from "@/workbench/contributions"; import type { FileMatches, SearchQuery } from "@/platform/ipc"; -import { buildFindTree } from "../find/FindToolWindow"; +import { buildFindTree } from "../find/findTree"; import type { FindDeps } from "../find/session"; import { closeFindTab, diff --git a/src/features/search/__tests__/replaceFlow.test.ts b/src/features/search/__tests__/replaceFlow.test.ts index a20d7fe06..1f388b99f 100644 --- a/src/features/search/__tests__/replaceFlow.test.ts +++ b/src/features/search/__tests__/replaceFlow.test.ts @@ -19,7 +19,7 @@ import { toggleExcluded, type ReplaceDeps, } from "../find/replaceFlow"; -import { buildFindTree, nodeGroups } from "../find/FindToolWindow"; +import { buildFindTree, nodeGroups } from "../find/findTree"; const q: SearchQuery = { pattern: "foo", diff --git a/src/features/search/find/FindToolWindow.tsx b/src/features/search/find/FindToolWindow.tsx index b3a8aa128..f26a2423b 100644 --- a/src/features/search/find/FindToolWindow.tsx +++ b/src/features/search/find/FindToolWindow.tsx @@ -3,7 +3,6 @@ import { useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from " import clsx from "clsx"; import { create } from "zustand"; import { executeAction } from "@/platform/actions"; -import type { FileMatches } from "@/platform/ipc"; import { formatBinding, hostBinding, shortcutLabel } from "@/platform/keymap"; import { Button, @@ -23,8 +22,8 @@ import { T, } from "@/ui"; import { notifications, useOccurrenceNavigator } from "@/workbench/contributions"; -import { basename, openLocation, relDir } from "../common/open"; -import { countFileMatches } from "./session"; +import { openLocation } from "../common/open"; +import { FindTreeBuilder, allExpandableKeys, nodeGroups, type Node } from "./findTree"; import { CodePreview, MatchText, type PreviewHighlight } from "./parts"; import { confirmReplacement } from "./ReplaceAllConfirmation"; import { @@ -41,7 +40,6 @@ import { type ReplaceMarks, type ReplaceProgress, type ReplaceRun, - type UsageGroup, type Usage, } from "./replaceFlow"; import { @@ -56,78 +54,6 @@ import { import styles from "./FindToolWindow.module.css"; import { t, tx } from "@/platform/i18n"; -type Node = - | { kind: "dir"; key: string; label: string; count: number; children: Node[] } - | { kind: "file"; key: string; path: string; name: string; dir: string; count: number; children: Node[] } - | { - kind: "match"; - key: string; - path: string; - line: number; - col: number; - endCol: number; - text: string; - /** Column of `text` in the real line. */ - textCol: number; - ranges: Array<[number, number]>; - starts: Array<{ line: number; col: number }>; - }; - -/** - * Streamed file matches as file → line nodes, flat and sorted by path (IDEA's - * default), or under their directory with `groupByDirectory`. - */ -export function buildFindTree(files: readonly FileMatches[], groupByDirectory = false): Node[] { - const dirs = new Map(); - const flat: Node[] = []; - for (const f of files) { - const dir = relDir(f.relPath); - let d = dirs.get(dir); - if (!d && groupByDirectory) { - d = { kind: "dir", key: `d:${dir}`, label: dir || "/", count: 0, children: [] }; - dirs.set(dir, d); - } - const children: Node[] = f.matches.map((m) => { - const lead = m.text.length - m.text.trimStart().length; - const text = m.text.slice(lead).trimEnd(); - const first = m.ranges[0] ?? [0, 0]; - return { - kind: "match", - key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`, - path: f.path, - line: m.line, - col: first[0] + m.textOffset, - endCol: first[1] + m.textOffset, - text, - textCol: lead + m.textOffset, - ranges: m.ranges - .map(([s, e]) => [Math.max(0, s - lead), Math.min(text.length, e - lead)] as [number, number]) - .filter(([s, e]) => e > s), - starts: m.ranges.map(([s]) => ({ line: m.line, col: s + m.textOffset })), - }; - }); - const count = countFileMatches(f); - const file: Node = { - kind: "file", - key: `f:${f.path}`, - path: f.path, - name: basename(f.relPath), - dir, - count, - children, - }; - if (d) { - d.children.push(file); - d.count += count; - } else flat.push(file); - } - if (!groupByDirectory) { - const rel = (n: Node) => (n.kind === "file" ? (n.dir ? `${n.dir}/${n.name}` : n.name) : ""); - return flat.sort((a, b) => rel(a).localeCompare(rel(b))); - } - return [...dirs.values()].sort((a, b) => a.label.localeCompare(b.label)); -} - /** Preview target of a node: a match, or a file's first match. */ function previewOf(node: Node | null): { path: string; line: number } | null { if (!node || node.kind === "dir") return null; @@ -136,12 +62,6 @@ function previewOf(node: Node | null): { path: string; line: number } | null { return first?.kind === "match" ? { path: node.path, line: first.line } : null; } -/** The usages under a node (itself for a match). */ -export function nodeGroups(node: Node): UsageGroup[] { - if (node.kind === "match") return [{ key: node.key, path: node.path, starts: node.starts }]; - return node.children.flatMap(nodeGroups); -} - /** Excluded (⌫) / replaced usages per Find tab. */ const useMarks = create<{ byTab: Record }>(() => ({ byTab: {} })); const setMarks = (tab: number, marks: ReplaceMarks) => @@ -151,15 +71,6 @@ const useCollapsed = create<{ byTab: Record> }>(() = const setCollapsed = (tab: number, keys: ReadonlySet) => useCollapsed.setState((s) => ({ byTab: { ...s.byTab, [tab]: keys } })); -function allExpandableKeys(nodes: readonly Node[], out = new Set()): Set { - for (const n of nodes) { - if (n.kind === "match") continue; - out.add(n.key); - allExpandableKeys(n.children, out); - } - return out; -} - /** Search tabs in the tool window header. */ export function FindTabs() { const tabs = useFindWindow((s) => s.tabs); @@ -236,32 +147,23 @@ function FindTabView({ tab }: { tab: FindTab }) { }, [showPreview]); const previewLayout = stacked ? "openidea.find.previewSplit.vertical" : "openidea.find.previewSplit"; const minPanelSize = stacked ? "30%" : 160; - const roots = useMemo(() => buildFindTree(tab.state.files, groupByDirectory), [tab.state.files, groupByDirectory]); + const findTree = useMemo(() => new FindTreeBuilder(groupByDirectory), [groupByDirectory]); + const roots = useMemo(() => findTree.sync(tab.state.files), [findTree, tab.state.files]); const tree = useRef(null); const [leadNode, setLeadNode] = useState(null); const collapsed = useCollapsed((s) => s.byTab[tab.id]); const expanded = useMemo(() => { - const all = allExpandableKeys(roots); + const all = new Set(findTree.expandable); if (collapsed) for (const k of collapsed) all.delete(k); return all; - }, [roots, collapsed]); + }, [findTree, roots, collapsed]); // eslint-disable-line react-hooks/exhaustive-deps -- roots: the builder changed under it const st = tab.state; const marks = useMarks((m) => m.byTab[tab.id]) ?? NO_MARKS; const [selection, setSelection] = useState>(new Set()); const [running, setRunning] = useState(null); const [progress, setProgress] = useState(null); const busy = !!running; - const allGroups = useMemo(() => roots.flatMap(nodeGroups), [roots]); - const byKey = useMemo(() => { - const map = new Map(); - const walk = (list: readonly Node[]) => - list.forEach((n) => { - map.set(n.key, n); - if (n.kind !== "match") walk(n.children); - }); - walk(roots); - return map; - }, [roots]); + const byKey = findTree.byKey; const selectedGroups = () => [...selection].flatMap((k) => (byKey.get(k) ? nodeGroups(byKey.get(k)!) : [])); const exclude = () => { @@ -284,7 +186,7 @@ function FindTabView({ tab }: { tab: FindTab }) { const preview = previewOf(leadNode); const highlights = useMemo(() => { - const f = preview && st.files.find((x) => x.path === preview.path); + const f = preview && findTree.filesByPath.get(preview.path); return (f?.matches ?? []).map((m) => ({ line: m.line, ranges: m.ranges.map(([a, b]) => [a + m.textOffset, b + m.textOffset] as [number, number]), @@ -298,7 +200,7 @@ function FindTabView({ tab }: { tab: FindTab }) { query: tab.query, replacement: tab.replacement, preserveCase: !!tab.preserveCase, - targets: allInScope ? skipTargets(allGroups, marks) : replaceTargets(usages), + targets: allInScope ? skipTargets(roots.flatMap(nodeGroups), marks) : replaceTargets(usages), allInScope, }, setProgress, @@ -363,7 +265,11 @@ function FindTabView({ tab }: { tab: FindTab }) { }; const replaceMode = tab.replacement !== null; - const allPending = pendingUsages(allGroups, marks); + // Replace All stays disabled while results stream in, so the pass over every usage waits for the end. + const allPending = useMemo( + () => (replaceMode && st.status !== "searching" ? pendingUsages(roots.flatMap(nodeGroups), marks) : []), + [replaceMode, st.status, roots, marks], + ); // Past the search's limit, every match in the scope is replaced, listed or not (as in IDEA). const allInScope = !!st.summary?.limitHit; const confirmReplaceAll = async () => { diff --git a/src/features/search/find/findTree.ts b/src/features/search/find/findTree.ts new file mode 100644 index 000000000..91bd24749 --- /dev/null +++ b/src/features/search/find/findTree.ts @@ -0,0 +1,198 @@ +import type { FileMatches } from "@/platform/ipc"; +import { basename, relDir } from "../common/open"; +import { countFileMatches } from "./session"; +import type { UsageGroup } from "./replaceFlow"; + +export type Node = + | { kind: "dir"; key: string; label: string; count: number; children: Node[] } + | { kind: "file"; key: string; path: string; name: string; dir: string; count: number; children: Node[] } + | { + kind: "match"; + key: string; + path: string; + line: number; + col: number; + endCol: number; + text: string; + /** Column of `text` in the real line. */ + textCol: number; + ranges: Array<[number, number]>; + starts: Array<{ line: number; col: number }>; + }; + +type FileNode = Node & { kind: "file" }; + +function fileNode(f: FileMatches): FileNode { + const children: Node[] = f.matches.map((m) => { + const lead = m.text.length - m.text.trimStart().length; + const text = m.text.slice(lead).trimEnd(); + const first = m.ranges[0] ?? [0, 0]; + return { + kind: "match", + key: `m:${f.path}:${m.line}:${first[0] + m.textOffset}`, + path: f.path, + line: m.line, + col: first[0] + m.textOffset, + endCol: first[1] + m.textOffset, + text, + textCol: lead + m.textOffset, + ranges: m.ranges + .map(([s, e]) => [Math.max(0, s - lead), Math.min(text.length, e - lead)] as [number, number]) + .filter(([s, e]) => e > s), + starts: m.ranges.map(([s]) => ({ line: m.line, col: s + m.textOffset })), + }; + }); + return { + kind: "file", + key: `f:${f.path}`, + path: f.path, + name: basename(f.relPath), + dir: relDir(f.relPath), + count: countFileMatches(f), + children, + }; +} + +/** `old` and `add` are sorted by `cmp`; ties keep `old` first, so the result equals a stable sort of both. */ +function mergeSorted(old: readonly T[], add: T[], cmp: (a: T, b: T) => number): T[] { + if (!add.length) return old.slice(); + add.sort(cmp); + const out: T[] = []; + let from = 0; + let i = 0; + while (i < add.length) { + // First `old` entry greater than add[i]. + let lo = from; + let hi = old.length; + while (lo < hi) { + const mid = (lo + hi) >>> 1; + if (cmp(old[mid]!, add[i]!) <= 0) lo = mid + 1; + else hi = mid; + } + for (let k = from; k < lo; k++) out.push(old[k]!); + from = lo; + out.push(add[i++]!); + } + for (let k = from; k < old.length; k++) out.push(old[k]!); + return out; +} + +interface FlatEntry { + rel: string; + node: FileNode; +} + +interface DirEntry { + key: string; + label: string; + count: number; + children: Node[]; + node: Node | null; +} + +/** + * Streamed file matches as file → line nodes, flat and sorted by path (IDEA's + * default), or under their directory with `groupByDirectory`. + * + * `sync` is incremental: the streamed list only ever grows at its end, so a call + * builds nodes for the new files alone and merges them into the sorted result, + * making the cost of a whole stream linear in the number of files. A list that + * is not an extension of the previous one is rebuilt from scratch. + */ +export class FindTreeBuilder { + /** Every node by key, kept in step with `sync`. */ + readonly byKey = new Map(); + /** Keys of every node that has children (files, directories). */ + readonly expandable = new Set(); + readonly filesByPath = new Map(); + private roots: Node[] = []; + private built = 0; + private first: FileMatches | null = null; + private last: FileMatches | null = null; + private flat: FlatEntry[] = []; + private dirs = new Map(); + private dirList: DirEntry[] = []; + + constructor(private readonly groupByDirectory = false) {} + + /** Roots for `files`; the same array while nothing was appended. */ + sync(files: readonly FileMatches[]): Node[] { + if (this.built && (files.length < this.built || files[0] !== this.first || files[this.built - 1] !== this.last)) + this.reset(); + if (files.length === this.built) return this.roots; + const fresh: FlatEntry[] = []; + const newDirs: DirEntry[] = []; + const touched = new Set(); + for (let i = this.built; i < files.length; i++) { + const f = files[i]!; + const file = fileNode(f); + this.filesByPath.set(f.path, f); + this.byKey.set(file.key, file); + this.expandable.add(file.key); + for (const m of file.children) this.byKey.set(m.key, m); + if (!this.groupByDirectory) { + fresh.push({ rel: file.dir ? `${file.dir}/${file.name}` : file.name, node: file }); + continue; + } + let d = this.dirs.get(file.dir); + if (!d) { + d = { key: `d:${file.dir}`, label: file.dir || "/", count: 0, children: [], node: null }; + this.dirs.set(file.dir, d); + newDirs.push(d); + } + d.children.push(file); + d.count += file.count; + touched.add(d); + } + if (files.length) { + this.first = files[0]!; + this.last = files[files.length - 1]!; + } + this.built = files.length; + if (!this.groupByDirectory) { + this.flat = mergeSorted(this.flat, fresh, (a, b) => a.rel.localeCompare(b.rel)); + this.roots = this.flat.map((e) => e.node); + return this.roots; + } + // A directory that gained files becomes a new node, so rows showing its count update. + for (const d of touched) { + d.node = { kind: "dir", key: d.key, label: d.label, count: d.count, children: d.children.slice() }; + this.byKey.set(d.key, d.node); + this.expandable.add(d.key); + } + this.dirList = mergeSorted(this.dirList, newDirs, (a, b) => a.label.localeCompare(b.label)); + this.roots = this.dirList.map((d) => d.node!); + return this.roots; + } + + private reset() { + this.byKey.clear(); + this.expandable.clear(); + this.filesByPath.clear(); + this.roots = []; + this.built = 0; + this.first = this.last = null; + this.flat = []; + this.dirs.clear(); + this.dirList = []; + } +} + +export function buildFindTree(files: readonly FileMatches[], groupByDirectory = false): Node[] { + return new FindTreeBuilder(groupByDirectory).sync(files); +} + +/** The usages under a node (itself for a match). */ +export function nodeGroups(node: Node): UsageGroup[] { + if (node.kind === "match") return [{ key: node.key, path: node.path, starts: node.starts }]; + return node.children.flatMap(nodeGroups); +} + +export function allExpandableKeys(nodes: readonly Node[], out = new Set()): Set { + for (const n of nodes) { + if (n.kind === "match") continue; + out.add(n.key); + allExpandableKeys(n.children, out); + } + return out; +} diff --git a/src/features/search/find/session.ts b/src/features/search/find/session.ts index e187db30e..2e8c8f7c4 100644 --- a/src/features/search/find/session.ts +++ b/src/features/search/find/session.ts @@ -7,7 +7,8 @@ * * A new `search()` supersedes whatever is running: the previous backend * request is cancelled and its late events are dropped. Results stream in - * per file and are published at most once per microtask. + * per file and are published at most once per `PUBLISH_INTERVAL_MS`, so a burst of + * files costs one view update instead of one per file. */ import type { FileMatches, RequestId, SearchQuery, SearchSummary } from "@/platform/ipc"; import { preserveCase } from "@/platform/search"; @@ -33,6 +34,9 @@ export interface FindDeps { nextRequestId(): RequestId; } +/** Streamed results reach the view at most this often (a few frames), keeping a long stream linear. */ +const PUBLISH_INTERVAL_MS = 50; + export const countFileMatches = (file: FileMatches): number => file.matches.reduce((count, line) => count + line.ranges.length, 0); @@ -60,6 +64,8 @@ export class FindSession { private request: RequestId | null = null; private state: FindState = IDLE; private queued = false; + private timer: ReturnType | undefined; + private lastPublish = 0; private disposed = false; constructor( @@ -102,6 +108,7 @@ export class FindSession { const request = this.deps.nextRequestId(); this.request = request; + this.lastPublish = 0; const files: FileMatches[] = []; let matchCount = 0; this.update({ ...this.state, status: "searching" }, true); @@ -151,17 +158,28 @@ export class FindSession { this.state = next; if (this.disposed) return; if (immediate) { - this.queued = false; - this.onChange(next); + this.publish(false); return; } - if (this.queued) return; - this.queued = true; - queueMicrotask(() => { - if (!this.queued || this.disposed) return; - this.queued = false; - this.onChange(this.state); - }); + if (this.timer !== undefined || this.queued) return; + // A streamed file publishes at once when the last publish is old enough (the first file shows + // without delay); otherwise it waits so the batch behind it is one update, not one per file. + const wait = this.lastPublish + PUBLISH_INTERVAL_MS - Date.now(); + if (wait <= 0) { + this.queued = true; + queueMicrotask(() => { + if (this.queued) this.publish(true); + }); + } else this.timer = setTimeout(() => this.publish(true), wait); + } + + private publish(streamed: boolean) { + this.queued = false; + clearTimeout(this.timer); + this.timer = undefined; + if (this.disposed) return; + if (streamed) this.lastPublish = Date.now(); + this.onChange(this.state); } }