This commit is contained in:
Yao
2024-12-20 17:49:45 +08:00
parent 86b0363ce1
commit 654d456c7d
7011 changed files with 1705926 additions and 7 deletions

View File

@@ -0,0 +1,206 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SwiftUI
#if SWIFT_PACKAGE
@_exported import FirebaseFirestoreInternalWrapper
#else
@_exported import FirebaseFirestoreInternal
#endif // SWIFT_PACKAGE
/// The strategy to use when an error occurs during mapping Firestore documents
/// to the target type of `FirestoreQuery`.
///
public enum DecodingFailureStrategy {
/// Ignore any errors that occur when mapping Firestore documents.
case ignore
/// Raise an error when mapping a Firestore document fails.
case raise
}
/// A property wrapper that listens to a Firestore collection.
///
/// In the following example, `FirestoreQuery` will fetch all documents from the
/// `fruits` collection, filtering only documents whose `isFavourite` attribute
/// is equal to `true`, map members of result set to the `Fruit` type, and make
/// them available via the wrapped value `fruits`.
///
/// struct ContentView: View {
/// @FirestoreQuery(
/// collectionPath: "fruits",
/// predicates: [.whereField("isFavourite", isEqualTo: true)]
/// ) var fruits: [Fruit]
///
/// var body: some View {
/// List(fruits) { fruit in
/// Text(fruit.name)
/// }
/// }
/// }
///
/// `FirestoreQuery` also supports returning a `Result` type. The `.success` case
/// returns an array of elements, whereas the `.failure` case returns an error
/// in case mapping the Firestore docments wasn't successful:
///
/// struct ContentView: View {
/// @FirestoreQuery(
/// collectionPath: "fruits",
/// predicates: [.whereField("isFavourite", isEqualTo: true)]
/// ) var fruitResults: Result<[Fruit], Error>
///
/// var body: some View {
/// if case let .success(fruits) = fruitResults {
/// List(fruits) { fruit in
/// Text(fruit.name)
/// }
/// } else if case let .failure(error) = fruitResults {
/// Text("Couldn't map data: \(error.localizedDescription)")
/// }
/// }
///
/// Alternatively, the _projected value_ of the property wrapper provides access to
/// the `error` as well. This allows you to display a list of all successfully mapped
/// documents, as well as an error message with details about the documents that couldn't
/// be mapped successfully (e.g. because of a field name mismatch).
///
/// struct ContentView: View {
/// @FirestoreQuery(
/// collectionPath: "mappingFailure",
/// decodingFailureStrategy: .ignore
/// ) private var fruits: [Fruit]
///
/// var body: some View {
/// VStack(alignment: .leading) {
/// List(fruits) { fruit in
/// Text(fruit.name)
/// }
/// if $fruits.error != nil {
/// HStack {
/// Text("There was an error")
/// .foregroundColor(Color(UIColor.systemBackground))
/// Spacer()
/// }
/// .padding(30)
/// .background(Color.red)
/// }
/// }
/// }
/// }
///
/// Internally, `@FirestoreQuery` sets up a snapshot listener and publishes
/// any incoming changes via an `@StateObject`.
///
/// The projected value of this property wrapper provides access to a
/// configuration object of type `FirestoreQueryConfiguration` which can be used
/// to modify the query criteria. Changing the filter predicates results in the
/// underlying snapshot listener being unregistered and a new one registered.
///
/// Button("Show only Apples and Oranges") {
/// $fruits.predicates = [.whereField("name", isIn: ["Apple", "Orange]]
/// }
///
/// This property wrapper does not support updating the `wrappedValue`, i.e.
/// you need to use Firestore's other APIs to add, delete, or modify documents.
@available(iOS 14.0, macOS 11.0, macCatalyst 14.0, tvOS 14.0, watchOS 7.0, *)
@propertyWrapper
public struct FirestoreQuery<T>: DynamicProperty {
@StateObject private var firestoreQueryObservable: FirestoreQueryObservable<T>
/// The query's configurable properties.
public struct Configuration {
/// The query's collection path.
public var path: String
/// The query's predicates.
public var predicates: [QueryPredicate]
/// The strategy to use in case there was a problem during the decoding phase.
public var decodingFailureStrategy: DecodingFailureStrategy = .raise
/// If any errors occurred, they will be exposed here as well.
public var error: Error?
/// The type of animation to apply when updating the view. If this is ommitted then no
/// animations are fired.
public var animation: Animation?
}
/// The results of the query.
///
/// This property returns an empty collection when there are no matching results.
public var wrappedValue: T {
firestoreQueryObservable.items
}
/// A binding to the request's mutable configuration properties
public var projectedValue: Configuration {
get {
firestoreQueryObservable.configuration
}
nonmutating set {
firestoreQueryObservable.objectWillChange.send()
firestoreQueryObservable.configuration = newValue
}
}
/// Creates an instance by defining a query based on the parameters.
/// - Parameters:
/// - collectionPath: The path to the Firestore collection to query.
/// - predicates: An optional array of `QueryPredicate`s that defines a
/// filter for the fetched results.
/// - decodingFailureStrategy: The strategy to use when there is a failure
/// during the decoding phase. Defaults to `DecodingFailureStrategy.raise`.
/// - animation: The optional animation to apply to the transaction.
public init<U: Decodable>(collectionPath: String, predicates: [QueryPredicate] = [],
decodingFailureStrategy: DecodingFailureStrategy = .raise,
animation: Animation? = nil)
where T == [U] {
let configuration = Configuration(
path: collectionPath,
predicates: predicates,
decodingFailureStrategy: decodingFailureStrategy,
animation: animation
)
_firestoreQueryObservable =
StateObject(wrappedValue: FirestoreQueryObservable<T>(configuration: configuration))
}
/// Creates an instance by defining a query based on the parameters.
/// - Parameters:
/// - collectionPath: The path to the Firestore collection to query.
/// - predicates: An optional array of `QueryPredicate`s that defines a
/// filter for the fetched results.
/// - decodingFailureStrategy: The strategy to use when there is a failure
/// during the decoding phase. Defaults to `DecodingFailureStrategy.raise`.
/// - animation: The optional animation to apply to the transaction.
public init<U: Decodable>(collectionPath: String, predicates: [QueryPredicate] = [],
decodingFailureStrategy: DecodingFailureStrategy = .raise,
animation: Animation? = nil)
where T == Result<[U], Error> {
let configuration = Configuration(
path: collectionPath,
predicates: predicates,
decodingFailureStrategy: decodingFailureStrategy,
animation: animation
)
_firestoreQueryObservable =
StateObject(wrappedValue: FirestoreQueryObservable<T>(configuration: configuration))
}
}

