yattee/Shared/Search/SearchSuggestions.swift

101 lines
3.1 KiB
Swift
Raw Permalink Normal View History

2021-11-28 14:37:55 +00:00
import SwiftUI
struct SearchSuggestions: View {
@ObservedObject private var state = SearchModel.shared
2021-11-28 14:37:55 +00:00
var body: some View {
List {
2022-08-17 15:34:25 +00:00
if !state.queryText.isEmpty {
Button {
runQueryAction(state.queryText)
} label: {
HStack {
Image(systemName: "magnifyingglass")
2023-09-24 09:14:11 +00:00
Text(state.queryText.trimmingCharacters(in: .whitespacesAndNewlines))
2022-08-17 15:34:25 +00:00
.lineLimit(1)
}
2021-11-28 14:37:55 +00:00
}
2022-08-17 15:34:25 +00:00
.padding(.vertical, 5)
2022-08-17 15:34:25 +00:00
#if os(macOS)
.onHover(perform: onHover(_:))
#endif
}
2021-11-28 14:37:55 +00:00
ForEach(visibleSuggestions, id: \.self) { suggestion in
HStack {
Button {
runQueryAction(suggestion)
} label: {
HStack {
Image(systemName: "magnifyingglass")
HStack(spacing: 0) {
2022-12-11 13:28:16 +00:00
Text(suggestion)
.lineLimit(1)
.layoutPriority(1)
2022-12-11 13:28:16 +00:00
.truncationMode(.head)
2022-01-04 22:34:09 +00:00
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
2021-12-06 18:12:33 +00:00
}
2021-11-28 14:37:55 +00:00
}
2022-01-04 22:34:09 +00:00
.frame(minWidth: 0, maxWidth: .infinity, alignment: .leading)
.buttonStyle(.plain)
Spacer()
Button {
2022-08-17 15:34:25 +00:00
state.queryText = suggestion
} label: {
Image(systemName: "arrow.up.left.circle")
.foregroundColor(.secondary)
}
.padding(.horizontal, 10)
.padding(.vertical, 5)
.buttonStyle(.plain)
2021-11-28 14:37:55 +00:00
}
#if os(macOS)
.onHover(perform: onHover(_:))
#endif
}
}
#if os(macOS)
2022-08-17 15:34:25 +00:00
.buttonStyle(.link)
2021-11-28 14:37:55 +00:00
#endif
}
private func runQueryAction(_ queryText: String) {
2022-08-17 15:34:25 +00:00
state.queryText = queryText
state.changeQuery { query in
query.query = queryText
NavigationModel.shared.hideKeyboard()
}
RecentsModel.shared.addQuery(queryText)
}
2021-11-28 14:37:55 +00:00
private var visibleSuggestions: [String] {
2022-08-17 15:34:25 +00:00
state.querySuggestions.filter {
2021-11-28 14:37:55 +00:00
$0.compare(state.queryText, options: .caseInsensitive) != .orderedSame
}
}
#if os(macOS)
private func onHover(_ inside: Bool) {
if inside {
NSCursor.pointingHand.push()
} else {
NSCursor.pop()
}
}
#endif
}
struct SearchSuggestions_Previews: PreviewProvider {
static var previews: some View {
SearchSuggestions()
.injectFixtureEnvironmentObjects()
}
}