yattee/Shared/Trending/TrendingCountry.swift

89 lines
2.6 KiB
Swift
Raw Normal View History

import SwiftUI
2021-08-19 22:38:31 +00:00
struct TrendingCountry: View {
2022-09-04 15:28:30 +00:00
static let prompt = "Country Name or Code".localized()
@Binding var selectedCountry: Country
2021-09-25 08:18:22 +00:00
@StateObject private var store = Store(Country.allCases)
@State private var query: String = ""
@State private var selection: Country?
2022-06-14 16:10:54 +00:00
@Environment(\.colorScheme) private var colorScheme
2021-11-28 14:37:55 +00:00
@Environment(\.presentationMode) private var presentationMode
var body: some View {
VStack {
2021-11-28 14:37:55 +00:00
#if !os(tvOS)
HStack {
if #available(iOS 15.0, macOS 12.0, *) {
TextField("Country", text: $query, prompt: Text(Self.prompt))
} else {
TextField(Self.prompt, text: $query)
}
Button("Done") { selectCountryAndDismiss() }
.keyboardShortcut(.defaultAction)
.keyboardShortcut(.cancelAction)
}
.padding([.horizontal, .top])
#endif
2021-11-28 14:37:55 +00:00
countriesList
}
#if os(tvOS)
2022-06-14 16:10:54 +00:00
.searchable(text: $query, placement: .automatic, prompt: Text(Self.prompt))
.background(Color.background(scheme: colorScheme))
#endif
}
var countriesList: some View {
2021-11-28 14:37:55 +00:00
let list = ScrollViewReader { _ in
List(store.collection, selection: $selection) { country in
#if os(macOS)
Text(country.name)
.tag(country)
.id(country)
#else
Button(country.name) { selectCountryAndDismiss(country) }
#endif
}
.onChange(of: query) { newQuery in
let results = Country.search(newQuery)
store.replace(results)
selection = results.first
}
}
2021-11-28 14:37:55 +00:00
return Group {
#if os(macOS)
if #available(macOS 12.0, *) {
list
.listStyle(.inset(alternatesRowBackgrounds: true))
} else {
list
}
2021-11-28 14:37:55 +00:00
#else
list
#endif
}
#if os(macOS)
2021-11-08 16:29:35 +00:00
.padding(.bottom, 5)
#endif
}
func selectCountryAndDismiss(_ country: Country? = nil) {
if let selected = country ?? selection {
selectedCountry = selected
}
2021-11-28 14:37:55 +00:00
presentationMode.wrappedValue.dismiss()
}
}
2021-08-19 22:38:31 +00:00
struct TrendingCountry_Previews: PreviewProvider {
static var previews: some View {
2021-08-19 22:38:31 +00:00
TrendingCountry(selectedCountry: .constant(.pl))
}
}