View File

@@ -0,0 +1,221 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import SwiftUI
#if SWIFT_PACKAGE
@_exported import FirebaseFirestoreInternalWrapper
#else
@_exported import FirebaseFirestoreInternal
#endif // SWIFT_PACKAGE
@available(iOS 14.0, macOS 11.0, macCatalyst 14.0, tvOS 14.0, watchOS 7.0, *)
class FirestoreQueryObservable<T>: ObservableObject {
@Published var items: T
private let firestore = Firestore.firestore()
private var listener: ListenerRegistration?
private var setupListener: (() -> Void)!
var shouldUpdateListener = true
var configuration: FirestoreQuery<T>.Configuration {
didSet {
// prevent never-ending update cycle when updating the error field
guard shouldUpdateListener else { return }
removeListener()
setupListener()
}
}
init<U: Decodable>(configuration: FirestoreQuery<T>.Configuration) where T == [U] {
items = []
self.configuration = configuration
setupListener = createListener { [weak self] querySnapshot, error in
guard let self = self else { return }
if let error = error {
self.animated {
self.items = []
self.projectError(error)
}
return
} else {
self.animated {
self.projectError(nil)
}
}
guard let documents = querySnapshot?.documents else {
self.animated {
self.items = []
}
return
}
let decodedDocuments: [U] = documents.compactMap { queryDocumentSnapshot in
let result = Result { try queryDocumentSnapshot.data(as: U.self) }
switch result {
case let .success(decodedDocument):
return decodedDocument
case let .failure(error):
self.animated {
self.projectError(error)
}
return nil
}
}
if configuration.error != nil {
if configuration.decodingFailureStrategy == .raise {
self.animated {
self.items = []
}
} else {
self.animated {
self.items = decodedDocuments
}
}
} else {
self.animated {
self.items = decodedDocuments
}
}
}
setupListener()
}
init<U: Decodable>(configuration: FirestoreQuery<T>.Configuration) where T == Result<[U], Error> {
items = .success([])
self.configuration = configuration
setupListener = createListener { [weak self] querySnapshot, error in
guard let self = self else { return }
if let error = error {
self.animated {
self.items = .failure(error)
self.projectError(error)
}
return
} else {
self.animated {
self.projectError(nil)
}
}
guard let documents = querySnapshot?.documents else {
self.animated {
self.items = .success([])
}
return
}
let decodedDocuments: [U] = documents.compactMap { queryDocumentSnapshot in
let result = Result { try queryDocumentSnapshot.data(as: U.self) }
switch result {
case let .success(decodedDocument):
return decodedDocument
case let .failure(error):
self.animated {
self.projectError(error)
}
return nil
}
}
if let error = self.configuration.error {
if configuration.decodingFailureStrategy == .raise {
self.animated {
self.items = .failure(error)
}
} else {
self.animated {
self.items = .success(decodedDocuments)
}
}
} else {
self.animated {
self.items = .success(decodedDocuments)
}
}
}
setupListener()
}
deinit {
removeListener()
}
private func createListener(with handler: @escaping (QuerySnapshot?, Error?) -> Void)
-> () -> Void {
return {
var query: Query = self.firestore.collection(self.configuration.path)
for predicate in self.configuration.predicates {
switch predicate {
case let .isEqualTo(field, value):
query = query.whereField(field, isEqualTo: value)
case let .isIn(field, values):
query = query.whereField(field, in: values)
case let .isNotIn(field, values):
query = query.whereField(field, notIn: values)
case let .arrayContains(field, value):
query = query.whereField(field, arrayContains: value)
case let .arrayContainsAny(field, values):
query = query.whereField(field, arrayContainsAny: values)
case let .isLessThan(field, value):
query = query.whereField(field, isLessThan: value)
case let .isGreaterThan(field, value):
query = query.whereField(field, isGreaterThan: value)
case let .isLessThanOrEqualTo(field, value):
query = query.whereField(field, isLessThanOrEqualTo: value)
case let .isGreaterThanOrEqualTo(field, value):
query = query.whereField(field, isGreaterThanOrEqualTo: value)
case let .orderBy(field, value):
query = query.order(by: field, descending: value)
case let .limitTo(field):
query = query.limit(to: field)
case let .limitToLast(field):
query = query.limit(toLast: field)
}
}
self.listener = query.addSnapshotListener(handler)
}
}
private func projectError(_ error: Error?) {
shouldUpdateListener = false
configuration.error = error
shouldUpdateListener = true
}
private func removeListener() {
listener?.remove()
listener = nil
}
private func animated(_ body: () -> Void) {
if let animation = configuration.animation {
withAnimation(animation) {
body()
}
} else {
body()
}
}
}

