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