Sources/Orgstar/SearchViews.swift
87 lines · 3557 bytes
1import AppKit
2import OrgApp
3import OrgIndex
4import OrgWorkspace
5import SwiftUI
6
7struct SearchResults: View {
8 let results: Result<[HeadingLocation], any Error>
9 let open: (HeadingLocation) -> Void
10
11 var body: some View {
12 let found = (try? results.get()) ?? []
13 List(found, id: \.self) { location in
14 Button {
15 open(location)
16 } label: {
17 VStack(alignment: .leading, spacing: 2) {
18 Text(location.title.isEmpty ? "(untitled)" : location.title).lineLimit(1)
19 if let snippet = location.snippet {
20 Text(snippet.attributed).font(.callout).foregroundStyle(.secondary).lineLimit(3)
21 }
22 Text((location.path as NSString).lastPathComponent).font(.caption).foregroundStyle(.tertiary)
23 }
24 }
25 .buttonStyle(.plain)
26 }
27 .overlay {
28 if case .failure(let error) = results {
29 ContentUnavailableView(error.localizedDescription, systemImage: "exclamationmark.triangle")
30 } else if found.isEmpty {
31 ContentUnavailableView.search
32 }
33 }
34 }
35}
36
37struct QuickOpenView: View {
38 let workspace: WorkspaceModel
39 let open: (FileEntry) -> Void
40 @State private var query = ""
41 /// The highlighted match, moved by ↑/↓ or C-p/C-n and opened by Return.
42 @State private var selected = 0
43 @Environment(\.dismiss) private var dismiss
44
45 var body: some View {
46 let matches = workspace.quickOpen(query)
47 let current = min(selected, matches.count - 1)
48 VStack(spacing: 0) {
49 TextField("Open file", text: $query)
50 .textFieldStyle(.plain)
51 .font(.title3)
52 .padding(12)
53 .onSubmit { if current >= 0 { open(matches[current]) } }
54 .onKeyPress(phases: .down) { press in
55 let control = press.modifiers == .control
56 let step = if press.key == .downArrow || control && press.characters == "n" { 1 }
57 else if press.key == .upArrow || control && press.characters == "p" { -1 } else { 0 }
58 guard step != 0 else { return .ignored }
59 selected = max(0, min(current + step, matches.count - 1))
60 return .handled
61 }
62 .onChange(of: query) { selected = 0 }
63 Divider()
64 ScrollViewReader { proxy in
65 List(matches.indices, id: \.self) { index in
66 let entry = matches[index]
67 Button {
68 open(entry)
69 } label: {
70 VStack(alignment: .leading, spacing: 2) {
71 Text(entry.name)
72 Text(entry.relativePath).font(.caption).foregroundStyle(.secondary)
73 }
74 .frame(maxWidth: .infinity, alignment: .leading)
75 .contentShape(Rectangle())
76 }
77 .buttonStyle(.plain)
78 .listRowBackground(index == current ? Color.accentColor.opacity(0.25) : Color.clear)
79 .accessibilityAddTraits(index == current ? .isSelected : [])
80 }
81 .onChange(of: current) { if current >= 0 { proxy.scrollTo(current) } }
82 }
83 }
84 .frame(width: 520, height: 360)
85 .onExitCommand { dismiss() }
86 }
87}