import CoreGraphics import Foundation import HelderCore import HelderServices import Observation /// The ⌘F overlay's state: three indexes searched per keystroke (open file, project contents, file names). @Observable @MainActor public final class SearchModel { public enum Column: Equatable, Sendable { case thisFile, project, files } /// What ↵ or a click opens: a file, optionally at a line. public struct Target: Equatable, Sendable { public var path: String public var line: Int? } /// One content hit as it appears in the project column; `index` is its position for the keyboard. public struct HitRow: Equatable, Identifiable { public var path: String public var hit: ContentHit public var index: Int public var id: String { "\(path):\(hit.line)" } } public struct Group: Equatable, Identifiable { public var path: String /// Every hit ripgrep reported, for the count. public var hitCount: Int /// The hits drawn under the header. public var rows: [HitRow] public var id: String { path } } /// A file-type chip and how many results of that type the unfiltered set carries. public struct ExtensionChip: Equatable, Sendable { public var ext: String public var count: Int } /// Ranks file names for a query; injectable so a test can count the calls. public typealias FileRanker = (_ query: String, _ paths: [String], _ showHidden: Bool) -> [FileNameMatch] /// Hit lines shown per file; the header count still says how many there are. public static let shownHitsPerFile = 12 public private(set) var query: String public private(set) var column = Column.project public private(set) var projectSelection = 0 public private(set) var fileSelection = 0 public private(set) var inFileSelection = 0 /// nil shows every file type. public private(set) var extensionFilter: String? public private(set) var content: [ContentGroup] = [] public private(set) var allPaths: [String] = [] public var showHidden: Bool { didSet { guard showHidden != oldValue else { return } rankFileNames() recomputeContent() } } // Derived once per change, not per read: a view body reads these many times per render. public private(set) var inFileHits: [ContentHit] = [] public private(set) var groups: [Group] = [] public private(set) var hitRows: [HitRow] = [] public private(set) var totalHits = 0 /// Every file-name match after the type filter; the column draws the first `maxFileNameResults`. public private(set) var fileMatches: [FileNameMatch] = [] public private(set) var shownFileMatches: [FileNameMatch] = [] /// Chips for every type the unfiltered results carry; empty when there is only one. public private(set) var chips: [ExtensionChip] = [] @ObservationIgnored private var allFileMatches: [FileNameMatch] = [] @ObservationIgnored private var shownContent: [ContentGroup] = [] public let activePath: String? @ObservationIgnored private let activeText: String @ObservationIgnored private let search: SearchServicing @ObservationIgnored private let debounce: Duration @ObservationIgnored private let ranker: FileRanker @ObservationIgnored public private(set) var pendingSearch: Task? public init(search: SearchServicing, seed: String = "", activePath: String? = nil, activeText: String = "", showHidden: Bool = false, debounce: Duration = .milliseconds(SearchLimits.debounceMilliseconds), ranker: @escaping FileRanker = { Fuzzy.rankFileNames(query: $0, paths: $1, showHidden: $2) }) { self.search = search self.query = seed self.activePath = activePath self.activeText = activeText self.showHidden = showHidden self.debounce = debounce self.ranker = ranker findInFile() } /// Loads the file-name index and runs the seeded query. public func start() async { scheduleContentSearch() let paths = await search.listFiles(under: nil) allPaths = paths rankFileNames() recomputeContent() } public var term: String { query.trimmingCharacters(in: .whitespaces) } public var columns: [Column] { activePath == nil ? [.project, .files] : [.thisFile, .project, .files] } // MARK: Results public var extensionChips: [String] { chips.map(\.ext) } /// "0 here · 39 hits · 2 files"; the first part only when a file is open. public var summary: String { let files = fileMatches.count let here = activePath == nil ? "" : "\(inFileHits.count) here · " return here + "\(totalHits) hit\(totalHits == 1 ? "" : "s") · \(files) file\(files == 1 ? "" : "s")" } /// The hover text of a type chip. public nonisolated static func chipTooltip(count: Int, isChosen: Bool) -> String { "\(count) result\(count == 1 ? "" : "s") · " + (isChosen ? "click to show every type" : "click to show only this type") } /// The one sentence a column shows instead of results, or nil when it has results. public func emptyMessage(for column: Column) -> String? { switch column { case .thisFile: if term.isEmpty { return "Type to search this file." } return inFileHits.isEmpty ? "No matches in this file." : nil case .project: if term.count < SearchLimits.minContentQuery { return "Type at least two characters." } return groups.isEmpty ? "No content matches." : nil case .files: if term.isEmpty { return "Type to search file names." } return fileMatches.isEmpty ? "No file names match." : nil } } // MARK: Editing public func setQuery(_ value: String) { guard value != query else { return } let termChanged = value.trimmingCharacters(in: .whitespaces) != term query = value resetSelection() guard termChanged else { return } findInFile() rankFileNames() scheduleContentSearch() recomputeContent() } /// Clicking the chosen chip again shows every type. public func toggleExtension(_ ext: String) { extensionFilter = extensionFilter == ext ? nil : ext resetSelection() recomputeFiltered() } /// Debounced per keystroke; a newer keystroke cancels the older search and its result. private func scheduleContentSearch() { pendingSearch?.cancel() let term = self.term guard term.count >= SearchLimits.minContentQuery else { pendingSearch = nil content = [] return } let debounce = self.debounce let search = self.search pendingSearch = Task { [weak self] in do { try await Task.sleep(for: debounce) } catch { return } let groups = await search.searchContent(term) guard !Task.isCancelled, let self, self.term == term else { return } self.content = groups self.recomputeContent() } } private func findInFile() { guard activePath != nil, !term.isEmpty else { inFileHits = [] return } inFileHits = Array(InFileSearch.hits(query: term, in: activeText).prefix(SearchLimits.maxInFileResults)) } private func rankFileNames() { allFileMatches = term.isEmpty ? [] : ranker(term, allPaths, showHidden) } /// After the content, the hidden toggle or the ranking changed: chips, then the filtered lists. private func recomputeContent() { shownContent = showHidden ? content : content.filter { !PathUtils.isHidden($0.path) } let counts = InFileSearch.extensionCounts(paths: shownContent.map(\.path) + allFileMatches.map(\.path)) chips = counts.count > 1 ? counts.map { ExtensionChip(ext: $0.ext, count: $0.count) } : [] // A chosen type the new results no longer carry falls back to every type. if let extensionFilter, !chips.contains(where: { $0.ext == extensionFilter }) { self.extensionFilter = nil } recomputeFiltered() } private func recomputeFiltered() { let visible = extensionFilter.map { ext in shownContent.filter { FileType.ext($0.path) == ext } } ?? shownContent var index = 0 groups = visible.map { group in let rows = group.hits.prefix(Self.shownHitsPerFile).map { hit -> HitRow in defer { index += 1 } return HitRow(path: group.path, hit: hit, index: index) } return Group(path: group.path, hitCount: group.hits.count, rows: rows) } hitRows = groups.flatMap(\.rows) totalHits = groups.reduce(0) { $0 + $1.hitCount } fileMatches = extensionFilter.map { ext in allFileMatches.filter { FileType.ext($0.path) == ext } } ?? allFileMatches shownFileMatches = Array(fileMatches.prefix(SearchLimits.maxFileNameResults)) } private func resetSelection() { projectSelection = 0 fileSelection = 0 inFileSelection = 0 } // MARK: Keyboard /// ⌘← / ⌘→: stops at the ends. public func moveColumn(by step: Int) { let list = columns let index = list.firstIndex(of: column) ?? 0 column = list[min(max(index + step, 0), list.count - 1)] } /// ↑↓ and ⌘↑⌘↓ inside the focused column. public func moveRow(by step: Int) { switch column { case .thisFile: inFileSelection = clamp(inFileSelection + step, count: inFileHits.count) case .project: projectSelection = clamp(projectSelection + step, count: hitRows.count) case .files: fileSelection = clamp(fileSelection + step, count: shownFileMatches.count) } } /// Hover: the pointer moves the focus and the row together. public func select(_ column: Column, row: Int) { self.column = column switch column { case .thisFile: inFileSelection = row case .project: projectSelection = row case .files: fileSelection = row } } public func selection(in column: Column) -> Int { switch column { case .thisFile: inFileSelection case .project: projectSelection case .files: fileSelection } } /// ↵: the selected row, falling back to the other result kind when the column is empty. public func target() -> Target? { let hits = hitRows let files = shownFileMatches switch column { case .thisFile: guard let activePath, inFileHits.indices.contains(inFileSelection) else { return nil } return Target(path: activePath, line: inFileHits[inFileSelection].line) case .files: if files.indices.contains(fileSelection) { return Target(path: files[fileSelection].path, line: nil) } if hits.indices.contains(projectSelection) { return Target(path: hits[projectSelection].path, line: hits[projectSelection].hit.line) } return nil case .project: if hits.indices.contains(projectSelection) { return Target(path: hits[projectSelection].path, line: hits[projectSelection].hit.line) } return files.first.map { Target(path: $0.path, line: nil) } } } private func clamp(_ value: Int, count: Int) -> Int { max(0, min(value, count - 1)) } // MARK: Layout /// Fixed column widths that never follow the focus: 30 · 45 · 25 with this file, else 65 · 35. public static func widths(total: CGFloat, columns: [Column]) -> [Column: CGFloat] { var widths: [Column: CGFloat] = [:] if columns.contains(.thisFile) { widths[.thisFile] = (total * 0.30).rounded() widths[.files] = (total * 0.25).rounded() } else { widths[.files] = (total * 0.35).rounded() } widths[.project] = max(0, total - widths.values.reduce(0, +)) return widths } }