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