yattee/Shared/Search/SearchSuggestions.swift

112 lines
3.6 KiB
Swift
Raw Normal View History

2021-11-28 14:37:55 +00:00
import SwiftUI
struct SearchSuggestions: View {
@EnvironmentObject<NavigationModel> private var navigation
2021-11-28 14:37:55 +00:00
@EnvironmentObject<RecentsModel> private var recents
@EnvironmentObject<SearchModel> private var state
var body: some View {
List {
Button {
runQueryAction()
2021-11-28 14:37:55 +00:00
} label: {
2021-12-06 18:12:33 +00:00
HStack {
Image(systemName: "magnifyingglass")
Text(state.queryText)
2021-11-28 14:37:55 +00:00
.lineLimit(1)
}
}
.padding(.vertical, 5)
2021-11-28 14:37:55 +00:00
#if os(macOS)
.onHover(perform: onHover(_:))
2021-11-28 14:37:55 +00:00
#endif
ForEach(visibleSuggestions, id: \.self) { suggestion in
HStack {
Button {
state.queryText = suggestion
runQueryAction()
} label: {
HStack {
Image(systemName: "magnifyingglass")
HStack(spacing: 0) {
2022-01-09 14:47:48 +00:00
if suggestion.hasPrefix(state.suggestionsText.lowercased()) {
Text(state.suggestionsText.lowercased())
2022-01-09 15:05:05 +00:00
.lineLimit(1)
.layoutPriority(2)
.foregroundColor(.secondary)
2022-01-09 14:47:48 +00:00
}
2021-11-28 14:37:55 +00:00
Text(querySuffix(suggestion))
.lineLimit(1)
.layoutPriority(1)
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 {
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
}
}
.id(UUID())
2021-11-28 14:37:55 +00:00
#if os(macOS)
.buttonStyle(.link)
2021-11-28 14:37:55 +00:00
#endif
}
private func runQueryAction() {
state.changeQuery { query in
query.query = state.queryText
state.fieldIsFocused = false
2022-03-26 14:22:29 +00:00
navigation.hideKeyboard()
}
recents.addQuery(state.queryText, navigation: navigation)
}
2021-11-28 14:37:55 +00:00
private var visibleSuggestions: [String] {
state.querySuggestions.collection.filter {
$0.compare(state.queryText, options: .caseInsensitive) != .orderedSame
}
}
private func querySuffix(_ suggestion: String) -> String {
2021-12-06 18:12:33 +00:00
suggestion.replacingFirstOccurrence(of: state.suggestionsText.lowercased(), with: "")
2021-11-28 14:37:55 +00:00
}
#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()
}
}