Sources/OrgstarMobile/SearchScreen.swift

design-themes-widgets
orgstar/Sources/OrgstarMobile/SearchScreen.swift history · blame · raw

59 lines · 2693 bytes

 1#if os(iOS)
 2import OrgApp
 3import OrgIndex
 4import SwiftUI
 5
 6/// Files by name and headings by their words, as ⌘P and ⇧⌘F find them on the Mac.
 7struct SearchScreen: View {
 8    let workspace: WorkspaceModel
 9    let session: DocumentSession
10    @State private var query = ""
11
12    var body: some View {
13        let trimmed = query.trimmingCharacters(in: .whitespaces)
14        List {
15            if !trimmed.isEmpty {
16                let files = FuzzyMatch.rank(trimmed, workspace.files.filter { $0.kind == .org }, limit: 8)
17                if !files.isEmpty {
18                    Section("Files") {
19                        ForEach(files) { file in
20                            NavigationLink(value: ReaderRoute.file(file.path)) {
21                                Label(file.relativePath, systemImage: "doc.text")
22                            }
23                        }
24                    }
25                }
26                let results = Perf.measure("search.headings") { Result { try workspace.search(trimmed, overlay: workspace.overlay(session.openDocuments)) } }
27                let headings = (try? results.get()) ?? []
28                Section("Notes") {
29                    if case .failure(let error) = results {
30                        Text(error.localizedDescription).foregroundStyle(.secondary)
31                    } else if headings.isEmpty {
32                        Text("No notes match").foregroundStyle(.secondary)
33                    }
34                    ForEach(headings, id: \.self) { location in
35                        NavigationLink(value: ReaderRoute.heading(location)) {
36                            VStack(alignment: .leading, spacing: 2) {
37                                Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(2)
38                                if let snippet = location.snippet {
39                                    Text(snippet.attributed).font(.subheadline).foregroundStyle(.secondary).lineLimit(3)
40                                }
41                                Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
42                            }
43                        }
44                    }
45                }
46            }
47        }
48        .overlay {
49            if trimmed.isEmpty {
50                ContentUnavailableView("Search notes", systemImage: "magnifyingglass", description: Text("File names and the words of headings and their text."))
51            }
52        }
53        .navigationTitle("Search")
54        .searchable(text: $query, placement: .navigationBarDrawer(displayMode: .always))
55        .autocorrectionDisabled()
56        .textInputAutocapitalization(.never)
57    }
58}
59#endif