View File

@@ -0,0 +1,142 @@
/*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#if SWIFT_PACKAGE
@_exported import FirebaseFirestoreInternalWrapper
#else
@_exported import FirebaseFirestoreInternal
#endif // SWIFT_PACKAGE
/// Query predicates that can be used to filter results fetched by `FirestoreQuery`.
///
/// Construct predicates using one of the following ways:
///
/// let onlyFavourites: QueryPredicate = .whereField("isFavourite", isEqualTo: true)
/// let onlyFavourites2: QueryPredicate = .isEqualTo("isFavourite", true)
/// let onlyFavourites3: QueryPredicate = .where("isFavourite", isEqualTo: true)
public enum QueryPredicate {
case isEqualTo(_ field: String, _ value: Any)
case isIn(_ field: String, _ values: [Any])
case isNotIn(_ field: String, _ values: [Any])
case arrayContains(_ field: String, _ value: Any)
case arrayContainsAny(_ field: String, _ values: [Any])
case isLessThan(_ field: String, _ value: Any)
case isGreaterThan(_ field: String, _ value: Any)
case isLessThanOrEqualTo(_ field: String, _ value: Any)
case isGreaterThanOrEqualTo(_ field: String, _ value: Any)
case orderBy(_ field: String, _ value: Bool)
case limitTo(_ value: Int)
case limitToLast(_ value: Int)
/*
Factory methods
*/
public static func whereField(_ field: String, isEqualTo value: Any) -> QueryPredicate {
.isEqualTo(field, value)
}
public static func whereField(_ field: String, isIn values: [Any]) -> QueryPredicate {
.isIn(field, values)
}
public static func whereField(_ field: String, isNotIn values: [Any]) -> QueryPredicate {
.isNotIn(field, values)
}
public static func whereField(_ field: String, arrayContains value: Any) -> QueryPredicate {
.arrayContains(field, value)
}
public static func whereField(_ field: String,
arrayContainsAny values: [Any]) -> QueryPredicate {
.arrayContainsAny(field, values)
}
public static func whereField(_ field: String, isLessThan value: Any) -> QueryPredicate {
.isLessThan(field, value)
}
public static func whereField(_ field: String, isGreaterThan value: Any) -> QueryPredicate {
.isGreaterThan(field, value)
}
public static func whereField(_ field: String,
isLessThanOrEqualTo value: Any) -> QueryPredicate {
.isLessThanOrEqualTo(field, value)
}
public static func whereField(_ field: String,
isGreaterThanOrEqualTo value: Any) -> QueryPredicate {
.isGreaterThanOrEqualTo(field, value)
}
public static func order(by field: String, descending value: Bool = false) -> QueryPredicate {
.orderBy(field, value)
}
public static func limit(to value: Int) -> QueryPredicate {
.limitTo(value)
}
public static func limit(toLast value: Int) -> QueryPredicate {
.limitToLast(value)
}
// Alternate naming
public static func `where`(_ name: String, isEqualTo value: Any) -> QueryPredicate {
.isEqualTo(name, value)
}
public static func `where`(_ name: String, isIn values: [Any]) -> QueryPredicate {
.isIn(name, values)
}
public static func `where`(_ name: String, isNotIn values: [Any]) -> QueryPredicate {
.isNotIn(name, values)
}
public static func `where`(field name: String, arrayContains value: Any) -> QueryPredicate {
.arrayContains(name, value)
}
public static func `where`(_ name: String, arrayContainsAny values: [Any]) -> QueryPredicate {
.arrayContainsAny(name, values)
}
public static func `where`(_ name: String, isLessThan value: Any) -> QueryPredicate {
.isLessThan(name, value)
}
public static func `where`(_ name: String, isGreaterThan value: Any) -> QueryPredicate {
.isGreaterThan(name, value)
}
public static func `where`(_ name: String, isLessThanOrEqualTo value: Any) -> QueryPredicate {
.isLessThanOrEqualTo(name, value)
}
public static func `where`(_ name: String,
isGreaterThanOrEqualTo value: Any) -> QueryPredicate {
.isGreaterThanOrEqualTo(name, value)
}
}