diff --git a/Sources/OpenSwiftUI/Modifier/ViewModifier/TaskModifier2.swift b/Sources/OpenSwiftUI/Modifier/ViewModifier/TaskModifier2.swift new file mode 100644 index 000000000..40199cdbf --- /dev/null +++ b/Sources/OpenSwiftUI/Modifier/ViewModifier/TaskModifier2.swift @@ -0,0 +1,240 @@ +// +// TaskModifier2.swift +// OpenSwiftUI +// +// Implemented from the public documentation of +// View.task(name:executorPreference:priority:_:). Unlike _TaskModifier it +// also carries a task name and a TaskExecutor preference, and the action is +// @isolated(any). +// +// The initialiser labels and parameter types follow the symbol names that +// SwiftUI-linked apps import; Tests/OpenSwiftUITests/Modifier/TaskModifier2Tests.swift +// lists the mangled names this must keep matching. + +import OpenAttributeGraphShims +@_spi(ForOpenSwiftUIOnly) +import OpenSwiftUICore + +@available(OpenSwiftUI_v7_0, *) +@frozen +public struct _TaskModifier2: ViewModifier { + public var name: String + + public var executorPreference: (any TaskExecutor)? + + public var priority: TaskPriority + + nonisolated(unsafe) public var action: @isolated(any) () async -> Void + + // nonisolated: inheriting ViewModifier's @preconcurrency @MainActor + // isolation drops `YA` (@isolated(any)) from the init's mangled name. + @inlinable + nonisolated public init( + name: String, + executorPreference: (any TaskExecutor)?, + priority: TaskPriority, + action: sending @escaping @isolated(any) () async -> Void + ) { + self.name = name + self.executorPreference = executorPreference + self.priority = priority + self.action = action + } + + nonisolated public static func _makeView( + modifier: _GraphValue, + inputs: _ViewInputs, + body: @escaping (_Graph, _ViewInputs) -> _ViewOutputs + ) -> _ViewOutputs { + Child.Value._makeView( + modifier: _GraphValue(Child(modifier: modifier.value)), + inputs: inputs, + body: body + ) + } + + nonisolated public static func _makeViewList( + modifier: _GraphValue, + inputs: _ViewListInputs, + body: @escaping (_Graph, _ViewListInputs) -> _ViewListOutputs + ) -> _ViewListOutputs { + Child.Value._makeViewList( + modifier: _GraphValue(Child(modifier: modifier.value)), + inputs: inputs, + body: body + ) + } + + nonisolated public static func _viewListCount( + inputs: _ViewListCountInputs, + body: (_ViewListCountInputs) -> Int? + ) -> Int? { + Child.Value._viewListCount( + inputs: inputs, + body: body + ) + } + + private struct Child: Rule, AsyncAttribute { + @Attribute + var modifier: _TaskModifier2 + + var value: InnerModifier { + InnerModifier(base: modifier) + } + } + + private struct InnerModifier: ViewModifier { + var base: _TaskModifier2 + + @State + private var task: Task? + + private func start() -> Task { + Task.detached( + name: base.name, + executorPreference: base.executorPreference, + priority: base.priority, + operation: base.action + ) + } + + func body(content: Content) -> some View { + content.modifier(_AppearanceActionModifier( + appear: { + guard task == nil else { return } + task = start() + }, + disappear: { + if let task { + task.cancel() + self.task = nil + } + } + )) + } + } +} + +@available(OpenSwiftUI_v7_0, *) +@frozen +public struct _TaskValueModifier2: ViewModifier where Value: Equatable { + nonisolated(unsafe) public var value: Value + + public var name: String + + public var executorPreference: (any TaskExecutor)? + + public var priority: TaskPriority + + nonisolated(unsafe) public var action: @isolated(any) () async -> Void + + // nonisolated: inheriting ViewModifier's @preconcurrency @MainActor + // isolation drops `YA` (@isolated(any)) from the init's mangled name. + @inlinable + nonisolated public init( + id value: Value, + name: String, + executorPreference: (any TaskExecutor)?, + priority: TaskPriority, + action: sending @escaping @isolated(any) () async -> Void + ) { + self.value = value + self.name = name + self.executorPreference = executorPreference + self.priority = priority + self.action = action + } + + nonisolated public static func _makeView( + modifier: _GraphValue, + inputs: _ViewInputs, + body: @escaping (_Graph, _ViewInputs) -> _ViewOutputs + ) -> _ViewOutputs { + Child.Value._makeView( + modifier: _GraphValue(Child(modifier: modifier.value)), + inputs: inputs, + body: body + ) + } + + nonisolated public static func _makeViewList( + modifier: _GraphValue, + inputs: _ViewListInputs, + body: @escaping (_Graph, _ViewListInputs) -> _ViewListOutputs + ) -> _ViewListOutputs { + Child.Value._makeViewList( + modifier: _GraphValue(Child(modifier: modifier.value)), + inputs: inputs, + body: body + ) + } + + nonisolated public static func _viewListCount( + inputs: _ViewListCountInputs, + body: (_ViewListCountInputs) -> Int? + ) -> Int? { + Child.Value._viewListCount( + inputs: inputs, + body: body + ) + } + + private struct Child: Rule, AsyncAttribute { + @Attribute + var modifier: _TaskValueModifier2 + + var value: InnerModifier { + InnerModifier(base: modifier) + } + } + + private struct InnerModifier: ViewModifier { + var base: _TaskValueModifier2 + + struct TaskState { + var task: Task + var value: Value + } + + @State + private var taskState: TaskState? + + private func start() -> TaskState { + TaskState( + task: Task.detached( + name: base.name, + executorPreference: base.executorPreference, + priority: base.priority, + operation: base.action + ), + value: base.value + ) + } + + func body(content: Content) -> some View { + content.modifier(_AppearanceActionModifier( + appear: { + guard taskState == nil else { return } + taskState = start() + }, + disappear: { + if let taskState { + taskState.task.cancel() + self.taskState = nil + } + } + )) + .onChange(of: base.value) { + guard let taskState, + taskState.value != base.value + else { return } + taskState.task.cancel() + self.taskState = start() + } + } + } +} + +@available(*, unavailable) +extension _TaskValueModifier2: Sendable {} diff --git a/Tests/OpenSwiftUICompatibilityTests/Modifier/ViewModifier/TaskModifier2LifecycleTests.swift b/Tests/OpenSwiftUICompatibilityTests/Modifier/ViewModifier/TaskModifier2LifecycleTests.swift new file mode 100644 index 000000000..db0a84086 --- /dev/null +++ b/Tests/OpenSwiftUICompatibilityTests/Modifier/ViewModifier/TaskModifier2LifecycleTests.swift @@ -0,0 +1,102 @@ +// +// TaskModifier2LifecycleTests.swift +// OpenSwiftUICompatibilityTests + +import OpenSwiftUITestsSupport +import Testing + +@MainActor +@available(OpenSwiftUI_v7_0, *) +struct TaskModifier2LifecycleTests { + @Test + func taskStartsOnAppear() async throws { + struct ContentView: View { + let confirmation: Confirmation + var continuation: UnsafeContinuation + + var body: some View { + Color.red.modifier(_TaskModifier2( + name: "start", + executorPreference: nil, + priority: .userInitiated, + action: { + confirmation() + continuation.resume() + } + )) + } + } + + try await triggerLayoutWithWindow { confirmation, continuation in + PlatformHostingController( + rootView: ContentView( + confirmation: confirmation, + continuation: continuation + ) + ) + } + } + + @Test + func taskCancelsAndRestartsOnIDChange() async throws { + // Resumes the continuation only after the id-0 task has observed + // cancellation and the id-1 task has started, so a missing cancel() + // hangs the test instead of passing it. + final class Gate: @unchecked Sendable { + private let lock = NSLock() + private var firstCancelled = false + private var secondStarted = false + func mark(firstCancelled f: Bool = false, secondStarted s: Bool = false, then resume: () -> Void) { + lock.lock() + firstCancelled = firstCancelled || f + secondStarted = secondStarted || s + let done = firstCancelled && secondStarted + lock.unlock() + if done { resume() } + } + } + + struct ContentView: View { + @State private var value = 0 + let gate = Gate() + let confirmation: Confirmation + var continuation: UnsafeContinuation + + var body: some View { + Color.red + .onAppear { + DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { + value += 1 + } + } + .modifier(_TaskValueModifier2( + id: value, + name: "restart", + executorPreference: nil, + priority: .userInitiated, + action: { [value, gate] in + confirmation() + if value == 0 { + // Stays alive until the id change cancels it. + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: 10_000_000) + } + gate.mark(firstCancelled: true) { continuation.resume() } + } else { + gate.mark(secondStarted: true) { continuation.resume() } + } + } + )) + } + } + + try await triggerLayoutWithWindow(expectedCount: 2) { confirmation, continuation in + PlatformHostingController( + rootView: ContentView( + confirmation: confirmation, + continuation: continuation + ) + ) + } + } +} diff --git a/Tests/OpenSwiftUITests/Modifier/TaskModifier2Tests.swift b/Tests/OpenSwiftUITests/Modifier/TaskModifier2Tests.swift new file mode 100644 index 000000000..747c448b8 --- /dev/null +++ b/Tests/OpenSwiftUITests/Modifier/TaskModifier2Tests.swift @@ -0,0 +1,58 @@ +// +// TaskModifier2Tests.swift +// OpenSwiftUITests + +import OpenSwiftUI +import Testing + +@MainActor +@Suite +@available(OpenSwiftUI_v7_0, *) +struct TaskModifier2Tests { + // ABI note: these must keep mangling to the symbols imported by + // SwiftUI-linked apps (module renamed to SwiftUI). The `n` in `yyYaYAcn` + // comes from `sending` (__owned in mangling); `YA` appears only because + // inits are `nonisolated` (dropped under inherited @MainActor @preconcurrency). + // Check built symbols with `nm`: + // $s7SwiftUI14_TaskModifier2V4name18executorPreference8priority6actionACSS_Sch_pSgScPyyYaYAcntcfC + // = _TaskModifier2.init(name: String, executorPreference: (any TaskExecutor)?, + // priority: TaskPriority, action: sending @isolated(any) () async -> ()) + // $s7SwiftUI19_TaskValueModifier2V2id4name18executorPreference8priority6actionACyxGx_SSSch_pSgScPyyYaYAcntcfC + // = _TaskValueModifier2.init(id: Value, name: ..., same trailing parameters) + // plus metadata accessor (Ma), nominal descriptor (Mn) and ViewModifier + // conformance descriptor (AA12ViewModifierAAMc) for both types. + + @Test + func taskModifierStoresParameters() { + let modifier = _TaskModifier2( + name: "load", + executorPreference: nil, + priority: .utility, + action: {} + ) + #expect(modifier.name == "load") + #expect(modifier.executorPreference == nil) + #expect(modifier.priority == .utility) + } + + @Test + func taskValueModifierStoresParameters() { + let modifier = _TaskValueModifier2( + id: 3, + name: "reload", + executorPreference: nil, + priority: .high, + action: {} + ) + #expect(modifier.value == 3) + #expect(modifier.name == "reload") + #expect(modifier.priority == .high) + } + + @Test + func conformsToViewModifier() { + func isViewModifier(_ type: T.Type) -> Bool { type is any ViewModifier.Type } + #expect(isViewModifier(_TaskModifier2.self)) + #expect(isViewModifier(_TaskValueModifier2.self)) + } +}