mirror of
https://github.com/Novaloop-AG/element-x-ios.git
synced 2026-11-03 16:10:20 +00:00
Update the template screen to use the new(ish) Observation framework. (#4077)
* Update the template screen to use the new(ish) Observation framework. * Add a variant of deferFulfillment that supports observables. * Update snapshot fulfilment to work with either a publisher or a stream.
This commit is contained in:
@@ -9,4 +9,19 @@ extension AsyncSequence {
|
||||
func first() async rethrows -> Self.Element? {
|
||||
try await first { _ in true }
|
||||
}
|
||||
|
||||
/// Type-erases the sequence into a newly constructed asynchronous stream. This is useful until
|
||||
/// we drop support for iOS 17, at which point we can replace this with `any AsyncSequence`.
|
||||
@available(iOS, deprecated: 18.0, message: "Use `any AsyncSequence` instead.")
|
||||
func eraseToStream() -> AsyncStream<Element> {
|
||||
var asyncIterator = makeAsyncIterator()
|
||||
return AsyncStream<Element> {
|
||||
do {
|
||||
return try await asyncIterator.next()
|
||||
} catch {
|
||||
MXLog.warning("Stopping stream: \(error)")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// Copyright 2025 New Vector Ltd.
|
||||
//
|
||||
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
|
||||
// Please see LICENSE files in the repository root for full details.
|
||||
//
|
||||
|
||||
import Foundation
|
||||
|
||||
extension Observable {
|
||||
/// Creates an async stream for the specified property on this object. We probably won't need this once SE-0475 is available:
|
||||
/// https://github.com/swiftlang/swift-evolution/blob/main/proposals/0475-observed.md
|
||||
///
|
||||
/// - Parameter property: The key path to the property you would like to observe.
|
||||
func observe<Value>(_ property: KeyPath<Self, Value>) -> AsyncStream<Value> {
|
||||
AsyncStream { continuation in
|
||||
var isActive = true
|
||||
|
||||
@Sendable func observe() {
|
||||
let value = withObservationTracking {
|
||||
self[keyPath: property]
|
||||
} onChange: {
|
||||
// Dispatch the update as this is willSet not didSet.
|
||||
DispatchQueue.main.async {
|
||||
guard isActive else { return }
|
||||
observe()
|
||||
}
|
||||
}
|
||||
continuation.yield(value)
|
||||
}
|
||||
|
||||
continuation.onTermination = { _ in isActive = false }
|
||||
|
||||
observe()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,21 +24,26 @@ struct SnapshotPerceptualPrecisionPreferenceKey: PreferenceKey {
|
||||
}
|
||||
}
|
||||
|
||||
struct FulfillmentPublisherEquatableWrapper: Equatable {
|
||||
let publisher: AnyPublisher<Bool, Never>?
|
||||
|
||||
// Publisher equatability complicates things but, luckily, we're only interesting in them changing from nil
|
||||
static func == (lhs: FulfillmentPublisherEquatableWrapper, rhs: FulfillmentPublisherEquatableWrapper) -> Bool {
|
||||
lhs.publisher != nil && rhs.publisher != nil
|
||||
}
|
||||
}
|
||||
struct SnapshotFulfillmentPreferenceKey: PreferenceKey {
|
||||
static var defaultValue: Wrapper?
|
||||
|
||||
struct SnapshotFulfillmentPublisherPreferenceKey: PreferenceKey {
|
||||
static var defaultValue: FulfillmentPublisherEquatableWrapper?
|
||||
|
||||
static func reduce(value: inout FulfillmentPublisherEquatableWrapper?, nextValue: () -> FulfillmentPublisherEquatableWrapper?) {
|
||||
static func reduce(value: inout Wrapper?, nextValue: () -> Wrapper?) {
|
||||
value = nextValue()
|
||||
}
|
||||
|
||||
enum Source {
|
||||
case publisher(AnyPublisher<Bool, Never>)
|
||||
case stream(AsyncStream<Bool>)
|
||||
}
|
||||
|
||||
struct Wrapper: Equatable {
|
||||
let id = UUID()
|
||||
let source: Source
|
||||
|
||||
static func == (lhs: Wrapper, rhs: Wrapper) -> Bool {
|
||||
lhs.id == rhs.id // Not ideal, but it's good enough for snapshots.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension SwiftUI.View {
|
||||
@@ -47,7 +52,7 @@ extension SwiftUI.View {
|
||||
/// These preferences can then be retrieved and used elsewhere in your view hierarchy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - delay: The delay time in seconds that you want to set as a preference to the View.
|
||||
/// - expect: A publisher that indicates when the preview is ready for snapshotting.
|
||||
/// - precision: The percentage of pixels that must match.
|
||||
/// - perceptualPrecision: The percentage a pixel must match the source pixel to be considered a match. 98-99% mimics the precision of the human eye.
|
||||
func snapshotPreferences(expect fulfillmentPublisher: (any Publisher<Bool, Never>)? = nil,
|
||||
@@ -55,6 +60,22 @@ extension SwiftUI.View {
|
||||
perceptualPrecision: Float = 0.98) -> some SwiftUI.View {
|
||||
preference(key: SnapshotPrecisionPreferenceKey.self, value: precision)
|
||||
.preference(key: SnapshotPerceptualPrecisionPreferenceKey.self, value: perceptualPrecision)
|
||||
.preference(key: SnapshotFulfillmentPublisherPreferenceKey.self, value: FulfillmentPublisherEquatableWrapper(publisher: fulfillmentPublisher?.eraseToAnyPublisher()))
|
||||
.preference(key: SnapshotFulfillmentPreferenceKey.self, value: fulfillmentPublisher.map { SnapshotFulfillmentPreferenceKey.Wrapper(source: .publisher($0.eraseToAnyPublisher())) })
|
||||
}
|
||||
|
||||
/// Use this modifier when you want to apply snapshot-specific preferences,
|
||||
/// like delay and precision, to the view.
|
||||
/// These preferences can then be retrieved and used elsewhere in your view hierarchy.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - expect: A stream that indicates when the preview is ready for snapshotting.
|
||||
/// - precision: The percentage of pixels that must match.
|
||||
/// - perceptualPrecision: The percentage a pixel must match the source pixel to be considered a match. 98-99% mimics the precision of the human eye.
|
||||
func snapshotPreferences(expect fulfillmentStream: AsyncStream<Bool>? = nil,
|
||||
precision: Float = 1.0,
|
||||
perceptualPrecision: Float = 0.98) -> some SwiftUI.View {
|
||||
preference(key: SnapshotPrecisionPreferenceKey.self, value: precision)
|
||||
.preference(key: SnapshotPerceptualPrecisionPreferenceKey.self, value: perceptualPrecision)
|
||||
.preference(key: SnapshotFulfillmentPreferenceKey.self, value: fulfillmentStream.map { SnapshotFulfillmentPreferenceKey.Wrapper(source: .stream($0)) })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,6 +48,39 @@ extension XCTestCase {
|
||||
}
|
||||
}
|
||||
|
||||
/// XCTest utility that assists in observing an async stream, deferring the fulfilment and results until some condition has been met.
|
||||
/// - Parameters:
|
||||
/// - asyncStream: The stream to wait on.
|
||||
/// - timeout: A timeout after which we give up.
|
||||
/// - message: An optional custom expectation message
|
||||
/// - until: callback that evaluates outputs until some condition is reached
|
||||
/// - Returns: The deferred fulfilment to be executed after some actions and that returns the result of the publisher.
|
||||
func deferFulfillment<Value>(_ asyncStream: AsyncStream<Value>,
|
||||
timeout: TimeInterval = 10,
|
||||
message: String? = nil,
|
||||
until condition: @escaping (Value) -> Bool) -> DeferredFulfillment<Value> {
|
||||
var result: Result<Value, Error>?
|
||||
let expectation = expectation(description: message ?? "Awaiting stream")
|
||||
var hasFulfilled = false
|
||||
|
||||
let task = Task {
|
||||
for await value in asyncStream {
|
||||
if condition(value), !hasFulfilled {
|
||||
result = .success(value)
|
||||
expectation.fulfill()
|
||||
hasFulfilled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return DeferredFulfillment<Value> {
|
||||
await self.fulfillment(of: [expectation], timeout: timeout)
|
||||
task.cancel()
|
||||
let unwrappedResult = try XCTUnwrap(result, "Awaited stream did not produce any output")
|
||||
return try unwrappedResult.get()
|
||||
}
|
||||
}
|
||||
|
||||
/// XCTest utility that assists in subscribing to a publisher and deferring the fulfilment and results until some other actions have been performed.
|
||||
/// - Parameters:
|
||||
/// - publisher: The publisher to wait on.
|
||||
|
||||
Reference in New Issue
Block a user