From 37e7adbef1bde09de869686b18a9eeee26fc81d3 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Tue, 13 Aug 2024 19:09:48 +0800 Subject: [PATCH 001/141] Initial commit --- Package.swift | 24 + .../Bindings/UIColorWell.swift | 30 ++ .../AppKitNavigation/Bindings/UIControl.swift | 107 ++++ .../Bindings/UIDatePicker.swift | 30 ++ .../Bindings/UIPageControl.swift | 28 ++ .../Bindings/UISegmentedControl.swift | 81 +++ .../AppKitNavigation/Bindings/UISlider.swift | 29 ++ .../AppKitNavigation/Bindings/UIStepper.swift | 29 ++ .../AppKitNavigation/Bindings/UISwitch.swift | 32 ++ .../Bindings/UITabBarController.swift | 65 +++ .../Bindings/UITextField.swift | 311 ++++++++++++ .../Extensions/UIColorWell.md | 8 + .../Extensions/UIControlProtocol.md | 8 + .../Extensions/UIDatePicker.md | 8 + .../Extensions/UIKitAnimation.md | 35 ++ .../Extensions/UIPageControl.md | 8 + .../Documentation.docc/Extensions/UISlider.md | 8 + .../Extensions/UIStepper.md | 8 + .../Documentation.docc/Extensions/UISwitch.md | 8 + .../Extensions/UITextField.md | 22 + .../Extensions/UIViewController.md | 26 + .../Documentation.docc/Extensions/observe.md | 7 + .../Documentation.docc/UIKitNavigation.md | 165 +++++++ .../Internal/AssumeIsolated.swift | 30 ++ .../Internal/ErrorMechanism.swift | 20 + .../AppKitNavigation/Internal/Exports.swift | 3 + .../Internal/ToOptionalUnit.swift | 12 + .../Navigation/Presentation.swift | 463 ++++++++++++++++++ .../Navigation/UIAlertController.swift | 87 ++++ Sources/AppKitNavigation/Observe.swift | 188 +++++++ .../SwiftUI/Representable.swift | 24 + Sources/AppKitNavigation/UIBinding.swift | 15 + Sources/AppKitNavigation/UIKitAnimation.swift | 144 ++++++ Sources/AppKitNavigation/UITransaction.swift | 53 ++ Sources/AppKitNavigationShim/include/shim.h | 19 + Sources/AppKitNavigationShim/shim.m | 106 ++++ 36 files changed, 2241 insertions(+) create mode 100644 Sources/AppKitNavigation/Bindings/UIColorWell.swift create mode 100644 Sources/AppKitNavigation/Bindings/UIControl.swift create mode 100644 Sources/AppKitNavigation/Bindings/UIDatePicker.swift create mode 100644 Sources/AppKitNavigation/Bindings/UIPageControl.swift create mode 100644 Sources/AppKitNavigation/Bindings/UISegmentedControl.swift create mode 100644 Sources/AppKitNavigation/Bindings/UISlider.swift create mode 100644 Sources/AppKitNavigation/Bindings/UIStepper.swift create mode 100644 Sources/AppKitNavigation/Bindings/UISwitch.swift create mode 100644 Sources/AppKitNavigation/Bindings/UITabBarController.swift create mode 100644 Sources/AppKitNavigation/Bindings/UITextField.swift create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIColorWell.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIControlProtocol.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIDatePicker.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIKitAnimation.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIPageControl.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UISlider.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIStepper.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UISwitch.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UITextField.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIViewController.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/observe.md create mode 100644 Sources/AppKitNavigation/Documentation.docc/UIKitNavigation.md create mode 100644 Sources/AppKitNavigation/Internal/AssumeIsolated.swift create mode 100644 Sources/AppKitNavigation/Internal/ErrorMechanism.swift create mode 100644 Sources/AppKitNavigation/Internal/Exports.swift create mode 100644 Sources/AppKitNavigation/Internal/ToOptionalUnit.swift create mode 100644 Sources/AppKitNavigation/Navigation/Presentation.swift create mode 100644 Sources/AppKitNavigation/Navigation/UIAlertController.swift create mode 100644 Sources/AppKitNavigation/Observe.swift create mode 100644 Sources/AppKitNavigation/SwiftUI/Representable.swift create mode 100644 Sources/AppKitNavigation/UIBinding.swift create mode 100644 Sources/AppKitNavigation/UIKitAnimation.swift create mode 100644 Sources/AppKitNavigation/UITransaction.swift create mode 100644 Sources/AppKitNavigationShim/include/shim.h create mode 100644 Sources/AppKitNavigationShim/shim.m diff --git a/Package.swift b/Package.swift index 46c1d7edbe..3bc91c28ee 100644 --- a/Package.swift +++ b/Package.swift @@ -23,6 +23,10 @@ let package = Package( name: "UIKitNavigation", targets: ["UIKitNavigation"] ), + .library( + name: "AppKitNavigation", + targets: ["AppKitNavigation"] + ), ], dependencies: [ .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -62,10 +66,18 @@ let package = Package( "SwiftUINavigation" ] ), + .target( + name: "CocoaNavigation", + dependencies: [ + "SwiftNavigation", + .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), + ] + ), .target( name: "UIKitNavigation", dependencies: [ "SwiftNavigation", + "CocoaNavigation", "UIKitNavigationShim", .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), ] @@ -73,6 +85,18 @@ let package = Package( .target( name: "UIKitNavigationShim" ), + .target( + name: "AppKitNavigation", + dependencies: [ + "SwiftNavigation", + "CocoaNavigation", + "AppKitNavigationShim", + .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), + ] + ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/Bindings/UIColorWell.swift b/Sources/AppKitNavigation/Bindings/UIColorWell.swift new file mode 100644 index 0000000000..96c0a12f16 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UIColorWell.swift @@ -0,0 +1,30 @@ +#if canImport(UIKit) && !os(tvOS) && !os(watchOS) + import UIKit + + @available(iOS 14, *) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + extension UIColorWell { + /// Creates a new color well with the specified frame and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - selectedColor: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init(frame: CGRect = .zero, selectedColor: UIBinding) { + self.init(frame: frame) + bind(selectedColor: selectedColor) + } + + /// Establishes a two-way connection between a binding and the color well's selected color. + /// + /// - Parameter selectedColor: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(selectedColor: UIBinding) -> ObservationToken { + bind(selectedColor, to: \.selectedColor, for: .valueChanged) + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UIControl.swift b/Sources/AppKitNavigation/Bindings/UIControl.swift new file mode 100644 index 0000000000..2854c166d0 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UIControl.swift @@ -0,0 +1,107 @@ +#if canImport(UIKit) && !os(watchOS) + import ConcurrencyExtras + @_spi(Internals) import SwiftNavigation + import UIKit + + /// A protocol used to extend `UIControl`. + @MainActor + public protocol UIControlProtocol: UIControl {} + + extension UIControl: UIControlProtocol {} + + @available(iOS 14, tvOS 14, *) + extension UIControlProtocol { + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: ReferenceWritableKeyPath, + for event: UIControl.Event + ) -> ObservationToken { + bind(binding, to: keyPath, for: event) { control, newValue, _ in + control[keyPath: keyPath] = newValue + } + } + + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - set: A closure that is called when the binding's value changes with a weakly-captured + /// control, a new value that can be used to configure the control, and a transaction, which + /// can be used to determine how and if the change should be animated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: KeyPath, + for event: UIControl.Event, + set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void + ) -> ObservationToken { + unbind(keyPath) + let action = UIAction { [weak self] _ in + guard let self else { return } + binding.wrappedValue = self[keyPath: keyPath] + } + addAction(action, for: event) + let isSetting = LockIsolated(false) + let token = observe { [weak self] transaction in + guard let self else { return } + isSetting.withValue { $0 = true } + defer { isSetting.withValue { $0 = false } } + set( + self, + binding.wrappedValue, + transaction.uiKit.animation == nil && !transaction.uiKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + @UncheckedSendable var uncheckedKeyPath = keyPath + let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in + guard isSetting.withValue({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + } + } + let observationToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + self?.removeAction(action, for: .allEvents) + } + token.cancel() + observation.invalidate() + } + observationTokens[keyPath] = observationToken + return observationToken + } + + public func unbind(_ keyPath: KeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } + + var observationTokens: [AnyKeyPath: ObservationToken] { + get { + objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] + ?? [:] + } + set { + objc_setAssociatedObject( + self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + } + + @MainActor + private let observationTokensKey = malloc(1)! +#endif diff --git a/Sources/AppKitNavigation/Bindings/UIDatePicker.swift b/Sources/AppKitNavigation/Bindings/UIDatePicker.swift new file mode 100644 index 0000000000..b4c02a007f --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UIDatePicker.swift @@ -0,0 +1,30 @@ +#if canImport(UIKit) && !os(tvOS) && !os(watchOS) + import UIKit + + @available(iOS 14, *) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + extension UIDatePicker { + /// Creates a new date picker with the specified frame and registers the binding against the + /// selected date. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected date, and write to when the selected + /// date changes. + public convenience init(frame: CGRect = .zero, date: UIBinding) { + self.init(frame: frame) + bind(date: date) + } + + /// Establishes a two-way connection between a binding and the date picker's selected date. + /// + /// - Parameter date: The binding to read from for the selected date, and write to when the + /// selected date changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(date: UIBinding) -> ObservationToken { + bind(date, to: \.date, for: .valueChanged) + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UIPageControl.swift b/Sources/AppKitNavigation/Bindings/UIPageControl.swift new file mode 100644 index 0000000000..626798fe36 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UIPageControl.swift @@ -0,0 +1,28 @@ +#if canImport(UIKit) && !os(watchOS) + import UIKit + + @available(iOS 14, tvOS 14, *) + extension UIPageControl { + /// Creates a new page control with the specified frame and registers the binding against the + /// current page. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - currentPage: The binding to read from for the current page, and write to when the + /// current page changes. + public convenience init(frame: CGRect = .zero, currentPage: UIBinding) { + self.init(frame: frame) + bind(currentPage: currentPage) + } + + /// Establishes a two-way connection between a binding and the page control's current page. + /// + /// - Parameter currentPage: The binding to read from for the current page, and write to when + /// the current page changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(currentPage: UIBinding) -> ObservationToken { + bind(currentPage, to: \.currentPage, for: .valueChanged) + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UISegmentedControl.swift b/Sources/AppKitNavigation/Bindings/UISegmentedControl.swift new file mode 100644 index 0000000000..5c2c9a86a6 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UISegmentedControl.swift @@ -0,0 +1,81 @@ +#if canImport(UIKit) && !os(watchOS) + import IssueReporting + import UIKit + + @available(iOS 14, tvOS 14, *) + extension UISegmentedControl { + /// Creates a new color well with the specified frame and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - selectedSegment: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init( + frame: CGRect = .zero, selectedSegment: UIBinding>, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + self.init(frame: frame) + bind( + selectedSegment: selectedSegment, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Establishes a two-way connection between a binding and the color well's selected color. + /// + /// - Parameter selectedSegment: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selectedSegment: UIBinding>, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObservationToken { + let fileID = HashableStaticString(rawValue: fileID) + let filePath = HashableStaticString(rawValue: filePath) + return bind( + selectedSegment[fileID: fileID, filePath: filePath, line: line, column: column], + to: \.selectedSegmentIndex, + for: .valueChanged + ) + } + } + + extension RawRepresentable { + fileprivate subscript( + fileID fileID: HashableStaticString, + filePath filePath: HashableStaticString, + line line: UInt, + column column: UInt + ) -> Int { + get { rawValue } + set { + guard let rawRepresentable = Self(rawValue: newValue) + else { + reportIssue( + """ + Raw-representable 'UIBinding<\(Self.self)>' attempted to write an invalid raw value \ + ('\(newValue)'). + """, + fileID: fileID.rawValue, + filePath: filePath.rawValue, + line: line, + column: column + ) + return + } + self = rawRepresentable + } + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UISlider.swift b/Sources/AppKitNavigation/Bindings/UISlider.swift new file mode 100644 index 0000000000..f2fd9a2f61 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UISlider.swift @@ -0,0 +1,29 @@ +#if canImport(UIKit) && !os(tvOS) && !os(watchOS) + import UIKit + + @available(iOS 14, *) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + extension UISlider { + /// Creates a new slider with the specified frame and registers the binding against the value. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - value: The binding to read from for the current value, and write to when the value + /// changes. + public convenience init(frame: CGRect = .zero, value: UIBinding) { + self.init(frame: frame) + bind(value: value) + } + + /// Establishes a two-way connection between a binding and the slider's current value. + /// + /// - Parameter value: The binding to read from for the current value, and write to when the + /// value changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(value: UIBinding) -> ObservationToken { + bind(value, to: \.value, for: .valueChanged) + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UIStepper.swift b/Sources/AppKitNavigation/Bindings/UIStepper.swift new file mode 100644 index 0000000000..d3e664e9d2 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UIStepper.swift @@ -0,0 +1,29 @@ +#if canImport(UIKit) && !os(tvOS) && !os(watchOS) + import UIKit + + @available(iOS 14, *) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + extension UIStepper { + /// Creates a new stepper with the specified frame and registers the binding against the value. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - value: The binding to read from for the current value, and write to when the value + /// changes. + public convenience init(frame: CGRect = .zero, value: UIBinding) { + self.init(frame: frame) + bind(value: value) + } + + /// Establishes a two-way connection between a binding and the stepper's current value. + /// + /// - Parameter value: The binding to read from for the current value, and write to when the + /// value changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(value: UIBinding) -> ObservationToken { + bind(value, to: \.value, for: .valueChanged) + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UISwitch.swift b/Sources/AppKitNavigation/Bindings/UISwitch.swift new file mode 100644 index 0000000000..c8e4ab0ff3 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UISwitch.swift @@ -0,0 +1,32 @@ +#if canImport(UIKit) && !os(tvOS) && !os(watchOS) + import UIKit + + @available(iOS 14, *) + @available(tvOS, unavailable) + @available(watchOS, unavailable) + extension UISwitch { + /// Creates a new switch with the specified frame and registers the binding against whether or + /// not the switch is on. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - isOn: The binding to read from for the current state, and write to when the state + /// changes. + public convenience init(frame: CGRect = .zero, isOn: UIBinding) { + self.init(frame: frame) + bind(isOn: isOn) + } + + /// Establishes a two-way connection between a binding and the switch's current state. + /// + /// - Parameter isOn: The binding to read from for the current state, and write to when the + /// state changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(isOn: UIBinding) -> ObservationToken { + bind(isOn, to: \.isOn, for: .valueChanged) { control, isOn, transaction in + control.setOn(isOn, animated: !transaction.uiKit.disablesAnimations) + } + } + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UITabBarController.swift b/Sources/AppKitNavigation/Bindings/UITabBarController.swift new file mode 100644 index 0000000000..7b9e6351a1 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UITabBarController.swift @@ -0,0 +1,65 @@ +#if swift(>=6) && canImport(UIKit) && !os(tvOS) && !os(watchOS) + import IssueReporting + import UIKit + + @available(iOS 18, tvOS 18, visionOS 2, *) + extension UITabBarController { + @discardableResult + public func bind( + selectedTab: UIBinding, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObservationToken { + let token = observe { [weak self] in + guard let self else { return } + guard let identifier = selectedTab.wrappedValue else { + self.selectedTab = nil + return + } + guard let tab = tabs.first(where: { $0.identifier == identifier }) + else { + reportIssue( + """ + Tab bar controller binding attempted to write an invalid identifier ('\(identifier)'). + + Valid identifiers: \(tabs.map(\.identifier)) + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + self.selectedTab = nil + return + } + self.selectedTab = tab + } + let observation = observe(\.selectedTab) { controller, _ in + MainActor.assumeIsolated { + selectedTab.wrappedValue = controller.selectedTab?.identifier + } + } + let observationToken = ObservationToken { + token.cancel() + observation.invalidate() + } + self.observationToken = observationToken + return observationToken + } + + private var observationToken: ObservationToken? { + get { + objc_getAssociatedObject(self, Self.observationTokenKey) as? ObservationToken + } + set { + objc_setAssociatedObject( + self, Self.observationTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private static let observationTokenKey = malloc(1)! + } +#endif diff --git a/Sources/AppKitNavigation/Bindings/UITextField.swift b/Sources/AppKitNavigation/Bindings/UITextField.swift new file mode 100644 index 0000000000..6214680fe9 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/UITextField.swift @@ -0,0 +1,311 @@ +#if canImport(UIKit) && !os(watchOS) + import UIKit + + @available(iOS 14, tvOS 14, *) + extension UITextField { + /// Creates a new text field with the specified frame and registers the binding against its + /// text. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - text: The binding to read from for the current text, and write to when the text + /// changes. + public convenience init(frame: CGRect = .zero, text: UIBinding) { + self.init(frame: frame) + bind(text: text) + } + + /// Creates a new text field with the specified frame and registers the binding against its + /// text. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - attributedText: The binding to read from for the current text, and write to when the + /// attributed text changes. + public convenience init(frame: CGRect = .zero, attributedText: UIBinding) { + self.init(frame: frame) + bind(attributedText: attributedText) + } + + /// Establishes a two-way connection between a binding and the text field's current text. + /// + /// - Parameter text: The binding to read from for the current text, and write to when the text + /// changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(text: UIBinding) -> ObservationToken { + bind(UIBinding(text), to: \.text, for: .editingChanged) + } + + /// Establishes a two-way connection between a binding and the text field's current text. + /// + /// - Parameter attributedText: The binding to read from for the current text, and write to when + /// the attributed text changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(attributedText: UIBinding) -> ObservationToken { + bind(UIBinding(attributedText), to: \.attributedText, for: .editingChanged) + } + + /// Establishes a two-way connection between a binding and the text field's current selection. + /// + /// - Parameter selection: The binding to read from for the current selection, and write to when + /// the selected text range changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(selection: UIBinding) -> ObservationToken { + let editingChangedAction = UIAction { [weak self] _ in + guard let self else { return } + selection.wrappedValue = self.textSelection + } + addAction(editingChangedAction, for: [.editingChanged, .editingDidBegin]) + let editingDidEndAction = UIAction { _ in selection.wrappedValue = nil } + addAction(editingDidEndAction, for: .editingDidEnd) + let token = observe { [weak self] in + guard let self else { return } + textSelection = selection.wrappedValue + } + let observation = observe(\.selectedTextRange) { control, _ in + MainActor._assumeIsolated { + selection.wrappedValue = control.textSelection + } + } + let observationToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + self?.removeAction(editingChangedAction, for: [.editingChanged, .editingDidBegin]) + self?.removeAction(editingDidEndAction, for: .editingDidEnd) + } + token.cancel() + observation.invalidate() + } + observationTokens[\UITextField.selectedTextRange] = observationToken + return observationToken + } + + fileprivate var textSelection: UITextSelection? { + get { + guard + let textRange = selectedTextRange, + let text + else { + return nil + } + let lowerBound = + text.index( + text.startIndex, + offsetBy: offset(from: beginningOfDocument, to: textRange.start), + limitedBy: text.endIndex + ) ?? text.endIndex + let upperBound = + text.index( + text.startIndex, + offsetBy: offset(from: beginningOfDocument, to: textRange.end), + limitedBy: text.endIndex + ) ?? text.endIndex + return UITextSelection(range: lowerBound..( + focus: UIBinding, equals value: Value + ) -> ObservationToken { + self.focusToken?.cancel() + let editingDidBeginAction = UIAction { _ in focus.wrappedValue = value } + let editingDidEndAction = UIAction { _ in + guard focus.wrappedValue == value else { return } + focus.wrappedValue = nil + } + addAction(editingDidBeginAction, for: .editingDidBegin) + addAction(editingDidEndAction, for: [.editingDidEnd, .editingDidEndOnExit]) + let innerToken = observe { [weak self] in + guard let self else { return } + switch (focus.wrappedValue, isFirstResponder) { + case (value, false): + becomeFirstResponder() + case (nil, true): + resignFirstResponder() + default: + break + } + } + let outerToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + self?.removeAction(editingDidBeginAction, for: .editingDidBegin) + self?.removeAction(editingDidEndAction, for: [.editingDidEnd, .editingDidEndOnExit]) + } + innerToken.cancel() + } + self.focusToken = outerToken + return outerToken + } + + /// Binds this text field's focus state to the given Boolean state value. + /// + /// Use this method to cause the text field to receive focus whenever the the `condition` value + /// is `true`. You can use this method to observe the focus state of a text field, or + /// programmatically set and remove focus from the text field. + /// + /// In the following example, a single `UITextField` accepts a user's desired `username`. The + /// text field binds its focus state to the Boolean value `usernameFieldIsFocused`. A "Submit" + /// button's action verifies whether the name is available. If the name is unavailable, the + /// button sets `usernameFieldIsFocused` to `true`, which causes focus to return to the text + /// field, so the user can enter a different name. + /// + /// ```swift + /// final class LoginViewController: UIViewController { + /// @UIBindable private var username = "" + /// @UIBindable private var usernameFieldIsFocused = false + /// + /// // ... + /// + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// let textField = UITextField(text: $username) + /// textField.focus($usernameFieldIsFocused) + /// + /// let submitButton = UIButton( + /// style: .system, + /// primaryAction: UIAction { [weak self] _ in + /// guard let self else { return } + /// if !isUserNameAvailable(username: username) { + /// usernameFieldIsFocused = true + /// } + /// } + /// ) + /// submitButton.setTitle("Sign In", for: .normal) + /// + /// // ... + /// } + /// } + /// ``` + /// + /// To control focus by matching a value, use the ``UIKit/UITextField/bind(focus:equals:)`` + /// method instead. + /// + /// - Parameter condition: The focus state to bind. When focus moves to the text field, the + /// binding sets the bound value to `true`. If a caller sets the value to `true` + /// programmatically, then focus moves to the text field. When focus leaves the text field, + /// the binding sets the value to `false`. If a caller sets the value to `false`, UIKit + /// automatically dismisses focus. + /// - Returns: A cancel token. + @discardableResult + public func bind(focus condition: UIBinding) -> ObservationToken { + bind(focus: condition.toOptionalUnit, equals: Bool.Unit()) + } + + private var focusToken: ObservationToken? { + get { objc_getAssociatedObject(self, Self.focusTokenKey) as? ObservationToken } + set { + objc_setAssociatedObject( + self, Self.focusTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private static let focusTokenKey = malloc(1)! + } + + /// Represents a selection of text. + /// + /// Like SwiftUI's `TextSelection`, but for UIKit. + public struct UITextSelection: Hashable, Sendable { + public var range: Range + + public init(range: Range) { + self.range = range + } + public init(insertionPoint: String.Index) { + self.range = insertionPoint..( + _ operation: @MainActor () throws -> T, + file: StaticString = #fileID, + line: UInt = #line + ) rethrows -> T { + #if swift(<5.10) + typealias YesActor = @MainActor () throws -> T + typealias NoActor = () throws -> T + + guard Thread.isMainThread else { + fatalError( + "Incorrect actor executor assumption; Expected same executor as \(self).", + file: file, + line: line + ) + } + + return try withoutActuallyEscaping(operation) { (_ fn: @escaping YesActor) throws -> T in + let rawFn = unsafeBitCast(fn, to: NoActor.self) + return try rawFn() + } + #else + return try assumeIsolated(operation, file: file, line: line) + #endif + } +} diff --git a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift new file mode 100644 index 0000000000..d527e73ca7 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift @@ -0,0 +1,20 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + @rethrows + protocol _ErrorMechanism { + associatedtype Output + func get() throws -> Output + } + + extension _ErrorMechanism { + func _rethrowError() rethrows -> Never { + _ = try _rethrowGet() + fatalError() + } + + func _rethrowGet() rethrows -> Output { + return try get() + } + } + + extension Result: _ErrorMechanism {} +#endif diff --git a/Sources/AppKitNavigation/Internal/Exports.swift b/Sources/AppKitNavigation/Internal/Exports.swift new file mode 100644 index 0000000000..6f94b2acad --- /dev/null +++ b/Sources/AppKitNavigation/Internal/Exports.swift @@ -0,0 +1,3 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + @_exported import SwiftNavigation +#endif diff --git a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift new file mode 100644 index 0000000000..bbe60acbac --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift @@ -0,0 +1,12 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + extension Bool { + struct Unit: Hashable, Identifiable { + var id: Unit { self } + } + + var toOptionalUnit: Unit? { + get { self ? Unit() : nil } + set { self = newValue != nil } + } + } +#endif diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift new file mode 100644 index 0000000000..6952a998b6 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -0,0 +1,463 @@ +#if canImport(UIKit) && !os(watchOS) + import IssueReporting + @_spi(Internals) import SwiftNavigation + import UIKit + import UIKitNavigationShim + + extension UIViewController { + /// Presents a view controller modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to present the view + /// controller. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func present( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> UIViewController + ) -> ObservationToken { + present(item: isPresented.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + /// Presents a view controller modally using the given item as a data source for its content. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func present( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> UIViewController + ) -> ObservationToken { + present(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + /// Presents a view controller modally using the given item as a data source for its content. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> UIViewController + ) -> ObservationToken { + present(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + /// Presents a view controller modally using the given item as a data source for its content. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - id: The key path to the provided item's identifier. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> UIViewController + ) -> ObservationToken { + present(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + /// Presents a view controller modally using the given item as a data source for its content. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - id: The key path to the provided item's identifier. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> UIViewController + ) -> ObservationToken { + destination(item: item, id: id) { $item in + content($item) + } present: { [weak self] child, transaction in + guard let self else { return } + if presentedViewController != nil { + self.dismiss(animated: !transaction.uiKit.disablesAnimations) { + onDismiss?() + self.present(child, animated: !transaction.uiKit.disablesAnimations) + } + } else { + self.present(child, animated: !transaction.uiKit.disablesAnimations) + } + } dismiss: { [weak self] _, transaction in + self?.dismiss(animated: !transaction.uiKit.disablesAnimations) { + onDismiss?() + } + } + } + + /// Pushes a view controller onto the receiver's stack when a binding to a Boolean value you + /// provide is true. + /// + /// Like SwiftUI's `navigationDestination(isPresented:)` view modifier, but for UIKit. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to push the view + /// controller. + /// - content: A closure that returns the view controller to display onto the receiver's + /// stack. + @discardableResult + public func navigationDestination( + isPresented: UIBinding, + content: @escaping () -> UIViewController + ) -> ObservationToken { + navigationDestination(item: isPresented.toOptionalUnit) { _ in content() } + } + + /// Pushes a view controller onto the receiver's stack using the given item as a data source for + /// its content. + /// + /// Like SwiftUI's `navigationDestination(item:)` view modifier, but for UIKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. + /// - content: A closure that returns the view controller to display onto the receiver's + /// stack. + @discardableResult + public func navigationDestination( + item: UIBinding, + content: @escaping (Item) -> UIViewController + ) -> ObservationToken { + navigationDestination(item: item) { + content($0.wrappedValue) + } + } + + /// Pushes a view controller onto the receiver's stack using the given item as a data source for + /// its content. + /// + /// Like SwiftUI's `navigationDestination(item:)` view modifier, but for UIKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. + /// - content: A closure that returns the view controller to display onto the receiver's + /// stack. + @_disfavoredOverload + @discardableResult + public func navigationDestination( + item: UIBinding, + content: @escaping (UIBinding) -> UIViewController + ) -> ObservationToken { + destination(item: item) { $item in + content($item) + } present: { [weak self] child, transaction in + guard + let navigationController = self?.navigationController ?? self as? UINavigationController + else { + reportIssue( + """ + Can't present navigation item: "navigationController" is "nil". + """ + ) + return + } + navigationController.pushViewController( + child, animated: !transaction.uiKit.disablesAnimations + ) + } dismiss: { [weak self] child, transaction in + guard + let navigationController = self?.navigationController ?? self as? UINavigationController + else { + reportIssue( + """ + Can't dismiss navigation item: "navigationController" is "nil". + """ + ) + return + } + navigationController.popFromViewController( + child, animated: !transaction.uiKit.disablesAnimations + ) + } + } + + /// Presents a view controller when a binding to a Boolean value you provide is true. + /// + /// This helper powers ``present(isPresented:onDismiss:content:)`` and + /// ``UIKit/UINavigationController/pushViewController(isPresented:content:)`` and can be used to + /// define custom transitions. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to present the view + /// controller. + /// - content: A closure that returns the view controller to display. + /// - present: The closure to execute when presenting the view controller. + /// - dismiss: The closure to execute when dismissing the view controller. + @discardableResult + public func destination( + isPresented: UIBinding, + content: @escaping () -> UIViewController, + present: @escaping (UIViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: UIViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + destination( + item: isPresented.toOptionalUnit, + content: { _ in content() }, + present: present, + dismiss: dismiss + ) + } + + /// Presents a view controller using the given item as a data source for its content. + /// + /// This helper powers ``navigationDestination(item:content:)-367r6`` and can be used to define + /// custom transitions. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. + /// - content: A closure that returns the view controller to display. + /// - present: The closure to execute when presenting the view controller. + /// - dismiss: The closure to execute when dismissing the view controller. + @discardableResult + public func destination( + item: UIBinding, + content: @escaping (UIBinding) -> UIViewController, + present: @escaping (UIViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: UIViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + destination( + item: item, + id: { _ in nil }, + content: content, + present: present, + dismiss: dismiss + ) + } + + /// Presents a view controller using the given item as a data source for its content. + /// + /// This helper powers ``present(item:onDismiss:content:)-34iup`` and can be used to define + /// custom transitions. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - id: The key path to the provided item's identifier. + /// - content: A closure that returns the view controller to display. + /// - present: The closure to execute when presenting the view controller. + /// - dismiss: The closure to execute when dismissing the view controller. + @discardableResult + public func destination( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> UIViewController, + present: @escaping ( + _ child: UIViewController, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: UIViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + destination( + item: item, + id: { $0[keyPath: id] }, + content: content, + present: present, + dismiss: dismiss + ) + } + + private func destination( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> UIViewController, + present: @escaping ( + _ child: UIViewController, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: UIViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let presented = presentedByID[key] { + guard let presentationID = presented.presentationID, + presentationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let childController = content(unwrappedItem) + let onDismiss = { [presentationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + presentationID == id(wrappedValue) + { + item.wrappedValue = nil + } + } + childController.onDismiss = onDismiss + if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) { + childController.traitOverrides.dismiss = UIDismissAction { _ in + onDismiss() + } + } + self.presentedByID[key] = Presented(childController, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + present(childController, transaction) + } + } + if hasViewAppeared { + work() + } else { + onViewAppear.append(work) + } + } else if let presented = presentedByID[key] { + if let controller = presented.controller { + dismiss(controller, transaction) + } + self.presentedByID[key] = nil + } + } + } + + fileprivate var presentedByID: [UIBindingIdentifier: Presented] { + get { + (objc_getAssociatedObject(self, Self.presentedKey) + as? [UIBindingIdentifier: Presented]) + ?? [:] + } + set { + objc_setAssociatedObject( + self, Self.presentedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private static let presentedKey = malloc(1)! + } + + extension UINavigationController { + @available( + *, deprecated, + message: """ + Use 'self.navigationDestination(isPresented:)' instead of 'self.navigationController?.pushViewController(isPresented:)'. + """ + ) + @discardableResult + public func pushViewController( + isPresented: UIBinding, + content: @escaping () -> UIViewController + ) -> ObservationToken { + navigationDestination(isPresented: isPresented, content: content) + } + + @available( + *, deprecated, + message: """ + Use 'self.navigationDestination(item:)' instead of 'self.navigationController?.pushViewController(item:)'. + """ + ) + @discardableResult + public func pushViewController( + item: UIBinding, + content: @escaping (Item) -> UIViewController + ) -> ObservationToken { + navigationDestination(item: item, content: content) + } + + @available( + *, deprecated, + message: """ + Use 'self.navigationDestination(item:)' instead of 'self.navigationController?.pushViewController(item:)'. + """ + ) + @_disfavoredOverload + @discardableResult + public func pushViewController( + item: UIBinding, + content: @escaping (UIBinding) -> UIViewController + ) -> ObservationToken { + navigationDestination(item: item, content: content) + } + } + + @MainActor + private class Presented { + weak var controller: UIViewController? + let presentationID: AnyHashable? + deinit { + // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to + // deinit alongside it on the main thread. If we use this other places we should force it + // to be a UIViewController as well, to ensure this functionality. + MainActor._assumeIsolated { + self.controller?.dismiss(animated: false) + } + } + init(_ controller: UIViewController, id presentationID: AnyHashable? = nil) { + self.controller = controller + self.presentationID = presentationID + } + } +#endif diff --git a/Sources/AppKitNavigation/Navigation/UIAlertController.swift b/Sources/AppKitNavigation/Navigation/UIAlertController.swift new file mode 100644 index 0000000000..0151edcdf4 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/UIAlertController.swift @@ -0,0 +1,87 @@ +#if canImport(UIKit) && !os(watchOS) + import UIKit + + @available(iOS 13, *) + @available(macCatalyst 13, *) + @available(macOS, unavailable) + @available(tvOS 13, *) + @available(watchOS, unavailable) + extension UIAlertController { + /// Creates and returns a view controller for displaying an alert using a data description. + /// + /// - Parameters: + /// - state: A data description of the alert. + /// - handler: A closure that is invoked with an action held in `state`. + public convenience init( + state: AlertState, + handler: @escaping (_ action: Action?) -> Void + ) { + self.init( + title: String(state: state.title), + message: state.message.map { String(state: $0) }, + preferredStyle: .alert + ) + for button in state.buttons { + addAction(UIAlertAction(button, action: handler)) + } + } + + /// Creates and returns a view controller for displaying an action sheet using a data + /// description. + /// + /// - Parameters: + /// - state: A data description of the alert. + /// - handler: A closure that is invoked with an action held in `state`. + public convenience init( + state: ConfirmationDialogState, + handler: @escaping (_ action: Action?) -> Void + ) { + self.init( + title: state.titleVisibility == .visible ? String(state: state.title) : nil, + message: state.message.map { String(state: $0) }, + preferredStyle: .actionSheet + ) + for button in state.buttons { + addAction(UIAlertAction(button, action: handler)) + } + } + } + + @available(iOS 13, *) + @available(macCatalyst 13, *) + @available(macOS, unavailable) + @available(tvOS 13, *) + @available(watchOS, unavailable) + extension UIAlertAction.Style { + public init(_ role: ButtonStateRole) { + switch role { + case .cancel: + self = .cancel + case .destructive: + self = .destructive + } + } + } + + @available(iOS 13, *) + @available(macCatalyst 13, *) + @available(macOS, unavailable) + @available(tvOS 13, *) + @available(watchOS, unavailable) + extension UIAlertAction { + public convenience init( + _ button: ButtonState, + action handler: @escaping (_ action: Action?) -> Void + ) { + self.init( + title: String(state: button.label), + style: button.role.map(UIAlertAction.Style.init) ?? .default + ) { _ in + button.withAction(handler) + } + if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { + self.accessibilityLabel = button.label.accessibilityLabel.map { String(state: $0) } + } + } + } +#endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift new file mode 100644 index 0000000000..d7a6d934a7 --- /dev/null +++ b/Sources/AppKitNavigation/Observe.swift @@ -0,0 +1,188 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + @_spi(Internals) import SwiftNavigation + import AppKit + + @MainActor + extension NSObject { + /// Observe access to properties of an observable (or perceptible) object. + /// + /// This tool allows you to set up an observation loop so that you can access fields from an + /// observable model in order to populate your view, and also automatically track changes to + /// any accessed fields so that the view is always up-to-date. + /// + /// It is most useful when dealing with non-SwiftUI views, such as UIKit views and controller. + /// You can invoke the ``observe(_:)`` method a single time in the `viewDidLoad` and update all + /// the view elements: + /// + /// ```swift + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// let countLabel = UILabel() + /// let incrementButton = UIButton(primaryAction: UIAction { [weak self] _ in + /// self?.model.incrementButtonTapped() + /// }) + /// + /// observe { [weak self] in + /// guard let self + /// else { return } + /// + /// countLabel.text = "\(model.count)" + /// } + /// } + /// ``` + /// + /// This closure is immediately called, allowing you to set the initial state of your UI + /// components from the feature's state. And if the `count` property in the feature's state is + /// ever mutated, this trailing closure will be called again, allowing us to update the view + /// again. + /// + /// Generally speaking you can usually have a single ``observe(_:)`` in the entry point of your + /// view, such as `viewDidLoad` for `UIViewController`. This works even if you have many UI + /// components to update: + /// + /// ```swift + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// observe { [weak self] in + /// guard let self + /// else { return } + /// + /// countLabel.isHidden = model.isObservingCount + /// if !countLabel.isHidden { + /// countLabel.text = "\(model.count)" + /// } + /// factLabel.text = model.fact + /// } + /// } + /// ``` + /// + /// This does mean that you may execute the line `factLabel.text = model.fact` even when + /// something unrelated changes, such as `store.model`, but that is typically OK for simple + /// properties of UI components. It is not a performance problem to repeatedly set the `text` of + /// a label or the `isHidden` of a button. + /// + /// However, if there is heavy work you need to perform when state changes, then it is best to + /// put that in its own ``observe(_:)``. For example, if you needed to reload a table view or + /// collection view when a collection changes: + /// + /// ```swift + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// observe { [weak self] in + /// guard let self + /// else { return } + /// + /// dataSource = model.items + /// tableView.reloadData() + /// } + /// } + /// ``` + /// + /// ## Cancellation + /// + /// The method returns an ``ObservationToken`` that can be used to cancel observation. For + /// example, if you only want to observe while a view controller is visible, you can start + /// observation in the `viewWillAppear` and then cancel observation in the `viewWillDisappear`: + /// + /// ```swift + /// var observation: ObservationToken? + /// + /// func viewWillAppear() { + /// super.viewWillAppear() + /// observation = observe { [weak self] in + /// // ... + /// } + /// } + /// func viewWillDisappear() { + /// super.viewWillDisappear() + /// observation?.cancel() + /// } + /// ``` + /// + /// - Parameter apply: A closure that contains properties to track and is invoked when the value + /// of a property changes. + /// - Returns: A cancellation token. + @discardableResult + public func observe(_ apply: @escaping @MainActor @Sendable () -> Void) -> ObservationToken { + observe { _ in apply() } + } + + /// Observe access to properties of an observable (or perceptible) object. + /// + /// A version of ``observe(_:)`` that is passed the current transaction. + /// + /// - Parameter apply: A closure that contains properties to track and is invoked when the value + /// of a property changes. + /// - Returns: A cancellation token. + @discardableResult + public func observe( + _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void + ) -> ObservationToken { + let token = SwiftNavigation.observe { transaction in + MainActor._assumeIsolated { + withUITransaction(transaction) { + #if os(watchOS) + apply(transaction) + #else + if transaction.appKit.disablesAnimations { + NSView.performWithoutAnimation { apply(transaction) } + for completion in transaction.appKit.animationCompletions { + completion(true) + } + } else if let animation = transaction.appKit.animation { + return animation.perform( + { apply(transaction) }, + completion: transaction.appKit.animationCompletions.isEmpty + ? nil + : { + for completion in transaction.appKit.animationCompletions { + completion($0) + } + } + ) + } else { + apply(transaction) + for completion in transaction.appKit.animationCompletions { + completion(true) + } + } + #endif + } + } + } task: { transaction, work in + DispatchQueue.main.async { + withUITransaction(transaction, work) + } + } + tokens.append(token) + return token + } + + fileprivate var tokens: [Any] { + get { + objc_getAssociatedObject(self, Self.tokensKey) as? [Any] ?? [] + } + set { + objc_setAssociatedObject(self, Self.tokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + private static let tokensKey = malloc(1)! + } + +extension NSView { + static func performWithoutAnimation(_ block: () -> Void) { + if NSAnimationContext.current.allowsImplicitAnimation { + NSAnimationContext.current.allowsImplicitAnimation = false + block() + NSAnimationContext.current.allowsImplicitAnimation = true + } else { + block() + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/SwiftUI/Representable.swift b/Sources/AppKitNavigation/SwiftUI/Representable.swift new file mode 100644 index 0000000000..29ac8b2301 --- /dev/null +++ b/Sources/AppKitNavigation/SwiftUI/Representable.swift @@ -0,0 +1,24 @@ +#if canImport(SwiftUI) && canImport(AppKit) && !targetEnvironment(macCatalyst) + import SwiftUI + import AppKit + + public struct NSViewControllerRepresenting< + NSViewControllerType: NSViewController + >: NSViewControllerRepresentable { + private let base: NSViewControllerType + public init(_ base: () -> NSViewControllerType) { + self.base = base() + } + public func makeNSViewController(context _: Context) -> NSViewControllerType { base } + public func updateNSViewController(_: NSViewControllerType, context _: Context) {} + } + + public struct NSViewRepresenting: NSViewRepresentable { + private let base: NSViewType + public init(_ base: () -> NSViewType) { + self.base = base() + } + public func makeNSView(context _: Context) -> NSViewType { base } + public func updateNSView(_: NSViewType, context _: Context) {} + } +#endif diff --git a/Sources/AppKitNavigation/UIBinding.swift b/Sources/AppKitNavigation/UIBinding.swift new file mode 100644 index 0000000000..4a66220b17 --- /dev/null +++ b/Sources/AppKitNavigation/UIBinding.swift @@ -0,0 +1,15 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import SwiftNavigation + + extension UIBinding { + /// Specifies an animation to perform when the binding value changes. + /// + /// - Parameter animation: An animation sequence performed when the binding value changes. + /// - Returns: A new binding. + public func animation(_ animation: AppKitAnimation? = .default) -> Self { + var binding = self + binding.transaction.appKit.animation = animation + return binding + } + } +#endif diff --git a/Sources/AppKitNavigation/UIKitAnimation.swift b/Sources/AppKitNavigation/UIKitAnimation.swift new file mode 100644 index 0000000000..7e5106edc5 --- /dev/null +++ b/Sources/AppKitNavigation/UIKitAnimation.swift @@ -0,0 +1,144 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + + #if canImport(SwiftUI) + import SwiftUI + #endif + import SwiftNavigation + /// Executes a closure with the specified animation and returns the result. + /// + /// - Parameters: + /// - animation: An animation, set in the ``UITransaction/appKit`` property of the thread's + /// current transaction. + /// - body: A closure to execute. + /// - completion: A completion to run when the animation is complete. + /// - Returns: The result of executing the closure with the specified animation. + @MainActor + public func withAppKitAnimation( + _ animation: AppKitAnimation? = .default, + _ body: () throws -> Result, + completion: (@Sendable (Bool?) -> Void)? = nil + ) rethrows -> Result { + var transaction = UITransaction() + transaction.appKit.animation = animation + if let completion { + transaction.appKit.addAnimationCompletion(completion) + } + return try withUITransaction(transaction, body) + } + + /// The way a view changes over time to create a smooth visual transition from one state to + /// another. + public struct AppKitAnimation: Hashable, Sendable { + fileprivate let framework: Framework + + @MainActor + func perform( + _ body: () throws -> Result, + completion: ((Bool?) -> Void)? = nil + ) rethrows -> Result { + switch framework { + case let .swiftUI(animation): + #if swift(>=6) + if #available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *) { + var result: Swift.Result? + UIView.animate( + with: animation, + changes: { result = Swift.Result(catching: body) }, + completion: completion.map { completion in { completion(true) } } + ) + return try result!._rethrowGet() + } + #endif + _ = animation + fatalError() + + case let .appKit(animation): + var result: Swift.Result? + NSAnimationContext.runAnimationGroup { context in + context.duration = animation.duration + result = Swift.Result(catching: body) + } completionHandler: { + completion?(true) + } + + return try result!._rethrowGet() + + + } + } + + fileprivate enum Framework: Hashable, Sendable { + case appKit(AppKit) + case swiftUI(Animation) + + fileprivate struct AppKit: Hashable, Sendable { + fileprivate var duration: TimeInterval + + func hash(into hasher: inout Hasher) { + hasher.combine(duration) + } + + } + } + } + + extension AppKitAnimation { + + /// Performs am animation using a timing curve corresponding to the motion of a physical spring. + /// + /// A value description of + /// `UIView.animate(withDuration:delay:dampingRatio:velocity:options:animations:completion:)` + /// that can be used with ``withAppKitAnimation(_:_:completion:)``. + /// + /// - Parameters: + /// - duration: The total duration of the animations, measured in seconds. If you specify a + /// negative value or `0`, the changes are made without animating them. + /// - delay: The amount of time (measured in seconds) to wait before beginning the animations. + /// Specify a value of `0` to begin the animations immediately. + /// - dampingRatio: The damping ratio for the spring animation as it approaches its quiescent + /// state. + /// + /// To smoothly decelerate the animation without oscillation, use a value of `1`. Employ a + /// damping ratio closer to zero to increase oscillation. + /// - velocity: The initial spring velocity. For smooth start to the animation, match this + /// value to the view's velocity as it was prior to attachment. + /// + /// A value of `1` corresponds to the total animation distance traversed in one second. For + /// example, if the total animation distance is 200 points and you want the start of the + /// animation to match a view velocity of 100 pt/s, use a value of `0.5`. + /// - options: A mask of options indicating how you want to perform the animations. For a list + /// of valid constants, see `UIView.AnimationOptions`. + /// - Returns: An animation using a timing curve corresponding to the motion of a physical + /// spring. + public static func animate( + withDuration duration: TimeInterval = 0.25 + ) -> Self { + Self( + framework: .appKit( + Framework.AppKit( + duration: duration + ) + ) + ) + } + + + /// Animates changes using the specified SwiftUI animation. + /// + /// - Parameter animation: The animation to use for the changes. + @available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *) + public init(_ animation: Animation) { + self.init(framework: .swiftUI(animation)) + } + + /// A default animation instance. + public static var `default`: Self { + if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) { + return .animate() + } else { + return .animate(withDuration: 0.35) + } + } + } +#endif diff --git a/Sources/AppKitNavigation/UITransaction.swift b/Sources/AppKitNavigation/UITransaction.swift new file mode 100644 index 0000000000..88ba674b30 --- /dev/null +++ b/Sources/AppKitNavigation/UITransaction.swift @@ -0,0 +1,53 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import SwiftNavigation + + extension UITransaction { + /// Creates a transaction and assigns its animation property. + /// + /// - Parameter animation: The animation to perform when the current state changes. + public init(animation: AppKitAnimation? = nil) { + self.init() + self.appKit.animation = animation + } + + /// AppKit-specific data associated with the current state change. + public var appKit: AppKit { + get { self[AppKitKey.self] } + set { self[AppKitKey.self] = newValue } + } + + private enum AppKitKey: UITransactionKey { + static let defaultValue = AppKit() + } + + /// AppKit-specific data associated with a ``UITransaction``. + public struct AppKit: Sendable { + /// The animation, if any, associated with the current state change. + public var animation: AppKitAnimation? + + /// A Boolean value that indicates whether views should disable animations. + public var disablesAnimations = false + + var animationCompletions: [@Sendable (Bool?) -> Void] = [] + + /// Adds a completion to run when the animations created with this transaction are all + /// complete. + /// + /// The completion callback will always be fired exactly one time. + public mutating func addAnimationCompletion( + _ completion: @escaping @Sendable (Bool?) -> Void + ) { + animationCompletions.append(completion) + } + } + } + + private enum AnimationCompletionsKey: UITransactionKey { + static let defaultValue: [@Sendable (Bool?) -> Void] = [] + } + + private enum DisablesAnimationsKey: UITransactionKey { + static let defaultValue = false + } +#endif diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h new file mode 100644 index 0000000000..1d2054f3ca --- /dev/null +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -0,0 +1,19 @@ +#if __has_include() + #include + + #if __has_include() && !TARGET_OS_MACCATALYST + @import AppKit; + + NS_ASSUME_NONNULL_BEGIN + + @interface NSViewController (AppKitNavigation) + + @property BOOL hasViewAppeared; + @property (nullable) void (^onDismiss)(); + @property NSArray *onViewAppear; + + @end + + NS_ASSUME_NONNULL_END + #endif +#endif diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m new file mode 100644 index 0000000000..a2fb9479a5 --- /dev/null +++ b/Sources/AppKitNavigationShim/shim.m @@ -0,0 +1,106 @@ +#if __has_include() + #include + + #if __has_include() && !TARGET_OS_MACCATALYST + @import ObjectiveC; + @import AppKit; + #import "shim.h" + + @interface AppKitNavigationShim : NSObject + + @end + + @implementation AppKitNavigationShim + + // NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible + // for state-driven presentation and dismissal of child features. + + + (void)load { + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(viewDidAppear)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidAppear)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(viewDidDisappear)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidDisappear)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) + ); + } + + @end + + static void *hasViewAppearedKey = &hasViewAppearedKey; + static void *onDismissKey = &onDismissKey; + static void *onViewAppearKey = &onViewAppearKey; + + @implementation NSViewController (AppKitNavigation) + + - (void)AppKitNavigation_viewDidAppear { + [self AppKitNavigation_viewDidAppear]; + + if (self.hasViewAppeared) { + return; + } + self.hasViewAppeared = YES; + for (void (^work)() in self.onViewAppear) { + work(); + } + self.onViewAppear = @[]; + } + + - (void)setBeingDismissed:(BOOL)beingDismissed { + objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); + } + + - (BOOL)isBeingDismissed { + return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; + } + + - (void)AppKitNavigation_viewDidDisappear { + [self AppKitNavigation_viewDidDisappear]; + + if ((self.isBeingDismissed) && self.onDismiss != NULL) { + self.onDismiss(); + self.onDismiss = nil; + [self setBeingDismissed:NO]; + } + } + + - (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { + [self AppKitNavigation_dismissViewController:sender]; + [self setBeingDismissed:YES]; + } + + - (BOOL)hasViewAppeared { + return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; + } + + - (void)setHasViewAppeared:(BOOL)hasViewAppeared { + objc_setAssociatedObject( + self, hasViewAppearedKey, @(hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC + ); + } + + - (void (^)())onDismiss { + return objc_getAssociatedObject(self, onDismissKey); + } + + - (void)setOnDismiss:(void (^)())onDismiss { + objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); + } + + - (NSMutableArray *)onViewAppear { + id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); + return onViewAppear == nil ? @[] : onViewAppear; + } + + - (void)setOnViewAppear:(NSMutableArray *)onViewAppear { + objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); + } + + @end + #endif +#endif From 4678f0adba6576a56467f0136a34b9d14cda985a Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Wed, 14 Aug 2024 01:33:33 +0800 Subject: [PATCH 002/141] Updates --- Package.swift | 9 - .../AppKitNavigation/AppKitAnimation.swift | 121 +++++ .../Bindings/NSColorPanel.swift | 41 ++ .../Bindings/NSColorWell.swift | 27 + .../AppKitNavigation/Bindings/NSControl.swift | 17 + ...{UIDatePicker.swift => NSDatePicker.swift} | 17 +- .../Bindings/NSFontManager.swift | 74 +++ .../Bindings/NSMenuItem.swift | 17 + .../Bindings/NSOpenPanel.swift | 5 + .../Bindings/NSPathControl.swift | 29 ++ .../Bindings/NSSavePanel.swift | 5 + .../Bindings/NSSegmentedControl.swift | 79 +++ .../{UISlider.swift => NSSlider.swift} | 17 +- .../{UIStepper.swift => NSStepper.swift} | 17 +- .../{UISwitch.swift => NSSwitch.swift} | 26 +- .../Bindings/NSTargetAction.swift | 127 +++++ .../{UITextField.swift => NSTextField.swift} | 260 +++++----- .../Bindings/NSToolbarItem.swift | 17 + .../Bindings/UIColorWell.swift | 30 -- .../AppKitNavigation/Bindings/UIControl.swift | 107 ---- .../Bindings/UIPageControl.swift | 28 -- .../Bindings/UISegmentedControl.swift | 81 --- .../Bindings/UITabBarController.swift | 65 --- .../Navigation/Presentation.swift | 475 +++++++----------- .../Navigation/UIAlertController.swift | 168 +++---- Sources/AppKitNavigation/UIKitAnimation.swift | 144 ------ 26 files changed, 999 insertions(+), 1004 deletions(-) create mode 100644 Sources/AppKitNavigation/AppKitAnimation.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSColorPanel.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSColorWell.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSControl.swift rename Sources/AppKitNavigation/Bindings/{UIDatePicker.swift => NSDatePicker.swift} (73%) create mode 100644 Sources/AppKitNavigation/Bindings/NSFontManager.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSMenuItem.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSOpenPanel.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSPathControl.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSSavePanel.swift create mode 100644 Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift rename Sources/AppKitNavigation/Bindings/{UISlider.swift => NSSlider.swift} (72%) rename Sources/AppKitNavigation/Bindings/{UIStepper.swift => NSStepper.swift} (72%) rename Sources/AppKitNavigation/Bindings/{UISwitch.swift => NSSwitch.swift} (66%) create mode 100644 Sources/AppKitNavigation/Bindings/NSTargetAction.swift rename Sources/AppKitNavigation/Bindings/{UITextField.swift => NSTextField.swift} (58%) create mode 100644 Sources/AppKitNavigation/Bindings/NSToolbarItem.swift delete mode 100644 Sources/AppKitNavigation/Bindings/UIColorWell.swift delete mode 100644 Sources/AppKitNavigation/Bindings/UIControl.swift delete mode 100644 Sources/AppKitNavigation/Bindings/UIPageControl.swift delete mode 100644 Sources/AppKitNavigation/Bindings/UISegmentedControl.swift delete mode 100644 Sources/AppKitNavigation/Bindings/UITabBarController.swift delete mode 100644 Sources/AppKitNavigation/UIKitAnimation.swift diff --git a/Package.swift b/Package.swift index 3bc91c28ee..480e3861b8 100644 --- a/Package.swift +++ b/Package.swift @@ -66,18 +66,10 @@ let package = Package( "SwiftUINavigation" ] ), - .target( - name: "CocoaNavigation", - dependencies: [ - "SwiftNavigation", - .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), - ] - ), .target( name: "UIKitNavigation", dependencies: [ "SwiftNavigation", - "CocoaNavigation", "UIKitNavigationShim", .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), ] @@ -89,7 +81,6 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "CocoaNavigation", "AppKitNavigationShim", .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), ] diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift new file mode 100644 index 0000000000..75e40b8f86 --- /dev/null +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -0,0 +1,121 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +#if canImport(SwiftUI) +import SwiftUI +#endif + +import SwiftNavigation + +/// Executes a closure with the specified animation and returns the result. +/// +/// - Parameters: +/// - animation: An animation, set in the ``UITransaction/appKit`` property of the thread's +/// current transaction. +/// - body: A closure to execute. +/// - completion: A completion to run when the animation is complete. +/// - Returns: The result of executing the closure with the specified animation. +@MainActor +public func withAppKitAnimation( + _ animation: AppKitAnimation? = .default, + _ body: () throws -> Result, + completion: (@Sendable (Bool?) -> Void)? = nil +) rethrows -> Result { + var transaction = UITransaction() + transaction.appKit.animation = animation + if let completion { + transaction.appKit.addAnimationCompletion(completion) + } + return try withUITransaction(transaction, body) +} + +/// The way a view changes over time to create a smooth visual transition from one state to +/// another. +public struct AppKitAnimation: Hashable, Sendable { + fileprivate let framework: Framework + + @MainActor + func perform( + _ body: () throws -> Result, + completion: ((Bool?) -> Void)? = nil + ) rethrows -> Result { + switch framework { + case let .swiftUI(animation): + _ = animation + fatalError() + case let .appKit(animation): + var result: Swift.Result? + NSAnimationContext.runAnimationGroup { context in + context.duration = animation.duration + result = Swift.Result(catching: body) + } completionHandler: { + completion?(true) + } + + return try result!._rethrowGet() + } + } + + fileprivate enum Framework: Hashable, Sendable { + case appKit(AppKit) + case swiftUI(Animation) + + fileprivate struct AppKit: Hashable, Sendable { + fileprivate var duration: TimeInterval + + func hash(into hasher: inout Hasher) { + hasher.combine(duration) + } + } + } +} + +extension AppKitAnimation { + /// Performs am animation using a timing curve corresponding to the motion of a physical spring. + /// + /// A value description of + /// `UIView.animate(withDuration:delay:dampingRatio:velocity:options:animations:completion:)` + /// that can be used with ``withAppKitAnimation(_:_:completion:)``. + /// + /// - Parameters: + /// - duration: The total duration of the animations, measured in seconds. If you specify a + /// negative value or `0`, the changes are made without animating them. + /// - delay: The amount of time (measured in seconds) to wait before beginning the animations. + /// Specify a value of `0` to begin the animations immediately. + /// - dampingRatio: The damping ratio for the spring animation as it approaches its quiescent + /// state. + /// + /// To smoothly decelerate the animation without oscillation, use a value of `1`. Employ a + /// damping ratio closer to zero to increase oscillation. + /// - velocity: The initial spring velocity. For smooth start to the animation, match this + /// value to the view's velocity as it was prior to attachment. + /// + /// A value of `1` corresponds to the total animation distance traversed in one second. For + /// example, if the total animation distance is 200 points and you want the start of the + /// animation to match a view velocity of 100 pt/s, use a value of `0.5`. + /// - options: A mask of options indicating how you want to perform the animations. For a list + /// of valid constants, see `UIView.AnimationOptions`. + /// - Returns: An animation using a timing curve corresponding to the motion of a physical + /// spring. + public static func animate( + withDuration duration: TimeInterval = 0.25 + ) -> Self { + Self( + framework: .appKit( + Framework.AppKit( + duration: duration + ) + ) + ) + } + + /// A default animation instance. + public static var `default`: Self { + if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) { + return .animate() + } else { + return .animate(withDuration: 0.35) + } + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift new file mode 100644 index 0000000000..e266d8bc8a --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -0,0 +1,41 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSColorPanel: NSTargetActionProtocol { + public var appkitNavigationTarget: AnyObject? { + set { setTarget(newValue) } + get { value(forKeyPath: "target") as? AnyObject } + } + + public var appkitNavigationAction: Selector? { + set { setAction(newValue) } + get { value(forKeyPath: "action") as? Selector } + } +} + +extension NSColorPanel { + /// Creates a new color panel and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - color: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init(color: UIBinding) { + self.init() + bind(color: color) + } + + /// Establishes a two-way connection between a binding and the color panel's selected color. + /// + /// - Parameter color: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(color: UIBinding) -> ObservationToken { + bind(color, to: \.color) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSColorWell.swift b/Sources/AppKitNavigation/Bindings/NSColorWell.swift new file mode 100644 index 0000000000..8dda1c8a1c --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSColorWell.swift @@ -0,0 +1,27 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSColorWell { + /// Creates a new color well with the specified frame and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - color: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init(frame: CGRect = .zero, color: UIBinding) { + self.init(frame: frame) + bind(color: color) + } + + /// Establishes a two-way connection between a binding and the color well's selected color. + /// + /// - Parameter color: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(color: UIBinding) -> ObservationToken { + bind(color, to: \.color) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift new file mode 100644 index 0000000000..de03e4bd48 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -0,0 +1,17 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSControl: NSTargetActionProtocol { + public var appkitNavigationTarget: AnyObject? { + set { target = newValue } + get { target } + } + + public var appkitNavigationAction: Selector? { + set { action = newValue } + get { action } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/UIDatePicker.swift b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift similarity index 73% rename from Sources/AppKitNavigation/Bindings/UIDatePicker.swift rename to Sources/AppKitNavigation/Bindings/NSDatePicker.swift index b4c02a007f..793dcc4d8f 100644 --- a/Sources/AppKitNavigation/Bindings/UIDatePicker.swift +++ b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift @@ -1,10 +1,7 @@ -#if canImport(UIKit) && !os(tvOS) && !os(watchOS) - import UIKit +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit - @available(iOS 14, *) - @available(tvOS, unavailable) - @available(watchOS, unavailable) - extension UIDatePicker { +extension NSDatePicker { /// Creates a new date picker with the specified frame and registers the binding against the /// selected date. /// @@ -13,8 +10,8 @@ /// - date: The binding to read from for the selected date, and write to when the selected /// date changes. public convenience init(frame: CGRect = .zero, date: UIBinding) { - self.init(frame: frame) - bind(date: date) + self.init(frame: frame) + bind(date: date) } /// Establishes a two-way connection between a binding and the date picker's selected date. @@ -24,7 +21,7 @@ /// - Returns: A cancel token. @discardableResult public func bind(date: UIBinding) -> ObservationToken { - bind(date, to: \.date, for: .valueChanged) + bind(date, to: \.dateValue) } - } +} #endif diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift new file mode 100644 index 0000000000..373b40f34d --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -0,0 +1,74 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { + public var appkitNavigationTarget: AnyObject? { + set { appkitNavigationDelegate.target = newValue } + get { appkitNavigationDelegate.target } + } + + public var appkitNavigationAction: Selector? { + set { appkitNavigationDelegate.action = newValue } + get { appkitNavigationDelegate.action } + } + + private var appkitNavigationDelegate: Delegate { + set { + objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + if let delegate = objc_getAssociatedObject(self, #function) as? Delegate { + return delegate + } else { + let delegate = Delegate() + self.target = delegate + self.appkitNavigationDelegate = delegate + return delegate + } + } + } + + private class Delegate: NSObject, NSFontChanging { + var target: AnyObject? + var action: Selector? + + func changeFont(_ sender: NSFontManager?) { + if let action { + NSApplication.shared.sendAction(action, to: target, from: sender) + } + } + } +} + +@MainActor +extension NSFontManager { + /// Creates a new date picker with the specified frame and registers the binding against the + /// selected date. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected date, and write to when the selected + /// date changes. + public convenience init(font: UIBinding) { + self.init() + bind(font: font) + } + + /// Establishes a two-way connection between a binding and the date picker's selected date. + /// + /// - Parameter date: The binding to read from for the selected date, and write to when the + /// selected date changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(font: UIBinding) -> ObservationToken { + bind(font, to: \._selectedFont) + } + + private var _selectedFont: NSFont { + set { setSelectedFont(newValue, isMultiple: false) } + get { convert(.systemFont(ofSize: 0)) } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift new file mode 100644 index 0000000000..25d7dd5c0a --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift @@ -0,0 +1,17 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSMenuItem: NSTargetActionProtocol, @unchecked Sendable { + public var appkitNavigationTarget: AnyObject? { + set { target = newValue } + get { target } + } + + public var appkitNavigationAction: Selector? { + set { action = newValue } + get { action } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift new file mode 100644 index 0000000000..893f31d20e --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift @@ -0,0 +1,5 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSPathControl.swift b/Sources/AppKitNavigation/Bindings/NSPathControl.swift new file mode 100644 index 0000000000..78a0bf0f0c --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSPathControl.swift @@ -0,0 +1,29 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSPathControl { + /// Creates a new path control with the specified frame and registers the binding against the + /// selected url. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected url, and write to when the selected + /// url changes. + public convenience init(frame: CGRect = .zero, date: UIBinding) { + self.init(frame: frame) + bind(url: date) + } + + /// Establishes a two-way connection between a binding and the path control's selected url. + /// + /// - Parameter url: The binding to read from for the selected url, and write to when the + /// selected url changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(url: UIBinding) -> ObservationToken { + bind(url, to: \.url) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSavePanel.swift b/Sources/AppKitNavigation/Bindings/NSSavePanel.swift new file mode 100644 index 0000000000..893f31d20e --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSavePanel.swift @@ -0,0 +1,5 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift new file mode 100644 index 0000000000..fa32c08dd5 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -0,0 +1,79 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import IssueReporting +import AppKit + +extension NSSegmentedControl { + /// Creates a new color well with the specified frame and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - selectedSegment: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init( + frame: CGRect = .zero, selectedSegment: UIBinding>, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + self.init(frame: frame) + bind( + selectedSegment: selectedSegment, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Establishes a two-way connection between a binding and the color well's selected color. + /// + /// - Parameter selectedSegment: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selectedSegment: UIBinding>, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObservationToken { + let fileID = HashableStaticString(rawValue: fileID) + let filePath = HashableStaticString(rawValue: filePath) + return bind( + selectedSegment[fileID: fileID, filePath: filePath, line: line, column: column], + to: \.selectedSegment + ) + } +} + +extension RawRepresentable { + fileprivate subscript( + fileID fileID: HashableStaticString, + filePath filePath: HashableStaticString, + line line: UInt, + column column: UInt + ) -> Int { + get { rawValue } + set { + guard let rawRepresentable = Self(rawValue: newValue) + else { + reportIssue( + """ + Raw-representable 'UIBinding<\(Self.self)>' attempted to write an invalid raw value \ + ('\(newValue)'). + """, + fileID: fileID.rawValue, + filePath: filePath.rawValue, + line: line, + column: column + ) + return + } + self = rawRepresentable + } + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/UISlider.swift b/Sources/AppKitNavigation/Bindings/NSSlider.swift similarity index 72% rename from Sources/AppKitNavigation/Bindings/UISlider.swift rename to Sources/AppKitNavigation/Bindings/NSSlider.swift index f2fd9a2f61..50778248a1 100644 --- a/Sources/AppKitNavigation/Bindings/UISlider.swift +++ b/Sources/AppKitNavigation/Bindings/NSSlider.swift @@ -1,10 +1,7 @@ -#if canImport(UIKit) && !os(tvOS) && !os(watchOS) - import UIKit +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit - @available(iOS 14, *) - @available(tvOS, unavailable) - @available(watchOS, unavailable) - extension UISlider { +extension NSSlider { /// Creates a new slider with the specified frame and registers the binding against the value. /// /// - Parameters: @@ -12,8 +9,8 @@ /// - value: The binding to read from for the current value, and write to when the value /// changes. public convenience init(frame: CGRect = .zero, value: UIBinding) { - self.init(frame: frame) - bind(value: value) + self.init(frame: frame) + bind(value: value) } /// Establishes a two-way connection between a binding and the slider's current value. @@ -23,7 +20,7 @@ /// - Returns: A cancel token. @discardableResult public func bind(value: UIBinding) -> ObservationToken { - bind(value, to: \.value, for: .valueChanged) + bind(value, to: \.floatValue) } - } +} #endif diff --git a/Sources/AppKitNavigation/Bindings/UIStepper.swift b/Sources/AppKitNavigation/Bindings/NSStepper.swift similarity index 72% rename from Sources/AppKitNavigation/Bindings/UIStepper.swift rename to Sources/AppKitNavigation/Bindings/NSStepper.swift index d3e664e9d2..a2fb9bbf43 100644 --- a/Sources/AppKitNavigation/Bindings/UIStepper.swift +++ b/Sources/AppKitNavigation/Bindings/NSStepper.swift @@ -1,10 +1,7 @@ -#if canImport(UIKit) && !os(tvOS) && !os(watchOS) - import UIKit +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit - @available(iOS 14, *) - @available(tvOS, unavailable) - @available(watchOS, unavailable) - extension UIStepper { +extension NSStepper { /// Creates a new stepper with the specified frame and registers the binding against the value. /// /// - Parameters: @@ -12,8 +9,8 @@ /// - value: The binding to read from for the current value, and write to when the value /// changes. public convenience init(frame: CGRect = .zero, value: UIBinding) { - self.init(frame: frame) - bind(value: value) + self.init(frame: frame) + bind(value: value) } /// Establishes a two-way connection between a binding and the stepper's current value. @@ -23,7 +20,7 @@ /// - Returns: A cancel token. @discardableResult public func bind(value: UIBinding) -> ObservationToken { - bind(value, to: \.value, for: .valueChanged) + bind(value, to: \.doubleValue) } - } +} #endif diff --git a/Sources/AppKitNavigation/Bindings/UISwitch.swift b/Sources/AppKitNavigation/Bindings/NSSwitch.swift similarity index 66% rename from Sources/AppKitNavigation/Bindings/UISwitch.swift rename to Sources/AppKitNavigation/Bindings/NSSwitch.swift index c8e4ab0ff3..21b752be18 100644 --- a/Sources/AppKitNavigation/Bindings/UISwitch.swift +++ b/Sources/AppKitNavigation/Bindings/NSSwitch.swift @@ -1,10 +1,7 @@ -#if canImport(UIKit) && !os(tvOS) && !os(watchOS) - import UIKit +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit - @available(iOS 14, *) - @available(tvOS, unavailable) - @available(watchOS, unavailable) - extension UISwitch { +extension NSSwitch { /// Creates a new switch with the specified frame and registers the binding against whether or /// not the switch is on. /// @@ -13,8 +10,8 @@ /// - isOn: The binding to read from for the current state, and write to when the state /// changes. public convenience init(frame: CGRect = .zero, isOn: UIBinding) { - self.init(frame: frame) - bind(isOn: isOn) + self.init(frame: frame) + bind(isOn: isOn) } /// Establishes a two-way connection between a binding and the switch's current state. @@ -24,9 +21,14 @@ /// - Returns: A cancel token. @discardableResult public func bind(isOn: UIBinding) -> ObservationToken { - bind(isOn, to: \.isOn, for: .valueChanged) { control, isOn, transaction in - control.setOn(isOn, animated: !transaction.uiKit.disablesAnimations) - } + bind(isOn, to: \.boolValue) { control, isOn, transaction in + control.boolValue = isOn + } } - } + + var boolValue: Bool { + set { state = newValue ? .on : .off } + get { state == .on } + } +} #endif diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift new file mode 100644 index 0000000000..305ef278ed --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -0,0 +1,127 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import ConcurrencyExtras +@_spi(Internals) import SwiftNavigation +import AppKit + +/// A protocol used to extend `NSControl, NSMenuItem...`. +@MainActor +public protocol NSTargetActionProtocol: NSObject, Sendable { + var appkitNavigationTarget: AnyObject? { set get } + var appkitNavigationAction: Selector? { set get } +} + +private class NSControlActionHandler: NSObject { + let action: (NSControl) -> Void + + init(action: @escaping (NSControl) -> Void) { + self.action = action + } + + @objc func invokeAction(_ sender: NSControl) { + action(sender) + } +} + +extension NSTargetActionProtocol { + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: ReferenceWritableKeyPath + ) -> ObservationToken { + bind(binding, to: keyPath) { control, newValue, _ in + control[keyPath: keyPath] = newValue + } + } + + private var actionHandler: NSControlActionHandler? { + set { objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } + get { objc_getAssociatedObject(self, #function) as? NSControlActionHandler } + } + + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - set: A closure that is called when the binding's value changes with a weakly-captured + /// control, a new value that can be used to configure the control, and a transaction, which + /// can be used to determine how and if the change should be animated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: KeyPath, + set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void + ) -> ObservationToken { + unbind(keyPath) + let actionHandler = NSControlActionHandler { [weak self] _ in + guard let self else { return } + binding.wrappedValue = self[keyPath: keyPath] + } + self.actionHandler = actionHandler + appkitNavigationTarget = actionHandler + appkitNavigationAction = #selector(NSControlActionHandler.invokeAction(_:)) + + let isSetting = LockIsolated(false) + let token = observe { [weak self] transaction in + guard let self else { return } + isSetting.withValue { $0 = true } + defer { isSetting.withValue { $0 = false } } + set( + self, + binding.wrappedValue, + transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + @UncheckedSendable var uncheckedKeyPath = keyPath + let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in + guard isSetting.withValue({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + } + } + let observationToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + self?.appkitNavigationTarget = nil + self?.appkitNavigationAction = nil + self?.actionHandler = nil + } + token.cancel() + observation.invalidate() + } + observationTokens[keyPath] = observationToken + return observationToken + } + + public func unbind(_ keyPath: KeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } + + var observationTokens: [AnyKeyPath: ObservationToken] { + get { + objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] + ?? [:] + } + set { + objc_setAssociatedObject( + self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } +} + +@MainActor +private let observationTokensKey = malloc(1)! +#endif diff --git a/Sources/AppKitNavigation/Bindings/UITextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift similarity index 58% rename from Sources/AppKitNavigation/Bindings/UITextField.swift rename to Sources/AppKitNavigation/Bindings/NSTextField.swift index 6214680fe9..e5c4370993 100644 --- a/Sources/AppKitNavigation/Bindings/UITextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -1,8 +1,8 @@ -#if canImport(UIKit) && !os(watchOS) - import UIKit +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import SwiftNavigation - @available(iOS 14, tvOS 14, *) - extension UITextField { +extension NSTextField: NSTextViewDelegate { /// Creates a new text field with the specified frame and registers the binding against its /// text. /// @@ -11,8 +11,8 @@ /// - text: The binding to read from for the current text, and write to when the text /// changes. public convenience init(frame: CGRect = .zero, text: UIBinding) { - self.init(frame: frame) - bind(text: text) + self.init(frame: frame) + bind(text: text) } /// Creates a new text field with the specified frame and registers the binding against its @@ -23,8 +23,8 @@ /// - attributedText: The binding to read from for the current text, and write to when the /// attributed text changes. public convenience init(frame: CGRect = .zero, attributedText: UIBinding) { - self.init(frame: frame) - bind(attributedText: attributedText) + self.init(frame: frame) + bind(attributedText: attributedText) } /// Establishes a two-way connection between a binding and the text field's current text. @@ -34,7 +34,7 @@ /// - Returns: A cancel token. @discardableResult public func bind(text: UIBinding) -> ObservationToken { - bind(UIBinding(text), to: \.text, for: .editingChanged) + bind(text, to: \.stringValue) } /// Establishes a two-way connection between a binding and the text field's current text. @@ -44,7 +44,7 @@ /// - Returns: A cancel token. @discardableResult public func bind(attributedText: UIBinding) -> ObservationToken { - bind(UIBinding(attributedText), to: \.attributedText, for: .editingChanged) + bind(attributedText, to: \.attributedStringValue) } /// Establishes a two-way connection between a binding and the text field's current selection. @@ -53,79 +53,101 @@ /// the selected text range changes. /// - Returns: A cancel token. @discardableResult - public func bind(selection: UIBinding) -> ObservationToken { - let editingChangedAction = UIAction { [weak self] _ in - guard let self else { return } - selection.wrappedValue = self.textSelection - } - addAction(editingChangedAction, for: [.editingChanged, .editingDidBegin]) - let editingDidEndAction = UIAction { _ in selection.wrappedValue = nil } - addAction(editingDidEndAction, for: .editingDidEnd) - let token = observe { [weak self] in - guard let self else { return } - textSelection = selection.wrappedValue - } - let observation = observe(\.selectedTextRange) { control, _ in - MainActor._assumeIsolated { - selection.wrappedValue = control.textSelection + public func bind(selection: UIBinding) -> ObservationToken { + let editingChangedAction = NotificationCenter.default.publisher(for: NSTextField.textDidChangeNotification, object: self) + .sink { [weak self] _ in + guard let self else { return } + selection.wrappedValue = self.textSelection + } + let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in selection.wrappedValue = nil } + let token = observe { [weak self] in + guard let self else { return } + textSelection = selection.wrappedValue } - } - let observationToken = ObservationToken { [weak self] in - MainActor._assumeIsolated { - self?.removeAction(editingChangedAction, for: [.editingChanged, .editingDidBegin]) - self?.removeAction(editingDidEndAction, for: .editingDidEnd) + textSelectionObserver = TextSelectionObserver { control in + MainActor._assumeIsolated { + selection.wrappedValue = control.textSelection + } + } + let observationToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + editingChangedAction.cancel() + editingDidEndAction.cancel() + } + token.cancel() + self?.textSelectionObserver = nil + } + observationTokens[\NSTextField.selectedRange] = observationToken + return observationToken + } + + fileprivate var selectedRange: NSRange? { + set { + currentEditor()?.selectedRange = newValue ?? .init(location: 0, length: 0) + } + + get { + currentEditor()?.selectedRange } - token.cancel() - observation.invalidate() - } - observationTokens[\UITextField.selectedTextRange] = observationToken - return observationToken } - fileprivate var textSelection: UITextSelection? { - get { - guard - let textRange = selectedTextRange, - let text - else { - return nil + fileprivate class TextSelectionObserver: NSObject { + let observer: (NSTextField) -> Void + + init(observer: @escaping (NSTextField) -> Void) { + self.observer = observer + } + } + + fileprivate var textSelectionObserver: TextSelectionObserver? { + set { + objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, #function) as? TextSelectionObserver } - let lowerBound = - text.index( - text.startIndex, - offsetBy: offset(from: beginningOfDocument, to: textRange.start), - limitedBy: text.endIndex - ) ?? text.endIndex - let upperBound = - text.index( - text.startIndex, - offsetBy: offset(from: beginningOfDocument, to: textRange.end), - limitedBy: text.endIndex - ) ?? text.endIndex - return UITextSelection(range: lowerBound..( - focus: UIBinding, equals value: Value + focus: UIBinding, equals value: Value ) -> ObservationToken { - self.focusToken?.cancel() - let editingDidBeginAction = UIAction { _ in focus.wrappedValue = value } - let editingDidEndAction = UIAction { _ in - guard focus.wrappedValue == value else { return } - focus.wrappedValue = nil - } - addAction(editingDidBeginAction, for: .editingDidBegin) - addAction(editingDidEndAction, for: [.editingDidEnd, .editingDidEndOnExit]) - let innerToken = observe { [weak self] in - guard let self else { return } - switch (focus.wrappedValue, isFirstResponder) { - case (value, false): - becomeFirstResponder() - case (nil, true): - resignFirstResponder() - default: - break + focusToken?.cancel() + let editingDidBeginAction = NotificationCenter.default.publisher(for: NSTextField.textDidBeginEditingNotification, object: self).sink { _ in + focus.wrappedValue = value + } + + let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in + guard focus.wrappedValue == value else { return } + focus.wrappedValue = nil } - } - let outerToken = ObservationToken { [weak self] in - MainActor._assumeIsolated { - self?.removeAction(editingDidBeginAction, for: .editingDidBegin) - self?.removeAction(editingDidEndAction, for: [.editingDidEnd, .editingDidEndOnExit]) + + let innerToken = observe { [weak self] in + guard let self else { return } + switch (focus.wrappedValue, currentEditor() != nil) { + case (value, false): + becomeFirstResponder() + case (nil, true): + window?.makeFirstResponder(nil) + default: + break + } + } + let outerToken = ObservationToken { + editingDidBeginAction.cancel() + editingDidEndAction.cancel() + innerToken.cancel() } - innerToken.cancel() - } - self.focusToken = outerToken - return outerToken + focusToken = outerToken + return outerToken } /// Binds this text field's focus state to the given Boolean state value. @@ -277,35 +299,37 @@ /// - Returns: A cancel token. @discardableResult public func bind(focus condition: UIBinding) -> ObservationToken { - bind(focus: condition.toOptionalUnit, equals: Bool.Unit()) + bind(focus: condition.toOptionalUnit, equals: Bool.Unit()) } private var focusToken: ObservationToken? { - get { objc_getAssociatedObject(self, Self.focusTokenKey) as? ObservationToken } - set { - objc_setAssociatedObject( - self, Self.focusTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } + get { objc_getAssociatedObject(self, Self.focusTokenKey) as? ObservationToken } + set { + objc_setAssociatedObject( + self, Self.focusTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } } private static let focusTokenKey = malloc(1)! - } +} - /// Represents a selection of text. - /// - /// Like SwiftUI's `TextSelection`, but for UIKit. - public struct UITextSelection: Hashable, Sendable { +/// Represents a selection of text. +/// +/// Like SwiftUI's `TextSelection`, but for UIKit. +public struct AppKitTextSelection: Hashable, Sendable { public var range: Range public init(range: Range) { - self.range = range + self.range = range } + public init(insertionPoint: String.Index) { - self.range = insertionPoint..) { - self.init(frame: frame) - bind(selectedColor: selectedColor) - } - - /// Establishes a two-way connection between a binding and the color well's selected color. - /// - /// - Parameter selectedColor: The binding to read from for the selected color, and write to - /// when the selected color changes. - /// - Returns: A cancel token. - @discardableResult - public func bind(selectedColor: UIBinding) -> ObservationToken { - bind(selectedColor, to: \.selectedColor, for: .valueChanged) - } - } -#endif diff --git a/Sources/AppKitNavigation/Bindings/UIControl.swift b/Sources/AppKitNavigation/Bindings/UIControl.swift deleted file mode 100644 index 2854c166d0..0000000000 --- a/Sources/AppKitNavigation/Bindings/UIControl.swift +++ /dev/null @@ -1,107 +0,0 @@ -#if canImport(UIKit) && !os(watchOS) - import ConcurrencyExtras - @_spi(Internals) import SwiftNavigation - import UIKit - - /// A protocol used to extend `UIControl`. - @MainActor - public protocol UIControlProtocol: UIControl {} - - extension UIControl: UIControlProtocol {} - - @available(iOS 14, tvOS 14, *) - extension UIControlProtocol { - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: ReferenceWritableKeyPath, - for event: UIControl.Event - ) -> ObservationToken { - bind(binding, to: keyPath, for: event) { control, newValue, _ in - control[keyPath: keyPath] = newValue - } - } - - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - set: A closure that is called when the binding's value changes with a weakly-captured - /// control, a new value that can be used to configure the control, and a transaction, which - /// can be used to determine how and if the change should be animated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: KeyPath, - for event: UIControl.Event, - set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void - ) -> ObservationToken { - unbind(keyPath) - let action = UIAction { [weak self] _ in - guard let self else { return } - binding.wrappedValue = self[keyPath: keyPath] - } - addAction(action, for: event) - let isSetting = LockIsolated(false) - let token = observe { [weak self] transaction in - guard let self else { return } - isSetting.withValue { $0 = true } - defer { isSetting.withValue { $0 = false } } - set( - self, - binding.wrappedValue, - transaction.uiKit.animation == nil && !transaction.uiKit.disablesAnimations - ? binding.transaction - : transaction - ) - } - // NB: This key path must only be accessed on the main actor - @UncheckedSendable var uncheckedKeyPath = keyPath - let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in - guard isSetting.withValue({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] - } - } - let observationToken = ObservationToken { [weak self] in - MainActor._assumeIsolated { - self?.removeAction(action, for: .allEvents) - } - token.cancel() - observation.invalidate() - } - observationTokens[keyPath] = observationToken - return observationToken - } - - public func unbind(_ keyPath: KeyPath) { - observationTokens[keyPath]?.cancel() - observationTokens[keyPath] = nil - } - - var observationTokens: [AnyKeyPath: ObservationToken] { - get { - objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] - ?? [:] - } - set { - objc_setAssociatedObject( - self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - } - } - - @MainActor - private let observationTokensKey = malloc(1)! -#endif diff --git a/Sources/AppKitNavigation/Bindings/UIPageControl.swift b/Sources/AppKitNavigation/Bindings/UIPageControl.swift deleted file mode 100644 index 626798fe36..0000000000 --- a/Sources/AppKitNavigation/Bindings/UIPageControl.swift +++ /dev/null @@ -1,28 +0,0 @@ -#if canImport(UIKit) && !os(watchOS) - import UIKit - - @available(iOS 14, tvOS 14, *) - extension UIPageControl { - /// Creates a new page control with the specified frame and registers the binding against the - /// current page. - /// - /// - Parameters: - /// - frame: The frame rectangle for the view, measured in points. - /// - currentPage: The binding to read from for the current page, and write to when the - /// current page changes. - public convenience init(frame: CGRect = .zero, currentPage: UIBinding) { - self.init(frame: frame) - bind(currentPage: currentPage) - } - - /// Establishes a two-way connection between a binding and the page control's current page. - /// - /// - Parameter currentPage: The binding to read from for the current page, and write to when - /// the current page changes. - /// - Returns: A cancel token. - @discardableResult - public func bind(currentPage: UIBinding) -> ObservationToken { - bind(currentPage, to: \.currentPage, for: .valueChanged) - } - } -#endif diff --git a/Sources/AppKitNavigation/Bindings/UISegmentedControl.swift b/Sources/AppKitNavigation/Bindings/UISegmentedControl.swift deleted file mode 100644 index 5c2c9a86a6..0000000000 --- a/Sources/AppKitNavigation/Bindings/UISegmentedControl.swift +++ /dev/null @@ -1,81 +0,0 @@ -#if canImport(UIKit) && !os(watchOS) - import IssueReporting - import UIKit - - @available(iOS 14, tvOS 14, *) - extension UISegmentedControl { - /// Creates a new color well with the specified frame and registers the binding against the - /// selected color. - /// - /// - Parameters: - /// - frame: The frame rectangle for the view, measured in points. - /// - selectedSegment: The binding to read from for the selected color, and write to when the - /// selected color is changes. - public convenience init( - frame: CGRect = .zero, selectedSegment: UIBinding>, - fileID: StaticString = #fileID, - filePath: StaticString = #filePath, - line: UInt = #line, - column: UInt = #column - ) { - self.init(frame: frame) - bind( - selectedSegment: selectedSegment, - fileID: fileID, - filePath: filePath, - line: line, - column: column - ) - } - - /// Establishes a two-way connection between a binding and the color well's selected color. - /// - /// - Parameter selectedSegment: The binding to read from for the selected color, and write to - /// when the selected color changes. - /// - Returns: A cancel token. - @discardableResult - public func bind( - selectedSegment: UIBinding>, - fileID: StaticString = #fileID, - filePath: StaticString = #filePath, - line: UInt = #line, - column: UInt = #column - ) -> ObservationToken { - let fileID = HashableStaticString(rawValue: fileID) - let filePath = HashableStaticString(rawValue: filePath) - return bind( - selectedSegment[fileID: fileID, filePath: filePath, line: line, column: column], - to: \.selectedSegmentIndex, - for: .valueChanged - ) - } - } - - extension RawRepresentable { - fileprivate subscript( - fileID fileID: HashableStaticString, - filePath filePath: HashableStaticString, - line line: UInt, - column column: UInt - ) -> Int { - get { rawValue } - set { - guard let rawRepresentable = Self(rawValue: newValue) - else { - reportIssue( - """ - Raw-representable 'UIBinding<\(Self.self)>' attempted to write an invalid raw value \ - ('\(newValue)'). - """, - fileID: fileID.rawValue, - filePath: filePath.rawValue, - line: line, - column: column - ) - return - } - self = rawRepresentable - } - } - } -#endif diff --git a/Sources/AppKitNavigation/Bindings/UITabBarController.swift b/Sources/AppKitNavigation/Bindings/UITabBarController.swift deleted file mode 100644 index 7b9e6351a1..0000000000 --- a/Sources/AppKitNavigation/Bindings/UITabBarController.swift +++ /dev/null @@ -1,65 +0,0 @@ -#if swift(>=6) && canImport(UIKit) && !os(tvOS) && !os(watchOS) - import IssueReporting - import UIKit - - @available(iOS 18, tvOS 18, visionOS 2, *) - extension UITabBarController { - @discardableResult - public func bind( - selectedTab: UIBinding, - fileID: StaticString = #fileID, - filePath: StaticString = #filePath, - line: UInt = #line, - column: UInt = #column - ) -> ObservationToken { - let token = observe { [weak self] in - guard let self else { return } - guard let identifier = selectedTab.wrappedValue else { - self.selectedTab = nil - return - } - guard let tab = tabs.first(where: { $0.identifier == identifier }) - else { - reportIssue( - """ - Tab bar controller binding attempted to write an invalid identifier ('\(identifier)'). - - Valid identifiers: \(tabs.map(\.identifier)) - """, - fileID: fileID, - filePath: filePath, - line: line, - column: column - ) - self.selectedTab = nil - return - } - self.selectedTab = tab - } - let observation = observe(\.selectedTab) { controller, _ in - MainActor.assumeIsolated { - selectedTab.wrappedValue = controller.selectedTab?.identifier - } - } - let observationToken = ObservationToken { - token.cancel() - observation.invalidate() - } - self.observationToken = observationToken - return observationToken - } - - private var observationToken: ObservationToken? { - get { - objc_getAssociatedObject(self, Self.observationTokenKey) as? ObservationToken - } - set { - objc_setAssociatedObject( - self, Self.observationTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - } - - private static let observationTokenKey = malloc(1)! - } -#endif diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 6952a998b6..bc9c377ea6 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -1,10 +1,10 @@ -#if canImport(UIKit) && !os(watchOS) - import IssueReporting - @_spi(Internals) import SwiftNavigation - import UIKit - import UIKitNavigationShim +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import IssueReporting +@_spi(Internals) import SwiftNavigation +import AppKit +import AppKitNavigationShim - extension UIViewController { +extension NSViewController { /// Presents a view controller modally when a binding to a Boolean value you provide is true. /// /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. @@ -17,11 +17,12 @@ /// controller's content. @discardableResult public func present( - isPresented: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> UIViewController + isPresented: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController ) -> ObservationToken { - present(item: isPresented.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } } /// Presents a view controller modally using the given item as a data source for its content. @@ -39,11 +40,12 @@ /// controller's content. @discardableResult public func present( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> UIViewController + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController ) -> ObservationToken { - present(item: item, id: \.id, onDismiss: onDismiss, content: content) + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } /// Presents a view controller modally using the given item as a data source for its content. @@ -62,11 +64,12 @@ @_disfavoredOverload @discardableResult public func present( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> UIViewController + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController ) -> ObservationToken { - present(item: item, id: \.id, onDismiss: onDismiss, content: content) + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } /// Presents a view controller modally using the given item as a data source for its content. @@ -85,14 +88,15 @@ /// controller's content. @discardableResult public func present( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> UIViewController + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController ) -> ObservationToken { - present(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) - } + present(item: item, id: id, style: style, onDismiss: onDismiss) { + content($0.wrappedValue) + } } /// Presents a view controller modally using the given item as a data source for its content. @@ -112,117 +116,49 @@ @_disfavoredOverload @discardableResult public func present( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> UIViewController + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController ) -> ObservationToken { - destination(item: item, id: id) { $item in - content($item) - } present: { [weak self] child, transaction in - guard let self else { return } - if presentedViewController != nil { - self.dismiss(animated: !transaction.uiKit.disablesAnimations) { + destination(item: item, id: id) { $item in + content($item) + } present: { [weak self] child, transaction in + guard let self else { return } + if presentedViewControllers != nil { + self.dismiss(nil) + onDismiss?() + self.present(child, for: style) + + } else { + self.present(child, for: style) + } + } dismiss: { [weak self] _, transaction in + self?.dismiss(nil) onDismiss?() - self.present(child, animated: !transaction.uiKit.disablesAnimations) - } - } else { - self.present(child, animated: !transaction.uiKit.disablesAnimations) } - } dismiss: { [weak self] _, transaction in - self?.dismiss(animated: !transaction.uiKit.disablesAnimations) { - onDismiss?() - } - } - } - - /// Pushes a view controller onto the receiver's stack when a binding to a Boolean value you - /// provide is true. - /// - /// Like SwiftUI's `navigationDestination(isPresented:)` view modifier, but for UIKit. - /// - /// - Parameters: - /// - isPresented: A binding to a Boolean value that determines whether to push the view - /// controller. - /// - content: A closure that returns the view controller to display onto the receiver's - /// stack. - @discardableResult - public func navigationDestination( - isPresented: UIBinding, - content: @escaping () -> UIViewController - ) -> ObservationToken { - navigationDestination(item: isPresented.toOptionalUnit) { _ in content() } } - /// Pushes a view controller onto the receiver's stack using the given item as a data source for - /// its content. - /// - /// Like SwiftUI's `navigationDestination(item:)` view modifier, but for UIKit. - /// - /// - Parameters: - /// - item: A binding to an optional source of truth for the view controller. When `item` is - /// non-`nil`, the item's content is passed to the `content` closure. You display this - /// content in a view controller that you create that is displayed to the user. - /// - content: A closure that returns the view controller to display onto the receiver's - /// stack. - @discardableResult - public func navigationDestination( - item: UIBinding, - content: @escaping (Item) -> UIViewController - ) -> ObservationToken { - navigationDestination(item: item) { - content($0.wrappedValue) - } + + public enum TransitionStyle { + case sheet + case modalWindow + case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + case custom(NSViewControllerPresentationAnimator) } - /// Pushes a view controller onto the receiver's stack using the given item as a data source for - /// its content. - /// - /// Like SwiftUI's `navigationDestination(item:)` view modifier, but for UIKit. - /// - /// - Parameters: - /// - item: A binding to an optional source of truth for the view controller. When `item` is - /// non-`nil`, the item's content is passed to the `content` closure. You display this - /// content in a view controller that you create that is displayed to the user. - /// - content: A closure that returns the view controller to display onto the receiver's - /// stack. - @_disfavoredOverload - @discardableResult - public func navigationDestination( - item: UIBinding, - content: @escaping (UIBinding) -> UIViewController - ) -> ObservationToken { - destination(item: item) { $item in - content($item) - } present: { [weak self] child, transaction in - guard - let navigationController = self?.navigationController ?? self as? UINavigationController - else { - reportIssue( - """ - Can't present navigation item: "navigationController" is "nil". - """ - ) - return + fileprivate func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { + switch style { + case .sheet: + presentAsSheet(viewControllerToPresent) + case .modalWindow: + presentAsModalWindow(viewControllerToPresent) + case .popover(let rect, let view, let preferredEdge, let behavior): + present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) + case .custom(let animator): + present(viewControllerToPresent, animator: animator) } - navigationController.pushViewController( - child, animated: !transaction.uiKit.disablesAnimations - ) - } dismiss: { [weak self] child, transaction in - guard - let navigationController = self?.navigationController ?? self as? UINavigationController - else { - reportIssue( - """ - Can't dismiss navigation item: "navigationController" is "nil". - """ - ) - return - } - navigationController.popFromViewController( - child, animated: !transaction.uiKit.disablesAnimations - ) - } } /// Presents a view controller when a binding to a Boolean value you provide is true. @@ -239,20 +175,20 @@ /// - dismiss: The closure to execute when dismissing the view controller. @discardableResult public func destination( - isPresented: UIBinding, - content: @escaping () -> UIViewController, - present: @escaping (UIViewController, UITransaction) -> Void, - dismiss: @escaping ( - _ child: UIViewController, - _ transaction: UITransaction - ) -> Void + isPresented: UIBinding, + content: @escaping () -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void ) -> ObservationToken { - destination( - item: isPresented.toOptionalUnit, - content: { _ in content() }, - present: present, - dismiss: dismiss - ) + destination( + item: isPresented.toOptionalUnit, + content: { _ in content() }, + present: present, + dismiss: dismiss + ) } /// Presents a view controller using the given item as a data source for its content. @@ -269,21 +205,21 @@ /// - dismiss: The closure to execute when dismissing the view controller. @discardableResult public func destination( - item: UIBinding, - content: @escaping (UIBinding) -> UIViewController, - present: @escaping (UIViewController, UITransaction) -> Void, - dismiss: @escaping ( - _ child: UIViewController, - _ transaction: UITransaction - ) -> Void + item: UIBinding, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void ) -> ObservationToken { - destination( - item: item, - id: { _ in nil }, - content: content, - present: present, - dismiss: dismiss - ) + destination( + item: item, + id: { _ in nil }, + content: content, + present: present, + dismiss: dismiss + ) } /// Presents a view controller using the given item as a data source for its content. @@ -303,161 +239,112 @@ /// - dismiss: The closure to execute when dismissing the view controller. @discardableResult public func destination( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> UIViewController, - present: @escaping ( - _ child: UIViewController, - _ transaction: UITransaction - ) -> Void, - dismiss: @escaping ( - _ child: UIViewController, - _ transaction: UITransaction - ) -> Void + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void ) -> ObservationToken { - destination( - item: item, - id: { $0[keyPath: id] }, - content: content, - present: present, - dismiss: dismiss - ) + destination( + item: item, + id: { $0[keyPath: id] }, + content: content, + present: present, + dismiss: dismiss + ) } private func destination( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> UIViewController, - present: @escaping ( - _ child: UIViewController, - _ transaction: UITransaction - ) -> Void, - dismiss: @escaping ( - _ child: UIViewController, - _ transaction: UITransaction - ) -> Void + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void ) -> ObservationToken { - let key = UIBindingIdentifier(item) - return observe { [weak self] transaction in - guard let self else { return } - if let unwrappedItem = UIBinding(item) { - if let presented = presentedByID[key] { - guard let presentationID = presented.presentationID, - presentationID != id(unwrappedItem.wrappedValue) - else { - return - } - } - let childController = content(unwrappedItem) - let onDismiss = { [presentationID = id(unwrappedItem.wrappedValue)] in - if let wrappedValue = item.wrappedValue, - presentationID == id(wrappedValue) - { - item.wrappedValue = nil + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let presented = presentedByID[key] { + guard let presentationID = presented.presentationID, + presentationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let childController = content(unwrappedItem) + let onDismiss = { [presentationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + presentationID == id(wrappedValue) { + item.wrappedValue = nil + } + } + childController.onDismiss = onDismiss + + self.presentedByID[key] = Presented(childController, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + present(childController, transaction) + } + } + if hasViewAppeared { + work() + } else { + onViewAppear.append(work) + } + } else if let presented = presentedByID[key] { + if let controller = presented.controller { + dismiss(controller, transaction) + } + self.presentedByID[key] = nil } - } - childController.onDismiss = onDismiss - if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) { - childController.traitOverrides.dismiss = UIDismissAction { _ in - onDismiss() - } - } - self.presentedByID[key] = Presented(childController, id: id(unwrappedItem.wrappedValue)) - let work = { - withUITransaction(transaction) { - present(childController, transaction) - } - } - if hasViewAppeared { - work() - } else { - onViewAppear.append(work) - } - } else if let presented = presentedByID[key] { - if let controller = presented.controller { - dismiss(controller, transaction) - } - self.presentedByID[key] = nil } - } } fileprivate var presentedByID: [UIBindingIdentifier: Presented] { - get { - (objc_getAssociatedObject(self, Self.presentedKey) - as? [UIBindingIdentifier: Presented]) - ?? [:] - } - set { - objc_setAssociatedObject( - self, Self.presentedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } + get { + (objc_getAssociatedObject(self, Self.presentedKey) + as? [UIBindingIdentifier: Presented]) + ?? [:] + } + set { + objc_setAssociatedObject( + self, Self.presentedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } } private static let presentedKey = malloc(1)! - } +} - extension UINavigationController { - @available( - *, deprecated, - message: """ - Use 'self.navigationDestination(isPresented:)' instead of 'self.navigationController?.pushViewController(isPresented:)'. - """ - ) - @discardableResult - public func pushViewController( - isPresented: UIBinding, - content: @escaping () -> UIViewController - ) -> ObservationToken { - navigationDestination(isPresented: isPresented, content: content) - } - - @available( - *, deprecated, - message: """ - Use 'self.navigationDestination(item:)' instead of 'self.navigationController?.pushViewController(item:)'. - """ - ) - @discardableResult - public func pushViewController( - item: UIBinding, - content: @escaping (Item) -> UIViewController - ) -> ObservationToken { - navigationDestination(item: item, content: content) - } - - @available( - *, deprecated, - message: """ - Use 'self.navigationDestination(item:)' instead of 'self.navigationController?.pushViewController(item:)'. - """ - ) - @_disfavoredOverload - @discardableResult - public func pushViewController( - item: UIBinding, - content: @escaping (UIBinding) -> UIViewController - ) -> ObservationToken { - navigationDestination(item: item, content: content) - } - } - - @MainActor - private class Presented { - weak var controller: UIViewController? +@MainActor +private class Presented { + weak var controller: NSViewController? let presentationID: AnyHashable? deinit { - // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to - // deinit alongside it on the main thread. If we use this other places we should force it - // to be a UIViewController as well, to ensure this functionality. - MainActor._assumeIsolated { - self.controller?.dismiss(animated: false) - } + // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to + // deinit alongside it on the main thread. If we use this other places we should force it + // to be a UIViewController as well, to ensure this functionality. + MainActor._assumeIsolated { + self.controller?.dismiss(nil) + } } - init(_ controller: UIViewController, id presentationID: AnyHashable? = nil) { - self.controller = controller - self.presentationID = presentationID + + init(_ controller: NSViewController, id presentationID: AnyHashable? = nil) { + self.controller = controller + self.presentationID = presentationID } - } +} #endif diff --git a/Sources/AppKitNavigation/Navigation/UIAlertController.swift b/Sources/AppKitNavigation/Navigation/UIAlertController.swift index 0151edcdf4..ba24c57eed 100644 --- a/Sources/AppKitNavigation/Navigation/UIAlertController.swift +++ b/Sources/AppKitNavigation/Navigation/UIAlertController.swift @@ -1,87 +1,83 @@ -#if canImport(UIKit) && !os(watchOS) - import UIKit - - @available(iOS 13, *) - @available(macCatalyst 13, *) - @available(macOS, unavailable) - @available(tvOS 13, *) - @available(watchOS, unavailable) - extension UIAlertController { - /// Creates and returns a view controller for displaying an alert using a data description. - /// - /// - Parameters: - /// - state: A data description of the alert. - /// - handler: A closure that is invoked with an action held in `state`. - public convenience init( - state: AlertState, - handler: @escaping (_ action: Action?) -> Void - ) { - self.init( - title: String(state: state.title), - message: state.message.map { String(state: $0) }, - preferredStyle: .alert - ) - for button in state.buttons { - addAction(UIAlertAction(button, action: handler)) - } - } - - /// Creates and returns a view controller for displaying an action sheet using a data - /// description. - /// - /// - Parameters: - /// - state: A data description of the alert. - /// - handler: A closure that is invoked with an action held in `state`. - public convenience init( - state: ConfirmationDialogState, - handler: @escaping (_ action: Action?) -> Void - ) { - self.init( - title: state.titleVisibility == .visible ? String(state: state.title) : nil, - message: state.message.map { String(state: $0) }, - preferredStyle: .actionSheet - ) - for button in state.buttons { - addAction(UIAlertAction(button, action: handler)) - } - } - } - - @available(iOS 13, *) - @available(macCatalyst 13, *) - @available(macOS, unavailable) - @available(tvOS 13, *) - @available(watchOS, unavailable) - extension UIAlertAction.Style { - public init(_ role: ButtonStateRole) { - switch role { - case .cancel: - self = .cancel - case .destructive: - self = .destructive - } - } - } - - @available(iOS 13, *) - @available(macCatalyst 13, *) - @available(macOS, unavailable) - @available(tvOS 13, *) - @available(watchOS, unavailable) - extension UIAlertAction { - public convenience init( - _ button: ButtonState, - action handler: @escaping (_ action: Action?) -> Void - ) { - self.init( - title: String(state: button.label), - style: button.role.map(UIAlertAction.Style.init) ?? .default - ) { _ in - button.withAction(handler) - } - if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { - self.accessibilityLabel = button.label.accessibilityLabel.map { String(state: $0) } - } - } - } +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +// import AppKit +// +// +// extension NSAlert { +// /// Creates and returns a view controller for displaying an alert using a data description. +// /// +// /// - Parameters: +// /// - state: A data description of the alert. +// /// - handler: A closure that is invoked with an action held in `state`. +// public convenience init( +// state: AlertState, +// handler: @escaping (_ action: Action?) -> Void +// ) { +// self.init( +// title: String(state: state.title), +// message: state.message.map { String(state: $0) }, +// preferredStyle: .alert +// ) +// for button in state.buttons { +// addAction(UIAlertAction(button, action: handler)) +// } +// } +// +// /// Creates and returns a view controller for displaying an action sheet using a data +// /// description. +// /// +// /// - Parameters: +// /// - state: A data description of the alert. +// /// - handler: A closure that is invoked with an action held in `state`. +// public convenience init( +// state: ConfirmationDialogState, +// handler: @escaping (_ action: Action?) -> Void +// ) { +// self.init( +// title: state.titleVisibility == .visible ? String(state: state.title) : nil, +// message: state.message.map { String(state: $0) }, +// preferredStyle: .actionSheet +// ) +// for button in state.buttons { +// addAction(UIAlertAction(button, action: handler)) +// } +// } +// } +// +// @available(iOS 13, *) +// @available(macCatalyst 13, *) +// @available(macOS, unavailable) +// @available(tvOS 13, *) +// @available(watchOS, unavailable) +// extension UIAlertAction.Style { +// public init(_ role: ButtonStateRole) { +// switch role { +// case .cancel: +// self = .cancel +// case .destructive: +// self = .destructive +// } +// } +// } +// +// @available(iOS 13, *) +// @available(macCatalyst 13, *) +// @available(macOS, unavailable) +// @available(tvOS 13, *) +// @available(watchOS, unavailable) +// extension UIAlertAction { +// public convenience init( +// _ button: ButtonState, +// action handler: @escaping (_ action: Action?) -> Void +// ) { +// self.init( +// title: String(state: button.label), +// style: button.role.map(UIAlertAction.Style.init) ?? .default +// ) { _ in +// button.withAction(handler) +// } +// if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { +// self.accessibilityLabel = button.label.accessibilityLabel.map { String(state: $0) } +// } +// } +// } #endif diff --git a/Sources/AppKitNavigation/UIKitAnimation.swift b/Sources/AppKitNavigation/UIKitAnimation.swift deleted file mode 100644 index 7e5106edc5..0000000000 --- a/Sources/AppKitNavigation/UIKitAnimation.swift +++ /dev/null @@ -1,144 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - import AppKit - - #if canImport(SwiftUI) - import SwiftUI - #endif - import SwiftNavigation - /// Executes a closure with the specified animation and returns the result. - /// - /// - Parameters: - /// - animation: An animation, set in the ``UITransaction/appKit`` property of the thread's - /// current transaction. - /// - body: A closure to execute. - /// - completion: A completion to run when the animation is complete. - /// - Returns: The result of executing the closure with the specified animation. - @MainActor - public func withAppKitAnimation( - _ animation: AppKitAnimation? = .default, - _ body: () throws -> Result, - completion: (@Sendable (Bool?) -> Void)? = nil - ) rethrows -> Result { - var transaction = UITransaction() - transaction.appKit.animation = animation - if let completion { - transaction.appKit.addAnimationCompletion(completion) - } - return try withUITransaction(transaction, body) - } - - /// The way a view changes over time to create a smooth visual transition from one state to - /// another. - public struct AppKitAnimation: Hashable, Sendable { - fileprivate let framework: Framework - - @MainActor - func perform( - _ body: () throws -> Result, - completion: ((Bool?) -> Void)? = nil - ) rethrows -> Result { - switch framework { - case let .swiftUI(animation): - #if swift(>=6) - if #available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *) { - var result: Swift.Result? - UIView.animate( - with: animation, - changes: { result = Swift.Result(catching: body) }, - completion: completion.map { completion in { completion(true) } } - ) - return try result!._rethrowGet() - } - #endif - _ = animation - fatalError() - - case let .appKit(animation): - var result: Swift.Result? - NSAnimationContext.runAnimationGroup { context in - context.duration = animation.duration - result = Swift.Result(catching: body) - } completionHandler: { - completion?(true) - } - - return try result!._rethrowGet() - - - } - } - - fileprivate enum Framework: Hashable, Sendable { - case appKit(AppKit) - case swiftUI(Animation) - - fileprivate struct AppKit: Hashable, Sendable { - fileprivate var duration: TimeInterval - - func hash(into hasher: inout Hasher) { - hasher.combine(duration) - } - - } - } - } - - extension AppKitAnimation { - - /// Performs am animation using a timing curve corresponding to the motion of a physical spring. - /// - /// A value description of - /// `UIView.animate(withDuration:delay:dampingRatio:velocity:options:animations:completion:)` - /// that can be used with ``withAppKitAnimation(_:_:completion:)``. - /// - /// - Parameters: - /// - duration: The total duration of the animations, measured in seconds. If you specify a - /// negative value or `0`, the changes are made without animating them. - /// - delay: The amount of time (measured in seconds) to wait before beginning the animations. - /// Specify a value of `0` to begin the animations immediately. - /// - dampingRatio: The damping ratio for the spring animation as it approaches its quiescent - /// state. - /// - /// To smoothly decelerate the animation without oscillation, use a value of `1`. Employ a - /// damping ratio closer to zero to increase oscillation. - /// - velocity: The initial spring velocity. For smooth start to the animation, match this - /// value to the view's velocity as it was prior to attachment. - /// - /// A value of `1` corresponds to the total animation distance traversed in one second. For - /// example, if the total animation distance is 200 points and you want the start of the - /// animation to match a view velocity of 100 pt/s, use a value of `0.5`. - /// - options: A mask of options indicating how you want to perform the animations. For a list - /// of valid constants, see `UIView.AnimationOptions`. - /// - Returns: An animation using a timing curve corresponding to the motion of a physical - /// spring. - public static func animate( - withDuration duration: TimeInterval = 0.25 - ) -> Self { - Self( - framework: .appKit( - Framework.AppKit( - duration: duration - ) - ) - ) - } - - - /// Animates changes using the specified SwiftUI animation. - /// - /// - Parameter animation: The animation to use for the changes. - @available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *) - public init(_ animation: Animation) { - self.init(framework: .swiftUI(animation)) - } - - /// A default animation instance. - public static var `default`: Self { - if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) { - return .animate() - } else { - return .animate(withDuration: 0.35) - } - } - } -#endif From 4611a2a737d6570a3db3c34fa34021baaf1a7cb0 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Wed, 14 Aug 2024 18:14:31 +0800 Subject: [PATCH 003/141] Updates --- ...Kit+MinimalObservationViewController.swift | 78 +++++++++++ .../NSControlBindingsViewController.swift | 126 ++++++++++++++++++ Examples/CaseStudies/Internal/CaseStudy.swift | 24 +++- .../CaseStudies/Internal/DetentsHelper.swift | 2 + Examples/CaseStudies/RootView.swift | 2 + .../CaseStudies/SwiftUI/EnumNavigation.swift | 4 +- .../SwiftUI/OptionalNavigation.swift | 4 +- .../UIKit/AnimationsViewController.swift | 2 + .../BasicsNavigationViewController.swift | 2 + .../ConciseEnumNavigationViewController.swift | 2 + .../UIKit/EnumControlsViewController.swift | 2 + .../ErasedNavigationStackController.swift | 2 + .../UIKit/FocusViewController.swift | 2 + .../MinimalObservationViewController.swift | 2 + .../StaticNavigationStackController.swift | 2 + .../UIControlBindingsViewController.swift | 2 + .../CaseStudies/UIKit/UIKitCaseStudies.swift | 2 + .../WiFiFeature/ConnectToNetworkFeature.swift | 2 + .../WiFiFeature/NetworkDetailFeature.swift | 2 + .../WiFiFeature/WiFiSettingsFeature.swift | 2 + .../CaseStudiesTests/Internal/SetUp.swift | 2 + .../NavigationPathTests.swift | 2 + .../NavigationStackTests.swift | 2 + .../CaseStudiesTests/PresentationTests.swift | 2 + .../RuntimeWarningTests.swift | 2 + Examples/Examples.xcodeproj/project.pbxproj | 33 +++++ .../Bindings/NSFontManager.swift | 6 +- .../AppKitNavigation/Bindings/NSSwitch.swift | 2 +- .../Bindings/NSTargetAction.swift | 27 +++- .../Bindings/NSTextField.swift | 16 ++- .../Internal/AssumeIsolated.swift | 48 +++---- .../Internal/ErrorMechanism.swift | 18 +-- .../AppKitNavigation/Internal/Exports.swift | 2 +- .../Internal/ToOptionalUnit.swift | 10 +- .../AppKitNavigation/Navigation/NSAlert.swift | 48 +++++++ .../Navigation/UIAlertController.swift | 83 ------------ Sources/AppKitNavigation/Observe.swift | 7 +- 37 files changed, 423 insertions(+), 153 deletions(-) create mode 100644 Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift create mode 100644 Examples/CaseStudies/AppKit/NSControlBindingsViewController.swift create mode 100644 Sources/AppKitNavigation/Navigation/NSAlert.swift delete mode 100644 Sources/AppKitNavigation/Navigation/UIAlertController.swift diff --git a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift new file mode 100644 index 0000000000..9fcc665639 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift @@ -0,0 +1,78 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation +import ConcurrencyExtras + +class MinimalObservationViewController: NSViewController, AppKitCaseStudy { + let caseStudyTitle = "Minimal observation" + let readMe = """ + This case study demonstrates how to use the 'observe' tool from the library in order to \ + minimally observe changes to an @Observable model. + + To see this, tap the "Increment" button to see that the view re-renders each time you count \ + up. Then, hide the counter and increment again to see that the view does not re-render, even \ + though the count is changing. This shows that only the state accessed inside the trailing \ + closure of 'observe' causes re-renders. + """ + @UIBindable var model = Model() + + override func loadView() { + view = NSView() + } + + override func viewDidLoad() { + super.viewDidLoad() + + let countLabel = NSTextField(labelWithString: "") + let incrementButton = NSButton(title: "Increment", target: self, action: #selector(incrementButtonAction(_:))) + let isCountHiddenSwitch = NSSwitch(isOn: $model.isCountHidden) + let isCountHiddenLabel = NSTextField(labelWithString: "Is count hidden?") + let viewRenderLabel = NSTextField(labelWithString: "") + let stack = NSStackView(views: [ + countLabel, + incrementButton, + isCountHiddenLabel, + isCountHiddenSwitch, + viewRenderLabel, + ]) + stack.orientation = .vertical + stack.alignment = .centerX + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) + let viewRenderCount = LockIsolated(0) + observe { [weak self] in + guard let self else { return } + viewRenderCount.withValue { $0 += 1 } + + if !model.isCountHidden { + // NB: We do not access 'model.count' when the count is hidden, and therefore its mutations + // will not cause a re-render of the view. + countLabel.stringValue = model.count.description + } + countLabel.isHidden = model.isCountHidden + viewRenderLabel.stringValue = "# of view renders: \(viewRenderCount.value)" + } + } + + @objc func incrementButtonAction(_ sender: NSButton) { + model.count += 1 + } + + @Observable + class Model { + var count = 0 + var isCountHidden = false + } +} + +#Preview { + MinimalObservationViewController() +} + +#endif diff --git a/Examples/CaseStudies/AppKit/NSControlBindingsViewController.swift b/Examples/CaseStudies/AppKit/NSControlBindingsViewController.swift new file mode 100644 index 0000000000..fbecc6031d --- /dev/null +++ b/Examples/CaseStudies/AppKit/NSControlBindingsViewController.swift @@ -0,0 +1,126 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class XiblessViewController: NSViewController { + lazy var contentView = View() + + override func loadView() { + view = contentView + } +} + +class NSControlBindingsViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "NSControl bindings" + let readMe = """ + This demonstrates how to use the library's `@UIBinding` and `@UIBindable` property wrappers \ + to bind an observable model to various `NSControl`s. For the most part it works exactly \ + as it does in SwiftUI. Just use `$model` to construct an object that can derive bindings, \ + and then use simple dot-syntax to decide which field you want to derive a binding for. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + contentView.boxType = .custom + contentView.borderWidth = 0 + let colorWell = NSColorWell(color: $model.color) + let datePicker = NSDatePicker(date: $model.date) + let segmentControl = NSSegmentedControl(labels: Model.Segment.allCases.map { "\($0)" }, trackingMode: .selectOne, target: nil, action: nil) + segmentControl.bind(selectedSegment: $model.segment) + let slider = NSSlider(value: $model.sliderValue) + let stepper = NSStepper(value: $model.stepperValue) + let `switch` = NSSwitch(isOn: $model.isOn) + let textField = NSTextField(text: $model.text) + textField.bind(focus: $model.focus, equals: .text) + textField.bind(selection: $model.textSelection) + textField.bezelStyle = .roundedBezel + let label = NSTextField(labelWithString: "") + label.maximumNumberOfLines = 0 + let stack = NSStackView(views: [ + colorWell, + datePicker, + segmentControl, + slider, + stepper, + `switch`, + textField, + label, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false + contentView.contentView?.addSubview(stack) + NSLayoutConstraint.activate([ + stack.topAnchor.constraint(equalTo: view.topAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + stack.bottomAnchor.constraint(equalTo: view.bottomAnchor), + colorWell.heightAnchor.constraint(equalToConstant: 50), + ]) + + observe { [weak self] in + guard let self else { return } + + contentView.fillColor = model.color + + let textSelection = model.textSelection.map { + self.model.text.range(for: $0.range) + } + + label.stringValue = """ + MyModel( + color: \(model.color.description), + date: \(model.date), + focus: \(model.focus.map(String.init(describing:)) ?? "nil"), + isOn: \(model.isOn), + segment: \(model.segment), + sliderValue: \(model.sliderValue), + stepperValue: \(model.stepperValue), + text: \(model.text.debugDescription), + textSelection: \(textSelection.map(String.init(describing:)) ?? "nil") + ) + """ + } + } + + @MainActor + @Observable + final class Model: HashableObject { + var color: NSColor = .windowBackgroundColor + var date = Date() + var focus: Focus? + var isOn = false + var segment = Segment.columnA + var sliderValue: Float = 0.5 + var stepperValue: Double = 5 + var text = "Blob" + var textSelection: AppKitTextSelection? + + enum Focus: Hashable { + case attributedText + case text + } + + enum Segment: Int, CaseIterable { + case columnA + case columnB + } + } +} + +extension String { + fileprivate func range(for range: Range) -> Range { + distance( + from: startIndex, to: range.lowerBound + ) ..< distance(from: startIndex, to: range.upperBound) + } +} + + +#Preview(traits: .fixedLayout(width: 500, height: 800)) { + NSControlBindingsViewController() +} + + +#endif diff --git a/Examples/CaseStudies/Internal/CaseStudy.swift b/Examples/CaseStudies/Internal/CaseStudy.swift index 2f2a60cffe..9f7a8d1167 100644 --- a/Examples/CaseStudies/Internal/CaseStudy.swift +++ b/Examples/CaseStudies/Internal/CaseStudy.swift @@ -9,7 +9,18 @@ protocol CaseStudy { var isPresentedInSheet: Bool { get } } protocol SwiftUICaseStudy: CaseStudy, View {} +#if canImport(UIKit) && !os(watchOS) protocol UIKitCaseStudy: CaseStudy, UIViewController {} +extension UIKitCaseStudy { + var usesOwnLayout: Bool { true } +} +#endif +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +protocol AppKitCaseStudy: CaseStudy, NSViewController {} +extension AppKitCaseStudy { + var usesOwnLayout: Bool { true } +} +#endif extension CaseStudy { var caseStudyNavigationTitle: String { caseStudyTitle } @@ -18,9 +29,7 @@ extension CaseStudy { extension SwiftUICaseStudy { var usesOwnLayout: Bool { false } } -extension UIKitCaseStudy { - var usesOwnLayout: Bool { true } -} + @resultBuilder @MainActor @@ -31,10 +40,12 @@ enum CaseStudyViewBuilder { static func buildExpression(_ caseStudy: some SwiftUICaseStudy) -> some View { SwiftUICaseStudyButton(caseStudy: caseStudy) } +#if canImport(UIKit) && !os(watchOS) @ViewBuilder static func buildExpression(_ caseStudy: some UIKitCaseStudy) -> some View { UIKitCaseStudyButton(caseStudy: caseStudy) } + #endif static func buildPartialBlock(first: some View) -> some View { first } @@ -69,7 +80,7 @@ struct SwiftUICaseStudyButton: View { } } } - +#if canImport(UIKit) && !os(watchOS) struct UIKitCaseStudyButton: View { let caseStudy: C @State var isPresented = false @@ -116,7 +127,7 @@ extension UINavigationController { return self } } - +#endif struct CaseStudyModifier: ViewModifier { let caseStudy: C @State var isAboutPresented = false @@ -209,7 +220,7 @@ private struct DemoCaseStudy: SwiftUICaseStudy { Text("Hello!") } } - +#if canImport(UIKit) && !os(watchOS) private class DemoCaseStudyController: UIViewController, UIKitCaseStudy { let caseStudyTitle = "Demo Case Study" let readMe = """ @@ -218,3 +229,4 @@ private class DemoCaseStudyController: UIViewController, UIKitCaseStudy { Enjoy! """ } +#endif diff --git a/Examples/CaseStudies/Internal/DetentsHelper.swift b/Examples/CaseStudies/Internal/DetentsHelper.swift index 6f9ed41449..a782d5c297 100644 --- a/Examples/CaseStudies/Internal/DetentsHelper.swift +++ b/Examples/CaseStudies/Internal/DetentsHelper.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKit extension UIViewController { @@ -10,3 +11,4 @@ extension UIViewController { } } } +#endif diff --git a/Examples/CaseStudies/RootView.swift b/Examples/CaseStudies/RootView.swift index 81287338db..d552ddf930 100644 --- a/Examples/CaseStudies/RootView.swift +++ b/Examples/CaseStudies/RootView.swift @@ -8,9 +8,11 @@ struct RootView: View { NavigationLink("SwiftUI") { SwiftUICaseStudiesView() } +#if canImport(UIKit) && !os(watchOS) NavigationLink("UIKit") { UIKitCaseStudiesView() } +#endif } .navigationTitle("Case studies") } diff --git a/Examples/CaseStudies/SwiftUI/EnumNavigation.swift b/Examples/CaseStudies/SwiftUI/EnumNavigation.swift index c3769345df..9e5750bee4 100644 --- a/Examples/CaseStudies/SwiftUI/EnumNavigation.swift +++ b/Examples/CaseStudies/SwiftUI/EnumNavigation.swift @@ -70,7 +70,7 @@ struct EnumNavigation: SwiftUICaseStudy { .navigationTitle("Sheet with payload") .presentationDetents([.medium]) } - +#if canImport(UIKit) && !os(watchOS) Button("Cover is presented: \(destination.is(\.fullScreenCover) ? "✅" : "❌")") { destination = .fullScreenCover(.random(in: 1...1_000)) } @@ -92,7 +92,7 @@ struct EnumNavigation: SwiftUICaseStudy { } } } - + #endif Button("Popover is presented: \(destination.is(\.popover) ? "✅" : "❌")") { destination = .popover(.random(in: 1...1_000)) } diff --git a/Examples/CaseStudies/SwiftUI/OptionalNavigation.swift b/Examples/CaseStudies/SwiftUI/OptionalNavigation.swift index 1d6b0160ac..2378d76283 100644 --- a/Examples/CaseStudies/SwiftUI/OptionalNavigation.swift +++ b/Examples/CaseStudies/SwiftUI/OptionalNavigation.swift @@ -57,7 +57,7 @@ struct OptionalNavigation: SwiftUICaseStudy { .navigationTitle("Sheet") .presentationDetents([.medium]) } - +#if canImport(UIKit) && !os(watchOS) Button("Cover is presented: \(fullScreenCover != nil ? "✅" : "❌")") { fullScreenCover = .random(in: 1...1_000) } @@ -79,7 +79,7 @@ struct OptionalNavigation: SwiftUICaseStudy { } } } - + #endif Button("Popover is presented: \(popover != nil ? "✅" : "❌")") { popover = .random(in: 1...1_000) } diff --git a/Examples/CaseStudies/UIKit/AnimationsViewController.swift b/Examples/CaseStudies/UIKit/AnimationsViewController.swift index d06f6c9116..664a35855c 100644 --- a/Examples/CaseStudies/UIKit/AnimationsViewController.swift +++ b/Examples/CaseStudies/UIKit/AnimationsViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKit import UIKitNavigation @@ -89,3 +90,4 @@ class AnimationsViewController: UIViewController, UIKitCaseStudy { #Preview { AnimationsViewController() } +#endif diff --git a/Examples/CaseStudies/UIKit/BasicsNavigationViewController.swift b/Examples/CaseStudies/UIKit/BasicsNavigationViewController.swift index 6df4ef23ad..85433562c2 100644 --- a/Examples/CaseStudies/UIKit/BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/UIKit/BasicsNavigationViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKit import UIKitNavigation @@ -119,3 +120,4 @@ class BasicsNavigationViewController: UIViewController, UIKitCaseStudy { rootViewController: BasicsNavigationViewController() ) } +#endif diff --git a/Examples/CaseStudies/UIKit/ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/UIKit/ConciseEnumNavigationViewController.swift index 6b022f528d..c66bdb9d31 100644 --- a/Examples/CaseStudies/UIKit/ConciseEnumNavigationViewController.swift +++ b/Examples/CaseStudies/UIKit/ConciseEnumNavigationViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKit import UIKitNavigation @@ -134,3 +135,4 @@ class ConciseEnumNavigationViewController: UIViewController, UIKitCaseStudy { rootViewController: BasicsNavigationViewController() ) } +#endif diff --git a/Examples/CaseStudies/UIKit/EnumControlsViewController.swift b/Examples/CaseStudies/UIKit/EnumControlsViewController.swift index 0348a3e8c4..26919741aa 100644 --- a/Examples/CaseStudies/UIKit/EnumControlsViewController.swift +++ b/Examples/CaseStudies/UIKit/EnumControlsViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKit import UIKitNavigation @@ -111,3 +112,4 @@ extension Int { set { self = Int(newValue) } } } +#endif diff --git a/Examples/CaseStudies/UIKit/ErasedNavigationStackController.swift b/Examples/CaseStudies/UIKit/ErasedNavigationStackController.swift index c77aae3e3d..d7bb43b6d8 100644 --- a/Examples/CaseStudies/UIKit/ErasedNavigationStackController.swift +++ b/Examples/CaseStudies/UIKit/ErasedNavigationStackController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKit import UIKitNavigation @@ -258,3 +259,4 @@ private class BoolFeatureViewController: UIViewController { #Preview { ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) } +#endif diff --git a/Examples/CaseStudies/UIKit/FocusViewController.swift b/Examples/CaseStudies/UIKit/FocusViewController.swift index 8e6d4cb59d..20243756d6 100644 --- a/Examples/CaseStudies/UIKit/FocusViewController.swift +++ b/Examples/CaseStudies/UIKit/FocusViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKit import UIKitNavigation @@ -130,3 +131,4 @@ class FocusViewController: UIViewController, UIKitCaseStudy { #Preview { FocusViewController() } +#endif diff --git a/Examples/CaseStudies/UIKit/MinimalObservationViewController.swift b/Examples/CaseStudies/UIKit/MinimalObservationViewController.swift index 887eebf62e..99655a4a7e 100644 --- a/Examples/CaseStudies/UIKit/MinimalObservationViewController.swift +++ b/Examples/CaseStudies/UIKit/MinimalObservationViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import ConcurrencyExtras import UIKit import UIKitNavigation @@ -76,3 +77,4 @@ class MinimalObservationViewController: UIViewController, UIKitCaseStudy { rootViewController: MinimalObservationViewController() ) } +#endif diff --git a/Examples/CaseStudies/UIKit/StaticNavigationStackController.swift b/Examples/CaseStudies/UIKit/StaticNavigationStackController.swift index 54128d9a25..ed5d72b896 100644 --- a/Examples/CaseStudies/UIKit/StaticNavigationStackController.swift +++ b/Examples/CaseStudies/UIKit/StaticNavigationStackController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKit import UIKitNavigation @@ -172,3 +173,4 @@ private class FeatureViewController: UIViewController { #Preview { StaticNavigationStackController() } +#endif diff --git a/Examples/CaseStudies/UIKit/UIControlBindingsViewController.swift b/Examples/CaseStudies/UIKit/UIControlBindingsViewController.swift index f9a2fe907c..9995dd4c0b 100644 --- a/Examples/CaseStudies/UIKit/UIControlBindingsViewController.swift +++ b/Examples/CaseStudies/UIKit/UIControlBindingsViewController.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKit import UIKitNavigation @@ -127,3 +128,4 @@ extension String { rootViewController: UIControlBindingsViewController() ) } +#endif diff --git a/Examples/CaseStudies/UIKit/UIKitCaseStudies.swift b/Examples/CaseStudies/UIKit/UIKitCaseStudies.swift index f4b47e72a1..6751d3439e 100644 --- a/Examples/CaseStudies/UIKit/UIKitCaseStudies.swift +++ b/Examples/CaseStudies/UIKit/UIKitCaseStudies.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import SwiftUINavigation @@ -38,3 +39,4 @@ struct UIKitCaseStudiesView: View { UIKitCaseStudiesView() } } +#endif diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift index fee0ef6472..fe305a2748 100644 --- a/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift +++ b/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKitNavigation import XCTestDynamicOverlay @@ -109,3 +110,4 @@ final class ConnectToNetworkViewController: UIViewController { ) } } +#endif diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift index 3255e01d04..124b64124c 100644 --- a/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift +++ b/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKitNavigation import XCTestDynamicOverlay @@ -97,3 +98,4 @@ final class NetworkDetailViewController: UIViewController { ) } } +#endif diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift index 3fb9c068c7..a025d7855e 100644 --- a/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift +++ b/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import SwiftUI import UIKitNavigation @@ -309,3 +310,4 @@ extension NSDiffableDataSourceSnapshot< } } } +#endif diff --git a/Examples/CaseStudiesTests/Internal/SetUp.swift b/Examples/CaseStudiesTests/Internal/SetUp.swift index 8eb7a5a9fc..432aacbfb1 100644 --- a/Examples/CaseStudiesTests/Internal/SetUp.swift +++ b/Examples/CaseStudiesTests/Internal/SetUp.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKit import XCTest @@ -16,3 +17,4 @@ extension XCTestCase { try await Task.sleep(for: .milliseconds(100)) } } +#endif diff --git a/Examples/CaseStudiesTests/NavigationPathTests.swift b/Examples/CaseStudiesTests/NavigationPathTests.swift index f9604841a4..6014c6ce09 100644 --- a/Examples/CaseStudiesTests/NavigationPathTests.swift +++ b/Examples/CaseStudiesTests/NavigationPathTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) @_spi(Internals) import SwiftNavigation import UIKitNavigation import XCTest @@ -644,3 +645,4 @@ private struct User: Hashable, Codable { static let mangledTypeName = "21UIKitCaseStudiesTests014NavigationPathD0C10$10685e7e0yXZ10$10685e7ecyXZ4UserV" } +#endif diff --git a/Examples/CaseStudiesTests/NavigationStackTests.swift b/Examples/CaseStudiesTests/NavigationStackTests.swift index e504e94c33..d4a9c05884 100644 --- a/Examples/CaseStudiesTests/NavigationStackTests.swift +++ b/Examples/CaseStudiesTests/NavigationStackTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKitNavigation import XCTest @@ -316,3 +317,4 @@ private final class ChildViewController: UIViewController { } } } +#endif diff --git a/Examples/CaseStudiesTests/PresentationTests.swift b/Examples/CaseStudiesTests/PresentationTests.swift index d318c35552..ff453ba76a 100644 --- a/Examples/CaseStudiesTests/PresentationTests.swift +++ b/Examples/CaseStudiesTests/PresentationTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKitNavigation import XCTest @@ -496,3 +497,4 @@ private class BasicViewController: UIViewController { } } } +#endif diff --git a/Examples/CaseStudiesTests/RuntimeWarningTests.swift b/Examples/CaseStudiesTests/RuntimeWarningTests.swift index 0730982b3c..7d80bb2bad 100644 --- a/Examples/CaseStudiesTests/RuntimeWarningTests.swift +++ b/Examples/CaseStudiesTests/RuntimeWarningTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKitNavigation import XCTest @@ -142,3 +143,4 @@ final class RuntimeWarningTests: XCTestCase { try await setUp(controller: vc) } } +#endif diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index 46455e484b..9a7069ae89 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -52,6 +52,9 @@ CADCA3662C1CE8BE00DE645F /* CaseStudy.swift in Sources */ = {isa = PBXBuildFile; fileRef = CADCA3652C1CE8BE00DE645F /* CaseStudy.swift */; }; DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC6A8410291F227400B3F6C9 /* SynchronizedBindings.swift */; }; DC86E8712C208D8D003C0EC9 /* Text+Template.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC86E8702C208D8A003C0EC9 /* Text+Template.swift */; }; + E9836D922C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */; }; + E9836D942C6CA07300FC6EFD /* AppKitNavigation in Frameworks */ = {isa = PBXBuildFile; productRef = E9836D932C6CA07300FC6EFD /* AppKitNavigation */; }; + E9836D962C6CADBB00FC6EFD /* NSControlBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D952C6CADBB00FC6EFD /* NSControlBindingsViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -110,6 +113,8 @@ DC5EB9D32C0525FA0034B757 /* NavigationStackTests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NavigationStackTests.swift; sourceTree = ""; }; DC6A8410291F227400B3F6C9 /* SynchronizedBindings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SynchronizedBindings.swift; sourceTree = ""; }; DC86E8702C208D8A003C0EC9 /* Text+Template.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Text+Template.swift"; sourceTree = ""; }; + E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+MinimalObservationViewController.swift"; sourceTree = ""; }; + E9836D952C6CADBB00FC6EFD /* NSControlBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSControlBindingsViewController.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -130,6 +135,7 @@ CA48F2FA2C49645100BE2C3C /* SwiftUINavigation in Frameworks */, CA48F3052C49650F00BE2C3C /* Tagged in Frameworks */, CA48F2FC2C49645100BE2C3C /* UIKitNavigation in Frameworks */, + E9836D942C6CA07300FC6EFD /* AppKitNavigation in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -194,6 +200,7 @@ CA9D70492C1F642A003B672A /* Internal */, CADCA3642C1CE80B00DE645F /* SwiftUI */, CA9D704A2C1F6431003B672A /* UIKit */, + E9836D902C6C9E3000FC6EFD /* AppKit */, ); path = CaseStudies; sourceTree = ""; @@ -274,6 +281,15 @@ path = Internal; sourceTree = ""; }; + E9836D902C6C9E3000FC6EFD /* AppKit */ = { + isa = PBXGroup; + children = ( + E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */, + E9836D952C6CADBB00FC6EFD /* NSControlBindingsViewController.swift */, + ); + path = AppKit; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -316,6 +332,7 @@ CA48F3012C49650100BE2C3C /* IdentifiedCollections */, CA48F3042C49650F00BE2C3C /* Tagged */, CA48F3072C49651700BE2C3C /* ConcurrencyExtras */, + E9836D932C6CA07300FC6EFD /* AppKitNavigation */, ); productName = CaseStudies; productReference = CA473804272F0D330012CAC3 /* CaseStudies.app */; @@ -432,6 +449,7 @@ buildActionMask = 2147483647; files = ( CABE9FC1272F2C0000AFC150 /* EnumNavigation.swift in Sources */, + E9836D922C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift in Sources */, DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */, CA9D70502C1FB431003B672A /* StaticNavigationStackController.swift in Sources */, CA473837272F0D860012CAC3 /* FactClient.swift in Sources */, @@ -441,6 +459,7 @@ CA473836272F0D860012CAC3 /* CaseStudiesApp.swift in Sources */, CA473834272F0D860012CAC3 /* RootView.swift in Sources */, CA3D0E322C20B27B00CCF7CD /* ConnectToNetworkFeature.swift in Sources */, + E9836D962C6CADBB00FC6EFD /* NSControlBindingsViewController.swift in Sources */, CA3D0E332C20B27B00CCF7CD /* NetworkDetailFeature.swift in Sources */, CA3D0E342C20B27B00CCF7CD /* Network.swift in Sources */, CA3D0E352C20B27B00CCF7CD /* WiFiSettingsFeature.swift in Sources */, @@ -683,6 +702,8 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.CaseStudies; PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SUPPORTS_MACCATALYST = NO; SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; SWIFT_VERSION = 5.0; @@ -713,6 +734,8 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.CaseStudies; PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SUPPORTS_MACCATALYST = NO; SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -725,6 +748,7 @@ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GCC_C_LANGUAGE_STANDARD = gnu17; @@ -734,6 +758,8 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.CaseStudiesTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SUPPORTS_MACCATALYST = YES; SWIFT_ACTIVE_COMPILATION_CONDITIONS = "DEBUG $(inherited)"; SWIFT_EMIT_LOC_STRINGS = NO; SWIFT_VERSION = 5.0; @@ -748,6 +774,7 @@ ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES; BUNDLE_LOADER = "$(TEST_HOST)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++20"; + "CODE_SIGN_IDENTITY[sdk=macosx*]" = "-"; CODE_SIGN_STYLE = Automatic; CURRENT_PROJECT_VERSION = 1; GCC_C_LANGUAGE_STANDARD = gnu17; @@ -757,6 +784,8 @@ MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.CaseStudiesTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SUPPORTS_MACCATALYST = YES; SWIFT_EMIT_LOC_STRINGS = NO; SWIFT_VERSION = 5.0; TARGETED_DEVICE_FAMILY = "1,2"; @@ -868,6 +897,10 @@ package = CA48F3062C49651700BE2C3C /* XCRemoteSwiftPackageReference "swift-concurrency-extras" */; productName = ConcurrencyExtras; }; + E9836D932C6CA07300FC6EFD /* AppKitNavigation */ = { + isa = XCSwiftPackageProductDependency; + productName = AppKitNavigation; + }; /* End XCSwiftPackageProductDependency section */ }; rootObject = CA47378C272F08EF0012CAC3 /* Project object */; diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 373b40f34d..85a5cd29d2 100644 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -13,12 +13,14 @@ extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { get { appkitNavigationDelegate.action } } + private static let appkitNavigationDelegateKey = malloc(1)! + private var appkitNavigationDelegate: Delegate { set { - objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + objc_setAssociatedObject(self, Self.appkitNavigationDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { - if let delegate = objc_getAssociatedObject(self, #function) as? Delegate { + if let delegate = objc_getAssociatedObject(self, Self.appkitNavigationDelegateKey) as? Delegate { return delegate } else { let delegate = Delegate() diff --git a/Sources/AppKitNavigation/Bindings/NSSwitch.swift b/Sources/AppKitNavigation/Bindings/NSSwitch.swift index 21b752be18..47f4eead06 100644 --- a/Sources/AppKitNavigation/Bindings/NSSwitch.swift +++ b/Sources/AppKitNavigation/Bindings/NSSwitch.swift @@ -26,7 +26,7 @@ extension NSSwitch { } } - var boolValue: Bool { + @objc var boolValue: Bool { set { state = newValue ? .on : .off } get { state == .on } } diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift index 305ef278ed..295ff6b670 100644 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -10,18 +10,28 @@ public protocol NSTargetActionProtocol: NSObject, Sendable { var appkitNavigationAction: Selector? { set get } } -private class NSControlActionHandler: NSObject { +@MainActor +internal class NSTargetActionHandler: NSObject { let action: (NSControl) -> Void + var originTarget: AnyObject? + + var originAction: Selector? + init(action: @escaping (NSControl) -> Void) { self.action = action } @objc func invokeAction(_ sender: NSControl) { + if let originTarget, let originAction { + NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) + } action(sender) + } } + extension NSTargetActionProtocol { /// Establishes a two-way connection between a source of truth and a property of this control. /// @@ -40,9 +50,11 @@ extension NSTargetActionProtocol { } } - private var actionHandler: NSControlActionHandler? { - set { objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - get { objc_getAssociatedObject(self, #function) as? NSControlActionHandler } + + + internal var actionHandler: NSTargetActionHandler? { + set { objc_setAssociatedObject(self, actionHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } + get { objc_getAssociatedObject(self, actionHandlerKey) as? NSTargetActionHandler } } /// Establishes a two-way connection between a source of truth and a property of this control. @@ -62,13 +74,13 @@ extension NSTargetActionProtocol { set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObservationToken { unbind(keyPath) - let actionHandler = NSControlActionHandler { [weak self] _ in + let actionHandler = NSTargetActionHandler { [weak self] _ in guard let self else { return } binding.wrappedValue = self[keyPath: keyPath] } self.actionHandler = actionHandler appkitNavigationTarget = actionHandler - appkitNavigationAction = #selector(NSControlActionHandler.invokeAction(_:)) + appkitNavigationAction = #selector(NSTargetActionHandler.invokeAction(_:)) let isSetting = LockIsolated(false) let token = observe { [weak self] transaction in @@ -124,4 +136,7 @@ extension NSTargetActionProtocol { @MainActor private let observationTokensKey = malloc(1)! +@MainActor +private let actionHandlerKey = malloc(1)! + #endif diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index e5c4370993..64d1c0de7a 100644 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -69,11 +69,12 @@ extension NSTextField: NSTextViewDelegate { selection.wrappedValue = control.textSelection } } + let observationToken = ObservationToken { [weak self] in - MainActor._assumeIsolated { - editingChangedAction.cancel() - editingDidEndAction.cancel() - } +// MainActor._assumeIsolated { + editingChangedAction.cancel() + editingDidEndAction.cancel() +// } token.cancel() self?.textSelectionObserver = nil } @@ -99,12 +100,13 @@ extension NSTextField: NSTextViewDelegate { } } - fileprivate var textSelectionObserver: TextSelectionObserver? { + private static let textSelectionObserverKey = malloc(1)! + private var textSelectionObserver: TextSelectionObserver? { set { - objc_setAssociatedObject(self, #function, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + objc_setAssociatedObject(self, Self.textSelectionObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { - objc_getAssociatedObject(self, #function) as? TextSelectionObserver + objc_getAssociatedObject(self, Self.textSelectionObserverKey) as? TextSelectionObserver } } diff --git a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift index fea107e3ae..9a7465a99f 100644 --- a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift +++ b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift @@ -1,30 +1,30 @@ import Foundation extension MainActor { - // NB: This functionality was not back-deployed in Swift 5.9 - static func _assumeIsolated( - _ operation: @MainActor () throws -> T, - file: StaticString = #fileID, - line: UInt = #line - ) rethrows -> T { - #if swift(<5.10) - typealias YesActor = @MainActor () throws -> T - typealias NoActor = () throws -> T + // NB: This functionality was not back-deployed in Swift 5.9 + static func _assumeIsolated( + _ operation: @MainActor () throws -> T, + file: StaticString = #fileID, + line: UInt = #line + ) rethrows -> T { + #if swift(<5.10) + typealias YesActor = @MainActor () throws -> T + typealias NoActor = () throws -> T - guard Thread.isMainThread else { - fatalError( - "Incorrect actor executor assumption; Expected same executor as \(self).", - file: file, - line: line - ) - } + guard Thread.isMainThread else { + fatalError( + "Incorrect actor executor assumption; Expected same executor as \(self).", + file: file, + line: line + ) + } - return try withoutActuallyEscaping(operation) { (_ fn: @escaping YesActor) throws -> T in - let rawFn = unsafeBitCast(fn, to: NoActor.self) - return try rawFn() - } - #else - return try assumeIsolated(operation, file: file, line: line) - #endif - } + return try withoutActuallyEscaping(operation) { (_ fn: @escaping YesActor) throws -> T in + let rawFn = unsafeBitCast(fn, to: NoActor.self) + return try rawFn() + } + #else + return try assumeIsolated(operation, file: file, line: line) + #endif + } } diff --git a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift index d527e73ca7..1ec4c47b0a 100644 --- a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift +++ b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift @@ -1,20 +1,20 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - @rethrows - protocol _ErrorMechanism { +@rethrows +protocol _ErrorMechanism { associatedtype Output func get() throws -> Output - } +} - extension _ErrorMechanism { +extension _ErrorMechanism { func _rethrowError() rethrows -> Never { - _ = try _rethrowGet() - fatalError() + _ = try _rethrowGet() + fatalError() } func _rethrowGet() rethrows -> Output { - return try get() + return try get() } - } +} - extension Result: _ErrorMechanism {} +extension Result: _ErrorMechanism {} #endif diff --git a/Sources/AppKitNavigation/Internal/Exports.swift b/Sources/AppKitNavigation/Internal/Exports.swift index 6f94b2acad..554225adc1 100644 --- a/Sources/AppKitNavigation/Internal/Exports.swift +++ b/Sources/AppKitNavigation/Internal/Exports.swift @@ -1,3 +1,3 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - @_exported import SwiftNavigation +@_exported import SwiftNavigation #endif diff --git a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift index bbe60acbac..a11cfaaf1d 100644 --- a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift +++ b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift @@ -1,12 +1,12 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - extension Bool { +extension Bool { struct Unit: Hashable, Identifiable { - var id: Unit { self } + var id: Unit { self } } var toOptionalUnit: Unit? { - get { self ? Unit() : nil } - set { self = newValue != nil } + get { self ? Unit() : nil } + set { self = newValue != nil } } - } +} #endif diff --git a/Sources/AppKitNavigation/Navigation/NSAlert.swift b/Sources/AppKitNavigation/Navigation/NSAlert.swift new file mode 100644 index 0000000000..09229b6e57 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NSAlert.swift @@ -0,0 +1,48 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSAlert { + /// Creates and returns a view controller for displaying an alert using a data description. + /// + /// - Parameters: + /// - state: A data description of the alert. + /// - handler: A closure that is invoked with an action held in `state`. + public convenience init( + state: AlertState, + handler: @escaping (_ action: Action?) -> Void + ) { + self.init() + self.messageText = String(state: state.title) + state.message.map { self.informativeText = String(state: $0) } + + for button in state.buttons { + addButton(button, action: handler) + } + } +} + +extension NSAlert { + public func addButton( + _ buttonState: ButtonState, + action handler: @escaping (_ action: Action?) -> Void + ) { + let button = addButton(withTitle: String(state: buttonState.label)) + + let actionHandler = NSTargetActionHandler { _ in + buttonState.withAction(handler) + } + actionHandler.originTarget = button.target + actionHandler.originAction = button.action + button.target = actionHandler + button.action = #selector(NSTargetActionHandler.invokeAction(_:)) + button.actionHandler = actionHandler + if buttonState.role == .destructive, #available(macOS 11.0, *) { + button.hasDestructiveAction = true + } + if buttonState.role == .cancel { + button.keyEquivalent = "\u{1b}" + } +// self.accessibilityLabel = button.label.accessibilityLabel.map { String(state: $0) } + } +} +#endif diff --git a/Sources/AppKitNavigation/Navigation/UIAlertController.swift b/Sources/AppKitNavigation/Navigation/UIAlertController.swift deleted file mode 100644 index ba24c57eed..0000000000 --- a/Sources/AppKitNavigation/Navigation/UIAlertController.swift +++ /dev/null @@ -1,83 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -// import AppKit -// -// -// extension NSAlert { -// /// Creates and returns a view controller for displaying an alert using a data description. -// /// -// /// - Parameters: -// /// - state: A data description of the alert. -// /// - handler: A closure that is invoked with an action held in `state`. -// public convenience init( -// state: AlertState, -// handler: @escaping (_ action: Action?) -> Void -// ) { -// self.init( -// title: String(state: state.title), -// message: state.message.map { String(state: $0) }, -// preferredStyle: .alert -// ) -// for button in state.buttons { -// addAction(UIAlertAction(button, action: handler)) -// } -// } -// -// /// Creates and returns a view controller for displaying an action sheet using a data -// /// description. -// /// -// /// - Parameters: -// /// - state: A data description of the alert. -// /// - handler: A closure that is invoked with an action held in `state`. -// public convenience init( -// state: ConfirmationDialogState, -// handler: @escaping (_ action: Action?) -> Void -// ) { -// self.init( -// title: state.titleVisibility == .visible ? String(state: state.title) : nil, -// message: state.message.map { String(state: $0) }, -// preferredStyle: .actionSheet -// ) -// for button in state.buttons { -// addAction(UIAlertAction(button, action: handler)) -// } -// } -// } -// -// @available(iOS 13, *) -// @available(macCatalyst 13, *) -// @available(macOS, unavailable) -// @available(tvOS 13, *) -// @available(watchOS, unavailable) -// extension UIAlertAction.Style { -// public init(_ role: ButtonStateRole) { -// switch role { -// case .cancel: -// self = .cancel -// case .destructive: -// self = .destructive -// } -// } -// } -// -// @available(iOS 13, *) -// @available(macCatalyst 13, *) -// @available(macOS, unavailable) -// @available(tvOS 13, *) -// @available(watchOS, unavailable) -// extension UIAlertAction { -// public convenience init( -// _ button: ButtonState, -// action handler: @escaping (_ action: Action?) -> Void -// ) { -// self.init( -// title: String(state: button.label), -// style: button.role.map(UIAlertAction.Style.init) ?? .default -// ) { _ in -// button.withAction(handler) -// } -// if #available(iOS 15, macOS 12, tvOS 15, watchOS 8, *) { -// self.accessibilityLabel = button.label.accessibilityLabel.map { String(state: $0) } -// } -// } -// } -#endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift index d7a6d934a7..59e3fcbb23 100644 --- a/Sources/AppKitNavigation/Observe.swift +++ b/Sources/AppKitNavigation/Observe.swift @@ -175,11 +175,8 @@ extension NSView { static func performWithoutAnimation(_ block: () -> Void) { - if NSAnimationContext.current.allowsImplicitAnimation { - NSAnimationContext.current.allowsImplicitAnimation = false - block() - NSAnimationContext.current.allowsImplicitAnimation = true - } else { + NSAnimationContext.runAnimationGroup { context in + context.allowsImplicitAnimation = false block() } } From 06f09afa8c225407f41d6919cddb7c5ad9c48c8b Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Thu, 15 Aug 2024 01:10:56 +0800 Subject: [PATCH 004/141] Updates --- ...ppKit+BasicsNavigationViewController.swift | 93 +++++ ...+ConciseEnumNavigationViewController.swift | 138 +++++++ .../AppKit+EnumControlsViewController.swift | 117 ++++++ .../AppKit/AppKit+FocusViewController.swift | 131 +++++++ ...Kit+MinimalObservationViewController.swift | 6 +- ...Kit+NSControlBindingsViewController.swift} | 0 .../AppKit/AppKitCaseStudies.swift | 42 +++ Examples/CaseStudies/Internal/CaseStudy.swift | 336 ++++++++++-------- Examples/CaseStudies/RootView.swift | 37 +- Examples/Examples.xcodeproj/project.pbxproj | 28 +- .../AppKitNavigation/Bindings/NSControl.swift | 10 + .../Bindings/NSFontManager.swift | 2 +- .../Bindings/NSTargetAction.swift | 51 ++- .../AppKitNavigation/Navigation/NSAlert.swift | 8 +- .../Navigation/Presentation.swift | 12 +- .../AppKitNavigation/Navigation/Sheet.swift | 228 ++++++++++++ Sources/AppKitNavigation/Observe.swift | 96 ++--- 17 files changed, 1084 insertions(+), 251 deletions(-) create mode 100644 Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift rename Examples/CaseStudies/AppKit/{NSControlBindingsViewController.swift => AppKit+NSControlBindingsViewController.swift} (100%) create mode 100644 Examples/CaseStudies/AppKit/AppKitCaseStudies.swift create mode 100644 Sources/AppKitNavigation/Navigation/Sheet.swift diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift new file mode 100644 index 0000000000..eeede2e017 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -0,0 +1,93 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import SwiftUI +import AppKit +import AppKitNavigation + +class BasicsNavigationViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Basics" + let readMe = """ + This case study demonstrates how to perform every major form of navigation in UIKit (alerts, \ + sheets, drill-downs) by driving navigation off of optional and boolean state. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let showAlertButton = NSButton { [weak self] _ in + self?.model.alert = "Hello!" + } + + let showSheetButton = NSButton { [weak self] _ in + self?.model.sheet = .random(in: 1 ... 1_000) + } + + let showSheetFromBooleanButton = NSButton { [weak self] _ in + self?.model.isSheetPresented = true + } + + let stack = NSStackView(views: [ + showAlertButton, + showSheetButton, + showSheetFromBooleanButton, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) + + observe { [weak self] in + guard let self else { return } + + showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" + showSheetButton.title = "Sheet is presented: \(model.sheet != nil ? "✅" : "❌")" + showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.isSheetPresented ? "✅" : "❌")" + + } + +// present(item: $model.alert, id: \.self) { message in +// let alert = UIAlertController( +// title: "This is an alert", +// message: message, +// preferredStyle: .alert +// ) +// alert.addAction(UIAlertAction(title: "OK", style: .default)) +// return alert +// } + sheet(item: $model.sheet, id: \.self) { count in + NSAlert(error: CocoaError.error(.coderInvalidValue)) + } +// present(item: $model.sheet, id: \.self, style: .sheet) { count in +//// let vc = NSHostingController( +//// rootView: Form { Text(count.description) } +//// ) +// let vc = XiblessViewController() +// vc.preferredContentSize = .init(width: 300, height: 200) +// return vc +// } + present(isPresented: $model.isSheetPresented, style: .sheet) { + let vc = NSHostingController( + rootView: Form { Text("Hello!") } + ) + return vc + } + } + + @Observable + class Model { + var alert: String? + var isSheetPresented = false + var sheet: Int? + } +} + +#Preview { + BasicsNavigationViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift new file mode 100644 index 0000000000..af08f37dfe --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -0,0 +1,138 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +//import SwiftUI +//import UIKit +//import UIKitNavigation +// +//class ConciseEnumNavigationViewController: UIViewController, UIKitCaseStudy { +// let caseStudyNavigationTitle = "Enum navigation" +// let caseStudyTitle = "Concise enum navigation" +// let readMe = """ +// This case study demonstrates how to navigate to multiple destinations from a single optional \ +// enum. +// +// This allows you to be very concise with your domain modeling by having a single enum \ +// describe all the possible destinations you can navigate to. In the case of this demo, we have \ +// four cases in the enum, which means there are exactly 5 possible states, including the case \ +// where none are active. +// +// If you were to instead model this domain with 4 optionals (or booleans), then you would have \ +// 16 possible states, of which only 5 are valid. That can leak complexity into your domain \ +// because you can never be sure of exactly what is presented at a given time. +// """ +// @UIBindable var model = Model() +// +// override func viewDidLoad() { +// super.viewDidLoad() +// view.backgroundColor = .systemBackground +// +// let showAlertButton = UIButton( +// type: .system, +// primaryAction: UIAction { [weak self] _ in +// self?.model.destination = .alert("Hello!") +// }) +// let showSheetButton = UIButton( +// type: .system, +// primaryAction: UIAction { [weak self] _ in +// self?.model.destination = .sheet(.random(in: 1...1_000)) +// }) +// let showSheetFromBooleanButton = UIButton( +// type: .system, +// primaryAction: UIAction { [weak self] _ in +// self?.model.destination = .sheetWithoutPayload +// }) +// let drillDownButton = UIButton( +// type: .system, +// primaryAction: UIAction { [weak self] _ in +// self?.model.destination = .drillDown(.random(in: 1...1_000)) +// }) +// +// let stack = UIStackView(arrangedSubviews: [ +// showAlertButton, +// showSheetButton, +// drillDownButton, +// showSheetFromBooleanButton, +// ]) +// stack.axis = .vertical +// stack.spacing = 12 +// stack.translatesAutoresizingMaskIntoConstraints = false +// +// view.addSubview(stack) +// NSLayoutConstraint.activate([ +// stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), +// stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), +// stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), +// ]) +// +// observe { [weak self] in +// guard let self else { return } +// +// showAlertButton.setTitle( +// "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")", +// for: .normal +// ) +// showSheetButton.setTitle( +// "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")", +// for: .normal +// ) +// showSheetFromBooleanButton.setTitle( +// "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")", +// for: .normal +// ) +// drillDownButton.setTitle( +// "Drill-down is presented: \(model.destination?.drillDown != nil ? "✅" : "❌")", +// for: .normal +// ) +// } +// +// present(item: $model.destination.alert, id: \.self) { message in +// let alert = UIAlertController( +// title: "This is an alert", +// message: message, +// preferredStyle: .alert +// ) +// alert.addAction(UIAlertAction(title: "OK", style: .default)) +// return alert +// } +// present(item: $model.destination.sheet, id: \.self) { count in +// let vc = UIHostingController( +// rootView: Form { Text(count.description) } +// ) +// vc.mediumDetents() +// return vc +// } +// present(isPresented: UIBinding($model.destination.sheetWithoutPayload)) { +// let vc = UIHostingController( +// rootView: Form { Text("Hello!") } +// ) +// vc.mediumDetents() +// return vc +// } +// navigationDestination(item: $model.destination.drillDown) { count in +// UIHostingController( +// rootView: Form { +// Text(count.description) +// } +// ) +// } +// } +// +// @Observable +// class Model { +// var destination: Destination? +// @CasePathable +// @dynamicMemberLookup +// enum Destination { +// case alert(String) +// case drillDown(Int) +// case sheet(Int) +// case sheetWithoutPayload +// } +// } +//} +// +//#Preview { +// UINavigationController( +// rootViewController: BasicsNavigationViewController() +// ) +//} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift new file mode 100644 index 0000000000..f6aada2f04 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift @@ -0,0 +1,117 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import AppKitNavigation + +class EnumControlsViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyNavigationTitle = "Enum controls" + let caseStudyTitle = "Concise enum controls" + let readMe = """ + This case study demonstrates how to drive form controls from bindings to enum state. In this \ + example, a single `Status` enum holds two cases: + + • An integer quantity for when an item is in stock, which can drive a stepper. + • A Boolean for whether an item is on back order when it is _not_ in stock, which can drive a \ + switch. + + This library provides tools to chain deeper into a binding's case by applying the \ + `@CasePathable` macro. + """ + + @CasePathable + enum Status { + case inStock(quantity: Int) + case outOfStock(isOnBackOrder: Bool) + } + + @UIBinding var status: Status = .inStock(quantity: 100) + + override func viewDidLoad() { + super.viewDidLoad() + + let quantityLabel = NSTextField(labelWithString: "") + let quantityStepper = NSStepper() + quantityStepper.maxValue = .infinity + let quantityStack = NSStackView(views: [ + quantityLabel, + quantityStepper, + ]) + let outOfStockButton = NSButton { [weak self] _ in + self?.status = .outOfStock(isOnBackOrder: false) + } + outOfStockButton.title = "Out of stock" + let inStockStack = NSStackView(views: [ + quantityStack, + outOfStockButton, + ]) + inStockStack.orientation = .vertical + + let isOnBackOrderLabel = NSTextField(labelWithString: "Is on back order?") + let isOnBackOrderSwitch = NSSwitch() + let isOnBackOrderStack = NSStackView(views: [ + isOnBackOrderLabel, + isOnBackOrderSwitch, + ]) + let backInStockButton = NSButton { [weak self] _ in + self?.status = .inStock(quantity: 100) + } + + backInStockButton.title = "Back in stock!" + let outOfStockStack = NSStackView(views: [ + isOnBackOrderStack, + backInStockButton, + ]) + outOfStockStack.orientation = .vertical + + let stack = NSStackView(views: [ + inStockStack, + outOfStockStack, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stack) + + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) + + observe { [weak self] in + guard let self else { return } + + inStockStack.isHidden = !status.is(\.inStock) + outOfStockStack.isHidden = !status.is(\.outOfStock) + + switch status { + case .inStock: + if let quantity = $status.inStock { + quantityLabel.stringValue = "Quantity: \(quantity.wrappedValue)" + quantityStepper.bind(value: quantity.asDouble) + } + + case .outOfStock: + if let isOnBackOrder = $status.outOfStock { + isOnBackOrderSwitch.bind(isOn: isOnBackOrder) + } + } + } + } +} + +@available(macOS 14.0, *) +#Preview { + EnumControlsViewController() +} + + +extension Int { + fileprivate var asDouble: Double { + get { Double(self) } + set { self = Int(newValue) } + } +} + +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift new file mode 100644 index 0000000000..9008fdf714 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift @@ -0,0 +1,131 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import AppKitNavigation + +class FocusViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Focus" + let readMe = """ + This case study demonstrates how to handle `UITextField` focus in a state-driven manner. The \ + focus in the UI is kept in sync with the focus value held in an observable model so that \ + changes in one are immediately reflected in the other. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let bioTextField = NSTextField(text: $model.bio) + bioTextField.bind(focus: $model.focus, equals: .bio) + bioTextField.bezelStyle = .roundedBezel + bioTextField.placeholderString = "Bio" + let emailTextField = NSTextField(text: $model.email) + emailTextField.bind(focus: $model.focus, equals: .email) + emailTextField.bezelStyle = .roundedBezel + emailTextField.placeholderString = "Email" + let passwordTextField = NSSecureTextField(text: $model.password) + passwordTextField.bind(focus: $model.focus, equals: .password) + passwordTextField.bezelStyle = .roundedBezel + passwordTextField.placeholderString = "Password" + let usernameTextField = NSTextField(text: $model.username) + usernameTextField.bind(focus: $model.focus, equals: .username) + usernameTextField.bezelStyle = .roundedBezel + usernameTextField.placeholderString = "Username" + + let currentFocusLabel = NSTextField(labelWithString: "") + + let focusBioButton = NSButton { [weak self] _ in + self?.model.focus = .bio + } + + focusBioButton.title = "Focus bio" + let focusEmailButton = NSButton { [weak self] _ in + self?.model.focus = .email + } + + focusEmailButton.title = "Focus email" + let focusPasswordButton = NSButton { [weak self] _ in + self?.model.focus = .password + } + + focusPasswordButton.title = "Focus password" + let focusUsernameButton = NSButton { [weak self] _ in + self?.model.focus = .username + } + + focusUsernameButton.title = "Focus username" + let resignFirstResponder = NSButton { [weak self] _ in + self?.view.window?.makeFirstResponder(nil) + } + + resignFirstResponder.title = "Resign first responder" + + let stack = NSStackView(views: [ + usernameTextField, + emailTextField, + passwordTextField, + bioTextField, + currentFocusLabel, + focusUsernameButton, + focusEmailButton, + focusPasswordButton, + focusBioButton, + resignFirstResponder, + ]) + stack.orientation = .vertical + stack.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.topAnchor + .constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + stack.leadingAnchor + .constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 24), + stack.trailingAnchor + .constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -24), + ]) + + observe { [weak self] in + guard let self else { return } + + currentFocusLabel.stringValue = "Current focus: \(model.focus?.rawValue ?? "none")" + bioTextField.backgroundColor = nil + emailTextField.backgroundColor = nil + passwordTextField.backgroundColor = nil + usernameTextField.backgroundColor = nil + switch model.focus { + case .bio: + bioTextField.backgroundColor = .lightGray + case .email: + emailTextField.backgroundColor = .lightGray + case .password: + passwordTextField.backgroundColor = .lightGray + case .username: + usernameTextField.backgroundColor = .lightGray + case .none: + break + } + } + } + + @Observable + class Model { + var bio = "" + var email = "" + var focus: Focus? + var password = "" + var username = "" + enum Focus: String { + case bio + case email + case password + case username + } + } +} + +#Preview { + FocusViewController() +} + +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift index 9fcc665639..f9b51ffca1 100644 --- a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift @@ -3,7 +3,7 @@ import AppKit import AppKitNavigation import ConcurrencyExtras -class MinimalObservationViewController: NSViewController, AppKitCaseStudy { +class MinimalObservationViewController: XiblessViewController, AppKitCaseStudy { let caseStudyTitle = "Minimal observation" let readMe = """ This case study demonstrates how to use the 'observe' tool from the library in order to \ @@ -15,10 +15,6 @@ class MinimalObservationViewController: NSViewController, AppKitCaseStudy { closure of 'observe' causes re-renders. """ @UIBindable var model = Model() - - override func loadView() { - view = NSView() - } override func viewDidLoad() { super.viewDidLoad() diff --git a/Examples/CaseStudies/AppKit/NSControlBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift similarity index 100% rename from Examples/CaseStudies/AppKit/NSControlBindingsViewController.swift rename to Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift new file mode 100644 index 0000000000..acdf6cb0e2 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -0,0 +1,42 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import SwiftUI +import SwiftUINavigation + +struct AppKitCaseStudiesView: View { + var body: some View { + List { + CaseStudyGroupView("Observation") { + MinimalObservationViewController() +// AnimationsViewController() + } + CaseStudyGroupView("Bindings") { + NSControlBindingsViewController() + EnumControlsViewController() + FocusViewController() + } + CaseStudyGroupView("Optional navigation") { + BasicsNavigationViewController() + // TODO: Alert/dialog state +// ConciseEnumNavigationViewController() + } +// CaseStudyGroupView("Stack navigation") { +// StaticNavigationStackController() +// ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) +// // TODO: state restoration +// } +// CaseStudyGroupView("Advanced") { +// // TODO: Deep link +// // TODO: Dismissal (show off from VCs and views) +// WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)) +// } + } + .navigationTitle("AppKit") + } +} + +#Preview { + NavigationStack { + AppKitCaseStudiesView() + } +} +#endif diff --git a/Examples/CaseStudies/Internal/CaseStudy.swift b/Examples/CaseStudies/Internal/CaseStudy.swift index 9f7a8d1167..88730a9b21 100644 --- a/Examples/CaseStudies/Internal/CaseStudy.swift +++ b/Examples/CaseStudies/Internal/CaseStudy.swift @@ -1,18 +1,20 @@ import SwiftUI +import AppKitNavigation import UIKitNavigation protocol CaseStudy { - var readMe: String { get } - var caseStudyTitle: String { get } - var caseStudyNavigationTitle: String { get } - var usesOwnLayout: Bool { get } - var isPresentedInSheet: Bool { get } + var readMe: String { get } + var caseStudyTitle: String { get } + var caseStudyNavigationTitle: String { get } + var usesOwnLayout: Bool { get } + var isPresentedInSheet: Bool { get } } + protocol SwiftUICaseStudy: CaseStudy, View {} #if canImport(UIKit) && !os(watchOS) protocol UIKitCaseStudy: CaseStudy, UIViewController {} extension UIKitCaseStudy { - var usesOwnLayout: Bool { true } + var usesOwnLayout: Bool { true } } #endif #if canImport(AppKit) && !targetEnvironment(macCatalyst) @@ -23,207 +25,249 @@ extension AppKitCaseStudy { #endif extension CaseStudy { - var caseStudyNavigationTitle: String { caseStudyTitle } - var isPresentedInSheet: Bool { false } + var caseStudyNavigationTitle: String { caseStudyTitle } + var isPresentedInSheet: Bool { false } } + extension SwiftUICaseStudy { - var usesOwnLayout: Bool { false } + var usesOwnLayout: Bool { false } } - @resultBuilder @MainActor enum CaseStudyViewBuilder { - @ViewBuilder - static func buildBlock() -> some View {} - @ViewBuilder - static func buildExpression(_ caseStudy: some SwiftUICaseStudy) -> some View { - SwiftUICaseStudyButton(caseStudy: caseStudy) - } -#if canImport(UIKit) && !os(watchOS) - @ViewBuilder - static func buildExpression(_ caseStudy: some UIKitCaseStudy) -> some View { - UIKitCaseStudyButton(caseStudy: caseStudy) - } + @ViewBuilder + static func buildBlock() -> some View {} + @ViewBuilder + static func buildExpression(_ caseStudy: some SwiftUICaseStudy) -> some View { + SwiftUICaseStudyButton(caseStudy: caseStudy) + } + + #if canImport(UIKit) && !os(watchOS) + @ViewBuilder + static func buildExpression(_ caseStudy: some UIKitCaseStudy) -> some View { + UIKitCaseStudyButton(caseStudy: caseStudy) + } + #endif + #if canImport(AppKit) && !targetEnvironment(macCatalyst) + @ViewBuilder + static func buildExpression(_ caseStudy: some AppKitCaseStudy) -> some View { + AppKitCaseStudyButton(caseStudy: caseStudy) + } #endif - static func buildPartialBlock(first: some View) -> some View { - first - } - @ViewBuilder - static func buildPartialBlock(accumulated: some View, next: some View) -> some View { - accumulated - next - } + static func buildPartialBlock(first: some View) -> some View { + first + } + + @ViewBuilder + static func buildPartialBlock(accumulated: some View, next: some View) -> some View { + accumulated + next + } } struct SwiftUICaseStudyButton: View { - let caseStudy: C - @State var isPresented = false - var body: some View { - if caseStudy.isPresentedInSheet { - Button(caseStudy.caseStudyTitle) { - isPresented = true - } - .sheet(isPresented: $isPresented) { - CaseStudyView { - caseStudy + let caseStudy: C + @State var isPresented = false + var body: some View { + if caseStudy.isPresentedInSheet { + Button(caseStudy.caseStudyTitle) { + isPresented = true + } + .sheet(isPresented: $isPresented) { + CaseStudyView { + caseStudy + } + .modifier(CaseStudyModifier(caseStudy: caseStudy)) + } + } else { + NavigationLink(caseStudy.caseStudyTitle) { + CaseStudyView { + caseStudy + } + .modifier(CaseStudyModifier(caseStudy: caseStudy)) + } } - .modifier(CaseStudyModifier(caseStudy: caseStudy)) - } - } else { - NavigationLink(caseStudy.caseStudyTitle) { - CaseStudyView { - caseStudy + } +} + +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +struct AppKitCaseStudyButton: View { + let caseStudy: C + @State var isPresented = false + var body: some View { +// if caseStudy.isPresentedInSheet { +// Button(caseStudy.caseStudyTitle) { +// isPresented = true +// } +// .sheet(isPresented: $isPresented) { +// NSViewControllerRepresenting { +// ((caseStudy as? UINavigationController) +// ?? UINavigationController(rootViewController: caseStudy)) +// .setUp(caseStudy: caseStudy) +// } +// .modifier(CaseStudyModifier(caseStudy: caseStudy)) +// } +// } else { + NavigationLink(caseStudy.caseStudyTitle) { + NSViewControllerRepresenting { + caseStudy + } + .modifier(CaseStudyModifier(caseStudy: caseStudy)) } - .modifier(CaseStudyModifier(caseStudy: caseStudy)) - } +// } } - } } + +#endif + #if canImport(UIKit) && !os(watchOS) struct UIKitCaseStudyButton: View { - let caseStudy: C - @State var isPresented = false - var body: some View { - if caseStudy.isPresentedInSheet { - Button(caseStudy.caseStudyTitle) { - isPresented = true - } - .sheet(isPresented: $isPresented) { - UIViewControllerRepresenting { - ((caseStudy as? UINavigationController) - ?? UINavigationController(rootViewController: caseStudy)) - .setUp(caseStudy: caseStudy) - } - .modifier(CaseStudyModifier(caseStudy: caseStudy)) - } - } else { - NavigationLink(caseStudy.caseStudyTitle) { - UIViewControllerRepresenting { - caseStudy + let caseStudy: C + @State var isPresented = false + var body: some View { + if caseStudy.isPresentedInSheet { + Button(caseStudy.caseStudyTitle) { + isPresented = true + } + .sheet(isPresented: $isPresented) { + UIViewControllerRepresenting { + ((caseStudy as? UINavigationController) + ?? UINavigationController(rootViewController: caseStudy)) + .setUp(caseStudy: caseStudy) + } + .modifier(CaseStudyModifier(caseStudy: caseStudy)) + } + } else { + NavigationLink(caseStudy.caseStudyTitle) { + UIViewControllerRepresenting { + caseStudy + } + .modifier(CaseStudyModifier(caseStudy: caseStudy)) + } } - .modifier(CaseStudyModifier(caseStudy: caseStudy)) - } } - } } extension UINavigationController { - func setUp(caseStudy: some CaseStudy) -> Self { - self.viewControllers[0].title = caseStudy.caseStudyNavigationTitle - self.viewControllers[0].navigationItem.rightBarButtonItem = UIBarButtonItem( - title: "About", - primaryAction: UIAction { [weak self] _ in - self?.present( - UIHostingController( - rootView: Form { - Text(template: caseStudy.readMe) + func setUp(caseStudy: some CaseStudy) -> Self { + viewControllers[0].title = caseStudy.caseStudyNavigationTitle + viewControllers[0].navigationItem.rightBarButtonItem = UIBarButtonItem( + title: "About", + primaryAction: UIAction { [weak self] _ in + self?.present( + UIHostingController( + rootView: Form { + Text(template: caseStudy.readMe) + } + .presentationDetents([.medium]) + ), + animated: true + ) } - .presentationDetents([.medium]) - ), - animated: true ) - }) - return self - } + return self + } } #endif struct CaseStudyModifier: ViewModifier { - let caseStudy: C - @State var isAboutPresented = false - func body(content: Content) -> some View { - content - .navigationTitle(caseStudy.caseStudyNavigationTitle) - .toolbar { - ToolbarItem { - Button("About") { isAboutPresented = true } - } - } - .sheet(isPresented: $isAboutPresented) { - Form { - Text(template: caseStudy.readMe) - } - .presentationDetents([.medium]) - } - } + let caseStudy: C + @State var isAboutPresented = false + func body(content: Content) -> some View { + content + .navigationTitle(caseStudy.caseStudyNavigationTitle) + .toolbar { + ToolbarItem { + Button("About") { isAboutPresented = true } + } + } + .sheet(isPresented: $isAboutPresented) { + Form { + Text(template: caseStudy.readMe) + } + .presentationDetents([.medium]) + } + } } struct CaseStudyView: View { - @ViewBuilder let caseStudy: C - @State var isAboutPresented = false - var body: some View { - if caseStudy.usesOwnLayout { - VStack { - caseStudy - } - } else { - Form { - caseStudy - } + @ViewBuilder let caseStudy: C + @State var isAboutPresented = false + var body: some View { + if caseStudy.usesOwnLayout { + VStack { + caseStudy + } + } else { + Form { + caseStudy + } + } } - } } struct CaseStudyGroupView: View { - @CaseStudyViewBuilder let content: Content - @ViewBuilder let title: Title + @CaseStudyViewBuilder let content: Content + @ViewBuilder let title: Title - var body: some View { - Section { - content - } header: { - title + var body: some View { + Section { + content + } header: { + title + } } - } } extension CaseStudyGroupView where Title == Text { - init(_ title: String, @CaseStudyViewBuilder content: () -> Content) { - self.init(content: content) { Text(title) } - } + init(_ title: String, @CaseStudyViewBuilder content: () -> Content) { + self.init(content: content) { Text(title) } + } } extension SwiftUICaseStudy { - fileprivate func navigationLink() -> some View { - NavigationLink(caseStudyTitle) { - self + fileprivate func navigationLink() -> some View { + NavigationLink(caseStudyTitle) { + self + } } - } } #Preview("SwiftUI case study") { - NavigationStack { - CaseStudyView { - DemoCaseStudy() + NavigationStack { + CaseStudyView { + DemoCaseStudy() + } } - } } #Preview("SwiftUI case study group") { - NavigationStack { - Form { - CaseStudyGroupView("Group") { - DemoCaseStudy() - } + NavigationStack { + Form { + CaseStudyGroupView("Group") { + DemoCaseStudy() + } + } } - } } private struct DemoCaseStudy: SwiftUICaseStudy { - let caseStudyTitle = "Demo Case Study" - let readMe = """ + let caseStudyTitle = "Demo Case Study" + let readMe = """ Hello! This is a demo case study. Enjoy! """ - var body: some View { - Text("Hello!") - } + var body: some View { + Text("Hello!") + } } + #if canImport(UIKit) && !os(watchOS) private class DemoCaseStudyController: UIViewController, UIKitCaseStudy { - let caseStudyTitle = "Demo Case Study" - let readMe = """ + let caseStudyTitle = "Demo Case Study" + let readMe = """ Hello! This is a demo case study. Enjoy! diff --git a/Examples/CaseStudies/RootView.swift b/Examples/CaseStudies/RootView.swift index d552ddf930..cb466a2879 100644 --- a/Examples/CaseStudies/RootView.swift +++ b/Examples/CaseStudies/RootView.swift @@ -2,25 +2,30 @@ import SwiftUI import SwiftUINavigation struct RootView: View { - var body: some View { - NavigationStack { - List { - NavigationLink("SwiftUI") { - SwiftUICaseStudiesView() + var body: some View { + NavigationStack { + List { + NavigationLink("SwiftUI") { + SwiftUICaseStudiesView() + } + #if canImport(UIKit) && !os(watchOS) + NavigationLink("UIKit") { + UIKitCaseStudiesView() + } + #endif + #if canImport(AppKit) && !targetEnvironment(macCatalyst) + NavigationLink("AppKit") { + AppKitCaseStudiesView() + } + #endif + } + .navigationTitle("Case studies") } -#if canImport(UIKit) && !os(watchOS) - NavigationLink("UIKit") { - UIKitCaseStudiesView() - } -#endif - } - .navigationTitle("Case studies") } - } } struct RootView_Previews: PreviewProvider { - static var previews: some View { - RootView() - } + static var previews: some View { + RootView() + } } diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index 9a7069ae89..f3552b0cfa 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -54,7 +54,12 @@ DC86E8712C208D8D003C0EC9 /* Text+Template.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC86E8702C208D8A003C0EC9 /* Text+Template.swift */; }; E9836D922C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */; }; E9836D942C6CA07300FC6EFD /* AppKitNavigation in Frameworks */ = {isa = PBXBuildFile; productRef = E9836D932C6CA07300FC6EFD /* AppKitNavigation */; }; - E9836D962C6CADBB00FC6EFD /* NSControlBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D952C6CADBB00FC6EFD /* NSControlBindingsViewController.swift */; }; + E9836D962C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D952C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift */; }; + E9CD5B762C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B752C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift */; }; + E9CD5B782C6CDEA500CE7947 /* AppKit+FocusViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B772C6CDEA500CE7947 /* AppKit+FocusViewController.swift */; }; + E9CD5B7B2C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */; }; + E9CD5B7C2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B7A2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift */; }; + E9CD5B7E2C6D14DC00CE7947 /* AppKitCaseStudies.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B7D2C6D14DC00CE7947 /* AppKitCaseStudies.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -114,7 +119,12 @@ DC6A8410291F227400B3F6C9 /* SynchronizedBindings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SynchronizedBindings.swift; sourceTree = ""; }; DC86E8702C208D8A003C0EC9 /* Text+Template.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Text+Template.swift"; sourceTree = ""; }; E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+MinimalObservationViewController.swift"; sourceTree = ""; }; - E9836D952C6CADBB00FC6EFD /* NSControlBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NSControlBindingsViewController.swift; sourceTree = ""; }; + E9836D952C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+NSControlBindingsViewController.swift"; sourceTree = ""; }; + E9CD5B752C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+EnumControlsViewController.swift"; sourceTree = ""; }; + E9CD5B772C6CDEA500CE7947 /* AppKit+FocusViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+FocusViewController.swift"; sourceTree = ""; }; + E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppKit+BasicsNavigationViewController.swift"; sourceTree = ""; }; + E9CD5B7A2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppKit+ConciseEnumNavigationViewController.swift"; sourceTree = ""; }; + E9CD5B7D2C6D14DC00CE7947 /* AppKitCaseStudies.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppKitCaseStudies.swift; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -284,8 +294,13 @@ E9836D902C6C9E3000FC6EFD /* AppKit */ = { isa = PBXGroup; children = ( + E9CD5B7D2C6D14DC00CE7947 /* AppKitCaseStudies.swift */, E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */, - E9836D952C6CADBB00FC6EFD /* NSControlBindingsViewController.swift */, + E9836D952C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift */, + E9CD5B752C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift */, + E9CD5B772C6CDEA500CE7947 /* AppKit+FocusViewController.swift */, + E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */, + E9CD5B7A2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift */, ); path = AppKit; sourceTree = ""; @@ -449,17 +464,20 @@ buildActionMask = 2147483647; files = ( CABE9FC1272F2C0000AFC150 /* EnumNavigation.swift in Sources */, + E9CD5B782C6CDEA500CE7947 /* AppKit+FocusViewController.swift in Sources */, E9836D922C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift in Sources */, + E9CD5B7B2C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift in Sources */, DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */, CA9D70502C1FB431003B672A /* StaticNavigationStackController.swift in Sources */, CA473837272F0D860012CAC3 /* FactClient.swift in Sources */, + E9CD5B7C2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift in Sources */, CA9D704E2C1FAFAD003B672A /* ConciseEnumNavigationViewController.swift in Sources */, CA9D70582C2088B7003B672A /* MinimalObservationViewController.swift in Sources */, CA9D70562C2087DC003B672A /* EnumControls.swift in Sources */, CA473836272F0D860012CAC3 /* CaseStudiesApp.swift in Sources */, CA473834272F0D860012CAC3 /* RootView.swift in Sources */, CA3D0E322C20B27B00CCF7CD /* ConnectToNetworkFeature.swift in Sources */, - E9836D962C6CADBB00FC6EFD /* NSControlBindingsViewController.swift in Sources */, + E9836D962C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift in Sources */, CA3D0E332C20B27B00CCF7CD /* NetworkDetailFeature.swift in Sources */, CA3D0E342C20B27B00CCF7CD /* Network.swift in Sources */, CA3D0E352C20B27B00CCF7CD /* WiFiSettingsFeature.swift in Sources */, @@ -473,8 +491,10 @@ CA601BAE2C234613006B0C5F /* AnimationsViewController.swift in Sources */, CADCA3662C1CE8BE00DE645F /* CaseStudy.swift in Sources */, CA49D9542C20D4DF00E6C5BB /* ErasedNavigationStackController.swift in Sources */, + E9CD5B762C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift in Sources */, CA9D70542C1FB4FA003B672A /* BasicsNavigationViewController.swift in Sources */, DC86E8712C208D8D003C0EC9 /* Text+Template.swift in Sources */, + E9CD5B7E2C6D14DC00CE7947 /* AppKitCaseStudies.swift in Sources */, CA473838272F0D860012CAC3 /* OptionalNavigation.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index de03e4bd48..d1ee6d68b3 100644 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -14,4 +14,14 @@ extension NSControl: NSTargetActionProtocol { } } +extension NSControl { + public convenience init(action: @escaping (Self) -> Void) { + self.init(frame: .zero) + createActionHandlerIfNeeded().addAction { [weak self] _ in + guard let self else { return } + action(self) + } + } +} + #endif diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 85a5cd29d2..0525f42582 100644 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -67,7 +67,7 @@ extension NSFontManager { bind(font, to: \._selectedFont) } - private var _selectedFont: NSFont { + @objc private var _selectedFont: NSFont { set { setSelectedFont(newValue, isMultiple: false) } get { convert(.systemFont(ofSize: 0)) } } diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift index 295ff6b670..3412960d4d 100644 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -12,25 +12,24 @@ public protocol NSTargetActionProtocol: NSObject, Sendable { @MainActor internal class NSTargetActionHandler: NSObject { - let action: (NSControl) -> Void + typealias Action = (Any?) -> Void + var actions: [Action] = [] var originTarget: AnyObject? - + var originAction: Selector? - - init(action: @escaping (NSControl) -> Void) { - self.action = action - } - @objc func invokeAction(_ sender: NSControl) { + @objc func invokeAction(_ sender: Any?) { if let originTarget, let originAction { NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } - action(sender) - + actions.forEach { $0(sender) } } -} + func addAction(_ action: @escaping Action) { + actions.append(action) + } +} extension NSTargetActionProtocol { /// Establishes a two-way connection between a source of truth and a property of this control. @@ -50,11 +49,27 @@ extension NSTargetActionProtocol { } } - - internal var actionHandler: NSTargetActionHandler? { - set { objc_setAssociatedObject(self, actionHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } - get { objc_getAssociatedObject(self, actionHandlerKey) as? NSTargetActionHandler } + set { + objc_setAssociatedObject(self, actionHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, actionHandlerKey) as? NSTargetActionHandler + } + } + + internal func createActionHandlerIfNeeded() -> NSTargetActionHandler { + if let actionHandler { + return actionHandler + } else { + let actionHandler = NSTargetActionHandler() + actionHandler.originTarget = appkitNavigationTarget + actionHandler.originAction = appkitNavigationAction + self.actionHandler = actionHandler + appkitNavigationTarget = actionHandler + appkitNavigationAction = #selector(NSTargetActionHandler.invokeAction(_:)) + return actionHandler + } } /// Establishes a two-way connection between a source of truth and a property of this control. @@ -74,13 +89,11 @@ extension NSTargetActionProtocol { set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObservationToken { unbind(keyPath) - let actionHandler = NSTargetActionHandler { [weak self] _ in + let actionHandler = createActionHandlerIfNeeded() + actionHandler.addAction { [weak self] _ in guard let self else { return } binding.wrappedValue = self[keyPath: keyPath] } - self.actionHandler = actionHandler - appkitNavigationTarget = actionHandler - appkitNavigationAction = #selector(NSTargetActionHandler.invokeAction(_:)) let isSetting = LockIsolated(false) let token = observe { [weak self] transaction in @@ -134,6 +147,8 @@ extension NSTargetActionProtocol { } } + + @MainActor private let observationTokensKey = malloc(1)! @MainActor diff --git a/Sources/AppKitNavigation/Navigation/NSAlert.swift b/Sources/AppKitNavigation/Navigation/NSAlert.swift index 09229b6e57..ed7dbe924b 100644 --- a/Sources/AppKitNavigation/Navigation/NSAlert.swift +++ b/Sources/AppKitNavigation/Navigation/NSAlert.swift @@ -28,14 +28,10 @@ extension NSAlert { ) { let button = addButton(withTitle: String(state: buttonState.label)) - let actionHandler = NSTargetActionHandler { _ in + button.createActionHandlerIfNeeded().addAction { _ in buttonState.withAction(handler) } - actionHandler.originTarget = button.target - actionHandler.originAction = button.action - button.target = actionHandler - button.action = #selector(NSTargetActionHandler.invokeAction(_:)) - button.actionHandler = actionHandler + if buttonState.role == .destructive, #available(macOS 11.0, *) { button.hasDestructiveAction = true } diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index bc9c377ea6..50e4bf93c3 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -128,9 +128,8 @@ extension NSViewController { guard let self else { return } if presentedViewControllers != nil { self.dismiss(nil) - onDismiss?() - self.present(child, for: style) - + onDismiss?() + self.present(child, for: style) } else { self.present(child, for: style) } @@ -140,7 +139,6 @@ extension NSViewController { } } - public enum TransitionStyle { case sheet case modalWindow @@ -154,9 +152,9 @@ extension NSViewController { presentAsSheet(viewControllerToPresent) case .modalWindow: presentAsModalWindow(viewControllerToPresent) - case .popover(let rect, let view, let preferredEdge, let behavior): + case let .popover(rect, view, preferredEdge, behavior): present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) - case .custom(let animator): + case let .custom(animator): present(viewControllerToPresent, animator: animator) } } @@ -292,7 +290,7 @@ extension NSViewController { } } childController.onDismiss = onDismiss - + self.presentedByID[key] = Presented(childController, id: id(unwrappedItem.wrappedValue)) let work = { withUITransaction(transaction) { diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift new file mode 100644 index 0000000000..199de83e28 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -0,0 +1,228 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol WindowProviderAdapter: NSObject { + var currentWindow: NSWindow? { get } + func beginSheet(for provider: WindowProviderAdapter) async + func endSheet(for provider: WindowProviderAdapter) +} + +extension WindowProviderAdapter { + public func beginSheet(for provider: any WindowProviderAdapter) async { + if let sheetedWindow = provider.currentWindow { + await currentWindow?.beginSheet(sheetedWindow) + } + } + + public func endSheet(for provider: any WindowProviderAdapter) { + if let sheetedWindow = provider.currentWindow { + currentWindow?.endSheet(sheetedWindow) + } + } +} + +extension NSWindow: WindowProviderAdapter { + public var currentWindow: NSWindow? { self } +} + +extension NSWindowController: WindowProviderAdapter { + public var currentWindow: NSWindow? { window } +} + +extension NSViewController: WindowProviderAdapter { + public var currentWindow: NSWindow? { view.window } +} + +extension NSAlert: WindowProviderAdapter { + public var currentWindow: NSWindow? { window } + + public func beginSheet(for provider: any WindowProviderAdapter) async { + guard let parentWindow = provider.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + public func endSheet(for provider: any WindowProviderAdapter) { + provider.currentWindow?.endSheet(window) + } +} + +extension WindowProviderAdapter { + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> WindowProviderAdapter + ) -> ObservationToken { + sheet(item: item, id: id) { $item in + content($item) + } beginSheet: { [weak self] child, transaction in + guard let self else { return } + if let attachedSheetWindow = currentWindow?.attachedSheet { + self.endSheet(for: attachedSheetWindow) + onDismiss?() + Task { @MainActor in + await self.beginSheet(for: child) + child.onEndSheet?.invoke() + child.onEndSheet = nil + } + } else { + Task { @MainActor in + await self.beginSheet(for: child) + child.onEndSheet?.invoke() + child.onEndSheet = nil + } + } + } endSheet: { [weak self] provider, transaction in + self?.endSheet(for: provider) + onDismiss?() + } + } + + private func sheet( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> WindowProviderAdapter, + beginSheet: @escaping ( + _ child: WindowProviderAdapter, + _ transaction: UITransaction + ) -> Void, + endSheet: @escaping ( + _ child: WindowProviderAdapter, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + sheet( + item: item, + id: { $0[keyPath: id] }, + content: content, + beginSheet: beginSheet, + endSheet: endSheet + ) + } + + private func sheet( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> WindowProviderAdapter, + beginSheet: @escaping ( + _ child: WindowProviderAdapter, + _ transaction: UITransaction + ) -> Void, + endSheet: @escaping ( + _ child: WindowProviderAdapter, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let presented = sheetedByID[key] { + guard let presentationID = presented.sheetID, + presentationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let childController = content(unwrappedItem) + let onEndSheet = ClosureHolder { [presentationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + presentationID == id(wrappedValue) { + item.wrappedValue = nil + } + } + childController.onEndSheet = onEndSheet + + self.sheetedByID[key] = Sheeted(childController, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + beginSheet(childController, transaction) + } + } +// if hasViewAppeared { + work() +// } else { +// onViewAppear.append(work) +// } + } else if let presented = sheetedByID[key] { + if let controller = presented.provider { + endSheet(controller, transaction) + } + self.sheetedByID[key] = nil + } + } + } + + private var sheetedByID: [UIBindingIdentifier: Sheeted] { + get { + (objc_getAssociatedObject(self, sheetedKey) + as? [UIBindingIdentifier: Sheeted]) + ?? [:] + } + set { + objc_setAssociatedObject( + self, sheetedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private var onEndSheet: ClosureHolder? { + set { + objc_setAssociatedObject( + self, onEndSheetKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + get { + objc_getAssociatedObject(self, onEndSheetKey) as? ClosureHolder + } + } + +// func modal() {} +} + +private class ClosureHolder: NSObject { + let closure: () -> Void + init(closure: @escaping () -> Void) { + self.closure = closure + } + func invoke() { + closure() + } +} + +private let onEndSheetKey = malloc(1)! +private let sheetedKey = malloc(1)! + +@MainActor +private class Sheeted { + weak var provider: WindowProviderAdapter? + let sheetID: AnyHashable? + deinit { + // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to + // deinit alongside it on the main thread. If we use this other places we should force it + // to be a UIViewController as well, to ensure this functionality. + MainActor._assumeIsolated { + self.provider?.currentWindow?.endSheeted() + } + } + + init(_ provider: WindowProviderAdapter? = nil, id: AnyHashable?) { + self.provider = provider + self.sheetID = id + } +} + +extension NSWindow { + func endSheeted() { + guard sheetParent != nil else { + return + } + sheetParent?.endSheet(self) + } +} + + +#endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift index 59e3fcbb23..23190e08bf 100644 --- a/Sources/AppKitNavigation/Observe.swift +++ b/Sources/AppKitNavigation/Observe.swift @@ -1,9 +1,9 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - @_spi(Internals) import SwiftNavigation - import AppKit +@_spi(Internals) import SwiftNavigation +import AppKit - @MainActor - extension NSObject { +@MainActor +extension NSObject { /// Observe access to properties of an observable (or perceptible) object. /// /// This tool allows you to set up an observation loop so that you can access fields from an @@ -107,7 +107,7 @@ /// - Returns: A cancellation token. @discardableResult public func observe(_ apply: @escaping @MainActor @Sendable () -> Void) -> ObservationToken { - observe { _ in apply() } + observe { _ in apply() } } /// Observe access to properties of an observable (or perceptible) object. @@ -119,59 +119,59 @@ /// - Returns: A cancellation token. @discardableResult public func observe( - _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void + _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void ) -> ObservationToken { - let token = SwiftNavigation.observe { transaction in - MainActor._assumeIsolated { - withUITransaction(transaction) { - #if os(watchOS) - apply(transaction) - #else - if transaction.appKit.disablesAnimations { - NSView.performWithoutAnimation { apply(transaction) } - for completion in transaction.appKit.animationCompletions { - completion(true) - } - } else if let animation = transaction.appKit.animation { - return animation.perform( - { apply(transaction) }, - completion: transaction.appKit.animationCompletions.isEmpty - ? nil - : { - for completion in transaction.appKit.animationCompletions { - completion($0) - } + let token = SwiftNavigation.observe { transaction in + MainActor._assumeIsolated { + withUITransaction(transaction) { + #if os(watchOS) + apply(transaction) + #else + if transaction.appKit.disablesAnimations { + NSView.performWithoutAnimation { apply(transaction) } + for completion in transaction.appKit.animationCompletions { + completion(true) + } + } else if let animation = transaction.appKit.animation { + return animation.perform( + { apply(transaction) }, + completion: transaction.appKit.animationCompletions.isEmpty + ? nil + : { + for completion in transaction.appKit.animationCompletions { + completion($0) + } + } + ) + } else { + apply(transaction) + for completion in transaction.appKit.animationCompletions { + completion(true) + } } - ) - } else { - apply(transaction) - for completion in transaction.appKit.animationCompletions { - completion(true) + #endif } - } - #endif - } - } - } task: { transaction, work in - DispatchQueue.main.async { - withUITransaction(transaction, work) + } + } task: { transaction, work in + DispatchQueue.main.async { + withUITransaction(transaction, work) + } } - } - tokens.append(token) - return token + tokens.append(token) + return token } fileprivate var tokens: [Any] { - get { - objc_getAssociatedObject(self, Self.tokensKey) as? [Any] ?? [] - } - set { - objc_setAssociatedObject(self, Self.tokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } + get { + objc_getAssociatedObject(self, Self.tokensKey) as? [Any] ?? [] + } + set { + objc_setAssociatedObject(self, Self.tokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } } private static let tokensKey = malloc(1)! - } +} extension NSView { static func performWithoutAnimation(_ block: () -> Void) { From 590bb2bf6ad6fc190110e4f8ea2da4c45bc6e175 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Thu, 15 Aug 2024 19:14:25 +0800 Subject: [PATCH 005/141] WIP --- ...ppKit+BasicsNavigationViewController.swift | 7 +- .../{Navigation => Bindings}/NSAlert.swift | 0 .../AppKitNavigation/Navigation/Modal.swift | 195 ++++++++++++++++++ .../AppKitNavigation/Navigation/Sheet.swift | 50 ++--- 4 files changed, 225 insertions(+), 27 deletions(-) rename Sources/AppKitNavigation/{Navigation => Bindings}/NSAlert.swift (100%) create mode 100644 Sources/AppKitNavigation/Navigation/Modal.swift diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index eeede2e017..d5497efe8a 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -20,6 +20,9 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS let showSheetButton = NSButton { [weak self] _ in self?.model.sheet = .random(in: 1 ... 1_000) + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { + self?.model.sheet = nil + } } let showSheetFromBooleanButton = NSButton { [weak self] _ in @@ -60,8 +63,8 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS // alert.addAction(UIAlertAction(title: "OK", style: .default)) // return alert // } - sheet(item: $model.sheet, id: \.self) { count in - NSAlert(error: CocoaError.error(.coderInvalidValue)) + modal(item: $model.sheet, id: \.self) { count in + NSWindow(contentViewController: XiblessViewController()) } // present(item: $model.sheet, id: \.self, style: .sheet) { count in //// let vc = NSHostingController( diff --git a/Sources/AppKitNavigation/Navigation/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift similarity index 100% rename from Sources/AppKitNavigation/Navigation/NSAlert.swift rename to Sources/AppKitNavigation/Bindings/NSAlert.swift diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift new file mode 100644 index 0000000000..bd341b3529 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -0,0 +1,195 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import Combine + +@MainActor +@objc +public protocol ModalRepresentable where Self: NSObject { + @objc @discardableResult func runModal() -> NSApplication.ModalResponse + @objc var window: NSWindow { get } +} + +extension NSWindow: ModalRepresentable { + + public var window: NSWindow { self } + + public func runModal() -> NSApplication.ModalResponse { + NSApplication.shared.runModal(for: self) + } +} + +extension NSAlert: ModalRepresentable {} + +@MainActor +class WindowsObserver: NSObject { + static let shared = WindowsObserver() + + var windowsCancellable: [NSWindow: AnyCancellable] = [:] + + func observeWindow(_ window: NSWindow) { + windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) + .sink { [weak self] _ in + guard let self else { return } + if NSApplication.shared.modalWindow === window { + NSApplication.shared.stopModal() + } + windowsCancellable.removeValue(forKey: window) + } + } +} + +@MainActor +extension NSObject { + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> ModalRepresentable + ) -> ObservationToken { + modal(item: item, id: id) { $item in + content($item) + } beginSheet: { modalRepresentable, _ in + if NSApplication.shared.modalWindow != nil { + NSApplication.shared.stopModal() + onDismiss?() + DispatchQueue.main.async { + WindowsObserver.shared.observeWindow(modalRepresentable.window) + modalRepresentable.runModal() + modalRepresentable.onEndModal?.invoke() + modalRepresentable.onEndModal = nil + } + + } else { + DispatchQueue.main.async { + WindowsObserver.shared.observeWindow(modalRepresentable.window) + modalRepresentable.runModal() + modalRepresentable.onEndModal?.invoke() + modalRepresentable.onEndModal = nil + } + } + } endSheet: { provider, _ in + NSApplication.shared.stopModal() + onDismiss?() + } + } + + private func modal( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> ModalRepresentable, + beginSheet: @escaping ( + _ child: ModalRepresentable, + _ transaction: UITransaction + ) -> Void, + endSheet: @escaping ( + _ child: ModalRepresentable, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + modal( + item: item, + id: { $0[keyPath: id] }, + content: content, + beginModal: beginSheet, + endModal: endSheet + ) + } + + private func modal( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> ModalRepresentable, + beginModal: @escaping ( + _ child: ModalRepresentable, + _ transaction: UITransaction + ) -> Void, + endModal: @escaping ( + _ child: ModalRepresentable, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let presented = modaledByID[key] { + guard let presentationID = presented.modalID, + presentationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let modalRepresentable = content(unwrappedItem) + let onEndSheet = ClosureHolder { [presentationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + presentationID == id(wrappedValue) { + item.wrappedValue = nil + } + } + modalRepresentable.onEndModal = onEndSheet + + self.modaledByID[key] = Modaled(modalRepresentable, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + beginModal(modalRepresentable, transaction) + } + } + work() + } else if let modaled = modaledByID[key] { + if let modalRepresentable = modaled.provider { + endModal(modalRepresentable, transaction) + } + self.modaledByID[key] = nil + } + } + } + + private var modaledByID: [UIBindingIdentifier: Modaled] { + get { + (objc_getAssociatedObject(self, modaledKey) + as? [UIBindingIdentifier: Modaled]) + ?? [:] + } + set { + objc_setAssociatedObject( + self, modaledKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private var onEndModal: ClosureHolder? { + set { + objc_setAssociatedObject( + self, onEndModalKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + get { + objc_getAssociatedObject(self, onEndModalKey) as? ClosureHolder + } + } +} + +private let onEndModalKey = malloc(1)! +private let modaledKey = malloc(1)! + +@MainActor +private class Modaled { + weak var provider: ModalRepresentable? + let modalID: AnyHashable? + deinit { + // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to + // deinit alongside it on the main thread. If we use this other places we should force it + // to be a UIViewController as well, to ensure this functionality. + MainActor._assumeIsolated { + NSApplication.shared.stopModal() + } + } + + init(_ provider: ModalRepresentable? = nil, id: AnyHashable?) { + self.provider = provider + self.modalID = id + } +} +#endif diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 199de83e28..348902992f 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -3,58 +3,58 @@ import AppKit @MainActor -public protocol WindowProviderAdapter: NSObject { +public protocol SheetRepresentable: NSObject { var currentWindow: NSWindow? { get } - func beginSheet(for provider: WindowProviderAdapter) async - func endSheet(for provider: WindowProviderAdapter) + func beginSheet(for provider: SheetRepresentable) async + func endSheet(for provider: SheetRepresentable) } -extension WindowProviderAdapter { - public func beginSheet(for provider: any WindowProviderAdapter) async { +extension SheetRepresentable { + public func beginSheet(for provider: any SheetRepresentable) async { if let sheetedWindow = provider.currentWindow { await currentWindow?.beginSheet(sheetedWindow) } } - public func endSheet(for provider: any WindowProviderAdapter) { + public func endSheet(for provider: any SheetRepresentable) { if let sheetedWindow = provider.currentWindow { currentWindow?.endSheet(sheetedWindow) } } } -extension NSWindow: WindowProviderAdapter { +extension NSWindow: SheetRepresentable { public var currentWindow: NSWindow? { self } } -extension NSWindowController: WindowProviderAdapter { +extension NSWindowController: SheetRepresentable { public var currentWindow: NSWindow? { window } } -extension NSViewController: WindowProviderAdapter { +extension NSViewController: SheetRepresentable { public var currentWindow: NSWindow? { view.window } } -extension NSAlert: WindowProviderAdapter { +extension NSAlert: SheetRepresentable { public var currentWindow: NSWindow? { window } - public func beginSheet(for provider: any WindowProviderAdapter) async { + public func beginSheet(for provider: any SheetRepresentable) async { guard let parentWindow = provider.currentWindow else { return } await beginSheetModal(for: parentWindow) } - public func endSheet(for provider: any WindowProviderAdapter) { + public func endSheet(for provider: any SheetRepresentable) { provider.currentWindow?.endSheet(window) } } -extension WindowProviderAdapter { +extension SheetRepresentable { @discardableResult public func sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> WindowProviderAdapter + content: @escaping (UIBinding) -> SheetRepresentable ) -> ObservationToken { sheet(item: item, id: id) { $item in content($item) @@ -84,13 +84,13 @@ extension WindowProviderAdapter { private func sheet( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> WindowProviderAdapter, + content: @escaping (UIBinding) -> SheetRepresentable, beginSheet: @escaping ( - _ child: WindowProviderAdapter, + _ child: SheetRepresentable, _ transaction: UITransaction ) -> Void, endSheet: @escaping ( - _ child: WindowProviderAdapter, + _ child: SheetRepresentable, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -106,13 +106,13 @@ extension WindowProviderAdapter { private func sheet( item: UIBinding, id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> WindowProviderAdapter, + content: @escaping (UIBinding) -> SheetRepresentable, beginSheet: @escaping ( - _ child: WindowProviderAdapter, + _ child: SheetRepresentable, _ transaction: UITransaction ) -> Void, endSheet: @escaping ( - _ child: WindowProviderAdapter, + _ child: SheetRepresentable, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -179,15 +179,15 @@ extension WindowProviderAdapter { objc_getAssociatedObject(self, onEndSheetKey) as? ClosureHolder } } - -// func modal() {} } -private class ClosureHolder: NSObject { +internal class ClosureHolder: NSObject { let closure: () -> Void + init(closure: @escaping () -> Void) { self.closure = closure } + func invoke() { closure() } @@ -198,7 +198,7 @@ private let sheetedKey = malloc(1)! @MainActor private class Sheeted { - weak var provider: WindowProviderAdapter? + weak var provider: SheetRepresentable? let sheetID: AnyHashable? deinit { // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to @@ -209,7 +209,7 @@ private class Sheeted { } } - init(_ provider: WindowProviderAdapter? = nil, id: AnyHashable?) { + init(_ provider: SheetRepresentable? = nil, id: AnyHashable?) { self.provider = provider self.sheetID = id } From cb5aa023844151a0f36f84dc2759b5eb96363f0c Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Thu, 15 Aug 2024 22:27:21 +0800 Subject: [PATCH 006/141] WIP --- .../AppKitNavigation/AppKitAnimation.swift | 21 +-- .../AppKitNavigation/Bindings/NSAlert.swift | 7 +- .../Internal/ClosureHolder.swift | 17 +++ .../Internal/ModalWindowsObserver.swift | 24 ++++ .../AppKitNavigation/Navigation/Modal.swift | 52 ++----- .../Navigation/ModalRepresentable.swift | 23 +++ .../Navigation/Presentation.swift | 14 +- .../AppKitNavigation/Navigation/Sheet.swift | 135 +++++++++++------- .../Navigation/SheetRepresentable.swift | 51 +++++++ Sources/AppKitNavigation/Observe.swift | 22 ++- 10 files changed, 225 insertions(+), 141 deletions(-) create mode 100644 Sources/AppKitNavigation/Internal/ClosureHolder.swift create mode 100644 Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift create mode 100644 Sources/AppKitNavigation/Navigation/ModalRepresentable.swift create mode 100644 Sources/AppKitNavigation/Navigation/SheetRepresentable.swift diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 75e40b8f86..0d8230c8fb 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -80,21 +80,6 @@ extension AppKitAnimation { /// - Parameters: /// - duration: The total duration of the animations, measured in seconds. If you specify a /// negative value or `0`, the changes are made without animating them. - /// - delay: The amount of time (measured in seconds) to wait before beginning the animations. - /// Specify a value of `0` to begin the animations immediately. - /// - dampingRatio: The damping ratio for the spring animation as it approaches its quiescent - /// state. - /// - /// To smoothly decelerate the animation without oscillation, use a value of `1`. Employ a - /// damping ratio closer to zero to increase oscillation. - /// - velocity: The initial spring velocity. For smooth start to the animation, match this - /// value to the view's velocity as it was prior to attachment. - /// - /// A value of `1` corresponds to the total animation distance traversed in one second. For - /// example, if the total animation distance is 200 points and you want the start of the - /// animation to match a view velocity of 100 pt/s, use a value of `0.5`. - /// - options: A mask of options indicating how you want to perform the animations. For a list - /// of valid constants, see `UIView.AnimationOptions`. /// - Returns: An animation using a timing curve corresponding to the motion of a physical /// spring. public static func animate( @@ -111,11 +96,7 @@ extension AppKitAnimation { /// A default animation instance. public static var `default`: Self { - if #available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) { - return .animate() - } else { - return .animate(withDuration: 0.35) - } + return .animate() } } #endif diff --git a/Sources/AppKitNavigation/Bindings/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift index ed7dbe924b..37d7bb6ba3 100644 --- a/Sources/AppKitNavigation/Bindings/NSAlert.swift +++ b/Sources/AppKitNavigation/Bindings/NSAlert.swift @@ -2,7 +2,7 @@ import AppKit extension NSAlert { - /// Creates and returns a view controller for displaying an alert using a data description. + /// Creates and returns a alert for displaying an alert using a data description. /// /// - Parameters: /// - state: A data description of the alert. @@ -38,7 +38,10 @@ extension NSAlert { if buttonState.role == .cancel { button.keyEquivalent = "\u{1b}" } -// self.accessibilityLabel = button.label.accessibilityLabel.map { String(state: $0) } + + if #available(macOS 12, *) { + button.setAccessibilityLabel(buttonState.label.accessibilityLabel.map { String(state: $0) }) + } } } #endif diff --git a/Sources/AppKitNavigation/Internal/ClosureHolder.swift b/Sources/AppKitNavigation/Internal/ClosureHolder.swift new file mode 100644 index 0000000000..814e884dff --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ClosureHolder.swift @@ -0,0 +1,17 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import Foundation + +internal class ClosureHolder: NSObject { + let closure: () -> Void + + init(closure: @escaping () -> Void) { + self.closure = closure + } + + func invoke() { + closure() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift new file mode 100644 index 0000000000..4fb5f90e74 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift @@ -0,0 +1,24 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import Combine + +@MainActor +class ModalWindowsObserver: NSObject { + static let shared = ModalWindowsObserver() + + var windowsCancellable: [NSWindow: AnyCancellable] = [:] + + func observeWindow(_ window: NSWindow) { + windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) + .sink { [weak self] _ in + guard let self else { return } + if NSApplication.shared.modalWindow === window { + NSApplication.shared.stopModal() + } + windowsCancellable.removeValue(forKey: window) + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index bd341b3529..1acc9e7ec1 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -3,42 +3,6 @@ import AppKit import Combine -@MainActor -@objc -public protocol ModalRepresentable where Self: NSObject { - @objc @discardableResult func runModal() -> NSApplication.ModalResponse - @objc var window: NSWindow { get } -} - -extension NSWindow: ModalRepresentable { - - public var window: NSWindow { self } - - public func runModal() -> NSApplication.ModalResponse { - NSApplication.shared.runModal(for: self) - } -} - -extension NSAlert: ModalRepresentable {} - -@MainActor -class WindowsObserver: NSObject { - static let shared = WindowsObserver() - - var windowsCancellable: [NSWindow: AnyCancellable] = [:] - - func observeWindow(_ window: NSWindow) { - windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) - .sink { [weak self] _ in - guard let self else { return } - if NSApplication.shared.modalWindow === window { - NSApplication.shared.stopModal() - } - windowsCancellable.removeValue(forKey: window) - } - } -} - @MainActor extension NSObject { @discardableResult @@ -50,12 +14,12 @@ extension NSObject { ) -> ObservationToken { modal(item: item, id: id) { $item in content($item) - } beginSheet: { modalRepresentable, _ in + } beginModal: { modalRepresentable, _ in if NSApplication.shared.modalWindow != nil { NSApplication.shared.stopModal() onDismiss?() DispatchQueue.main.async { - WindowsObserver.shared.observeWindow(modalRepresentable.window) + ModalWindowsObserver.shared.observeWindow(modalRepresentable.window) modalRepresentable.runModal() modalRepresentable.onEndModal?.invoke() modalRepresentable.onEndModal = nil @@ -63,13 +27,13 @@ extension NSObject { } else { DispatchQueue.main.async { - WindowsObserver.shared.observeWindow(modalRepresentable.window) + ModalWindowsObserver.shared.observeWindow(modalRepresentable.window) modalRepresentable.runModal() modalRepresentable.onEndModal?.invoke() modalRepresentable.onEndModal = nil } } - } endSheet: { provider, _ in + } endModal: { provider, _ in NSApplication.shared.stopModal() onDismiss?() } @@ -79,11 +43,11 @@ extension NSObject { item: UIBinding, id: KeyPath, content: @escaping (UIBinding) -> ModalRepresentable, - beginSheet: @escaping ( + beginModal: @escaping ( _ child: ModalRepresentable, _ transaction: UITransaction ) -> Void, - endSheet: @escaping ( + endModal: @escaping ( _ child: ModalRepresentable, _ transaction: UITransaction ) -> Void @@ -92,8 +56,8 @@ extension NSObject { item: item, id: { $0[keyPath: id] }, content: content, - beginModal: beginSheet, - endModal: endSheet + beginModal: beginModal, + endModal: endModal ) } diff --git a/Sources/AppKitNavigation/Navigation/ModalRepresentable.swift b/Sources/AppKitNavigation/Navigation/ModalRepresentable.swift new file mode 100644 index 0000000000..f3526ea73e --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/ModalRepresentable.swift @@ -0,0 +1,23 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +@objc +public protocol ModalRepresentable where Self: NSObject { + @objc @discardableResult func runModal() -> NSApplication.ModalResponse + @objc var window: NSWindow { get } +} + +extension NSWindow: ModalRepresentable { + + public var window: NSWindow { self } + + public func runModal() -> NSApplication.ModalResponse { + NSApplication.shared.runModal(for: self) + } +} + +extension NSAlert: ModalRepresentable {} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 50e4bf93c3..8a9f6a52a2 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -7,7 +7,7 @@ import AppKitNavigationShim extension NSViewController { /// Presents a view controller modally when a binding to a Boolean value you provide is true. /// - /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. /// /// - Parameters: /// - isPresented: A binding to a Boolean value that determines whether to present the view @@ -27,7 +27,7 @@ extension NSViewController { /// Presents a view controller modally using the given item as a data source for its content. /// - /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. /// /// - Parameters: /// - item: A binding to an optional source of truth for the view controller. When `item` is @@ -50,7 +50,7 @@ extension NSViewController { /// Presents a view controller modally using the given item as a data source for its content. /// - /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. /// /// - Parameters: /// - item: A binding to an optional source of truth for the view controller. When `item` is @@ -74,7 +74,7 @@ extension NSViewController { /// Presents a view controller modally using the given item as a data source for its content. /// - /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. /// /// - Parameters: /// - item: A binding to an optional source of truth for the view controller. When `item` is @@ -101,7 +101,7 @@ extension NSViewController { /// Presents a view controller modally using the given item as a data source for its content. /// - /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for UIKit. + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. /// /// - Parameters: /// - item: A binding to an optional source of truth for the view controller. When `item` is @@ -332,9 +332,9 @@ private class Presented { weak var controller: NSViewController? let presentationID: AnyHashable? deinit { - // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to + // NB: This can only be assumed because it is held in a NSViewController and is guaranteed to // deinit alongside it on the main thread. If we use this other places we should force it - // to be a UIViewController as well, to ensure this functionality. + // to be a NSViewController as well, to ensure this functionality. MainActor._assumeIsolated { self.controller?.dismiss(nil) } diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 348902992f..935a2182d4 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -2,53 +2,95 @@ import AppKit -@MainActor -public protocol SheetRepresentable: NSObject { - var currentWindow: NSWindow? { get } - func beginSheet(for provider: SheetRepresentable) async - func endSheet(for provider: SheetRepresentable) -} - extension SheetRepresentable { - public func beginSheet(for provider: any SheetRepresentable) async { - if let sheetedWindow = provider.currentWindow { - await currentWindow?.beginSheet(sheetedWindow) - } + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - isSheeted: A binding to a Boolean value that determines whether to sheet the representable + /// - onDismiss: The closure to execute when dismissing the representable. + /// - content: A closure that returns the representable to display over the current window content. + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> SheetRepresentable + ) -> ObservationToken { + sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } - public func endSheet(for provider: any SheetRepresentable) { - if let sheetedWindow = provider.currentWindow { - currentWindow?.endSheet(sheetedWindow) - } + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> SheetRepresentable + ) -> ObservationToken { + sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } -} - -extension NSWindow: SheetRepresentable { - public var currentWindow: NSWindow? { self } -} - -extension NSWindowController: SheetRepresentable { - public var currentWindow: NSWindow? { window } -} - -extension NSViewController: SheetRepresentable { - public var currentWindow: NSWindow? { view.window } -} - -extension NSAlert: SheetRepresentable { - public var currentWindow: NSWindow? { window } - public func beginSheet(for provider: any SheetRepresentable) async { - guard let parentWindow = provider.currentWindow else { return } - await beginSheetModal(for: parentWindow) + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> SheetRepresentable + ) -> ObservationToken { + sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } - public func endSheet(for provider: any SheetRepresentable) { - provider.currentWindow?.endSheet(window) + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - id: The key path to the provided item's identifier. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> SheetRepresentable + ) -> ObservationToken { + sheet(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } } -} -extension SheetRepresentable { @discardableResult public func sheet( item: UIBinding, @@ -142,11 +184,7 @@ extension SheetRepresentable { beginSheet(childController, transaction) } } -// if hasViewAppeared { work() -// } else { -// onViewAppear.append(work) -// } } else if let presented = sheetedByID[key] { if let controller = presented.provider { endSheet(controller, transaction) @@ -181,18 +219,6 @@ extension SheetRepresentable { } } -internal class ClosureHolder: NSObject { - let closure: () -> Void - - init(closure: @escaping () -> Void) { - self.closure = closure - } - - func invoke() { - closure() - } -} - private let onEndSheetKey = malloc(1)! private let sheetedKey = malloc(1)! @@ -224,5 +250,4 @@ extension NSWindow { } } - #endif diff --git a/Sources/AppKitNavigation/Navigation/SheetRepresentable.swift b/Sources/AppKitNavigation/Navigation/SheetRepresentable.swift new file mode 100644 index 0000000000..03b16aede2 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/SheetRepresentable.swift @@ -0,0 +1,51 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol SheetRepresentable: NSObject { + var currentWindow: NSWindow? { get } + func beginSheet(for provider: SheetRepresentable) async + func endSheet(for provider: SheetRepresentable) +} + +extension SheetRepresentable { + public func beginSheet(for provider: any SheetRepresentable) async { + if let sheetedWindow = provider.currentWindow { + await currentWindow?.beginSheet(sheetedWindow) + } + } + + public func endSheet(for provider: any SheetRepresentable) { + if let sheetedWindow = provider.currentWindow { + currentWindow?.endSheet(sheetedWindow) + } + } +} + +extension NSWindow: SheetRepresentable { + public var currentWindow: NSWindow? { self } +} + +extension NSWindowController: SheetRepresentable { + public var currentWindow: NSWindow? { window } +} + +extension NSViewController: SheetRepresentable { + public var currentWindow: NSWindow? { view.window } +} + +extension NSAlert: SheetRepresentable { + public var currentWindow: NSWindow? { window } + + public func beginSheet(for provider: any SheetRepresentable) async { + guard let parentWindow = provider.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + public func endSheet(for provider: any SheetRepresentable) { + provider.currentWindow?.endSheet(window) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift index 23190e08bf..8032874494 100644 --- a/Sources/AppKitNavigation/Observe.swift +++ b/Sources/AppKitNavigation/Observe.swift @@ -10,7 +10,7 @@ extension NSObject { /// observable model in order to populate your view, and also automatically track changes to /// any accessed fields so that the view is always up-to-date. /// - /// It is most useful when dealing with non-SwiftUI views, such as UIKit views and controller. + /// It is most useful when dealing with non-SwiftUI views, such as AppKit views and controller. /// You can invoke the ``observe(_:)`` method a single time in the `viewDidLoad` and update all /// the view elements: /// @@ -18,16 +18,16 @@ extension NSObject { /// override func viewDidLoad() { /// super.viewDidLoad() /// - /// let countLabel = UILabel() - /// let incrementButton = UIButton(primaryAction: UIAction { [weak self] _ in + /// let countLabel = NSTextField(labelWithString: "") + /// let incrementButton = NSButton { [weak self] _ in /// self?.model.incrementButtonTapped() - /// }) + /// } /// /// observe { [weak self] in /// guard let self /// else { return } /// - /// countLabel.text = "\(model.count)" + /// countLabel.stringValue = "\(model.count)" /// } /// } /// ``` @@ -38,7 +38,7 @@ extension NSObject { /// again. /// /// Generally speaking you can usually have a single ``observe(_:)`` in the entry point of your - /// view, such as `viewDidLoad` for `UIViewController`. This works even if you have many UI + /// view, such as `viewDidLoad` for `NSViewController`. This works even if you have many UI /// components to update: /// /// ```swift @@ -51,9 +51,9 @@ extension NSObject { /// /// countLabel.isHidden = model.isObservingCount /// if !countLabel.isHidden { - /// countLabel.text = "\(model.count)" + /// countLabel.stringValue = "\(model.count)" /// } - /// factLabel.text = model.fact + /// factLabel.stringValue = model.fact /// } /// } /// ``` @@ -124,9 +124,6 @@ extension NSObject { let token = SwiftNavigation.observe { transaction in MainActor._assumeIsolated { withUITransaction(transaction) { - #if os(watchOS) - apply(transaction) - #else if transaction.appKit.disablesAnimations { NSView.performWithoutAnimation { apply(transaction) } for completion in transaction.appKit.animationCompletions { @@ -149,7 +146,6 @@ extension NSObject { completion(true) } } - #endif } } } task: { transaction, work in @@ -174,7 +170,7 @@ extension NSObject { } extension NSView { - static func performWithoutAnimation(_ block: () -> Void) { + fileprivate static func performWithoutAnimation(_ block: () -> Void) { NSAnimationContext.runAnimationGroup { context in context.allowsImplicitAnimation = false block() From 26ef0fa75c47d5f82083f351748d72cb69c6e3bc Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 16 Aug 2024 18:38:19 +0800 Subject: [PATCH 007/141] Refactoring, can't compile for now --- ...ppKit+BasicsNavigationViewController.swift | 4 +- .../AppKitNavigation/Navigation/Modal.swift | 140 +++++------------- .../Navigation/ModalContent.swift | 41 +++++ .../Navigation/ModalRepresentable.swift | 23 --- .../Navigation/NavigationContent.swift | 82 ++++++++++ .../Navigation/NavigationObserver.swift | 86 +++++++++++ .../Navigation/Presentation.swift | 94 +++++++++--- .../AppKitNavigation/Navigation/Sheet.swift | 85 +++++++---- .../Navigation/SheetContent.swift | 90 +++++++++++ .../Navigation/SheetRepresentable.swift | 51 ------- 10 files changed, 462 insertions(+), 234 deletions(-) create mode 100644 Sources/AppKitNavigation/Navigation/ModalContent.swift delete mode 100644 Sources/AppKitNavigation/Navigation/ModalRepresentable.swift create mode 100644 Sources/AppKitNavigation/Navigation/NavigationContent.swift create mode 100644 Sources/AppKitNavigation/Navigation/NavigationObserver.swift create mode 100644 Sources/AppKitNavigation/Navigation/SheetContent.swift delete mode 100644 Sources/AppKitNavigation/Navigation/SheetRepresentable.swift diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index d5497efe8a..8ec32db007 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -64,7 +64,9 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS // return alert // } modal(item: $model.sheet, id: \.self) { count in - NSWindow(contentViewController: XiblessViewController()) + let vc = XiblessViewController() + vc.view.frame = .init(x: 0, y: 0, width: 500, height: 500) + return NSWindow(contentViewController: vc) } // present(item: $model.sheet, id: \.self, style: .sheet) { count in //// let vc = NSHostingController( diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 1acc9e7ec1..2ce2d03ad6 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -6,154 +6,82 @@ import Combine @MainActor extension NSObject { @discardableResult - public func modal( + public func modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> ModalRepresentable + content: @escaping (UIBinding) -> Content ) -> ObservationToken { modal(item: item, id: id) { $item in content($item) - } beginModal: { modalRepresentable, _ in + } beginModal: { modalContent, _ in if NSApplication.shared.modalWindow != nil { NSApplication.shared.stopModal() onDismiss?() DispatchQueue.main.async { - ModalWindowsObserver.shared.observeWindow(modalRepresentable.window) - modalRepresentable.runModal() - modalRepresentable.onEndModal?.invoke() - modalRepresentable.onEndModal = nil + ModalWindowsObserver.shared.observeWindow(modalContent.window) + modalContent.runModal() + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil } } else { DispatchQueue.main.async { - ModalWindowsObserver.shared.observeWindow(modalRepresentable.window) - modalRepresentable.runModal() - modalRepresentable.onEndModal?.invoke() - modalRepresentable.onEndModal = nil + ModalWindowsObserver.shared.observeWindow(modalContent.window) + modalContent.runModal() + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil } } - } endModal: { provider, _ in + } endModal: { _, _ in NSApplication.shared.stopModal() onDismiss?() } } - private func modal( + private func modal( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> ModalRepresentable, + content: @escaping (UIBinding) -> Content, beginModal: @escaping ( - _ child: ModalRepresentable, + _ child: Content, _ transaction: UITransaction ) -> Void, endModal: @escaping ( - _ child: ModalRepresentable, + _ child: Content, _ transaction: UITransaction ) -> Void ) -> ObservationToken { - modal( + let modalObserver: ModalObserver = modalObserver() + return modalObserver.observe( item: item, id: { $0[keyPath: id] }, content: content, - beginModal: beginModal, - endModal: endModal + begin: beginModal, + end: endModal ) } - private func modal( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> ModalRepresentable, - beginModal: @escaping ( - _ child: ModalRepresentable, - _ transaction: UITransaction - ) -> Void, - endModal: @escaping ( - _ child: ModalRepresentable, - _ transaction: UITransaction - ) -> Void - ) -> ObservationToken { - let key = UIBindingIdentifier(item) - return observe { [weak self] transaction in - guard let self else { return } - if let unwrappedItem = UIBinding(item) { - if let presented = modaledByID[key] { - guard let presentationID = presented.modalID, - presentationID != id(unwrappedItem.wrappedValue) - else { - return - } - } - let modalRepresentable = content(unwrappedItem) - let onEndSheet = ClosureHolder { [presentationID = id(unwrappedItem.wrappedValue)] in - if let wrappedValue = item.wrappedValue, - presentationID == id(wrappedValue) { - item.wrappedValue = nil - } - } - modalRepresentable.onEndModal = onEndSheet - - self.modaledByID[key] = Modaled(modalRepresentable, id: id(unwrappedItem.wrappedValue)) - let work = { - withUITransaction(transaction) { - beginModal(modalRepresentable, transaction) - } - } - work() - } else if let modaled = modaledByID[key] { - if let modalRepresentable = modaled.provider { - endModal(modalRepresentable, transaction) - } - self.modaledByID[key] = nil - } - } - } - - private var modaledByID: [UIBindingIdentifier: Modaled] { - get { - (objc_getAssociatedObject(self, modaledKey) - as? [UIBindingIdentifier: Modaled]) - ?? [:] - } - set { - objc_setAssociatedObject( - self, modaledKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - } - - private var onEndModal: ClosureHolder? { - set { - objc_setAssociatedObject( - self, onEndModalKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - get { - objc_getAssociatedObject(self, onEndModalKey) as? ClosureHolder + private func modalObserver() -> ModalObserver { + if let observer = objc_getAssociatedObject(self, modalObserverKey) as? ModalObserver { + return observer + } else { + let modalObserver = ModalObserver(owner: self) + objc_setAssociatedObject(self, modalObserverKey, modalObserver, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return modalObserver } } } -private let onEndModalKey = malloc(1)! -private let modaledKey = malloc(1)! - +private let modalObserverKey = malloc(1)! @MainActor -private class Modaled { - weak var provider: ModalRepresentable? - let modalID: AnyHashable? - deinit { - // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to - // deinit alongside it on the main thread. If we use this other places we should force it - // to be a UIViewController as well, to ensure this functionality. - MainActor._assumeIsolated { - NSApplication.shared.stopModal() - } - } +private var modalObserverKeys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] +private typealias ModalObserver = NavigationObserver - init(_ provider: ModalRepresentable? = nil, id: AnyHashable?) { - self.provider = provider - self.modalID = id +extension Navigated where Content: ModalContent { + func clearup() { + NSApplication.shared.stopModal() } } + #endif diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift new file mode 100644 index 0000000000..c141aa1f11 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -0,0 +1,41 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol ModalContent: NavigationContent { + @discardableResult func runModal() -> NSApplication.ModalResponse + var window: NSWindow { get } +} + +extension NSWindow: ModalContent { + public var window: NSWindow { self } + + public func runModal() -> NSApplication.ModalResponse { + NSApplication.shared.runModal(for: self) + } + + public var onBeginNavigation: (() -> Void)? { + set { _onBeginNavigation = newValue } + get { _onBeginNavigation } + } + + public var onEndNavigation: (() -> Void)? { + set { _onEndNavigation = newValue } + get { _onEndNavigation } + } +} + +extension NSAlert: ModalContent { + public var onBeginNavigation: (() -> Void)? { + set { _onBeginNavigation = newValue } + get { _onBeginNavigation } + } + + public var onEndNavigation: (() -> Void)? { + set { _onEndNavigation = newValue } + get { _onEndNavigation } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/ModalRepresentable.swift b/Sources/AppKitNavigation/Navigation/ModalRepresentable.swift deleted file mode 100644 index f3526ea73e..0000000000 --- a/Sources/AppKitNavigation/Navigation/ModalRepresentable.swift +++ /dev/null @@ -1,23 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -@MainActor -@objc -public protocol ModalRepresentable where Self: NSObject { - @objc @discardableResult func runModal() -> NSApplication.ModalResponse - @objc var window: NSWindow { get } -} - -extension NSWindow: ModalRepresentable { - - public var window: NSWindow { self } - - public func runModal() -> NSApplication.ModalResponse { - NSApplication.shared.runModal(for: self) - } -} - -extension NSAlert: ModalRepresentable {} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift new file mode 100644 index 0000000000..718af62732 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -0,0 +1,82 @@ +import Foundation + +@MainActor +@objc +public protocol NavigationContent where Self: NSObject { + var onBeginNavigation: (() -> Void)? { set get } + var onEndNavigation: (() -> Void)? { set get } +} + +@MainActor +private var onBeginNavigationKeys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] + +@MainActor +private var onEndNavigationKeys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] +/// Hashable wrapper for any metatype value. +struct AnyHashableMetatype: Hashable { + static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { + return lhs.base == rhs.base + } + + let base: Any.Type + + init(_ base: Any.Type) { + self.base = base + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(base)) + } + // Pre Swift 4.2: + // var hashValue: Int { return ObjectIdentifier(base).hashValue } +} + +extension NavigationContent { + static var onBeginNavigationKey: UnsafeMutableRawPointer { + let key = AnyHashableMetatype(Self.self) + if let onBeginNavigationKey = onBeginNavigationKeys[key] { + return onBeginNavigationKey + } else { + let onBeginNavigationKey = malloc(1)! + onBeginNavigationKeys[key] = onBeginNavigationKey + return onBeginNavigationKey + } + } + + static var onEndNavigationKey: UnsafeMutableRawPointer { + let key = AnyHashableMetatype(Self.self) + if let onEndNavigationKey = onEndNavigationKeys[key] { + return onEndNavigationKey + } else { + let onEndNavigationKey = malloc(1)! + onEndNavigationKeys[key] = onEndNavigationKey + return onEndNavigationKey + } + } + + var _onBeginNavigation: (() -> Void)? { + set { + objc_setAssociatedObject(self, Self.onBeginNavigationKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + get { + objc_getAssociatedObject(self, Self.onBeginNavigationKey) as? () -> Void + } + } + + var _onEndNavigation: (() -> Void)? { + set { + objc_setAssociatedObject(self, Self.onEndNavigationKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + get { + objc_getAssociatedObject(self, Self.onEndNavigationKey) as? () -> Void + } + } +} + +@MainActor +protocol NavigatedProtocol: AnyObject { + associatedtype Content: NavigationContent + var content: Content? { get } + var id: AnyHashable? { get } + init(_ content: Content, id: AnyHashable?) +} diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift new file mode 100644 index 0000000000..b7e6b22b96 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift @@ -0,0 +1,86 @@ +import Foundation +import SwiftNavigation + +@MainActor +class NavigationObserver: NSObject { + + + private var navigatedByID: [UIBindingIdentifier: Navigated] = [:] + + unowned let owner: Owner + + init(owner: Owner) { + self.owner = owner + super.init() + } + + func observe( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> Content, + begin: @escaping ( + _ content: Content, + _ transaction: UITransaction + ) -> Void, + end: @escaping ( + _ content: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObservationToken { + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let presented = navigatedByID[key] { + guard let presentationID = presented.id, + presentationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let content = content(unwrappedItem) + let onEndNavigation = { [presentationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + presentationID == id(wrappedValue) { + item.wrappedValue = nil + } + } + content.onEndNavigation = onEndNavigation + + self.navigatedByID[key] = Navigated(content, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + begin(content, transaction) + } + } + commitWork(work) + } else if let navigated = navigatedByID[key] { + if let content = navigated.content { + end(content, transaction) + } + self.navigatedByID[key] = nil + } + } + } + + func commitWork(_ work: @escaping () -> Void) { + work() + } +} + +@MainActor +class Navigated { + weak var content: Content? + let id: AnyHashable? + func clearup() {} + deinit { + MainActor._assumeIsolated { + clearup() + } + } + + required init(_ content: Content, id: AnyHashable?) { + self.content = content + self.id = id + } +} diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 8a9f6a52a2..08e70ddafe 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -20,7 +20,7 @@ extension NSViewController { isPresented: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController + content: @escaping () -> PresentationContent ) -> ObservationToken { present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } } @@ -43,7 +43,7 @@ extension NSViewController { item: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController + content: @escaping (Item) -> PresentationContent ) -> ObservationToken { present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } @@ -67,7 +67,7 @@ extension NSViewController { item: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController + content: @escaping (UIBinding) -> PresentationContent ) -> ObservationToken { present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } @@ -92,7 +92,7 @@ extension NSViewController { id: KeyPath, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController + content: @escaping (Item) -> PresentationContent ) -> ObservationToken { present(item: item, id: id, style: style, onDismiss: onDismiss) { content($0.wrappedValue) @@ -120,7 +120,7 @@ extension NSViewController { id: KeyPath, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController + content: @escaping (UIBinding) -> PresentationContent ) -> ObservationToken { destination(item: item, id: id) { $item in content($item) @@ -174,10 +174,10 @@ extension NSViewController { @discardableResult public func destination( isPresented: UIBinding, - content: @escaping () -> NSViewController, - present: @escaping (NSViewController, UITransaction) -> Void, + content: @escaping () -> PresentationContent, + present: @escaping (PresentationContent, UITransaction) -> Void, dismiss: @escaping ( - _ child: NSViewController, + _ child: PresentationContent, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -204,10 +204,10 @@ extension NSViewController { @discardableResult public func destination( item: UIBinding, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping (NSViewController, UITransaction) -> Void, + content: @escaping (UIBinding) -> PresentationContent, + present: @escaping (PresentationContent, UITransaction) -> Void, dismiss: @escaping ( - _ child: NSViewController, + _ child: PresentationContent, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -239,23 +239,25 @@ extension NSViewController { public func destination( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> NSViewController, + content: @escaping (UIBinding) -> PresentationContent, present: @escaping ( - _ child: NSViewController, + _ child: PresentationContent, _ transaction: UITransaction ) -> Void, dismiss: @escaping ( - _ child: NSViewController, + _ child: PresentationContent, _ transaction: UITransaction ) -> Void ) -> ObservationToken { - destination( - item: item, - id: { $0[keyPath: id] }, - content: content, - present: present, - dismiss: dismiss - ) +// destination( +// item: item, +// id: { $0[keyPath: id] }, +// content: content, +// present: present, +// dismiss: dismiss +// ) + presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) + } private func destination( @@ -325,6 +327,54 @@ extension NSViewController { } private static let presentedKey = malloc(1)! + + private var presentationObserver: PresentationObserver { + set { + objc_setAssociatedObject(self, presentationObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + if let observer = objc_getAssociatedObject(self, presentationObserverKey) as? PresentationObserver { + return observer + } else { + let observer = PresentationObserver(owner: self) + self.presentationObserver = observer + return observer + } + } + } + +} +private let presentationObserverKey = malloc(1)! + +public protocol PresentationContent: NavigationContent { + func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) +} +extension NSViewController: PresentationContent {} +extension NavigationContent where Self: NSViewController { + var _onEndNavigation: (() -> Void)? { + set { + onDismiss = newValue + } + get { + onDismiss + } + } +} + +class PresentationObserver: NavigationObserver { + override func commitWork(_ work: @escaping () -> Void) { + if owner.hasViewAppeared { + work() + } else { + owner.onViewAppear.append(work) + } + } +} + +extension Navigated where Content: NSViewController { + func clearup() { + self.content?.dismiss(nil) + } } @MainActor @@ -340,7 +390,7 @@ private class Presented { } } - init(_ controller: NSViewController, id presentationID: AnyHashable? = nil) { + required init(_ controller: NSViewController, id presentationID: AnyHashable? = nil) { self.controller = controller self.presentationID = presentationID } diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 935a2182d4..350dff6d90 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -2,7 +2,7 @@ import AppKit -extension SheetRepresentable { +extension SheetContent { /// Sheet a representable modally when a binding to a Boolean value you provide is true. /// /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. @@ -15,7 +15,7 @@ extension SheetRepresentable { public func sheet( isSheeted: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> SheetRepresentable + content: @escaping () -> SheetContent ) -> ObservationToken { sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } @@ -37,7 +37,7 @@ extension SheetRepresentable { public func sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> SheetRepresentable + content: @escaping (Item) -> SheetContent ) -> ObservationToken { sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } @@ -60,7 +60,7 @@ extension SheetRepresentable { public func sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> SheetRepresentable + content: @escaping (UIBinding) -> SheetContent ) -> ObservationToken { sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } @@ -84,7 +84,7 @@ extension SheetRepresentable { item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> SheetRepresentable + content: @escaping (Item) -> SheetContent ) -> ObservationToken { sheet(item: item, id: id, onDismiss: onDismiss) { content($0.wrappedValue) @@ -96,29 +96,29 @@ extension SheetRepresentable { item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> SheetRepresentable + content: @escaping (UIBinding) -> SheetContent ) -> ObservationToken { sheet(item: item, id: id) { $item in content($item) - } beginSheet: { [weak self] child, transaction in + } beginSheet: { [weak self] child, _ in guard let self else { return } if let attachedSheetWindow = currentWindow?.attachedSheet { self.endSheet(for: attachedSheetWindow) onDismiss?() Task { @MainActor in await self.beginSheet(for: child) - child.onEndSheet?.invoke() - child.onEndSheet = nil + child.onEndNavigation?() + child.onEndNavigation = nil } } else { Task { @MainActor in await self.beginSheet(for: child) - child.onEndSheet?.invoke() - child.onEndSheet = nil + child.onEndNavigation?() + child.onEndNavigation = nil } } - } endSheet: { [weak self] provider, transaction in - self?.endSheet(for: provider) + } endSheet: { [weak self] content, _ in + self?.endSheet(for: content) onDismiss?() } } @@ -126,35 +126,35 @@ extension SheetRepresentable { private func sheet( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> SheetRepresentable, + content: @escaping (UIBinding) -> SheetContent, beginSheet: @escaping ( - _ child: SheetRepresentable, + _ child: SheetContent, _ transaction: UITransaction ) -> Void, endSheet: @escaping ( - _ child: SheetRepresentable, + _ child: SheetContent, _ transaction: UITransaction ) -> Void ) -> ObservationToken { - sheet( + sheetObserver.observe( item: item, id: { $0[keyPath: id] }, content: content, - beginSheet: beginSheet, - endSheet: endSheet + begin: beginSheet, + end: endSheet ) } private func sheet( item: UIBinding, id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> SheetRepresentable, + content: @escaping (UIBinding) -> SheetContent, beginSheet: @escaping ( - _ child: SheetRepresentable, + _ child: SheetContent, _ transaction: UITransaction ) -> Void, endSheet: @escaping ( - _ child: SheetRepresentable, + _ child: SheetContent, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -163,7 +163,7 @@ extension SheetRepresentable { guard let self else { return } if let unwrappedItem = UIBinding(item) { if let presented = sheetedByID[key] { - guard let presentationID = presented.sheetID, + guard let presentationID = presented.id, presentationID != id(unwrappedItem.wrappedValue) else { return @@ -186,7 +186,7 @@ extension SheetRepresentable { } work() } else if let presented = sheetedByID[key] { - if let controller = presented.provider { + if let controller = presented.content { endSheet(controller, transaction) } self.sheetedByID[key] = nil @@ -217,27 +217,44 @@ extension SheetRepresentable { objc_getAssociatedObject(self, onEndSheetKey) as? ClosureHolder } } + + private var sheetObserver: SheetObserver { + set { + objc_setAssociatedObject(self, sheetObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + if let observer = objc_getAssociatedObject(self, sheetObserverKey) as? SheetObserver { + return observer + } else { + let observer = SheetObserver(owner: self) + self.sheetObserver = observer + return observer + } + } + } } +private typealias SheetObserver = NavigationObserver +private let sheetObserverKey = malloc(1)! private let onEndSheetKey = malloc(1)! private let sheetedKey = malloc(1)! @MainActor -private class Sheeted { - weak var provider: SheetRepresentable? - let sheetID: AnyHashable? +private class Sheeted: NavigatedProtocol { + weak var content: (any SheetContent)? + let id: AnyHashable? deinit { // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to // deinit alongside it on the main thread. If we use this other places we should force it // to be a UIViewController as well, to ensure this functionality. MainActor._assumeIsolated { - self.provider?.currentWindow?.endSheeted() + self.content?.currentWindow?.endSheeted() } } - init(_ provider: SheetRepresentable? = nil, id: AnyHashable?) { - self.provider = provider - self.sheetID = id + required init(_ content: any SheetContent, id: AnyHashable?) { + self.content = content + self.id = id } } @@ -250,4 +267,10 @@ extension NSWindow { } } +extension Navigated where Content: SheetContent { + func clearup() { + self.content?.currentWindow?.endSheeted() + } +} + #endif diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift new file mode 100644 index 0000000000..2fc4318bac --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -0,0 +1,90 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +@objc +public protocol SheetContent: NavigationContent { + var currentWindow: NSWindow? { get } + func beginSheet(for content: SheetContent) async + func endSheet(for content: SheetContent) +} + +extension SheetContent { + func _beginSheet(for content: any SheetContent) async { + if let sheetedWindow = content.currentWindow { + await currentWindow?.beginSheet(sheetedWindow) + } + } + + func _endSheet(for content: any SheetContent) { + if let sheetedWindow = content.currentWindow { + currentWindow?.endSheet(sheetedWindow) + } + } +} + +extension NSWindow: SheetContent { + public var currentWindow: NSWindow? { self } + public func beginSheet(for content: any SheetContent) async { + await _beginSheet(for: content) + } + public func endSheet(for content: any SheetContent) { + _endSheet(for: content) + } +} + +extension NSWindowController: SheetContent { + public var currentWindow: NSWindow? { window } + public func beginSheet(for content: any SheetContent) async { + await _beginSheet(for: content) + } + public func endSheet(for content: any SheetContent) { + _endSheet(for: content) + } + + public var onBeginNavigation: (() -> Void)? { + set { _onBeginNavigation = newValue } + get { _onBeginNavigation } + } + + public var onEndNavigation: (() -> Void)? { + set { _onEndNavigation = newValue } + get { _onEndNavigation } + } +} + +extension NSViewController: SheetContent { + public var currentWindow: NSWindow? { view.window } + public func beginSheet(for content: any SheetContent) async { + await _beginSheet(for: content) + } + public func endSheet(for content: any SheetContent) { + _endSheet(for: content) + } + + public var onBeginNavigation: (() -> Void)? { + set { _onBeginNavigation = newValue } + get { _onBeginNavigation } + } + + public var onEndNavigation: (() -> Void)? { + set { _onEndNavigation = newValue } + get { _onEndNavigation } + } +} + +extension NSAlert: SheetContent { + public var currentWindow: NSWindow? { window } + + public func beginSheet(for content: any SheetContent) async { + guard let parentWindow = content.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + public func endSheet(for content: any SheetContent) { + content.currentWindow?.endSheet(window) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/SheetRepresentable.swift b/Sources/AppKitNavigation/Navigation/SheetRepresentable.swift deleted file mode 100644 index 03b16aede2..0000000000 --- a/Sources/AppKitNavigation/Navigation/SheetRepresentable.swift +++ /dev/null @@ -1,51 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -@MainActor -public protocol SheetRepresentable: NSObject { - var currentWindow: NSWindow? { get } - func beginSheet(for provider: SheetRepresentable) async - func endSheet(for provider: SheetRepresentable) -} - -extension SheetRepresentable { - public func beginSheet(for provider: any SheetRepresentable) async { - if let sheetedWindow = provider.currentWindow { - await currentWindow?.beginSheet(sheetedWindow) - } - } - - public func endSheet(for provider: any SheetRepresentable) { - if let sheetedWindow = provider.currentWindow { - currentWindow?.endSheet(sheetedWindow) - } - } -} - -extension NSWindow: SheetRepresentable { - public var currentWindow: NSWindow? { self } -} - -extension NSWindowController: SheetRepresentable { - public var currentWindow: NSWindow? { window } -} - -extension NSViewController: SheetRepresentable { - public var currentWindow: NSWindow? { view.window } -} - -extension NSAlert: SheetRepresentable { - public var currentWindow: NSWindow? { window } - - public func beginSheet(for provider: any SheetRepresentable) async { - guard let parentWindow = provider.currentWindow else { return } - await beginSheetModal(for: parentWindow) - } - - public func endSheet(for provider: any SheetRepresentable) { - provider.currentWindow?.endSheet(window) - } -} - -#endif From 8e0e22523b1372b7083916d81adeff082ad6aeff Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 16 Aug 2024 22:20:14 +0800 Subject: [PATCH 008/141] WIP --- ...ppKit+BasicsNavigationViewController.swift | 31 ++- .../AppKitNavigation/Navigation/Modal.swift | 10 +- .../Navigation/ModalContent.swift | 22 +- .../Navigation/NavigationContent.swift | 68 +++---- .../Navigation/Presentation.swift | 191 ++++++------------ .../AppKitNavigation/Navigation/Sheet.swift | 145 +++---------- .../Navigation/SheetContent.swift | 43 +--- 7 files changed, 141 insertions(+), 369 deletions(-) diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index 8ec32db007..5cf3b8a187 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -63,19 +63,28 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS // alert.addAction(UIAlertAction(title: "OK", style: .default)) // return alert // } - modal(item: $model.sheet, id: \.self) { count in - let vc = XiblessViewController() - vc.view.frame = .init(x: 0, y: 0, width: 500, height: 500) - return NSWindow(contentViewController: vc) - } -// present(item: $model.sheet, id: \.self, style: .sheet) { count in -//// let vc = NSHostingController( -//// rootView: Form { Text(count.description) } -//// ) + + + +// modal(item: $model.sheet, id: \.self) { count in +// let vc = XiblessViewController() +// vc.view.frame = .init(x: 0, y: 0, width: 500, height: 500) +// return NSWindow(contentViewController: vc) +// } + +// sheet(item: $model.sheet, id: \.self) { count in // let vc = XiblessViewController() -// vc.preferredContentSize = .init(width: 300, height: 200) -// return vc +// vc.view.frame = .init(x: 0, y: 0, width: 500, height: 500) +// return NSWindow(contentViewController: vc) // } + present(item: $model.sheet, id: \.self, style: .sheet) { count in +// let vc = NSHostingController( +// rootView: Form { Text(count.description) } +// ) + let vc = XiblessViewController() + vc.preferredContentSize = .init(width: 300, height: 200) + return vc + } present(isPresented: $model.isSheetPresented, style: .sheet) { let vc = NSHostingController( rootView: Form { Text("Hello!") } diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 2ce2d03ad6..927a64d815 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -63,19 +63,19 @@ extension NSObject { } private func modalObserver() -> ModalObserver { - if let observer = objc_getAssociatedObject(self, modalObserverKey) as? ModalObserver { + if let observer = objc_getAssociatedObject(self, modalObserverKeys.key(of: Content.self)) as? ModalObserver { return observer } else { - let modalObserver = ModalObserver(owner: self) - objc_setAssociatedObject(self, modalObserverKey, modalObserver, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return modalObserver + let observer = ModalObserver(owner: self) + objc_setAssociatedObject(self, modalObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer } } } private let modalObserverKey = malloc(1)! @MainActor -private var modalObserverKeys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] +private var modalObserverKeys = AssociatedKeys() private typealias ModalObserver = NavigationObserver extension Navigated where Content: ModalContent { diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift index c141aa1f11..a372687396 100644 --- a/Sources/AppKitNavigation/Navigation/ModalContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -14,28 +14,8 @@ extension NSWindow: ModalContent { public func runModal() -> NSApplication.ModalResponse { NSApplication.shared.runModal(for: self) } - - public var onBeginNavigation: (() -> Void)? { - set { _onBeginNavigation = newValue } - get { _onBeginNavigation } - } - - public var onEndNavigation: (() -> Void)? { - set { _onEndNavigation = newValue } - get { _onEndNavigation } - } } -extension NSAlert: ModalContent { - public var onBeginNavigation: (() -> Void)? { - set { _onBeginNavigation = newValue } - get { _onBeginNavigation } - } - - public var onEndNavigation: (() -> Void)? { - set { _onEndNavigation = newValue } - get { _onEndNavigation } - } -} +extension NSAlert: ModalContent {} #endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift index 718af62732..3af25d1ecd 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationContent.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -1,18 +1,33 @@ import Foundation @MainActor -@objc -public protocol NavigationContent where Self: NSObject { +public protocol NavigationContent: AnyObject { var onBeginNavigation: (() -> Void)? { set get } var onEndNavigation: (() -> Void)? { set get } } @MainActor -private var onBeginNavigationKeys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] +private var onBeginNavigationKeys = AssociatedKeys() @MainActor -private var onEndNavigationKeys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] -/// Hashable wrapper for any metatype value. +private var onEndNavigationKeys = AssociatedKeys() + +struct AssociatedKeys { + var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] + + mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { + let key = AnyHashableMetatype(type) + if let associatedKey = keys[key] { + return associatedKey + } else { + let associatedKey = malloc(1)! + keys[key] = associatedKey + return associatedKey + } + } +} + + struct AnyHashableMetatype: Hashable { static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { return lhs.base == rhs.base @@ -27,56 +42,25 @@ struct AnyHashableMetatype: Hashable { func hash(into hasher: inout Hasher) { hasher.combine(ObjectIdentifier(base)) } - // Pre Swift 4.2: - // var hashValue: Int { return ObjectIdentifier(base).hashValue } } extension NavigationContent { - static var onBeginNavigationKey: UnsafeMutableRawPointer { - let key = AnyHashableMetatype(Self.self) - if let onBeginNavigationKey = onBeginNavigationKeys[key] { - return onBeginNavigationKey - } else { - let onBeginNavigationKey = malloc(1)! - onBeginNavigationKeys[key] = onBeginNavigationKey - return onBeginNavigationKey - } - } - - static var onEndNavigationKey: UnsafeMutableRawPointer { - let key = AnyHashableMetatype(Self.self) - if let onEndNavigationKey = onEndNavigationKeys[key] { - return onEndNavigationKey - } else { - let onEndNavigationKey = malloc(1)! - onEndNavigationKeys[key] = onEndNavigationKey - return onEndNavigationKey - } - } - var _onBeginNavigation: (() -> Void)? { + public var onBeginNavigation: (() -> Void)? { set { - objc_setAssociatedObject(self, Self.onBeginNavigationKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } get { - objc_getAssociatedObject(self, Self.onBeginNavigationKey) as? () -> Void + objc_getAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self)) as? () -> Void } } - var _onEndNavigation: (() -> Void)? { + public var onEndNavigation: (() -> Void)? { set { - objc_setAssociatedObject(self, Self.onEndNavigationKey, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + objc_setAssociatedObject(self, onEndNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } get { - objc_getAssociatedObject(self, Self.onEndNavigationKey) as? () -> Void + objc_getAssociatedObject(self, onEndNavigationKeys.key(of: Self.self)) as? () -> Void } } } - -@MainActor -protocol NavigatedProtocol: AnyObject { - associatedtype Content: NavigationContent - var content: Content? { get } - var id: AnyHashable? { get } - init(_ content: Content, id: AnyHashable?) -} diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 08e70ddafe..676c452c76 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -16,11 +16,11 @@ extension NSViewController { /// - content: A closure that returns the view controller to display over the current view /// controller's content. @discardableResult - public func present( + public func present( isPresented: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping () -> PresentationContent + content: @escaping () -> Content ) -> ObservationToken { present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } } @@ -39,11 +39,11 @@ extension NSViewController { /// - content: A closure that returns the view controller to display over the current view /// controller's content. @discardableResult - public func present( + public func present( item: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> PresentationContent + content: @escaping (Item) -> Content ) -> ObservationToken { present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } @@ -63,11 +63,11 @@ extension NSViewController { /// controller's content. @_disfavoredOverload @discardableResult - public func present( + public func present( item: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> PresentationContent + content: @escaping (UIBinding) -> Content ) -> ObservationToken { present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } @@ -87,12 +87,12 @@ extension NSViewController { /// - content: A closure that returns the view controller to display over the current view /// controller's content. @discardableResult - public func present( + public func present( item: UIBinding, id: KeyPath, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> PresentationContent + content: @escaping (Item) -> Content ) -> ObservationToken { present(item: item, id: id, style: style, onDismiss: onDismiss) { content($0.wrappedValue) @@ -115,26 +115,27 @@ extension NSViewController { /// controller's content. @_disfavoredOverload @discardableResult - public func present( + public func present( item: UIBinding, id: KeyPath, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> PresentationContent + content: @escaping (UIBinding) -> Content ) -> ObservationToken { destination(item: item, id: id) { $item in content($item) } present: { [weak self] child, transaction in guard let self else { return } - if presentedViewControllers != nil { - self.dismiss(nil) + if let presentedViewController = presentedViewControllers?.first { + self.dismiss(presentedViewController) onDismiss?() - self.present(child, for: style) + child.presented(from: self, style: style) } else { - self.present(child, for: style) + child.presented(from: self, style: style) } - } dismiss: { [weak self] _, transaction in - self?.dismiss(nil) + } dismiss: { [weak self] child, transaction in + guard let self else { return } + child.dismiss(from: self) onDismiss?() } } @@ -172,12 +173,12 @@ extension NSViewController { /// - present: The closure to execute when presenting the view controller. /// - dismiss: The closure to execute when dismissing the view controller. @discardableResult - public func destination( + public func destination( isPresented: UIBinding, - content: @escaping () -> PresentationContent, - present: @escaping (PresentationContent, UITransaction) -> Void, + content: @escaping () -> Content, + present: @escaping (Content, UITransaction) -> Void, dismiss: @escaping ( - _ child: PresentationContent, + _ child: Content, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -202,21 +203,22 @@ extension NSViewController { /// - present: The closure to execute when presenting the view controller. /// - dismiss: The closure to execute when dismissing the view controller. @discardableResult - public func destination( + public func destination( item: UIBinding, - content: @escaping (UIBinding) -> PresentationContent, - present: @escaping (PresentationContent, UITransaction) -> Void, + content: @escaping (UIBinding) -> Content, + present: @escaping (Content, UITransaction) -> Void, dismiss: @escaping ( - _ child: PresentationContent, + _ child: Content, _ transaction: UITransaction ) -> Void ) -> ObservationToken { - destination( + let presentationObserver: PresentationObserver = presentationObserver() + return presentationObserver.observe( item: item, id: { _ in nil }, content: content, - present: present, - dismiss: dismiss + begin: present, + end: dismiss ) } @@ -236,16 +238,16 @@ extension NSViewController { /// - present: The closure to execute when presenting the view controller. /// - dismiss: The closure to execute when dismissing the view controller. @discardableResult - public func destination( + public func destination( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> PresentationContent, + content: @escaping (UIBinding) -> Content, present: @escaping ( - _ child: PresentationContent, + _ child: Content, _ transaction: UITransaction ) -> Void, dismiss: @escaping ( - _ child: PresentationContent, + _ child: Content, _ transaction: UITransaction ) -> Void ) -> ObservationToken { @@ -256,100 +258,45 @@ extension NSViewController { // present: present, // dismiss: dismiss // ) - presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) + let presentationObserver: PresentationObserver = presentationObserver() + return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) } - private func destination( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObservationToken { - let key = UIBindingIdentifier(item) - return observe { [weak self] transaction in - guard let self else { return } - if let unwrappedItem = UIBinding(item) { - if let presented = presentedByID[key] { - guard let presentationID = presented.presentationID, - presentationID != id(unwrappedItem.wrappedValue) - else { - return - } - } - let childController = content(unwrappedItem) - let onDismiss = { [presentationID = id(unwrappedItem.wrappedValue)] in - if let wrappedValue = item.wrappedValue, - presentationID == id(wrappedValue) { - item.wrappedValue = nil - } - } - childController.onDismiss = onDismiss - - self.presentedByID[key] = Presented(childController, id: id(unwrappedItem.wrappedValue)) - let work = { - withUITransaction(transaction) { - present(childController, transaction) - } - } - if hasViewAppeared { - work() - } else { - onViewAppear.append(work) - } - } else if let presented = presentedByID[key] { - if let controller = presented.controller { - dismiss(controller, transaction) - } - self.presentedByID[key] = nil - } - } - } - - fileprivate var presentedByID: [UIBindingIdentifier: Presented] { - get { - (objc_getAssociatedObject(self, Self.presentedKey) - as? [UIBindingIdentifier: Presented]) - ?? [:] - } - set { - objc_setAssociatedObject( - self, Self.presentedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - } - - private static let presentedKey = malloc(1)! - private var presentationObserver: PresentationObserver { - set { - objc_setAssociatedObject(self, presentationObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - if let observer = objc_getAssociatedObject(self, presentationObserverKey) as? PresentationObserver { - return observer - } else { - let observer = PresentationObserver(owner: self) - self.presentationObserver = observer - return observer - } + private func presentationObserver() -> PresentationObserver { + if let observer = objc_getAssociatedObject(self, presentationObserverKeys.key(of: Content.self)) as? PresentationObserver { + return observer + } else { + let observer = PresentationObserver(owner: self) + objc_setAssociatedObject(self, presentationObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer } } } private let presentationObserverKey = malloc(1)! +@MainActor +private var presentationObserverKeys = AssociatedKeys() + +@MainActor public protocol PresentationContent: NavigationContent { func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) + func dismiss(from presentingViewController: NSViewController) } -extension NSViewController: PresentationContent {} + + +extension NSViewController: PresentationContent { + public func presented(from presentingViewController: NSViewController, style: TransitionStyle) { + presentingViewController.present(self, for: style) + } + + public func dismiss(from presentingViewController: NSViewController) { + presentingViewController.dismiss(self) + } +} + extension NavigationContent where Self: NSViewController { var _onEndNavigation: (() -> Void)? { set { @@ -361,7 +308,7 @@ extension NavigationContent where Self: NSViewController { } } -class PresentationObserver: NavigationObserver { +class PresentationObserver: NavigationObserver { override func commitWork(_ work: @escaping () -> Void) { if owner.hasViewAppeared { work() @@ -377,22 +324,4 @@ extension Navigated where Content: NSViewController { } } -@MainActor -private class Presented { - weak var controller: NSViewController? - let presentationID: AnyHashable? - deinit { - // NB: This can only be assumed because it is held in a NSViewController and is guaranteed to - // deinit alongside it on the main thread. If we use this other places we should force it - // to be a NSViewController as well, to ensure this functionality. - MainActor._assumeIsolated { - self.controller?.dismiss(nil) - } - } - - required init(_ controller: NSViewController, id presentationID: AnyHashable? = nil) { - self.controller = controller - self.presentationID = presentationID - } -} #endif diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 350dff6d90..a2ff357ebd 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -12,10 +12,10 @@ extension SheetContent { /// - onDismiss: The closure to execute when dismissing the representable. /// - content: A closure that returns the representable to display over the current window content. @discardableResult - public func sheet( + public func sheet( isSheeted: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> SheetContent + content: @escaping () -> Content ) -> ObservationToken { sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } @@ -34,10 +34,10 @@ extension SheetContent { /// - content: A closure that returns the view controller to display over the current view /// controller's content. @discardableResult - public func sheet( + public func sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> SheetContent + content: @escaping (Item) -> Content ) -> ObservationToken { sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } @@ -57,10 +57,10 @@ extension SheetContent { /// controller's content. @_disfavoredOverload @discardableResult - public func sheet( + public func sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> SheetContent + content: @escaping (UIBinding) -> Content ) -> ObservationToken { sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } @@ -80,11 +80,11 @@ extension SheetContent { /// - content: A closure that returns the view controller to display over the current view /// controller's content. @discardableResult - public func sheet( + public func sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> SheetContent + content: @escaping (Item) -> Content ) -> ObservationToken { sheet(item: item, id: id, onDismiss: onDismiss) { content($0.wrappedValue) @@ -92,11 +92,11 @@ extension SheetContent { } @discardableResult - public func sheet( + public func sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> SheetContent + content: @escaping (UIBinding) -> Content ) -> ObservationToken { sheet(item: item, id: id) { $item in content($item) @@ -123,20 +123,21 @@ extension SheetContent { } } - private func sheet( + private func sheet( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> SheetContent, + content: @escaping (UIBinding) -> Content, beginSheet: @escaping ( - _ child: SheetContent, + _ child: Content, _ transaction: UITransaction ) -> Void, endSheet: @escaping ( - _ child: SheetContent, + _ child: Content, _ transaction: UITransaction ) -> Void ) -> ObservationToken { - sheetObserver.observe( + let sheetObserver: SheetObserver = sheetObserver() + return sheetObserver.observe( item: item, id: { $0[keyPath: id] }, content: content, @@ -145,118 +146,26 @@ extension SheetContent { ) } - private func sheet( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> SheetContent, - beginSheet: @escaping ( - _ child: SheetContent, - _ transaction: UITransaction - ) -> Void, - endSheet: @escaping ( - _ child: SheetContent, - _ transaction: UITransaction - ) -> Void - ) -> ObservationToken { - let key = UIBindingIdentifier(item) - return observe { [weak self] transaction in - guard let self else { return } - if let unwrappedItem = UIBinding(item) { - if let presented = sheetedByID[key] { - guard let presentationID = presented.id, - presentationID != id(unwrappedItem.wrappedValue) - else { - return - } - } - let childController = content(unwrappedItem) - let onEndSheet = ClosureHolder { [presentationID = id(unwrappedItem.wrappedValue)] in - if let wrappedValue = item.wrappedValue, - presentationID == id(wrappedValue) { - item.wrappedValue = nil - } - } - childController.onEndSheet = onEndSheet - - self.sheetedByID[key] = Sheeted(childController, id: id(unwrappedItem.wrappedValue)) - let work = { - withUITransaction(transaction) { - beginSheet(childController, transaction) - } - } - work() - } else if let presented = sheetedByID[key] { - if let controller = presented.content { - endSheet(controller, transaction) - } - self.sheetedByID[key] = nil - } - } - } - - private var sheetedByID: [UIBindingIdentifier: Sheeted] { - get { - (objc_getAssociatedObject(self, sheetedKey) - as? [UIBindingIdentifier: Sheeted]) - ?? [:] - } - set { - objc_setAssociatedObject( - self, sheetedKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - } - private var onEndSheet: ClosureHolder? { - set { - objc_setAssociatedObject( - self, onEndSheetKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - get { - objc_getAssociatedObject(self, onEndSheetKey) as? ClosureHolder - } - } - - private var sheetObserver: SheetObserver { - set { - objc_setAssociatedObject(self, sheetObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - if let observer = objc_getAssociatedObject(self, sheetObserverKey) as? SheetObserver { - return observer - } else { - let observer = SheetObserver(owner: self) - self.sheetObserver = observer - return observer - } + private func sheetObserver() -> SheetObserver { + if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver { + return observer + } else { + let observer = SheetObserver(owner: self) + objc_setAssociatedObject(self, sheetObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer } } } -private typealias SheetObserver = NavigationObserver +private typealias SheetObserver = NavigationObserver private let sheetObserverKey = malloc(1)! -private let onEndSheetKey = malloc(1)! -private let sheetedKey = malloc(1)! @MainActor -private class Sheeted: NavigatedProtocol { - weak var content: (any SheetContent)? - let id: AnyHashable? - deinit { - // NB: This can only be assumed because it is held in a UIViewController and is guaranteed to - // deinit alongside it on the main thread. If we use this other places we should force it - // to be a UIViewController as well, to ensure this functionality. - MainActor._assumeIsolated { - self.content?.currentWindow?.endSheeted() - } - } +private var sheetObserverKeys = AssociatedKeys() - required init(_ content: any SheetContent, id: AnyHashable?) { - self.content = content - self.id = id - } -} +private let onEndSheetKey = malloc(1)! +private let sheetedKey = malloc(1)! extension NSWindow { func endSheeted() { diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index 2fc4318bac..8162d88d3a 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -3,7 +3,6 @@ import AppKit @MainActor -@objc public protocol SheetContent: NavigationContent { var currentWindow: NSWindow? { get } func beginSheet(for content: SheetContent) async @@ -11,13 +10,13 @@ public protocol SheetContent: NavigationContent { } extension SheetContent { - func _beginSheet(for content: any SheetContent) async { + public func beginSheet(for content: any SheetContent) async { if let sheetedWindow = content.currentWindow { await currentWindow?.beginSheet(sheetedWindow) } } - func _endSheet(for content: any SheetContent) { + public func endSheet(for content: any SheetContent) { if let sheetedWindow = content.currentWindow { currentWindow?.endSheet(sheetedWindow) } @@ -26,52 +25,14 @@ extension SheetContent { extension NSWindow: SheetContent { public var currentWindow: NSWindow? { self } - public func beginSheet(for content: any SheetContent) async { - await _beginSheet(for: content) - } - public func endSheet(for content: any SheetContent) { - _endSheet(for: content) - } } extension NSWindowController: SheetContent { public var currentWindow: NSWindow? { window } - public func beginSheet(for content: any SheetContent) async { - await _beginSheet(for: content) - } - public func endSheet(for content: any SheetContent) { - _endSheet(for: content) - } - - public var onBeginNavigation: (() -> Void)? { - set { _onBeginNavigation = newValue } - get { _onBeginNavigation } - } - - public var onEndNavigation: (() -> Void)? { - set { _onEndNavigation = newValue } - get { _onEndNavigation } - } } extension NSViewController: SheetContent { public var currentWindow: NSWindow? { view.window } - public func beginSheet(for content: any SheetContent) async { - await _beginSheet(for: content) - } - public func endSheet(for content: any SheetContent) { - _endSheet(for: content) - } - - public var onBeginNavigation: (() -> Void)? { - set { _onBeginNavigation = newValue } - get { _onBeginNavigation } - } - - public var onEndNavigation: (() -> Void)? { - set { _onEndNavigation = newValue } - get { _onEndNavigation } - } } extension NSAlert: SheetContent { From 01fafbe19444c6532cd7f99240815af1172b331c Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 16 Aug 2024 23:02:53 +0800 Subject: [PATCH 009/141] WIP --- ...ppKit+BasicsNavigationViewController.swift | 49 ++-- ...+ConciseEnumNavigationViewController.swift | 242 ++++++++---------- .../AppKit/AppKitCaseStudies.swift | 2 +- .../Internal/AssociatedKeys.swift | 36 +++ .../AppKitNavigation/Navigation/Modal.swift | 98 ++++++- .../Navigation/NavigationContent.swift | 33 --- .../Navigation/NavigationObserver.swift | 2 - .../Navigation/Presentation.swift | 69 +---- .../Navigation/PresentationContent.swift | 41 +++ 9 files changed, 306 insertions(+), 266 deletions(-) create mode 100644 Sources/AppKitNavigation/Internal/AssociatedKeys.swift create mode 100644 Sources/AppKitNavigation/Navigation/PresentationContent.swift diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index 5cf3b8a187..a9a20fb710 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -17,7 +17,7 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS let showAlertButton = NSButton { [weak self] _ in self?.model.alert = "Hello!" } - + let showSheetButton = NSButton { [weak self] _ in self?.model.sheet = .random(in: 1 ... 1_000) DispatchQueue.main.asyncAfter(deadline: .now() + 3) { @@ -51,45 +51,26 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" showSheetButton.title = "Sheet is presented: \(model.sheet != nil ? "✅" : "❌")" showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.isSheetPresented ? "✅" : "❌")" - } -// present(item: $model.alert, id: \.self) { message in -// let alert = UIAlertController( -// title: "This is an alert", -// message: message, -// preferredStyle: .alert -// ) -// alert.addAction(UIAlertAction(title: "OK", style: .default)) -// return alert -// } - - - -// modal(item: $model.sheet, id: \.self) { count in -// let vc = XiblessViewController() -// vc.view.frame = .init(x: 0, y: 0, width: 500, height: 500) -// return NSWindow(contentViewController: vc) -// } - -// sheet(item: $model.sheet, id: \.self) { count in -// let vc = XiblessViewController() -// vc.view.frame = .init(x: 0, y: 0, width: 500, height: 500) -// return NSWindow(contentViewController: vc) -// } + modal(item: $model.alert, id: \.self) { message in + let alert = NSAlert() + alert.messageText = "This is an alert" + alert.informativeText = message + alert.addButton(withTitle: "OK") + return alert + } + present(item: $model.sheet, id: \.self, style: .sheet) { count in -// let vc = NSHostingController( -// rootView: Form { Text(count.description) } -// ) - let vc = XiblessViewController() - vc.preferredContentSize = .init(width: 300, height: 200) - return vc + NSHostingController( + rootView: Form { Text(count.description) }.frame(width: 100, height: 100, alignment: .center) + ) } + present(isPresented: $model.isSheetPresented, style: .sheet) { - let vc = NSHostingController( - rootView: Form { Text("Hello!") } + NSHostingController( + rootView: Form { Text("Hello!") }.frame(width: 100, height: 100, alignment: .center) ) - return vc } } diff --git a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift index af08f37dfe..8abcdec54c 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -1,138 +1,108 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -//import SwiftUI -//import UIKit -//import UIKitNavigation -// -//class ConciseEnumNavigationViewController: UIViewController, UIKitCaseStudy { -// let caseStudyNavigationTitle = "Enum navigation" -// let caseStudyTitle = "Concise enum navigation" -// let readMe = """ -// This case study demonstrates how to navigate to multiple destinations from a single optional \ -// enum. -// -// This allows you to be very concise with your domain modeling by having a single enum \ -// describe all the possible destinations you can navigate to. In the case of this demo, we have \ -// four cases in the enum, which means there are exactly 5 possible states, including the case \ -// where none are active. -// -// If you were to instead model this domain with 4 optionals (or booleans), then you would have \ -// 16 possible states, of which only 5 are valid. That can leak complexity into your domain \ -// because you can never be sure of exactly what is presented at a given time. -// """ -// @UIBindable var model = Model() -// -// override func viewDidLoad() { -// super.viewDidLoad() -// view.backgroundColor = .systemBackground -// -// let showAlertButton = UIButton( -// type: .system, -// primaryAction: UIAction { [weak self] _ in -// self?.model.destination = .alert("Hello!") -// }) -// let showSheetButton = UIButton( -// type: .system, -// primaryAction: UIAction { [weak self] _ in -// self?.model.destination = .sheet(.random(in: 1...1_000)) -// }) -// let showSheetFromBooleanButton = UIButton( -// type: .system, -// primaryAction: UIAction { [weak self] _ in -// self?.model.destination = .sheetWithoutPayload -// }) -// let drillDownButton = UIButton( -// type: .system, -// primaryAction: UIAction { [weak self] _ in -// self?.model.destination = .drillDown(.random(in: 1...1_000)) -// }) -// -// let stack = UIStackView(arrangedSubviews: [ -// showAlertButton, -// showSheetButton, -// drillDownButton, -// showSheetFromBooleanButton, -// ]) -// stack.axis = .vertical -// stack.spacing = 12 -// stack.translatesAutoresizingMaskIntoConstraints = false -// -// view.addSubview(stack) -// NSLayoutConstraint.activate([ -// stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), -// stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), -// stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), -// ]) -// -// observe { [weak self] in -// guard let self else { return } -// -// showAlertButton.setTitle( -// "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")", -// for: .normal -// ) -// showSheetButton.setTitle( -// "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")", -// for: .normal -// ) -// showSheetFromBooleanButton.setTitle( -// "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")", -// for: .normal -// ) -// drillDownButton.setTitle( -// "Drill-down is presented: \(model.destination?.drillDown != nil ? "✅" : "❌")", -// for: .normal -// ) -// } -// -// present(item: $model.destination.alert, id: \.self) { message in -// let alert = UIAlertController( -// title: "This is an alert", -// message: message, -// preferredStyle: .alert -// ) -// alert.addAction(UIAlertAction(title: "OK", style: .default)) -// return alert -// } -// present(item: $model.destination.sheet, id: \.self) { count in -// let vc = UIHostingController( -// rootView: Form { Text(count.description) } -// ) -// vc.mediumDetents() -// return vc -// } -// present(isPresented: UIBinding($model.destination.sheetWithoutPayload)) { -// let vc = UIHostingController( -// rootView: Form { Text("Hello!") } -// ) -// vc.mediumDetents() -// return vc -// } -// navigationDestination(item: $model.destination.drillDown) { count in -// UIHostingController( -// rootView: Form { -// Text(count.description) -// } -// ) -// } -// } -// -// @Observable -// class Model { -// var destination: Destination? -// @CasePathable -// @dynamicMemberLookup -// enum Destination { -// case alert(String) -// case drillDown(Int) -// case sheet(Int) -// case sheetWithoutPayload -// } -// } -//} -// -//#Preview { -// UINavigationController( -// rootViewController: BasicsNavigationViewController() -// ) -//} +import SwiftUI +import AppKit +import AppKitNavigation + +class ConciseEnumNavigationViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyNavigationTitle = "Enum navigation" + let caseStudyTitle = "Concise enum navigation" + let readMe = """ + This case study demonstrates how to navigate to multiple destinations from a single optional \ + enum. + + This allows you to be very concise with your domain modeling by having a single enum \ + describe all the possible destinations you can navigate to. In the case of this demo, we have \ + four cases in the enum, which means there are exactly 5 possible states, including the case \ + where none are active. + + If you were to instead model this domain with 4 optionals (or booleans), then you would have \ + 16 possible states, of which only 5 are valid. That can leak complexity into your domain \ + because you can never be sure of exactly what is presented at a given time. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let showAlertButton = NSButton { [weak self] _ in + self?.model.destination = .alert("Hello!") + } + let showSheetButton = NSButton { [weak self] _ in + self?.model.destination = .sheet(.random(in: 1 ... 1_000)) + } + let showSheetFromBooleanButton = NSButton { [weak self] _ in + self?.model.destination = .sheetWithoutPayload + } + + let stack = NSStackView(views: [ + showAlertButton, + showSheetButton, + showSheetFromBooleanButton, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) + + observe { [weak self] in + guard let self else { return } + + showAlertButton.title = "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")" + showSheetButton.title = "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")" + showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")" + } + + modal(item: $model.destination.alert, id: \.self) { message in + let alert = NSAlert() + alert.messageText = "This is an alert" + alert.informativeText = message + alert.addButton(withTitle: "OK") + return alert + } + present(item: $model.destination.sheet, id: \.self, style: .sheet) { [unowned self] count in + + NSHostingController( + rootView: Form { + Text(count.description) + Button("Close") { + self.model.destination = nil + } + }.frame(width: 200, height: 200, alignment: .center) + ) + } + present(isPresented: UIBinding($model.destination.sheetWithoutPayload), style: .sheet) { [unowned self] in + NSHostingController( + rootView: Form { + Text("Hello!") + Button("Close") { + self.model.destination = nil + } + }.frame(width: 200, height: 200, alignment: .center) + ) + } + } + + @Observable + class Model { + var destination: Destination? + @CasePathable + @dynamicMemberLookup + enum Destination { + case alert(String) + case drillDown(Int) + case sheet(Int) + case sheetWithoutPayload + } + } +} + +#Preview { + ConciseEnumNavigationViewController() +} #endif diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift index acdf6cb0e2..0a13289c2b 100644 --- a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -17,7 +17,7 @@ struct AppKitCaseStudiesView: View { CaseStudyGroupView("Optional navigation") { BasicsNavigationViewController() // TODO: Alert/dialog state -// ConciseEnumNavigationViewController() + ConciseEnumNavigationViewController() } // CaseStudyGroupView("Stack navigation") { // StaticNavigationStackController() diff --git a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift new file mode 100644 index 0000000000..1df9f50edc --- /dev/null +++ b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift @@ -0,0 +1,36 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +struct AssociatedKeys { + var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] + + mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { + let key = AnyHashableMetatype(type) + if let associatedKey = keys[key] { + return associatedKey + } else { + let associatedKey = malloc(1)! + keys[key] = associatedKey + return associatedKey + } + } +} + +struct AnyHashableMetatype: Hashable { + static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { + return lhs.base == rhs.base + } + + let base: Any.Type + + init(_ base: Any.Type) { + self.base = base + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(base)) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 927a64d815..3ab909472b 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -3,8 +3,101 @@ import AppKit import Combine +@MainActor +private var modalObserverKeys = AssociatedKeys() + +private typealias ModalObserver = NavigationObserver + @MainActor extension NSObject { + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - isSheeted: A binding to a Boolean value that determines whether to sheet the representable + /// - onDismiss: The closure to execute when dismissing the representable. + /// - content: A closure that returns the representable to display over the current window content. + @discardableResult + public func modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObservationToken { + modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObservationToken { + modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObservationToken { + modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + /// Sheet a representable modally when a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet`, `fullScreenCover`, and `popover` view modifiers, but for AppKit. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. When `item` is + /// non-`nil`, the item's content is passed to the `content` closure. You display this + /// content in a view controller that you create that is displayed to the user. If `item`'s + /// identity changes, the view controller is dismissed and replaced with a new one using the + /// same process. + /// - id: The key path to the provided item's identifier. + /// - onDismiss: The closure to execute when dismissing the view controller. + /// - content: A closure that returns the view controller to display over the current view + /// controller's content. + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObservationToken { + modal(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + @discardableResult public func modal( item: UIBinding, @@ -73,11 +166,6 @@ extension NSObject { } } -private let modalObserverKey = malloc(1)! -@MainActor -private var modalObserverKeys = AssociatedKeys() -private typealias ModalObserver = NavigationObserver - extension Navigated where Content: ModalContent { func clearup() { NSApplication.shared.stopModal() diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift index 3af25d1ecd..a67417c95f 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationContent.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -12,40 +12,7 @@ private var onBeginNavigationKeys = AssociatedKeys() @MainActor private var onEndNavigationKeys = AssociatedKeys() -struct AssociatedKeys { - var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] - - mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { - let key = AnyHashableMetatype(type) - if let associatedKey = keys[key] { - return associatedKey - } else { - let associatedKey = malloc(1)! - keys[key] = associatedKey - return associatedKey - } - } -} - - -struct AnyHashableMetatype: Hashable { - static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { - return lhs.base == rhs.base - } - - let base: Any.Type - - init(_ base: Any.Type) { - self.base = base - } - - func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(base)) - } -} - extension NavigationContent { - public var onBeginNavigation: (() -> Void)? { set { objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift index b7e6b22b96..a666af9959 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift @@ -3,8 +3,6 @@ import SwiftNavigation @MainActor class NavigationObserver: NSObject { - - private var navigatedByID: [UIBindingIdentifier: Navigated] = [:] unowned let owner: Owner diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 676c452c76..f8c4cc5e4c 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -4,6 +4,19 @@ import IssueReporting import AppKit import AppKitNavigationShim +@MainActor +private var presentationObserverKeys = AssociatedKeys() + +class PresentationObserver: NavigationObserver { + override func commitWork(_ work: @escaping () -> Void) { + if owner.hasViewAppeared { + work() + } else { + owner.onViewAppear.append(work) + } + } +} + extension NSViewController { /// Presents a view controller modally when a binding to a Boolean value you provide is true. /// @@ -140,26 +153,6 @@ extension NSViewController { } } - public enum TransitionStyle { - case sheet - case modalWindow - case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) - case custom(NSViewControllerPresentationAnimator) - } - - fileprivate func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { - switch style { - case .sheet: - presentAsSheet(viewControllerToPresent) - case .modalWindow: - presentAsModalWindow(viewControllerToPresent) - case let .popover(rect, view, preferredEdge, behavior): - present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) - case let .custom(animator): - present(viewControllerToPresent, animator: animator) - } - } - /// Presents a view controller when a binding to a Boolean value you provide is true. /// /// This helper powers ``present(isPresented:onDismiss:content:)`` and @@ -260,10 +253,8 @@ extension NSViewController { // ) let presentationObserver: PresentationObserver = presentationObserver() return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) - } - private func presentationObserver() -> PresentationObserver { if let observer = objc_getAssociatedObject(self, presentationObserverKeys.key(of: Content.self)) as? PresentationObserver { return observer @@ -273,28 +264,6 @@ extension NSViewController { return observer } } - -} -private let presentationObserverKey = malloc(1)! - -@MainActor -private var presentationObserverKeys = AssociatedKeys() - -@MainActor -public protocol PresentationContent: NavigationContent { - func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) - func dismiss(from presentingViewController: NSViewController) -} - - -extension NSViewController: PresentationContent { - public func presented(from presentingViewController: NSViewController, style: TransitionStyle) { - presentingViewController.present(self, for: style) - } - - public func dismiss(from presentingViewController: NSViewController) { - presentingViewController.dismiss(self) - } } extension NavigationContent where Self: NSViewController { @@ -308,19 +277,9 @@ extension NavigationContent where Self: NSViewController { } } -class PresentationObserver: NavigationObserver { - override func commitWork(_ work: @escaping () -> Void) { - if owner.hasViewAppeared { - work() - } else { - owner.onViewAppear.append(work) - } - } -} - extension Navigated where Content: NSViewController { func clearup() { - self.content?.dismiss(nil) + content?.dismiss(nil) } } diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift new file mode 100644 index 0000000000..eba08ad600 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/PresentationContent.swift @@ -0,0 +1,41 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol PresentationContent: NavigationContent { + func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) + func dismiss(from presentingViewController: NSViewController) +} + +extension NSViewController: PresentationContent { + public func presented(from presentingViewController: NSViewController, style: TransitionStyle) { + presentingViewController.present(self, for: style) + } + + public func dismiss(from presentingViewController: NSViewController) { + presentingViewController.dismiss(self) + } + + public enum TransitionStyle { + case sheet + case modalWindow + case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + case custom(NSViewControllerPresentationAnimator) + } + + private func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { + switch style { + case .sheet: + presentAsSheet(viewControllerToPresent) + case .modalWindow: + presentAsModalWindow(viewControllerToPresent) + case let .popover(rect, view, preferredEdge, behavior): + present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) + case let .custom(animator): + present(viewControllerToPresent, animator: animator) + } + } +} + +#endif From cd4422f1951113f3a35747df638d7f6309a5f0fc Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Sat, 17 Aug 2024 01:31:20 +0800 Subject: [PATCH 010/141] WIP-Fix bugs and support NSSave/OpenPanel --- ...ppKit+BasicsNavigationViewController.swift | 22 ++- Package@swift-6.0.swift | 15 ++ .../Bindings/NSFontManager.swift | 1 + .../Bindings/NSOpenPanel.swift | 60 ++++++ .../Bindings/NSTargetAction.swift | 16 +- .../Internal/AssumeIsolated.swift | 5 + .../AppKitNavigation/Navigation/Modal.swift | 5 +- .../Navigation/ModalContent.swift | 20 +- .../Navigation/NavigationContent.swift | 5 + .../Navigation/NavigationObserver.swift | 15 +- .../AppKitNavigation/Navigation/Sheet.swift | 17 +- Sources/AppKitNavigationShim/include/shim.h | 28 +-- Sources/AppKitNavigationShim/shim.m | 180 +++++++++++------- 13 files changed, 281 insertions(+), 108 deletions(-) diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index a9a20fb710..c7a71253f3 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -48,17 +48,24 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS observe { [weak self] in guard let self else { return } - showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" + if let url = model.url { + showAlertButton.title = "URL is: \(url)" + } else { + showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" + } showSheetButton.title = "Sheet is presented: \(model.sheet != nil ? "✅" : "❌")" showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.isSheetPresented ? "✅" : "❌")" } - modal(item: $model.alert, id: \.self) { message in - let alert = NSAlert() - alert.messageText = "This is an alert" - alert.informativeText = message - alert.addButton(withTitle: "OK") - return alert + modal(item: $model.alert, id: \.self) { [unowned self] message in +// let alert = NSAlert() +// alert.messageText = "This is an alert" +// alert.informativeText = message +// alert.addButton(withTitle: "OK") +// return alert + let openPanel = NSOpenPanel(url: $model.url) + openPanel.message = message + return openPanel } present(item: $model.sheet, id: \.self, style: .sheet) { count in @@ -79,6 +86,7 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS var alert: String? var isSheetPresented = false var sheet: Int? + var url: URL? } } diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 9ed432ff67..96bf3a52ea 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -23,6 +23,10 @@ let package = Package( name: "UIKitNavigation", targets: ["UIKitNavigation"] ), + .library( + name: "AppKitNavigation", + targets: ["AppKitNavigation"] + ), ], dependencies: [ .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -73,6 +77,17 @@ let package = Package( .target( name: "UIKitNavigationShim" ), + .target( + name: "AppKitNavigation", + dependencies: [ + "SwiftNavigation", + "AppKitNavigationShim", + .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), + ] + ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 0525f42582..752c4a62dc 100644 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -1,6 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit +import SwiftNavigation extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { public var appkitNavigationTarget: AnyObject? { diff --git a/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift index 893f31d20e..896135f71e 100644 --- a/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift @@ -1,5 +1,65 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit +import AppKitNavigationShim + +extension NSSavePanel { + public convenience init(url: UIBinding) { + self.init() + bind(url: url) + } + + @discardableResult + public func bind(url binding: UIBinding) -> ObservationToken { + appKitNavigation_onFinalURL = { url in + binding.wrappedValue = url + } + + let observationToken = ObservationToken { [weak self] in + guard let self else { return } + MainActor._assumeIsolated { + self.appKitNavigation_onFinalURL = nil + } + } + observationTokens[\NSSavePanel.url] = observationToken + return observationToken + } + + public func unbindURL() { + observationTokens[\NSSavePanel.url]?.cancel() + observationTokens[\NSSavePanel.url] = nil + } + + +} + +extension NSOpenPanel { + + public convenience init(urls: UIBinding<[URL]>) { + self.init() + bind(urls: urls) + } + + @discardableResult + public func bind(urls binding: UIBinding<[URL]>) -> ObservationToken { + appKitNavigation_onFinalURLs = { urls in + binding.wrappedValue = urls + } + + let observationToken = ObservationToken { [weak self] in + guard let self else { return } + MainActor._assumeIsolated { + self.appKitNavigation_onFinalURLs = nil + } + } + observationTokens[\NSOpenPanel.urls] = observationToken + return observationToken + } + + public func unbindURLs() { + observationTokens[\NSOpenPanel.urls]?.cancel() + observationTokens[\NSOpenPanel.urls] = nil + } +} #endif diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift index 3412960d4d..4c0dce7971 100644 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -134,6 +134,21 @@ extension NSTargetActionProtocol { observationTokens[keyPath] = nil } +// var observationTokens: [AnyKeyPath: ObservationToken] { +// get { +// objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] +// ?? [:] +// } +// set { +// objc_setAssociatedObject( +// self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC +// ) +// } +// } +} + +@MainActor +extension NSObject { var observationTokens: [AnyKeyPath: ObservationToken] { get { objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] @@ -148,7 +163,6 @@ extension NSTargetActionProtocol { } - @MainActor private let observationTokensKey = malloc(1)! @MainActor diff --git a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift index 9a7465a99f..93f1c40098 100644 --- a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift +++ b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift @@ -1,3 +1,5 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import Foundation extension MainActor { @@ -28,3 +30,6 @@ extension MainActor { #endif } } + + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 3ab909472b..615f985e1d 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -1,7 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit -import Combine @MainActor private var modalObserverKeys = AssociatedKeys() @@ -113,7 +112,7 @@ extension NSObject { onDismiss?() DispatchQueue.main.async { ModalWindowsObserver.shared.observeWindow(modalContent.window) - modalContent.runModal() + modalContent.appKitNavigationRunModal() modalContent.onEndNavigation?() modalContent.onEndNavigation = nil } @@ -121,7 +120,7 @@ extension NSObject { } else { DispatchQueue.main.async { ModalWindowsObserver.shared.observeWindow(modalContent.window) - modalContent.runModal() + modalContent.appKitNavigationRunModal() modalContent.onEndNavigation?() modalContent.onEndNavigation = nil } diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift index a372687396..00772647f2 100644 --- a/Sources/AppKitNavigation/Navigation/ModalContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -4,18 +4,32 @@ import AppKit @MainActor public protocol ModalContent: NavigationContent { - @discardableResult func runModal() -> NSApplication.ModalResponse + @discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse var window: NSWindow { get } } extension NSWindow: ModalContent { public var window: NSWindow { self } - public func runModal() -> NSApplication.ModalResponse { + public func appKitNavigationRunModal() -> NSApplication.ModalResponse { + __appKitNavigationRunModal() + } + + @objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse { NSApplication.shared.runModal(for: self) } } -extension NSAlert: ModalContent {} +extension NSSavePanel { + override func __appKitNavigationRunModal() -> NSApplication.ModalResponse { + runModal() + } +} + +extension NSAlert: ModalContent { + public func appKitNavigationRunModal() -> NSApplication.ModalResponse { + runModal() + } +} #endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift index a67417c95f..762032cf09 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationContent.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -1,3 +1,5 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import Foundation @MainActor @@ -31,3 +33,6 @@ extension NavigationContent { } } } + + +#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift index a666af9959..c9af34445f 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift @@ -1,3 +1,5 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import Foundation import SwiftNavigation @@ -29,17 +31,17 @@ class NavigationObserver: NSObject return observe { [weak self] transaction in guard let self else { return } if let unwrappedItem = UIBinding(item) { - if let presented = navigatedByID[key] { - guard let presentationID = presented.id, - presentationID != id(unwrappedItem.wrappedValue) + if let navigated = navigatedByID[key] { + guard let navigationID = navigated.id, + navigationID != id(unwrappedItem.wrappedValue) else { return } } let content = content(unwrappedItem) - let onEndNavigation = { [presentationID = id(unwrappedItem.wrappedValue)] in + let onEndNavigation = { [navigationID = id(unwrappedItem.wrappedValue)] in if let wrappedValue = item.wrappedValue, - presentationID == id(wrappedValue) { + navigationID == id(wrappedValue) { item.wrappedValue = nil } } @@ -82,3 +84,6 @@ class Navigated { self.id = id } } + + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index a2ff357ebd..76d8786698 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -2,6 +2,11 @@ import AppKit +private typealias SheetObserver = NavigationObserver + +@MainActor +private var sheetObserverKeys = AssociatedKeys() + extension SheetContent { /// Sheet a representable modally when a binding to a Boolean value you provide is true. /// @@ -146,7 +151,6 @@ extension SheetContent { ) } - private func sheetObserver() -> SheetObserver { if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver { return observer @@ -158,15 +162,6 @@ extension SheetContent { } } -private typealias SheetObserver = NavigationObserver -private let sheetObserverKey = malloc(1)! - -@MainActor -private var sheetObserverKeys = AssociatedKeys() - -private let onEndSheetKey = malloc(1)! -private let sheetedKey = malloc(1)! - extension NSWindow { func endSheeted() { guard sheetParent != nil else { @@ -178,7 +173,7 @@ extension NSWindow { extension Navigated where Content: SheetContent { func clearup() { - self.content?.currentWindow?.endSheeted() + content?.currentWindow?.endSheeted() } } diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h index 1d2054f3ca..e1844275f7 100644 --- a/Sources/AppKitNavigationShim/include/shim.h +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -1,19 +1,25 @@ #if __has_include() - #include +#include - #if __has_include() && !TARGET_OS_MACCATALYST - @import AppKit; +#if __has_include() && !TARGET_OS_MACCATALYST +@import AppKit; - NS_ASSUME_NONNULL_BEGIN +NS_ASSUME_NONNULL_BEGIN - @interface NSViewController (AppKitNavigation) +@interface NSViewController (AppKitNavigation) - @property BOOL hasViewAppeared; - @property (nullable) void (^onDismiss)(); - @property NSArray *onViewAppear; +@property BOOL hasViewAppeared; +@property (nullable) void (^ onDismiss)(); +@property NSArray *onViewAppear; - @end +@end - NS_ASSUME_NONNULL_END - #endif +@interface NSSavePanel (AppKitNavigation) +@property (nullable) void (^ AppKitNavigation_onFinalURL)(NSURL *_Nullable); +@property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); +@end + + +NS_ASSUME_NONNULL_END #endif +#endif /* if __has_include() */ diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index a2fb9479a5..21f5f9c08b 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -1,106 +1,152 @@ #if __has_include() - #include +#include - #if __has_include() && !TARGET_OS_MACCATALYST - @import ObjectiveC; - @import AppKit; - #import "shim.h" +#if __has_include() && !TARGET_OS_MACCATALYST +@import ObjectiveC; +@import AppKit; +#import "shim.h" - @interface AppKitNavigationShim : NSObject +@interface AppKitNavigationShim : NSObject - @end +@end - @implementation AppKitNavigationShim +@implementation AppKitNavigationShim - // NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible - // for state-driven presentation and dismissal of child features. +// NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible +// for state-driven presentation and dismissal of child features. - + (void)load { - method_exchangeImplementations( ++ (void)load { + method_exchangeImplementations( class_getInstanceMethod(NSViewController.class, @selector(viewDidAppear)), class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidAppear)) - ); - method_exchangeImplementations( + ); + method_exchangeImplementations( class_getInstanceMethod(NSViewController.class, @selector(viewDidDisappear)), class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidDisappear)) - ); - method_exchangeImplementations( + ); + method_exchangeImplementations( class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) - ); + ); + method_exchangeImplementations( + class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), + class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURLs:")), + class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURLs:)) + ); +} + +@end + +@implementation NSSavePanel (AppKitNavigation) + +- (void)setAppKitNavigation_onFinalURLs:(void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { + objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs), AppKitNavigation_onFinalURLs, OBJC_ASSOCIATION_COPY); +} + +- (void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { + return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs)); +} + +- (void)setAppKitNavigation_onFinalURL:(void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { + objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURL), AppKitNavigation_onFinalURL, OBJC_ASSOCIATION_COPY); +} + +- (void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { + return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURL)); +} + +- (void)AppKitNavigation_setFinalURL:(nullable NSURL *)url { + [self AppKitNavigation_setFinalURL:url]; + if (self.AppKitNavigation_onFinalURL) { + self.AppKitNavigation_onFinalURL(url); } +} - @end +- (void)AppKitNavigation_setFinalURLs:(NSArray *)urls { + [self AppKitNavigation_setFinalURLs:urls]; + if (self.AppKitNavigation_onFinalURLs) { + self.AppKitNavigation_onFinalURLs(urls); + } +} + +@end - static void *hasViewAppearedKey = &hasViewAppearedKey; - static void *onDismissKey = &onDismissKey; - static void *onViewAppearKey = &onViewAppearKey; +static void *hasViewAppearedKey = &hasViewAppearedKey; +static void *onDismissKey = &onDismissKey; +static void *onViewAppearKey = &onViewAppearKey; - @implementation NSViewController (AppKitNavigation) +@implementation NSViewController (AppKitNavigation) - - (void)AppKitNavigation_viewDidAppear { - [self AppKitNavigation_viewDidAppear]; +- (void)AppKitNavigation_viewDidAppear { + [self AppKitNavigation_viewDidAppear]; - if (self.hasViewAppeared) { + if (self.hasViewAppeared) { return; - } - self.hasViewAppeared = YES; - for (void (^work)() in self.onViewAppear) { - work(); - } - self.onViewAppear = @[]; } - - (void)setBeingDismissed:(BOOL)beingDismissed { - objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); - } + self.hasViewAppeared = YES; - - (BOOL)isBeingDismissed { - return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; + for (void (^work)() in self.onViewAppear) { + work(); } - - (void)AppKitNavigation_viewDidDisappear { - [self AppKitNavigation_viewDidDisappear]; + self.onViewAppear = @[]; +} + +- (void)setBeingDismissed:(BOOL)beingDismissed { + objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); +} + +- (BOOL)isBeingDismissed { + return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; +} + +- (void)AppKitNavigation_viewDidDisappear { + [self AppKitNavigation_viewDidDisappear]; - if ((self.isBeingDismissed) && self.onDismiss != NULL) { + if ((self.isBeingDismissed) && self.onDismiss != NULL) { self.onDismiss(); self.onDismiss = nil; [self setBeingDismissed:NO]; - } } +} - - (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { - [self AppKitNavigation_dismissViewController:sender]; - [self setBeingDismissed:YES]; - } +- (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { + [self AppKitNavigation_dismissViewController:sender]; + [self setBeingDismissed:YES]; +} - - (BOOL)hasViewAppeared { - return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; - } +- (BOOL)hasViewAppeared { + return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; +} - - (void)setHasViewAppeared:(BOOL)hasViewAppeared { - objc_setAssociatedObject( +- (void)setHasViewAppeared:(BOOL)hasViewAppeared { + objc_setAssociatedObject( self, hasViewAppearedKey, @(hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC - ); - } + ); +} - - (void (^)())onDismiss { - return objc_getAssociatedObject(self, onDismissKey); - } +- (void (^)())onDismiss { + return objc_getAssociatedObject(self, onDismissKey); +} - - (void)setOnDismiss:(void (^)())onDismiss { - objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); - } +- (void)setOnDismiss:(void (^)())onDismiss { + objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); +} - - (NSMutableArray *)onViewAppear { - id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); - return onViewAppear == nil ? @[] : onViewAppear; - } +- (NSMutableArray *)onViewAppear { + id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); - - (void)setOnViewAppear:(NSMutableArray *)onViewAppear { - objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); - } + return onViewAppear == nil ? @[] : onViewAppear; +} + +- (void)setOnViewAppear:(NSMutableArray *)onViewAppear { + objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); +} - @end - #endif -#endif +@end +#endif /* if __has_include() && !TARGET_OS_MACCATALYST */ +#endif /* if __has_include() */ From 27c61522cf309d39386c898b03ea66a8f1323e8b Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Sun, 18 Aug 2024 22:25:00 +0800 Subject: [PATCH 011/141] WIP-Support WiFiFeature Case Study --- ...pKit+NSControlBindingsViewController.swift | 11 +- .../AppKit/AppKitCaseStudies.swift | 10 +- Examples/CaseStudies/Internal/CaseStudy.swift | 6 +- .../WiFiFeature/ConnectToNetworkFeature.swift | 113 ------ .../WiFiFeature/NetworkDetailFeature.swift | 101 ----- .../WiFiFeature/WiFiSettingsFeature.swift | 313 ---------------- ...ppKit+ConnectToNetworkViewController.swift | 177 +++++++++ .../ConnectToNetworkModel.swift | 36 ++ ...UIKit+ConnectToNetworkViewController.swift | 90 +++++ .../{UIKit => }/WiFiFeature/Network.swift | 0 .../AppKit+NetworkDetailViewController.swift | 65 ++++ .../NetworkDetailModel.swift | 32 ++ .../UIKit+NetworkDetailViewController.swift | 76 ++++ .../AppKit+WiFiSettingsViewController.swift | 352 ++++++++++++++++++ .../UIKit+WiFiSettingsViewController.swift | 199 ++++++++++ .../WiFiSettingsModel.swift | 75 ++++ .../WiFiSettingsViewController+.swift | 60 +++ Examples/Examples.xcodeproj/project.pbxproj | 82 +++- .../AppKitNavigation/Bindings/NSAlert.swift | 2 +- .../Bindings/NSColorPanel.swift | 2 +- .../AppKitNavigation/Bindings/NSControl.swift | 13 +- .../Bindings/NSFontManager.swift | 10 +- ...SOpenPanel.swift => NSSaveOpenPanel.swift} | 0 .../Bindings/NSTargetAction.swift | 70 +++- .../Bindings/NSTextField.swift | 19 +- .../Internal/ModalWindowsObserver.swift | 13 +- .../NavigationObserver.swift | 0 .../AppKitNavigation/Navigation/Modal.swift | 74 ++++ .../ModalSession.swift} | 2 + .../Navigation/ModalSessionContent.swift | 29 ++ .../Navigation/SheetContent.swift | 21 +- .../xcshareddata/swiftpm/Package.resolved | 8 +- 32 files changed, 1463 insertions(+), 598 deletions(-) delete mode 100644 Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift delete mode 100644 Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift delete mode 100644 Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift create mode 100644 Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift create mode 100644 Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift create mode 100644 Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/UIKit+ConnectToNetworkViewController.swift rename Examples/CaseStudies/{UIKit => }/WiFiFeature/Network.swift (100%) create mode 100644 Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift create mode 100644 Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift create mode 100644 Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/UIKit+NetworkDetailViewController.swift create mode 100644 Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift create mode 100644 Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/UIKit+WiFiSettingsViewController.swift create mode 100644 Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsModel.swift create mode 100644 Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsViewController+.swift rename Sources/AppKitNavigation/Bindings/{NSOpenPanel.swift => NSSaveOpenPanel.swift} (100%) rename Sources/AppKitNavigation/{Navigation => Internal}/NavigationObserver.swift (100%) rename Sources/AppKitNavigation/{Bindings/NSSavePanel.swift => Navigation/ModalSession.swift} (97%) create mode 100644 Sources/AppKitNavigation/Navigation/ModalSessionContent.swift diff --git a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift index fbecc6031d..75fe38967b 100644 --- a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift @@ -8,6 +8,15 @@ class XiblessViewController: NSViewController { override func loadView() { view = contentView } + + override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("") + } } class NSControlBindingsViewController: XiblessViewController, AppKitCaseStudy { @@ -117,10 +126,8 @@ extension String { } } - #Preview(traits: .fixedLayout(width: 500, height: 800)) { NSControlBindingsViewController() } - #endif diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift index 0a13289c2b..5fb7bee5c3 100644 --- a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -24,11 +24,11 @@ struct AppKitCaseStudiesView: View { // ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) // // TODO: state restoration // } -// CaseStudyGroupView("Advanced") { -// // TODO: Deep link -// // TODO: Dismissal (show off from VCs and views) -// WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)) -// } + CaseStudyGroupView("Advanced") { + // TODO: Deep link + // TODO: Dismissal (show off from VCs and views) + WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)) + } } .navigationTitle("AppKit") } diff --git a/Examples/CaseStudies/Internal/CaseStudy.swift b/Examples/CaseStudies/Internal/CaseStudy.swift index 88730a9b21..b6d739cb31 100644 --- a/Examples/CaseStudies/Internal/CaseStudy.swift +++ b/Examples/CaseStudies/Internal/CaseStudy.swift @@ -1,6 +1,4 @@ import SwiftUI -import AppKitNavigation -import UIKitNavigation protocol CaseStudy { var readMe: String { get } @@ -12,12 +10,16 @@ protocol CaseStudy { protocol SwiftUICaseStudy: CaseStudy, View {} #if canImport(UIKit) && !os(watchOS) +import UIKitNavigation + protocol UIKitCaseStudy: CaseStudy, UIViewController {} extension UIKitCaseStudy { var usesOwnLayout: Bool { true } } #endif #if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKitNavigation + protocol AppKitCaseStudy: CaseStudy, NSViewController {} extension AppKitCaseStudy { var usesOwnLayout: Bool { true } diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift deleted file mode 100644 index fe305a2748..0000000000 --- a/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift +++ /dev/null @@ -1,113 +0,0 @@ -#if canImport(UIKit) && !os(watchOS) -import SwiftUI -import UIKitNavigation -import XCTestDynamicOverlay - -@Observable -@MainActor -class ConnectToNetworkModel: Identifiable { - var incorrectPasswordAlertIsPresented = false - var isConnecting = false - var onConnect: (Network) -> Void = { _ in - XCTFail("ConnectToNetworkModel.onConnect unimplemented.") - } - let network: Network - var password = "" - init(network: Network) { - self.network = network - } - func joinButtonTapped() async { - isConnecting = true - defer { isConnecting = false } - try? await Task.sleep(for: .seconds(1)) - if password == "blob" { - onConnect(network) - } else { - incorrectPasswordAlertIsPresented = true - } - } -} - -final class ConnectToNetworkViewController: UIViewController { - @UIBindable var model: ConnectToNetworkModel - - init(model: ConnectToNetworkModel) { - self.model = model - super.init(nibName: nil, bundle: nil) - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - navigationItem.title = "Enter the password for “\(model.network.name)”" - - let passwordTextField = UITextField(text: $model.password) - passwordTextField.borderStyle = .line - passwordTextField.isSecureTextEntry = true - passwordTextField.becomeFirstResponder() - passwordTextField.placeholder = "The password is 'blob'" - let joinButton = UIButton( - type: .system, - primaryAction: UIAction { [weak self] _ in - guard let self else { return } - Task { - await self.model.joinButtonTapped() - } - }) - joinButton.setTitle("Join network", for: .normal) - let activityIndicator = UIActivityIndicatorView(style: .medium) - activityIndicator.startAnimating() - - let stack = UIStackView(arrangedSubviews: [ - passwordTextField, - joinButton, - activityIndicator, - ]) - stack.axis = .vertical - stack.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerXAnchor.constraint(equalTo: view.centerXAnchor), - stack.centerYAnchor.constraint(equalTo: view.centerYAnchor), - stack.widthAnchor.constraint(equalToConstant: 200), - ]) - - observe { [weak self, weak passwordTextField] in - guard - let self, - let passwordTextField - else { return } - - passwordTextField.isEnabled = !model.isConnecting - joinButton.isEnabled = !model.isConnecting - activityIndicator.isHidden = !model.isConnecting - } - - present(isPresented: $model.incorrectPasswordAlertIsPresented) { [unowned self] in - let controller = UIAlertController( - title: "Incorrect password for “\(model.network.name)”", - message: nil, - preferredStyle: .alert - ) - controller.addAction(UIAlertAction(title: "OK", style: .default)) - return controller - } - } -} - -#Preview { - UIViewControllerRepresenting { - UINavigationController( - rootViewController: ConnectToNetworkViewController( - model: ConnectToNetworkModel( - network: Network(name: "Blob's WiFi") - ) - ) - ) - } -} -#endif diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift deleted file mode 100644 index 124b64124c..0000000000 --- a/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift +++ /dev/null @@ -1,101 +0,0 @@ -#if canImport(UIKit) && !os(watchOS) -import SwiftUI -import UIKitNavigation -import XCTestDynamicOverlay - -@MainActor -@Observable -class NetworkDetailModel { - var forgetAlertIsPresented = false - var onConfirmForget: () -> Void = { - XCTFail("NetworkDetailModel.onConfirmForget unimplemented.") - } - let network: Network - let selectedNetworkID: Network.ID? - - init( - network: Network, - selectedNetworkID: Network.ID? - ) { - self.network = network - self.selectedNetworkID = selectedNetworkID - } - - func forgetNetworkButtonTapped() { - forgetAlertIsPresented = true - } - - func confirmForgetNetworkButtonTapped() { - onConfirmForget() - } -} - -final class NetworkDetailViewController: UIViewController { - @UIBindable var model: NetworkDetailModel - - init(model: NetworkDetailModel) { - self.model = model - super.init(nibName: nil, bundle: nil) - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func viewDidLoad() { - super.viewDidLoad() - view.backgroundColor = .systemBackground - navigationItem.title = model.network.name - - let forgetButton = UIButton( - type: .system, - primaryAction: UIAction { [weak self] _ in - self?.model.forgetNetworkButtonTapped() - }) - forgetButton.setTitle("Forget network", for: .normal) - forgetButton.setTitleColor(.red, for: .normal) - forgetButton.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(forgetButton) - NSLayoutConstraint.activate([ - forgetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), - forgetButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), - ]) - - observe { [weak self] in - guard let self else { return } - - forgetButton.isHidden = model.network.id != model.selectedNetworkID - } - - present(isPresented: $model.forgetAlertIsPresented) { [unowned self] in - let controller = UIAlertController( - title: "Forget Wi-Fi Network “\(model.network.name)”?", - message: """ - Your iPhone and other devices using iCloud Keychain will no longer join this Wi-Fi \ - network. - """, - preferredStyle: .alert - ) - controller.addAction(UIAlertAction(title: "Cancel", style: .cancel)) - controller.addAction( - UIAlertAction(title: "Forget", style: .destructive) { [weak self] _ in - self?.model.confirmForgetNetworkButtonTapped() - }) - return controller - } - } -} - -#Preview { - UIViewControllerRepresenting { - UINavigationController( - rootViewController: NetworkDetailViewController( - model: NetworkDetailModel( - network: Network(name: "Blob's WiFi"), - selectedNetworkID: UUID() - ) - ) - ) - } -} -#endif diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift deleted file mode 100644 index a025d7855e..0000000000 --- a/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift +++ /dev/null @@ -1,313 +0,0 @@ -#if canImport(UIKit) && !os(watchOS) -import SwiftUI -import UIKitNavigation - -@Observable -@MainActor -class WiFiSettingsModel { - var destination: Destination? { - didSet { bind() } - } - var foundNetworks: [Network] - var isOn: Bool - var selectedNetworkID: Network.ID? - - @CasePathable - enum Destination { - case connect(ConnectToNetworkModel) - case detail(NetworkDetailModel) - } - - init( - foundNetworks: [Network] = [], - isOn: Bool = true, - selectedNetworkID: Network.ID? = nil - ) { - self.foundNetworks = foundNetworks - self.isOn = isOn - self.selectedNetworkID = selectedNetworkID - bind() - } - - private func bind() { - switch destination { - case .connect(let model): - model.onConnect = { [weak self] network in - guard let self else { return } - destination = nil - selectedNetworkID = network.id - } - - case .detail(let model): - model.onConfirmForget = { [weak self] in - guard let self else { return } - self.destination = nil - self.selectedNetworkID = nil - } - - case .none: - break - } - } - - func infoButtonTapped(network: Network) { - destination = .detail( - NetworkDetailModel( - network: network, - selectedNetworkID: selectedNetworkID - ) - ) - } - - func networkTapped(_ network: Network) { - if network.id == selectedNetworkID { - infoButtonTapped(network: network) - } else if network.isSecured { - destination = .connect(ConnectToNetworkModel(network: network)) - } else { - selectedNetworkID = network.id - } - } -} - -class WiFiSettingsViewController: UICollectionViewController, UIKitCaseStudy { - let caseStudyTitle = "Wi-Fi Settings" - let readMe = """ - This demo shows how to built a moderately complex feature using the tools of the library. \ - There are multiple features that communicate with each other, there are multiple navigation \ - patterns, and the root feature has a complex collection view that updates dynamically. - """ - let isPresentedInSheet = true - - @UIBindable var model: WiFiSettingsModel - var dataSource: UICollectionViewDiffableDataSource! - - init(model: WiFiSettingsModel) { - self.model = model - super.init( - collectionViewLayout: UICollectionViewCompositionalLayout.list( - using: UICollectionLayoutListConfiguration(appearance: .insetGrouped) - ) - ) - } - - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } - - override func viewDidLoad() { - super.viewDidLoad() - navigationItem.title = "Wi-Fi" - - let cellRegistration = UICollectionView.CellRegistration { - [weak self] cell, indexPath, item in - - guard let self else { return } - configure(cell: cell, indexPath: indexPath, item: item) - } - - self.dataSource = UICollectionViewDiffableDataSource( - collectionView: self.collectionView - ) { collectionView, indexPath, item in - collectionView.dequeueConfiguredReusableCell( - using: cellRegistration, - for: indexPath, - item: item - ) - } - - observe { [weak self] in - guard let self else { return } - dataSource.apply( - NSDiffableDataSourceSnapshot(model: model), - animatingDifferences: true - ) - } - - present(item: $model.destination.connect) { model in - UINavigationController( - rootViewController: ConnectToNetworkViewController(model: model) - ) - } - - navigationDestination(item: $model.destination.detail) { model in - NetworkDetailViewController(model: model) - } - } - - private func configure( - cell: UICollectionViewListCell, - indexPath: IndexPath, - item: Item - ) { - var configuration = cell.defaultContentConfiguration() - defer { cell.contentConfiguration = configuration } - cell.accessories = [] - - switch item { - case .isOn: - configuration.text = "Wi-Fi" - cell.accessories = [ - .customView( - configuration: UICellAccessory.CustomViewConfiguration( - customView: UISwitch(isOn: $model.isOn), - placement: .trailing(displayed: .always) - ) - ) - ] - - case let .selectedNetwork(networkID): - guard let network = model.foundNetworks.first(where: { $0.id == networkID }) - else { return } - configureNetwork(cell: cell, network: network, indexPath: indexPath, item: item) - - case let .foundNetwork(network): - configureNetwork(cell: cell, network: network, indexPath: indexPath, item: item) - } - - func configureNetwork( - cell: UICollectionViewListCell, - network: Network, - indexPath: IndexPath, - item: Item - ) { - configuration.text = network.name - cell.accessories.append( - .detail(displayed: .always) { [weak self] in - guard let self else { return } - model.infoButtonTapped(network: network) - } - ) - if network.isSecured { - let image = UIImage(systemName: "lock.fill")! - let imageView = UIImageView(image: image) - imageView.tintColor = .darkText - cell.accessories.append( - .customView( - configuration: UICellAccessory.CustomViewConfiguration( - customView: imageView, - placement: .trailing(displayed: .always) - ) - ) - ) - } - let image = UIImage(systemName: "wifi", variableValue: network.connectivity)! - let imageView = UIImageView(image: image) - imageView.tintColor = .darkText - cell.accessories.append( - .customView( - configuration: UICellAccessory.CustomViewConfiguration( - customView: imageView, - placement: .trailing(displayed: .always) - ) - ) - ) - if network.id == model.selectedNetworkID { - cell.accessories.append( - .customView( - configuration: UICellAccessory.CustomViewConfiguration( - customView: UIImageView(image: UIImage(systemName: "checkmark")!), - placement: .leading(displayed: .always), - reservedLayoutWidth: .custom(1) - ) - ) - ) - } - } - } - - override func collectionView( - _ collectionView: UICollectionView, - shouldSelectItemAt indexPath: IndexPath - ) -> Bool { - indexPath.section != 0 || indexPath.row != 0 - } - - override func collectionView( - _ collectionView: UICollectionView, - didSelectItemAt indexPath: IndexPath - ) { - guard let network = dataSource.itemIdentifier(for: indexPath)?.foundNetwork - else { return } - model.networkTapped(network) - } - - enum Section: Hashable, Sendable { - case top - case foundNetworks - } - - @CasePathable - @dynamicMemberLookup - enum Item: Hashable, Sendable { - case isOn - case selectedNetwork(Network.ID) - case foundNetwork(Network) - } -} - -extension NSDiffableDataSourceSnapshot< - WiFiSettingsViewController.Section, - WiFiSettingsViewController.Item -> { - @MainActor - init(model: WiFiSettingsModel) { - self.init() - - appendSections([.top]) - appendItems([.isOn], toSection: .top) - - guard model.isOn - else { return } - - if let selectedNetworkID = model.selectedNetworkID { - appendItems([.selectedNetwork(selectedNetworkID)], toSection: .top) - } - - appendSections([.foundNetworks]) - appendItems( - model.foundNetworks - .sorted { lhs, rhs in - (lhs.isSecured ? 1 : 0, lhs.connectivity) - > (rhs.isSecured ? 1 : 0, rhs.connectivity) - } - .compactMap { network in - network.id == model.selectedNetworkID - ? nil - : .foundNetwork(network) - }, - toSection: .foundNetworks - ) - } -} - -#Preview { - let model = WiFiSettingsModel(foundNetworks: .mocks) - return UIViewControllerRepresenting { - UINavigationController( - rootViewController: WiFiSettingsViewController(model: model) - ) - } - .task { - while true { - try? await Task.sleep(for: .seconds(1)) - guard Bool.random() else { continue } - if Bool.random() { - guard let randomIndex = (0.. { + @UIBindable var model: ConnectToNetworkModel + + init(model: ConnectToNetworkModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + view.frame = .init(origin: .zero, size: .init(width: 450, height: 234)) + let wifiIconImage = NSImageView(systemSymbolName: "wifi") + wifiIconImage.contentTintColor = .systemBlue + wifiIconImage.symbolConfiguration = .init(pointSize: 60, weight: .regular) + + let titleLabel = NSTextField(labelWithString: "Enter the password for “\(model.network.name)”") + titleLabel.font = .boldSystemFont(ofSize: 13) + let detailLabel = NSTextField(wrappingLabelWithString: "You can also access this Wi-Fi network by sharing the password from a nearby iPhone, iPad, or Mac which has connected to this network and has you in their contacts.") + detailLabel.font = .systemFont(ofSize: 12) + let textStackView = NSStackView(views: [ + titleLabel, + detailLabel, + ]) + textStackView.orientation = .vertical + textStackView.alignment = .leading + + let topStackView = NSStackView(views: [ + Spacer(size: .init(width: 15, height: 0)), + wifiIconImage, + textStackView, + HorizontalMaxSpacer(), + ]) + topStackView.orientation = .horizontal + + let passwordLabel = NSTextField(labelWithString: "Password:") + + let passwordTextField = NSSecureTextField(text: $model.password) + passwordTextField.bezelStyle = .roundedBezel + passwordTextField.becomeFirstResponder() + passwordTextField.placeholderString = "The password is 'blob'" + + let centerStackView = NSStackView(views: [ + HorizontalMaxSpacer(), + passwordLabel, + passwordTextField, + ]) + centerStackView.orientation = .horizontal + NSLayoutConstraint.activate([ + passwordTextField.widthAnchor.constraint(equalToConstant: 253), + ]) + + let cancelButton = NSButton { [weak self] _ in + guard let self else { return } + model.cancelButtonTapped() + } + cancelButton.title = "Cancel" + + let joinButton = NSButton { [weak self] _ in + guard let self else { return } + Task { + await self.model.joinButtonTapped() + } + } + joinButton.title = "Join" + + let progress = NSProgressIndicator() + progress.isIndeterminate = true + progress.style = .spinning + progress.controlSize = .small + progress.startAnimation(nil) + + let progressStackView = NSStackView(views: [ + HorizontalMaxSpacer(), + progress, + ]) + + let bottomStackView = NSStackView(views: [ + HorizontalMaxSpacer(), + cancelButton, + joinButton, + ]) + bottomStackView.orientation = .horizontal + + NSLayoutConstraint.activate([ + joinButton.widthAnchor.constraint(equalToConstant: 70), + cancelButton.widthAnchor.constraint(equalToConstant: 70), + ]) + + let stack = NSStackView(views: [ + topStackView, + centerStackView, + progressStackView, + bottomStackView, + ]) + + stack.orientation = .vertical + stack.translatesAutoresizingMaskIntoConstraints = false + stack.edgeInsets = .init(top: 20, left: 0, bottom: 20, right: 20) + stack.distribution = .equalSpacing + stack.detachesHiddenViews = false + view.addSubview(stack) + progressStackView.isHidden = true + NSLayoutConstraint.activate([ + stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + stack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), + stack.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor), + stack.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor), + ]) + + observe { [weak self, weak passwordTextField] in + guard + let self, + let passwordTextField + else { return } + + passwordTextField.isEnabled = !model.isConnecting + joinButton.isEnabled = !model.isConnecting + progressStackView.isHidden = !model.isConnecting + } + + modal(isModaled: $model.incorrectPasswordAlertIsPresented) { [unowned self] in + let alert = NSAlert() + alert.messageText = "Incorrect password for “\(model.network.name)”" + alert.addButton(withTitle: "OK") + return alert + } + } +} + +class HorizontalMaxSpacer: NSView { + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + setContentHuggingPriority(.fittingSizeCompression, for: .horizontal) + setContentCompressionResistancePriority(.fittingSizeCompression, for: .horizontal) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +class Spacer: NSView { + init(size: NSSize) { + super.init(frame: .zero) + NSLayoutConstraint.activate([ + widthAnchor.constraint(equalToConstant: size.width), + heightAnchor.constraint(equalToConstant: size.height), + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +#Preview(traits: .fixedLayout(width: 450, height: 262)) { + let vc = ConnectToNetworkViewController( + model: ConnectToNetworkModel( + network: Network(name: "Blob's WiFi") + ) + ) + vc.preferredContentSize = .init(width: 450, height: 234) + return vc +} +#endif diff --git a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift new file mode 100644 index 0000000000..305710387b --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift @@ -0,0 +1,36 @@ +import Foundation +import XCTestDynamicOverlay + +@Observable +@MainActor +class ConnectToNetworkModel: Identifiable { + var incorrectPasswordAlertIsPresented = false + var isConnecting = false + var onCancel: () -> Void = { + XCTFail("ConnectToNetworkModel.onCancel unimplemented.") + } + var onConnect: (Network) -> Void = { _ in + XCTFail("ConnectToNetworkModel.onConnect unimplemented.") + } + + let network: Network + var password = "" + init(network: Network) { + self.network = network + } + + func cancelButtonTapped() { + onCancel() + } + + func joinButtonTapped() async { + isConnecting = true + defer { isConnecting = false } + try? await Task.sleep(for: .seconds(1)) + if password == "blob" { + onConnect(network) + } else { + incorrectPasswordAlertIsPresented = true + } + } +} diff --git a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/UIKit+ConnectToNetworkViewController.swift b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/UIKit+ConnectToNetworkViewController.swift new file mode 100644 index 0000000000..389a6b345f --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/UIKit+ConnectToNetworkViewController.swift @@ -0,0 +1,90 @@ +#if canImport(UIKit) && !os(watchOS) + +import SwiftUI +import UIKitNavigation + +final class ConnectToNetworkViewController: UIViewController { + @UIBindable var model: ConnectToNetworkModel + + init(model: ConnectToNetworkModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + navigationItem.title = "Enter the password for “\(model.network.name)”" + + let passwordTextField = UITextField(text: $model.password) + passwordTextField.borderStyle = .line + passwordTextField.isSecureTextEntry = true + passwordTextField.becomeFirstResponder() + passwordTextField.placeholder = "The password is 'blob'" + let joinButton = UIButton( + type: .system, + primaryAction: UIAction { [weak self] _ in + guard let self else { return } + Task { + await self.model.joinButtonTapped() + } + } + ) + joinButton.setTitle("Join network", for: .normal) + let activityIndicator = UIActivityIndicatorView(style: .medium) + activityIndicator.startAnimating() + + let stack = UIStackView(arrangedSubviews: [ + passwordTextField, + joinButton, + activityIndicator, + ]) + stack.axis = .vertical + stack.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerXAnchor.constraint(equalTo: view.centerXAnchor), + stack.centerYAnchor.constraint(equalTo: view.centerYAnchor), + stack.widthAnchor.constraint(equalToConstant: 200), + ]) + + observe { [weak self, weak passwordTextField] in + guard + let self, + let passwordTextField + else { return } + + passwordTextField.isEnabled = !model.isConnecting + joinButton.isEnabled = !model.isConnecting + activityIndicator.isHidden = !model.isConnecting + } + + present(isPresented: $model.incorrectPasswordAlertIsPresented) { [unowned self] in + let controller = UIAlertController( + title: "Incorrect password for “\(model.network.name)”", + message: nil, + preferredStyle: .alert + ) + controller.addAction(UIAlertAction(title: "OK", style: .default)) + return controller + } + } +} + +#Preview { + UIViewControllerRepresenting { + UINavigationController( + rootViewController: ConnectToNetworkViewController( + model: ConnectToNetworkModel( + network: Network(name: "Blob's WiFi") + ) + ) + ) + } +} +#endif diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/Network.swift b/Examples/CaseStudies/WiFiFeature/Network.swift similarity index 100% rename from Examples/CaseStudies/UIKit/WiFiFeature/Network.swift rename to Examples/CaseStudies/WiFiFeature/Network.swift diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift new file mode 100644 index 0000000000..0c6219045a --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift @@ -0,0 +1,65 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import AppKitNavigation + +final class NetworkDetailViewController: XiblessViewController { + @UIBindable var model: NetworkDetailModel + + init(model: NetworkDetailModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + override func viewDidLoad() { + super.viewDidLoad() + +// navigationItem.title = model.network.name + + let forgetButton = NSButton { [weak self] _ in + guard let self else { return } + model.forgetNetworkButtonTapped() + } + + forgetButton.title = "Forget network" +// forgetButton.hasDestructiveAction = true + forgetButton.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(forgetButton) + NSLayoutConstraint.activate([ + forgetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), + forgetButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), + ]) + + observe { [weak self] in + guard let self else { return } + +// forgetButton.isHidden = model.network.id != model.selectedNetworkID + } + + modal(isModaled: $model.forgetAlertIsPresented) { [unowned self] in + let alert = NSAlert() + alert.messageText = "Forget Wi-Fi Network “\(model.network.name)”?" + alert.informativeText = """ + Your Mac and other devices using iCloud Keychain will no longer join this Wi-Fi \ + network. + """ + + alert.addButton(ButtonState(role: .cancel) { TextState("Cancel") }) { _ in } + alert.addButton(ButtonState(role: .destructive) { TextState("Forget") }) { [weak self] _ in + guard let self else { return } + model.confirmForgetNetworkButtonTapped() + } + return alert + } + } +} + +#Preview { + NetworkDetailViewController( + model: NetworkDetailModel( + network: Network(name: "Blob's WiFi"), + selectedNetworkID: UUID() + ) + ) +} +#endif diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift new file mode 100644 index 0000000000..db0101b467 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift @@ -0,0 +1,32 @@ +import Foundation +import XCTestDynamicOverlay + +@MainActor +@Observable +class NetworkDetailModel: Identifiable { + var forgetAlertIsPresented = false + var onConfirmForget: () -> Void = { + XCTFail("NetworkDetailModel.onConfirmForget unimplemented.") + } + + let network: Network + let selectedNetworkID: Network.ID? + + let id = UUID() + + init( + network: Network, + selectedNetworkID: Network.ID? + ) { + self.network = network + self.selectedNetworkID = selectedNetworkID + } + + func forgetNetworkButtonTapped() { + forgetAlertIsPresented = true + } + + func confirmForgetNetworkButtonTapped() { + onConfirmForget() + } +} diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/UIKit+NetworkDetailViewController.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/UIKit+NetworkDetailViewController.swift new file mode 100644 index 0000000000..d32e1afc05 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/UIKit+NetworkDetailViewController.swift @@ -0,0 +1,76 @@ +#if canImport(UIKit) && !os(watchOS) + +import SwiftUI +import UIKitNavigation + +final class NetworkDetailViewController: UIViewController { + @UIBindable var model: NetworkDetailModel + + init(model: NetworkDetailModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + view.backgroundColor = .systemBackground + navigationItem.title = model.network.name + + let forgetButton = UIButton( + type: .system, + primaryAction: UIAction { [weak self] _ in + self?.model.forgetNetworkButtonTapped() + } + ) + forgetButton.setTitle("Forget network", for: .normal) + forgetButton.setTitleColor(.red, for: .normal) + forgetButton.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(forgetButton) + NSLayoutConstraint.activate([ + forgetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), + forgetButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), + ]) + + observe { [weak self] in + guard let self else { return } + + forgetButton.isHidden = model.network.id != model.selectedNetworkID + } + + present(isPresented: $model.forgetAlertIsPresented) { [unowned self] in + let controller = UIAlertController( + title: "Forget Wi-Fi Network “\(model.network.name)”?", + message: """ + Your iPhone and other devices using iCloud Keychain will no longer join this Wi-Fi \ + network. + """, + preferredStyle: .alert + ) + controller.addAction(UIAlertAction(title: "Cancel", style: .cancel)) + controller.addAction( + UIAlertAction(title: "Forget", style: .destructive) { [weak self] _ in + self?.model.confirmForgetNetworkButtonTapped() + }) + return controller + } + } +} + +#Preview { + UIViewControllerRepresenting { + UINavigationController( + rootViewController: NetworkDetailViewController( + model: NetworkDetailModel( + network: Network(name: "Blob's WiFi"), + selectedNetworkID: UUID() + ) + ) + ) + } +} +#endif diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift new file mode 100644 index 0000000000..698db6d09b --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -0,0 +1,352 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import AppKitNavigation +import SwiftUI + +class WiFiSettingsViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Wi-Fi Settings" + let readMe = """ + This demo shows how to built a moderately complex feature using the tools of the library. \ + There are multiple features that communicate with each other, there are multiple navigation \ + patterns, and the root feature has a complex collection view that updates dynamically. + """ + let isPresentedInSheet = true + + @UIBindable var model: WiFiSettingsModel + + var dataSource: NSCollectionViewDiffableDataSource! + + let collectionView = NSCollectionView() + + init(model: WiFiSettingsModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + override func viewDidLoad() { + super.viewDidLoad() + collectionView.autoresizingMask = [.width, .height] + contentView.documentView = collectionView + let collectionViewLayout = NSCollectionViewCompositionalLayout { sectionIndex, layoutEnvironment -> NSCollectionLayoutSection? in + // Item + let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(sectionIndex == 0 ? 60 : 44)) + let item = NSCollectionLayoutItem(layoutSize: itemSize) + item.contentInsets = .init(top: 0, leading: sectionIndex == 0 ? 10 : 30, bottom: 0, trailing: 10) + // Group + let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(sectionIndex == 0 ? 60 : 44)) + let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) + + // Section + let section = NSCollectionLayoutSection(group: group) + section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10) + let decorationItem = NSCollectionLayoutDecorationItem.background(elementKind: NSCollectionView.DecorationElementKind.background) + decorationItem.contentInsets = .init(top: 0, leading: 10, bottom: 0, trailing: 10) + section.decorationItems = [decorationItem] + return section + } + collectionViewLayout.register(WiFiSettingsSectionBackgroundView.self, forDecorationViewOfKind: .background) + let configuration = NSCollectionViewCompositionalLayoutConfiguration() + configuration.interSectionSpacing = 20 + collectionViewLayout.configuration = configuration + collectionView.collectionViewLayout = collectionViewLayout + collectionView.register(WiFiSettingsSwitchViewItem.self, forItemWithIdentifier: .init(WiFiSettingsSwitchViewItem.self)) + collectionView.register(WiFiSettingsConnectedNetworkViewItem.self, forItemWithIdentifier: .init(WiFiSettingsConnectedNetworkViewItem.self)) + collectionView.register(WiFiSettingsFoundedNetworkViewItem.self, forItemWithIdentifier: .init(WiFiSettingsFoundedNetworkViewItem.self)) + + dataSource = NSCollectionViewDiffableDataSource( + collectionView: collectionView + ) { [unowned self] collectionView, indexPath, item in + + switch item { + case .isOn: + let switchViewItem = collectionView.makeItem(withIdentifier: .init(WiFiSettingsSwitchViewItem.self), for: indexPath) as! WiFiSettingsSwitchViewItem + switchViewItem.switchView.bind(isOn: $model.isOn) + return switchViewItem + case let .selectedNetwork(networkID): + guard let network = model.foundNetworks.first(where: { $0.id == networkID }) + else { return nil } + let connectedViewItem = collectionView.makeItem(withIdentifier: .init(WiFiSettingsConnectedNetworkViewItem.self), for: indexPath) as! WiFiSettingsConnectedNetworkViewItem + connectedViewItem.nameLabel.stringValue = network.name + connectedViewItem.securedIconImageView.isHidden = !network.isSecured + connectedViewItem.wifiIconImageView.image = NSImage(systemSymbolName: "wifi", variableValue: network.connectivity, accessibilityDescription: nil) + connectedViewItem.detailButton.addAction { _ in + self.model.infoButtonTapped(network: network) + } + return connectedViewItem + case let .foundNetwork(network): + let foundedViewItem = collectionView.makeItem(withIdentifier: .init(WiFiSettingsFoundedNetworkViewItem.self), for: indexPath) as! WiFiSettingsFoundedNetworkViewItem + foundedViewItem.titleLabel.stringValue = network.name + foundedViewItem.securedIconImageView.isHidden = !network.isSecured + foundedViewItem.wifiIconImageView.image = NSImage(systemSymbolName: "wifi", variableValue: network.connectivity, accessibilityDescription: nil) + foundedViewItem.connectButton.addAction { _ in + self.model.networkTapped(network) + } + return foundedViewItem + } + } + + observe { [weak self] in + guard let self else { return } + dataSource.apply( + NSDiffableDataSourceSnapshot(model: model), + animatingDifferences: true + ) + } + + modalSession(item: $model.destination.connect) { model in + let panel = NSPanel(contentViewController: ConnectToNetworkViewController(model: model)) + panel.styleMask = [.titled] + panel.animationBehavior = .none + return panel + } + + present(item: $model.destination.detail, style: .sheet) { model in + let vc = NetworkDetailViewController(model: model) + vc.preferredContentSize = .init(width: 300, height: 200) + return vc + } + } +} + +#Preview { + let model = WiFiSettingsModel(foundNetworks: .mocks) + return NSViewControllerRepresenting { + WiFiSettingsViewController(model: model) + } + .task { + while true { + try? await Task.sleep(for: .seconds(1)) + guard Bool.random() else { continue } + if Bool.random() { + guard let randomIndex = (0 ..< model.foundNetworks.count).randomElement() + else { continue } + if model.foundNetworks[randomIndex].id != model.selectedNetworkID { + model.foundNetworks.remove(at: randomIndex) + } + } else { + model.foundNetworks.append( + Network( + name: goofyWiFiNames.randomElement()!, + isSecured: !(1 ... 1000).randomElement()!.isMultiple(of: 5), + connectivity: Double((1 ... 100).randomElement()!) / 100 + ) + ) + } + } + } +} + +extension NSCollectionView.DecorationElementKind { + static let background = "BackgroundKind" +} + +class WiFiSettingsSectionBackgroundView: NSBox, NSCollectionViewElement { + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + commonInit() + } + + required init?(coder: NSCoder) { + super.init(coder: coder) + commonInit() + } + + func commonInit() { + titlePosition = .noTitle + } +} + +class XiblessCollectionViewItem: NSCollectionViewItem { + override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func loadView() { + view = View() + } +} + +class WiFiSettingsSwitchViewItem: XiblessCollectionViewItem { + let iconImageView = NSImageView() + + let titleLabel = NSTextField(labelWithString: "Wi-Fi") + + let switchView = NSSwitch() + override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + let stackView = NSStackView() + stackView.addView(iconImageView, in: .leading) + stackView.addView(titleLabel, in: .leading) + stackView.addView(switchView, in: .trailing) + stackView.orientation = .horizontal + stackView.alignment = .centerY + stackView.spacing = 15 + view.addSubview(stackView) + stackView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + stackView.leftAnchor.constraint(equalTo: view.leftAnchor), + stackView.rightAnchor.constraint(equalTo: view.rightAnchor), + stackView.topAnchor.constraint(equalTo: view.topAnchor), + stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + let image = NSImage(systemSymbolName: "wifi", accessibilityDescription: "Wi-Fi")! + iconImageView.image = image.withSymbolConfiguration(.init(pointSize: 15, weight: .regular)) + iconImageView.wantsLayer = true + iconImageView.layer?.cornerRadius = 5 + iconImageView.layer?.backgroundColor = NSColor.systemBlue.cgColor + iconImageView.contentTintColor = .white + NSLayoutConstraint.activate([ + iconImageView.widthAnchor.constraint(equalToConstant: 26), + iconImageView.heightAnchor.constraint(equalToConstant: 20), + ]) + switchView.controlSize = .large + } +} + +class WiFiSettingsConnectedNetworkViewItem: XiblessCollectionViewItem { + let nameLabel = NSTextField(labelWithString: "WiFi Name") + let statusButton = NSButton() + let securedIconImageView = NSImageView(systemSymbolName: "lock.fill") + let wifiIconImageView = NSImageView(systemSymbolName: "wifi") + let detailButton = NSButton(title: "Detail...", target: nil, action: nil) + override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + let stackView = NSStackView() + stackView.orientation = .horizontal + stackView.alignment = .centerY + stackView.spacing = 15 + view.addSubview(stackView) + stackView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + stackView.leftAnchor.constraint(equalTo: view.leftAnchor), + stackView.rightAnchor.constraint(equalTo: view.rightAnchor), + stackView.topAnchor.constraint(equalTo: view.topAnchor), + stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + + let textStackView = NSStackView() + textStackView.orientation = .vertical + textStackView.alignment = .leading + textStackView.spacing = 3 + textStackView.addArrangedSubview(nameLabel) + textStackView.addArrangedSubview(statusButton) + stackView.addView(textStackView, in: .leading) + stackView.addView(securedIconImageView, in: .trailing) + stackView.addView(wifiIconImageView, in: .trailing) + stackView.addView(detailButton, in: .trailing) + + statusButton.isBordered = false + statusButton.image = NSImage(named: NSImage.statusAvailableName) + (statusButton.cell as! NSButtonCell).highlightsBy = [] + statusButton.attributedTitle = NSAttributedString(string: "Connected", attributes: [ + .foregroundColor: NSColor.secondaryLabelColor, + ]) + statusButton.imagePosition = .imageLeft + securedIconImageView.contentTintColor = .labelColor + wifiIconImageView.contentTintColor = .labelColor + } + + override func prepareForReuse() { + super.prepareForReuse() + + detailButton.removeAllActions() + } +} + +class WiFiSettingsFoundedNetworkViewItem: XiblessCollectionViewItem { + let selectedIconImageView = NSImageView(systemSymbolName: "checkmark") + let titleLabel = NSTextField(labelWithString: "WiFi Name") + let securedIconImageView = NSImageView(systemSymbolName: "lock.fill") + let wifiIconImageView = NSImageView(systemSymbolName: "wifi") + let connectButton = NSButton(title: "Connect", target: nil, action: nil) + + override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + let stackView = NSStackView() + stackView.orientation = .horizontal + stackView.alignment = .centerY + stackView.spacing = 10 + view.addSubview(stackView) + stackView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + stackView.leftAnchor.constraint(equalTo: view.leftAnchor), + stackView.rightAnchor.constraint(equalTo: view.rightAnchor), + stackView.topAnchor.constraint(equalTo: view.topAnchor), + stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) +// stackView.addView(selectedIconImageView, in: .leading) + stackView.addView(titleLabel, in: .leading) + stackView.addView(connectButton, in: .trailing) + stackView.addView(securedIconImageView, in: .trailing) + stackView.addView(wifiIconImageView, in: .trailing) + selectedIconImageView.symbolConfiguration = .init(pointSize: 12, weight: .heavy) + selectedIconImageView.contentTintColor = .labelColor + securedIconImageView.contentTintColor = .labelColor + wifiIconImageView.contentTintColor = .labelColor + connectButton.isHidden = true + } + + override func viewDidLayout() { + super.viewDidLayout() + view.trackingAreas.forEach(view.removeTrackingArea(_:)) + view.addTrackingArea(.init(rect: view.bounds, options: [.mouseEnteredAndExited, .mouseMoved, .activeAlways, .assumeInside], owner: self)) + } + + override func mouseEntered(with event: NSEvent) { + connectButton.isHidden = false + } + + override func mouseMoved(with event: NSEvent) { + connectButton.isHidden = false + } + + override func mouseExited(with event: NSEvent) { + connectButton.isHidden = true + } + + override func prepareForReuse() { + super.prepareForReuse() + + connectButton.removeAllActions() + } +} + +@available(macOS 14.0, *) +#Preview { + let item = WiFiSettingsConnectedNetworkViewItem() + item.preferredContentSize = .init(width: 500, height: 200) + return item +} + +extension NSUserInterfaceItemIdentifier { + init(_ anyClass: AnyClass) { + self.init(rawValue: "\(anyClass)") + } +} + +extension NSImageView { + convenience init(systemSymbolName: String) { + self.init() + self.image = NSImage(systemSymbolName: systemSymbolName, accessibilityDescription: nil) + } + + convenience init(systemSymbolName: String, variableValue: Double) { + self.init() + self.image = NSImage(systemSymbolName: systemSymbolName, variableValue: variableValue, accessibilityDescription: nil) + } +} + +extension NSButton { + convenience init(systemSymbolName: String) { + self.init() + self.image = NSImage(systemSymbolName: systemSymbolName, accessibilityDescription: nil) + } +} + +#endif diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/UIKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/UIKit+WiFiSettingsViewController.swift new file mode 100644 index 0000000000..ae1081985b --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/UIKit+WiFiSettingsViewController.swift @@ -0,0 +1,199 @@ +#if canImport(UIKit) && !os(watchOS) + +import SwiftUI +import UIKitNavigation + +class WiFiSettingsViewController: UICollectionViewController, UIKitCaseStudy { + let caseStudyTitle = "Wi-Fi Settings" + let readMe = """ + This demo shows how to built a moderately complex feature using the tools of the library. \ + There are multiple features that communicate with each other, there are multiple navigation \ + patterns, and the root feature has a complex collection view that updates dynamically. + """ + let isPresentedInSheet = true + + @UIBindable var model: WiFiSettingsModel + var dataSource: UICollectionViewDiffableDataSource! + + init(model: WiFiSettingsModel) { + self.model = model + super.init( + collectionViewLayout: UICollectionViewCompositionalLayout.list( + using: UICollectionLayoutListConfiguration(appearance: .insetGrouped) + ) + ) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + navigationItem.title = "Wi-Fi" + + let cellRegistration = UICollectionView.CellRegistration { + [weak self] cell, indexPath, item in + + guard let self else { return } + configure(cell: cell, indexPath: indexPath, item: item) + } + + dataSource = UICollectionViewDiffableDataSource( + collectionView: collectionView + ) { collectionView, indexPath, item in + collectionView.dequeueConfiguredReusableCell( + using: cellRegistration, + for: indexPath, + item: item + ) + } + + observe { [weak self] in + guard let self else { return } + dataSource.apply( + NSDiffableDataSourceSnapshot(model: model), + animatingDifferences: true + ) + } + + present(item: $model.destination.connect) { model in + UINavigationController( + rootViewController: ConnectToNetworkViewController(model: model) + ) + } + + navigationDestination(item: $model.destination.detail) { model in + NetworkDetailViewController(model: model) + } + } + + private func configure( + cell: UICollectionViewListCell, + indexPath: IndexPath, + item: Item + ) { + var configuration = cell.defaultContentConfiguration() + defer { cell.contentConfiguration = configuration } + cell.accessories = [] + + switch item { + case .isOn: + configuration.text = "Wi-Fi" + cell.accessories = [ + .customView( + configuration: UICellAccessory.CustomViewConfiguration( + customView: UISwitch(isOn: $model.isOn), + placement: .trailing(displayed: .always) + ) + ), + ] + + case let .selectedNetwork(networkID): + guard let network = model.foundNetworks.first(where: { $0.id == networkID }) + else { return } + configureNetwork(cell: cell, network: network, indexPath: indexPath, item: item) + + case let .foundNetwork(network): + configureNetwork(cell: cell, network: network, indexPath: indexPath, item: item) + } + + func configureNetwork( + cell: UICollectionViewListCell, + network: Network, + indexPath: IndexPath, + item: Item + ) { + configuration.text = network.name + cell.accessories.append( + .detail(displayed: .always) { [weak self] in + guard let self else { return } + model.infoButtonTapped(network: network) + } + ) + if network.isSecured { + let image = UIImage(systemName: "lock.fill")! + let imageView = UIImageView(image: image) + imageView.tintColor = .darkText + cell.accessories.append( + .customView( + configuration: UICellAccessory.CustomViewConfiguration( + customView: imageView, + placement: .trailing(displayed: .always) + ) + ) + ) + } + let image = UIImage(systemName: "wifi", variableValue: network.connectivity)! + let imageView = UIImageView(image: image) + imageView.tintColor = .darkText + cell.accessories.append( + .customView( + configuration: UICellAccessory.CustomViewConfiguration( + customView: imageView, + placement: .trailing(displayed: .always) + ) + ) + ) + if network.id == model.selectedNetworkID { + cell.accessories.append( + .customView( + configuration: UICellAccessory.CustomViewConfiguration( + customView: UIImageView(image: UIImage(systemName: "checkmark")!), + placement: .leading(displayed: .always), + reservedLayoutWidth: .custom(1) + ) + ) + ) + } + } + } + + override func collectionView( + _ collectionView: UICollectionView, + shouldSelectItemAt indexPath: IndexPath + ) -> Bool { + indexPath.section != 0 || indexPath.row != 0 + } + + override func collectionView( + _ collectionView: UICollectionView, + didSelectItemAt indexPath: IndexPath + ) { + guard let network = dataSource.itemIdentifier(for: indexPath)?.foundNetwork + else { return } + model.networkTapped(network) + } +} + +#Preview { + let model = WiFiSettingsModel(foundNetworks: .mocks) + return UIViewControllerRepresenting { + UINavigationController( + rootViewController: WiFiSettingsViewController(model: model) + ) + } + .task { + while true { + try? await Task.sleep(for: .seconds(1)) + guard Bool.random() else { continue } + if Bool.random() { + guard let randomIndex = (0 ..< model.foundNetworks.count).randomElement() + else { continue } + if model.foundNetworks[randomIndex].id != model.selectedNetworkID { + model.foundNetworks.remove(at: randomIndex) + } + } else { + model.foundNetworks.append( + Network( + name: goofyWiFiNames.randomElement()!, + isSecured: !(1 ... 1000).randomElement()!.isMultiple(of: 5), + connectivity: Double((1 ... 100).randomElement()!) / 100 + ) + ) + } + } + } +} +#endif diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsModel.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsModel.swift new file mode 100644 index 0000000000..a212f71177 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsModel.swift @@ -0,0 +1,75 @@ +import Foundation +import CasePaths + +@Observable +@MainActor +class WiFiSettingsModel { + var destination: Destination? { + didSet { bind() } + } + + var foundNetworks: [Network] + var isOn: Bool + var selectedNetworkID: Network.ID? + + @CasePathable + enum Destination { + case connect(ConnectToNetworkModel) + case detail(NetworkDetailModel) + } + + init( + foundNetworks: [Network] = [], + isOn: Bool = true, + selectedNetworkID: Network.ID? = nil + ) { + self.foundNetworks = foundNetworks + self.isOn = isOn + self.selectedNetworkID = selectedNetworkID + bind() + } + + private func bind() { + switch destination { + case let .connect(model): + model.onConnect = { [weak self] network in + guard let self else { return } + destination = nil + selectedNetworkID = network.id + } + model.onCancel = { [weak self] in + guard let self else { return } + destination = nil + } + + case let .detail(model): + model.onConfirmForget = { [weak self] in + guard let self else { return } + self.destination = nil + self.selectedNetworkID = nil + } + + case .none: + break + } + } + + func infoButtonTapped(network: Network) { + destination = .detail( + NetworkDetailModel( + network: network, + selectedNetworkID: selectedNetworkID + ) + ) + } + + func networkTapped(_ network: Network) { + if network.id == selectedNetworkID { + infoButtonTapped(network: network) + } else if network.isSecured { + destination = .connect(ConnectToNetworkModel(network: network)) + } else { + selectedNetworkID = network.id + } + } +} diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsViewController+.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsViewController+.swift new file mode 100644 index 0000000000..a94213b0e9 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/WiFiSettingsViewController+.swift @@ -0,0 +1,60 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +#endif + +#if canImport(UIKit) +import UIKit +#endif + +import CasePaths + +extension NSDiffableDataSourceSnapshot< + WiFiSettingsViewController.Section, + WiFiSettingsViewController.Item +> { + @MainActor + init(model: WiFiSettingsModel) { + self.init() + + appendSections([.top]) + appendItems([.isOn], toSection: .top) + + guard model.isOn + else { return } + + if let selectedNetworkID = model.selectedNetworkID { + appendItems([.selectedNetwork(selectedNetworkID)], toSection: .top) + } + + appendSections([.foundNetworks]) + appendItems( + model.foundNetworks + .sorted { lhs, rhs in + (lhs.isSecured ? 1 : 0, lhs.connectivity) + > (rhs.isSecured ? 1 : 0, rhs.connectivity) + } + .compactMap { network in + network.id == model.selectedNetworkID + ? nil + : .foundNetwork(network) + }, + toSection: .foundNetworks + ) + } +} + +extension WiFiSettingsViewController { + enum Section: Hashable, Sendable { + case top + case foundNetworks + } + + @CasePathable + @dynamicMemberLookup + enum Item: Hashable, Sendable { + case isOn + case selectedNetwork(Network.ID) + case foundNetwork(Network) + } +} + diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index f3552b0cfa..ea0c563924 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -8,10 +8,10 @@ /* Begin PBXBuildFile section */ CA26036D2C20973600822CA5 /* DetentsHelper.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA26036C2C20973600822CA5 /* DetentsHelper.swift */; }; - CA3D0E322C20B27B00CCF7CD /* ConnectToNetworkFeature.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9B82C0525980034B757 /* ConnectToNetworkFeature.swift */; }; - CA3D0E332C20B27B00CCF7CD /* NetworkDetailFeature.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9BA2C0525980034B757 /* NetworkDetailFeature.swift */; }; + CA3D0E322C20B27B00CCF7CD /* UIKit+ConnectToNetworkViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9B82C0525980034B757 /* UIKit+ConnectToNetworkViewController.swift */; }; + CA3D0E332C20B27B00CCF7CD /* UIKit+NetworkDetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9BA2C0525980034B757 /* UIKit+NetworkDetailViewController.swift */; }; CA3D0E342C20B27B00CCF7CD /* Network.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9B92C0525980034B757 /* Network.swift */; }; - CA3D0E352C20B27B00CCF7CD /* WiFiSettingsFeature.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9BB2C0525980034B757 /* WiFiSettingsFeature.swift */; }; + CA3D0E352C20B27B00CCF7CD /* WiFiSettingsViewController+.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC5EB9BB2C0525980034B757 /* WiFiSettingsViewController+.swift */; }; CA4737CF272F09600012CAC3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = CA4737CE272F09600012CAC3 /* Assets.xcassets */; }; CA4737F4272F09780012CAC3 /* SwiftUINavigation in Frameworks */ = {isa = PBXBuildFile; productRef = CA4737F3272F09780012CAC3 /* SwiftUINavigation */; }; CA4737F9272F09D00012CAC3 /* ItemRow.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA4737F5272F09D00012CAC3 /* ItemRow.swift */; }; @@ -24,7 +24,7 @@ CA473837272F0D860012CAC3 /* FactClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA473831272F0D860012CAC3 /* FactClient.swift */; }; CA473838272F0D860012CAC3 /* OptionalNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA473832272F0D860012CAC3 /* OptionalNavigation.swift */; }; CA48F2FA2C49645100BE2C3C /* SwiftUINavigation in Frameworks */ = {isa = PBXBuildFile; productRef = CA48F2F92C49645100BE2C3C /* SwiftUINavigation */; }; - CA48F2FC2C49645100BE2C3C /* UIKitNavigation in Frameworks */ = {isa = PBXBuildFile; productRef = CA48F2FB2C49645100BE2C3C /* UIKitNavigation */; }; + CA48F2FC2C49645100BE2C3C /* UIKitNavigation in Frameworks */ = {isa = PBXBuildFile; platformFilter = ios; productRef = CA48F2FB2C49645100BE2C3C /* UIKitNavigation */; }; CA48F3022C49650100BE2C3C /* IdentifiedCollections in Frameworks */ = {isa = PBXBuildFile; productRef = CA48F3012C49650100BE2C3C /* IdentifiedCollections */; }; CA48F3052C49650F00BE2C3C /* Tagged in Frameworks */ = {isa = PBXBuildFile; productRef = CA48F3042C49650F00BE2C3C /* Tagged */; }; CA48F3082C49651700BE2C3C /* ConcurrencyExtras in Frameworks */ = {isa = PBXBuildFile; productRef = CA48F3072C49651700BE2C3C /* ConcurrencyExtras */; }; @@ -53,8 +53,15 @@ DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC6A8410291F227400B3F6C9 /* SynchronizedBindings.swift */; }; DC86E8712C208D8D003C0EC9 /* Text+Template.swift in Sources */ = {isa = PBXBuildFile; fileRef = DC86E8702C208D8A003C0EC9 /* Text+Template.swift */; }; E9836D922C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */; }; - E9836D942C6CA07300FC6EFD /* AppKitNavigation in Frameworks */ = {isa = PBXBuildFile; productRef = E9836D932C6CA07300FC6EFD /* AppKitNavigation */; }; + E9836D942C6CA07300FC6EFD /* AppKitNavigation in Frameworks */ = {isa = PBXBuildFile; platformFilters = (macos, ); productRef = E9836D932C6CA07300FC6EFD /* AppKitNavigation */; }; E9836D962C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9836D952C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift */; }; + E99B05952C70CE36003D3AFF /* WiFiSettingsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B05942C70CE36003D3AFF /* WiFiSettingsModel.swift */; }; + E99B05972C70CE59003D3AFF /* AppKit+WiFiSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B05962C70CE59003D3AFF /* AppKit+WiFiSettingsViewController.swift */; }; + E99B05992C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B05982C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift */; }; + E99B059C2C70CEFE003D3AFF /* ConnectToNetworkModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B059B2C70CEFE003D3AFF /* ConnectToNetworkModel.swift */; }; + E99B059E2C70CF18003D3AFF /* NetworkDetailModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B059D2C70CF18003D3AFF /* NetworkDetailModel.swift */; }; + E99B05A22C70D5E1003D3AFF /* AppKit+NetworkDetailViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B05A12C70D5E1003D3AFF /* AppKit+NetworkDetailViewController.swift */; }; + E99B05A42C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E99B05A32C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift */; }; E9CD5B762C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B752C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift */; }; E9CD5B782C6CDEA500CE7947 /* AppKit+FocusViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B772C6CDEA500CE7947 /* AppKit+FocusViewController.swift */; }; E9CD5B7B2C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */; }; @@ -107,10 +114,10 @@ CABE9FC0272F2C0000AFC150 /* EnumNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EnumNavigation.swift; sourceTree = ""; }; CADCA3622C1CE75500DE645F /* SwiftUICaseStudies.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwiftUICaseStudies.swift; sourceTree = ""; }; CADCA3652C1CE8BE00DE645F /* CaseStudy.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CaseStudy.swift; sourceTree = ""; }; - DC5EB9B82C0525980034B757 /* ConnectToNetworkFeature.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ConnectToNetworkFeature.swift; sourceTree = ""; }; + DC5EB9B82C0525980034B757 /* UIKit+ConnectToNetworkViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIKit+ConnectToNetworkViewController.swift"; sourceTree = ""; }; DC5EB9B92C0525980034B757 /* Network.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Network.swift; sourceTree = ""; }; - DC5EB9BA2C0525980034B757 /* NetworkDetailFeature.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NetworkDetailFeature.swift; sourceTree = ""; }; - DC5EB9BB2C0525980034B757 /* WiFiSettingsFeature.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = WiFiSettingsFeature.swift; sourceTree = ""; }; + DC5EB9BA2C0525980034B757 /* UIKit+NetworkDetailViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UIKit+NetworkDetailViewController.swift"; sourceTree = ""; }; + DC5EB9BB2C0525980034B757 /* WiFiSettingsViewController+.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "WiFiSettingsViewController+.swift"; sourceTree = ""; }; DC5EB9CB2C0525E80034B757 /* AssertEventually.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AssertEventually.swift; sourceTree = ""; }; DC5EB9CC2C0525E80034B757 /* SetUp.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SetUp.swift; sourceTree = ""; }; DC5EB9CD2C0525E80034B757 /* XCTTODO.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = XCTTODO.swift; sourceTree = ""; }; @@ -120,6 +127,13 @@ DC86E8702C208D8A003C0EC9 /* Text+Template.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Text+Template.swift"; sourceTree = ""; }; E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+MinimalObservationViewController.swift"; sourceTree = ""; }; E9836D952C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+NSControlBindingsViewController.swift"; sourceTree = ""; }; + E99B05942C70CE36003D3AFF /* WiFiSettingsModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WiFiSettingsModel.swift; sourceTree = ""; }; + E99B05962C70CE59003D3AFF /* AppKit+WiFiSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+WiFiSettingsViewController.swift"; sourceTree = ""; }; + E99B05982C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIKit+WiFiSettingsViewController.swift"; sourceTree = ""; }; + E99B059B2C70CEFE003D3AFF /* ConnectToNetworkModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConnectToNetworkModel.swift; sourceTree = ""; }; + E99B059D2C70CF18003D3AFF /* NetworkDetailModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NetworkDetailModel.swift; sourceTree = ""; }; + E99B05A12C70D5E1003D3AFF /* AppKit+NetworkDetailViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+NetworkDetailViewController.swift"; sourceTree = ""; }; + E99B05A32C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+ConnectToNetworkViewController.swift"; sourceTree = ""; }; E9CD5B752C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+EnumControlsViewController.swift"; sourceTree = ""; }; E9CD5B772C6CDEA500CE7947 /* AppKit+FocusViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+FocusViewController.swift"; sourceTree = ""; }; E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppKit+BasicsNavigationViewController.swift"; sourceTree = ""; }; @@ -207,6 +221,7 @@ CA473830272F0D860012CAC3 /* CaseStudiesApp.swift */, CA47382E272F0D860012CAC3 /* RootView.swift */, CA47380A272F0D340012CAC3 /* Assets.xcassets */, + DC5EB9BC2C0525980034B757 /* WiFiFeature */, CA9D70492C1F642A003B672A /* Internal */, CADCA3642C1CE80B00DE645F /* SwiftUI */, CA9D704A2C1F6431003B672A /* UIKit */, @@ -252,7 +267,6 @@ CA9D704F2C1FB431003B672A /* StaticNavigationStackController.swift */, CA9D70592C208977003B672A /* UIControlBindingsViewController.swift */, CA9D70442C1F6001003B672A /* UIKitCaseStudies.swift */, - DC5EB9BC2C0525980034B757 /* WiFiFeature */, ); path = UIKit; sourceTree = ""; @@ -273,10 +287,10 @@ DC5EB9BC2C0525980034B757 /* WiFiFeature */ = { isa = PBXGroup; children = ( - DC5EB9B82C0525980034B757 /* ConnectToNetworkFeature.swift */, DC5EB9B92C0525980034B757 /* Network.swift */, - DC5EB9BA2C0525980034B757 /* NetworkDetailFeature.swift */, - DC5EB9BB2C0525980034B757 /* WiFiSettingsFeature.swift */, + E99B05A02C70CF43003D3AFF /* ConnectToNetworkFeature */, + E99B059F2C70CF38003D3AFF /* NetworkDetailFeature */, + E99B059A2C70CEE1003D3AFF /* WiFiSettingsFeature */, ); path = WiFiFeature; sourceTree = ""; @@ -305,6 +319,37 @@ path = AppKit; sourceTree = ""; }; + E99B059A2C70CEE1003D3AFF /* WiFiSettingsFeature */ = { + isa = PBXGroup; + children = ( + E99B05942C70CE36003D3AFF /* WiFiSettingsModel.swift */, + DC5EB9BB2C0525980034B757 /* WiFiSettingsViewController+.swift */, + E99B05962C70CE59003D3AFF /* AppKit+WiFiSettingsViewController.swift */, + E99B05982C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift */, + ); + path = WiFiSettingsFeature; + sourceTree = ""; + }; + E99B059F2C70CF38003D3AFF /* NetworkDetailFeature */ = { + isa = PBXGroup; + children = ( + E99B059D2C70CF18003D3AFF /* NetworkDetailModel.swift */, + E99B05A12C70D5E1003D3AFF /* AppKit+NetworkDetailViewController.swift */, + DC5EB9BA2C0525980034B757 /* UIKit+NetworkDetailViewController.swift */, + ); + path = NetworkDetailFeature; + sourceTree = ""; + }; + E99B05A02C70CF43003D3AFF /* ConnectToNetworkFeature */ = { + isa = PBXGroup; + children = ( + E99B059B2C70CEFE003D3AFF /* ConnectToNetworkModel.swift */, + E99B05A32C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift */, + DC5EB9B82C0525980034B757 /* UIKit+ConnectToNetworkViewController.swift */, + ); + path = ConnectToNetworkFeature; + sourceTree = ""; + }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ @@ -466,8 +511,12 @@ CABE9FC1272F2C0000AFC150 /* EnumNavigation.swift in Sources */, E9CD5B782C6CDEA500CE7947 /* AppKit+FocusViewController.swift in Sources */, E9836D922C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift in Sources */, + E99B059E2C70CF18003D3AFF /* NetworkDetailModel.swift in Sources */, + E99B059C2C70CEFE003D3AFF /* ConnectToNetworkModel.swift in Sources */, E9CD5B7B2C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift in Sources */, DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */, + E99B05992C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift in Sources */, + E99B05A42C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift in Sources */, CA9D70502C1FB431003B672A /* StaticNavigationStackController.swift in Sources */, CA473837272F0D860012CAC3 /* FactClient.swift in Sources */, E9CD5B7C2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift in Sources */, @@ -476,18 +525,21 @@ CA9D70562C2087DC003B672A /* EnumControls.swift in Sources */, CA473836272F0D860012CAC3 /* CaseStudiesApp.swift in Sources */, CA473834272F0D860012CAC3 /* RootView.swift in Sources */, - CA3D0E322C20B27B00CCF7CD /* ConnectToNetworkFeature.swift in Sources */, + CA3D0E322C20B27B00CCF7CD /* UIKit+ConnectToNetworkViewController.swift in Sources */, E9836D962C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift in Sources */, - CA3D0E332C20B27B00CCF7CD /* NetworkDetailFeature.swift in Sources */, + CA3D0E332C20B27B00CCF7CD /* UIKit+NetworkDetailViewController.swift in Sources */, CA3D0E342C20B27B00CCF7CD /* Network.swift in Sources */, - CA3D0E352C20B27B00CCF7CD /* WiFiSettingsFeature.swift in Sources */, + CA3D0E352C20B27B00CCF7CD /* WiFiSettingsViewController+.swift in Sources */, + E99B05972C70CE59003D3AFF /* AppKit+WiFiSettingsViewController.swift in Sources */, CA26036D2C20973600822CA5 /* DetentsHelper.swift in Sources */, CA9D705A2C208977003B672A /* UIControlBindingsViewController.swift in Sources */, CA601BB02C236544006B0C5F /* FocusViewController.swift in Sources */, + E99B05952C70CE36003D3AFF /* WiFiSettingsModel.swift in Sources */, CA9D70472C1F6108003B672A /* AlertDialogState.swift in Sources */, CA9D70452C1F6001003B672A /* UIKitCaseStudies.swift in Sources */, CADCA3632C1CE75500DE645F /* SwiftUICaseStudies.swift in Sources */, CA9D705E2C2089DD003B672A /* EnumControlsViewController.swift in Sources */, + E99B05A22C70D5E1003D3AFF /* AppKit+NetworkDetailViewController.swift in Sources */, CA601BAE2C234613006B0C5F /* AnimationsViewController.swift in Sources */, CADCA3662C1CE8BE00DE645F /* CaseStudy.swift in Sources */, CA49D9542C20D4DF00E6C5BB /* ErasedNavigationStackController.swift in Sources */, diff --git a/Sources/AppKitNavigation/Bindings/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift index 37d7bb6ba3..ad4f4bf0df 100644 --- a/Sources/AppKitNavigation/Bindings/NSAlert.swift +++ b/Sources/AppKitNavigation/Bindings/NSAlert.swift @@ -28,7 +28,7 @@ extension NSAlert { ) { let button = addButton(withTitle: String(state: buttonState.label)) - button.createActionHandlerIfNeeded().addAction { _ in + button.createActionProxyIfNeeded().addBindingAction { _ in buttonState.withAction(handler) } diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index e266d8bc8a..4e7a88ffae 100644 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -26,7 +26,7 @@ extension NSColorPanel { self.init() bind(color: color) } - + /// Establishes a two-way connection between a binding and the color panel's selected color. /// /// - Parameter color: The binding to read from for the selected color, and write to diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index d1ee6d68b3..02294ec437 100644 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -17,11 +17,22 @@ extension NSControl: NSTargetActionProtocol { extension NSControl { public convenience init(action: @escaping (Self) -> Void) { self.init(frame: .zero) - createActionHandlerIfNeeded().addAction { [weak self] _ in + createActionProxyIfNeeded().addAction { [weak self] _ in guard let self else { return } action(self) } } + + public func addAction(_ action: @escaping (NSControl) -> Void) { + createActionProxyIfNeeded().addAction { [weak self] _ in + guard let self else { return } + action(self) + } + } + + public func removeAllActions() { + createActionProxyIfNeeded().removeAllActions() + } } #endif diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 752c4a62dc..a24aba654c 100644 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -15,7 +15,7 @@ extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { } private static let appkitNavigationDelegateKey = malloc(1)! - + private var appkitNavigationDelegate: Delegate { set { objc_setAssociatedObject(self, Self.appkitNavigationDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) @@ -25,17 +25,17 @@ extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { return delegate } else { let delegate = Delegate() - self.target = delegate + target = delegate self.appkitNavigationDelegate = delegate return delegate } } } - + private class Delegate: NSObject, NSFontChanging { var target: AnyObject? var action: Selector? - + func changeFont(_ sender: NSFontManager?) { if let action { NSApplication.shared.sendAction(action, to: target, from: sender) @@ -67,7 +67,7 @@ extension NSFontManager { public func bind(font: UIBinding) -> ObservationToken { bind(font, to: \._selectedFont) } - + @objc private var _selectedFont: NSFont { set { setSelectedFont(newValue, isMultiple: false) } get { convert(.systemFont(ofSize: 0)) } diff --git a/Sources/AppKitNavigation/Bindings/NSOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift similarity index 100% rename from Sources/AppKitNavigation/Bindings/NSOpenPanel.swift rename to Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift index 4c0dce7971..6362757314 100644 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -11,24 +11,59 @@ public protocol NSTargetActionProtocol: NSObject, Sendable { } @MainActor -internal class NSTargetActionHandler: NSObject { +class NSTargetActionProxy: NSObject { typealias Action = (Any?) -> Void - var actions: [Action] = [] + + internal private(set) var bindingActions: [Action] = [] + + internal private(set) var actions: [Action] = [] var originTarget: AnyObject? var originAction: Selector? + weak var owner: NSTargetActionProtocol? + + required init(owner: NSTargetActionProtocol) { + self.owner = owner + super.init() + self.originTarget = owner.appkitNavigationTarget + self.originAction = owner.appkitNavigationAction + owner.appkitNavigationTarget = self + owner.appkitNavigationAction = #selector(invokeAction(_:)) + if let textField = owner as? NSTextField { + NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) + } + } + + @objc func controlTextDidChange(_ obj: Notification) { + bindingActions.forEach { $0(obj.object) } + actions.forEach { $0(obj.object) } + } + @objc func invokeAction(_ sender: Any?) { if let originTarget, let originAction { NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } + bindingActions.forEach { $0(sender) } actions.forEach { $0(sender) } } func addAction(_ action: @escaping Action) { actions.append(action) } + + func removeAllActions() { + actions.removeAll() + } + + func addBindingAction(_ bindingAction: @escaping Action) { + bindingActions.append(bindingAction) + } + + func removeAllBindingActions() { + bindingActions.removeAll() + } } extension NSTargetActionProtocol { @@ -49,26 +84,22 @@ extension NSTargetActionProtocol { } } - internal var actionHandler: NSTargetActionHandler? { + var actionProxy: NSTargetActionProxy? { set { - objc_setAssociatedObject(self, actionHandlerKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { - objc_getAssociatedObject(self, actionHandlerKey) as? NSTargetActionHandler + objc_getAssociatedObject(self, actionProxyKey) as? NSTargetActionProxy } } - internal func createActionHandlerIfNeeded() -> NSTargetActionHandler { - if let actionHandler { - return actionHandler + func createActionProxyIfNeeded() -> NSTargetActionProxy { + if let actionProxy { + return actionProxy } else { - let actionHandler = NSTargetActionHandler() - actionHandler.originTarget = appkitNavigationTarget - actionHandler.originAction = appkitNavigationAction - self.actionHandler = actionHandler - appkitNavigationTarget = actionHandler - appkitNavigationAction = #selector(NSTargetActionHandler.invokeAction(_:)) - return actionHandler + let actionProxy = NSTargetActionProxy(owner: self) + self.actionProxy = actionProxy + return actionProxy } } @@ -89,8 +120,8 @@ extension NSTargetActionProtocol { set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObservationToken { unbind(keyPath) - let actionHandler = createActionHandlerIfNeeded() - actionHandler.addAction { [weak self] _ in + let actionProxy = createActionProxyIfNeeded() + actionProxy.addBindingAction { [weak self] _ in guard let self else { return } binding.wrappedValue = self[keyPath: keyPath] } @@ -120,7 +151,7 @@ extension NSTargetActionProtocol { MainActor._assumeIsolated { self?.appkitNavigationTarget = nil self?.appkitNavigationAction = nil - self?.actionHandler = nil + self?.actionProxy = nil } token.cancel() observation.invalidate() @@ -162,10 +193,9 @@ extension NSObject { } } - @MainActor private let observationTokensKey = malloc(1)! @MainActor -private let actionHandlerKey = malloc(1)! +private let actionProxyKey = malloc(1)! #endif diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 64d1c0de7a..a5faaaf38f 100644 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -1,7 +1,9 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit +import Combine import SwiftNavigation +@MainActor extension NSTextField: NSTextViewDelegate { /// Creates a new text field with the specified frame and registers the binding against its /// text. @@ -69,14 +71,14 @@ extension NSTextField: NSTextViewDelegate { selection.wrappedValue = control.textSelection } } - + let observationToken = ObservationToken { [weak self] in -// MainActor._assumeIsolated { - editingChangedAction.cancel() - editingDidEndAction.cancel() -// } - token.cancel() - self?.textSelectionObserver = nil + MainActor._assumeIsolated { + editingChangedAction.cancel() + editingDidEndAction.cancel() + token.cancel() + self?.textSelectionObserver = nil + } } observationTokens[\NSTextField.selectedRange] = observationToken return observationToken @@ -334,4 +336,7 @@ public struct AppKitTextSelection: Hashable, Sendable { range.isEmpty } } + +extension AnyCancellable: @unchecked Sendable {} + #endif diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift index 4fb5f90e74..bc63b33443 100644 --- a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift +++ b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift @@ -9,13 +9,22 @@ class ModalWindowsObserver: NSObject { var windowsCancellable: [NSWindow: AnyCancellable] = [:] - func observeWindow(_ window: NSWindow) { + var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:] + + func observeWindow(_ window: NSWindow, modalSession: NSApplication.ModalSession? = nil) { + if let modalSession { + modalSessionByWindow[window] = modalSession + } windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) .sink { [weak self] _ in guard let self else { return } - if NSApplication.shared.modalWindow === window { + if let modalSession = modalSessionByWindow[window] { + NSApplication.shared.endModalSession(modalSession) + } else if NSApplication.shared.modalWindow === window { NSApplication.shared.stopModal() } + modalSessionByWindow.removeValue(forKey: window) + windowsCancellable[window]?.cancel() windowsCancellable.removeValue(forKey: window) } } diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Internal/NavigationObserver.swift similarity index 100% rename from Sources/AppKitNavigation/Navigation/NavigationObserver.swift rename to Sources/AppKitNavigation/Internal/NavigationObserver.swift diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 615f985e1d..95eca9b464 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -25,6 +25,15 @@ extension NSObject { ) -> ObservationToken { modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } + + @discardableResult + public func modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObservationToken { + modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } /// Sheet a representable modally when a binding to a Boolean value you provide is true. /// @@ -47,6 +56,15 @@ extension NSObject { ) -> ObservationToken { modal(item: item, id: \.id, onDismiss: onDismiss, content: content) } + + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObservationToken { + modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } /// Sheet a representable modally when a binding to a Boolean value you provide is true. /// @@ -70,6 +88,16 @@ extension NSObject { ) -> ObservationToken { modal(item: item, id: \.id, onDismiss: onDismiss, content: content) } + + @_disfavoredOverload + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObservationToken { + modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } /// Sheet a representable modally when a binding to a Boolean value you provide is true. /// @@ -97,6 +125,18 @@ extension NSObject { } } + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObservationToken { + modalSession(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + @discardableResult public func modal( item: UIBinding, @@ -131,6 +171,40 @@ extension NSObject { } } + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObservationToken { + modal(item: item, id: id) { $item in + content($item) + } beginModal: { modalContent, _ in + if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] { + NSApplication.shared.endModalSession(modalSession) + modaledWindow.window.close() + onDismiss?() + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) + } + + } else { + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) + } + } + } endModal: { modalContent, _ in + if let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] { + NSApplication.shared.endModalSession(modalSession) + modalContent.window.close() + onDismiss?() + } + } + } + private func modal( item: UIBinding, id: KeyPath, diff --git a/Sources/AppKitNavigation/Bindings/NSSavePanel.swift b/Sources/AppKitNavigation/Navigation/ModalSession.swift similarity index 97% rename from Sources/AppKitNavigation/Bindings/NSSavePanel.swift rename to Sources/AppKitNavigation/Navigation/ModalSession.swift index 893f31d20e..51a47075aa 100644 --- a/Sources/AppKitNavigation/Bindings/NSSavePanel.swift +++ b/Sources/AppKitNavigation/Navigation/ModalSession.swift @@ -2,4 +2,6 @@ import AppKit + + #endif diff --git a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift new file mode 100644 index 0000000000..5a27dab29c --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift @@ -0,0 +1,29 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol ModalSessionContent: ModalContent { + func appKitNavigationBeginModalSession() -> NSApplication.ModalSession +} + +extension NSWindow: ModalSessionContent { + + public func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { + __appKitNavigationBeginModalSession() + } + + @objc func __appKitNavigationBeginModalSession() -> NSApplication.ModalSession { + let modalSession = NSApplication.shared.beginModalSession(for: self) +// NSApplication.shared.runModalSession(modalSession) + return modalSession + } +} + +//extension NSSavePanel { +// override func __appKitNavigationBeginModalSession() -> NSApplication.ModalSession { +// begin +// } +//} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index 8162d88d3a..eb06919cd8 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -11,15 +11,13 @@ public protocol SheetContent: NavigationContent { extension SheetContent { public func beginSheet(for content: any SheetContent) async { - if let sheetedWindow = content.currentWindow { - await currentWindow?.beginSheet(sheetedWindow) - } + guard let sheetedWindow = content.currentWindow else { return } + await currentWindow?.beginSheet(sheetedWindow) } public func endSheet(for content: any SheetContent) { - if let sheetedWindow = content.currentWindow { - currentWindow?.endSheet(sheetedWindow) - } + guard let sheetedWindow = content.currentWindow else { return } + currentWindow?.endSheet(sheetedWindow) } } @@ -48,4 +46,15 @@ extension NSAlert: SheetContent { } } +extension NSSavePanel { + public func beginSheet(for content: any SheetContent) async { + guard let parentWindow = content.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + public func endSheet(for content: any SheetContent) { + content.currentWindow?.endSheet(window) + } +} + #endif diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index df6134abdd..d537d53be2 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -104,8 +104,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax", "state" : { - "revision" : "06b5cdc432e93b60e3bdf53aff2857c6b312991a", - "version" : "600.0.0-prerelease-2024-07-30" + "revision" : "515f79b522918f83483068d99c68daeb5116342d", + "version" : "600.0.0-prerelease-2024-08-14" } }, { @@ -122,8 +122,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { - "revision" : "357ca1e5dd31f613a1d43320870ebc219386a495", - "version" : "1.2.2" + "revision" : "c6809a193975cab4d5308c64bd1d51e0df467928", + "version" : "1.2.3" } } ], From 7278ccc691b1950a2c26a0e2aacb1054a987d236 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Sun, 18 Aug 2024 22:57:20 +0800 Subject: [PATCH 012/141] WIP --- Examples/CaseStudies/Internal/CaseStudy.swift | 7 +++++++ .../AppKit+WiFiSettingsViewController.swift | 13 ++++++++----- Examples/Examples.xcodeproj/project.pbxproj | 2 +- Sources/AppKitNavigation/Bindings/NSAlert.swift | 3 ++- .../Bindings/NSSaveOpenPanel.swift | 15 ++++++--------- 5 files changed, 24 insertions(+), 16 deletions(-) diff --git a/Examples/CaseStudies/Internal/CaseStudy.swift b/Examples/CaseStudies/Internal/CaseStudy.swift index b6d739cb31..c55a82c934 100644 --- a/Examples/CaseStudies/Internal/CaseStudy.swift +++ b/Examples/CaseStudies/Internal/CaseStudy.swift @@ -9,6 +9,7 @@ protocol CaseStudy { } protocol SwiftUICaseStudy: CaseStudy, View {} + #if canImport(UIKit) && !os(watchOS) import UIKitNavigation @@ -17,6 +18,7 @@ extension UIKitCaseStudy { var usesOwnLayout: Bool { true } } #endif + #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKitNavigation @@ -187,6 +189,11 @@ struct CaseStudyModifier: ViewModifier { .sheet(isPresented: $isAboutPresented) { Form { Text(template: caseStudy.readMe) + #if os(macOS) + Button("Close") { + isAboutPresented = false + } + #endif } .presentationDetents([.medium]) } diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift index 698db6d09b..9f72cd5b61 100644 --- a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -56,8 +56,8 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas dataSource = NSCollectionViewDiffableDataSource( collectionView: collectionView - ) { [unowned self] collectionView, indexPath, item in - + ) { [weak self] collectionView, indexPath, item in + guard let self else { return nil } switch item { case .isOn: let switchViewItem = collectionView.makeItem(withIdentifier: .init(WiFiSettingsSwitchViewItem.self), for: indexPath) as! WiFiSettingsSwitchViewItem @@ -70,7 +70,8 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas connectedViewItem.nameLabel.stringValue = network.name connectedViewItem.securedIconImageView.isHidden = !network.isSecured connectedViewItem.wifiIconImageView.image = NSImage(systemSymbolName: "wifi", variableValue: network.connectivity, accessibilityDescription: nil) - connectedViewItem.detailButton.addAction { _ in + connectedViewItem.detailButton.addAction { [weak self] _ in + guard let self else { return } self.model.infoButtonTapped(network: network) } return connectedViewItem @@ -79,7 +80,8 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas foundedViewItem.titleLabel.stringValue = network.name foundedViewItem.securedIconImageView.isHidden = !network.isSecured foundedViewItem.wifiIconImageView.image = NSImage(systemSymbolName: "wifi", variableValue: network.connectivity, accessibilityDescription: nil) - foundedViewItem.connectButton.addAction { _ in + foundedViewItem.connectButton.addAction { [weak self] _ in + guard let self else { return } self.model.networkTapped(network) } return foundedViewItem @@ -97,10 +99,11 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas modalSession(item: $model.destination.connect) { model in let panel = NSPanel(contentViewController: ConnectToNetworkViewController(model: model)) panel.styleMask = [.titled] + panel.title = "" panel.animationBehavior = .none return panel } - + present(item: $model.destination.detail, style: .sheet) { model in let vc = NetworkDetailViewController(model: model) vc.preferredContentSize = .init(width: 300, height: 200) diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index ea0c563924..34e4997f5f 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -221,11 +221,11 @@ CA473830272F0D860012CAC3 /* CaseStudiesApp.swift */, CA47382E272F0D860012CAC3 /* RootView.swift */, CA47380A272F0D340012CAC3 /* Assets.xcassets */, - DC5EB9BC2C0525980034B757 /* WiFiFeature */, CA9D70492C1F642A003B672A /* Internal */, CADCA3642C1CE80B00DE645F /* SwiftUI */, CA9D704A2C1F6431003B672A /* UIKit */, E9836D902C6C9E3000FC6EFD /* AppKit */, + DC5EB9BC2C0525980034B757 /* WiFiFeature */, ); path = CaseStudies; sourceTree = ""; diff --git a/Sources/AppKitNavigation/Bindings/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift index ad4f4bf0df..812f894812 100644 --- a/Sources/AppKitNavigation/Bindings/NSAlert.swift +++ b/Sources/AppKitNavigation/Bindings/NSAlert.swift @@ -24,7 +24,7 @@ extension NSAlert { extension NSAlert { public func addButton( _ buttonState: ButtonState, - action handler: @escaping (_ action: Action?) -> Void + action handler: @escaping (_ action: Action?) -> Void = { (_: Never?) in } ) { let button = addButton(withTitle: String(state: buttonState.label)) @@ -35,6 +35,7 @@ extension NSAlert { if buttonState.role == .destructive, #available(macOS 11.0, *) { button.hasDestructiveAction = true } + if buttonState.role == .cancel { button.keyEquivalent = "\u{1b}" } diff --git a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift index 896135f71e..b781c72116 100644 --- a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift @@ -8,13 +8,13 @@ extension NSSavePanel { self.init() bind(url: url) } - + @discardableResult public func bind(url binding: UIBinding) -> ObservationToken { appKitNavigation_onFinalURL = { url in binding.wrappedValue = url } - + let observationToken = ObservationToken { [weak self] in guard let self else { return } MainActor._assumeIsolated { @@ -24,28 +24,25 @@ extension NSSavePanel { observationTokens[\NSSavePanel.url] = observationToken return observationToken } - + public func unbindURL() { observationTokens[\NSSavePanel.url]?.cancel() observationTokens[\NSSavePanel.url] = nil } - - } extension NSOpenPanel { - public convenience init(urls: UIBinding<[URL]>) { self.init() bind(urls: urls) } - + @discardableResult public func bind(urls binding: UIBinding<[URL]>) -> ObservationToken { appKitNavigation_onFinalURLs = { urls in binding.wrappedValue = urls } - + let observationToken = ObservationToken { [weak self] in guard let self else { return } MainActor._assumeIsolated { @@ -55,7 +52,7 @@ extension NSOpenPanel { observationTokens[\NSOpenPanel.urls] = observationToken return observationToken } - + public func unbindURLs() { observationTokens[\NSOpenPanel.urls]?.cancel() observationTokens[\NSOpenPanel.urls] = nil From 61e1fff119d2a8888052a9d33c8908f46c41424e Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Mon, 19 Aug 2024 00:37:47 +0800 Subject: [PATCH 013/141] WIP --- Package.swift | 2 + .../AppKitNavigation/Bindings/NSControl.swift | 7 +- .../Bindings/NSTargetAction.swift | 62 +------------ .../Bindings/NSTargetActionProxy.swift | 88 +++++++++++++++++++ .../Internal/ClosureHolder.swift | 17 ---- .../ModalWindowsObserver.swift | 0 .../NavigationObserver.swift | 0 7 files changed, 98 insertions(+), 78 deletions(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift delete mode 100644 Sources/AppKitNavigation/Internal/ClosureHolder.swift rename Sources/AppKitNavigation/{Internal => Navigation}/ModalWindowsObserver.swift (100%) rename Sources/AppKitNavigation/{Internal => Navigation}/NavigationObserver.swift (100%) diff --git a/Package.swift b/Package.swift index 480e3861b8..fc20ea17dc 100644 --- a/Package.swift +++ b/Package.swift @@ -35,6 +35,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0"), ], targets: [ .target( @@ -83,6 +84,7 @@ let package = Package( "SwiftNavigation", "AppKitNavigationShim", .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index 02294ec437..7edc6aaef2 100644 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -23,13 +23,18 @@ extension NSControl { } } - public func addAction(_ action: @escaping (NSControl) -> Void) { + @discardableResult + public func addAction(_ action: @escaping (NSControl) -> Void) -> UUID { createActionProxyIfNeeded().addAction { [weak self] _ in guard let self else { return } action(self) } } + public func removeAction(for id: UUID) { + createActionProxyIfNeeded().removeAction(for: id) + } + public func removeAllActions() { createActionProxyIfNeeded().removeAllActions() } diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift index 6362757314..fb6e9553fa 100644 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -10,62 +10,6 @@ public protocol NSTargetActionProtocol: NSObject, Sendable { var appkitNavigationAction: Selector? { set get } } -@MainActor -class NSTargetActionProxy: NSObject { - typealias Action = (Any?) -> Void - - internal private(set) var bindingActions: [Action] = [] - - internal private(set) var actions: [Action] = [] - - var originTarget: AnyObject? - - var originAction: Selector? - - weak var owner: NSTargetActionProtocol? - - required init(owner: NSTargetActionProtocol) { - self.owner = owner - super.init() - self.originTarget = owner.appkitNavigationTarget - self.originAction = owner.appkitNavigationAction - owner.appkitNavigationTarget = self - owner.appkitNavigationAction = #selector(invokeAction(_:)) - if let textField = owner as? NSTextField { - NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) - } - } - - @objc func controlTextDidChange(_ obj: Notification) { - bindingActions.forEach { $0(obj.object) } - actions.forEach { $0(obj.object) } - } - - @objc func invokeAction(_ sender: Any?) { - if let originTarget, let originAction { - NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) - } - bindingActions.forEach { $0(sender) } - actions.forEach { $0(sender) } - } - - func addAction(_ action: @escaping Action) { - actions.append(action) - } - - func removeAllActions() { - actions.removeAll() - } - - func addBindingAction(_ bindingAction: @escaping Action) { - bindingActions.append(bindingAction) - } - - func removeAllBindingActions() { - bindingActions.removeAll() - } -} - extension NSTargetActionProtocol { /// Establishes a two-way connection between a source of truth and a property of this control. /// @@ -121,7 +65,7 @@ extension NSTargetActionProtocol { ) -> ObservationToken { unbind(keyPath) let actionProxy = createActionProxyIfNeeded() - actionProxy.addBindingAction { [weak self] _ in + let actionID = actionProxy.addBindingAction { [weak self] _ in guard let self else { return } binding.wrappedValue = self[keyPath: keyPath] } @@ -149,9 +93,7 @@ extension NSTargetActionProtocol { } let observationToken = ObservationToken { [weak self] in MainActor._assumeIsolated { - self?.appkitNavigationTarget = nil - self?.appkitNavigationAction = nil - self?.actionProxy = nil + self?.actionProxy?.removeAction(for: actionID) } token.cancel() observation.invalidate() diff --git a/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift new file mode 100644 index 0000000000..2d2054d0ec --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift @@ -0,0 +1,88 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import IdentifiedCollections + +@MainActor +class NSTargetActionProxy: NSObject { + typealias ActionClosure = (Any?) -> Void + + typealias ActionIdentifier = UUID + + private struct Action: Identifiable { + let id = UUID() + + var closure: ActionClosure + + func invoke(_ sender: Any?) { + closure(sender) + } + } + + private var bindingActions: IdentifiedArrayOf = [] + + private var actions: IdentifiedArrayOf = [] + + private var originTarget: AnyObject? + + private var originAction: Selector? + + weak var owner: NSTargetActionProtocol? + + required init(owner: NSTargetActionProtocol) { + self.owner = owner + super.init() + self.originTarget = owner.appkitNavigationTarget + self.originAction = owner.appkitNavigationAction + owner.appkitNavigationTarget = self + owner.appkitNavigationAction = #selector(invokeAction(_:)) + if let textField = owner as? NSTextField { + NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) + } + } + + @objc func controlTextDidChange(_ obj: Notification) { + bindingActions.forEach { $0.invoke(obj.object) } + actions.forEach { $0.invoke(obj.object) } + } + + @objc func invokeAction(_ sender: Any?) { + if let originTarget, let originAction { + NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) + } + bindingActions.forEach { $0.invoke(sender) } + actions.forEach { $0.invoke(sender) } + } + + @discardableResult + func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { + let action = Action(closure: actionClosure) + actions.append(action) + return action.id + } + + func removeAction(for id: ActionIdentifier) { + actions.remove(id: id) + } + + func removeAllActions() { + actions.removeAll() + } + + @discardableResult + func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { + let bindingAction = Action(closure: bindingActionClosure) + bindingActions.append(bindingAction) + return bindingAction.id + } + + func removeBindingAction(for id: ActionIdentifier) { + bindingActions.remove(id: id) + } + + func removeAllBindingActions() { + bindingActions.removeAll() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Internal/ClosureHolder.swift b/Sources/AppKitNavigation/Internal/ClosureHolder.swift deleted file mode 100644 index 814e884dff..0000000000 --- a/Sources/AppKitNavigation/Internal/ClosureHolder.swift +++ /dev/null @@ -1,17 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import Foundation - -internal class ClosureHolder: NSObject { - let closure: () -> Void - - init(closure: @escaping () -> Void) { - self.closure = closure - } - - func invoke() { - closure() - } -} - -#endif diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift similarity index 100% rename from Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift rename to Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift diff --git a/Sources/AppKitNavigation/Internal/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift similarity index 100% rename from Sources/AppKitNavigation/Internal/NavigationObserver.swift rename to Sources/AppKitNavigation/Navigation/NavigationObserver.swift From 2ba32eb37994d3076f1e23b12efacc1a0518838a Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Mon, 19 Aug 2024 22:28:33 +0800 Subject: [PATCH 014/141] Format --- .../SwiftUI/Representable.swift | 20 ++++--- Sources/AppKitNavigation/UIBinding.swift | 14 ++--- Sources/AppKitNavigation/UITransaction.swift | 56 +++++++++---------- 3 files changed, 46 insertions(+), 44 deletions(-) diff --git a/Sources/AppKitNavigation/SwiftUI/Representable.swift b/Sources/AppKitNavigation/SwiftUI/Representable.swift index 29ac8b2301..e89259acfe 100644 --- a/Sources/AppKitNavigation/SwiftUI/Representable.swift +++ b/Sources/AppKitNavigation/SwiftUI/Representable.swift @@ -1,24 +1,26 @@ #if canImport(SwiftUI) && canImport(AppKit) && !targetEnvironment(macCatalyst) - import SwiftUI - import AppKit +import SwiftUI +import AppKit - public struct NSViewControllerRepresenting< +public struct NSViewControllerRepresenting< NSViewControllerType: NSViewController - >: NSViewControllerRepresentable { +>: NSViewControllerRepresentable { private let base: NSViewControllerType public init(_ base: () -> NSViewControllerType) { - self.base = base() + self.base = base() } + public func makeNSViewController(context _: Context) -> NSViewControllerType { base } public func updateNSViewController(_: NSViewControllerType, context _: Context) {} - } +} - public struct NSViewRepresenting: NSViewRepresentable { +public struct NSViewRepresenting: NSViewRepresentable { private let base: NSViewType public init(_ base: () -> NSViewType) { - self.base = base() + self.base = base() } + public func makeNSView(context _: Context) -> NSViewType { base } public func updateNSView(_: NSViewType, context _: Context) {} - } +} #endif diff --git a/Sources/AppKitNavigation/UIBinding.swift b/Sources/AppKitNavigation/UIBinding.swift index 4a66220b17..ea3499dec7 100644 --- a/Sources/AppKitNavigation/UIBinding.swift +++ b/Sources/AppKitNavigation/UIBinding.swift @@ -1,15 +1,15 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - import SwiftNavigation - - extension UIBinding { +import SwiftNavigation + +extension UIBinding { /// Specifies an animation to perform when the binding value changes. /// /// - Parameter animation: An animation sequence performed when the binding value changes. /// - Returns: A new binding. public func animation(_ animation: AppKitAnimation? = .default) -> Self { - var binding = self - binding.transaction.appKit.animation = animation - return binding + var binding = self + binding.transaction.appKit.animation = animation + return binding } - } +} #endif diff --git a/Sources/AppKitNavigation/UITransaction.swift b/Sources/AppKitNavigation/UITransaction.swift index 88ba674b30..b4f9535f4e 100644 --- a/Sources/AppKitNavigation/UITransaction.swift +++ b/Sources/AppKitNavigation/UITransaction.swift @@ -2,52 +2,52 @@ import SwiftNavigation - extension UITransaction { +extension UITransaction { /// Creates a transaction and assigns its animation property. /// /// - Parameter animation: The animation to perform when the current state changes. public init(animation: AppKitAnimation? = nil) { - self.init() - self.appKit.animation = animation + self.init() + appKit.animation = animation } /// AppKit-specific data associated with the current state change. public var appKit: AppKit { - get { self[AppKitKey.self] } - set { self[AppKitKey.self] = newValue } + get { self[AppKitKey.self] } + set { self[AppKitKey.self] = newValue } } private enum AppKitKey: UITransactionKey { - static let defaultValue = AppKit() + static let defaultValue = AppKit() } /// AppKit-specific data associated with a ``UITransaction``. public struct AppKit: Sendable { - /// The animation, if any, associated with the current state change. - public var animation: AppKitAnimation? - - /// A Boolean value that indicates whether views should disable animations. - public var disablesAnimations = false - - var animationCompletions: [@Sendable (Bool?) -> Void] = [] - - /// Adds a completion to run when the animations created with this transaction are all - /// complete. - /// - /// The completion callback will always be fired exactly one time. - public mutating func addAnimationCompletion( - _ completion: @escaping @Sendable (Bool?) -> Void - ) { - animationCompletions.append(completion) - } + /// The animation, if any, associated with the current state change. + public var animation: AppKitAnimation? + + /// A Boolean value that indicates whether views should disable animations. + public var disablesAnimations = false + + var animationCompletions: [@Sendable (Bool?) -> Void] = [] + + /// Adds a completion to run when the animations created with this transaction are all + /// complete. + /// + /// The completion callback will always be fired exactly one time. + public mutating func addAnimationCompletion( + _ completion: @escaping @Sendable (Bool?) -> Void + ) { + animationCompletions.append(completion) + } } - } +} - private enum AnimationCompletionsKey: UITransactionKey { +private enum AnimationCompletionsKey: UITransactionKey { static let defaultValue: [@Sendable (Bool?) -> Void] = [] - } +} - private enum DisablesAnimationsKey: UITransactionKey { +private enum DisablesAnimationsKey: UITransactionKey { static let defaultValue = false - } +} #endif From e2c5db49fe6236eca0f9fbbef9d10ddc04092af4 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Mon, 19 Aug 2024 22:38:19 +0800 Subject: [PATCH 015/141] Common --- Package.swift | 17 ++ Package@swift-6.0.swift | 17 ++ .../AppKitNavigation/AppKitAnimation.swift | 102 ++++++++++ .../Internal/AssociatedKeys.swift | 36 ++++ .../Internal/AssumeIsolated.swift | 35 ++++ .../Internal/ErrorMechanism.swift | 20 ++ .../AppKitNavigation/Internal/Exports.swift | 3 + .../Internal/ToOptionalUnit.swift | 12 ++ Sources/AppKitNavigation/Observe.swift | 181 ++++++++++++++++++ Sources/AppKitNavigation/UIBinding.swift | 15 ++ Sources/AppKitNavigation/UITransaction.swift | 53 +++++ Sources/AppKitNavigationShim/include/shim.h | 25 +++ Sources/AppKitNavigationShim/shim.m | 152 +++++++++++++++ 13 files changed, 668 insertions(+) create mode 100644 Sources/AppKitNavigation/AppKitAnimation.swift create mode 100644 Sources/AppKitNavigation/Internal/AssociatedKeys.swift create mode 100644 Sources/AppKitNavigation/Internal/AssumeIsolated.swift create mode 100644 Sources/AppKitNavigation/Internal/ErrorMechanism.swift create mode 100644 Sources/AppKitNavigation/Internal/Exports.swift create mode 100644 Sources/AppKitNavigation/Internal/ToOptionalUnit.swift create mode 100644 Sources/AppKitNavigation/Observe.swift create mode 100644 Sources/AppKitNavigation/UIBinding.swift create mode 100644 Sources/AppKitNavigation/UITransaction.swift create mode 100644 Sources/AppKitNavigationShim/include/shim.h create mode 100644 Sources/AppKitNavigationShim/shim.m diff --git a/Package.swift b/Package.swift index 46c1d7edbe..fc20ea17dc 100644 --- a/Package.swift +++ b/Package.swift @@ -23,6 +23,10 @@ let package = Package( name: "UIKitNavigation", targets: ["UIKitNavigation"] ), + .library( + name: "AppKitNavigation", + targets: ["AppKitNavigation"] + ), ], dependencies: [ .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -31,6 +35,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0"), ], targets: [ .target( @@ -73,6 +78,18 @@ let package = Package( .target( name: "UIKitNavigationShim" ), + .target( + name: "AppKitNavigation", + dependencies: [ + "SwiftNavigation", + "AppKitNavigationShim", + .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), + ] + ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 9ed432ff67..a97be3d08e 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -23,6 +23,10 @@ let package = Package( name: "UIKitNavigation", targets: ["UIKitNavigation"] ), + .library( + name: "AppKitNavigation", + targets: ["AppKitNavigation"] + ), ], dependencies: [ .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -31,6 +35,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0"), ], targets: [ .target( @@ -73,6 +78,18 @@ let package = Package( .target( name: "UIKitNavigationShim" ), + .target( + name: "AppKitNavigation", + dependencies: [ + "SwiftNavigation", + "AppKitNavigationShim", + .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), + ] + ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift new file mode 100644 index 0000000000..0d8230c8fb --- /dev/null +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -0,0 +1,102 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +#if canImport(SwiftUI) +import SwiftUI +#endif + +import SwiftNavigation + +/// Executes a closure with the specified animation and returns the result. +/// +/// - Parameters: +/// - animation: An animation, set in the ``UITransaction/appKit`` property of the thread's +/// current transaction. +/// - body: A closure to execute. +/// - completion: A completion to run when the animation is complete. +/// - Returns: The result of executing the closure with the specified animation. +@MainActor +public func withAppKitAnimation( + _ animation: AppKitAnimation? = .default, + _ body: () throws -> Result, + completion: (@Sendable (Bool?) -> Void)? = nil +) rethrows -> Result { + var transaction = UITransaction() + transaction.appKit.animation = animation + if let completion { + transaction.appKit.addAnimationCompletion(completion) + } + return try withUITransaction(transaction, body) +} + +/// The way a view changes over time to create a smooth visual transition from one state to +/// another. +public struct AppKitAnimation: Hashable, Sendable { + fileprivate let framework: Framework + + @MainActor + func perform( + _ body: () throws -> Result, + completion: ((Bool?) -> Void)? = nil + ) rethrows -> Result { + switch framework { + case let .swiftUI(animation): + _ = animation + fatalError() + case let .appKit(animation): + var result: Swift.Result? + NSAnimationContext.runAnimationGroup { context in + context.duration = animation.duration + result = Swift.Result(catching: body) + } completionHandler: { + completion?(true) + } + + return try result!._rethrowGet() + } + } + + fileprivate enum Framework: Hashable, Sendable { + case appKit(AppKit) + case swiftUI(Animation) + + fileprivate struct AppKit: Hashable, Sendable { + fileprivate var duration: TimeInterval + + func hash(into hasher: inout Hasher) { + hasher.combine(duration) + } + } + } +} + +extension AppKitAnimation { + /// Performs am animation using a timing curve corresponding to the motion of a physical spring. + /// + /// A value description of + /// `UIView.animate(withDuration:delay:dampingRatio:velocity:options:animations:completion:)` + /// that can be used with ``withAppKitAnimation(_:_:completion:)``. + /// + /// - Parameters: + /// - duration: The total duration of the animations, measured in seconds. If you specify a + /// negative value or `0`, the changes are made without animating them. + /// - Returns: An animation using a timing curve corresponding to the motion of a physical + /// spring. + public static func animate( + withDuration duration: TimeInterval = 0.25 + ) -> Self { + Self( + framework: .appKit( + Framework.AppKit( + duration: duration + ) + ) + ) + } + + /// A default animation instance. + public static var `default`: Self { + return .animate() + } +} +#endif diff --git a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift new file mode 100644 index 0000000000..1df9f50edc --- /dev/null +++ b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift @@ -0,0 +1,36 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +struct AssociatedKeys { + var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] + + mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { + let key = AnyHashableMetatype(type) + if let associatedKey = keys[key] { + return associatedKey + } else { + let associatedKey = malloc(1)! + keys[key] = associatedKey + return associatedKey + } + } +} + +struct AnyHashableMetatype: Hashable { + static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { + return lhs.base == rhs.base + } + + let base: Any.Type + + init(_ base: Any.Type) { + self.base = base + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(base)) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift new file mode 100644 index 0000000000..93f1c40098 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift @@ -0,0 +1,35 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import Foundation + +extension MainActor { + // NB: This functionality was not back-deployed in Swift 5.9 + static func _assumeIsolated( + _ operation: @MainActor () throws -> T, + file: StaticString = #fileID, + line: UInt = #line + ) rethrows -> T { + #if swift(<5.10) + typealias YesActor = @MainActor () throws -> T + typealias NoActor = () throws -> T + + guard Thread.isMainThread else { + fatalError( + "Incorrect actor executor assumption; Expected same executor as \(self).", + file: file, + line: line + ) + } + + return try withoutActuallyEscaping(operation) { (_ fn: @escaping YesActor) throws -> T in + let rawFn = unsafeBitCast(fn, to: NoActor.self) + return try rawFn() + } + #else + return try assumeIsolated(operation, file: file, line: line) + #endif + } +} + + +#endif diff --git a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift new file mode 100644 index 0000000000..1ec4c47b0a --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift @@ -0,0 +1,20 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +@rethrows +protocol _ErrorMechanism { + associatedtype Output + func get() throws -> Output +} + +extension _ErrorMechanism { + func _rethrowError() rethrows -> Never { + _ = try _rethrowGet() + fatalError() + } + + func _rethrowGet() rethrows -> Output { + return try get() + } +} + +extension Result: _ErrorMechanism {} +#endif diff --git a/Sources/AppKitNavigation/Internal/Exports.swift b/Sources/AppKitNavigation/Internal/Exports.swift new file mode 100644 index 0000000000..554225adc1 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/Exports.swift @@ -0,0 +1,3 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +@_exported import SwiftNavigation +#endif diff --git a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift new file mode 100644 index 0000000000..a11cfaaf1d --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift @@ -0,0 +1,12 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +extension Bool { + struct Unit: Hashable, Identifiable { + var id: Unit { self } + } + + var toOptionalUnit: Unit? { + get { self ? Unit() : nil } + set { self = newValue != nil } + } +} +#endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift new file mode 100644 index 0000000000..8032874494 --- /dev/null +++ b/Sources/AppKitNavigation/Observe.swift @@ -0,0 +1,181 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +@_spi(Internals) import SwiftNavigation +import AppKit + +@MainActor +extension NSObject { + /// Observe access to properties of an observable (or perceptible) object. + /// + /// This tool allows you to set up an observation loop so that you can access fields from an + /// observable model in order to populate your view, and also automatically track changes to + /// any accessed fields so that the view is always up-to-date. + /// + /// It is most useful when dealing with non-SwiftUI views, such as AppKit views and controller. + /// You can invoke the ``observe(_:)`` method a single time in the `viewDidLoad` and update all + /// the view elements: + /// + /// ```swift + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// let countLabel = NSTextField(labelWithString: "") + /// let incrementButton = NSButton { [weak self] _ in + /// self?.model.incrementButtonTapped() + /// } + /// + /// observe { [weak self] in + /// guard let self + /// else { return } + /// + /// countLabel.stringValue = "\(model.count)" + /// } + /// } + /// ``` + /// + /// This closure is immediately called, allowing you to set the initial state of your UI + /// components from the feature's state. And if the `count` property in the feature's state is + /// ever mutated, this trailing closure will be called again, allowing us to update the view + /// again. + /// + /// Generally speaking you can usually have a single ``observe(_:)`` in the entry point of your + /// view, such as `viewDidLoad` for `NSViewController`. This works even if you have many UI + /// components to update: + /// + /// ```swift + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// observe { [weak self] in + /// guard let self + /// else { return } + /// + /// countLabel.isHidden = model.isObservingCount + /// if !countLabel.isHidden { + /// countLabel.stringValue = "\(model.count)" + /// } + /// factLabel.stringValue = model.fact + /// } + /// } + /// ``` + /// + /// This does mean that you may execute the line `factLabel.text = model.fact` even when + /// something unrelated changes, such as `store.model`, but that is typically OK for simple + /// properties of UI components. It is not a performance problem to repeatedly set the `text` of + /// a label or the `isHidden` of a button. + /// + /// However, if there is heavy work you need to perform when state changes, then it is best to + /// put that in its own ``observe(_:)``. For example, if you needed to reload a table view or + /// collection view when a collection changes: + /// + /// ```swift + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// observe { [weak self] in + /// guard let self + /// else { return } + /// + /// dataSource = model.items + /// tableView.reloadData() + /// } + /// } + /// ``` + /// + /// ## Cancellation + /// + /// The method returns an ``ObservationToken`` that can be used to cancel observation. For + /// example, if you only want to observe while a view controller is visible, you can start + /// observation in the `viewWillAppear` and then cancel observation in the `viewWillDisappear`: + /// + /// ```swift + /// var observation: ObservationToken? + /// + /// func viewWillAppear() { + /// super.viewWillAppear() + /// observation = observe { [weak self] in + /// // ... + /// } + /// } + /// func viewWillDisappear() { + /// super.viewWillDisappear() + /// observation?.cancel() + /// } + /// ``` + /// + /// - Parameter apply: A closure that contains properties to track and is invoked when the value + /// of a property changes. + /// - Returns: A cancellation token. + @discardableResult + public func observe(_ apply: @escaping @MainActor @Sendable () -> Void) -> ObservationToken { + observe { _ in apply() } + } + + /// Observe access to properties of an observable (or perceptible) object. + /// + /// A version of ``observe(_:)`` that is passed the current transaction. + /// + /// - Parameter apply: A closure that contains properties to track and is invoked when the value + /// of a property changes. + /// - Returns: A cancellation token. + @discardableResult + public func observe( + _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void + ) -> ObservationToken { + let token = SwiftNavigation.observe { transaction in + MainActor._assumeIsolated { + withUITransaction(transaction) { + if transaction.appKit.disablesAnimations { + NSView.performWithoutAnimation { apply(transaction) } + for completion in transaction.appKit.animationCompletions { + completion(true) + } + } else if let animation = transaction.appKit.animation { + return animation.perform( + { apply(transaction) }, + completion: transaction.appKit.animationCompletions.isEmpty + ? nil + : { + for completion in transaction.appKit.animationCompletions { + completion($0) + } + } + ) + } else { + apply(transaction) + for completion in transaction.appKit.animationCompletions { + completion(true) + } + } + } + } + } task: { transaction, work in + DispatchQueue.main.async { + withUITransaction(transaction, work) + } + } + tokens.append(token) + return token + } + + fileprivate var tokens: [Any] { + get { + objc_getAssociatedObject(self, Self.tokensKey) as? [Any] ?? [] + } + set { + objc_setAssociatedObject(self, Self.tokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + private static let tokensKey = malloc(1)! +} + +extension NSView { + fileprivate static func performWithoutAnimation(_ block: () -> Void) { + NSAnimationContext.runAnimationGroup { context in + context.allowsImplicitAnimation = false + block() + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/UIBinding.swift b/Sources/AppKitNavigation/UIBinding.swift new file mode 100644 index 0000000000..ea3499dec7 --- /dev/null +++ b/Sources/AppKitNavigation/UIBinding.swift @@ -0,0 +1,15 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import SwiftNavigation + +extension UIBinding { + /// Specifies an animation to perform when the binding value changes. + /// + /// - Parameter animation: An animation sequence performed when the binding value changes. + /// - Returns: A new binding. + public func animation(_ animation: AppKitAnimation? = .default) -> Self { + var binding = self + binding.transaction.appKit.animation = animation + return binding + } +} +#endif diff --git a/Sources/AppKitNavigation/UITransaction.swift b/Sources/AppKitNavigation/UITransaction.swift new file mode 100644 index 0000000000..b4f9535f4e --- /dev/null +++ b/Sources/AppKitNavigation/UITransaction.swift @@ -0,0 +1,53 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import SwiftNavigation + +extension UITransaction { + /// Creates a transaction and assigns its animation property. + /// + /// - Parameter animation: The animation to perform when the current state changes. + public init(animation: AppKitAnimation? = nil) { + self.init() + appKit.animation = animation + } + + /// AppKit-specific data associated with the current state change. + public var appKit: AppKit { + get { self[AppKitKey.self] } + set { self[AppKitKey.self] = newValue } + } + + private enum AppKitKey: UITransactionKey { + static let defaultValue = AppKit() + } + + /// AppKit-specific data associated with a ``UITransaction``. + public struct AppKit: Sendable { + /// The animation, if any, associated with the current state change. + public var animation: AppKitAnimation? + + /// A Boolean value that indicates whether views should disable animations. + public var disablesAnimations = false + + var animationCompletions: [@Sendable (Bool?) -> Void] = [] + + /// Adds a completion to run when the animations created with this transaction are all + /// complete. + /// + /// The completion callback will always be fired exactly one time. + public mutating func addAnimationCompletion( + _ completion: @escaping @Sendable (Bool?) -> Void + ) { + animationCompletions.append(completion) + } + } +} + +private enum AnimationCompletionsKey: UITransactionKey { + static let defaultValue: [@Sendable (Bool?) -> Void] = [] +} + +private enum DisablesAnimationsKey: UITransactionKey { + static let defaultValue = false +} +#endif diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h new file mode 100644 index 0000000000..e1844275f7 --- /dev/null +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -0,0 +1,25 @@ +#if __has_include() +#include + +#if __has_include() && !TARGET_OS_MACCATALYST +@import AppKit; + +NS_ASSUME_NONNULL_BEGIN + +@interface NSViewController (AppKitNavigation) + +@property BOOL hasViewAppeared; +@property (nullable) void (^ onDismiss)(); +@property NSArray *onViewAppear; + +@end + +@interface NSSavePanel (AppKitNavigation) +@property (nullable) void (^ AppKitNavigation_onFinalURL)(NSURL *_Nullable); +@property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); +@end + + +NS_ASSUME_NONNULL_END +#endif +#endif /* if __has_include() */ diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m new file mode 100644 index 0000000000..21f5f9c08b --- /dev/null +++ b/Sources/AppKitNavigationShim/shim.m @@ -0,0 +1,152 @@ +#if __has_include() +#include + +#if __has_include() && !TARGET_OS_MACCATALYST +@import ObjectiveC; +@import AppKit; +#import "shim.h" + +@interface AppKitNavigationShim : NSObject + +@end + +@implementation AppKitNavigationShim + +// NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible +// for state-driven presentation and dismissal of child features. + ++ (void)load { + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(viewDidAppear)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidAppear)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(viewDidDisappear)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidDisappear)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), + class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURLs:")), + class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURLs:)) + ); +} + +@end + +@implementation NSSavePanel (AppKitNavigation) + +- (void)setAppKitNavigation_onFinalURLs:(void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { + objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs), AppKitNavigation_onFinalURLs, OBJC_ASSOCIATION_COPY); +} + +- (void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { + return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs)); +} + +- (void)setAppKitNavigation_onFinalURL:(void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { + objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURL), AppKitNavigation_onFinalURL, OBJC_ASSOCIATION_COPY); +} + +- (void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { + return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURL)); +} + +- (void)AppKitNavigation_setFinalURL:(nullable NSURL *)url { + [self AppKitNavigation_setFinalURL:url]; + if (self.AppKitNavigation_onFinalURL) { + self.AppKitNavigation_onFinalURL(url); + } +} + +- (void)AppKitNavigation_setFinalURLs:(NSArray *)urls { + [self AppKitNavigation_setFinalURLs:urls]; + if (self.AppKitNavigation_onFinalURLs) { + self.AppKitNavigation_onFinalURLs(urls); + } +} + +@end + +static void *hasViewAppearedKey = &hasViewAppearedKey; +static void *onDismissKey = &onDismissKey; +static void *onViewAppearKey = &onViewAppearKey; + +@implementation NSViewController (AppKitNavigation) + +- (void)AppKitNavigation_viewDidAppear { + [self AppKitNavigation_viewDidAppear]; + + if (self.hasViewAppeared) { + return; + } + + self.hasViewAppeared = YES; + + for (void (^work)() in self.onViewAppear) { + work(); + } + + self.onViewAppear = @[]; +} + +- (void)setBeingDismissed:(BOOL)beingDismissed { + objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); +} + +- (BOOL)isBeingDismissed { + return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; +} + +- (void)AppKitNavigation_viewDidDisappear { + [self AppKitNavigation_viewDidDisappear]; + + if ((self.isBeingDismissed) && self.onDismiss != NULL) { + self.onDismiss(); + self.onDismiss = nil; + [self setBeingDismissed:NO]; + } +} + +- (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { + [self AppKitNavigation_dismissViewController:sender]; + [self setBeingDismissed:YES]; +} + +- (BOOL)hasViewAppeared { + return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; +} + +- (void)setHasViewAppeared:(BOOL)hasViewAppeared { + objc_setAssociatedObject( + self, hasViewAppearedKey, @(hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC + ); +} + +- (void (^)())onDismiss { + return objc_getAssociatedObject(self, onDismissKey); +} + +- (void)setOnDismiss:(void (^)())onDismiss { + objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +- (NSMutableArray *)onViewAppear { + id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); + + return onViewAppear == nil ? @[] : onViewAppear; +} + +- (void)setOnViewAppear:(NSMutableArray *)onViewAppear { + objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +@end +#endif /* if __has_include() && !TARGET_OS_MACCATALYST */ +#endif /* if __has_include() */ From 0c61b636b616e3fa186c7f42627add5cf1e8d0be Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Tue, 20 Aug 2024 20:39:14 +0800 Subject: [PATCH 016/141] Remove unused code --- Package.swift | 6 - Package@swift-6.0.swift | 6 - .../AppKitNavigation/AppKitAnimation.swift | 22 ---- .../Internal/AssociatedKeys.swift | 36 ------ .../Internal/ToOptionalUnit.swift | 12 -- Sources/AppKitNavigation/Observe.swift | 108 ------------------ Sources/AppKitNavigation/UIBinding.swift | 4 - Sources/AppKitNavigation/UITransaction.swift | 11 -- .../Internal/AssumeIsolated.swift | 7 +- .../Internal/ErrorMechanism.swift | 9 +- .../Internal/ToOptionalUnit.swift | 12 ++ .../Internal/AssumeIsolated.swift | 30 ----- .../Internal/ErrorMechanism.swift | 20 ---- .../Internal/ToOptionalUnit.swift | 12 -- 14 files changed, 17 insertions(+), 278 deletions(-) delete mode 100644 Sources/AppKitNavigation/Internal/AssociatedKeys.swift delete mode 100644 Sources/AppKitNavigation/Internal/ToOptionalUnit.swift rename Sources/{AppKitNavigation => SwiftNavigation}/Internal/AssumeIsolated.swift (88%) rename Sources/{AppKitNavigation => SwiftNavigation}/Internal/ErrorMechanism.swift (55%) create mode 100644 Sources/SwiftNavigation/Internal/ToOptionalUnit.swift delete mode 100644 Sources/UIKitNavigation/Internal/AssumeIsolated.swift delete mode 100644 Sources/UIKitNavigation/Internal/ErrorMechanism.swift delete mode 100644 Sources/UIKitNavigation/Internal/ToOptionalUnit.swift diff --git a/Package.swift b/Package.swift index fc20ea17dc..3ca03ba03e 100644 --- a/Package.swift +++ b/Package.swift @@ -35,7 +35,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), - .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0"), ], targets: [ .target( @@ -82,14 +81,9 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "AppKitNavigationShim", .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), - .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), - .target( - name: "AppKitNavigationShim" - ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index a97be3d08e..7d316472db 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -35,7 +35,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), - .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.0.0"), ], targets: [ .target( @@ -82,14 +81,9 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "AppKitNavigationShim", .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), - .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), - .target( - name: "AppKitNavigationShim" - ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 0d8230c8fb..e2c8199a00 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -7,14 +7,6 @@ import SwiftUI import SwiftNavigation -/// Executes a closure with the specified animation and returns the result. -/// -/// - Parameters: -/// - animation: An animation, set in the ``UITransaction/appKit`` property of the thread's -/// current transaction. -/// - body: A closure to execute. -/// - completion: A completion to run when the animation is complete. -/// - Returns: The result of executing the closure with the specified animation. @MainActor public func withAppKitAnimation( _ animation: AppKitAnimation? = .default, @@ -29,8 +21,6 @@ public func withAppKitAnimation( return try withUITransaction(transaction, body) } -/// The way a view changes over time to create a smooth visual transition from one state to -/// another. public struct AppKitAnimation: Hashable, Sendable { fileprivate let framework: Framework @@ -71,17 +61,6 @@ public struct AppKitAnimation: Hashable, Sendable { } extension AppKitAnimation { - /// Performs am animation using a timing curve corresponding to the motion of a physical spring. - /// - /// A value description of - /// `UIView.animate(withDuration:delay:dampingRatio:velocity:options:animations:completion:)` - /// that can be used with ``withAppKitAnimation(_:_:completion:)``. - /// - /// - Parameters: - /// - duration: The total duration of the animations, measured in seconds. If you specify a - /// negative value or `0`, the changes are made without animating them. - /// - Returns: An animation using a timing curve corresponding to the motion of a physical - /// spring. public static func animate( withDuration duration: TimeInterval = 0.25 ) -> Self { @@ -94,7 +73,6 @@ extension AppKitAnimation { ) } - /// A default animation instance. public static var `default`: Self { return .animate() } diff --git a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift deleted file mode 100644 index 1df9f50edc..0000000000 --- a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift +++ /dev/null @@ -1,36 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -struct AssociatedKeys { - var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] - - mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { - let key = AnyHashableMetatype(type) - if let associatedKey = keys[key] { - return associatedKey - } else { - let associatedKey = malloc(1)! - keys[key] = associatedKey - return associatedKey - } - } -} - -struct AnyHashableMetatype: Hashable { - static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { - return lhs.base == rhs.base - } - - let base: Any.Type - - init(_ base: Any.Type) { - self.base = base - } - - func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(base)) - } -} - -#endif diff --git a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift deleted file mode 100644 index a11cfaaf1d..0000000000 --- a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift +++ /dev/null @@ -1,12 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -extension Bool { - struct Unit: Hashable, Identifiable { - var id: Unit { self } - } - - var toOptionalUnit: Unit? { - get { self ? Unit() : nil } - set { self = newValue != nil } - } -} -#endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift index 8032874494..6e334545ce 100644 --- a/Sources/AppKitNavigation/Observe.swift +++ b/Sources/AppKitNavigation/Observe.swift @@ -4,119 +4,11 @@ import AppKit @MainActor extension NSObject { - /// Observe access to properties of an observable (or perceptible) object. - /// - /// This tool allows you to set up an observation loop so that you can access fields from an - /// observable model in order to populate your view, and also automatically track changes to - /// any accessed fields so that the view is always up-to-date. - /// - /// It is most useful when dealing with non-SwiftUI views, such as AppKit views and controller. - /// You can invoke the ``observe(_:)`` method a single time in the `viewDidLoad` and update all - /// the view elements: - /// - /// ```swift - /// override func viewDidLoad() { - /// super.viewDidLoad() - /// - /// let countLabel = NSTextField(labelWithString: "") - /// let incrementButton = NSButton { [weak self] _ in - /// self?.model.incrementButtonTapped() - /// } - /// - /// observe { [weak self] in - /// guard let self - /// else { return } - /// - /// countLabel.stringValue = "\(model.count)" - /// } - /// } - /// ``` - /// - /// This closure is immediately called, allowing you to set the initial state of your UI - /// components from the feature's state. And if the `count` property in the feature's state is - /// ever mutated, this trailing closure will be called again, allowing us to update the view - /// again. - /// - /// Generally speaking you can usually have a single ``observe(_:)`` in the entry point of your - /// view, such as `viewDidLoad` for `NSViewController`. This works even if you have many UI - /// components to update: - /// - /// ```swift - /// override func viewDidLoad() { - /// super.viewDidLoad() - /// - /// observe { [weak self] in - /// guard let self - /// else { return } - /// - /// countLabel.isHidden = model.isObservingCount - /// if !countLabel.isHidden { - /// countLabel.stringValue = "\(model.count)" - /// } - /// factLabel.stringValue = model.fact - /// } - /// } - /// ``` - /// - /// This does mean that you may execute the line `factLabel.text = model.fact` even when - /// something unrelated changes, such as `store.model`, but that is typically OK for simple - /// properties of UI components. It is not a performance problem to repeatedly set the `text` of - /// a label or the `isHidden` of a button. - /// - /// However, if there is heavy work you need to perform when state changes, then it is best to - /// put that in its own ``observe(_:)``. For example, if you needed to reload a table view or - /// collection view when a collection changes: - /// - /// ```swift - /// override func viewDidLoad() { - /// super.viewDidLoad() - /// - /// observe { [weak self] in - /// guard let self - /// else { return } - /// - /// dataSource = model.items - /// tableView.reloadData() - /// } - /// } - /// ``` - /// - /// ## Cancellation - /// - /// The method returns an ``ObservationToken`` that can be used to cancel observation. For - /// example, if you only want to observe while a view controller is visible, you can start - /// observation in the `viewWillAppear` and then cancel observation in the `viewWillDisappear`: - /// - /// ```swift - /// var observation: ObservationToken? - /// - /// func viewWillAppear() { - /// super.viewWillAppear() - /// observation = observe { [weak self] in - /// // ... - /// } - /// } - /// func viewWillDisappear() { - /// super.viewWillDisappear() - /// observation?.cancel() - /// } - /// ``` - /// - /// - Parameter apply: A closure that contains properties to track and is invoked when the value - /// of a property changes. - /// - Returns: A cancellation token. @discardableResult public func observe(_ apply: @escaping @MainActor @Sendable () -> Void) -> ObservationToken { observe { _ in apply() } } - /// Observe access to properties of an observable (or perceptible) object. - /// - /// A version of ``observe(_:)`` that is passed the current transaction. - /// - /// - Parameter apply: A closure that contains properties to track and is invoked when the value - /// of a property changes. - /// - Returns: A cancellation token. @discardableResult public func observe( _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void diff --git a/Sources/AppKitNavigation/UIBinding.swift b/Sources/AppKitNavigation/UIBinding.swift index ea3499dec7..e69009dfed 100644 --- a/Sources/AppKitNavigation/UIBinding.swift +++ b/Sources/AppKitNavigation/UIBinding.swift @@ -2,10 +2,6 @@ import SwiftNavigation extension UIBinding { - /// Specifies an animation to perform when the binding value changes. - /// - /// - Parameter animation: An animation sequence performed when the binding value changes. - /// - Returns: A new binding. public func animation(_ animation: AppKitAnimation? = .default) -> Self { var binding = self binding.transaction.appKit.animation = animation diff --git a/Sources/AppKitNavigation/UITransaction.swift b/Sources/AppKitNavigation/UITransaction.swift index b4f9535f4e..01b798797c 100644 --- a/Sources/AppKitNavigation/UITransaction.swift +++ b/Sources/AppKitNavigation/UITransaction.swift @@ -3,15 +3,11 @@ import SwiftNavigation extension UITransaction { - /// Creates a transaction and assigns its animation property. - /// - /// - Parameter animation: The animation to perform when the current state changes. public init(animation: AppKitAnimation? = nil) { self.init() appKit.animation = animation } - /// AppKit-specific data associated with the current state change. public var appKit: AppKit { get { self[AppKitKey.self] } set { self[AppKitKey.self] = newValue } @@ -21,20 +17,13 @@ extension UITransaction { static let defaultValue = AppKit() } - /// AppKit-specific data associated with a ``UITransaction``. public struct AppKit: Sendable { - /// The animation, if any, associated with the current state change. public var animation: AppKitAnimation? - /// A Boolean value that indicates whether views should disable animations. public var disablesAnimations = false var animationCompletions: [@Sendable (Bool?) -> Void] = [] - /// Adds a completion to run when the animations created with this transaction are all - /// complete. - /// - /// The completion callback will always be fired exactly one time. public mutating func addAnimationCompletion( _ completion: @escaping @Sendable (Bool?) -> Void ) { diff --git a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift b/Sources/SwiftNavigation/Internal/AssumeIsolated.swift similarity index 88% rename from Sources/AppKitNavigation/Internal/AssumeIsolated.swift rename to Sources/SwiftNavigation/Internal/AssumeIsolated.swift index 93f1c40098..97054027e7 100644 --- a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift +++ b/Sources/SwiftNavigation/Internal/AssumeIsolated.swift @@ -1,10 +1,8 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - import Foundation extension MainActor { // NB: This functionality was not back-deployed in Swift 5.9 - static func _assumeIsolated( + package static func _assumeIsolated( _ operation: @MainActor () throws -> T, file: StaticString = #fileID, line: UInt = #line @@ -30,6 +28,3 @@ extension MainActor { #endif } } - - -#endif diff --git a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift b/Sources/SwiftNavigation/Internal/ErrorMechanism.swift similarity index 55% rename from Sources/AppKitNavigation/Internal/ErrorMechanism.swift rename to Sources/SwiftNavigation/Internal/ErrorMechanism.swift index 1ec4c47b0a..36cbdd7bc4 100644 --- a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift +++ b/Sources/SwiftNavigation/Internal/ErrorMechanism.swift @@ -1,20 +1,19 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) @rethrows -protocol _ErrorMechanism { +package protocol _ErrorMechanism { associatedtype Output func get() throws -> Output } extension _ErrorMechanism { - func _rethrowError() rethrows -> Never { + package func _rethrowError() rethrows -> Never { _ = try _rethrowGet() fatalError() } - func _rethrowGet() rethrows -> Output { + package func _rethrowGet() rethrows -> Output { return try get() } } extension Result: _ErrorMechanism {} -#endif + diff --git a/Sources/SwiftNavigation/Internal/ToOptionalUnit.swift b/Sources/SwiftNavigation/Internal/ToOptionalUnit.swift new file mode 100644 index 0000000000..46fa0d119c --- /dev/null +++ b/Sources/SwiftNavigation/Internal/ToOptionalUnit.swift @@ -0,0 +1,12 @@ +extension Bool { + package struct Unit: Hashable, Identifiable { + package var id: Unit { self } + + package init() {} + } + + package var toOptionalUnit: Unit? { + get { self ? Unit() : nil } + set { self = newValue != nil } + } +} diff --git a/Sources/UIKitNavigation/Internal/AssumeIsolated.swift b/Sources/UIKitNavigation/Internal/AssumeIsolated.swift deleted file mode 100644 index fea107e3ae..0000000000 --- a/Sources/UIKitNavigation/Internal/AssumeIsolated.swift +++ /dev/null @@ -1,30 +0,0 @@ -import Foundation - -extension MainActor { - // NB: This functionality was not back-deployed in Swift 5.9 - static func _assumeIsolated( - _ operation: @MainActor () throws -> T, - file: StaticString = #fileID, - line: UInt = #line - ) rethrows -> T { - #if swift(<5.10) - typealias YesActor = @MainActor () throws -> T - typealias NoActor = () throws -> T - - guard Thread.isMainThread else { - fatalError( - "Incorrect actor executor assumption; Expected same executor as \(self).", - file: file, - line: line - ) - } - - return try withoutActuallyEscaping(operation) { (_ fn: @escaping YesActor) throws -> T in - let rawFn = unsafeBitCast(fn, to: NoActor.self) - return try rawFn() - } - #else - return try assumeIsolated(operation, file: file, line: line) - #endif - } -} diff --git a/Sources/UIKitNavigation/Internal/ErrorMechanism.swift b/Sources/UIKitNavigation/Internal/ErrorMechanism.swift deleted file mode 100644 index 18644daeba..0000000000 --- a/Sources/UIKitNavigation/Internal/ErrorMechanism.swift +++ /dev/null @@ -1,20 +0,0 @@ -#if canImport(UIKit) - @rethrows - protocol _ErrorMechanism { - associatedtype Output - func get() throws -> Output - } - - extension _ErrorMechanism { - func _rethrowError() rethrows -> Never { - _ = try _rethrowGet() - fatalError() - } - - func _rethrowGet() rethrows -> Output { - return try get() - } - } - - extension Result: _ErrorMechanism {} -#endif diff --git a/Sources/UIKitNavigation/Internal/ToOptionalUnit.swift b/Sources/UIKitNavigation/Internal/ToOptionalUnit.swift deleted file mode 100644 index ed30e639d9..0000000000 --- a/Sources/UIKitNavigation/Internal/ToOptionalUnit.swift +++ /dev/null @@ -1,12 +0,0 @@ -#if canImport(UIKit) - extension Bool { - struct Unit: Hashable, Identifiable { - var id: Unit { self } - } - - var toOptionalUnit: Unit? { - get { self ? Unit() : nil } - set { self = newValue != nil } - } - } -#endif From c2bdb0dde8a19d4cc337cc2002a1945d282ade93 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Wed, 21 Aug 2024 01:38:40 +0800 Subject: [PATCH 017/141] Remove unused code --- Sources/AppKitNavigationShim/include/shim.h | 25 ---- Sources/AppKitNavigationShim/shim.m | 152 -------------------- 2 files changed, 177 deletions(-) delete mode 100644 Sources/AppKitNavigationShim/include/shim.h delete mode 100644 Sources/AppKitNavigationShim/shim.m diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h deleted file mode 100644 index e1844275f7..0000000000 --- a/Sources/AppKitNavigationShim/include/shim.h +++ /dev/null @@ -1,25 +0,0 @@ -#if __has_include() -#include - -#if __has_include() && !TARGET_OS_MACCATALYST -@import AppKit; - -NS_ASSUME_NONNULL_BEGIN - -@interface NSViewController (AppKitNavigation) - -@property BOOL hasViewAppeared; -@property (nullable) void (^ onDismiss)(); -@property NSArray *onViewAppear; - -@end - -@interface NSSavePanel (AppKitNavigation) -@property (nullable) void (^ AppKitNavigation_onFinalURL)(NSURL *_Nullable); -@property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); -@end - - -NS_ASSUME_NONNULL_END -#endif -#endif /* if __has_include() */ diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m deleted file mode 100644 index 21f5f9c08b..0000000000 --- a/Sources/AppKitNavigationShim/shim.m +++ /dev/null @@ -1,152 +0,0 @@ -#if __has_include() -#include - -#if __has_include() && !TARGET_OS_MACCATALYST -@import ObjectiveC; -@import AppKit; -#import "shim.h" - -@interface AppKitNavigationShim : NSObject - -@end - -@implementation AppKitNavigationShim - -// NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible -// for state-driven presentation and dismissal of child features. - -+ (void)load { - method_exchangeImplementations( - class_getInstanceMethod(NSViewController.class, @selector(viewDidAppear)), - class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidAppear)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSViewController.class, @selector(viewDidDisappear)), - class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidDisappear)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), - class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), - class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURLs:")), - class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURLs:)) - ); -} - -@end - -@implementation NSSavePanel (AppKitNavigation) - -- (void)setAppKitNavigation_onFinalURLs:(void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { - objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs), AppKitNavigation_onFinalURLs, OBJC_ASSOCIATION_COPY); -} - -- (void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { - return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs)); -} - -- (void)setAppKitNavigation_onFinalURL:(void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { - objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURL), AppKitNavigation_onFinalURL, OBJC_ASSOCIATION_COPY); -} - -- (void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { - return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURL)); -} - -- (void)AppKitNavigation_setFinalURL:(nullable NSURL *)url { - [self AppKitNavigation_setFinalURL:url]; - if (self.AppKitNavigation_onFinalURL) { - self.AppKitNavigation_onFinalURL(url); - } -} - -- (void)AppKitNavigation_setFinalURLs:(NSArray *)urls { - [self AppKitNavigation_setFinalURLs:urls]; - if (self.AppKitNavigation_onFinalURLs) { - self.AppKitNavigation_onFinalURLs(urls); - } -} - -@end - -static void *hasViewAppearedKey = &hasViewAppearedKey; -static void *onDismissKey = &onDismissKey; -static void *onViewAppearKey = &onViewAppearKey; - -@implementation NSViewController (AppKitNavigation) - -- (void)AppKitNavigation_viewDidAppear { - [self AppKitNavigation_viewDidAppear]; - - if (self.hasViewAppeared) { - return; - } - - self.hasViewAppeared = YES; - - for (void (^work)() in self.onViewAppear) { - work(); - } - - self.onViewAppear = @[]; -} - -- (void)setBeingDismissed:(BOOL)beingDismissed { - objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); -} - -- (BOOL)isBeingDismissed { - return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; -} - -- (void)AppKitNavigation_viewDidDisappear { - [self AppKitNavigation_viewDidDisappear]; - - if ((self.isBeingDismissed) && self.onDismiss != NULL) { - self.onDismiss(); - self.onDismiss = nil; - [self setBeingDismissed:NO]; - } -} - -- (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { - [self AppKitNavigation_dismissViewController:sender]; - [self setBeingDismissed:YES]; -} - -- (BOOL)hasViewAppeared { - return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; -} - -- (void)setHasViewAppeared:(BOOL)hasViewAppeared { - objc_setAssociatedObject( - self, hasViewAppearedKey, @(hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC - ); -} - -- (void (^)())onDismiss { - return objc_getAssociatedObject(self, onDismissKey); -} - -- (void)setOnDismiss:(void (^)())onDismiss { - objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); -} - -- (NSMutableArray *)onViewAppear { - id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); - - return onViewAppear == nil ? @[] : onViewAppear; -} - -- (void)setOnViewAppear:(NSMutableArray *)onViewAppear { - objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); -} - -@end -#endif /* if __has_include() && !TARGET_OS_MACCATALYST */ -#endif /* if __has_include() */ From 8e5e4e610303017e0707fbd8791a4c5896683b7d Mon Sep 17 00:00:00 2001 From: Stephen Celis Date: Thu, 22 Aug 2024 16:32:18 -0700 Subject: [PATCH 018/141] Integrate custom transaction --- Sources/AppKitNavigation/Observe.swift | 73 ------------------- Sources/AppKitNavigation/UITransaction.swift | 77 ++++++++++++++------ 2 files changed, 55 insertions(+), 95 deletions(-) delete mode 100644 Sources/AppKitNavigation/Observe.swift diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift deleted file mode 100644 index 6e334545ce..0000000000 --- a/Sources/AppKitNavigation/Observe.swift +++ /dev/null @@ -1,73 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -@_spi(Internals) import SwiftNavigation -import AppKit - -@MainActor -extension NSObject { - @discardableResult - public func observe(_ apply: @escaping @MainActor @Sendable () -> Void) -> ObservationToken { - observe { _ in apply() } - } - - @discardableResult - public func observe( - _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void - ) -> ObservationToken { - let token = SwiftNavigation.observe { transaction in - MainActor._assumeIsolated { - withUITransaction(transaction) { - if transaction.appKit.disablesAnimations { - NSView.performWithoutAnimation { apply(transaction) } - for completion in transaction.appKit.animationCompletions { - completion(true) - } - } else if let animation = transaction.appKit.animation { - return animation.perform( - { apply(transaction) }, - completion: transaction.appKit.animationCompletions.isEmpty - ? nil - : { - for completion in transaction.appKit.animationCompletions { - completion($0) - } - } - ) - } else { - apply(transaction) - for completion in transaction.appKit.animationCompletions { - completion(true) - } - } - } - } - } task: { transaction, work in - DispatchQueue.main.async { - withUITransaction(transaction, work) - } - } - tokens.append(token) - return token - } - - fileprivate var tokens: [Any] { - get { - objc_getAssociatedObject(self, Self.tokensKey) as? [Any] ?? [] - } - set { - objc_setAssociatedObject(self, Self.tokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - } - - private static let tokensKey = malloc(1)! -} - -extension NSView { - fileprivate static func performWithoutAnimation(_ block: () -> Void) { - NSAnimationContext.runAnimationGroup { context in - context.allowsImplicitAnimation = false - block() - } - } -} - -#endif diff --git a/Sources/AppKitNavigation/UITransaction.swift b/Sources/AppKitNavigation/UITransaction.swift index 01b798797c..99559dbc48 100644 --- a/Sources/AppKitNavigation/UITransaction.swift +++ b/Sources/AppKitNavigation/UITransaction.swift @@ -1,42 +1,75 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import SwiftNavigation -import SwiftNavigation - -extension UITransaction { + extension UITransaction { public init(animation: AppKitAnimation? = nil) { - self.init() - appKit.animation = animation + self.init() + appKit.animation = animation } public var appKit: AppKit { - get { self[AppKitKey.self] } - set { self[AppKitKey.self] = newValue } + get { self[AppKitKey.self] } + set { self[AppKitKey.self] = newValue } } - private enum AppKitKey: UITransactionKey { - static let defaultValue = AppKit() + private enum AppKitKey: _UICustomTransactionKey { + static let defaultValue = AppKit() + + static func perform( + value: AppKit, + operation: @Sendable () -> Void + ) { + MainActor._assumeIsolated { + if value.disablesAnimations { + NSAnimationContext.runAnimationGroup { context in + context.allowsImplicitAnimation = false + operation() + } + for completion in value.animationCompletions { + completion(true) + } + } else if let animation = value.animation { + return animation.perform( + { operation() }, + completion: value.animationCompletions.isEmpty + ? nil + : { + for completion in value.animationCompletions { + completion($0) + } + } + ) + } else { + operation() + for completion in value.animationCompletions { + completion(true) + } + } + } + } } public struct AppKit: Sendable { - public var animation: AppKitAnimation? + public var animation: AppKitAnimation? - public var disablesAnimations = false + public var disablesAnimations = false - var animationCompletions: [@Sendable (Bool?) -> Void] = [] + var animationCompletions: [@Sendable (Bool?) -> Void] = [] - public mutating func addAnimationCompletion( - _ completion: @escaping @Sendable (Bool?) -> Void - ) { - animationCompletions.append(completion) - } + public mutating func addAnimationCompletion( + _ completion: @escaping @Sendable (Bool?) -> Void + ) { + animationCompletions.append(completion) + } } -} + } -private enum AnimationCompletionsKey: UITransactionKey { + private enum AnimationCompletionsKey: UITransactionKey { static let defaultValue: [@Sendable (Bool?) -> Void] = [] -} + } -private enum DisablesAnimationsKey: UITransactionKey { + private enum DisablesAnimationsKey: UITransactionKey { static let defaultValue = false -} + } #endif From 2b91081b304a729a5c532e43ade481b0a14264ce Mon Sep 17 00:00:00 2001 From: Stephen Celis Date: Thu, 22 Aug 2024 16:43:34 -0700 Subject: [PATCH 019/141] address fatal error --- .../AppKitNavigation/AppKitAnimation.swift | 101 ++++++++++-------- 1 file changed, 58 insertions(+), 43 deletions(-) diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index e2c8199a00..346478c856 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -1,80 +1,95 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit + import AppKit -#if canImport(SwiftUI) -import SwiftUI -#endif + #if canImport(SwiftUI) + import SwiftUI + #endif -import SwiftNavigation + import SwiftNavigation -@MainActor -public func withAppKitAnimation( + @MainActor + public func withAppKitAnimation( _ animation: AppKitAnimation? = .default, _ body: () throws -> Result, completion: (@Sendable (Bool?) -> Void)? = nil -) rethrows -> Result { + ) rethrows -> Result { var transaction = UITransaction() transaction.appKit.animation = animation if let completion { - transaction.appKit.addAnimationCompletion(completion) + transaction.appKit.addAnimationCompletion(completion) } return try withUITransaction(transaction, body) -} + } -public struct AppKitAnimation: Hashable, Sendable { + public struct AppKitAnimation: Hashable, Sendable { fileprivate let framework: Framework @MainActor func perform( - _ body: () throws -> Result, - completion: ((Bool?) -> Void)? = nil + _ body: () throws -> Result, + completion: ((Bool?) -> Void)? = nil ) rethrows -> Result { - switch framework { - case let .swiftUI(animation): - _ = animation - fatalError() - case let .appKit(animation): - var result: Swift.Result? - NSAnimationContext.runAnimationGroup { context in - context.duration = animation.duration - result = Swift.Result(catching: body) - } completionHandler: { - completion?(true) + switch framework { + case let .swiftUI(animation): + var result: Swift.Result? + #if swift(>=6) + if #available(macOS 15, *) { + NSAnimationContext.animate(animation) { + result = Swift.Result(catching: body) + } completion: { + completion?(true) } - return try result!._rethrowGet() + } + #endif + _ = animation + fatalError() + case let .appKit(animation): + var result: Swift.Result? + NSAnimationContext.runAnimationGroup { context in + context.duration = animation.duration + result = Swift.Result(catching: body) + } completionHandler: { + completion?(true) } + return try result!._rethrowGet() + } } fileprivate enum Framework: Hashable, Sendable { - case appKit(AppKit) - case swiftUI(Animation) + case appKit(AppKit) + case swiftUI(Animation) - fileprivate struct AppKit: Hashable, Sendable { - fileprivate var duration: TimeInterval + fileprivate struct AppKit: Hashable, Sendable { + fileprivate var duration: TimeInterval - func hash(into hasher: inout Hasher) { - hasher.combine(duration) - } + func hash(into hasher: inout Hasher) { + hasher.combine(duration) } + } + } + } + + extension AppKitAnimation { + @available(macOS 15, *) + public init(_ animation: Animation) { + self.init(framework: .swiftUI(animation)) } -} -extension AppKitAnimation { public static func animate( - withDuration duration: TimeInterval = 0.25 + withDuration duration: TimeInterval = 0.25 ) -> Self { - Self( - framework: .appKit( - Framework.AppKit( - duration: duration - ) - ) + Self( + framework: .appKit( + Framework.AppKit( + duration: duration + ) ) + ) } public static var `default`: Self { - return .animate() + return .animate() } -} + } #endif From cad947be25bb3b9bede965c2a20089abded9d69f Mon Sep 17 00:00:00 2001 From: Stephen Celis Date: Fri, 23 Aug 2024 08:16:19 -0700 Subject: [PATCH 020/141] Round out animation --- .../AppKitNavigation/AppKitAnimation.swift | 56 ++++++++++++++----- .../SwiftNavigationTests/LifetimeTests.swift | 2 +- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 346478c856..2dab48e14c 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -30,6 +30,18 @@ completion: ((Bool?) -> Void)? = nil ) rethrows -> Result { switch framework { + case let .appKit(animation): + var result: Swift.Result? + NSAnimationContext.runAnimationGroup { context in + context.allowsImplicitAnimation = true + context.duration = animation.duration + context.timingFunction = animation.timingFunction + result = Swift.Result(catching: body) + } completionHandler: { + completion?(true) + } + return try result!._rethrowGet() + case let .swiftUI(animation): var result: Swift.Result? #if swift(>=6) @@ -44,15 +56,6 @@ #endif _ = animation fatalError() - case let .appKit(animation): - var result: Swift.Result? - NSAnimationContext.runAnimationGroup { context in - context.duration = animation.duration - result = Swift.Result(catching: body) - } completionHandler: { - completion?(true) - } - return try result!._rethrowGet() } } @@ -60,8 +63,9 @@ case appKit(AppKit) case swiftUI(Animation) - fileprivate struct AppKit: Hashable, Sendable { + fileprivate struct AppKit: Hashable, @unchecked Sendable { fileprivate var duration: TimeInterval + fileprivate var timingFunction: CAMediaTimingFunction? func hash(into hasher: inout Hasher) { hasher.combine(duration) @@ -77,19 +81,45 @@ } public static func animate( - withDuration duration: TimeInterval = 0.25 + duration: TimeInterval = 0.25, + timingFunction: CAMediaTimingFunction? = nil ) -> Self { Self( framework: .appKit( Framework.AppKit( - duration: duration + duration: duration, + timingFunction: timingFunction ) ) ) } public static var `default`: Self { - return .animate() + .animate() + } + + public static var linear: Self { .linear(duration: 0.25) } + + public static func linear(duration: TimeInterval) -> Self { + .animate(duration: duration, timingFunction: CAMediaTimingFunction(name: .linear)) + } + + public static var easeIn: Self { .easeIn(duration: 0.25) } + + public static func easeIn(duration: TimeInterval) -> Self { + .animate(duration: duration, timingFunction: CAMediaTimingFunction(name: .easeIn)) + } + + public static var easeOut: Self { .easeOut(duration: 0.25) } + + public static func easeOut(duration: TimeInterval) -> Self { + .animate(duration: duration, timingFunction: CAMediaTimingFunction(name: .easeOut)) + } + + public static var easeInOut: Self { .easeInOut(duration: 0.25) } + + public static func easeInOut(duration: TimeInterval) -> Self { + .animate(duration: duration, timingFunction: CAMediaTimingFunction(name: .easeInEaseOut)) } } #endif diff --git a/Tests/SwiftNavigationTests/LifetimeTests.swift b/Tests/SwiftNavigationTests/LifetimeTests.swift index 66569ba62b..6c68de4637 100644 --- a/Tests/SwiftNavigationTests/LifetimeTests.swift +++ b/Tests/SwiftNavigationTests/LifetimeTests.swift @@ -29,7 +29,7 @@ @Perceptible @MainActor - class Model { + private class Model { var count = 0 } #endif From e863c54496957d76fb1dbae5a355fb3632aa9364 Mon Sep 17 00:00:00 2001 From: Brandon Williams <135203+mbrandonw@users.noreply.github.com> Date: Fri, 23 Aug 2024 14:57:16 -0400 Subject: [PATCH 021/141] Update Package.swift --- Package.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Package.swift b/Package.swift index 8a8b002389..f3b38e8535 100644 --- a/Package.swift +++ b/Package.swift @@ -83,7 +83,6 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), ] ), .testTarget( From 00ed18a322665a08ca85a47955d23e841a840022 Mon Sep 17 00:00:00 2001 From: Brandon Williams <135203+mbrandonw@users.noreply.github.com> Date: Fri, 23 Aug 2024 14:57:32 -0400 Subject: [PATCH 022/141] Update Package@swift-6.0.swift --- Package@swift-6.0.swift | 1 - 1 file changed, 1 deletion(-) diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 9f37971b8a..2edac05b6d 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -83,7 +83,6 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - .product(name: "ConcurrencyExtras", package: "swift-concurrency-extras"), ] ), .testTarget( From df6eda79c2932762f2e01e668efac142975e88cd Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Sun, 25 Aug 2024 01:16:25 +0800 Subject: [PATCH 023/141] Support AppKit Navigation --- Package.swift | 4 + Package@swift-6.0.swift | 4 + .../AppKitNavigation/AppKitAnimation.swift | 2 +- .../Internal/AssociatedKeys.swift | 36 ++++ .../AppKitNavigation/Navigation/Modal.swift | 200 ++++++++++++++++++ .../Navigation/ModalContent.swift | 35 +++ .../Navigation/ModalSessionContent.swift | 22 ++ .../Navigation/ModalWindowsObserver.swift | 33 +++ .../Navigation/NavigationContent.swift | 38 ++++ .../Navigation/NavigationObserver.swift | 88 ++++++++ .../Navigation/Presentation.swift | 175 +++++++++++++++ .../Navigation/PresentationContent.swift | 41 ++++ .../AppKitNavigation/Navigation/Sheet.swift | 132 ++++++++++++ .../Navigation/SheetContent.swift | 60 ++++++ Sources/AppKitNavigationShim/include/shim.h | 19 ++ Sources/AppKitNavigationShim/shim.m | 110 ++++++++++ 16 files changed, 998 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Internal/AssociatedKeys.swift create mode 100644 Sources/AppKitNavigation/Navigation/Modal.swift create mode 100644 Sources/AppKitNavigation/Navigation/ModalContent.swift create mode 100644 Sources/AppKitNavigation/Navigation/ModalSessionContent.swift create mode 100644 Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift create mode 100644 Sources/AppKitNavigation/Navigation/NavigationContent.swift create mode 100644 Sources/AppKitNavigation/Navigation/NavigationObserver.swift create mode 100644 Sources/AppKitNavigation/Navigation/Presentation.swift create mode 100644 Sources/AppKitNavigation/Navigation/PresentationContent.swift create mode 100644 Sources/AppKitNavigation/Navigation/Sheet.swift create mode 100644 Sources/AppKitNavigation/Navigation/SheetContent.swift create mode 100644 Sources/AppKitNavigationShim/include/shim.h create mode 100644 Sources/AppKitNavigationShim/shim.m diff --git a/Package.swift b/Package.swift index f3b38e8535..0210bad713 100644 --- a/Package.swift +++ b/Package.swift @@ -83,8 +83,12 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", + "AppKitNavigationShim", ] ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 2edac05b6d..1859da950d 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -83,8 +83,12 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", + "AppKitNavigationShim", ] ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 2dab48e14c..b0e8a2cd85 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -43,8 +43,8 @@ return try result!._rethrowGet() case let .swiftUI(animation): - var result: Swift.Result? #if swift(>=6) + var result: Swift.Result? if #available(macOS 15, *) { NSAnimationContext.animate(animation) { result = Swift.Result(catching: body) diff --git a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift new file mode 100644 index 0000000000..1df9f50edc --- /dev/null +++ b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift @@ -0,0 +1,36 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +struct AssociatedKeys { + var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] + + mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { + let key = AnyHashableMetatype(type) + if let associatedKey = keys[key] { + return associatedKey + } else { + let associatedKey = malloc(1)! + keys[key] = associatedKey + return associatedKey + } + } +} + +struct AnyHashableMetatype: Hashable { + static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { + return lhs.base == rhs.base + } + + let base: Any.Type + + init(_ base: Any.Type) { + self.base = base + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(base)) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift new file mode 100644 index 0000000000..14681eda9e --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -0,0 +1,200 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +private var modalObserverKeys = AssociatedKeys() + +private typealias ModalObserver = NavigationObserver + +@MainActor +extension NSObject { + @discardableResult + public func modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + public func modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + modal(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + modalSession(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + modal(item: item, id: id) { $item in + content($item) + } beginModal: { modalContent, _ in + if NSApplication.shared.modalWindow != nil { + NSApplication.shared.stopModal() + onDismiss?() + DispatchQueue.main.async { + ModalWindowsObserver.shared.observeWindow(modalContent.window) + modalContent.appKitNavigationRunModal() + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil + } + + } else { + DispatchQueue.main.async { + ModalWindowsObserver.shared.observeWindow(modalContent.window) + modalContent.appKitNavigationRunModal() + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil + } + } + } endModal: { _, _ in + NSApplication.shared.stopModal() + onDismiss?() + } + } + + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + modal(item: item, id: id) { $item in + content($item) + } beginModal: { modalContent, _ in + if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] { + NSApplication.shared.endModalSession(modalSession) + modaledWindow.window.close() + onDismiss?() + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) + } + + } else { + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) + } + } + } endModal: { modalContent, _ in + if let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] { + NSApplication.shared.endModalSession(modalSession) + modalContent.window.close() + onDismiss?() + } + } + } + + private func modal( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> Content, + beginModal: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void, + endModal: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let modalObserver: ModalObserver = modalObserver() + return modalObserver.observe( + item: item, + id: { $0[keyPath: id] }, + content: content, + begin: beginModal, + end: endModal + ) + } + + private func modalObserver() -> ModalObserver { + if let observer = objc_getAssociatedObject(self, modalObserverKeys.key(of: Content.self)) as? ModalObserver { + return observer + } else { + let observer = ModalObserver(owner: self) + objc_setAssociatedObject(self, modalObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer + } + } +} + +extension Navigated where Content: ModalContent { + func clearup() { + NSApplication.shared.stopModal() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift new file mode 100644 index 0000000000..00772647f2 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -0,0 +1,35 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol ModalContent: NavigationContent { + @discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse + var window: NSWindow { get } +} + +extension NSWindow: ModalContent { + public var window: NSWindow { self } + + public func appKitNavigationRunModal() -> NSApplication.ModalResponse { + __appKitNavigationRunModal() + } + + @objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse { + NSApplication.shared.runModal(for: self) + } +} + +extension NSSavePanel { + override func __appKitNavigationRunModal() -> NSApplication.ModalResponse { + runModal() + } +} + +extension NSAlert: ModalContent { + public func appKitNavigationRunModal() -> NSApplication.ModalResponse { + runModal() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift new file mode 100644 index 0000000000..9132638de7 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift @@ -0,0 +1,22 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol ModalSessionContent: ModalContent { + func appKitNavigationBeginModalSession() -> NSApplication.ModalSession +} + +extension NSWindow: ModalSessionContent { + + public func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { + __appKitNavigationBeginModalSession() + } + + @objc func __appKitNavigationBeginModalSession() -> NSApplication.ModalSession { + let modalSession = NSApplication.shared.beginModalSession(for: self) + return modalSession + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift new file mode 100644 index 0000000000..bc63b33443 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift @@ -0,0 +1,33 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import Combine + +@MainActor +class ModalWindowsObserver: NSObject { + static let shared = ModalWindowsObserver() + + var windowsCancellable: [NSWindow: AnyCancellable] = [:] + + var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:] + + func observeWindow(_ window: NSWindow, modalSession: NSApplication.ModalSession? = nil) { + if let modalSession { + modalSessionByWindow[window] = modalSession + } + windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) + .sink { [weak self] _ in + guard let self else { return } + if let modalSession = modalSessionByWindow[window] { + NSApplication.shared.endModalSession(modalSession) + } else if NSApplication.shared.modalWindow === window { + NSApplication.shared.stopModal() + } + modalSessionByWindow.removeValue(forKey: window) + windowsCancellable[window]?.cancel() + windowsCancellable.removeValue(forKey: window) + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift new file mode 100644 index 0000000000..762032cf09 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -0,0 +1,38 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import Foundation + +@MainActor +public protocol NavigationContent: AnyObject { + var onBeginNavigation: (() -> Void)? { set get } + var onEndNavigation: (() -> Void)? { set get } +} + +@MainActor +private var onBeginNavigationKeys = AssociatedKeys() + +@MainActor +private var onEndNavigationKeys = AssociatedKeys() + +extension NavigationContent { + public var onBeginNavigation: (() -> Void)? { + set { + objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + get { + objc_getAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self)) as? () -> Void + } + } + + public var onEndNavigation: (() -> Void)? { + set { + objc_setAssociatedObject(self, onEndNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + get { + objc_getAssociatedObject(self, onEndNavigationKeys.key(of: Self.self)) as? () -> Void + } + } +} + + +#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift new file mode 100644 index 0000000000..488cf6b4b9 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift @@ -0,0 +1,88 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import Foundation +import SwiftNavigation + +@MainActor +class NavigationObserver: NSObject { + private var navigatedByID: [UIBindingIdentifier: Navigated] = [:] + + unowned let owner: Owner + + init(owner: Owner) { + self.owner = owner + super.init() + } + + func observe( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> Content, + begin: @escaping ( + _ content: Content, + _ transaction: UITransaction + ) -> Void, + end: @escaping ( + _ content: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let navigated = navigatedByID[key] { + guard let navigationID = navigated.id, + navigationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let content = content(unwrappedItem) + let onEndNavigation = { [navigationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + navigationID == id(wrappedValue) { + item.wrappedValue = nil + } + } + content.onEndNavigation = onEndNavigation + + self.navigatedByID[key] = Navigated(content, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + begin(content, transaction) + } + } + commitWork(work) + } else if let navigated = navigatedByID[key] { + if let content = navigated.content { + end(content, transaction) + } + self.navigatedByID[key] = nil + } + } + } + + func commitWork(_ work: @escaping () -> Void) { + work() + } +} + +@MainActor +class Navigated { + weak var content: Content? + let id: AnyHashable? + func clearup() {} + deinit { + MainActor._assumeIsolated { + clearup() + } + } + + required init(_ content: Content, id: AnyHashable?) { + self.content = content + self.id = id + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift new file mode 100644 index 0000000000..5b2c0662ca --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -0,0 +1,175 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import SwiftNavigation +import AppKit +import AppKitNavigationShim + +@MainActor +private var presentationObserverKeys = AssociatedKeys() + +class PresentationObserver: NavigationObserver { + override func commitWork(_ work: @escaping () -> Void) { + if owner.hasViewAppeared { + work() + } else { + owner.onViewAppear.append(work) + } + } +} + +extension NSViewController { + @discardableResult + public func present( + isPresented: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + public func present( + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + present(item: item, id: id, style: style, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + destination(item: item, id: id) { $item in + content($item) + } present: { [weak self] child, transaction in + guard let self else { return } + if let presentedViewController = presentedViewControllers?.first { + self.dismiss(presentedViewController) + onDismiss?() + child.presented(from: self, style: style) + } else { + child.presented(from: self, style: style) + } + } dismiss: { [weak self] child, transaction in + guard let self else { return } + child.dismiss(from: self) + onDismiss?() + } + } + + @discardableResult + public func destination( + isPresented: UIBinding, + content: @escaping () -> Content, + present: @escaping (Content, UITransaction) -> Void, + dismiss: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + destination( + item: isPresented.toOptionalUnit, + content: { _ in content() }, + present: present, + dismiss: dismiss + ) + } + + @discardableResult + public func destination( + item: UIBinding, + content: @escaping (UIBinding) -> Content, + present: @escaping (Content, UITransaction) -> Void, + dismiss: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let presentationObserver: PresentationObserver = presentationObserver() + return presentationObserver.observe( + item: item, + id: { _ in nil }, + content: content, + begin: present, + end: dismiss + ) + } + + @discardableResult + public func destination( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> Content, + present: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let presentationObserver: PresentationObserver = presentationObserver() + return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) + } + + private func presentationObserver() -> PresentationObserver { + if let observer = objc_getAssociatedObject(self, presentationObserverKeys.key(of: Content.self)) as? PresentationObserver { + return observer + } else { + let observer = PresentationObserver(owner: self) + objc_setAssociatedObject(self, presentationObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer + } + } +} + +extension NavigationContent where Self: NSViewController { + var _onEndNavigation: (() -> Void)? { + set { + onDismiss = newValue + } + get { + onDismiss + } + } +} + +extension Navigated where Content: NSViewController { + func clearup() { + content?.dismiss(nil) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift new file mode 100644 index 0000000000..eba08ad600 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/PresentationContent.swift @@ -0,0 +1,41 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol PresentationContent: NavigationContent { + func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) + func dismiss(from presentingViewController: NSViewController) +} + +extension NSViewController: PresentationContent { + public func presented(from presentingViewController: NSViewController, style: TransitionStyle) { + presentingViewController.present(self, for: style) + } + + public func dismiss(from presentingViewController: NSViewController) { + presentingViewController.dismiss(self) + } + + public enum TransitionStyle { + case sheet + case modalWindow + case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + case custom(NSViewControllerPresentationAnimator) + } + + private func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { + switch style { + case .sheet: + presentAsSheet(viewControllerToPresent) + case .modalWindow: + presentAsModalWindow(viewControllerToPresent) + case let .popover(rect, view, preferredEdge, behavior): + present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) + case let .custom(animator): + present(viewControllerToPresent, animator: animator) + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift new file mode 100644 index 0000000000..d7bc4fcae2 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -0,0 +1,132 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +private typealias SheetObserver = NavigationObserver + +@MainActor +private var sheetObserverKeys = AssociatedKeys() + +extension SheetContent { + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + sheet(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + sheet(item: item, id: id) { $item in + content($item) + } beginSheet: { [weak self] child, _ in + guard let self else { return } + if let attachedSheetWindow = currentWindow?.attachedSheet { + self.endSheet(for: attachedSheetWindow) + onDismiss?() + Task { @MainActor in + await self.beginSheet(for: child) + child.onEndNavigation?() + child.onEndNavigation = nil + } + } else { + Task { @MainActor in + await self.beginSheet(for: child) + child.onEndNavigation?() + child.onEndNavigation = nil + } + } + } endSheet: { [weak self] content, _ in + self?.endSheet(for: content) + onDismiss?() + } + } + + private func sheet( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> Content, + beginSheet: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void, + endSheet: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let sheetObserver: SheetObserver = sheetObserver() + return sheetObserver.observe( + item: item, + id: { $0[keyPath: id] }, + content: content, + begin: beginSheet, + end: endSheet + ) + } + + private func sheetObserver() -> SheetObserver { + if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver { + return observer + } else { + let observer = SheetObserver(owner: self) + objc_setAssociatedObject(self, sheetObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer + } + } +} + +extension NSWindow { + func endSheeted() { + guard sheetParent != nil else { + return + } + sheetParent?.endSheet(self) + } +} + +extension Navigated where Content: SheetContent { + func clearup() { + content?.currentWindow?.endSheeted() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift new file mode 100644 index 0000000000..eb06919cd8 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -0,0 +1,60 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +public protocol SheetContent: NavigationContent { + var currentWindow: NSWindow? { get } + func beginSheet(for content: SheetContent) async + func endSheet(for content: SheetContent) +} + +extension SheetContent { + public func beginSheet(for content: any SheetContent) async { + guard let sheetedWindow = content.currentWindow else { return } + await currentWindow?.beginSheet(sheetedWindow) + } + + public func endSheet(for content: any SheetContent) { + guard let sheetedWindow = content.currentWindow else { return } + currentWindow?.endSheet(sheetedWindow) + } +} + +extension NSWindow: SheetContent { + public var currentWindow: NSWindow? { self } +} + +extension NSWindowController: SheetContent { + public var currentWindow: NSWindow? { window } +} + +extension NSViewController: SheetContent { + public var currentWindow: NSWindow? { view.window } +} + +extension NSAlert: SheetContent { + public var currentWindow: NSWindow? { window } + + public func beginSheet(for content: any SheetContent) async { + guard let parentWindow = content.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + public func endSheet(for content: any SheetContent) { + content.currentWindow?.endSheet(window) + } +} + +extension NSSavePanel { + public func beginSheet(for content: any SheetContent) async { + guard let parentWindow = content.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + public func endSheet(for content: any SheetContent) { + content.currentWindow?.endSheet(window) + } +} + +#endif diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h new file mode 100644 index 0000000000..5a4e070ea3 --- /dev/null +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -0,0 +1,19 @@ +#if __has_include() +#include + +#if __has_include() && !TARGET_OS_MACCATALYST +@import AppKit; + +NS_ASSUME_NONNULL_BEGIN + +@interface NSViewController (AppKitNavigation) + +@property BOOL hasViewAppeared; +@property (nullable) void (^ onDismiss)(); +@property NSArray *onViewAppear; + +@end + +NS_ASSUME_NONNULL_END +#endif +#endif /* if __has_include() */ diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m new file mode 100644 index 0000000000..14e82c72dd --- /dev/null +++ b/Sources/AppKitNavigationShim/shim.m @@ -0,0 +1,110 @@ +#if __has_include() +#include + +#if __has_include() && !TARGET_OS_MACCATALYST +@import ObjectiveC; +@import AppKit; +#import "shim.h" + +@interface AppKitNavigationShim : NSObject + +@end + +@implementation AppKitNavigationShim + +// NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible +// for state-driven presentation and dismissal of child features. + ++ (void)load { + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(viewDidAppear)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidAppear)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(viewDidDisappear)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidDisappear)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), + class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) + ); +} + +@end + +static void *hasViewAppearedKey = &hasViewAppearedKey; +static void *onDismissKey = &onDismissKey; +static void *onViewAppearKey = &onViewAppearKey; + +@implementation NSViewController (AppKitNavigation) + +- (void)AppKitNavigation_viewDidAppear { + [self AppKitNavigation_viewDidAppear]; + + if (self.hasViewAppeared) { + return; + } + + self.hasViewAppeared = YES; + + for (void (^work)() in self.onViewAppear) { + work(); + } + + self.onViewAppear = @[]; +} + +- (void)setBeingDismissed:(BOOL)beingDismissed { + objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); +} + +- (BOOL)isBeingDismissed { + return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; +} + +- (void)AppKitNavigation_viewDidDisappear { + [self AppKitNavigation_viewDidDisappear]; + + if ((self.isBeingDismissed) && self.onDismiss != NULL) { + self.onDismiss(); + self.onDismiss = nil; + [self setBeingDismissed:NO]; + } +} + +- (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { + [self AppKitNavigation_dismissViewController:sender]; + [self setBeingDismissed:YES]; +} + +- (BOOL)hasViewAppeared { + return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; +} + +- (void)setHasViewAppeared:(BOOL)hasViewAppeared { + objc_setAssociatedObject( + self, hasViewAppearedKey, @(hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC + ); +} + +- (void (^)())onDismiss { + return objc_getAssociatedObject(self, onDismissKey); +} + +- (void)setOnDismiss:(void (^)())onDismiss { + objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +- (NSMutableArray *)onViewAppear { + id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); + + return onViewAppear == nil ? @[] : onViewAppear; +} + +- (void)setOnViewAppear:(NSMutableArray *)onViewAppear { + objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); +} + +@end +#endif /* if __has_include() && !TARGET_OS_MACCATALYST */ +#endif /* if __has_include() */ From 2228ad119c9339d2219dc0c8aa6f153757534b6b Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Wed, 28 Aug 2024 00:59:52 +0800 Subject: [PATCH 024/141] Update Sources/AppKitNavigationShim/include/shim.h Co-authored-by: Stephen Celis --- Sources/AppKitNavigationShim/include/shim.h | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h index 5a4e070ea3..a19cbd8f53 100644 --- a/Sources/AppKitNavigationShim/include/shim.h +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -8,9 +8,9 @@ NS_ASSUME_NONNULL_BEGIN @interface NSViewController (AppKitNavigation) -@property BOOL hasViewAppeared; -@property (nullable) void (^ onDismiss)(); -@property NSArray *onViewAppear; +@property BOOL _AppKitNavigation_hasViewAppeared; +@property (nullable) void (^ _AppKitNavigation_onDismiss)(); +@property NSArray *_AppKitNavigation_onViewAppear; @end From 47ac7b3df1f0cdb2d47c518d6a599de4c762e283 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Wed, 28 Aug 2024 01:00:02 +0800 Subject: [PATCH 025/141] Update Sources/AppKitNavigation/Navigation/Sheet.swift Co-authored-by: Stephen Celis --- Sources/AppKitNavigation/Navigation/Sheet.swift | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index d7bc4fcae2..6ec8b0d806 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -114,18 +114,10 @@ extension SheetContent { } } -extension NSWindow { - func endSheeted() { - guard sheetParent != nil else { - return - } - sheetParent?.endSheet(self) - } -} - extension Navigated where Content: SheetContent { func clearup() { - content?.currentWindow?.endSheeted() + guard let window = content?.currentWindow else { return } + window.sheetParent?.endSheet(window) } } From 6111e32c433b5940486320e0bf69aa254ed31776 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Wed, 28 Aug 2024 01:00:20 +0800 Subject: [PATCH 026/141] Update Sources/AppKitNavigation/Navigation/ModalSessionContent.swift Co-authored-by: Stephen Celis --- .../AppKitNavigation/Navigation/ModalSessionContent.swift | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift index 9132638de7..cc50c0afdf 100644 --- a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift @@ -10,12 +10,7 @@ public protocol ModalSessionContent: ModalContent { extension NSWindow: ModalSessionContent { public func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { - __appKitNavigationBeginModalSession() - } - - @objc func __appKitNavigationBeginModalSession() -> NSApplication.ModalSession { - let modalSession = NSApplication.shared.beginModalSession(for: self) - return modalSession + NSApplication.shared.beginModalSession(for: self) } } From 3832d5118ed814210669cd382be52323e6d82913 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Tue, 17 Sep 2024 16:32:43 +0800 Subject: [PATCH 027/141] Fixes building errors --- .../Navigation/Presentation.swift | 8 ++--- Sources/AppKitNavigationShim/shim.m | 30 +++++++++---------- 2 files changed, 19 insertions(+), 19 deletions(-) diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 5b2c0662ca..e5f0197e7e 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -8,10 +8,10 @@ private var presentationObserverKeys = AssociatedKeys() class PresentationObserver: NavigationObserver { override func commitWork(_ work: @escaping () -> Void) { - if owner.hasViewAppeared { + if owner._AppKitNavigation_hasViewAppeared { work() } else { - owner.onViewAppear.append(work) + owner._AppKitNavigation_onViewAppear.append(work) } } } @@ -158,10 +158,10 @@ extension NSViewController { extension NavigationContent where Self: NSViewController { var _onEndNavigation: (() -> Void)? { set { - onDismiss = newValue + _AppKitNavigation_onDismiss = newValue } get { - onDismiss + _AppKitNavigation_onDismiss } } } diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index 14e82c72dd..9ebf4859ba 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -41,17 +41,17 @@ @implementation NSViewController (AppKitNavigation) - (void)AppKitNavigation_viewDidAppear { [self AppKitNavigation_viewDidAppear]; - if (self.hasViewAppeared) { + if (self._AppKitNavigation_hasViewAppeared) { return; } - self.hasViewAppeared = YES; + self._AppKitNavigation_hasViewAppeared = YES; - for (void (^work)() in self.onViewAppear) { + for (void (^work)() in self._AppKitNavigation_onViewAppear) { work(); } - self.onViewAppear = @[]; + self._AppKitNavigation_onViewAppear = @[]; } - (void)setBeingDismissed:(BOOL)beingDismissed { @@ -65,9 +65,9 @@ - (BOOL)isBeingDismissed { - (void)AppKitNavigation_viewDidDisappear { [self AppKitNavigation_viewDidDisappear]; - if ((self.isBeingDismissed) && self.onDismiss != NULL) { - self.onDismiss(); - self.onDismiss = nil; + if ((self.isBeingDismissed) && self._AppKitNavigation_onDismiss != NULL) { + self._AppKitNavigation_onDismiss(); + self._AppKitNavigation_onDismiss = nil; [self setBeingDismissed:NO]; } } @@ -77,31 +77,31 @@ - (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { [self setBeingDismissed:YES]; } -- (BOOL)hasViewAppeared { +- (BOOL)_AppKitNavigation_hasViewAppeared { return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; } -- (void)setHasViewAppeared:(BOOL)hasViewAppeared { +- (void)set_AppKitNavigation_hasViewAppeared:(BOOL)_AppKitNavigation_hasViewAppeared { objc_setAssociatedObject( - self, hasViewAppearedKey, @(hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC + self, hasViewAppearedKey, @(_AppKitNavigation_hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC ); } -- (void (^)())onDismiss { +- (void (^)())_AppKitNavigation_onDismiss { return objc_getAssociatedObject(self, onDismissKey); } -- (void)setOnDismiss:(void (^)())onDismiss { - objc_setAssociatedObject(self, onDismissKey, [onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); +- (void)set_AppKitNavigation_onDismiss:(void (^)())_AppKitNavigation_onDismiss { + objc_setAssociatedObject(self, onDismissKey, [_AppKitNavigation_onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); } -- (NSMutableArray *)onViewAppear { +- (NSMutableArray *)_AppKitNavigation_onViewAppear { id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); return onViewAppear == nil ? @[] : onViewAppear; } -- (void)setOnViewAppear:(NSMutableArray *)onViewAppear { +- (void)set_AppKitNavigation_onViewAppear:(NSMutableArray *)onViewAppear { objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); } From 593cae881ffd62d0f2e59bc403106f4951f64b3e Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 11 Oct 2024 10:42:57 +0800 Subject: [PATCH 028/141] Support control bindings --- Package.swift | 8 +- Package@swift-6.0.swift | 4 + .../AppKitNavigation/AppKitAnimation.swift | 2 +- .../AppKitNavigation/Bindings/NSAlert.swift | 48 +++ .../Bindings/NSColorPanel.swift | 41 +++ .../Bindings/NSColorWell.swift | 27 ++ .../AppKitNavigation/Bindings/NSControl.swift | 43 +++ .../Bindings/NSDatePicker.swift | 27 ++ .../Bindings/NSFontManager.swift | 77 ++++ .../Bindings/NSMenuItem.swift | 17 + .../Bindings/NSPathControl.swift | 29 ++ .../Bindings/NSSaveOpenPanel.swift | 62 ++++ .../Bindings/NSSegmentedControl.swift | 79 ++++ .../AppKitNavigation/Bindings/NSSlider.swift | 26 ++ .../AppKitNavigation/Bindings/NSStepper.swift | 26 ++ .../AppKitNavigation/Bindings/NSSwitch.swift | 34 ++ .../Bindings/NSTargetAction.swift | 143 ++++++++ .../Bindings/NSTargetActionProxy.swift | 88 +++++ .../Bindings/NSTextField.swift | 342 ++++++++++++++++++ .../Bindings/NSToolbarItem.swift | 17 + Sources/AppKitNavigationShim/include/shim.h | 17 + Sources/AppKitNavigationShim/shim.m | 66 ++++ .../xcshareddata/swiftpm/Package.resolved | 34 +- 23 files changed, 1238 insertions(+), 19 deletions(-) create mode 100755 Sources/AppKitNavigation/Bindings/NSAlert.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSColorPanel.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSColorWell.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSControl.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSDatePicker.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSFontManager.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSMenuItem.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSPathControl.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSSlider.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSStepper.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSSwitch.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSTargetAction.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSTextField.swift create mode 100755 Sources/AppKitNavigation/Bindings/NSToolbarItem.swift create mode 100755 Sources/AppKitNavigationShim/include/shim.h create mode 100755 Sources/AppKitNavigationShim/shim.m diff --git a/Package.swift b/Package.swift index 2194c6fcfc..2fb60be222 100644 --- a/Package.swift +++ b/Package.swift @@ -36,6 +36,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), ], targets: [ .target( @@ -82,9 +83,14 @@ let package = Package( .target( name: "AppKitNavigation", dependencies: [ - "SwiftNavigation" + "SwiftNavigation", + "AppKitNavigationShim", + .product(name: "IdentifiedCollections", package: "swift-identified-collections") ] ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 490fe55fcd..169fd95403 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -83,8 +83,12 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", + "AppKitNavigationShim", ] ), + .target( + name: "AppKitNavigationShim" + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 096761ab34..7d469824ea 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -52,8 +52,8 @@ return try result!._rethrowGet() case let .swiftUI(animation): - var result: Swift.Result? #if swift(>=6) + var result: Swift.Result? if #available(macOS 15, *) { NSAnimationContext.animate(animation) { result = Swift.Result(catching: body) diff --git a/Sources/AppKitNavigation/Bindings/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift new file mode 100755 index 0000000000..812f894812 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSAlert.swift @@ -0,0 +1,48 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSAlert { + /// Creates and returns a alert for displaying an alert using a data description. + /// + /// - Parameters: + /// - state: A data description of the alert. + /// - handler: A closure that is invoked with an action held in `state`. + public convenience init( + state: AlertState, + handler: @escaping (_ action: Action?) -> Void + ) { + self.init() + self.messageText = String(state: state.title) + state.message.map { self.informativeText = String(state: $0) } + + for button in state.buttons { + addButton(button, action: handler) + } + } +} + +extension NSAlert { + public func addButton( + _ buttonState: ButtonState, + action handler: @escaping (_ action: Action?) -> Void = { (_: Never?) in } + ) { + let button = addButton(withTitle: String(state: buttonState.label)) + + button.createActionProxyIfNeeded().addBindingAction { _ in + buttonState.withAction(handler) + } + + if buttonState.role == .destructive, #available(macOS 11.0, *) { + button.hasDestructiveAction = true + } + + if buttonState.role == .cancel { + button.keyEquivalent = "\u{1b}" + } + + if #available(macOS 12, *) { + button.setAccessibilityLabel(buttonState.label.accessibilityLabel.map { String(state: $0) }) + } + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift new file mode 100755 index 0000000000..d2287caf93 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -0,0 +1,41 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSColorPanel: NSTargetActionProtocol { + public var appkitNavigationTarget: AnyObject? { + set { setTarget(newValue) } + get { value(forKeyPath: "target") as? AnyObject } + } + + public var appkitNavigationAction: Selector? { + set { setAction(newValue) } + get { value(forKeyPath: "action") as? Selector } + } +} + +extension NSColorPanel { + /// Creates a new color panel and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - color: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init(color: UIBinding) { + self.init() + bind(color: color) + } + + /// Establishes a two-way connection between a binding and the color panel's selected color. + /// + /// - Parameter color: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(color: UIBinding) -> ObserveToken { + bind(color, to: \.color) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSColorWell.swift b/Sources/AppKitNavigation/Bindings/NSColorWell.swift new file mode 100755 index 0000000000..71eab79865 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSColorWell.swift @@ -0,0 +1,27 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSColorWell { + /// Creates a new color well with the specified frame and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - color: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init(frame: CGRect = .zero, color: UIBinding) { + self.init(frame: frame) + bind(color: color) + } + + /// Establishes a two-way connection between a binding and the color well's selected color. + /// + /// - Parameter color: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(color: UIBinding) -> ObserveToken { + bind(color, to: \.color) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift new file mode 100755 index 0000000000..7edc6aaef2 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -0,0 +1,43 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSControl: NSTargetActionProtocol { + public var appkitNavigationTarget: AnyObject? { + set { target = newValue } + get { target } + } + + public var appkitNavigationAction: Selector? { + set { action = newValue } + get { action } + } +} + +extension NSControl { + public convenience init(action: @escaping (Self) -> Void) { + self.init(frame: .zero) + createActionProxyIfNeeded().addAction { [weak self] _ in + guard let self else { return } + action(self) + } + } + + @discardableResult + public func addAction(_ action: @escaping (NSControl) -> Void) -> UUID { + createActionProxyIfNeeded().addAction { [weak self] _ in + guard let self else { return } + action(self) + } + } + + public func removeAction(for id: UUID) { + createActionProxyIfNeeded().removeAction(for: id) + } + + public func removeAllActions() { + createActionProxyIfNeeded().removeAllActions() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSDatePicker.swift b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift new file mode 100755 index 0000000000..17e3d26ecd --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift @@ -0,0 +1,27 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSDatePicker { + /// Creates a new date picker with the specified frame and registers the binding against the + /// selected date. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected date, and write to when the selected + /// date changes. + public convenience init(frame: CGRect = .zero, date: UIBinding) { + self.init(frame: frame) + bind(date: date) + } + + /// Establishes a two-way connection between a binding and the date picker's selected date. + /// + /// - Parameter date: The binding to read from for the selected date, and write to when the + /// selected date changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(date: UIBinding) -> ObserveToken { + bind(date, to: \.dateValue) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift new file mode 100755 index 0000000000..9797d82ae6 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -0,0 +1,77 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import SwiftNavigation + +extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { + public var appkitNavigationTarget: AnyObject? { + set { appkitNavigationDelegate.target = newValue } + get { appkitNavigationDelegate.target } + } + + public var appkitNavigationAction: Selector? { + set { appkitNavigationDelegate.action = newValue } + get { appkitNavigationDelegate.action } + } + + private static let appkitNavigationDelegateKey = malloc(1)! + + private var appkitNavigationDelegate: Delegate { + set { + objc_setAssociatedObject(self, Self.appkitNavigationDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + if let delegate = objc_getAssociatedObject(self, Self.appkitNavigationDelegateKey) as? Delegate { + return delegate + } else { + let delegate = Delegate() + target = delegate + self.appkitNavigationDelegate = delegate + return delegate + } + } + } + + private class Delegate: NSObject, NSFontChanging { + var target: AnyObject? + var action: Selector? + + func changeFont(_ sender: NSFontManager?) { + if let action { + NSApplication.shared.sendAction(action, to: target, from: sender) + } + } + } +} + +@MainActor +extension NSFontManager { + /// Creates a new date picker with the specified frame and registers the binding against the + /// selected date. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected date, and write to when the selected + /// date changes. + public convenience init(font: UIBinding) { + self.init() + bind(font: font) + } + + /// Establishes a two-way connection between a binding and the date picker's selected date. + /// + /// - Parameter date: The binding to read from for the selected date, and write to when the + /// selected date changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(font: UIBinding) -> ObserveToken { + bind(font, to: \._selectedFont) + } + + @objc private var _selectedFont: NSFont { + set { setSelectedFont(newValue, isMultiple: false) } + get { convert(.systemFont(ofSize: 0)) } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift new file mode 100755 index 0000000000..25d7dd5c0a --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift @@ -0,0 +1,17 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSMenuItem: NSTargetActionProtocol, @unchecked Sendable { + public var appkitNavigationTarget: AnyObject? { + set { target = newValue } + get { target } + } + + public var appkitNavigationAction: Selector? { + set { action = newValue } + get { action } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSPathControl.swift b/Sources/AppKitNavigation/Bindings/NSPathControl.swift new file mode 100755 index 0000000000..fda06940be --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSPathControl.swift @@ -0,0 +1,29 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSPathControl { + /// Creates a new path control with the specified frame and registers the binding against the + /// selected url. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected url, and write to when the selected + /// url changes. + public convenience init(frame: CGRect = .zero, date: UIBinding) { + self.init(frame: frame) + bind(url: date) + } + + /// Establishes a two-way connection between a binding and the path control's selected url. + /// + /// - Parameter url: The binding to read from for the selected url, and write to when the + /// selected url changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(url: UIBinding) -> ObserveToken { + bind(url, to: \.url) + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift new file mode 100755 index 0000000000..8220b89367 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift @@ -0,0 +1,62 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import AppKitNavigationShim + +extension NSSavePanel { + public convenience init(url: UIBinding) { + self.init() + bind(url: url) + } + + @discardableResult + public func bind(url binding: UIBinding) -> ObserveToken { + appKitNavigation_onFinalURL = { url in + binding.wrappedValue = url + } + + let observationToken = ObserveToken { [weak self] in + guard let self else { return } + MainActor._assumeIsolated { + self.appKitNavigation_onFinalURL = nil + } + } + observationTokens[\NSSavePanel.url] = observationToken + return observationToken + } + + public func unbindURL() { + observationTokens[\NSSavePanel.url]?.cancel() + observationTokens[\NSSavePanel.url] = nil + } +} + +extension NSOpenPanel { + public convenience init(urls: UIBinding<[URL]>) { + self.init() + bind(urls: urls) + } + + @discardableResult + public func bind(urls binding: UIBinding<[URL]>) -> ObserveToken { + appKitNavigation_onFinalURLs = { urls in + binding.wrappedValue = urls + } + + let observationToken = ObserveToken { [weak self] in + guard let self else { return } + MainActor._assumeIsolated { + self.appKitNavigation_onFinalURLs = nil + } + } + observationTokens[\NSOpenPanel.urls] = observationToken + return observationToken + } + + public func unbindURLs() { + observationTokens[\NSOpenPanel.urls]?.cancel() + observationTokens[\NSOpenPanel.urls] = nil + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift new file mode 100755 index 0000000000..25b1bdd441 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -0,0 +1,79 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import IssueReporting +import AppKit + +extension NSSegmentedControl { + /// Creates a new color well with the specified frame and registers the binding against the + /// selected color. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - selectedSegment: The binding to read from for the selected color, and write to when the + /// selected color is changes. + public convenience init( + frame: CGRect = .zero, selectedSegment: UIBinding>, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + self.init(frame: frame) + bind( + selectedSegment: selectedSegment, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Establishes a two-way connection between a binding and the color well's selected color. + /// + /// - Parameter selectedSegment: The binding to read from for the selected color, and write to + /// when the selected color changes. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selectedSegment: UIBinding>, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + let fileID = HashableStaticString(rawValue: fileID) + let filePath = HashableStaticString(rawValue: filePath) + return bind( + selectedSegment[fileID: fileID, filePath: filePath, line: line, column: column], + to: \.selectedSegment + ) + } +} + +extension RawRepresentable { + fileprivate subscript( + fileID fileID: HashableStaticString, + filePath filePath: HashableStaticString, + line line: UInt, + column column: UInt + ) -> Int { + get { rawValue } + set { + guard let rawRepresentable = Self(rawValue: newValue) + else { + reportIssue( + """ + Raw-representable 'UIBinding<\(Self.self)>' attempted to write an invalid raw value \ + ('\(newValue)'). + """, + fileID: fileID.rawValue, + filePath: filePath.rawValue, + line: line, + column: column + ) + return + } + self = rawRepresentable + } + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSlider.swift b/Sources/AppKitNavigation/Bindings/NSSlider.swift new file mode 100755 index 0000000000..7931a6d921 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSlider.swift @@ -0,0 +1,26 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSSlider { + /// Creates a new slider with the specified frame and registers the binding against the value. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - value: The binding to read from for the current value, and write to when the value + /// changes. + public convenience init(frame: CGRect = .zero, value: UIBinding) { + self.init(frame: frame) + bind(value: value) + } + + /// Establishes a two-way connection between a binding and the slider's current value. + /// + /// - Parameter value: The binding to read from for the current value, and write to when the + /// value changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(value: UIBinding) -> ObserveToken { + bind(value, to: \.floatValue) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSStepper.swift b/Sources/AppKitNavigation/Bindings/NSStepper.swift new file mode 100755 index 0000000000..59a679d71f --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSStepper.swift @@ -0,0 +1,26 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSStepper { + /// Creates a new stepper with the specified frame and registers the binding against the value. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - value: The binding to read from for the current value, and write to when the value + /// changes. + public convenience init(frame: CGRect = .zero, value: UIBinding) { + self.init(frame: frame) + bind(value: value) + } + + /// Establishes a two-way connection between a binding and the stepper's current value. + /// + /// - Parameter value: The binding to read from for the current value, and write to when the + /// value changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(value: UIBinding) -> ObserveToken { + bind(value, to: \.doubleValue) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSwitch.swift b/Sources/AppKitNavigation/Bindings/NSSwitch.swift new file mode 100755 index 0000000000..60a92b14fa --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSwitch.swift @@ -0,0 +1,34 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit + +extension NSSwitch { + /// Creates a new switch with the specified frame and registers the binding against whether or + /// not the switch is on. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - isOn: The binding to read from for the current state, and write to when the state + /// changes. + public convenience init(frame: CGRect = .zero, isOn: UIBinding) { + self.init(frame: frame) + bind(isOn: isOn) + } + + /// Establishes a two-way connection between a binding and the switch's current state. + /// + /// - Parameter isOn: The binding to read from for the current state, and write to when the + /// state changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(isOn: UIBinding) -> ObserveToken { + bind(isOn, to: \.boolValue) { control, isOn, transaction in + control.boolValue = isOn + } + } + + @objc var boolValue: Bool { + set { state = newValue ? .on : .off } + get { state == .on } + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift new file mode 100755 index 0000000000..1d72abb4eb --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift @@ -0,0 +1,143 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import ConcurrencyExtras +@_spi(Internals) import SwiftNavigation +import AppKit + +/// A protocol used to extend `NSControl, NSMenuItem...`. +@MainActor +public protocol NSTargetActionProtocol: NSObject, Sendable { + var appkitNavigationTarget: AnyObject? { set get } + var appkitNavigationAction: Selector? { set get } +} + +extension NSTargetActionProtocol { + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: ReferenceWritableKeyPath + ) -> ObserveToken { + bind(binding, to: keyPath) { control, newValue, _ in + control[keyPath: keyPath] = newValue + } + } + + var actionProxy: NSTargetActionProxy? { + set { + objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, actionProxyKey) as? NSTargetActionProxy + } + } + + func createActionProxyIfNeeded() -> NSTargetActionProxy { + if let actionProxy { + return actionProxy + } else { + let actionProxy = NSTargetActionProxy(owner: self) + self.actionProxy = actionProxy + return actionProxy + } + } + + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - set: A closure that is called when the binding's value changes with a weakly-captured + /// control, a new value that can be used to configure the control, and a transaction, which + /// can be used to determine how and if the change should be animated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: KeyPath, + set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void + ) -> ObservationToken { + unbind(keyPath) + let actionProxy = createActionProxyIfNeeded() + let actionID = actionProxy.addBindingAction { [weak self] _ in + guard let self else { return } + binding.wrappedValue = self[keyPath: keyPath] + } + + let isSetting = LockIsolated(false) + let token = observe { [weak self] transaction in + guard let self else { return } + isSetting.withValue { $0 = true } + defer { isSetting.withValue { $0 = false } } + set( + self, + binding.wrappedValue, + transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + @UncheckedSendable var uncheckedKeyPath = keyPath + let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in + guard isSetting.withValue({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + } + } + let observationToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + self?.actionProxy?.removeAction(for: actionID) + } + token.cancel() + observation.invalidate() + } + observationTokens[keyPath] = observationToken + return observationToken + } + + public func unbind(_ keyPath: KeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } + +// var observationTokens: [AnyKeyPath: ObservationToken] { +// get { +// objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] +// ?? [:] +// } +// set { +// objc_setAssociatedObject( +// self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC +// ) +// } +// } +} + +@MainActor +extension NSObject { + var observationTokens: [AnyKeyPath: ObservationToken] { + get { + objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] + ?? [:] + } + set { + objc_setAssociatedObject( + self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } +} + +@MainActor +private let observationTokensKey = malloc(1)! +@MainActor +private let actionProxyKey = malloc(1)! + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift new file mode 100755 index 0000000000..2d2054d0ec --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift @@ -0,0 +1,88 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import IdentifiedCollections + +@MainActor +class NSTargetActionProxy: NSObject { + typealias ActionClosure = (Any?) -> Void + + typealias ActionIdentifier = UUID + + private struct Action: Identifiable { + let id = UUID() + + var closure: ActionClosure + + func invoke(_ sender: Any?) { + closure(sender) + } + } + + private var bindingActions: IdentifiedArrayOf = [] + + private var actions: IdentifiedArrayOf = [] + + private var originTarget: AnyObject? + + private var originAction: Selector? + + weak var owner: NSTargetActionProtocol? + + required init(owner: NSTargetActionProtocol) { + self.owner = owner + super.init() + self.originTarget = owner.appkitNavigationTarget + self.originAction = owner.appkitNavigationAction + owner.appkitNavigationTarget = self + owner.appkitNavigationAction = #selector(invokeAction(_:)) + if let textField = owner as? NSTextField { + NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) + } + } + + @objc func controlTextDidChange(_ obj: Notification) { + bindingActions.forEach { $0.invoke(obj.object) } + actions.forEach { $0.invoke(obj.object) } + } + + @objc func invokeAction(_ sender: Any?) { + if let originTarget, let originAction { + NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) + } + bindingActions.forEach { $0.invoke(sender) } + actions.forEach { $0.invoke(sender) } + } + + @discardableResult + func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { + let action = Action(closure: actionClosure) + actions.append(action) + return action.id + } + + func removeAction(for id: ActionIdentifier) { + actions.remove(id: id) + } + + func removeAllActions() { + actions.removeAll() + } + + @discardableResult + func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { + let bindingAction = Action(closure: bindingActionClosure) + bindingActions.append(bindingAction) + return bindingAction.id + } + + func removeBindingAction(for id: ActionIdentifier) { + bindingActions.remove(id: id) + } + + func removeAllBindingActions() { + bindingActions.removeAll() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift new file mode 100755 index 0000000000..897efc8417 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -0,0 +1,342 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import Combine +import SwiftNavigation + +@MainActor +extension NSTextField: NSTextViewDelegate { + /// Creates a new text field with the specified frame and registers the binding against its + /// text. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - text: The binding to read from for the current text, and write to when the text + /// changes. + public convenience init(frame: CGRect = .zero, text: UIBinding) { + self.init(frame: frame) + bind(text: text) + } + + /// Creates a new text field with the specified frame and registers the binding against its + /// text. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - attributedText: The binding to read from for the current text, and write to when the + /// attributed text changes. + public convenience init(frame: CGRect = .zero, attributedText: UIBinding) { + self.init(frame: frame) + bind(attributedText: attributedText) + } + + /// Establishes a two-way connection between a binding and the text field's current text. + /// + /// - Parameter text: The binding to read from for the current text, and write to when the text + /// changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(text: UIBinding) -> ObserveToken { + bind(text, to: \.stringValue) + } + + /// Establishes a two-way connection between a binding and the text field's current text. + /// + /// - Parameter attributedText: The binding to read from for the current text, and write to when + /// the attributed text changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(attributedText: UIBinding) -> ObserveToken { + bind(attributedText, to: \.attributedStringValue) + } + + /// Establishes a two-way connection between a binding and the text field's current selection. + /// + /// - Parameter selection: The binding to read from for the current selection, and write to when + /// the selected text range changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(selection: UIBinding) -> ObserveToken { + let editingChangedAction = NotificationCenter.default.publisher(for: NSTextField.textDidChangeNotification, object: self) + .sink { [weak self] _ in + guard let self else { return } + selection.wrappedValue = self.textSelection + } + let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in selection.wrappedValue = nil } + let token = observe { [weak self] in + guard let self else { return } + textSelection = selection.wrappedValue + } + textSelectionObserver = TextSelectionObserver { control in + MainActor._assumeIsolated { + selection.wrappedValue = control.textSelection + } + } + + let observationToken = ObservationToken { [weak self] in + MainActor._assumeIsolated { + editingChangedAction.cancel() + editingDidEndAction.cancel() + token.cancel() + self?.textSelectionObserver = nil + } + } + observationTokens[\NSTextField.selectedRange] = observationToken + return observationToken + } + + fileprivate var selectedRange: NSRange? { + set { + currentEditor()?.selectedRange = newValue ?? .init(location: 0, length: 0) + } + + get { + currentEditor()?.selectedRange + } + } + + fileprivate class TextSelectionObserver: NSObject { + let observer: (NSTextField) -> Void + + init(observer: @escaping (NSTextField) -> Void) { + self.observer = observer + } + } + + private static let textSelectionObserverKey = malloc(1)! + private var textSelectionObserver: TextSelectionObserver? { + set { + objc_setAssociatedObject(self, Self.textSelectionObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, Self.textSelectionObserverKey) as? TextSelectionObserver + } + } + + public func textViewDidChangeSelection(_ notification: Notification) { + textSelectionObserver?.observer(self) + } + + fileprivate var textSelection: AppKitTextSelection? { + get { + guard + let textRange = selectedRange + else { + return nil + } + let text = stringValue + let lowerBound = + text.index( + text.startIndex, + offsetBy: textRange.location, + limitedBy: text.endIndex + ) ?? text.endIndex + let upperBound = + text.index( + text.startIndex, + offsetBy: NSMaxRange(textRange), + limitedBy: text.endIndex + ) ?? text.endIndex + return AppKitTextSelection(range: lowerBound ..< upperBound) + } + set { + guard let selection = newValue?.range else { + selectedRange = nil + return + } + let text = stringValue + let from = text.distance( + from: text.startIndex, to: min(selection.lowerBound, text.endIndex) + ) + let to = text.distance( + from: text.startIndex, to: min(selection.upperBound, text.endIndex) + ) + selectedRange = .init(location: from, length: to - from) + } + } + + /// Modifies this text field by binding its focus state to the given state value. + /// + /// Use this modifier to cause the text field to receive focus whenever the the `binding` equals + /// the `value`. Typically, you create an enumeration of fields that may receive focus, bind an + /// instance of this enumeration, and assign its cases to focusable text fields. + /// + /// The following example uses the cases of a `LoginForm` enumeration to bind the focus state of + /// two `UITextField` views. A sign-in button validates the fields and sets the bound + /// `focusedField` value to any field that requires the user to correct a problem. + /// + /// ```swift + /// final class LoginViewController: UIViewController { + /// enum Field { + /// case usernameField + /// case passwordField + /// } + /// + /// @UIBinding private var username = "" + /// @UIBinding private var password = "" + /// @UIBinding private var focusedField: Field? + /// + /// // ... + /// + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// let usernameTextField = UITextField(text: $username) + /// usernameTextField.focus($focusedField, equals: .usernameField) + /// + /// let passwordTextField = UITextField(text: $password) + /// passwordTextField.focus($focusedField, equals: .passwordField) + /// passwordTextField.isSecureTextEntry = true + /// + /// let signInButton = UIButton( + /// style: .system, + /// primaryAction: UIAction { [weak self] _ in + /// guard let self else { return } + /// if username.isEmpty { + /// focusedField = .usernameField + /// } else if password.isEmpty { + /// focusedField = .passwordField + /// } else { + /// handleLogin(username, password) + /// } + /// } + /// ) + /// signInButton.setTitle("Sign In", for: .normal) + /// + /// // ... + /// } + /// } + /// ``` + /// + /// To control focus using a Boolean, use the ``UIKit/UITextField/bind(focus:)`` method instead. + /// + /// - Parameters: + /// - focus: The state binding to register. When focus moves to the text field, the binding + /// sets the bound value to the corresponding match value. If a caller sets the state value + /// programmatically to the matching value, then focus moves to the text field. When focus + /// leaves the text field, the binding sets the bound value to `nil`. If a caller sets the + /// value to `nil`, UIKit automatically dismisses focus. + /// - value: The value to match against when determining whether the binding should change. + /// - Returns: A cancel token. + @discardableResult + public func bind( + focus: UIBinding, equals value: Value + ) -> ObserveToken { + focusToken?.cancel() + let editingDidBeginAction = NotificationCenter.default.publisher(for: NSTextField.textDidBeginEditingNotification, object: self).sink { _ in + focus.wrappedValue = value + } + + let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in + guard focus.wrappedValue == value else { return } + focus.wrappedValue = nil + } + + let innerToken = observe { [weak self] in + guard let self else { return } + switch (focus.wrappedValue, currentEditor() != nil) { + case (value, false): + becomeFirstResponder() + case (nil, true): + window?.makeFirstResponder(nil) + default: + break + } + } + let outerToken = ObservationToken { + editingDidBeginAction.cancel() + editingDidEndAction.cancel() + innerToken.cancel() + } + focusToken = outerToken + return outerToken + } + + /// Binds this text field's focus state to the given Boolean state value. + /// + /// Use this method to cause the text field to receive focus whenever the the `condition` value + /// is `true`. You can use this method to observe the focus state of a text field, or + /// programmatically set and remove focus from the text field. + /// + /// In the following example, a single `UITextField` accepts a user's desired `username`. The + /// text field binds its focus state to the Boolean value `usernameFieldIsFocused`. A "Submit" + /// button's action verifies whether the name is available. If the name is unavailable, the + /// button sets `usernameFieldIsFocused` to `true`, which causes focus to return to the text + /// field, so the user can enter a different name. + /// + /// ```swift + /// final class LoginViewController: UIViewController { + /// @UIBindable private var username = "" + /// @UIBindable private var usernameFieldIsFocused = false + /// + /// // ... + /// + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// let textField = UITextField(text: $username) + /// textField.focus($usernameFieldIsFocused) + /// + /// let submitButton = UIButton( + /// style: .system, + /// primaryAction: UIAction { [weak self] _ in + /// guard let self else { return } + /// if !isUserNameAvailable(username: username) { + /// usernameFieldIsFocused = true + /// } + /// } + /// ) + /// submitButton.setTitle("Sign In", for: .normal) + /// + /// // ... + /// } + /// } + /// ``` + /// + /// To control focus by matching a value, use the ``UIKit/UITextField/bind(focus:equals:)`` + /// method instead. + /// + /// - Parameter condition: The focus state to bind. When focus moves to the text field, the + /// binding sets the bound value to `true`. If a caller sets the value to `true` + /// programmatically, then focus moves to the text field. When focus leaves the text field, + /// the binding sets the value to `false`. If a caller sets the value to `false`, UIKit + /// automatically dismisses focus. + /// - Returns: A cancel token. + @discardableResult + public func bind(focus condition: UIBinding) -> ObserveToken { + bind(focus: condition.toOptionalUnit, equals: Bool.Unit()) + } + + private var focusToken: ObserveToken? { + get { objc_getAssociatedObject(self, Self.focusTokenKey) as? ObserveToken } + set { + objc_setAssociatedObject( + self, Self.focusTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private static let focusTokenKey = malloc(1)! +} + +/// Represents a selection of text. +/// +/// Like SwiftUI's `TextSelection`, but for UIKit. +public struct AppKitTextSelection: Hashable, Sendable { + public var range: Range + + public init(range: Range) { + self.range = range + } + + public init(insertionPoint: String.Index) { + self.range = insertionPoint ..< insertionPoint + } + + public var isInsertion: Bool { + range.isEmpty + } +} + +extension AnyCancellable: @unchecked Sendable {} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift new file mode 100755 index 0000000000..478253a51e --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift @@ -0,0 +1,17 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSToolbarItem: NSTargetActionProtocol { + public var appkitNavigationTarget: AnyObject? { + set { target = newValue } + get { target } + } + + public var appkitNavigationAction: Selector? { + set { action = newValue } + get { action } + } +} + +#endif diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h new file mode 100755 index 0000000000..9bd7111902 --- /dev/null +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -0,0 +1,17 @@ +#if __has_include() +#include + +#if __has_include() && !TARGET_OS_MACCATALYST +@import AppKit; + +NS_ASSUME_NONNULL_BEGIN + +@interface NSSavePanel (AppKitNavigation) +@property (nullable) void (^ AppKitNavigation_onFinalURL)(NSURL *_Nullable); +@property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); +@end + + +NS_ASSUME_NONNULL_END +#endif +#endif /* if __has_include() */ diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m new file mode 100755 index 0000000000..8101d55352 --- /dev/null +++ b/Sources/AppKitNavigationShim/shim.m @@ -0,0 +1,66 @@ +#if __has_include() +#include + +#if __has_include() && !TARGET_OS_MACCATALYST +@import ObjectiveC; +@import AppKit; +#import "shim.h" + +@interface AppKitNavigationShim : NSObject + +@end + +@implementation AppKitNavigationShim + +// NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible +// for state-driven presentation and dismissal of child features. + ++ (void)load { + method_exchangeImplementations( + class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), + class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) + ); + method_exchangeImplementations( + class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURLs:")), + class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURLs:)) + ); +} + +@end + +@implementation NSSavePanel (AppKitNavigation) + +- (void)setAppKitNavigation_onFinalURLs:(void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { + objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs), AppKitNavigation_onFinalURLs, OBJC_ASSOCIATION_COPY); +} + +- (void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { + return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs)); +} + +- (void)setAppKitNavigation_onFinalURL:(void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { + objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURL), AppKitNavigation_onFinalURL, OBJC_ASSOCIATION_COPY); +} + +- (void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { + return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURL)); +} + +- (void)AppKitNavigation_setFinalURL:(nullable NSURL *)url { + [self AppKitNavigation_setFinalURL:url]; + if (self.AppKitNavigation_onFinalURL) { + self.AppKitNavigation_onFinalURL(url); + } +} + +- (void)AppKitNavigation_setFinalURLs:(NSArray *)urls { + [self AppKitNavigation_setFinalURLs:urls]; + if (self.AppKitNavigation_onFinalURLs) { + self.AppKitNavigation_onFinalURLs(urls); + } +} + +@end + +#endif /* if __has_include() && !TARGET_OS_MACCATALYST */ +#endif /* if __has_include() */ diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index 23b8079026..e5c147398a 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -14,8 +14,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { - "revision" : "71344dd930fde41e8f3adafe260adcbb2fc2a3dc", - "version" : "1.5.4" + "revision" : "bc92c4b27f9a84bfb498cdbfdf35d5a357e9161f", + "version" : "1.5.6" } }, { @@ -23,8 +23,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-clocks", "state" : { - "revision" : "3581e280bf0d90c3fb9236fb23e75a5d8c46b533", - "version" : "1.0.4" + "revision" : "b9b24b69e2adda099a1fa381cda1eeec272d5b53", + "version" : "1.0.5" } }, { @@ -32,8 +32,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections", "state" : { - "revision" : "3d2dc41a01f9e49d84f0a3925fb858bed64f702d", - "version" : "1.1.2" + "revision" : "671108c96644956dddcd89dd59c203dcdb36cec7", + "version" : "1.1.4" } }, { @@ -59,8 +59,8 @@ "kind" : "remoteSourceControl", "location" : "http://github.com/pointfreeco/swift-dependencies", "state" : { - "revision" : "d7472be6b3c89251ce4c0db07d32405b43426781", - "version" : "1.3.7" + "revision" : "0fc0255e780bf742abeef29dec80924f5f0ae7b9", + "version" : "1.4.1" } }, { @@ -68,14 +68,14 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-docc-plugin", "state" : { - "revision" : "26ac5758409154cc448d7ab82389c520fa8a8247", - "version" : "1.3.0" + "revision" : "85e4bb4e1cd62cec64a4b8e769dcefdf0c5b9d64", + "version" : "1.4.3" } }, { "identity" : "swift-docc-symbolkit", "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-docc-symbolkit", + "location" : "https://github.com/swiftlang/swift-docc-symbolkit", "state" : { "revision" : "b45d1f2ed151d057b54504d653e0da5552844e34", "version" : "1.0.0" @@ -95,8 +95,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-perception", "state" : { - "revision" : "1552c8f722ac256cc0b8daaf1a7073217d4fcdfb", - "version" : "1.3.4" + "revision" : "bc67aa8e461351c97282c2419153757a446ae1c9", + "version" : "1.3.5" } }, { @@ -104,8 +104,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax", "state" : { - "revision" : "06b5cdc432e93b60e3bdf53aff2857c6b312991a", - "version" : "600.0.0-prerelease-2024-07-30" + "revision" : "0687f71944021d616d34d922343dcef086855920", + "version" : "600.0.1" } }, { @@ -122,8 +122,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { - "revision" : "357ca1e5dd31f613a1d43320870ebc219386a495", - "version" : "1.2.2" + "revision" : "770f990d3e4eececb57ac04a6076e22f8c97daeb", + "version" : "1.4.2" } } ], From 2479dbaa7e4e8042ee3429c0984cb1c97cba531a Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 11 Oct 2024 11:40:01 +0800 Subject: [PATCH 029/141] Translate some protocol to internal --- .../AppKitNavigation/Navigation/Modal.swift | 153 ++++++++++++++---- .../Navigation/ModalContent.swift | 10 +- .../Navigation/ModalSessionContent.swift | 5 +- .../Navigation/NavigationContent.swift | 6 +- .../Navigation/Presentation.swift | 63 ++++---- .../Navigation/PresentationContent.swift | 6 +- .../AppKitNavigation/Navigation/Sheet.swift | 22 +-- .../Navigation/SheetContent.swift | 22 +-- 8 files changed, 185 insertions(+), 102 deletions(-) diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 14681eda9e..79075a67be 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -9,94 +9,139 @@ private typealias ModalObserver = NavigationObserver( + public func modal( isModaled: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content + content: @escaping () -> NSWindow ) -> ObserveToken { modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } - @discardableResult - public func modalSession( - isModaled: UIBinding, + public func modal( + item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content + content: @escaping (Item) -> NSWindow ) -> ObserveToken { - modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + modal(item: item, id: \.id, onDismiss: onDismiss, content: content) } + @_disfavoredOverload @discardableResult - public func modal( + public func modal( item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content + content: @escaping (UIBinding) -> NSWindow ) -> ObserveToken { modal(item: item, id: \.id, onDismiss: onDismiss, content: content) } @discardableResult - public func modalSession( + public func modal( item: UIBinding, + id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content + content: @escaping (Item) -> NSWindow ) -> ObserveToken { - modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + modal(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } } - @_disfavoredOverload @discardableResult - public func modal( + public func modal( item: UIBinding, + id: KeyPath, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content + content: @escaping (UIBinding) -> NSWindow ) -> ObserveToken { - modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + _modal(item: item, id: id, onDismiss: onDismiss, content: content) } + // MARK: - Modal - NSSavePanel - @_disfavoredOverload @discardableResult - public func modalSession( - item: UIBinding, + public func modal( + isModaled: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content + content: @escaping () -> NSSavePanel + ) -> ObserveToken { + _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + // MARK: - Modal - NSAlert + + @discardableResult + public func modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSAlert + ) -> ObserveToken { + _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + // MARK: - Modal Session - NSWindow + + @discardableResult + public func modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + _modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + // MARK: - Private Modal + + @discardableResult + private func _modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content ) -> ObserveToken { - modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } - + @discardableResult - public func modal( + private func _modal( item: UIBinding, - id: KeyPath, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content ) -> ObserveToken { - modal(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) - } + _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + private func _modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) } @discardableResult - public func modalSession( + private func _modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content ) -> ObserveToken { - modalSession(item: item, id: id, onDismiss: onDismiss) { + _modal(item: item, id: id, onDismiss: onDismiss) { content($0.wrappedValue) } } @discardableResult - public func modal( + private func _modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content ) -> ObserveToken { - modal(item: item, id: id) { $item in + _modal(item: item, id: id) { $item in content($item) } beginModal: { modalContent, _ in if NSApplication.shared.modalWindow != nil { @@ -122,15 +167,55 @@ extension NSObject { onDismiss?() } } + // MARK: - Modal Session + @discardableResult + private func _modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + _modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + private func _modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + private func _modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @discardableResult + private func _modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _modalSession(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } @discardableResult - public func modalSession( + private func _modalSession( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content ) -> ObserveToken { - modal(item: item, id: id) { $item in + _modal(item: item, id: id) { $item in content($item) } beginModal: { modalContent, _ in if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] { @@ -157,7 +242,7 @@ extension NSObject { } } - private func modal( + private func _modal( item: UIBinding, id: KeyPath, content: @escaping (UIBinding) -> Content, diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift index 00772647f2..676b8857b8 100644 --- a/Sources/AppKitNavigation/Navigation/ModalContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -3,18 +3,18 @@ import AppKit @MainActor -public protocol ModalContent: NavigationContent { +protocol ModalContent: NavigationContent { @discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse var window: NSWindow { get } } extension NSWindow: ModalContent { - public var window: NSWindow { self } + var window: NSWindow { self } - public func appKitNavigationRunModal() -> NSApplication.ModalResponse { + func appKitNavigationRunModal() -> NSApplication.ModalResponse { __appKitNavigationRunModal() } - + @objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse { NSApplication.shared.runModal(for: self) } @@ -27,7 +27,7 @@ extension NSSavePanel { } extension NSAlert: ModalContent { - public func appKitNavigationRunModal() -> NSApplication.ModalResponse { + func appKitNavigationRunModal() -> NSApplication.ModalResponse { runModal() } } diff --git a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift index cc50c0afdf..a897018c9e 100644 --- a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift @@ -3,13 +3,12 @@ import AppKit @MainActor -public protocol ModalSessionContent: ModalContent { +protocol ModalSessionContent: ModalContent { func appKitNavigationBeginModalSession() -> NSApplication.ModalSession } extension NSWindow: ModalSessionContent { - - public func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { + func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { NSApplication.shared.beginModalSession(for: self) } } diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift index 762032cf09..2e35321c1b 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationContent.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -3,7 +3,7 @@ import Foundation @MainActor -public protocol NavigationContent: AnyObject { +protocol NavigationContent: AnyObject { var onBeginNavigation: (() -> Void)? { set get } var onEndNavigation: (() -> Void)? { set get } } @@ -15,7 +15,7 @@ private var onBeginNavigationKeys = AssociatedKeys() private var onEndNavigationKeys = AssociatedKeys() extension NavigationContent { - public var onBeginNavigation: (() -> Void)? { + var onBeginNavigation: (() -> Void)? { set { objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } @@ -24,7 +24,7 @@ extension NavigationContent { } } - public var onEndNavigation: (() -> Void)? { + var onEndNavigation: (() -> Void)? { set { objc_setAssociatedObject(self, onEndNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index e5f0197e7e..a9e28256fd 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -3,10 +3,7 @@ import SwiftNavigation import AppKit import AppKitNavigationShim -@MainActor -private var presentationObserverKeys = AssociatedKeys() - -class PresentationObserver: NavigationObserver { +class PresentationObserver: NavigationObserver { override func commitWork(_ work: @escaping () -> Void) { if owner._AppKitNavigation_hasViewAppeared { work() @@ -18,43 +15,43 @@ class PresentationObserver: NavigationObserver( + public func present( isPresented: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content + content: @escaping () -> NSViewController ) -> ObserveToken { present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } } @discardableResult - public func present( + public func present( item: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content + content: @escaping (Item) -> NSViewController ) -> ObserveToken { present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } @_disfavoredOverload @discardableResult - public func present( + public func present( item: UIBinding, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content + content: @escaping (UIBinding) -> NSViewController ) -> ObserveToken { present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } @discardableResult - public func present( + public func present( item: UIBinding, id: KeyPath, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content + content: @escaping (Item) -> NSViewController ) -> ObserveToken { present(item: item, id: id, style: style, onDismiss: onDismiss) { content($0.wrappedValue) @@ -63,12 +60,12 @@ extension NSViewController { @_disfavoredOverload @discardableResult - public func present( + public func present( item: UIBinding, id: KeyPath, style: TransitionStyle, onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content + content: @escaping (UIBinding) -> NSViewController ) -> ObserveToken { destination(item: item, id: id) { $item in content($item) @@ -89,12 +86,12 @@ extension NSViewController { } @discardableResult - public func destination( + public func destination( isPresented: UIBinding, - content: @escaping () -> Content, - present: @escaping (Content, UITransaction) -> Void, + content: @escaping () -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, dismiss: @escaping ( - _ child: Content, + _ child: NSViewController, _ transaction: UITransaction ) -> Void ) -> ObserveToken { @@ -107,16 +104,16 @@ extension NSViewController { } @discardableResult - public func destination( + public func destination( item: UIBinding, - content: @escaping (UIBinding) -> Content, - present: @escaping (Content, UITransaction) -> Void, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, dismiss: @escaping ( - _ child: Content, + _ child: NSViewController, _ transaction: UITransaction ) -> Void ) -> ObserveToken { - let presentationObserver: PresentationObserver = presentationObserver() + let presentationObserver: PresentationObserver = presentationObserver() return presentationObserver.observe( item: item, id: { _ in nil }, @@ -127,29 +124,31 @@ extension NSViewController { } @discardableResult - public func destination( + public func destination( item: UIBinding, id: KeyPath, - content: @escaping (UIBinding) -> Content, + content: @escaping (UIBinding) -> NSViewController, present: @escaping ( - _ child: Content, + _ child: NSViewController, _ transaction: UITransaction ) -> Void, dismiss: @escaping ( - _ child: Content, + _ child: NSViewController, _ transaction: UITransaction ) -> Void ) -> ObserveToken { - let presentationObserver: PresentationObserver = presentationObserver() + let presentationObserver: PresentationObserver = presentationObserver() return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) } - private func presentationObserver() -> PresentationObserver { - if let observer = objc_getAssociatedObject(self, presentationObserverKeys.key(of: Content.self)) as? PresentationObserver { + private static var presentationObserverKey = malloc(1)! + + private func presentationObserver() -> PresentationObserver { + if let observer = objc_getAssociatedObject(self, Self.presentationObserverKey) as? PresentationObserver { return observer } else { - let observer = PresentationObserver(owner: self) - objc_setAssociatedObject(self, presentationObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + let observer = PresentationObserver(owner: self) + objc_setAssociatedObject(self, Self.presentationObserverKey, observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) return observer } } diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift index eba08ad600..93de778e57 100644 --- a/Sources/AppKitNavigation/Navigation/PresentationContent.swift +++ b/Sources/AppKitNavigation/Navigation/PresentationContent.swift @@ -3,17 +3,17 @@ import AppKit @MainActor -public protocol PresentationContent: NavigationContent { +protocol PresentationContent: NavigationContent { func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) func dismiss(from presentingViewController: NSViewController) } extension NSViewController: PresentationContent { - public func presented(from presentingViewController: NSViewController, style: TransitionStyle) { + func presented(from presentingViewController: NSViewController, style: TransitionStyle) { presentingViewController.present(self, for: style) } - public func dismiss(from presentingViewController: NSViewController) { + func dismiss(from presentingViewController: NSViewController) { presentingViewController.dismiss(self) } diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 6ec8b0d806..ee0cda49ab 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -9,53 +9,53 @@ private var sheetObserverKeys = AssociatedKeys() extension SheetContent { @discardableResult - public func sheet( + private func _sheet( isSheeted: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content ) -> ObserveToken { - sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + _sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } } @discardableResult - public func sheet( + private func _sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content ) -> ObserveToken { - sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } @_disfavoredOverload @discardableResult - public func sheet( + private func _sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content ) -> ObserveToken { - sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) } @discardableResult - public func sheet( + private func _sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content ) -> ObserveToken { - sheet(item: item, id: id, onDismiss: onDismiss) { + _sheet(item: item, id: id, onDismiss: onDismiss) { content($0.wrappedValue) } } @discardableResult - public func sheet( + private func _sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content ) -> ObserveToken { - sheet(item: item, id: id) { $item in + _sheet(item: item, id: id) { $item in content($item) } beginSheet: { [weak self] child, _ in guard let self else { return } @@ -80,7 +80,7 @@ extension SheetContent { } } - private func sheet( + private func _sheet( item: UIBinding, id: KeyPath, content: @escaping (UIBinding) -> Content, diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index eb06919cd8..25d27c466b 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -3,56 +3,56 @@ import AppKit @MainActor -public protocol SheetContent: NavigationContent { +protocol SheetContent: NavigationContent { var currentWindow: NSWindow? { get } func beginSheet(for content: SheetContent) async func endSheet(for content: SheetContent) } extension SheetContent { - public func beginSheet(for content: any SheetContent) async { + func beginSheet(for content: any SheetContent) async { guard let sheetedWindow = content.currentWindow else { return } await currentWindow?.beginSheet(sheetedWindow) } - public func endSheet(for content: any SheetContent) { + func endSheet(for content: any SheetContent) { guard let sheetedWindow = content.currentWindow else { return } currentWindow?.endSheet(sheetedWindow) } } extension NSWindow: SheetContent { - public var currentWindow: NSWindow? { self } + var currentWindow: NSWindow? { self } } extension NSWindowController: SheetContent { - public var currentWindow: NSWindow? { window } + var currentWindow: NSWindow? { window } } extension NSViewController: SheetContent { - public var currentWindow: NSWindow? { view.window } + var currentWindow: NSWindow? { view.window } } extension NSAlert: SheetContent { - public var currentWindow: NSWindow? { window } + var currentWindow: NSWindow? { window } - public func beginSheet(for content: any SheetContent) async { + func beginSheet(for content: any SheetContent) async { guard let parentWindow = content.currentWindow else { return } await beginSheetModal(for: parentWindow) } - public func endSheet(for content: any SheetContent) { + func endSheet(for content: any SheetContent) { content.currentWindow?.endSheet(window) } } extension NSSavePanel { - public func beginSheet(for content: any SheetContent) async { + func beginSheet(for content: any SheetContent) async { guard let parentWindow = content.currentWindow else { return } await beginSheetModal(for: parentWindow) } - public func endSheet(for content: any SheetContent) { + func endSheet(for content: any SheetContent) { content.currentWindow?.endSheet(window) } } From 863c8d2d6c37462a012b78ad654fc6c6c9d274c5 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 11 Oct 2024 14:23:03 +0800 Subject: [PATCH 030/141] Completion --- .../AppKitNavigation/Navigation/Modal.swift | 189 +++++++++++++++--- .../Navigation/Presentation.swift | 26 ++- .../Navigation/PresentationContent.swift | 41 ---- .../AppKitNavigation/Navigation/Sheet.swift | 161 ++++++++++++++- .../Navigation/SheetContent.swift | 8 - 5 files changed, 339 insertions(+), 86 deletions(-) delete mode 100644 Sources/AppKitNavigation/Navigation/PresentationContent.swift diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 79075a67be..0d053d6f0d 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -7,25 +7,79 @@ private var modalObserverKeys = AssociatedKeys() private typealias ModalObserver = NavigationObserver +// MARK: - Modal Session - NSWindow @MainActor extension NSObject { - // MARK: - Modal - NSWindow + @discardableResult + public func modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + _modalSession(isModaled: isModaled, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + +// MARK: - Modal - NSWindow + +@MainActor +extension NSObject { @discardableResult public func modal( isModaled: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> NSWindow ) -> ObserveToken { - modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) } + @discardableResult public func modal( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> NSWindow ) -> ObserveToken { - modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + _modal(item: item, onDismiss: onDismiss, content: content) } @_disfavoredOverload @@ -35,7 +89,7 @@ extension NSObject { onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> NSWindow ) -> ObserveToken { - modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + _modal(item: item, onDismiss: onDismiss, content: content) } @discardableResult @@ -45,9 +99,7 @@ extension NSObject { onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> NSWindow ) -> ObserveToken { - modal(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) - } + _modal(item: item, id: id, onDismiss: onDismiss, content: content) } @discardableResult @@ -59,43 +111,120 @@ extension NSObject { ) -> ObserveToken { _modal(item: item, id: id, onDismiss: onDismiss, content: content) } - // MARK: - Modal - NSSavePanel +} +// MARK: - Modal - NSAlert + +@MainActor +extension NSObject { @discardableResult public func modal( isModaled: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSSavePanel + content: @escaping () -> NSAlert ) -> ObserveToken { - _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) } - // MARK: - Modal - NSAlert + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + +// MARK: - Modal - NSSavePanel + +@MainActor +extension NSObject { @discardableResult public func modal( isModaled: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSAlert + content: @escaping () -> NSSavePanel ) -> ObserveToken { - _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) } - // MARK: - Modal Session - NSWindow + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + @_disfavoredOverload @discardableResult - public func modalSession( - isModaled: UIBinding, + public func modal( + item: UIBinding, onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow + content: @escaping (UIBinding) -> NSSavePanel ) -> ObserveToken { - _modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) } - // MARK: - Private Modal + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + +// MARK: - Private Modal +@MainActor +extension NSObject { @discardableResult - private func _modal( + fileprivate func _modal( isModaled: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content @@ -104,7 +233,7 @@ extension NSObject { } @discardableResult - private func _modal( + fileprivate func _modal( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content @@ -114,7 +243,7 @@ extension NSObject { @_disfavoredOverload @discardableResult - private func _modal( + fileprivate func _modal( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content @@ -123,7 +252,7 @@ extension NSObject { } @discardableResult - private func _modal( + fileprivate func _modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -135,7 +264,7 @@ extension NSObject { } @discardableResult - private func _modal( + fileprivate func _modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -167,9 +296,11 @@ extension NSObject { onDismiss?() } } + // MARK: - Modal Session + @discardableResult - private func _modalSession( + fileprivate func _modalSession( isModaled: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content @@ -178,7 +309,7 @@ extension NSObject { } @discardableResult - private func _modalSession( + fileprivate func _modalSession( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content @@ -188,7 +319,7 @@ extension NSObject { @_disfavoredOverload @discardableResult - private func _modalSession( + fileprivate func _modalSession( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content @@ -197,7 +328,7 @@ extension NSObject { } @discardableResult - private func _modalSession( + fileprivate func _modalSession( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -209,7 +340,7 @@ extension NSObject { } @discardableResult - private func _modalSession( + fileprivate func _modalSession( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index a9e28256fd..fbd5f46777 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -74,13 +74,13 @@ extension NSViewController { if let presentedViewController = presentedViewControllers?.first { self.dismiss(presentedViewController) onDismiss?() - child.presented(from: self, style: style) + self.present(child, for: style) } else { - child.presented(from: self, style: style) + self.present(child, for: style) } } dismiss: { [weak self] child, transaction in guard let self else { return } - child.dismiss(from: self) + self.dismiss(child) onDismiss?() } } @@ -152,6 +152,26 @@ extension NSViewController { return observer } } + + public enum TransitionStyle { + case sheet + case modalWindow + case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + case custom(NSViewControllerPresentationAnimator) + } + + private func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { + switch style { + case .sheet: + presentAsSheet(viewControllerToPresent) + case .modalWindow: + presentAsModalWindow(viewControllerToPresent) + case let .popover(rect, view, preferredEdge, behavior): + present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) + case let .custom(animator): + present(viewControllerToPresent, animator: animator) + } + } } extension NavigationContent where Self: NSViewController { diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift deleted file mode 100644 index 93de778e57..0000000000 --- a/Sources/AppKitNavigation/Navigation/PresentationContent.swift +++ /dev/null @@ -1,41 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -@MainActor -protocol PresentationContent: NavigationContent { - func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) - func dismiss(from presentingViewController: NSViewController) -} - -extension NSViewController: PresentationContent { - func presented(from presentingViewController: NSViewController, style: TransitionStyle) { - presentingViewController.present(self, for: style) - } - - func dismiss(from presentingViewController: NSViewController) { - presentingViewController.dismiss(self) - } - - public enum TransitionStyle { - case sheet - case modalWindow - case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) - case custom(NSViewControllerPresentationAnimator) - } - - private func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { - switch style { - case .sheet: - presentAsSheet(viewControllerToPresent) - case .modalWindow: - presentAsModalWindow(viewControllerToPresent) - case let .popover(rect, view, preferredEdge, behavior): - present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) - case let .custom(animator): - present(viewControllerToPresent, animator: animator) - } - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index ee0cda49ab..ba9cbd1846 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -7,9 +7,160 @@ private typealias SheetObserver, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + +extension NSWindow { + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSAlert + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + +extension NSWindow { + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSSavePanel + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + + extension SheetContent { @discardableResult - private func _sheet( + fileprivate func _sheet( isSheeted: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content @@ -18,7 +169,7 @@ extension SheetContent { } @discardableResult - private func _sheet( + fileprivate func _sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content @@ -28,7 +179,7 @@ extension SheetContent { @_disfavoredOverload @discardableResult - private func _sheet( + fileprivate func _sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content @@ -37,7 +188,7 @@ extension SheetContent { } @discardableResult - private func _sheet( + fileprivate func _sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -49,7 +200,7 @@ extension SheetContent { } @discardableResult - private func _sheet( + fileprivate func _sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index 25d27c466b..3da396258f 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -25,14 +25,6 @@ extension NSWindow: SheetContent { var currentWindow: NSWindow? { self } } -extension NSWindowController: SheetContent { - var currentWindow: NSWindow? { window } -} - -extension NSViewController: SheetContent { - var currentWindow: NSWindow? { view.window } -} - extension NSAlert: SheetContent { var currentWindow: NSWindow? { window } From 2963dd1faae5afd40e71ebc0a54b1b6916e0b66a Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Fri, 11 Oct 2024 14:50:33 +0800 Subject: [PATCH 031/141] Fixes --- Package.swift | 2 +- Package@swift-6.0.swift | 2 + .../Bindings/NSColorPanel.swift | 6 +- .../AppKitNavigation/Bindings/NSControl.swift | 12 +- .../Bindings/NSFontManager.swift | 202 ++++++++++++++++-- .../Bindings/NSMenuItem.swift | 12 +- .../Bindings/NSTextField.swift | 4 +- .../Bindings/NSToolbarItem.swift | 17 -- ...ction.swift => TargetActionProtocol.swift} | 35 ++- ...ionProxy.swift => TargetActionProxy.swift} | 14 +- 10 files changed, 219 insertions(+), 87 deletions(-) delete mode 100755 Sources/AppKitNavigation/Bindings/NSToolbarItem.swift rename Sources/AppKitNavigation/Bindings/{NSTargetAction.swift => TargetActionProtocol.swift} (79%) rename Sources/AppKitNavigation/Bindings/{NSTargetActionProxy.swift => TargetActionProxy.swift} (85%) diff --git a/Package.swift b/Package.swift index 2fb60be222..d8e88c6c6d 100644 --- a/Package.swift +++ b/Package.swift @@ -85,7 +85,7 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", - .product(name: "IdentifiedCollections", package: "swift-identified-collections") + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 169fd95403..5db189cb1a 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -36,6 +36,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.2.2"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), ], targets: [ .target( @@ -84,6 +85,7 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index d2287caf93..36715c56cd 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -2,13 +2,13 @@ import AppKit -extension NSColorPanel: NSTargetActionProtocol { - public var appkitNavigationTarget: AnyObject? { +extension NSColorPanel: TargetActionProtocol { + public var target: AnyObject? { set { setTarget(newValue) } get { value(forKeyPath: "target") as? AnyObject } } - public var appkitNavigationAction: Selector? { + public var action: Selector? { set { setAction(newValue) } get { value(forKeyPath: "action") as? Selector } } diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index 7edc6aaef2..05b5f7fa13 100755 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -2,17 +2,7 @@ import AppKit -extension NSControl: NSTargetActionProtocol { - public var appkitNavigationTarget: AnyObject? { - set { target = newValue } - get { target } - } - - public var appkitNavigationAction: Selector? { - set { action = newValue } - get { action } - } -} +extension NSControl: TargetActionProtocol {} extension NSControl { public convenience init(action: @escaping (Self) -> Void) { diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 9797d82ae6..51944e85ac 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -1,19 +1,12 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) +import ConcurrencyExtras +@_spi(Internals) import SwiftNavigation import AppKit -import SwiftNavigation - -extension NSFontManager: NSTargetActionProtocol, @unchecked Sendable { - public var appkitNavigationTarget: AnyObject? { - set { appkitNavigationDelegate.target = newValue } - get { appkitNavigationDelegate.target } - } - - public var appkitNavigationAction: Selector? { - set { appkitNavigationDelegate.action = newValue } - get { appkitNavigationDelegate.action } - } +import IdentifiedCollections +extension NSFontManager: @unchecked Sendable { + private static let appkitNavigationDelegateKey = malloc(1)! private var appkitNavigationDelegate: Delegate { @@ -74,4 +67,189 @@ extension NSFontManager { } } + +@MainActor +extension NSFontManager { + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: ReferenceWritableKeyPath + ) -> ObserveToken { + bind(binding, to: keyPath) { control, newValue, _ in + control[keyPath: keyPath] = newValue + } + } + + private var actionProxy: FontManagerProxy? { + set { + objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, actionProxyKey) as? FontManagerProxy + } + } + + private func createActionProxyIfNeeded() -> FontManagerProxy { + if let actionProxy { + return actionProxy + } else { + let actionProxy = FontManagerProxy(owner: self) + self.actionProxy = actionProxy + return actionProxy + } + } + + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - set: A closure that is called when the binding's value changes with a weakly-captured + /// control, a new value that can be used to configure the control, and a transaction, which + /// can be used to determine how and if the change should be animated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: KeyPath, + set: @escaping (_ control: NSFontManager, _ newValue: Value, _ transaction: UITransaction) -> Void + ) -> ObserveToken { + unbind(keyPath) + let actionProxy = createActionProxyIfNeeded() + let actionID = actionProxy.addBindingAction { [weak self] _ in + guard let self else { return } + binding.wrappedValue = self[keyPath: keyPath] + } + + let isSetting = LockIsolated(false) + let token = observe { [weak self] transaction in + guard let self else { return } + isSetting.withValue { $0 = true } + defer { isSetting.withValue { $0 = false } } + set( + self, + binding.wrappedValue, + transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + @UncheckedSendable var uncheckedKeyPath = keyPath + let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in + guard isSetting.withValue({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + } + } + let observationToken = ObserveToken { [weak self] in + MainActor._assumeIsolated { + self?.actionProxy?.removeAction(for: actionID) + } + token.cancel() + observation.invalidate() + } + observationTokens[keyPath] = observationToken + return observationToken + } + + public func unbind(_ keyPath: KeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } +} + + +@MainActor +private let observationTokensKey = malloc(1)! +@MainActor +private let actionProxyKey = malloc(1)! + +@MainActor +private class FontManagerProxy: NSObject { + typealias ActionClosure = (Any?) -> Void + + typealias ActionIdentifier = UUID + + private struct Action: Identifiable { + let id = UUID() + + var closure: ActionClosure + + func invoke(_ sender: Any?) { + closure(sender) + } + } + + private var bindingActions: IdentifiedArrayOf = [] + + private var actions: IdentifiedArrayOf = [] + + private var originTarget: AnyObject? + + private var originAction: Selector? + + weak var owner: NSFontManager? + + required init(owner: NSFontManager) { + self.owner = owner + super.init() + self.originTarget = owner.target + self.originAction = owner.action + owner.target = self + owner.action = #selector(invokeAction(_:)) + } + + @objc func controlTextDidChange(_ obj: Notification) { + bindingActions.forEach { $0.invoke(obj.object) } + actions.forEach { $0.invoke(obj.object) } + } + + @objc func invokeAction(_ sender: Any?) { + if let originTarget, let originAction { + NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) + } + bindingActions.forEach { $0.invoke(sender) } + actions.forEach { $0.invoke(sender) } + } + + @discardableResult + func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { + let action = Action(closure: actionClosure) + actions.append(action) + return action.id + } + + func removeAction(for id: ActionIdentifier) { + actions.remove(id: id) + } + + func removeAllActions() { + actions.removeAll() + } + + @discardableResult + func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { + let bindingAction = Action(closure: bindingActionClosure) + bindingActions.append(bindingAction) + return bindingAction.id + } + + func removeBindingAction(for id: ActionIdentifier) { + bindingActions.remove(id: id) + } + + func removeAllBindingActions() { + bindingActions.removeAll() + } +} + #endif diff --git a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift index 25d7dd5c0a..01bb9ac88b 100755 --- a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift +++ b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift @@ -2,16 +2,6 @@ import AppKit -extension NSMenuItem: NSTargetActionProtocol, @unchecked Sendable { - public var appkitNavigationTarget: AnyObject? { - set { target = newValue } - get { target } - } - - public var appkitNavigationAction: Selector? { - set { action = newValue } - get { action } - } -} +extension NSMenuItem: TargetActionProtocol, @unchecked Sendable {} #endif diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 897efc8417..96a45cf170 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -72,7 +72,7 @@ extension NSTextField: NSTextViewDelegate { } } - let observationToken = ObservationToken { [weak self] in + let observationToken = ObserveToken { [weak self] in MainActor._assumeIsolated { editingChangedAction.cancel() editingDidEndAction.cancel() @@ -242,7 +242,7 @@ extension NSTextField: NSTextViewDelegate { break } } - let outerToken = ObservationToken { + let outerToken = ObserveToken { editingDidBeginAction.cancel() editingDidEndAction.cancel() innerToken.cancel() diff --git a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift deleted file mode 100755 index 478253a51e..0000000000 --- a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift +++ /dev/null @@ -1,17 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -extension NSToolbarItem: NSTargetActionProtocol { - public var appkitNavigationTarget: AnyObject? { - set { target = newValue } - get { target } - } - - public var appkitNavigationAction: Selector? { - set { action = newValue } - get { action } - } -} - -#endif diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift similarity index 79% rename from Sources/AppKitNavigation/Bindings/NSTargetAction.swift rename to Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index 1d72abb4eb..c7bbedb5c6 100755 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -5,12 +5,12 @@ import AppKit /// A protocol used to extend `NSControl, NSMenuItem...`. @MainActor -public protocol NSTargetActionProtocol: NSObject, Sendable { - var appkitNavigationTarget: AnyObject? { set get } - var appkitNavigationAction: Selector? { set get } +public protocol TargetActionProtocol: NSObject, Sendable { + var target: AnyObject? { set get } + var action: Selector? { set get } } -extension NSTargetActionProtocol { +extension TargetActionProtocol { /// Establishes a two-way connection between a source of truth and a property of this control. /// /// - Parameters: @@ -28,20 +28,20 @@ extension NSTargetActionProtocol { } } - var actionProxy: NSTargetActionProxy? { + var actionProxy: TargetActionProxy? { set { objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } get { - objc_getAssociatedObject(self, actionProxyKey) as? NSTargetActionProxy + objc_getAssociatedObject(self, actionProxyKey) as? TargetActionProxy } } - func createActionProxyIfNeeded() -> NSTargetActionProxy { + func createActionProxyIfNeeded() -> TargetActionProxy { if let actionProxy { return actionProxy } else { - let actionProxy = NSTargetActionProxy(owner: self) + let actionProxy = TargetActionProxy(owner: self) self.actionProxy = actionProxy return actionProxy } @@ -62,7 +62,7 @@ extension NSTargetActionProtocol { _ binding: UIBinding, to keyPath: KeyPath, set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void - ) -> ObservationToken { + ) -> ObserveToken { unbind(keyPath) let actionProxy = createActionProxyIfNeeded() let actionID = actionProxy.addBindingAction { [weak self] _ in @@ -91,7 +91,7 @@ extension NSTargetActionProtocol { binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] } } - let observationToken = ObservationToken { [weak self] in + let observationToken = ObserveToken { [weak self] in MainActor._assumeIsolated { self?.actionProxy?.removeAction(for: actionID) } @@ -107,24 +107,13 @@ extension NSTargetActionProtocol { observationTokens[keyPath] = nil } -// var observationTokens: [AnyKeyPath: ObservationToken] { -// get { -// objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] -// ?? [:] -// } -// set { -// objc_setAssociatedObject( -// self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC -// ) -// } -// } } @MainActor extension NSObject { - var observationTokens: [AnyKeyPath: ObservationToken] { + var observationTokens: [AnyKeyPath: ObserveToken] { get { - objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] + objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObserveToken] ?? [:] } set { diff --git a/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift similarity index 85% rename from Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift rename to Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 2d2054d0ec..c7e82fb291 100755 --- a/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -4,7 +4,7 @@ import AppKit import IdentifiedCollections @MainActor -class NSTargetActionProxy: NSObject { +class TargetActionProxy: NSObject { typealias ActionClosure = (Any?) -> Void typealias ActionIdentifier = UUID @@ -27,15 +27,15 @@ class NSTargetActionProxy: NSObject { private var originAction: Selector? - weak var owner: NSTargetActionProtocol? + weak var owner: TargetActionProtocol? - required init(owner: NSTargetActionProtocol) { + required init(owner: TargetActionProtocol) { self.owner = owner super.init() - self.originTarget = owner.appkitNavigationTarget - self.originAction = owner.appkitNavigationAction - owner.appkitNavigationTarget = self - owner.appkitNavigationAction = #selector(invokeAction(_:)) + self.originTarget = owner.target + self.originAction = owner.action + owner.target = self + owner.action = #selector(invokeAction(_:)) if let textField = owner as? NSTextField { NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) } From 9d0df7e6732ee86bf6e53dc122930c0a65b87aad Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Sun, 1 Dec 2024 02:20:55 +0800 Subject: [PATCH 032/141] Fix errors --- Sources/AppKitNavigation/Bindings/NSColorPanel.swift | 1 + Sources/AppKitNavigation/Bindings/NSControl.swift | 1 + Sources/AppKitNavigation/Bindings/NSFontManager.swift | 5 +++-- Sources/AppKitNavigation/Bindings/NSMenuItem.swift | 2 +- Sources/AppKitNavigation/Bindings/NSTextField.swift | 5 +++-- 5 files changed, 9 insertions(+), 5 deletions(-) diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index 36715c56cd..79adfd1851 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -2,6 +2,7 @@ import AppKit +extension NSColorPanel: @retroactive Sendable {} extension NSColorPanel: TargetActionProtocol { public var target: AnyObject? { set { setTarget(newValue) } diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index 05b5f7fa13..33ae9d4348 100755 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -2,6 +2,7 @@ import AppKit +extension NSControl: @retroactive Sendable {} extension NSControl: TargetActionProtocol {} extension NSControl { diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 51944e85ac..01bc6b00ca 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -5,9 +5,10 @@ import ConcurrencyExtras import AppKit import IdentifiedCollections -extension NSFontManager: @unchecked Sendable { +@MainActor +extension NSFontManager: @unchecked @retroactive Sendable { - private static let appkitNavigationDelegateKey = malloc(1)! + private static let appkitNavigationDelegateKey = malloc(1)! private var appkitNavigationDelegate: Delegate { set { diff --git a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift index 01bb9ac88b..663c1302e9 100755 --- a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift +++ b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift @@ -2,6 +2,6 @@ import AppKit -extension NSMenuItem: TargetActionProtocol, @unchecked Sendable {} +extension NSMenuItem: TargetActionProtocol, @unchecked @retroactive Sendable {} #endif diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 96a45cf170..8b9182aa08 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -4,7 +4,8 @@ import Combine import SwiftNavigation @MainActor -extension NSTextField: NSTextViewDelegate { +extension NSTextField: @retroactive NSTextDelegate {} +extension NSTextField: @retroactive NSTextViewDelegate { /// Creates a new text field with the specified frame and registers the binding against its /// text. /// @@ -337,6 +338,6 @@ public struct AppKitTextSelection: Hashable, Sendable { } } -extension AnyCancellable: @unchecked Sendable {} +extension AnyCancellable: @unchecked @retroactive Sendable {} #endif From 567a607430cf40f796f6a300f3464ff63fbc6f66 Mon Sep 17 00:00:00 2001 From: Mx-Iris <61279231+Mx-Iris@users.noreply.github.com> Date: Tue, 4 Feb 2025 15:36:43 +0800 Subject: [PATCH 033/141] Merge upstream main branch --- Examples/Examples.xcodeproj/project.pbxproj | 1 - .../AppKitNavigation/AppKitAnimation.swift | 2 +- .../Bindings/NSTargetAction.swift | 143 ---- .../Bindings/NSTargetActionProxy.swift | 88 --- .../Bindings/NSToolbarItem.swift | 13 +- .../Bindings/TargetActionProxy.swift | 126 +-- .../Internal/AssociatedKeys.swift | 42 +- .../Internal/AssumeIsolated.swift | 35 - .../Internal/ErrorMechanism.swift | 20 - .../AppKitNavigation/Internal/Exports.swift | 2 +- .../Internal/ModalWindowsObserver.swift | 33 + .../Internal/ToOptionalUnit.swift | 12 - .../AppKitNavigation/Navigation/Modal.swift | 740 +++++++++--------- .../Navigation/ModalContent.swift | 41 +- .../Navigation/ModalSession.swift | 7 - .../Navigation/ModalSessionContent.swift | 16 - .../Navigation/ModalWindowsObserver.swift | 33 - .../Navigation/NavigationContent.swift | 33 +- .../Navigation/NavigationObserver.swift | 130 +-- .../Navigation/Presentation.swift | 304 ++++--- .../Navigation/PresentationContent.swift | 52 +- .../AppKitNavigation/Navigation/Sheet.swift | 455 ++++++----- .../Navigation/SheetContent.swift | 58 +- Sources/AppKitNavigation/Observe.swift | 181 ----- Sources/AppKitNavigationShim/shim.m | 2 + .../xcshareddata/swiftpm/Package.resolved | 39 +- 26 files changed, 1044 insertions(+), 1564 deletions(-) delete mode 100644 Sources/AppKitNavigation/Bindings/NSTargetAction.swift delete mode 100644 Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift delete mode 100644 Sources/AppKitNavigation/Internal/AssumeIsolated.swift delete mode 100644 Sources/AppKitNavigation/Internal/ErrorMechanism.swift create mode 100644 Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift delete mode 100644 Sources/AppKitNavigation/Internal/ToOptionalUnit.swift delete mode 100644 Sources/AppKitNavigation/Navigation/ModalSession.swift delete mode 100644 Sources/AppKitNavigation/Navigation/ModalSessionContent.swift delete mode 100644 Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift delete mode 100644 Sources/AppKitNavigation/Observe.swift diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index 74a5badb07..ac06aec67b 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -1176,7 +1176,6 @@ isa = XCSwiftPackageProductDependency; productName = SwiftUINavigation; }; ->>>>>>> origin/appkit-navigation-bindings /* End XCSwiftPackageProductDependency section */ }; rootObject = CA47378C272F08EF0012CAC3 /* Project object */; diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 7d469824ea..096761ab34 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -52,8 +52,8 @@ return try result!._rethrowGet() case let .swiftUI(animation): + var result: Swift.Result? #if swift(>=6) - var result: Swift.Result? if #available(macOS 15, *) { NSAnimationContext.animate(animation) { result = Swift.Result(catching: body) diff --git a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift b/Sources/AppKitNavigation/Bindings/NSTargetAction.swift deleted file mode 100644 index fb6e9553fa..0000000000 --- a/Sources/AppKitNavigation/Bindings/NSTargetAction.swift +++ /dev/null @@ -1,143 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -import ConcurrencyExtras -@_spi(Internals) import SwiftNavigation -import AppKit - -/// A protocol used to extend `NSControl, NSMenuItem...`. -@MainActor -public protocol NSTargetActionProtocol: NSObject, Sendable { - var appkitNavigationTarget: AnyObject? { set get } - var appkitNavigationAction: Selector? { set get } -} - -extension NSTargetActionProtocol { - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: ReferenceWritableKeyPath - ) -> ObservationToken { - bind(binding, to: keyPath) { control, newValue, _ in - control[keyPath: keyPath] = newValue - } - } - - var actionProxy: NSTargetActionProxy? { - set { - objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - objc_getAssociatedObject(self, actionProxyKey) as? NSTargetActionProxy - } - } - - func createActionProxyIfNeeded() -> NSTargetActionProxy { - if let actionProxy { - return actionProxy - } else { - let actionProxy = NSTargetActionProxy(owner: self) - self.actionProxy = actionProxy - return actionProxy - } - } - - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - set: A closure that is called when the binding's value changes with a weakly-captured - /// control, a new value that can be used to configure the control, and a transaction, which - /// can be used to determine how and if the change should be animated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: KeyPath, - set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void - ) -> ObservationToken { - unbind(keyPath) - let actionProxy = createActionProxyIfNeeded() - let actionID = actionProxy.addBindingAction { [weak self] _ in - guard let self else { return } - binding.wrappedValue = self[keyPath: keyPath] - } - - let isSetting = LockIsolated(false) - let token = observe { [weak self] transaction in - guard let self else { return } - isSetting.withValue { $0 = true } - defer { isSetting.withValue { $0 = false } } - set( - self, - binding.wrappedValue, - transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations - ? binding.transaction - : transaction - ) - } - // NB: This key path must only be accessed on the main actor - @UncheckedSendable var uncheckedKeyPath = keyPath - let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in - guard isSetting.withValue({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] - } - } - let observationToken = ObservationToken { [weak self] in - MainActor._assumeIsolated { - self?.actionProxy?.removeAction(for: actionID) - } - token.cancel() - observation.invalidate() - } - observationTokens[keyPath] = observationToken - return observationToken - } - - public func unbind(_ keyPath: KeyPath) { - observationTokens[keyPath]?.cancel() - observationTokens[keyPath] = nil - } - -// var observationTokens: [AnyKeyPath: ObservationToken] { -// get { -// objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] -// ?? [:] -// } -// set { -// objc_setAssociatedObject( -// self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC -// ) -// } -// } -} - -@MainActor -extension NSObject { - var observationTokens: [AnyKeyPath: ObservationToken] { - get { - objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObservationToken] - ?? [:] - } - set { - objc_setAssociatedObject( - self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } - } -} - -@MainActor -private let observationTokensKey = malloc(1)! -@MainActor -private let actionProxyKey = malloc(1)! - -#endif diff --git a/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift deleted file mode 100644 index 2d2054d0ec..0000000000 --- a/Sources/AppKitNavigation/Bindings/NSTargetActionProxy.swift +++ /dev/null @@ -1,88 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit -import IdentifiedCollections - -@MainActor -class NSTargetActionProxy: NSObject { - typealias ActionClosure = (Any?) -> Void - - typealias ActionIdentifier = UUID - - private struct Action: Identifiable { - let id = UUID() - - var closure: ActionClosure - - func invoke(_ sender: Any?) { - closure(sender) - } - } - - private var bindingActions: IdentifiedArrayOf = [] - - private var actions: IdentifiedArrayOf = [] - - private var originTarget: AnyObject? - - private var originAction: Selector? - - weak var owner: NSTargetActionProtocol? - - required init(owner: NSTargetActionProtocol) { - self.owner = owner - super.init() - self.originTarget = owner.appkitNavigationTarget - self.originAction = owner.appkitNavigationAction - owner.appkitNavigationTarget = self - owner.appkitNavigationAction = #selector(invokeAction(_:)) - if let textField = owner as? NSTextField { - NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) - } - } - - @objc func controlTextDidChange(_ obj: Notification) { - bindingActions.forEach { $0.invoke(obj.object) } - actions.forEach { $0.invoke(obj.object) } - } - - @objc func invokeAction(_ sender: Any?) { - if let originTarget, let originAction { - NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) - } - bindingActions.forEach { $0.invoke(sender) } - actions.forEach { $0.invoke(sender) } - } - - @discardableResult - func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { - let action = Action(closure: actionClosure) - actions.append(action) - return action.id - } - - func removeAction(for id: ActionIdentifier) { - actions.remove(id: id) - } - - func removeAllActions() { - actions.removeAll() - } - - @discardableResult - func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { - let bindingAction = Action(closure: bindingActionClosure) - bindingActions.append(bindingAction) - return bindingAction.id - } - - func removeBindingAction(for id: ActionIdentifier) { - bindingActions.remove(id: id) - } - - func removeAllBindingActions() { - bindingActions.removeAll() - } -} - -#endif diff --git a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift index 478253a51e..e90fec934d 100644 --- a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift +++ b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift @@ -2,16 +2,7 @@ import AppKit -extension NSToolbarItem: NSTargetActionProtocol { - public var appkitNavigationTarget: AnyObject? { - set { target = newValue } - get { target } - } - - public var appkitNavigationAction: Selector? { - set { action = newValue } - get { action } - } -} +extension NSToolbarItem: @retroactive Sendable {} +extension NSToolbarItem: TargetActionProtocol {} #endif diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index c7e82fb291..961235ff1e 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -5,84 +5,84 @@ import IdentifiedCollections @MainActor class TargetActionProxy: NSObject { - typealias ActionClosure = (Any?) -> Void + typealias ActionClosure = (Any?) -> Void - typealias ActionIdentifier = UUID + typealias ActionIdentifier = UUID - private struct Action: Identifiable { - let id = UUID() + private struct Action: Identifiable { + let id = UUID() - var closure: ActionClosure + var closure: ActionClosure - func invoke(_ sender: Any?) { - closure(sender) - } + func invoke(_ sender: Any?) { + closure(sender) } + } - private var bindingActions: IdentifiedArrayOf = [] + private var bindingActions: IdentifiedArrayOf = [] - private var actions: IdentifiedArrayOf = [] + private var actions: IdentifiedArrayOf = [] - private var originTarget: AnyObject? + private var originTarget: AnyObject? - private var originAction: Selector? + private var originAction: Selector? - weak var owner: TargetActionProtocol? + weak var owner: TargetActionProtocol? - required init(owner: TargetActionProtocol) { - self.owner = owner - super.init() - self.originTarget = owner.target - self.originAction = owner.action - owner.target = self - owner.action = #selector(invokeAction(_:)) - if let textField = owner as? NSTextField { - NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) - } + required init(owner: TargetActionProtocol) { + self.owner = owner + super.init() + self.originTarget = owner.target + self.originAction = owner.action + owner.target = self + owner.action = #selector(invokeAction(_:)) + if let textField = owner as? NSTextField { + NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) } + } - @objc func controlTextDidChange(_ obj: Notification) { - bindingActions.forEach { $0.invoke(obj.object) } - actions.forEach { $0.invoke(obj.object) } - } - - @objc func invokeAction(_ sender: Any?) { - if let originTarget, let originAction { - NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) - } - bindingActions.forEach { $0.invoke(sender) } - actions.forEach { $0.invoke(sender) } - } - - @discardableResult - func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { - let action = Action(closure: actionClosure) - actions.append(action) - return action.id - } - - func removeAction(for id: ActionIdentifier) { - actions.remove(id: id) - } - - func removeAllActions() { - actions.removeAll() - } - - @discardableResult - func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { - let bindingAction = Action(closure: bindingActionClosure) - bindingActions.append(bindingAction) - return bindingAction.id - } - - func removeBindingAction(for id: ActionIdentifier) { - bindingActions.remove(id: id) - } + @objc func controlTextDidChange(_ obj: Notification) { + bindingActions.forEach { $0.invoke(obj.object) } + actions.forEach { $0.invoke(obj.object) } + } - func removeAllBindingActions() { - bindingActions.removeAll() + @objc func invokeAction(_ sender: Any?) { + if let originTarget, let originAction { + NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } + bindingActions.forEach { $0.invoke(sender) } + actions.forEach { $0.invoke(sender) } + } + + @discardableResult + func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { + let action = Action(closure: actionClosure) + actions.append(action) + return action.id + } + + func removeAction(for id: ActionIdentifier) { + actions.remove(id: id) + } + + func removeAllActions() { + actions.removeAll() + } + + @discardableResult + func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { + let bindingAction = Action(closure: bindingActionClosure) + bindingActions.append(bindingAction) + return bindingAction.id + } + + func removeBindingAction(for id: ActionIdentifier) { + bindingActions.remove(id: id) + } + + func removeAllBindingActions() { + bindingActions.removeAll() + } } #endif diff --git a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift index 1df9f50edc..f1398d8c8c 100644 --- a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift +++ b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift @@ -3,34 +3,34 @@ import AppKit struct AssociatedKeys { - var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] - - mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { - let key = AnyHashableMetatype(type) - if let associatedKey = keys[key] { - return associatedKey - } else { - let associatedKey = malloc(1)! - keys[key] = associatedKey - return associatedKey - } + var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] + + mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { + let key = AnyHashableMetatype(type) + if let associatedKey = keys[key] { + return associatedKey + } else { + let associatedKey = malloc(1)! + keys[key] = associatedKey + return associatedKey } + } } struct AnyHashableMetatype: Hashable { - static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { - return lhs.base == rhs.base - } + static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { + return lhs.base == rhs.base + } - let base: Any.Type + let base: Any.Type - init(_ base: Any.Type) { - self.base = base - } + init(_ base: Any.Type) { + self.base = base + } - func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(base)) - } + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(base)) + } } #endif diff --git a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift b/Sources/AppKitNavigation/Internal/AssumeIsolated.swift deleted file mode 100644 index 93f1c40098..0000000000 --- a/Sources/AppKitNavigation/Internal/AssumeIsolated.swift +++ /dev/null @@ -1,35 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import Foundation - -extension MainActor { - // NB: This functionality was not back-deployed in Swift 5.9 - static func _assumeIsolated( - _ operation: @MainActor () throws -> T, - file: StaticString = #fileID, - line: UInt = #line - ) rethrows -> T { - #if swift(<5.10) - typealias YesActor = @MainActor () throws -> T - typealias NoActor = () throws -> T - - guard Thread.isMainThread else { - fatalError( - "Incorrect actor executor assumption; Expected same executor as \(self).", - file: file, - line: line - ) - } - - return try withoutActuallyEscaping(operation) { (_ fn: @escaping YesActor) throws -> T in - let rawFn = unsafeBitCast(fn, to: NoActor.self) - return try rawFn() - } - #else - return try assumeIsolated(operation, file: file, line: line) - #endif - } -} - - -#endif diff --git a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift b/Sources/AppKitNavigation/Internal/ErrorMechanism.swift deleted file mode 100644 index 1ec4c47b0a..0000000000 --- a/Sources/AppKitNavigation/Internal/ErrorMechanism.swift +++ /dev/null @@ -1,20 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -@rethrows -protocol _ErrorMechanism { - associatedtype Output - func get() throws -> Output -} - -extension _ErrorMechanism { - func _rethrowError() rethrows -> Never { - _ = try _rethrowGet() - fatalError() - } - - func _rethrowGet() rethrows -> Output { - return try get() - } -} - -extension Result: _ErrorMechanism {} -#endif diff --git a/Sources/AppKitNavigation/Internal/Exports.swift b/Sources/AppKitNavigation/Internal/Exports.swift index 6f94b2acad..554225adc1 100644 --- a/Sources/AppKitNavigation/Internal/Exports.swift +++ b/Sources/AppKitNavigation/Internal/Exports.swift @@ -1,3 +1,3 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - @_exported import SwiftNavigation +@_exported import SwiftNavigation #endif diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift new file mode 100644 index 0000000000..a95607191e --- /dev/null +++ b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift @@ -0,0 +1,33 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import Combine + +@MainActor +class ModalWindowsObserver: NSObject { + static let shared = ModalWindowsObserver() + + var windowsCancellable: [NSWindow: AnyCancellable] = [:] + + var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:] + + func observeWindow(_ window: NSWindow, modalSession: NSApplication.ModalSession? = nil) { + if let modalSession { + modalSessionByWindow[window] = modalSession + } + windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) + .sink { [weak self] _ in + guard let self else { return } + if let modalSession = modalSessionByWindow[window] { + NSApplication.shared.endModalSession(modalSession) + } else if NSApplication.shared.modalWindow === window { + NSApplication.shared.stopModal() + } + modalSessionByWindow.removeValue(forKey: window) + windowsCancellable[window]?.cancel() + windowsCancellable.removeValue(forKey: window) + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift b/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift deleted file mode 100644 index a11cfaaf1d..0000000000 --- a/Sources/AppKitNavigation/Internal/ToOptionalUnit.swift +++ /dev/null @@ -1,12 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -extension Bool { - struct Unit: Hashable, Identifiable { - var id: Unit { self } - } - - var toOptionalUnit: Unit? { - get { self ? Unit() : nil } - set { self = newValue != nil } - } -} -#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 0d053d6f0d..6ac702ac14 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -3,414 +3,414 @@ import AppKit @MainActor -private var modalObserverKeys = AssociatedKeys() +private var ModalObserverKeys = AssociatedKeys() private typealias ModalObserver = NavigationObserver // MARK: - Modal Session - NSWindow + @MainActor extension NSObject { - - @discardableResult - public func modalSession( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow - ) -> ObserveToken { - _modalSession(isModaled: isModaled, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + _modalSession(isModaled: isModaled, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) + } } // MARK: - Modal - NSWindow @MainActor extension NSObject { - @discardableResult - public func modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow - ) -> ObserveToken { - _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } } // MARK: - Modal - NSAlert @MainActor extension NSObject { - @discardableResult - public func modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSAlert - ) -> ObserveToken { - _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSAlert + ) -> ObserveToken { + _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } } // MARK: - Modal - NSSavePanel @MainActor extension NSObject { - @discardableResult - public func modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSSavePanel - ) -> ObserveToken { - _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSSavePanel + ) -> ObserveToken { + _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss, content: content) + } } // MARK: - Private Modal + @MainActor extension NSObject { - - @discardableResult - fileprivate func _modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content - ) -> ObserveToken { - _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } - } - - @discardableResult - fileprivate func _modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - fileprivate func _modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) - } - - @discardableResult - fileprivate func _modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) + @discardableResult + fileprivate func _modal( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + fileprivate func _modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + fileprivate func _modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @discardableResult + fileprivate func _modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _modal(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + @discardableResult + fileprivate func _modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _modal(item: item, id: id) { $item in + content($item) + } beginModal: { modalContent, _ in + if NSApplication.shared.modalWindow != nil { + NSApplication.shared.stopModal() + onDismiss?() + DispatchQueue.main.async { + ModalWindowsObserver.shared.observeWindow(modalContent.window) + modalContent.appKitNavigationRunModal() + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil } - } - @discardableResult - fileprivate func _modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modal(item: item, id: id) { $item in - content($item) - } beginModal: { modalContent, _ in - if NSApplication.shared.modalWindow != nil { - NSApplication.shared.stopModal() - onDismiss?() - DispatchQueue.main.async { - ModalWindowsObserver.shared.observeWindow(modalContent.window) - modalContent.appKitNavigationRunModal() - modalContent.onEndNavigation?() - modalContent.onEndNavigation = nil - } - - } else { - DispatchQueue.main.async { - ModalWindowsObserver.shared.observeWindow(modalContent.window) - modalContent.appKitNavigationRunModal() - modalContent.onEndNavigation?() - modalContent.onEndNavigation = nil - } - } - } endModal: { _, _ in - NSApplication.shared.stopModal() - onDismiss?() + } else { + DispatchQueue.main.async { + ModalWindowsObserver.shared.observeWindow(modalContent.window) + modalContent.appKitNavigationRunModal() + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil } - } - - // MARK: - Modal Session - - @discardableResult - fileprivate func _modalSession( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content - ) -> ObserveToken { - _modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } - } - - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) - } - - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modalSession(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) - } - } - - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modal(item: item, id: id) { $item in - content($item) - } beginModal: { modalContent, _ in - if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] { - NSApplication.shared.endModalSession(modalSession) - modaledWindow.window.close() - onDismiss?() - DispatchQueue.main.async { - let modalSession = modalContent.appKitNavigationBeginModalSession() - ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) - } - - } else { - DispatchQueue.main.async { - let modalSession = modalContent.appKitNavigationBeginModalSession() - ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) - } - } - } endModal: { modalContent, _ in - if let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] { - NSApplication.shared.endModalSession(modalSession) - modalContent.window.close() - onDismiss?() - } + } + } endModal: { _, _ in + NSApplication.shared.stopModal() + onDismiss?() + } + } + + // MARK: - Modal Session + + @discardableResult + fileprivate func _modalSession( + isModaled: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + _modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } + + @discardableResult + fileprivate func _modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + fileprivate func _modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + @discardableResult + fileprivate func _modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _modalSession(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + @discardableResult + fileprivate func _modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _modal(item: item, id: id) { $item in + content($item) + } beginModal: { modalContent, _ in + if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] { + NSApplication.shared.endModalSession(modalSession) + modaledWindow.window.close() + onDismiss?() + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) } - } - - private func _modal( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> Content, - beginModal: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void, - endModal: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let modalObserver: ModalObserver = modalObserver() - return modalObserver.observe( - item: item, - id: { $0[keyPath: id] }, - content: content, - begin: beginModal, - end: endModal - ) - } - private func modalObserver() -> ModalObserver { - if let observer = objc_getAssociatedObject(self, modalObserverKeys.key(of: Content.self)) as? ModalObserver { - return observer - } else { - let observer = ModalObserver(owner: self) - objc_setAssociatedObject(self, modalObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return observer + } else { + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) } - } + } + } endModal: { modalContent, _ in + if let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] { + NSApplication.shared.endModalSession(modalSession) + modalContent.window.close() + onDismiss?() + } + } + } + + private func _modal( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> Content, + beginModal: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void, + endModal: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let modalObserver: ModalObserver = modalObserver() + return modalObserver.observe( + item: item, + id: { $0[keyPath: id] }, + content: content, + begin: beginModal, + end: endModal + ) + } + + private func modalObserver() -> ModalObserver { + if let observer = objc_getAssociatedObject(self, ModalObserverKeys.key(of: Content.self)) as? ModalObserver { + return observer + } else { + let observer = ModalObserver(owner: self) + objc_setAssociatedObject(self, ModalObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer + } + } } extension Navigated where Content: ModalContent { - func clearup() { - NSApplication.shared.stopModal() - } + func clearup() { + NSApplication.shared.stopModal() + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift index 676b8857b8..3098e6a589 100644 --- a/Sources/AppKitNavigation/Navigation/ModalContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -4,32 +4,43 @@ import AppKit @MainActor protocol ModalContent: NavigationContent { - @discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse - var window: NSWindow { get } + @discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse + var window: NSWindow { get } +} + +@MainActor +protocol ModalSessionContent: ModalContent { + func appKitNavigationBeginModalSession() -> NSApplication.ModalSession } extension NSWindow: ModalContent { - var window: NSWindow { self } + var window: NSWindow { self } - func appKitNavigationRunModal() -> NSApplication.ModalResponse { - __appKitNavigationRunModal() - } + func appKitNavigationRunModal() -> NSApplication.ModalResponse { + __appKitNavigationRunModal() + } + + @objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse { + NSApplication.shared.runModal(for: self) + } +} - @objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse { - NSApplication.shared.runModal(for: self) - } +extension NSWindow: ModalSessionContent { + func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { + NSApplication.shared.beginModalSession(for: self) + } } extension NSSavePanel { - override func __appKitNavigationRunModal() -> NSApplication.ModalResponse { - runModal() - } + override func __appKitNavigationRunModal() -> NSApplication.ModalResponse { + runModal() + } } extension NSAlert: ModalContent { - func appKitNavigationRunModal() -> NSApplication.ModalResponse { - runModal() - } + func appKitNavigationRunModal() -> NSApplication.ModalResponse { + runModal() + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/ModalSession.swift b/Sources/AppKitNavigation/Navigation/ModalSession.swift deleted file mode 100644 index 51a47075aa..0000000000 --- a/Sources/AppKitNavigation/Navigation/ModalSession.swift +++ /dev/null @@ -1,7 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - - - -#endif diff --git a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift b/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift deleted file mode 100644 index a897018c9e..0000000000 --- a/Sources/AppKitNavigation/Navigation/ModalSessionContent.swift +++ /dev/null @@ -1,16 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -@MainActor -protocol ModalSessionContent: ModalContent { - func appKitNavigationBeginModalSession() -> NSApplication.ModalSession -} - -extension NSWindow: ModalSessionContent { - func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { - NSApplication.shared.beginModalSession(for: self) - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift deleted file mode 100644 index bc63b33443..0000000000 --- a/Sources/AppKitNavigation/Navigation/ModalWindowsObserver.swift +++ /dev/null @@ -1,33 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit -import Combine - -@MainActor -class ModalWindowsObserver: NSObject { - static let shared = ModalWindowsObserver() - - var windowsCancellable: [NSWindow: AnyCancellable] = [:] - - var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:] - - func observeWindow(_ window: NSWindow, modalSession: NSApplication.ModalSession? = nil) { - if let modalSession { - modalSessionByWindow[window] = modalSession - } - windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) - .sink { [weak self] _ in - guard let self else { return } - if let modalSession = modalSessionByWindow[window] { - NSApplication.shared.endModalSession(modalSession) - } else if NSApplication.shared.modalWindow === window { - NSApplication.shared.stopModal() - } - modalSessionByWindow.removeValue(forKey: window) - windowsCancellable[window]?.cancel() - windowsCancellable.removeValue(forKey: window) - } - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift index 2e35321c1b..8c10f8c664 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationContent.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationContent.swift @@ -4,8 +4,8 @@ import Foundation @MainActor protocol NavigationContent: AnyObject { - var onBeginNavigation: (() -> Void)? { set get } - var onEndNavigation: (() -> Void)? { set get } + var onBeginNavigation: (() -> Void)? { set get } + var onEndNavigation: (() -> Void)? { set get } } @MainActor @@ -15,24 +15,23 @@ private var onBeginNavigationKeys = AssociatedKeys() private var onEndNavigationKeys = AssociatedKeys() extension NavigationContent { - var onBeginNavigation: (() -> Void)? { - set { - objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) - } - get { - objc_getAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self)) as? () -> Void - } + var onBeginNavigation: (() -> Void)? { + set { + objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) } + get { + objc_getAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self)) as? () -> Void + } + } - var onEndNavigation: (() -> Void)? { - set { - objc_setAssociatedObject(self, onEndNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) - } - get { - objc_getAssociatedObject(self, onEndNavigationKeys.key(of: Self.self)) as? () -> Void - } + var onEndNavigation: (() -> Void)? { + set { + objc_setAssociatedObject(self, onEndNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) + } + get { + objc_getAssociatedObject(self, onEndNavigationKeys.key(of: Self.self)) as? () -> Void } + } } - #endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift index 488cf6b4b9..ce952a080a 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift @@ -5,84 +5,84 @@ import SwiftNavigation @MainActor class NavigationObserver: NSObject { - private var navigatedByID: [UIBindingIdentifier: Navigated] = [:] + private var navigatedByID: [UIBindingIdentifier: Navigated] = [:] - unowned let owner: Owner + unowned let owner: Owner - init(owner: Owner) { - self.owner = owner - super.init() - } + init(owner: Owner) { + self.owner = owner + super.init() + } - func observe( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> Content, - begin: @escaping ( - _ content: Content, - _ transaction: UITransaction - ) -> Void, - end: @escaping ( - _ content: Content, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let key = UIBindingIdentifier(item) - return observe { [weak self] transaction in - guard let self else { return } - if let unwrappedItem = UIBinding(item) { - if let navigated = navigatedByID[key] { - guard let navigationID = navigated.id, - navigationID != id(unwrappedItem.wrappedValue) - else { - return - } - } - let content = content(unwrappedItem) - let onEndNavigation = { [navigationID = id(unwrappedItem.wrappedValue)] in - if let wrappedValue = item.wrappedValue, - navigationID == id(wrappedValue) { - item.wrappedValue = nil - } - } - content.onEndNavigation = onEndNavigation + func observe( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> Content, + begin: @escaping ( + _ content: Content, + _ transaction: UITransaction + ) -> Void, + end: @escaping ( + _ content: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let key = UIBindingIdentifier(item) + return observe { [weak self] transaction in + guard let self else { return } + if let unwrappedItem = UIBinding(item) { + if let navigated = navigatedByID[key] { + guard let navigationID = navigated.id, + navigationID != id(unwrappedItem.wrappedValue) + else { + return + } + } + let content = content(unwrappedItem) + let onEndNavigation = { [navigationID = id(unwrappedItem.wrappedValue)] in + if let wrappedValue = item.wrappedValue, + navigationID == id(wrappedValue) { + item.wrappedValue = nil + } + } + content.onEndNavigation = onEndNavigation - self.navigatedByID[key] = Navigated(content, id: id(unwrappedItem.wrappedValue)) - let work = { - withUITransaction(transaction) { - begin(content, transaction) - } - } - commitWork(work) - } else if let navigated = navigatedByID[key] { - if let content = navigated.content { - end(content, transaction) - } - self.navigatedByID[key] = nil - } + self.navigatedByID[key] = Navigated(content, id: id(unwrappedItem.wrappedValue)) + let work = { + withUITransaction(transaction) { + begin(content, transaction) + } + } + commitWork(work) + } else if let navigated = navigatedByID[key] { + if let content = navigated.content { + end(content, transaction) } + self.navigatedByID[key] = nil + } } + } - func commitWork(_ work: @escaping () -> Void) { - work() - } + func commitWork(_ work: @escaping () -> Void) { + work() + } } @MainActor class Navigated { - weak var content: Content? - let id: AnyHashable? - func clearup() {} - deinit { - MainActor._assumeIsolated { - clearup() - } + weak var content: Content? + let id: AnyHashable? + func clearup() {} + deinit { + MainActor._assumeIsolated { + clearup() } + } - required init(_ content: Content, id: AnyHashable?) { - self.content = content - self.id = id - } + required init(_ content: Content, id: AnyHashable?) { + self.content = content + self.id = id + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index fbd5f46777..f90ec118a3 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -4,191 +4,171 @@ import AppKit import AppKitNavigationShim class PresentationObserver: NavigationObserver { - override func commitWork(_ work: @escaping () -> Void) { - if owner._AppKitNavigation_hasViewAppeared { - work() - } else { - owner._AppKitNavigation_onViewAppear.append(work) - } + override func commitWork(_ work: @escaping () -> Void) { + if owner._AppKitNavigation_hasViewAppeared { + work() + } else { + owner._AppKitNavigation_onViewAppear.append(work) } + } } extension NSViewController { - @discardableResult - public func present( - isPresented: UIBinding, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } - } + @discardableResult + public func present( + isPresented: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } + } - @discardableResult - public func present( - item: UIBinding, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) - } + @discardableResult + public func present( + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) + } - @_disfavoredOverload - @discardableResult - public func present( - item: UIBinding, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) - } + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) + } - @discardableResult - public func present( - item: UIBinding, - id: KeyPath, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - present(item: item, id: id, style: style, onDismiss: onDismiss) { - content($0.wrappedValue) - } + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + present(item: item, id: id, style: style, onDismiss: onDismiss) { + content($0.wrappedValue) } + } - @_disfavoredOverload - @discardableResult - public func present( - item: UIBinding, - id: KeyPath, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - destination(item: item, id: id) { $item in - content($item) - } present: { [weak self] child, transaction in - guard let self else { return } - if let presentedViewController = presentedViewControllers?.first { - self.dismiss(presentedViewController) - onDismiss?() - self.present(child, for: style) - } else { - self.present(child, for: style) - } - } dismiss: { [weak self] child, transaction in - guard let self else { return } - self.dismiss(child) - onDismiss?() - } + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + destination(item: item, id: id) { $item in + content($item) + } present: { [weak self] child, transaction in + guard let self else { return } + if let presentedViewController = presentedViewControllers?.first { + self.dismiss(presentedViewController) + onDismiss?() + self.present(child, for: style) + } else { + self.present(child, for: style) + } + } dismiss: { [weak self] child, transaction in + guard let self else { return } + self.dismiss(child) + onDismiss?() } + } - @discardableResult - public func destination( - isPresented: UIBinding, - content: @escaping () -> NSViewController, - present: @escaping (NSViewController, UITransaction) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - destination( - item: isPresented.toOptionalUnit, - content: { _ in content() }, - present: present, - dismiss: dismiss - ) - } + @discardableResult + public func destination( + isPresented: UIBinding, + content: @escaping () -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + destination( + item: isPresented.toOptionalUnit, + content: { _ in content() }, + present: present, + dismiss: dismiss + ) + } - @discardableResult - public func destination( - item: UIBinding, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping (NSViewController, UITransaction) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let presentationObserver: PresentationObserver = presentationObserver() - return presentationObserver.observe( - item: item, - id: { _ in nil }, - content: content, - begin: present, - end: dismiss - ) - } + @discardableResult + public func destination( + item: UIBinding, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let presentationObserver: PresentationObserver = presentationObserver() + return presentationObserver.observe( + item: item, + id: { _ in nil }, + content: content, + begin: present, + end: dismiss + ) + } - @discardableResult - public func destination( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let presentationObserver: PresentationObserver = presentationObserver() - return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) - } + @discardableResult + public func destination( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let presentationObserver: PresentationObserver = presentationObserver() + return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) + } - private static var presentationObserverKey = malloc(1)! - - private func presentationObserver() -> PresentationObserver { - if let observer = objc_getAssociatedObject(self, Self.presentationObserverKey) as? PresentationObserver { - return observer - } else { - let observer = PresentationObserver(owner: self) - objc_setAssociatedObject(self, Self.presentationObserverKey, observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return observer - } - } - - public enum TransitionStyle { - case sheet - case modalWindow - case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) - case custom(NSViewControllerPresentationAnimator) - } + private static var presentationObserverKey = malloc(1)! - private func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { - switch style { - case .sheet: - presentAsSheet(viewControllerToPresent) - case .modalWindow: - presentAsModalWindow(viewControllerToPresent) - case let .popover(rect, view, preferredEdge, behavior): - present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) - case let .custom(animator): - present(viewControllerToPresent, animator: animator) - } + private func presentationObserver() -> PresentationObserver { + if let observer = objc_getAssociatedObject(self, Self.presentationObserverKey) as? PresentationObserver { + return observer + } else { + let observer = PresentationObserver(owner: self) + objc_setAssociatedObject(self, Self.presentationObserverKey, observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer } + } } extension NavigationContent where Self: NSViewController { - var _onEndNavigation: (() -> Void)? { - set { - _AppKitNavigation_onDismiss = newValue - } - get { - _AppKitNavigation_onDismiss - } + var _onEndNavigation: (() -> Void)? { + set { + _AppKitNavigation_onDismiss = newValue } + get { + _AppKitNavigation_onDismiss + } + } } extension Navigated where Content: NSViewController { - func clearup() { - content?.dismiss(nil) - } + func clearup() { + content?.dismiss(nil) + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift index eba08ad600..907536422c 100644 --- a/Sources/AppKitNavigation/Navigation/PresentationContent.swift +++ b/Sources/AppKitNavigation/Navigation/PresentationContent.swift @@ -3,39 +3,39 @@ import AppKit @MainActor -public protocol PresentationContent: NavigationContent { - func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) - func dismiss(from presentingViewController: NSViewController) +protocol PresentationContent: NavigationContent { + func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) + func dismiss(from presentingViewController: NSViewController) } extension NSViewController: PresentationContent { - public func presented(from presentingViewController: NSViewController, style: TransitionStyle) { - presentingViewController.present(self, for: style) - } + func presented(from presentingViewController: NSViewController, style: TransitionStyle) { + presentingViewController.present(self, for: style) + } - public func dismiss(from presentingViewController: NSViewController) { - presentingViewController.dismiss(self) - } + func dismiss(from presentingViewController: NSViewController) { + presentingViewController.dismiss(self) + } - public enum TransitionStyle { - case sheet - case modalWindow - case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) - case custom(NSViewControllerPresentationAnimator) - } + public enum TransitionStyle { + case sheet + case modalWindow + case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + case custom(NSViewControllerPresentationAnimator) + } - private func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { - switch style { - case .sheet: - presentAsSheet(viewControllerToPresent) - case .modalWindow: - presentAsModalWindow(viewControllerToPresent) - case let .popover(rect, view, preferredEdge, behavior): - present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) - case let .custom(animator): - present(viewControllerToPresent, animator: animator) - } + func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { + switch style { + case .sheet: + presentAsSheet(viewControllerToPresent) + case .modalWindow: + presentAsModalWindow(viewControllerToPresent) + case let .popover(rect, view, preferredEdge, behavior): + present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) + case let .custom(animator): + present(viewControllerToPresent, animator: animator) } + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index ba9cbd1846..565c991704 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -8,268 +8,267 @@ private typealias SheetObserver, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } } extension NSWindow { - @discardableResult - public func sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSAlert - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSAlert + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSAlert + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } } extension NSWindow { - @discardableResult - public func sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSSavePanel - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSSavePanel + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSSavePanel + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } } - extension SheetContent { - @discardableResult - fileprivate func _sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content - ) -> ObserveToken { - _sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } - } + @discardableResult + fileprivate func _sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + _sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + } - @discardableResult - fileprivate func _sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) - } + @discardableResult + fileprivate func _sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + } - @_disfavoredOverload - @discardableResult - fileprivate func _sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) - } + @_disfavoredOverload + @discardableResult + fileprivate func _sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + } - @discardableResult - fileprivate func _sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) - } + @discardableResult + fileprivate func _sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) } + } - @discardableResult - fileprivate func _sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _sheet(item: item, id: id) { $item in - content($item) - } beginSheet: { [weak self] child, _ in - guard let self else { return } - if let attachedSheetWindow = currentWindow?.attachedSheet { - self.endSheet(for: attachedSheetWindow) - onDismiss?() - Task { @MainActor in - await self.beginSheet(for: child) - child.onEndNavigation?() - child.onEndNavigation = nil - } - } else { - Task { @MainActor in - await self.beginSheet(for: child) - child.onEndNavigation?() - child.onEndNavigation = nil - } - } - } endSheet: { [weak self] content, _ in - self?.endSheet(for: content) - onDismiss?() + @discardableResult + fileprivate func _sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + _sheet(item: item, id: id) { $item in + content($item) + } beginSheet: { [weak self] child, _ in + guard let self else { return } + if let attachedSheetWindow = currentWindow?.attachedSheet { + self.endSheet(for: attachedSheetWindow) + onDismiss?() + Task { @MainActor in + await self.beginSheet(for: child) + child.onEndNavigation?() + child.onEndNavigation = nil + } + } else { + Task { @MainActor in + await self.beginSheet(for: child) + child.onEndNavigation?() + child.onEndNavigation = nil } + } + } endSheet: { [weak self] content, _ in + self?.endSheet(for: content) + onDismiss?() } + } - private func _sheet( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> Content, - beginSheet: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void, - endSheet: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let sheetObserver: SheetObserver = sheetObserver() - return sheetObserver.observe( - item: item, - id: { $0[keyPath: id] }, - content: content, - begin: beginSheet, - end: endSheet - ) - } + private func _sheet( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> Content, + beginSheet: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void, + endSheet: @escaping ( + _ child: Content, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let sheetObserver: SheetObserver = sheetObserver() + return sheetObserver.observe( + item: item, + id: { $0[keyPath: id] }, + content: content, + begin: beginSheet, + end: endSheet + ) + } - private func sheetObserver() -> SheetObserver { - if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver { - return observer - } else { - let observer = SheetObserver(owner: self) - objc_setAssociatedObject(self, sheetObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return observer - } + private func sheetObserver() -> SheetObserver { + if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver { + return observer + } else { + let observer = SheetObserver(owner: self) + objc_setAssociatedObject(self, sheetObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + return observer } + } } extension Navigated where Content: SheetContent { - func clearup() { - guard let window = content?.currentWindow else { return } - window.sheetParent?.endSheet(window) - } + func clearup() { + guard let window = content?.currentWindow else { return } + window.sheetParent?.endSheet(window) + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index 3da396258f..b8ce7a2245 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -4,49 +4,49 @@ import AppKit @MainActor protocol SheetContent: NavigationContent { - var currentWindow: NSWindow? { get } - func beginSheet(for content: SheetContent) async - func endSheet(for content: SheetContent) + var currentWindow: NSWindow? { get } + func beginSheet(for content: SheetContent) async + func endSheet(for content: SheetContent) } extension SheetContent { - func beginSheet(for content: any SheetContent) async { - guard let sheetedWindow = content.currentWindow else { return } - await currentWindow?.beginSheet(sheetedWindow) - } - - func endSheet(for content: any SheetContent) { - guard let sheetedWindow = content.currentWindow else { return } - currentWindow?.endSheet(sheetedWindow) - } + func beginSheet(for content: any SheetContent) async { + guard let sheetedWindow = content.currentWindow else { return } + await currentWindow?.beginSheet(sheetedWindow) + } + + func endSheet(for content: any SheetContent) { + guard let sheetedWindow = content.currentWindow else { return } + currentWindow?.endSheet(sheetedWindow) + } } extension NSWindow: SheetContent { - var currentWindow: NSWindow? { self } + var currentWindow: NSWindow? { self } } extension NSAlert: SheetContent { - var currentWindow: NSWindow? { window } + var currentWindow: NSWindow? { window } - func beginSheet(for content: any SheetContent) async { - guard let parentWindow = content.currentWindow else { return } - await beginSheetModal(for: parentWindow) - } + func beginSheet(for content: any SheetContent) async { + guard let parentWindow = content.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } - func endSheet(for content: any SheetContent) { - content.currentWindow?.endSheet(window) - } + func endSheet(for content: any SheetContent) { + content.currentWindow?.endSheet(window) + } } extension NSSavePanel { - func beginSheet(for content: any SheetContent) async { - guard let parentWindow = content.currentWindow else { return } - await beginSheetModal(for: parentWindow) - } - - func endSheet(for content: any SheetContent) { - content.currentWindow?.endSheet(window) - } + func beginSheet(for content: any SheetContent) async { + guard let parentWindow = content.currentWindow else { return } + await beginSheetModal(for: parentWindow) + } + + func endSheet(for content: any SheetContent) { + content.currentWindow?.endSheet(window) + } } #endif diff --git a/Sources/AppKitNavigation/Observe.swift b/Sources/AppKitNavigation/Observe.swift deleted file mode 100644 index 8032874494..0000000000 --- a/Sources/AppKitNavigation/Observe.swift +++ /dev/null @@ -1,181 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) -@_spi(Internals) import SwiftNavigation -import AppKit - -@MainActor -extension NSObject { - /// Observe access to properties of an observable (or perceptible) object. - /// - /// This tool allows you to set up an observation loop so that you can access fields from an - /// observable model in order to populate your view, and also automatically track changes to - /// any accessed fields so that the view is always up-to-date. - /// - /// It is most useful when dealing with non-SwiftUI views, such as AppKit views and controller. - /// You can invoke the ``observe(_:)`` method a single time in the `viewDidLoad` and update all - /// the view elements: - /// - /// ```swift - /// override func viewDidLoad() { - /// super.viewDidLoad() - /// - /// let countLabel = NSTextField(labelWithString: "") - /// let incrementButton = NSButton { [weak self] _ in - /// self?.model.incrementButtonTapped() - /// } - /// - /// observe { [weak self] in - /// guard let self - /// else { return } - /// - /// countLabel.stringValue = "\(model.count)" - /// } - /// } - /// ``` - /// - /// This closure is immediately called, allowing you to set the initial state of your UI - /// components from the feature's state. And if the `count` property in the feature's state is - /// ever mutated, this trailing closure will be called again, allowing us to update the view - /// again. - /// - /// Generally speaking you can usually have a single ``observe(_:)`` in the entry point of your - /// view, such as `viewDidLoad` for `NSViewController`. This works even if you have many UI - /// components to update: - /// - /// ```swift - /// override func viewDidLoad() { - /// super.viewDidLoad() - /// - /// observe { [weak self] in - /// guard let self - /// else { return } - /// - /// countLabel.isHidden = model.isObservingCount - /// if !countLabel.isHidden { - /// countLabel.stringValue = "\(model.count)" - /// } - /// factLabel.stringValue = model.fact - /// } - /// } - /// ``` - /// - /// This does mean that you may execute the line `factLabel.text = model.fact` even when - /// something unrelated changes, such as `store.model`, but that is typically OK for simple - /// properties of UI components. It is not a performance problem to repeatedly set the `text` of - /// a label or the `isHidden` of a button. - /// - /// However, if there is heavy work you need to perform when state changes, then it is best to - /// put that in its own ``observe(_:)``. For example, if you needed to reload a table view or - /// collection view when a collection changes: - /// - /// ```swift - /// override func viewDidLoad() { - /// super.viewDidLoad() - /// - /// observe { [weak self] in - /// guard let self - /// else { return } - /// - /// dataSource = model.items - /// tableView.reloadData() - /// } - /// } - /// ``` - /// - /// ## Cancellation - /// - /// The method returns an ``ObservationToken`` that can be used to cancel observation. For - /// example, if you only want to observe while a view controller is visible, you can start - /// observation in the `viewWillAppear` and then cancel observation in the `viewWillDisappear`: - /// - /// ```swift - /// var observation: ObservationToken? - /// - /// func viewWillAppear() { - /// super.viewWillAppear() - /// observation = observe { [weak self] in - /// // ... - /// } - /// } - /// func viewWillDisappear() { - /// super.viewWillDisappear() - /// observation?.cancel() - /// } - /// ``` - /// - /// - Parameter apply: A closure that contains properties to track and is invoked when the value - /// of a property changes. - /// - Returns: A cancellation token. - @discardableResult - public func observe(_ apply: @escaping @MainActor @Sendable () -> Void) -> ObservationToken { - observe { _ in apply() } - } - - /// Observe access to properties of an observable (or perceptible) object. - /// - /// A version of ``observe(_:)`` that is passed the current transaction. - /// - /// - Parameter apply: A closure that contains properties to track and is invoked when the value - /// of a property changes. - /// - Returns: A cancellation token. - @discardableResult - public func observe( - _ apply: @escaping @MainActor @Sendable (_ transaction: UITransaction) -> Void - ) -> ObservationToken { - let token = SwiftNavigation.observe { transaction in - MainActor._assumeIsolated { - withUITransaction(transaction) { - if transaction.appKit.disablesAnimations { - NSView.performWithoutAnimation { apply(transaction) } - for completion in transaction.appKit.animationCompletions { - completion(true) - } - } else if let animation = transaction.appKit.animation { - return animation.perform( - { apply(transaction) }, - completion: transaction.appKit.animationCompletions.isEmpty - ? nil - : { - for completion in transaction.appKit.animationCompletions { - completion($0) - } - } - ) - } else { - apply(transaction) - for completion in transaction.appKit.animationCompletions { - completion(true) - } - } - } - } - } task: { transaction, work in - DispatchQueue.main.async { - withUITransaction(transaction, work) - } - } - tokens.append(token) - return token - } - - fileprivate var tokens: [Any] { - get { - objc_getAssociatedObject(self, Self.tokensKey) as? [Any] ?? [] - } - set { - objc_setAssociatedObject(self, Self.tokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - } - - private static let tokensKey = malloc(1)! -} - -extension NSView { - fileprivate static func performWithoutAnimation(_ block: () -> Void) { - NSAnimationContext.runAnimationGroup { context in - context.allowsImplicitAnimation = false - block() - } - } -} - -#endif diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index bbb814a0c9..e36845fde7 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -27,6 +27,8 @@ + (void)load { method_exchangeImplementations( class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) + ); + method_exchangeImplementations( class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) ); diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index e5c147398a..4e7a6a30d1 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,12 +1,13 @@ { + "originHash" : "fd561772dbb7da88879cfbd7ad587c7c0f94bd076b6d0e00f7d2d67ac20cb3a8", "pins" : [ { "identity" : "combine-schedulers", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/combine-schedulers", "state" : { - "revision" : "9fa31f4403da54855f1e2aeaeff478f4f0e40b13", - "version" : "1.0.2" + "revision" : "5928286acce13def418ec36d05a001a9641086f2", + "version" : "1.0.3" } }, { @@ -14,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { - "revision" : "bc92c4b27f9a84bfb498cdbfdf35d5a357e9161f", - "version" : "1.5.6" + "revision" : "19b7263bacb9751f151ec0c93ec816fe1ef67c7b", + "version" : "1.6.1" } }, { @@ -23,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-clocks", "state" : { - "revision" : "b9b24b69e2adda099a1fa381cda1eeec272d5b53", - "version" : "1.0.5" + "revision" : "cc46202b53476d64e824e0b6612da09d84ffde8e", + "version" : "1.0.6" } }, { @@ -39,10 +40,10 @@ { "identity" : "swift-concurrency-extras", "kind" : "remoteSourceControl", - "location" : "https://github.com/pointfreeco/swift-concurrency-extras.git", + "location" : "https://github.com/pointfreeco/swift-concurrency-extras", "state" : { - "revision" : "6054df64b55186f08b6d0fd87152081b8ad8d613", - "version" : "1.2.0" + "revision" : "82a4ae7170d98d8538ec77238b7eb8e7199ef2e8", + "version" : "1.3.1" } }, { @@ -59,8 +60,8 @@ "kind" : "remoteSourceControl", "location" : "http://github.com/pointfreeco/swift-dependencies", "state" : { - "revision" : "0fc0255e780bf742abeef29dec80924f5f0ae7b9", - "version" : "1.4.1" + "revision" : "52b5e1a09dc016e64ce253e19ab3124b7fae9ac9", + "version" : "1.7.0" } }, { @@ -84,10 +85,10 @@ { "identity" : "swift-identified-collections", "kind" : "remoteSourceControl", - "location" : "https://github.com/pointfreeco/swift-identified-collections.git", + "location" : "https://github.com/pointfreeco/swift-identified-collections", "state" : { - "revision" : "2f5ab6e091dd032b63dacbda052405756010dc3b", - "version" : "1.1.0" + "revision" : "322d9ffeeba85c9f7c4984b39422ec7cc3c56597", + "version" : "1.1.1" } }, { @@ -95,8 +96,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-perception", "state" : { - "revision" : "bc67aa8e461351c97282c2419153757a446ae1c9", - "version" : "1.3.5" + "revision" : "21811d6230a625fa0f2e6ffa85be857075cc02c4", + "version" : "1.5.0" } }, { @@ -122,10 +123,10 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { - "revision" : "770f990d3e4eececb57ac04a6076e22f8c97daeb", - "version" : "1.4.2" + "revision" : "b444594f79844b0d6d76d70fbfb3f7f71728f938", + "version" : "1.5.1" } } ], - "version" : 2 + "version" : 3 } From b57ed0fa07cb91684f565cc216ee999cfcb963aa Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 8 Oct 2025 20:02:32 +0800 Subject: [PATCH 034/141] Add NSProgressIndicator binding support --- ...ppKit+BasicsNavigationViewController.swift | 137 +++--- ...+ConciseEnumNavigationViewController.swift | 172 ++++---- .../AppKit+EnumControlsViewController.swift | 191 ++++---- .../AppKit/AppKit+FocusViewController.swift | 237 +++++----- ...ppKit+ConnectToNetworkViewController.swift | 312 ++++++------- .../AppKit+NetworkDetailViewController.swift | 83 ++-- Package.resolved | 39 +- .../AppKitNavigation/AppKitAnimation.swift | 2 +- .../AppKitNavigation/Bindings/NSControl.swift | 26 +- .../Bindings/NSFontManager.swift | 411 +++++++++--------- .../Bindings/NSProgressIndicator.swift | 32 ++ .../Bindings/TargetActionProtocol.swift | 209 ++++----- .../AppKitNavigation/Navigation/Sheet.swift | 54 ++- .../Navigation/SheetContent.swift | 19 + Sources/AppKitNavigationShim/shim.m | 2 +- Sources/UIKitNavigation/UIKitAnimation.swift | 2 +- .../xcschemes/AppKitNavigation.xcscheme | 67 +++ 17 files changed, 1087 insertions(+), 908 deletions(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift create mode 100644 SwiftNavigation.xcworkspace/xcshareddata/xcschemes/AppKitNavigation.xcscheme diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index c7a71253f3..6140afcab0 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -4,93 +4,96 @@ import AppKit import AppKitNavigation class BasicsNavigationViewController: XiblessViewController, AppKitCaseStudy { - let caseStudyTitle = "Basics" - let readMe = """ - This case study demonstrates how to perform every major form of navigation in UIKit (alerts, \ - sheets, drill-downs) by driving navigation off of optional and boolean state. - """ - @UIBindable var model = Model() + let caseStudyTitle = "Basics" + let readMe = """ + This case study demonstrates how to perform every major form of navigation in UIKit (alerts, \ + sheets, drill-downs) by driving navigation off of optional and boolean state. + """ + @UIBindable var model = Model() - override func viewDidLoad() { - super.viewDidLoad() + override func viewDidLoad() { + super.viewDidLoad() - let showAlertButton = NSButton { [weak self] _ in - self?.model.alert = "Hello!" - } + let showAlertButton = NSButton() + showAlertButton.addAction { [weak self] _ in + self?.model.alert = "Hello!" + } - let showSheetButton = NSButton { [weak self] _ in - self?.model.sheet = .random(in: 1 ... 1_000) - DispatchQueue.main.asyncAfter(deadline: .now() + 3) { - self?.model.sheet = nil - } - } + let showSheetButton = NSButton() + showSheetButton.addAction { [weak self] _ in + self?.model.sheet = .random(in: 1 ... 1_000) + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { + self?.model.sheet = nil + } + } - let showSheetFromBooleanButton = NSButton { [weak self] _ in - self?.model.isSheetPresented = true - } + let showSheetFromBooleanButton = NSButton() + showSheetFromBooleanButton.addAction { [weak self] _ in + self?.model.isSheetPresented = true + } - let stack = NSStackView(views: [ - showAlertButton, - showSheetButton, - showSheetFromBooleanButton, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false + let stack = NSStackView(views: [ + showAlertButton, + showSheetButton, + showSheetFromBooleanButton, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) - observe { [weak self] in - guard let self else { return } + observe { [weak self] in + guard let self else { return } - if let url = model.url { - showAlertButton.title = "URL is: \(url)" - } else { - showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" - } - showSheetButton.title = "Sheet is presented: \(model.sheet != nil ? "✅" : "❌")" - showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.isSheetPresented ? "✅" : "❌")" - } + if let url = model.url { + showAlertButton.title = "URL is: \(url)" + } else { + showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" + } + showSheetButton.title = "Sheet is presented: \(model.sheet != nil ? "✅" : "❌")" + showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.isSheetPresented ? "✅" : "❌")" + } - modal(item: $model.alert, id: \.self) { [unowned self] message in + modal(item: $model.alert, id: \.self) { [unowned self] message in // let alert = NSAlert() // alert.messageText = "This is an alert" // alert.informativeText = message // alert.addButton(withTitle: "OK") // return alert - let openPanel = NSOpenPanel(url: $model.url) - openPanel.message = message - return openPanel - } + let openPanel = NSOpenPanel(url: $model.url) + openPanel.message = message + return openPanel + } - present(item: $model.sheet, id: \.self, style: .sheet) { count in - NSHostingController( - rootView: Form { Text(count.description) }.frame(width: 100, height: 100, alignment: .center) - ) - } - - present(isPresented: $model.isSheetPresented, style: .sheet) { - NSHostingController( - rootView: Form { Text("Hello!") }.frame(width: 100, height: 100, alignment: .center) - ) - } + present(item: $model.sheet, id: \.self, style: .sheet) { count in + NSHostingController( + rootView: Form { Text(count.description) }.frame(width: 100, height: 100, alignment: .center) + ) } - @Observable - class Model { - var alert: String? - var isSheetPresented = false - var sheet: Int? - var url: URL? + present(isPresented: $model.isSheetPresented, style: .sheet) { + NSHostingController( + rootView: Form { Text("Hello!") }.frame(width: 100, height: 100, alignment: .center) + ) } + } + + @Observable + class Model { + var alert: String? + var isSheetPresented = false + var sheet: Int? + var url: URL? + } } #Preview { - BasicsNavigationViewController() + BasicsNavigationViewController() } #endif diff --git a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift index 8abcdec54c..dadfc4e8ad 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -4,105 +4,107 @@ import AppKit import AppKitNavigation class ConciseEnumNavigationViewController: XiblessViewController, AppKitCaseStudy { - let caseStudyNavigationTitle = "Enum navigation" - let caseStudyTitle = "Concise enum navigation" - let readMe = """ - This case study demonstrates how to navigate to multiple destinations from a single optional \ - enum. + let caseStudyNavigationTitle = "Enum navigation" + let caseStudyTitle = "Concise enum navigation" + let readMe = """ + This case study demonstrates how to navigate to multiple destinations from a single optional \ + enum. - This allows you to be very concise with your domain modeling by having a single enum \ - describe all the possible destinations you can navigate to. In the case of this demo, we have \ - four cases in the enum, which means there are exactly 5 possible states, including the case \ - where none are active. + This allows you to be very concise with your domain modeling by having a single enum \ + describe all the possible destinations you can navigate to. In the case of this demo, we have \ + four cases in the enum, which means there are exactly 5 possible states, including the case \ + where none are active. - If you were to instead model this domain with 4 optionals (or booleans), then you would have \ - 16 possible states, of which only 5 are valid. That can leak complexity into your domain \ - because you can never be sure of exactly what is presented at a given time. - """ - @UIBindable var model = Model() + If you were to instead model this domain with 4 optionals (or booleans), then you would have \ + 16 possible states, of which only 5 are valid. That can leak complexity into your domain \ + because you can never be sure of exactly what is presented at a given time. + """ + @UIBindable var model = Model() - override func viewDidLoad() { - super.viewDidLoad() + override func viewDidLoad() { + super.viewDidLoad() - let showAlertButton = NSButton { [weak self] _ in - self?.model.destination = .alert("Hello!") - } - let showSheetButton = NSButton { [weak self] _ in - self?.model.destination = .sheet(.random(in: 1 ... 1_000)) - } - let showSheetFromBooleanButton = NSButton { [weak self] _ in - self?.model.destination = .sheetWithoutPayload - } + let showAlertButton = NSButton() + showAlertButton.addAction { [weak self] _ in + self?.model.destination = .alert("Hello!") + } + let showSheetButton = NSButton() + showSheetButton.addAction { [weak self] _ in + self?.model.destination = .sheet(.random(in: 1 ... 1_000)) + } + let showSheetFromBooleanButton = NSButton() + showSheetFromBooleanButton.addAction { [weak self] _ in + self?.model.destination = .sheetWithoutPayload + } - let stack = NSStackView(views: [ - showAlertButton, - showSheetButton, - showSheetFromBooleanButton, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false + let stack = NSStackView(views: [ + showAlertButton, + showSheetButton, + showSheetFromBooleanButton, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) - observe { [weak self] in - guard let self else { return } + observe { [weak self] in + guard let self else { return } - showAlertButton.title = "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")" - showSheetButton.title = "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")" - showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")" - } + showAlertButton.title = "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")" + showSheetButton.title = "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")" + showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")" + } - modal(item: $model.destination.alert, id: \.self) { message in - let alert = NSAlert() - alert.messageText = "This is an alert" - alert.informativeText = message - alert.addButton(withTitle: "OK") - return alert - } - present(item: $model.destination.sheet, id: \.self, style: .sheet) { [unowned self] count in - - NSHostingController( - rootView: Form { - Text(count.description) - Button("Close") { - self.model.destination = nil - } - }.frame(width: 200, height: 200, alignment: .center) - ) - } - present(isPresented: UIBinding($model.destination.sheetWithoutPayload), style: .sheet) { [unowned self] in - NSHostingController( - rootView: Form { - Text("Hello!") - Button("Close") { - self.model.destination = nil - } - }.frame(width: 200, height: 200, alignment: .center) - ) - } + modal(item: $model.destination.alert, id: \.self) { message in + let alert = NSAlert() + alert.messageText = "This is an alert" + alert.informativeText = message + alert.addButton(withTitle: "OK") + return alert + } + present(item: $model.destination.sheet, id: \.self, style: .sheet) { [unowned self] count in + NSHostingController( + rootView: Form { + Text(count.description) + Button("Close") { + self.model.destination = nil + } + }.frame(width: 200, height: 200, alignment: .center) + ) + } + present(isPresented: UIBinding($model.destination.sheetWithoutPayload), style: .sheet) { [unowned self] in + NSHostingController( + rootView: Form { + Text("Hello!") + Button("Close") { + self.model.destination = nil + } + }.frame(width: 200, height: 200, alignment: .center) + ) } + } - @Observable - class Model { - var destination: Destination? - @CasePathable - @dynamicMemberLookup - enum Destination { - case alert(String) - case drillDown(Int) - case sheet(Int) - case sheetWithoutPayload - } + @Observable + class Model { + var destination: Destination? + @CasePathable + @dynamicMemberLookup + enum Destination { + case alert(String) + case drillDown(Int) + case sheet(Int) + case sheetWithoutPayload } + } } #Preview { - ConciseEnumNavigationViewController() + ConciseEnumNavigationViewController() } #endif diff --git a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift index f6aada2f04..9ec9f3613c 100644 --- a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift @@ -4,114 +4,115 @@ import AppKit import AppKitNavigation class EnumControlsViewController: XiblessViewController, AppKitCaseStudy { - let caseStudyNavigationTitle = "Enum controls" - let caseStudyTitle = "Concise enum controls" - let readMe = """ - This case study demonstrates how to drive form controls from bindings to enum state. In this \ - example, a single `Status` enum holds two cases: - - • An integer quantity for when an item is in stock, which can drive a stepper. - • A Boolean for whether an item is on back order when it is _not_ in stock, which can drive a \ - switch. - - This library provides tools to chain deeper into a binding's case by applying the \ - `@CasePathable` macro. - """ - - @CasePathable - enum Status { - case inStock(quantity: Int) - case outOfStock(isOnBackOrder: Bool) + let caseStudyNavigationTitle = "Enum controls" + let caseStudyTitle = "Concise enum controls" + let readMe = """ + This case study demonstrates how to drive form controls from bindings to enum state. In this \ + example, a single `Status` enum holds two cases: + + • An integer quantity for when an item is in stock, which can drive a stepper. + • A Boolean for whether an item is on back order when it is _not_ in stock, which can drive a \ + switch. + + This library provides tools to chain deeper into a binding's case by applying the \ + `@CasePathable` macro. + """ + + @CasePathable + enum Status { + case inStock(quantity: Int) + case outOfStock(isOnBackOrder: Bool) + } + + @UIBinding var status: Status = .inStock(quantity: 100) + + override func viewDidLoad() { + super.viewDidLoad() + + let quantityLabel = NSTextField(labelWithString: "") + let quantityStepper = NSStepper() + quantityStepper.maxValue = .infinity + let quantityStack = NSStackView(views: [ + quantityLabel, + quantityStepper, + ]) + let outOfStockButton = NSButton() + outOfStockButton.addAction { [weak self] _ in + self?.status = .outOfStock(isOnBackOrder: false) + } + outOfStockButton.title = "Out of stock" + let inStockStack = NSStackView(views: [ + quantityStack, + outOfStockButton, + ]) + inStockStack.orientation = .vertical + + let isOnBackOrderLabel = NSTextField(labelWithString: "Is on back order?") + let isOnBackOrderSwitch = NSSwitch() + let isOnBackOrderStack = NSStackView(views: [ + isOnBackOrderLabel, + isOnBackOrderSwitch, + ]) + let backInStockButton = NSButton() + backInStockButton.addAction { [weak self] _ in + self?.status = .inStock(quantity: 100) } - @UIBinding var status: Status = .inStock(quantity: 100) - - override func viewDidLoad() { - super.viewDidLoad() - - let quantityLabel = NSTextField(labelWithString: "") - let quantityStepper = NSStepper() - quantityStepper.maxValue = .infinity - let quantityStack = NSStackView(views: [ - quantityLabel, - quantityStepper, - ]) - let outOfStockButton = NSButton { [weak self] _ in - self?.status = .outOfStock(isOnBackOrder: false) - } - outOfStockButton.title = "Out of stock" - let inStockStack = NSStackView(views: [ - quantityStack, - outOfStockButton, - ]) - inStockStack.orientation = .vertical - - let isOnBackOrderLabel = NSTextField(labelWithString: "Is on back order?") - let isOnBackOrderSwitch = NSSwitch() - let isOnBackOrderStack = NSStackView(views: [ - isOnBackOrderLabel, - isOnBackOrderSwitch, - ]) - let backInStockButton = NSButton { [weak self] _ in - self?.status = .inStock(quantity: 100) + backInStockButton.title = "Back in stock!" + let outOfStockStack = NSStackView(views: [ + isOnBackOrderStack, + backInStockButton, + ]) + outOfStockStack.orientation = .vertical + + let stack = NSStackView(views: [ + inStockStack, + outOfStockStack, + ]) + stack.orientation = .vertical + stack.spacing = 12 + stack.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stack) + + NSLayoutConstraint.activate([ + stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), + stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), + stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), + ]) + + observe { [weak self] in + guard let self else { return } + + inStockStack.isHidden = !status.is(\.inStock) + outOfStockStack.isHidden = !status.is(\.outOfStock) + + switch status { + case .inStock: + if let quantity = $status.inStock { + quantityLabel.stringValue = "Quantity: \(quantity.wrappedValue)" + quantityStepper.bind(value: quantity.asDouble) } - backInStockButton.title = "Back in stock!" - let outOfStockStack = NSStackView(views: [ - isOnBackOrderStack, - backInStockButton, - ]) - outOfStockStack.orientation = .vertical - - let stack = NSStackView(views: [ - inStockStack, - outOfStockStack, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(stack) - - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) - - observe { [weak self] in - guard let self else { return } - - inStockStack.isHidden = !status.is(\.inStock) - outOfStockStack.isHidden = !status.is(\.outOfStock) - - switch status { - case .inStock: - if let quantity = $status.inStock { - quantityLabel.stringValue = "Quantity: \(quantity.wrappedValue)" - quantityStepper.bind(value: quantity.asDouble) - } - - case .outOfStock: - if let isOnBackOrder = $status.outOfStock { - isOnBackOrderSwitch.bind(isOn: isOnBackOrder) - } - } + case .outOfStock: + if let isOnBackOrder = $status.outOfStock { + isOnBackOrderSwitch.bind(isOn: isOnBackOrder) } + } } + } } @available(macOS 14.0, *) #Preview { - EnumControlsViewController() + EnumControlsViewController() } - extension Int { - fileprivate var asDouble: Double { - get { Double(self) } - set { self = Int(newValue) } - } + fileprivate var asDouble: Double { + get { Double(self) } + set { self = Int(newValue) } + } } #endif diff --git a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift index 9008fdf714..7623580bbf 100644 --- a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift @@ -4,128 +4,133 @@ import AppKit import AppKitNavigation class FocusViewController: XiblessViewController, AppKitCaseStudy { - let caseStudyTitle = "Focus" - let readMe = """ - This case study demonstrates how to handle `UITextField` focus in a state-driven manner. The \ - focus in the UI is kept in sync with the focus value held in an observable model so that \ - changes in one are immediately reflected in the other. - """ - @UIBindable var model = Model() - - override func viewDidLoad() { - super.viewDidLoad() - - let bioTextField = NSTextField(text: $model.bio) - bioTextField.bind(focus: $model.focus, equals: .bio) - bioTextField.bezelStyle = .roundedBezel - bioTextField.placeholderString = "Bio" - let emailTextField = NSTextField(text: $model.email) - emailTextField.bind(focus: $model.focus, equals: .email) - emailTextField.bezelStyle = .roundedBezel - emailTextField.placeholderString = "Email" - let passwordTextField = NSSecureTextField(text: $model.password) - passwordTextField.bind(focus: $model.focus, equals: .password) - passwordTextField.bezelStyle = .roundedBezel - passwordTextField.placeholderString = "Password" - let usernameTextField = NSTextField(text: $model.username) - usernameTextField.bind(focus: $model.focus, equals: .username) - usernameTextField.bezelStyle = .roundedBezel - usernameTextField.placeholderString = "Username" - - let currentFocusLabel = NSTextField(labelWithString: "") - - let focusBioButton = NSButton { [weak self] _ in - self?.model.focus = .bio - } - - focusBioButton.title = "Focus bio" - let focusEmailButton = NSButton { [weak self] _ in - self?.model.focus = .email - } - - focusEmailButton.title = "Focus email" - let focusPasswordButton = NSButton { [weak self] _ in - self?.model.focus = .password - } - - focusPasswordButton.title = "Focus password" - let focusUsernameButton = NSButton { [weak self] _ in - self?.model.focus = .username - } - - focusUsernameButton.title = "Focus username" - let resignFirstResponder = NSButton { [weak self] _ in - self?.view.window?.makeFirstResponder(nil) - } - - resignFirstResponder.title = "Resign first responder" - - let stack = NSStackView(views: [ - usernameTextField, - emailTextField, - passwordTextField, - bioTextField, - currentFocusLabel, - focusUsernameButton, - focusEmailButton, - focusPasswordButton, - focusBioButton, - resignFirstResponder, - ]) - stack.orientation = .vertical - stack.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.topAnchor - .constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - stack.leadingAnchor - .constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 24), - stack.trailingAnchor - .constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -24), - ]) - - observe { [weak self] in - guard let self else { return } - - currentFocusLabel.stringValue = "Current focus: \(model.focus?.rawValue ?? "none")" - bioTextField.backgroundColor = nil - emailTextField.backgroundColor = nil - passwordTextField.backgroundColor = nil - usernameTextField.backgroundColor = nil - switch model.focus { - case .bio: - bioTextField.backgroundColor = .lightGray - case .email: - emailTextField.backgroundColor = .lightGray - case .password: - passwordTextField.backgroundColor = .lightGray - case .username: - usernameTextField.backgroundColor = .lightGray - case .none: - break - } - } + let caseStudyTitle = "Focus" + let readMe = """ + This case study demonstrates how to handle `UITextField` focus in a state-driven manner. The \ + focus in the UI is kept in sync with the focus value held in an observable model so that \ + changes in one are immediately reflected in the other. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let bioTextField = NSTextField(text: $model.bio) + bioTextField.bind(focus: $model.focus, equals: .bio) + bioTextField.bezelStyle = .roundedBezel + bioTextField.placeholderString = "Bio" + let emailTextField = NSTextField(text: $model.email) + emailTextField.bind(focus: $model.focus, equals: .email) + emailTextField.bezelStyle = .roundedBezel + emailTextField.placeholderString = "Email" + let passwordTextField = NSSecureTextField(text: $model.password) + passwordTextField.bind(focus: $model.focus, equals: .password) + passwordTextField.bezelStyle = .roundedBezel + passwordTextField.placeholderString = "Password" + let usernameTextField = NSTextField(text: $model.username) + usernameTextField.bind(focus: $model.focus, equals: .username) + usernameTextField.bezelStyle = .roundedBezel + usernameTextField.placeholderString = "Username" + + let currentFocusLabel = NSTextField(labelWithString: "") + + let focusBioButton = NSButton() + focusBioButton.addAction { [weak self] _ in + self?.model.focus = .bio } - @Observable - class Model { - var bio = "" - var email = "" - var focus: Focus? - var password = "" - var username = "" - enum Focus: String { - case bio - case email - case password - case username - } + focusBioButton.title = "Focus bio" + let focusEmailButton = NSButton() + focusEmailButton.addAction { [weak self] _ in + self?.model.focus = .email } + + focusEmailButton.title = "Focus email" + let focusPasswordButton = NSButton() + focusPasswordButton.addAction { [weak self] _ in + self?.model.focus = .password + } + + focusPasswordButton.title = "Focus password" + let focusUsernameButton = NSButton() + focusUsernameButton.addAction { [weak self] _ in + self?.model.focus = .username + } + + focusUsernameButton.title = "Focus username" + let resignFirstResponder = NSButton() + resignFirstResponder.addAction { [weak self] _ in + self?.view.window?.makeFirstResponder(nil) + } + + resignFirstResponder.title = "Resign first responder" + + let stack = NSStackView(views: [ + usernameTextField, + emailTextField, + passwordTextField, + bioTextField, + currentFocusLabel, + focusUsernameButton, + focusEmailButton, + focusPasswordButton, + focusBioButton, + resignFirstResponder, + ]) + stack.orientation = .vertical + stack.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(stack) + NSLayoutConstraint.activate([ + stack.topAnchor + .constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + stack.leadingAnchor + .constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 24), + stack.trailingAnchor + .constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -24), + ]) + + observe { [weak self] in + guard let self else { return } + + currentFocusLabel.stringValue = "Current focus: \(model.focus?.rawValue ?? "none")" + bioTextField.backgroundColor = nil + emailTextField.backgroundColor = nil + passwordTextField.backgroundColor = nil + usernameTextField.backgroundColor = nil + switch model.focus { + case .bio: + bioTextField.backgroundColor = .lightGray + case .email: + emailTextField.backgroundColor = .lightGray + case .password: + passwordTextField.backgroundColor = .lightGray + case .username: + usernameTextField.backgroundColor = .lightGray + case .none: + break + } + } + } + + @Observable + class Model { + var bio = "" + var email = "" + var focus: Focus? + var password = "" + var username = "" + enum Focus: String { + case bio + case email + case password + case username + } + } } #Preview { - FocusViewController() + FocusViewController() } #endif diff --git a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift index 203e996393..5fbc9378f0 100644 --- a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift @@ -4,174 +4,176 @@ import AppKit import AppKitNavigation final class ConnectToNetworkViewController: XiblessViewController { - @UIBindable var model: ConnectToNetworkModel - - init(model: ConnectToNetworkModel) { - self.model = model - super.init(nibName: nil, bundle: nil) + @UIBindable var model: ConnectToNetworkModel + + init(model: ConnectToNetworkModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + view.frame = .init(origin: .zero, size: .init(width: 450, height: 234)) + let wifiIconImage = NSImageView(systemSymbolName: "wifi") + wifiIconImage.contentTintColor = .systemBlue + wifiIconImage.symbolConfiguration = .init(pointSize: 60, weight: .regular) + + let titleLabel = NSTextField(labelWithString: "Enter the password for “\(model.network.name)”") + titleLabel.font = .boldSystemFont(ofSize: 13) + let detailLabel = NSTextField(wrappingLabelWithString: "You can also access this Wi-Fi network by sharing the password from a nearby iPhone, iPad, or Mac which has connected to this network and has you in their contacts.") + detailLabel.font = .systemFont(ofSize: 12) + let textStackView = NSStackView(views: [ + titleLabel, + detailLabel, + ]) + textStackView.orientation = .vertical + textStackView.alignment = .leading + + let topStackView = NSStackView(views: [ + Spacer(size: .init(width: 15, height: 0)), + wifiIconImage, + textStackView, + HorizontalMaxSpacer(), + ]) + topStackView.orientation = .horizontal + + let passwordLabel = NSTextField(labelWithString: "Password:") + + let passwordTextField = NSSecureTextField(text: $model.password) + passwordTextField.bezelStyle = .roundedBezel + passwordTextField.becomeFirstResponder() + passwordTextField.placeholderString = "The password is 'blob'" + + let centerStackView = NSStackView(views: [ + HorizontalMaxSpacer(), + passwordLabel, + passwordTextField, + ]) + centerStackView.orientation = .horizontal + NSLayoutConstraint.activate([ + passwordTextField.widthAnchor.constraint(equalToConstant: 253), + ]) + + let cancelButton = NSButton() + cancelButton.addAction { [weak self] _ in + guard let self else { return } + model.cancelButtonTapped() } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") + cancelButton.title = "Cancel" + + let joinButton = NSButton() + joinButton.addAction { [weak self] _ in + guard let self else { return } + Task { + await self.model.joinButtonTapped() + } + } + joinButton.title = "Join" + + let progress = NSProgressIndicator() + progress.isIndeterminate = true + progress.style = .spinning + progress.controlSize = .small + progress.startAnimation(nil) + + let progressStackView = NSStackView(views: [ + HorizontalMaxSpacer(), + progress, + ]) + + let bottomStackView = NSStackView(views: [ + HorizontalMaxSpacer(), + cancelButton, + joinButton, + ]) + bottomStackView.orientation = .horizontal + + NSLayoutConstraint.activate([ + joinButton.widthAnchor.constraint(equalToConstant: 70), + cancelButton.widthAnchor.constraint(equalToConstant: 70), + ]) + + let stack = NSStackView(views: [ + topStackView, + centerStackView, + progressStackView, + bottomStackView, + ]) + + stack.orientation = .vertical + stack.translatesAutoresizingMaskIntoConstraints = false + stack.edgeInsets = .init(top: 20, left: 0, bottom: 20, right: 20) + stack.distribution = .equalSpacing + stack.detachesHiddenViews = false + view.addSubview(stack) + progressStackView.isHidden = true + NSLayoutConstraint.activate([ + stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), + stack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), + stack.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor), + stack.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor), + ]) + + observe { [weak self, weak passwordTextField] in + guard + let self, + let passwordTextField + else { return } + + passwordTextField.isEnabled = !model.isConnecting + joinButton.isEnabled = !model.isConnecting + progressStackView.isHidden = !model.isConnecting } - override func viewDidLoad() { - super.viewDidLoad() - view.frame = .init(origin: .zero, size: .init(width: 450, height: 234)) - let wifiIconImage = NSImageView(systemSymbolName: "wifi") - wifiIconImage.contentTintColor = .systemBlue - wifiIconImage.symbolConfiguration = .init(pointSize: 60, weight: .regular) - - let titleLabel = NSTextField(labelWithString: "Enter the password for “\(model.network.name)”") - titleLabel.font = .boldSystemFont(ofSize: 13) - let detailLabel = NSTextField(wrappingLabelWithString: "You can also access this Wi-Fi network by sharing the password from a nearby iPhone, iPad, or Mac which has connected to this network and has you in their contacts.") - detailLabel.font = .systemFont(ofSize: 12) - let textStackView = NSStackView(views: [ - titleLabel, - detailLabel, - ]) - textStackView.orientation = .vertical - textStackView.alignment = .leading - - let topStackView = NSStackView(views: [ - Spacer(size: .init(width: 15, height: 0)), - wifiIconImage, - textStackView, - HorizontalMaxSpacer(), - ]) - topStackView.orientation = .horizontal - - let passwordLabel = NSTextField(labelWithString: "Password:") - - let passwordTextField = NSSecureTextField(text: $model.password) - passwordTextField.bezelStyle = .roundedBezel - passwordTextField.becomeFirstResponder() - passwordTextField.placeholderString = "The password is 'blob'" - - let centerStackView = NSStackView(views: [ - HorizontalMaxSpacer(), - passwordLabel, - passwordTextField, - ]) - centerStackView.orientation = .horizontal - NSLayoutConstraint.activate([ - passwordTextField.widthAnchor.constraint(equalToConstant: 253), - ]) - - let cancelButton = NSButton { [weak self] _ in - guard let self else { return } - model.cancelButtonTapped() - } - cancelButton.title = "Cancel" - - let joinButton = NSButton { [weak self] _ in - guard let self else { return } - Task { - await self.model.joinButtonTapped() - } - } - joinButton.title = "Join" - - let progress = NSProgressIndicator() - progress.isIndeterminate = true - progress.style = .spinning - progress.controlSize = .small - progress.startAnimation(nil) - - let progressStackView = NSStackView(views: [ - HorizontalMaxSpacer(), - progress, - ]) - - let bottomStackView = NSStackView(views: [ - HorizontalMaxSpacer(), - cancelButton, - joinButton, - ]) - bottomStackView.orientation = .horizontal - - NSLayoutConstraint.activate([ - joinButton.widthAnchor.constraint(equalToConstant: 70), - cancelButton.widthAnchor.constraint(equalToConstant: 70), - ]) - - let stack = NSStackView(views: [ - topStackView, - centerStackView, - progressStackView, - bottomStackView, - ]) - - stack.orientation = .vertical - stack.translatesAutoresizingMaskIntoConstraints = false - stack.edgeInsets = .init(top: 20, left: 0, bottom: 20, right: 20) - stack.distribution = .equalSpacing - stack.detachesHiddenViews = false - view.addSubview(stack) - progressStackView.isHidden = true - NSLayoutConstraint.activate([ - stack.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - stack.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor), - stack.leftAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leftAnchor), - stack.rightAnchor.constraint(equalTo: view.safeAreaLayoutGuide.rightAnchor), - ]) - - observe { [weak self, weak passwordTextField] in - guard - let self, - let passwordTextField - else { return } - - passwordTextField.isEnabled = !model.isConnecting - joinButton.isEnabled = !model.isConnecting - progressStackView.isHidden = !model.isConnecting - } - - modal(isModaled: $model.incorrectPasswordAlertIsPresented) { [unowned self] in - let alert = NSAlert() - alert.messageText = "Incorrect password for “\(model.network.name)”" - alert.addButton(withTitle: "OK") - return alert - } + modal(isModaled: $model.incorrectPasswordAlertIsPresented) { [unowned self] in + let alert = NSAlert() + alert.messageText = "Incorrect password for “\(model.network.name)”" + alert.addButton(withTitle: "OK") + return alert } + } } class HorizontalMaxSpacer: NSView { - override init(frame frameRect: NSRect) { - super.init(frame: frameRect) - setContentHuggingPriority(.fittingSizeCompression, for: .horizontal) - setContentCompressionResistancePriority(.fittingSizeCompression, for: .horizontal) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + setContentHuggingPriority(.fittingSizeCompression, for: .horizontal) + setContentCompressionResistancePriority(.fittingSizeCompression, for: .horizontal) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } } class Spacer: NSView { - init(size: NSSize) { - super.init(frame: .zero) - NSLayoutConstraint.activate([ - widthAnchor.constraint(equalToConstant: size.width), - heightAnchor.constraint(equalToConstant: size.height), - ]) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("init(coder:) has not been implemented") - } + init(size: NSSize) { + super.init(frame: .zero) + NSLayoutConstraint.activate([ + widthAnchor.constraint(equalToConstant: size.width), + heightAnchor.constraint(equalToConstant: size.height), + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } } #Preview(traits: .fixedLayout(width: 450, height: 262)) { - let vc = ConnectToNetworkViewController( - model: ConnectToNetworkModel( - network: Network(name: "Blob's WiFi") - ) + let vc = ConnectToNetworkViewController( + model: ConnectToNetworkModel( + network: Network(name: "Blob's WiFi") ) - vc.preferredContentSize = .init(width: 450, height: 234) - return vc + ) + vc.preferredContentSize = .init(width: 450, height: 234) + return vc } #endif diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift index 0c6219045a..6f7b7c61fa 100644 --- a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift @@ -4,62 +4,63 @@ import AppKit import AppKitNavigation final class NetworkDetailViewController: XiblessViewController { - @UIBindable var model: NetworkDetailModel + @UIBindable var model: NetworkDetailModel - init(model: NetworkDetailModel) { - self.model = model - super.init(nibName: nil, bundle: nil) - } + init(model: NetworkDetailModel) { + self.model = model + super.init(nibName: nil, bundle: nil) + } - override func viewDidLoad() { - super.viewDidLoad() + override func viewDidLoad() { + super.viewDidLoad() // navigationItem.title = model.network.name - let forgetButton = NSButton { [weak self] _ in - guard let self else { return } - model.forgetNetworkButtonTapped() - } + let forgetButton = NSButton() + forgetButton.addAction { [weak self] _ in + guard let self else { return } + model.forgetNetworkButtonTapped() + } - forgetButton.title = "Forget network" + forgetButton.title = "Forget network" // forgetButton.hasDestructiveAction = true - forgetButton.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(forgetButton) - NSLayoutConstraint.activate([ - forgetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), - forgetButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), - ]) + forgetButton.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(forgetButton) + NSLayoutConstraint.activate([ + forgetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), + forgetButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), + ]) - observe { [weak self] in - guard let self else { return } + observe { [weak self] in + guard let self else { return } // forgetButton.isHidden = model.network.id != model.selectedNetworkID - } + } + + modal(isModaled: $model.forgetAlertIsPresented) { [unowned self] in + let alert = NSAlert() + alert.messageText = "Forget Wi-Fi Network “\(model.network.name)”?" + alert.informativeText = """ + Your Mac and other devices using iCloud Keychain will no longer join this Wi-Fi \ + network. + """ - modal(isModaled: $model.forgetAlertIsPresented) { [unowned self] in - let alert = NSAlert() - alert.messageText = "Forget Wi-Fi Network “\(model.network.name)”?" - alert.informativeText = """ - Your Mac and other devices using iCloud Keychain will no longer join this Wi-Fi \ - network. - """ - - alert.addButton(ButtonState(role: .cancel) { TextState("Cancel") }) { _ in } - alert.addButton(ButtonState(role: .destructive) { TextState("Forget") }) { [weak self] _ in - guard let self else { return } - model.confirmForgetNetworkButtonTapped() - } - return alert - } + alert.addButton(ButtonState(role: .cancel) { TextState("Cancel") }) { _ in } + alert.addButton(ButtonState(role: .destructive) { TextState("Forget") }) { [weak self] _ in + guard let self else { return } + model.confirmForgetNetworkButtonTapped() + } + return alert } + } } #Preview { - NetworkDetailViewController( - model: NetworkDetailModel( - network: Network(name: "Blob's WiFi"), - selectedNetworkID: UUID() - ) + NetworkDetailViewController( + model: NetworkDetailModel( + network: Network(name: "Blob's WiFi"), + selectedNetworkID: UUID() ) + ) } #endif diff --git a/Package.resolved b/Package.resolved index 1354e7886c..3ee1e092b3 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "84b747bb349cd4db8652b1d5a9a2696c12f4c9f15441533d0f2e2553cb31f019", + "originHash" : "15cd96b975d5e3807a52c2b1c6d570b25f285bb14bd48c163416ecbb6bbac386", "pins" : [ { "identity" : "swift-case-paths", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { - "revision" : "19b7263bacb9751f151ec0c93ec816fe1ef67c7b", - "version" : "1.6.1" + "revision" : "6989976265be3f8d2b5802c722f9ba168e227c71", + "version" : "1.7.2" } }, { @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections", "state" : { - "revision" : "9bf03ff58ce34478e66aaee630e491823326fd06", - "version" : "1.1.3" + "revision" : "7b847a3b7008b2dc2f47ca3110d8c782fb2e5c7e", + "version" : "1.3.0" } }, { @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-concurrency-extras", "state" : { - "revision" : "6054df64b55186f08b6d0fd87152081b8ad8d613", - "version" : "1.2.0" + "revision" : "5a3825302b1a0d744183200915a47b508c828e6f", + "version" : "1.3.2" } }, { @@ -42,8 +42,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-docc-plugin", "state" : { - "revision" : "2eb22993b3dfd0c0d32729b357c8dabb6cd44680", - "version" : "1.4.2" + "revision" : "3e4f133a77e644a5812911a0513aeb7288b07d06", + "version" : "1.4.5" } }, { @@ -55,13 +55,22 @@ "version" : "1.0.0" } }, + { + "identity" : "swift-identified-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-identified-collections", + "state" : { + "revision" : "322d9ffeeba85c9f7c4984b39422ec7cc3c56597", + "version" : "1.1.1" + } + }, { "identity" : "swift-perception", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-perception", "state" : { - "revision" : "bc67aa8e461351c97282c2419153757a446ae1c9", - "version" : "1.3.5" + "revision" : "d924c62a70fca5f43872f286dbd7cef0957f1c01", + "version" : "1.6.0" } }, { @@ -69,8 +78,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax", "state" : { - "revision" : "515f79b522918f83483068d99c68daeb5116342d", - "version" : "600.0.0-prerelease-2024-08-20" + "revision" : "f99ae8aa18f0cf0d53481901f88a0991dc3bd4a2", + "version" : "601.0.1" } }, { @@ -78,8 +87,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { - "revision" : "27d767d643fa2cf083d0a73d74fa84cacb53e85c", - "version" : "1.4.1" + "revision" : "4c27acf5394b645b70d8ba19dc249c0472d5f618", + "version" : "1.7.0" } } ], diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 096761ab34..22e729ae84 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -36,7 +36,7 @@ @MainActor func perform( _ body: () throws -> Result, - completion: ((Bool?) -> Void)? = nil + completion: (/*@Sendable*/ (Bool?) -> Void)? = nil ) rethrows -> Result { switch framework { case let .appKit(animation): diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index 33ae9d4348..1dc9a83188 100755 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -5,30 +5,6 @@ import AppKit extension NSControl: @retroactive Sendable {} extension NSControl: TargetActionProtocol {} -extension NSControl { - public convenience init(action: @escaping (Self) -> Void) { - self.init(frame: .zero) - createActionProxyIfNeeded().addAction { [weak self] _ in - guard let self else { return } - action(self) - } - } - - @discardableResult - public func addAction(_ action: @escaping (NSControl) -> Void) -> UUID { - createActionProxyIfNeeded().addAction { [weak self] _ in - guard let self else { return } - action(self) - } - } - - public func removeAction(for id: UUID) { - createActionProxyIfNeeded().removeAction(for: id) - } - - public func removeAllActions() { - createActionProxyIfNeeded().removeAllActions() - } -} +extension NSControl {} #endif diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 01bc6b00ca..8bc2fef516 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -7,168 +7,165 @@ import IdentifiedCollections @MainActor extension NSFontManager: @unchecked @retroactive Sendable { - - private static let appkitNavigationDelegateKey = malloc(1)! - - private var appkitNavigationDelegate: Delegate { - set { - objc_setAssociatedObject(self, Self.appkitNavigationDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - if let delegate = objc_getAssociatedObject(self, Self.appkitNavigationDelegateKey) as? Delegate { - return delegate - } else { - let delegate = Delegate() - target = delegate - self.appkitNavigationDelegate = delegate - return delegate - } - } - } - - private class Delegate: NSObject, NSFontChanging { - var target: AnyObject? - var action: Selector? - - func changeFont(_ sender: NSFontManager?) { - if let action { - NSApplication.shared.sendAction(action, to: target, from: sender) - } - } - } + private static let appkitNavigationDelegateKey = malloc(1)! + + private var appkitNavigationDelegate: Delegate { + set { + objc_setAssociatedObject(self, Self.appkitNavigationDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + if let delegate = objc_getAssociatedObject(self, Self.appkitNavigationDelegateKey) as? Delegate { + return delegate + } else { + let delegate = Delegate() + target = delegate + self.appkitNavigationDelegate = delegate + return delegate + } + } + } + + private class Delegate: NSObject, NSFontChanging { + var target: AnyObject? + var action: Selector? + + func changeFont(_ sender: NSFontManager?) { + if let action { + NSApplication.shared.sendAction(action, to: target, from: sender) + } + } + } } @MainActor extension NSFontManager { - /// Creates a new date picker with the specified frame and registers the binding against the - /// selected date. - /// - /// - Parameters: - /// - frame: The frame rectangle for the view, measured in points. - /// - date: The binding to read from for the selected date, and write to when the selected - /// date changes. - public convenience init(font: UIBinding) { - self.init() - bind(font: font) - } - - /// Establishes a two-way connection between a binding and the date picker's selected date. - /// - /// - Parameter date: The binding to read from for the selected date, and write to when the - /// selected date changes. - /// - Returns: A cancel token. - @discardableResult - public func bind(font: UIBinding) -> ObserveToken { - bind(font, to: \._selectedFont) - } - - @objc private var _selectedFont: NSFont { - set { setSelectedFont(newValue, isMultiple: false) } - get { convert(.systemFont(ofSize: 0)) } - } + /// Creates a new date picker with the specified frame and registers the binding against the + /// selected date. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - date: The binding to read from for the selected date, and write to when the selected + /// date changes. + public convenience init(font: UIBinding) { + self.init() + bind(font: font) + } + + /// Establishes a two-way connection between a binding and the date picker's selected date. + /// + /// - Parameter date: The binding to read from for the selected date, and write to when the + /// selected date changes. + /// - Returns: A cancel token. + @discardableResult + public func bind(font: UIBinding) -> ObserveToken { + bind(font, to: \._selectedFont) + } + + @objc private var _selectedFont: NSFont { + set { setSelectedFont(newValue, isMultiple: false) } + get { convert(.systemFont(ofSize: 0)) } + } } - @MainActor extension NSFontManager { - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: ReferenceWritableKeyPath - ) -> ObserveToken { - bind(binding, to: keyPath) { control, newValue, _ in - control[keyPath: keyPath] = newValue - } - } - - private var actionProxy: FontManagerProxy? { - set { - objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - objc_getAssociatedObject(self, actionProxyKey) as? FontManagerProxy - } - } - - private func createActionProxyIfNeeded() -> FontManagerProxy { - if let actionProxy { - return actionProxy - } else { - let actionProxy = FontManagerProxy(owner: self) - self.actionProxy = actionProxy - return actionProxy - } - } - - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - set: A closure that is called when the binding's value changes with a weakly-captured - /// control, a new value that can be used to configure the control, and a transaction, which - /// can be used to determine how and if the change should be animated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: KeyPath, - set: @escaping (_ control: NSFontManager, _ newValue: Value, _ transaction: UITransaction) -> Void - ) -> ObserveToken { - unbind(keyPath) - let actionProxy = createActionProxyIfNeeded() - let actionID = actionProxy.addBindingAction { [weak self] _ in - guard let self else { return } - binding.wrappedValue = self[keyPath: keyPath] - } - - let isSetting = LockIsolated(false) - let token = observe { [weak self] transaction in - guard let self else { return } - isSetting.withValue { $0 = true } - defer { isSetting.withValue { $0 = false } } - set( - self, - binding.wrappedValue, - transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations - ? binding.transaction - : transaction - ) - } - // NB: This key path must only be accessed on the main actor - @UncheckedSendable var uncheckedKeyPath = keyPath - let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in - guard isSetting.withValue({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] - } - } - let observationToken = ObserveToken { [weak self] in - MainActor._assumeIsolated { - self?.actionProxy?.removeAction(for: actionID) - } - token.cancel() - observation.invalidate() - } - observationTokens[keyPath] = observationToken - return observationToken - } - - public func unbind(_ keyPath: KeyPath) { - observationTokens[keyPath]?.cancel() - observationTokens[keyPath] = nil - } + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: ReferenceWritableKeyPath + ) -> ObserveToken { + bind(binding, to: keyPath) { control, newValue, _ in + control[keyPath: keyPath] = newValue + } + } + + private var actionProxy: FontManagerProxy? { + set { + objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, actionProxyKey) as? FontManagerProxy + } + } + + private func createActionProxyIfNeeded() -> FontManagerProxy { + if let actionProxy { + return actionProxy + } else { + let actionProxy = FontManagerProxy(owner: self) + self.actionProxy = actionProxy + return actionProxy + } + } + + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - set: A closure that is called when the binding's value changes with a weakly-captured + /// control, a new value that can be used to configure the control, and a transaction, which + /// can be used to determine how and if the change should be animated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: KeyPath, + set: @escaping (_ control: NSFontManager, _ newValue: Value, _ transaction: UITransaction) -> Void + ) -> ObserveToken { + unbind(keyPath) + let actionProxy = createActionProxyIfNeeded() + let actionID = actionProxy.addBindingAction { [weak self] _ in + guard let self else { return } + binding.wrappedValue = self[keyPath: keyPath] + } + + let isSetting = LockIsolated(false) + let token = observe { [weak self] transaction in + guard let self else { return } + isSetting.withValue { $0 = true } + defer { isSetting.withValue { $0 = false } } + set( + self, + binding.wrappedValue, + transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + @UncheckedSendable var uncheckedKeyPath = keyPath + let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in + guard isSetting.withValue({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + } + } + let observationToken = ObserveToken { [weak self] in + MainActor._assumeIsolated { + self?.actionProxy?.removeAction(for: actionID) + } + token.cancel() + observation.invalidate() + } + observationTokens[keyPath] = observationToken + return observationToken + } + + public func unbind(_ keyPath: KeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } } - @MainActor private let observationTokensKey = malloc(1)! @MainActor @@ -176,81 +173,81 @@ private let actionProxyKey = malloc(1)! @MainActor private class FontManagerProxy: NSObject { - typealias ActionClosure = (Any?) -> Void + typealias ActionClosure = (Any?) -> Void - typealias ActionIdentifier = UUID + typealias ActionIdentifier = UUID - private struct Action: Identifiable { - let id = UUID() + private struct Action: Identifiable { + let id = UUID() - var closure: ActionClosure + var closure: ActionClosure - func invoke(_ sender: Any?) { - closure(sender) - } + func invoke(_ sender: Any?) { + closure(sender) } + } - private var bindingActions: IdentifiedArrayOf = [] + private var bindingActions: IdentifiedArrayOf = [] - private var actions: IdentifiedArrayOf = [] + private var actions: IdentifiedArrayOf = [] - private var originTarget: AnyObject? + private var originTarget: AnyObject? - private var originAction: Selector? + private var originAction: Selector? - weak var owner: NSFontManager? + weak var owner: NSFontManager? - required init(owner: NSFontManager) { - self.owner = owner - super.init() - self.originTarget = owner.target - self.originAction = owner.action - owner.target = self - owner.action = #selector(invokeAction(_:)) - } + required init(owner: NSFontManager) { + self.owner = owner + super.init() + self.originTarget = owner.target + self.originAction = owner.action + owner.target = self + owner.action = #selector(invokeAction(_:)) + } - @objc func controlTextDidChange(_ obj: Notification) { - bindingActions.forEach { $0.invoke(obj.object) } - actions.forEach { $0.invoke(obj.object) } - } + @objc func controlTextDidChange(_ obj: Notification) { + bindingActions.forEach { $0.invoke(obj.object) } + actions.forEach { $0.invoke(obj.object) } + } - @objc func invokeAction(_ sender: Any?) { - if let originTarget, let originAction { - NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) - } - bindingActions.forEach { $0.invoke(sender) } - actions.forEach { $0.invoke(sender) } + @objc func invokeAction(_ sender: Any?) { + if let originTarget, let originAction { + NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } + bindingActions.forEach { $0.invoke(sender) } + actions.forEach { $0.invoke(sender) } + } - @discardableResult - func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { - let action = Action(closure: actionClosure) - actions.append(action) - return action.id - } + @discardableResult + func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { + let action = Action(closure: actionClosure) + actions.append(action) + return action.id + } - func removeAction(for id: ActionIdentifier) { - actions.remove(id: id) - } + func removeAction(for id: ActionIdentifier) { + actions.remove(id: id) + } - func removeAllActions() { - actions.removeAll() - } + func removeAllActions() { + actions.removeAll() + } - @discardableResult - func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { - let bindingAction = Action(closure: bindingActionClosure) - bindingActions.append(bindingAction) - return bindingAction.id - } + @discardableResult + func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { + let bindingAction = Action(closure: bindingActionClosure) + bindingActions.append(bindingAction) + return bindingAction.id + } - func removeBindingAction(for id: ActionIdentifier) { - bindingActions.remove(id: id) - } + func removeBindingAction(for id: ActionIdentifier) { + bindingActions.remove(id: id) + } - func removeAllBindingActions() { - bindingActions.removeAll() - } + func removeAllBindingActions() { + bindingActions.removeAll() + } } #endif diff --git a/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift new file mode 100644 index 0000000000..1719443cb2 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift @@ -0,0 +1,32 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import SwiftNavigation + +extension NSProgressIndicator { + + public convenience init(frame: CGRect = .zero, isAnimated: UIBinding) { + self.init(frame: frame) + bind(isAnimated: isAnimated) + } + + @discardableResult + public func bind(isAnimated: UIBinding) -> ObserveToken { + let token = observe { [weak self] in + guard let self else { return } + let isAnimated = isAnimated.wrappedValue + if isAnimated { + startAnimation(nil) + } else { + stopAnimation(nil) + } + } + + let observeToken = ObserveToken { + token.cancel() + } + return observeToken + } + +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index c7bbedb5c6..a9ab01f311 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -6,122 +6,137 @@ import AppKit /// A protocol used to extend `NSControl, NSMenuItem...`. @MainActor public protocol TargetActionProtocol: NSObject, Sendable { - var target: AnyObject? { set get } - var action: Selector? { set get } + var target: AnyObject? { set get } + var action: Selector? { set get } } extension TargetActionProtocol { - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: ReferenceWritableKeyPath - ) -> ObserveToken { - bind(binding, to: keyPath) { control, newValue, _ in - control[keyPath: keyPath] = newValue - } + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: ReferenceWritableKeyPath + ) -> ObserveToken { + bind(binding, to: keyPath) { control, newValue, _ in + control[keyPath: keyPath] = newValue } + } - var actionProxy: TargetActionProxy? { - set { - objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - objc_getAssociatedObject(self, actionProxyKey) as? TargetActionProxy - } + var actionProxy: TargetActionProxy? { + set { + objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } + get { + objc_getAssociatedObject(self, actionProxyKey) as? TargetActionProxy + } + } - func createActionProxyIfNeeded() -> TargetActionProxy { - if let actionProxy { - return actionProxy - } else { - let actionProxy = TargetActionProxy(owner: self) - self.actionProxy = actionProxy - return actionProxy - } + func createActionProxyIfNeeded() -> TargetActionProxy { + if let actionProxy { + return actionProxy + } else { + let actionProxy = TargetActionProxy(owner: self) + self.actionProxy = actionProxy + return actionProxy } + } - /// Establishes a two-way connection between a source of truth and a property of this control. - /// - /// - Parameters: - /// - binding: A source of truth for the control's value. - /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. - /// - set: A closure that is called when the binding's value changes with a weakly-captured - /// control, a new value that can be used to configure the control, and a transaction, which - /// can be used to determine how and if the change should be animated. - /// - Returns: A cancel token. - @discardableResult - public func bind( - _ binding: UIBinding, - to keyPath: KeyPath, - set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void - ) -> ObserveToken { - unbind(keyPath) - let actionProxy = createActionProxyIfNeeded() - let actionID = actionProxy.addBindingAction { [weak self] _ in - guard let self else { return } - binding.wrappedValue = self[keyPath: keyPath] - } + /// Establishes a two-way connection between a source of truth and a property of this control. + /// + /// - Parameters: + /// - binding: A source of truth for the control's value. + /// - keyPath: A key path to the control's value. + /// - event: The control-specific events for which the binding is updated. + /// - set: A closure that is called when the binding's value changes with a weakly-captured + /// control, a new value that can be used to configure the control, and a transaction, which + /// can be used to determine how and if the change should be animated. + /// - Returns: A cancel token. + @discardableResult + public func bind( + _ binding: UIBinding, + to keyPath: KeyPath, + set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void + ) -> ObserveToken { + unbind(keyPath) + let actionProxy = createActionProxyIfNeeded() + let actionID = actionProxy.addBindingAction { [weak self] _ in + guard let self else { return } + binding.wrappedValue = self[keyPath: keyPath] + } - let isSetting = LockIsolated(false) - let token = observe { [weak self] transaction in - guard let self else { return } - isSetting.withValue { $0 = true } - defer { isSetting.withValue { $0 = false } } - set( - self, - binding.wrappedValue, - transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations - ? binding.transaction - : transaction - ) - } - // NB: This key path must only be accessed on the main actor - @UncheckedSendable var uncheckedKeyPath = keyPath - let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in - guard isSetting.withValue({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] - } - } - let observationToken = ObserveToken { [weak self] in - MainActor._assumeIsolated { - self?.actionProxy?.removeAction(for: actionID) - } - token.cancel() - observation.invalidate() - } - observationTokens[keyPath] = observationToken - return observationToken + let isSetting = LockIsolated(false) + let token = observe { [weak self] transaction in + guard let self else { return } + isSetting.withValue { $0 = true } + defer { isSetting.withValue { $0 = false } } + set( + self, + binding.wrappedValue, + transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + @UncheckedSendable var uncheckedKeyPath = keyPath + let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in + guard isSetting.withValue({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + } + } + let observationToken = ObserveToken { [weak self] in + MainActor._assumeIsolated { + self?.actionProxy?.removeAction(for: actionID) + } + token.cancel() + observation.invalidate() } + observationTokens[keyPath] = observationToken + return observationToken + } - public func unbind(_ keyPath: KeyPath) { - observationTokens[keyPath]?.cancel() - observationTokens[keyPath] = nil + public func unbind(_ keyPath: KeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } + + @discardableResult + public func addAction(_ action: @escaping (Self) -> Void) -> UUID { + createActionProxyIfNeeded().addAction { [weak self] _ in + guard let self else { return } + action(self) } + } + + public func removeAction(for id: UUID) { + createActionProxyIfNeeded().removeAction(for: id) + } + public func removeAllActions() { + createActionProxyIfNeeded().removeAllActions() + } } @MainActor extension NSObject { - var observationTokens: [AnyKeyPath: ObserveToken] { - get { - objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObserveToken] - ?? [:] - } - set { - objc_setAssociatedObject( - self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - } + var observationTokens: [AnyKeyPath: ObserveToken] { + get { + objc_getAssociatedObject(self, observationTokensKey) as? [AnyKeyPath: ObserveToken] + ?? [:] + } + set { + objc_setAssociatedObject( + self, observationTokensKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) } + } } @MainActor diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 565c991704..93a36f1a3e 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -157,6 +157,56 @@ extension NSWindow { } } +extension NSViewController { + @discardableResult + public func sheet( + isSheeted: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _sheet(item: item, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } + + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _sheet(item: item, id: id, onDismiss: onDismiss, content: content) + } +} + extension SheetContent { @discardableResult fileprivate func _sheet( @@ -209,8 +259,8 @@ extension SheetContent { content($item) } beginSheet: { [weak self] child, _ in guard let self else { return } - if let attachedSheetWindow = currentWindow?.attachedSheet { - self.endSheet(for: attachedSheetWindow) + if let attachedContent = attachedContent { + self.endSheet(for: attachedContent) onDismiss?() Task { @MainActor in await self.beginSheet(for: child) diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index b8ce7a2245..b8549782a5 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -5,11 +5,14 @@ import AppKit @MainActor protocol SheetContent: NavigationContent { var currentWindow: NSWindow? { get } + var attachedContent: SheetContent? { get } func beginSheet(for content: SheetContent) async func endSheet(for content: SheetContent) } extension SheetContent { + var attachedContent: (any SheetContent)? { currentWindow?.attachedSheet } + func beginSheet(for content: any SheetContent) async { guard let sheetedWindow = content.currentWindow else { return } await currentWindow?.beginSheet(sheetedWindow) @@ -49,4 +52,20 @@ extension NSSavePanel { } } +extension NSViewController: SheetContent { + var currentWindow: NSWindow? { view.window } + + var attachedContent: (any SheetContent)? { currentWindow?.attachedSheet?.contentViewController } + + func beginSheet(for content: any SheetContent) async { + guard let viewController = content as? NSViewController else { return } + presentAsSheet(viewController) + } + + func endSheet(for content: any SheetContent) { + guard let viewController = content as? NSViewController else { return } + dismiss(viewController) + } +} + #endif diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index e36845fde7..5f422637ab 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -28,7 +28,7 @@ + (void)load { class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) ); - method_exchangeImplementations( + method_exchangeImplementations( class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) ); diff --git a/Sources/UIKitNavigation/UIKitAnimation.swift b/Sources/UIKitNavigation/UIKitAnimation.swift index f0fef59eae..425cae34ef 100644 --- a/Sources/UIKitNavigation/UIKitAnimation.swift +++ b/Sources/UIKitNavigation/UIKitAnimation.swift @@ -43,7 +43,7 @@ if #available(iOS 18, macOS 15, tvOS 18, visionOS 2, watchOS 11, *) { var result: Swift.Result? UIView.animate( - with: animation, + animation, changes: { result = Swift.Result(catching: body) }, completion: completion.map { completion in { completion(true) } } ) diff --git a/SwiftNavigation.xcworkspace/xcshareddata/xcschemes/AppKitNavigation.xcscheme b/SwiftNavigation.xcworkspace/xcshareddata/xcschemes/AppKitNavigation.xcscheme new file mode 100644 index 0000000000..74e470a162 --- /dev/null +++ b/SwiftNavigation.xcworkspace/xcshareddata/xcschemes/AppKitNavigation.xcscheme @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + From 15d12e3ba5f98ffba88827900821b12ae3f2dc88 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 11 Jan 2026 21:09:23 +0800 Subject: [PATCH 035/141] Fix error --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 79912487dd..9a264e3830 100644 --- a/Package.swift +++ b/Package.swift @@ -34,7 +34,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-case-paths", from: "1.5.6"), .package(url: "https://github.com/pointfreeco/swift-concurrency-extras", from: "1.2.0"), .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), - .package(url: "https://github.com/pointfreeco/swift-perception", from: "1.3.4"..<"3.0.0"), + .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.1"), ], From 48582044f3f6e784f513b085954b7ebf5b3cc5c8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 24 Jun 2026 17:18:35 +0800 Subject: [PATCH 036/141] Fix AppKitNavigation build under upstream changes Adapt AppKitNavigation to the current state of the package after upstream removed `swift-concurrency-extras`, adopted `InternalImportsByDefault`, and enabled `ExistentialAny`. - Replace `import ConcurrencyExtras` with SwiftNavigation's internal `LockIsolated` (via `@_spi(Internals) public import SwiftNavigation`); switch `withValue`/`@UncheckedSendable` to `withLock`/`nonisolated(unsafe)` to match UIKitNavigation's migration. - Promote `import AppKit` to `public import AppKit` in files that expose AppKit types through public API (NSAlert/NSColorPanel/NSColorWell/ NSDatePicker/NSPathControl/NSProgressIndicator/NSSaveOpenPanel/ NSSegmentedControl/NSSlider/NSStepper/NSSwitch/NSTextField/Modal/ Presentation/PresentationContent/Sheet). - Add `any` to protocol-as-type uses (SheetContent, TargetActionProtocol, NSViewControllerPresentationAnimator). - Drop the redundant `import IssueReporting` in NSSegmentedControl, which caused an ambiguous `reportIssue` call under Xcode's stricter resolution. - Split NSAlert.addButton into two overloads to silence the "default expression for inference" warning. - Clean up Package.swift duplicates (xctest-dynamic-overlay dependency and AppKitNavigation target) and propagate AppKitNavigationShim + IdentifiedCollections to Package@swift-6.0/6.1 manifests so 6.0/6.1 toolchains also build. --- Package.resolved | 57 +++++++++++-------- Package.swift | 7 --- Package@swift-6.0.swift | 8 ++- Package@swift-6.1.swift | 8 ++- .../AppKitNavigation/Bindings/NSAlert.swift | 10 +++- .../Bindings/NSColorPanel.swift | 2 +- .../Bindings/NSColorWell.swift | 2 +- .../Bindings/NSDatePicker.swift | 2 +- .../Bindings/NSFontManager.swift | 17 +++--- .../Bindings/NSPathControl.swift | 2 +- .../Bindings/NSProgressIndicator.swift | 4 +- .../Bindings/NSSaveOpenPanel.swift | 2 +- .../Bindings/NSSegmentedControl.swift | 3 +- .../AppKitNavigation/Bindings/NSSlider.swift | 2 +- .../AppKitNavigation/Bindings/NSStepper.swift | 2 +- .../AppKitNavigation/Bindings/NSSwitch.swift | 2 +- .../Bindings/NSTextField.swift | 4 +- .../Bindings/TargetActionProtocol.swift | 17 +++--- .../Bindings/TargetActionProxy.swift | 4 +- .../AppKitNavigation/Navigation/Modal.swift | 2 +- .../Navigation/Presentation.swift | 4 +- .../Navigation/PresentationContent.swift | 4 +- .../AppKitNavigation/Navigation/Sheet.swift | 2 +- .../Navigation/SheetContent.swift | 6 +- .../xcshareddata/swiftpm/Package.resolved | 24 +++++++- 25 files changed, 116 insertions(+), 81 deletions(-) diff --git a/Package.resolved b/Package.resolved index 3ee1e092b3..03415a25d2 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "15cd96b975d5e3807a52c2b1c6d570b25f285bb14bd48c163416ecbb6bbac386", + "originHash" : "5416cdb1da2655616e71aeb08bc276c32d79f63f560ff62523660acf3baf4a2c", "pins" : [ { "identity" : "swift-case-paths", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { - "revision" : "6989976265be3f8d2b5802c722f9ba168e227c71", - "version" : "1.7.2" + "revision" : "1197e80bc7e4b177051b6869ef93d8ac3ad677da", + "version" : "1.8.0" } }, { @@ -15,17 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections", "state" : { - "revision" : "7b847a3b7008b2dc2f47ca3110d8c782fb2e5c7e", - "version" : "1.3.0" - } - }, - { - "identity" : "swift-concurrency-extras", - "kind" : "remoteSourceControl", - "location" : "https://github.com/pointfreeco/swift-concurrency-extras", - "state" : { - "revision" : "5a3825302b1a0d744183200915a47b508c828e6f", - "version" : "1.3.2" + "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", + "version" : "1.6.0" } }, { @@ -33,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-custom-dump", "state" : { - "revision" : "82645ec760917961cfa08c9c0c7104a57a0fa4b1", - "version" : "1.3.3" + "revision" : "a8cd6c976f335ed361dcecddb0dc39ebda51bc3e", + "version" : "1.6.1" } }, { @@ -42,8 +33,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-docc-plugin", "state" : { - "revision" : "3e4f133a77e644a5812911a0513aeb7288b07d06", - "version" : "1.4.5" + "revision" : "647c708be89f834fa6a6d4945442793a77ddf5b6", + "version" : "1.5.0" } }, { @@ -64,13 +55,31 @@ "version" : "1.1.1" } }, + { + "identity" : "swift-macro-testing", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-macro-testing", + "state" : { + "revision" : "2e494c632d510715c96a694ff25e2a8d4ac3f64b", + "version" : "0.6.5" + } + }, { "identity" : "swift-perception", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-perception", "state" : { - "revision" : "d924c62a70fca5f43872f286dbd7cef0957f1c01", - "version" : "1.6.0" + "revision" : "25ac73741c3436605d61eceb5207e896973918e7", + "version" : "2.0.10" + } + }, + { + "identity" : "swift-snapshot-testing", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-snapshot-testing", + "state" : { + "revision" : "ad5e3190cc63dc288f28546f9c6827efc1e9d495", + "version" : "1.19.2" } }, { @@ -78,8 +87,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax", "state" : { - "revision" : "f99ae8aa18f0cf0d53481901f88a0991dc3bd4a2", - "version" : "601.0.1" + "revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1", + "version" : "603.0.2" } }, { @@ -87,8 +96,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", "state" : { - "revision" : "4c27acf5394b645b70d8ba19dc249c0472d5f618", - "version" : "1.7.0" + "revision" : "401bf70d95bfe8db2a1dc619f9e175a85c089321", + "version" : "1.10.1" } } ], diff --git a/Package.swift b/Package.swift index 993e8b9d05..e6768f3c02 100644 --- a/Package.swift +++ b/Package.swift @@ -65,7 +65,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.1"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.8.0"), - .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.1"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), .package(url: "https://github.com/swiftlang/swift-syntax", "509.0.0"..<"605.0.0"), ], @@ -203,12 +202,6 @@ let package = Package( .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), ] ), - .target( - name: "AppKitNavigation", - dependencies: [ - "SwiftNavigation" - ] - ), ], swiftLanguageModes: [.v6] ) diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index c179388e32..2d692daf37 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -35,6 +35,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.6.0"), .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.8.0"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.1"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -114,9 +115,14 @@ let package = Package( .target( name: "AppKitNavigation", dependencies: [ - "SwiftNavigation" + "SwiftNavigation", + "AppKitNavigationShim", + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), + .target( + name: "AppKitNavigationShim" + ), ], swiftLanguageModes: [.v6] ) diff --git a/Package@swift-6.1.swift b/Package@swift-6.1.swift index f2a5e4dc9a..100cf6c2a5 100644 --- a/Package@swift-6.1.swift +++ b/Package@swift-6.1.swift @@ -62,6 +62,7 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.6.0"), .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), + .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.8.0"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.4.1"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -192,9 +193,14 @@ let package = Package( .target( name: "AppKitNavigation", dependencies: [ - "SwiftNavigation" + "SwiftNavigation", + "AppKitNavigationShim", + .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), + .target( + name: "AppKitNavigationShim" + ), ], swiftLanguageModes: [.v6] ) diff --git a/Sources/AppKitNavigation/Bindings/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift index 812f894812..24cc2c2b01 100644 --- a/Sources/AppKitNavigation/Bindings/NSAlert.swift +++ b/Sources/AppKitNavigation/Bindings/NSAlert.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSAlert { /// Creates and returns a alert for displaying an alert using a data description. @@ -22,9 +22,15 @@ extension NSAlert { } extension NSAlert { + public func addButton( + _ buttonState: ButtonState + ) { + addButton(buttonState) { _ in } + } + public func addButton( _ buttonState: ButtonState, - action handler: @escaping (_ action: Action?) -> Void = { (_: Never?) in } + action handler: @escaping (_ action: Action?) -> Void ) { let button = addButton(withTitle: String(state: buttonState.label)) diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index 79adfd1851..b6c8092242 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSColorPanel: @retroactive Sendable {} extension NSColorPanel: TargetActionProtocol { diff --git a/Sources/AppKitNavigation/Bindings/NSColorWell.swift b/Sources/AppKitNavigation/Bindings/NSColorWell.swift index 71eab79865..b2c99fc415 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorWell.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorWell.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSColorWell { /// Creates a new color well with the specified frame and registers the binding against the diff --git a/Sources/AppKitNavigation/Bindings/NSDatePicker.swift b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift index 17e3d26ecd..cbb8b46881 100755 --- a/Sources/AppKitNavigation/Bindings/NSDatePicker.swift +++ b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSDatePicker { /// Creates a new date picker with the specified frame and registers the binding against the diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 8bc2fef516..8c28c5bc6a 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -1,8 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import ConcurrencyExtras -@_spi(Internals) import SwiftNavigation -import AppKit +@_spi(Internals) public import SwiftNavigation +public import AppKit import IdentifiedCollections @MainActor @@ -131,8 +130,8 @@ extension NSFontManager { let isSetting = LockIsolated(false) let token = observe { [weak self] transaction in guard let self else { return } - isSetting.withValue { $0 = true } - defer { isSetting.withValue { $0 = false } } + isSetting.withLock { $0 = true } + defer { isSetting.withLock { $0 = false } } set( self, binding.wrappedValue, @@ -142,11 +141,11 @@ extension NSFontManager { ) } // NB: This key path must only be accessed on the main actor - @UncheckedSendable var uncheckedKeyPath = keyPath - let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in - guard isSetting.withValue({ !$0 }) else { return } + nonisolated(unsafe) let uncheckedKeyPath = keyPath + let observation = observe(keyPath) { control, _ in + guard isSetting.withLock({ !$0 }) else { return } MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + binding.wrappedValue = control[keyPath: uncheckedKeyPath] } } let observationToken = ObserveToken { [weak self] in diff --git a/Sources/AppKitNavigation/Bindings/NSPathControl.swift b/Sources/AppKitNavigation/Bindings/NSPathControl.swift index fda06940be..3a9b53f9c0 100755 --- a/Sources/AppKitNavigation/Bindings/NSPathControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSPathControl.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSPathControl { /// Creates a new path control with the specified frame and registers the binding against the diff --git a/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift index 1719443cb2..d3d6d05d8b 100644 --- a/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift +++ b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit -import SwiftNavigation +public import AppKit +public import SwiftNavigation extension NSProgressIndicator { diff --git a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift index 8220b89367..aca52dab7c 100755 --- a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit import AppKitNavigationShim extension NSSavePanel { diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift index 25b1bdd441..929c5744e3 100755 --- a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -1,6 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import IssueReporting -import AppKit +public import AppKit extension NSSegmentedControl { /// Creates a new color well with the specified frame and registers the binding against the diff --git a/Sources/AppKitNavigation/Bindings/NSSlider.swift b/Sources/AppKitNavigation/Bindings/NSSlider.swift index 7931a6d921..1e091af00b 100755 --- a/Sources/AppKitNavigation/Bindings/NSSlider.swift +++ b/Sources/AppKitNavigation/Bindings/NSSlider.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSSlider { /// Creates a new slider with the specified frame and registers the binding against the value. diff --git a/Sources/AppKitNavigation/Bindings/NSStepper.swift b/Sources/AppKitNavigation/Bindings/NSStepper.swift index 59a679d71f..75eaa1e52f 100755 --- a/Sources/AppKitNavigation/Bindings/NSStepper.swift +++ b/Sources/AppKitNavigation/Bindings/NSStepper.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSStepper { /// Creates a new stepper with the specified frame and registers the binding against the value. diff --git a/Sources/AppKitNavigation/Bindings/NSSwitch.swift b/Sources/AppKitNavigation/Bindings/NSSwitch.swift index 60a92b14fa..e643487ec0 100755 --- a/Sources/AppKitNavigation/Bindings/NSSwitch.swift +++ b/Sources/AppKitNavigation/Bindings/NSSwitch.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSSwitch { /// Creates a new switch with the specified frame and registers the binding against whether or diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 8b9182aa08..0e3ed6730b 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -1,7 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit import Combine -import SwiftNavigation +public import SwiftNavigation @MainActor extension NSTextField: @retroactive NSTextDelegate {} diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index a9ab01f311..acc34394fd 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -1,7 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import ConcurrencyExtras -@_spi(Internals) import SwiftNavigation -import AppKit +@_spi(Internals) public import SwiftNavigation +public import AppKit /// A protocol used to extend `NSControl, NSMenuItem...`. @MainActor @@ -73,8 +72,8 @@ extension TargetActionProtocol { let isSetting = LockIsolated(false) let token = observe { [weak self] transaction in guard let self else { return } - isSetting.withValue { $0 = true } - defer { isSetting.withValue { $0 = false } } + isSetting.withLock { $0 = true } + defer { isSetting.withLock { $0 = false } } set( self, binding.wrappedValue, @@ -84,11 +83,11 @@ extension TargetActionProtocol { ) } // NB: This key path must only be accessed on the main actor - @UncheckedSendable var uncheckedKeyPath = keyPath - let observation = observe(keyPath) { [$uncheckedKeyPath] control, _ in - guard isSetting.withValue({ !$0 }) else { return } + nonisolated(unsafe) let uncheckedKeyPath = keyPath + let observation = observe(keyPath) { control, _ in + guard isSetting.withLock({ !$0 }) else { return } MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: $uncheckedKeyPath.wrappedValue] + binding.wrappedValue = control[keyPath: uncheckedKeyPath] } } let observationToken = ObserveToken { [weak self] in diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 961235ff1e..239e32672f 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -27,9 +27,9 @@ class TargetActionProxy: NSObject { private var originAction: Selector? - weak var owner: TargetActionProtocol? + weak var owner: (any TargetActionProtocol)? - required init(owner: TargetActionProtocol) { + required init(owner: any TargetActionProtocol) { self.owner = owner super.init() self.originTarget = owner.target diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 6ac702ac14..46ed6d42f5 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit @MainActor private var ModalObserverKeys = AssociatedKeys() diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index f90ec118a3..eb2abef201 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import SwiftNavigation -import AppKit +public import SwiftNavigation +public import AppKit import AppKitNavigationShim class PresentationObserver: NavigationObserver { diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift index 907536422c..fb6b85ad1a 100644 --- a/Sources/AppKitNavigation/Navigation/PresentationContent.swift +++ b/Sources/AppKitNavigation/Navigation/PresentationContent.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit @MainActor protocol PresentationContent: NavigationContent { @@ -21,7 +21,7 @@ extension NSViewController: PresentationContent { case sheet case modalWindow case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) - case custom(NSViewControllerPresentationAnimator) + case custom(any NSViewControllerPresentationAnimator) } func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 93a36f1a3e..5bb6f70211 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit private typealias SheetObserver = NavigationObserver diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index b8549782a5..299a4145df 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -5,9 +5,9 @@ import AppKit @MainActor protocol SheetContent: NavigationContent { var currentWindow: NSWindow? { get } - var attachedContent: SheetContent? { get } - func beginSheet(for content: SheetContent) async - func endSheet(for content: SheetContent) + var attachedContent: (any SheetContent)? { get } + func beginSheet(for content: any SheetContent) async + func endSheet(for content: any SheetContent) } extension SheetContent { diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index 4e7a6a30d1..065c79528b 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "fd561772dbb7da88879cfbd7ad587c7c0f94bd076b6d0e00f7d2d67ac20cb3a8", + "originHash" : "5459de6c7e9e8daaaec6ad4ddafe2158d2f46f43942a81d83636d6cdffc599af", "pins" : [ { "identity" : "combine-schedulers", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { - "revision" : "19b7263bacb9751f151ec0c93ec816fe1ef67c7b", - "version" : "1.6.1" + "revision" : "1197e80bc7e4b177051b6869ef93d8ac3ad677da", + "version" : "1.8.0" } }, { @@ -91,6 +91,15 @@ "version" : "1.1.1" } }, + { + "identity" : "swift-macro-testing", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-macro-testing", + "state" : { + "revision" : "2e494c632d510715c96a694ff25e2a8d4ac3f64b", + "version" : "0.6.5" + } + }, { "identity" : "swift-perception", "kind" : "remoteSourceControl", @@ -100,6 +109,15 @@ "version" : "1.5.0" } }, + { + "identity" : "swift-snapshot-testing", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-snapshot-testing", + "state" : { + "revision" : "ad5e3190cc63dc288f28546f9c6827efc1e9d495", + "version" : "1.19.2" + } + }, { "identity" : "swift-syntax", "kind" : "remoteSourceControl", From eb2eacadb466afd2389944346c0ac36c1d240af9 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 24 Jun 2026 17:18:46 +0800 Subject: [PATCH 037/141] Add `popover` navigation for AppKit Introduce `NSView.popover(...)` driven by `NSPopover` (not `NSViewController.present(_:asPopoverRelativeTo:...)`), mirroring the existing `PopoverContent` / `PopoverObserver` shape used by Sheet, Modal, and Presentation. - `PopoverContent` protocol + default `show`/`close` extension that wires `NSPopover.didCloseNotification` into the binding lifecycle so transient popovers dismissed by clicking outside reset the source-of-truth. - Fileprivate `_PopoverPresentation` wraps a user-supplied `NSViewController` with an internally-managed `NSPopover` so the public `content` closure stays VC-only; popover knobs (`behavior`, `animates`) move onto the `popover(...)` method itself. - `PopoverPresentationsObserver` singleton retains active popovers (an `NSPopover` is not self-retained by `show`) and clears them on close, mirroring `ModalWindowsObserver`. - Public API: 5 overloads on `NSView` (`isPresented`, `item: Identifiable` value/binding, `item:id:KeyPath` value/binding) with `relativeTo`, `preferredEdge`, `behavior`, `animates`, `onDismiss`. --- .../PopoverPresentationsObserver.swift | 24 ++ .../AppKitNavigation/Navigation/Popover.swift | 305 ++++++++++++++++++ .../Navigation/PopoverContent.swift | 25 ++ 3 files changed, 354 insertions(+) create mode 100644 Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift create mode 100644 Sources/AppKitNavigation/Navigation/Popover.swift create mode 100644 Sources/AppKitNavigation/Navigation/PopoverContent.swift diff --git a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift new file mode 100644 index 0000000000..043449fb5f --- /dev/null +++ b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift @@ -0,0 +1,24 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit +import Combine + +@MainActor +final class PopoverPresentationsObserver: NSObject { + static let shared = PopoverPresentationsObserver() + + var popoverCancellables: [NSPopover: AnyCancellable] = [:] + + func observePopover(_ popover: NSPopover, onDidClose: @escaping @MainActor () -> Void) { + popoverCancellables[popover] = NotificationCenter.default + .publisher(for: NSPopover.didCloseNotification, object: popover) + .sink { [weak self] _ in + MainActor._assumeIsolated { + onDidClose() + self?.popoverCancellables.removeValue(forKey: popover) + } + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Popover.swift b/Sources/AppKitNavigation/Navigation/Popover.swift new file mode 100644 index 0000000000..b3b301f034 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Popover.swift @@ -0,0 +1,305 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +public import AppKit + +@MainActor +fileprivate final class _PopoverPresentation: NSObject, PopoverContent { + let popover: NSPopover + + init( + viewController: NSViewController, + behavior: NSPopover.Behavior, + animates: Bool + ) { + let popover = NSPopover() + popover.contentViewController = viewController + popover.behavior = behavior + popover.animates = animates + self.popover = popover + super.init() + } +} + +private typealias PopoverObserver = NavigationObserver + +@MainActor +private let popoverObserverKey = malloc(1)! + +extension NSView { + @discardableResult + public func popover( + isPresented: UIBinding, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + _popover( + isPresented: isPresented, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + public func popover( + item: UIBinding, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @_disfavoredOverload + @discardableResult + public func popover( + item: UIBinding, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: id, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: id, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } +} + +extension NSView { + @discardableResult + fileprivate func _popover( + isPresented: UIBinding, + relativeTo rect: NSRect, + preferredEdge: NSRectEdge, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + _popover( + item: isPresented.toOptionalUnit, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss + ) { _ in content() } + } + + @discardableResult + fileprivate func _popover( + item: UIBinding, + relativeTo rect: NSRect, + preferredEdge: NSRectEdge, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: \.id, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @_disfavoredOverload + @discardableResult + fileprivate func _popover( + item: UIBinding, + relativeTo rect: NSRect, + preferredEdge: NSRectEdge, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: \.id, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + fileprivate func _popover( + item: UIBinding, + id: KeyPath, + relativeTo rect: NSRect, + preferredEdge: NSRectEdge, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: id, + relativeTo: rect, + preferredEdge: preferredEdge, + behavior: behavior, + animates: animates, + onDismiss: onDismiss + ) { + content($0.wrappedValue) + } + } + + @discardableResult + fileprivate func _popover( + item: UIBinding, + id: KeyPath, + relativeTo rect: NSRect, + preferredEdge: NSRectEdge, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover(item: item, id: id) { binding in + _PopoverPresentation( + viewController: content(binding), + behavior: behavior, + animates: animates + ) + } beginPopover: { [weak self] presentation, _ in + guard let self else { return } + presentation.appKitNavigationShowPopover( + relativeTo: rect, + of: self, + preferredEdge: preferredEdge + ) + } endPopover: { presentation, _ in + presentation.appKitNavigationClosePopover() + onDismiss?() + } + } + + private func _popover( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> _PopoverPresentation, + beginPopover: @escaping ( + _ child: _PopoverPresentation, + _ transaction: UITransaction + ) -> Void, + endPopover: @escaping ( + _ child: _PopoverPresentation, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let popoverObserver = popoverObserver() + return popoverObserver.observe( + item: item, + id: { $0[keyPath: id] }, + content: content, + begin: beginPopover, + end: endPopover + ) + } + + private func popoverObserver() -> PopoverObserver { + if let observer = objc_getAssociatedObject(self, popoverObserverKey) as? PopoverObserver { + return observer + } else { + let observer = PopoverObserver(owner: self) + objc_setAssociatedObject( + self, + popoverObserverKey, + observer, + .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + return observer + } + } +} + +extension Navigated where Content: PopoverContent { + func clearup() { + content?.appKitNavigationClosePopover() + } +} + +#endif diff --git a/Sources/AppKitNavigation/Navigation/PopoverContent.swift b/Sources/AppKitNavigation/Navigation/PopoverContent.swift new file mode 100644 index 0000000000..451b817ca1 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/PopoverContent.swift @@ -0,0 +1,25 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +@MainActor +protocol PopoverContent: NavigationContent { + var popover: NSPopover { get } + func appKitNavigationShowPopover(relativeTo rect: NSRect, of view: NSView, preferredEdge: NSRectEdge) + func appKitNavigationClosePopover() +} + +extension PopoverContent { + func appKitNavigationShowPopover(relativeTo rect: NSRect, of view: NSView, preferredEdge: NSRectEdge) { + PopoverPresentationsObserver.shared.observePopover(popover) { [weak self] in + self?.onEndNavigation?() + } + popover.show(relativeTo: rect, of: view, preferredEdge: preferredEdge) + } + + func appKitNavigationClosePopover() { + popover.close() + } +} + +#endif From 97b2ae15bb00a9f29299cada48fdbb2785cbd1bb Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 25 Jun 2026 11:19:27 +0800 Subject: [PATCH 038/141] Add `popover` support for `NSToolbarItem` (macOS 14+) `NSPopover.show(relativeTo:)` was added in macOS 14 to anchor a popover to a toolbar item. Expose it through the same family of `popover(...)` bindings already provided on `NSView`, omitting the `rect` and `preferredEdge` parameters that the toolbar-item API does not accept. --- .../AppKitNavigation/Navigation/Popover.swift | 237 ++++++++++++++++++ .../Navigation/PopoverContent.swift | 8 + 2 files changed, 245 insertions(+) diff --git a/Sources/AppKitNavigation/Navigation/Popover.swift b/Sources/AppKitNavigation/Navigation/Popover.swift index b3b301f034..0849287468 100644 --- a/Sources/AppKitNavigation/Navigation/Popover.swift +++ b/Sources/AppKitNavigation/Navigation/Popover.swift @@ -302,4 +302,241 @@ extension Navigated where Content: PopoverContent { } } +@available(macOS 14.0, *) +private typealias ToolbarItemPopoverObserver = NavigationObserver + +@MainActor +private let toolbarItemPopoverObserverKey = malloc(1)! + +@available(macOS 14.0, *) +extension NSToolbarItem { + @discardableResult + public func popover( + isPresented: UIBinding, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + _popover( + isPresented: isPresented, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + public func popover( + item: UIBinding, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @_disfavoredOverload + @discardableResult + public func popover( + item: UIBinding, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: id, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: id, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } +} + +@available(macOS 14.0, *) +extension NSToolbarItem { + @discardableResult + fileprivate func _popover( + isPresented: UIBinding, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + _popover( + item: isPresented.toOptionalUnit, + behavior: behavior, + animates: animates, + onDismiss: onDismiss + ) { _ in content() } + } + + @discardableResult + fileprivate func _popover( + item: UIBinding, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: \.id, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @_disfavoredOverload + @discardableResult + fileprivate func _popover( + item: UIBinding, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: \.id, + behavior: behavior, + animates: animates, + onDismiss: onDismiss, + content: content + ) + } + + @discardableResult + fileprivate func _popover( + item: UIBinding, + id: KeyPath, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + _popover( + item: item, + id: id, + behavior: behavior, + animates: animates, + onDismiss: onDismiss + ) { + content($0.wrappedValue) + } + } + + @discardableResult + fileprivate func _popover( + item: UIBinding, + id: KeyPath, + behavior: NSPopover.Behavior, + animates: Bool, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + _popover(item: item, id: id) { binding in + _PopoverPresentation( + viewController: content(binding), + behavior: behavior, + animates: animates + ) + } beginPopover: { [weak self] presentation, _ in + guard let self else { return } + presentation.appKitNavigationShowPopover(relativeTo: self) + } endPopover: { presentation, _ in + presentation.appKitNavigationClosePopover() + onDismiss?() + } + } + + private func _popover( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> _PopoverPresentation, + beginPopover: @escaping ( + _ child: _PopoverPresentation, + _ transaction: UITransaction + ) -> Void, + endPopover: @escaping ( + _ child: _PopoverPresentation, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + let popoverObserver = popoverObserver() + return popoverObserver.observe( + item: item, + id: { $0[keyPath: id] }, + content: content, + begin: beginPopover, + end: endPopover + ) + } + + private func popoverObserver() -> ToolbarItemPopoverObserver { + if let observer = objc_getAssociatedObject(self, toolbarItemPopoverObserverKey) as? ToolbarItemPopoverObserver { + return observer + } else { + let observer = ToolbarItemPopoverObserver(owner: self) + objc_setAssociatedObject( + self, + toolbarItemPopoverObserverKey, + observer, + .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + return observer + } + } +} + #endif diff --git a/Sources/AppKitNavigation/Navigation/PopoverContent.swift b/Sources/AppKitNavigation/Navigation/PopoverContent.swift index 451b817ca1..0131e45ed0 100644 --- a/Sources/AppKitNavigation/Navigation/PopoverContent.swift +++ b/Sources/AppKitNavigation/Navigation/PopoverContent.swift @@ -17,6 +17,14 @@ extension PopoverContent { popover.show(relativeTo: rect, of: view, preferredEdge: preferredEdge) } + @available(macOS 14.0, *) + func appKitNavigationShowPopover(relativeTo toolbarItem: NSToolbarItem) { + PopoverPresentationsObserver.shared.observePopover(popover) { [weak self] in + self?.onEndNavigation?() + } + popover.show(relativeTo: toolbarItem) + } + func appKitNavigationClosePopover() { popover.close() } From 3c81b1006da473b8b50e2e118585080c6b2193c8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 25 Jun 2026 11:52:34 +0800 Subject: [PATCH 039/141] Keep `_PopoverPresentation` alive across `NSPopover` lifecycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Navigated.content` is held weakly and `NSPopover` does not retain its `PopoverContent` host, so `_PopoverPresentation` was deallocated as soon as `begin(...)` returned. The `didCloseNotification` sink captured the host weakly, so `onEndNavigation` ran on a nil reference, the binding was never reset to `false`, and `navigatedByID` retained the prior id — blocking any subsequent presentation. Capture `self` strongly in the close subscription; lifetime stays bounded because the sink removes the cancellable from `PopoverPresentationsObserver.shared` once the close notification fires. --- .../AppKitNavigation/Navigation/PopoverContent.swift | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Sources/AppKitNavigation/Navigation/PopoverContent.swift b/Sources/AppKitNavigation/Navigation/PopoverContent.swift index 0131e45ed0..59e4037205 100644 --- a/Sources/AppKitNavigation/Navigation/PopoverContent.swift +++ b/Sources/AppKitNavigation/Navigation/PopoverContent.swift @@ -11,16 +11,20 @@ protocol PopoverContent: NavigationContent { extension PopoverContent { func appKitNavigationShowPopover(relativeTo rect: NSRect, of view: NSView, preferredEdge: NSRectEdge) { - PopoverPresentationsObserver.shared.observePopover(popover) { [weak self] in - self?.onEndNavigation?() + // `Navigated` holds `self` weakly, and `NSPopover` does not retain its + // `PopoverContent` host, so we must keep `self` alive through the close + // subscription. Otherwise `onEndNavigation` runs on a deallocated `self` + // and the binding is never reset, leaving the popover unable to reopen. + PopoverPresentationsObserver.shared.observePopover(popover) { [self] in + self.onEndNavigation?() } popover.show(relativeTo: rect, of: view, preferredEdge: preferredEdge) } @available(macOS 14.0, *) func appKitNavigationShowPopover(relativeTo toolbarItem: NSToolbarItem) { - PopoverPresentationsObserver.shared.observePopover(popover) { [weak self] in - self?.onEndNavigation?() + PopoverPresentationsObserver.shared.observePopover(popover) { [self] in + self.onEndNavigation?() } popover.show(relativeTo: toolbarItem) } From ad18e298db21474f9516c6d5d014942d05661dff Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 29 Jul 2026 22:06:34 +0800 Subject: [PATCH 040/141] Make AppKitNavigation imports `public` for library evolution Expose `AppKit`, `Combine`, and `IdentifiedCollections` via `public import` so the types they surface satisfy access-level-on-imports checks, matching the recently enabled `CheckImplementationOnly` feature. `Package.resolved` picks up the newly pinned `swift-collections` and `swift-identified-collections`. --- Package.resolved | 20 ++++++++++++++++++- .../Bindings/NSFontManager.swift | 2 +- .../Bindings/TargetActionProxy.swift | 4 ++-- .../Internal/ModalWindowsObserver.swift | 4 ++-- .../PopoverPresentationsObserver.swift | 4 ++-- 5 files changed, 26 insertions(+), 8 deletions(-) diff --git a/Package.resolved b/Package.resolved index 7ae7ea869d..bde244cd2b 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "fdc10853c1416eddaab5f368180b2890aa34ef46ff72e4ae1e58d0d63371abe5", + "originHash" : "a5f49799d3a165929f0773ae888b60c9cc72bdbcd87aab4044f78366d5c28585", "pins" : [ { "identity" : "swift-case-paths", @@ -10,6 +10,15 @@ "version" : "1.8.0" } }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections", + "state" : { + "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", + "version" : "1.6.0" + } + }, { "identity" : "swift-custom-dump", "kind" : "remoteSourceControl", @@ -37,6 +46,15 @@ "version" : "1.0.0" } }, + { + "identity" : "swift-identified-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-identified-collections", + "state" : { + "revision" : "322d9ffeeba85c9f7c4984b39422ec7cc3c56597", + "version" : "1.1.1" + } + }, { "identity" : "swift-macro-testing", "kind" : "remoteSourceControl", diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 8c28c5bc6a..9100f81d4d 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -2,7 +2,7 @@ @_spi(Internals) public import SwiftNavigation public import AppKit -import IdentifiedCollections +public import IdentifiedCollections @MainActor extension NSFontManager: @unchecked @retroactive Sendable { diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 239e32672f..f2dec4ec5c 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -1,7 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit -import IdentifiedCollections +public import AppKit +public import IdentifiedCollections @MainActor class TargetActionProxy: NSObject { diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift index a95607191e..55de75fb8f 100644 --- a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift +++ b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift @@ -1,7 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit -import Combine +public import AppKit +public import Combine @MainActor class ModalWindowsObserver: NSObject { diff --git a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift index 043449fb5f..f03a8e6c32 100644 --- a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift +++ b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift @@ -1,7 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit -import Combine +public import AppKit +public import Combine @MainActor final class PopoverPresentationsObserver: NSObject { From 00ff13d4cffc9690b8127d1ab35cf2c54a3eaf4c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 5 Sep 2026 13:56:39 +0800 Subject: [PATCH 041/141] fix(appkit): keep the progress indicator's isAnimated binding alive `bind(isAnimated:)` wrapped its observation in a freshly created `ObserveToken` and returned it without retaining it anywhere. Since the method is marked `@discardableResult`, the ordinary call site dropped that wrapper, it deallocated at the end of the statement, and its `deinit` cancelled the observation behind it. The indicator therefore honoured the binding once, synchronously, and never reacted to a change again. `init(frame:isAnimated:)` discards the token internally, so it had the same defect. Every other binding in the module already stores its token on the receiver via an associated object; this one was the only exception. Store it the same way and add `unbindIsAnimated()` to match `unbindURL()` and `unbind(_:)`. Adds an `AppKitNavigationTests` target, which the module did not have. The regression test fails against the previous implementation with `("[false]") is not equal to ("[false, true]")`. --- Package.swift | 7 ++ .../Bindings/NSProgressIndicator.swift | 44 +++++++++--- .../NSProgressIndicatorTests.swift | 72 +++++++++++++++++++ 3 files changed, 114 insertions(+), 9 deletions(-) create mode 100644 Tests/AppKitNavigationTests/NSProgressIndicatorTests.swift diff --git a/Package.swift b/Package.swift index 3b03a0f9e1..5db7314082 100644 --- a/Package.swift +++ b/Package.swift @@ -202,6 +202,13 @@ let package = Package( .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), ] ), + .testTarget( + name: "AppKitNavigationTests", + dependencies: [ + "AppKitNavigation", + .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), + ] + ), ], swiftLanguageModes: [.v6] ) diff --git a/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift index d3d6d05d8b..b0655848bc 100644 --- a/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift +++ b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift @@ -3,30 +3,56 @@ public import AppKit public import SwiftNavigation extension NSProgressIndicator { - + /// Creates a new progress indicator with the specified frame and registers the binding against + /// its animation state. + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - isAnimated: The binding to read from for whether the indicator should animate. public convenience init(frame: CGRect = .zero, isAnimated: UIBinding) { self.init(frame: frame) bind(isAnimated: isAnimated) } - + + /// Establishes a connection between a binding and the progress indicator's animation state. + /// + /// - Parameter isAnimated: The binding to read from for whether the indicator should animate. + /// - Returns: A cancel token. @discardableResult public func bind(isAnimated: UIBinding) -> ObserveToken { + unbindIsAnimated() let token = observe { [weak self] in guard let self else { return } - let isAnimated = isAnimated.wrappedValue - if isAnimated { + if isAnimated.wrappedValue { startAnimation(nil) } else { stopAnimation(nil) } } - - let observeToken = ObserveToken { - token.cancel() + // NB: The token has to be retained by the progress indicator itself. Returning a freshly + // created token would cancel the observation the moment the caller discarded it, which + // 'bind' is marked '@discardableResult' to encourage. + let observationToken = ObserveToken { token.cancel() } + isAnimatedToken = observationToken + return observationToken + } + + /// Cancels the connection established by ``bind(isAnimated:)``. + public func unbindIsAnimated() { + isAnimatedToken?.cancel() + isAnimatedToken = nil + } + + private var isAnimatedToken: ObserveToken? { + get { objc_getAssociatedObject(self, Self.isAnimatedTokenKey) as? ObserveToken } + set { + objc_setAssociatedObject( + self, Self.isAnimatedTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) } - return observeToken } - + + private static let isAnimatedTokenKey = malloc(1)! } #endif diff --git a/Tests/AppKitNavigationTests/NSProgressIndicatorTests.swift b/Tests/AppKitNavigationTests/NSProgressIndicatorTests.swift new file mode 100644 index 0000000000..abb9721ea3 --- /dev/null +++ b/Tests/AppKitNavigationTests/NSProgressIndicatorTests.swift @@ -0,0 +1,72 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKitNavigation + import XCTest + + final class NSProgressIndicatorTests: XCTestCase { + /// Records animation requests instead of running them, so the binding can be observed without + /// a window or a run loop. + private final class SpyProgressIndicator: NSProgressIndicator { + nonisolated(unsafe) var animationRequests: [Bool] = [] + + override func startAnimation(_ sender: Any?) { + animationRequests.append(true) + } + + override func stopAnimation(_ sender: Any?) { + animationRequests.append(false) + } + } + + /// The binding used to stop working as soon as the caller discarded the returned token: the + /// token was freshly created and retained by nobody, so it deallocated at the end of the + /// statement and cancelled the observation behind it. + @MainActor + func testKeepsObservingWhenTheTokenIsDiscarded() async { + @UIBinding var isAnimated = false + let progressIndicator = SpyProgressIndicator() + + progressIndicator.bind(isAnimated: $isAnimated) + XCTAssertEqual(progressIndicator.animationRequests, [false]) + + isAnimated = true + await Task.yield() + XCTAssertEqual(progressIndicator.animationRequests, [false, true]) + + isAnimated = false + await Task.yield() + XCTAssertEqual(progressIndicator.animationRequests, [false, true, false]) + } + + @MainActor + func testUnbindStopsObserving() async { + @UIBinding var isAnimated = false + let progressIndicator = SpyProgressIndicator() + + progressIndicator.bind(isAnimated: $isAnimated) + progressIndicator.unbindIsAnimated() + + isAnimated = true + await Task.yield() + XCTAssertEqual(progressIndicator.animationRequests, [false]) + } + + @MainActor + func testRebindingReplacesThePreviousBinding() async { + @UIBinding var first = false + @UIBinding var second = false + let progressIndicator = SpyProgressIndicator() + + progressIndicator.bind(isAnimated: $first) + progressIndicator.bind(isAnimated: $second) + progressIndicator.animationRequests.removeAll() + + first = true + await Task.yield() + XCTAssertEqual(progressIndicator.animationRequests, [], "the replaced binding must be silent") + + second = true + await Task.yield() + XCTAssertEqual(progressIndicator.animationRequests, [true]) + } + } +#endif From f7b57240a1472e6fb4eae70ce2375b3adfe6b87c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 5 Sep 2026 13:56:52 +0800 Subject: [PATCH 042/141] feat(appkit): register an additional target-action pair on macOS 27 `TargetActionProxy` took over a control's single `target` / `action` pair, saving the previous one and forwarding to it. That keeps a pair installed *before* the first binding working, but assigning `target` or `action` afterwards silently unhooks the proxy, and every binding and closure action on that control stops firing. AppKit has stored several target-action pairs per control since macOS 11 (`addTarget:action:forControlEvents:`), which removes the need to seize the pair at all. The API is only published in the macOS 27 SDK, so declare it in the shim behind an SDK check that compiles away once that SDK is in use. The events are not as old as the API, though. Measured on macOS 26.6, a button click delivers only `trackingBegan` and `trackingEndedInside`; `valueChanged` and `primaryActionTriggered` are never sent, and tracking events do not stand for "the action fired" (a keyboard-driven button never tracks). So the proxy registers as an additional target from macOS 27 on and keeps taking the pair over below that. Text fields deliberately do not register `valueChanged`: their per-keystroke changes already arrive through `textDidChangeNotification` on every version, and registering both would deliver each edit twice. Two things to know when touching the shim: - Do not copy `NS_SWIFT_NAME(NSControl.Events)` from the SDK. Nesting a type inside a class owned by a different module makes the Swift importer drop the whole declaration, methods included. - Never spell the option set at the call site. It is `NSControlEvents` from the shim and `NSControl.Events` from the macOS 27 SDK; an array literal infers under both. Built against both the macOS 26 and macOS 27 SDKs. The macOS 27 path itself is unverified at runtime for want of a machine running it; the tests are written as cross-path contracts so running them there confirms it. --- .../Bindings/TargetActionProxy.swift | 54 ++++++++- Sources/AppKitNavigationShim/include/shim.h | 63 ++++++++++ .../TargetActionTests.swift | 108 ++++++++++++++++++ 3 files changed, 219 insertions(+), 6 deletions(-) create mode 100644 Tests/AppKitNavigationTests/TargetActionTests.swift diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index f2dec4ec5c..aedc7b2a09 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -2,6 +2,7 @@ public import AppKit public import IdentifiedCollections +import AppKitNavigationShim @MainActor class TargetActionProxy: NSObject { @@ -27,17 +28,56 @@ class TargetActionProxy: NSObject { private var originAction: Selector? + /// Whether this proxy registered itself as an *additional* target rather than taking over the + /// control's single `target` / `action` pair. + /// + /// AppKit has stored several target-action pairs per control since macOS 11, but the events that + /// stand for "the control's action fired" — `valueChanged` and `primaryActionTriggered` — are + /// only delivered from macOS 27 on. Below that, only tracking events are sent, which is not the + /// same thing (a keyboard-driven button never tracks), so the proxy still has to take the pair + /// over. + private let registersAsAdditionalTarget: Bool + weak var owner: (any TargetActionProtocol)? required init(owner: any TargetActionProtocol) { self.owner = owner + if #available(macOS 27, *) { + registersAsAdditionalTarget = owner is NSControl + } else { + registersAsAdditionalTarget = false + } super.init() - self.originTarget = owner.target - self.originAction = owner.action - owner.target = self - owner.action = #selector(invokeAction(_:)) + + if #available(macOS 27, *), registersAsAdditionalTarget, let control = owner as? NSControl { + // NB: A text field's per-keystroke changes arrive through the notification below on every + // OS version, so 'valueChanged' is deliberately left out for text fields — registering + // both would deliver each edit twice. + // + // The event set is spelled as a literal on purpose: the option set is named + // 'NSControlEvents' when it comes from the shim and 'NSControl.Events' when it comes + // from the macOS 27 SDK, and inference makes both spellings compile. + if control is NSTextField { + control.addTarget(self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered]) + } else { + control.addTarget( + self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered, .valueChanged] + ) + } + } else { + self.originTarget = owner.target + self.originAction = owner.action + owner.target = self + owner.action = #selector(invokeAction(_:)) + } + if let textField = owner as? NSTextField { - NotificationCenter.default.addObserver(self, selector: #selector(controlTextDidChange(_:)), name: NSControl.textDidChangeNotification, object: textField) + NotificationCenter.default.addObserver( + self, + selector: #selector(controlTextDidChange(_:)), + name: NSControl.textDidChangeNotification, + object: textField + ) } } @@ -47,7 +87,9 @@ class TargetActionProxy: NSObject { } @objc func invokeAction(_ sender: Any?) { - if let originTarget, let originAction { + // NB: When registered as an additional target the original pair is still installed on the + // control, so AppKit delivers to it directly and forwarding here would double up. + if !registersAsAdditionalTarget, let originTarget, let originAction { NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } bindingActions.forEach { $0.invoke(sender) } diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h index 9dc496b6da..afe2026ce5 100644 --- a/Sources/AppKitNavigationShim/include/shim.h +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -19,6 +19,69 @@ NS_ASSUME_NONNULL_BEGIN @property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); @end +// MARK: - Multiple target-action pairs + +// NB: AppKit has stored several target-action pairs per control since macOS 11, but only published +// the API in the macOS 27 SDK. Redeclaring it here lets the binding layer register additional +// actions without taking over a control's single 'target' / 'action' pair, while still building +// against an older SDK. The whole block compiles away once the SDK in use declares it, so +// nothing has to be deleted by hand — but the redeclaration should be dropped altogether once +// the macOS 27 SDK is the minimum supported one. +// +// Note that the events themselves are not all as old as the API: on macOS 26 a button click +// only delivers NSControlEventTrackingBegan and NSControlEventTrackingEndedInside, and +// NSControlEventValueChanged / NSControlEventPrimaryActionTriggered are never sent. Anything +// relying on those has to stay behind an availability check. +// +// The SDK spells the type 'NS_SWIFT_NAME(NSControl.Events)'. That must NOT be repeated here: +// nesting a type inside a class that belongs to a *different* module makes the Swift importer +// drop the whole declaration, taking the two methods with it, and Swift then sees neither +// 'NSControlEvents' nor 'NSControl.Events'. Without the attribute Swift imports the type under +// its Objective-C name and the methods as 'addTarget(_:action:for:)'. +#if !defined(MAC_OS_VERSION_27_0) || __MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_27_0 + +typedef NS_OPTIONS(NSUInteger, NSControlEvents) { + NSControlEventTrackingBegan = 1 << 0, + NSControlEventTrackingRepeated API_AVAILABLE(macos(27.0)) = 1 << 1, + NSControlEventTrackingInside = 1 << 2, + NSControlEventTrackingOutside = 1 << 3, + NSControlEventTrackingEntered = 1 << 4, + NSControlEventTrackingExited = 1 << 5, + NSControlEventTrackingEndedInside = 1 << 6, + NSControlEventTrackingEndedOutside = 1 << 7, + NSControlEventTrackingCancelled = 1 << 8, + + NSControlEventValueChanged API_AVAILABLE(macos(27.0)) = 1 << 12, + NSControlEventPrimaryActionTriggered API_AVAILABLE(macos(27.0)) = 1 << 13, + NSControlEventMenuActionTriggered API_AVAILABLE(macos(27.0)) = 1 << 14, + + NSControlEventAllTrackingEvents = 0x00000FFF, + NSControlEventApplicationReserved API_AVAILABLE(macos(27.0)) = 0x0F000000, + NSControlEventSystemReserved = 0xF0000000, + NSControlEventAllEvents = 0xFFFFFFFF +} API_AVAILABLE(macos(11.0)); + +@interface NSControl (AppKitNavigationControlEvents) + +/// Associates a target object and action method with one or more control events. +/// +/// Unlike the 'target' and 'action' properties, this may be called several times to register +/// several pairs. The control does not retain the target. +- (void)addTarget:(nullable id)target + action:(SEL)action + forControlEvents:(NSControlEvents)controlEvents API_AVAILABLE(macos(11.0)); + +/// Stops the delivery of the specified events to the given target object. +/// +/// Pass 'nil' as the action to remove all actions for the target. +- (void)removeTarget:(nullable id)target + action:(nullable SEL)action + forControlEvents:(NSControlEvents)controlEvents API_AVAILABLE(macos(11.0)); + +@end + +#endif /* macOS 27 SDK redeclaration */ + NS_ASSUME_NONNULL_END #endif #endif /* if __has_include() */ diff --git a/Tests/AppKitNavigationTests/TargetActionTests.swift b/Tests/AppKitNavigationTests/TargetActionTests.swift new file mode 100644 index 0000000000..ed91e337d8 --- /dev/null +++ b/Tests/AppKitNavigationTests/TargetActionTests.swift @@ -0,0 +1,108 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKitNavigation + import XCTest + + final class TargetActionTests: XCTestCase { + override func setUp() { + super.setUp() + // NB: 'performClick' routes through 'NSApplication.sendAction(_:to:from:)', which silently + // does nothing when no application object exists yet. XCTest runs 'setUp' on the main + // thread, so assuming main-actor isolation here is sound. + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + private final class ActionRecipient: NSObject { + nonisolated(unsafe) var callCount = 0 + + @objc func recordAction(_ sender: Any?) { + callCount += 1 + } + } + + /// Whichever mechanism the proxy picks, a target-action pair installed *before* the first + /// closure action has to keep firing, and exactly once. + @MainActor + func testExistingTargetActionKeepsFiringAlongsideClosureActions() { + let recipient = ActionRecipient() + let button = NSButton() + button.target = recipient + button.action = #selector(ActionRecipient.recordAction(_:)) + + var closureCallCount = 0 + button.addAction { _ in closureCallCount += 1 } + + button.performClick(nil) + + XCTAssertEqual(recipient.callCount, 1) + XCTAssertEqual(closureCallCount, 1) + } + + @MainActor + func testClosureActionFiresWithoutAnyTargetAction() { + let button = NSButton() + + var closureCallCount = 0 + button.addAction { _ in closureCallCount += 1 } + + button.performClick(nil) + button.performClick(nil) + + XCTAssertEqual(closureCallCount, 2) + } + + @MainActor + func testRemoveActionStopsTheClosure() { + let button = NSButton() + + var closureCallCount = 0 + let id = button.addAction { _ in closureCallCount += 1 } + button.removeAction(for: id) + + button.performClick(nil) + + XCTAssertEqual(closureCallCount, 0) + } + + /// From macOS 27 on, AppKit delivers `primaryActionTriggered` / `valueChanged` to additional + /// targets, so the proxy no longer has to seize the control's own pair. Below that it does, + /// because only tracking events are sent and those do not stand for "the action fired". + @MainActor + func testProxyOnlySeizesTargetActionBelowMacOS27() { + let recipient = ActionRecipient() + let button = NSButton() + button.target = recipient + button.action = #selector(ActionRecipient.recordAction(_:)) + + button.addAction { _ in } + + if #available(macOS 27, *) { + XCTAssertIdentical(button.target as AnyObject?, recipient) + XCTAssertEqual(button.action, #selector(ActionRecipient.recordAction(_:))) + } else { + XCTAssertNotIdentical(button.target as AnyObject?, recipient) + } + } + + /// A text field reports every keystroke through the notification on every OS version, which is + /// why `valueChanged` is deliberately not registered for text fields. + @MainActor + func testTextFieldWritesBackOnEveryEdit() { + @UIBinding var text = "" + let textField = NSTextField(text: $text) + + textField.stringValue = "h" + NotificationCenter.default.post( + name: NSControl.textDidChangeNotification, object: textField + ) + XCTAssertEqual(text, "h") + + textField.stringValue = "hi" + NotificationCenter.default.post( + name: NSControl.textDidChangeNotification, object: textField + ) + XCTAssertEqual(text, "hi") + } + } +#endif From 3d7e519d51494a6694731e12e688c3be3369439f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:19:11 +0800 Subject: [PATCH 043/141] fix(appkit): run closure actions once per click on macOS 27 On macOS 27 the action proxy registers as an additional target instead of taking over the control's target / action pair, and it listened for both `primaryActionTriggered` and `valueChanged`. That path had never run on a macOS 27 machine; on 27.2 every closure action and binding write-back ran twice per click, three times for a stepper, and the existing `TargetActionTests` failed there. Measured on macOS 27.2, per control and per trigger: - `primaryActionTriggered` arrives exactly once for every `sendAction(_:to:)`, for every control type tried (push button, checkbox, radio, switch, stepper, segmented control, slider, text field, date picker, color well, path control). - `valueChanged` arrives on top of it when the control is clicked, twice for a stepper, and never for `sendAction(_:to:)`. So `primaryActionTriggered` alone is the event that means "the control sent its action", which is what target-action delivered before. Register only that one. Adds `ControlActionDeliveryTests`, which clicks and programmatically sends the action of seven control types; six of them failed before the change (closure counts of 2 and 3 instead of 1). --- .../Bindings/TargetActionProxy.swift | 30 +++---- .../ControlActionDeliveryTests.swift | 81 +++++++++++++++++++ .../TargetActionTests.swift | 10 +-- 3 files changed, 101 insertions(+), 20 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index aedc7b2a09..2d956790b2 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -31,11 +31,10 @@ class TargetActionProxy: NSObject { /// Whether this proxy registered itself as an *additional* target rather than taking over the /// control's single `target` / `action` pair. /// - /// AppKit has stored several target-action pairs per control since macOS 11, but the events that - /// stand for "the control's action fired" — `valueChanged` and `primaryActionTriggered` — are - /// only delivered from macOS 27 on. Below that, only tracking events are sent, which is not the - /// same thing (a keyboard-driven button never tracks), so the proxy still has to take the pair - /// over. + /// AppKit has stored several target-action pairs per control since macOS 11, but the event that + /// stands for "the control's action fired" — `primaryActionTriggered` — is only delivered from + /// macOS 27 on. Below that, only tracking events are sent, which is not the same thing (a + /// keyboard-driven button never tracks), so the proxy still has to take the pair over. private let registersAsAdditionalTarget: Bool weak var owner: (any TargetActionProtocol)? @@ -50,20 +49,21 @@ class TargetActionProxy: NSObject { super.init() if #available(macOS 27, *), registersAsAdditionalTarget, let control = owner as? NSControl { - // NB: A text field's per-keystroke changes arrive through the notification below on every - // OS version, so 'valueChanged' is deliberately left out for text fields — registering - // both would deliver each edit twice. + // NB: Only 'primaryActionTriggered' stands for "the control sent its action". Measured on + // macOS 27.2, every 'sendAction(_:to:)' delivers it exactly once, for every control type + // — buttons, switches, steppers, segmented controls, sliders, text fields, date pickers, + // color wells and path controls alike — which is what target-action delivered before. + // 'valueChanged' is no substitute and must not be added alongside it: a click delivers + // it on top of 'primaryActionTriggered' (registering both ran every closure twice), a + // stepper click delivers it twice, and 'sendAction(_:to:)' does not deliver it at all. + // + // A text field's per-keystroke changes arrive through the notification below on every + // OS version, so text fields need nothing more. // // The event set is spelled as a literal on purpose: the option set is named // 'NSControlEvents' when it comes from the shim and 'NSControl.Events' when it comes // from the macOS 27 SDK, and inference makes both spellings compile. - if control is NSTextField { - control.addTarget(self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered]) - } else { - control.addTarget( - self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered, .valueChanged] - ) - } + control.addTarget(self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered]) } else { self.originTarget = owner.target self.originAction = owner.action diff --git a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift new file mode 100644 index 0000000000..730b86a001 --- /dev/null +++ b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift @@ -0,0 +1,81 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + @MainActor + @Suite struct ControlActionDeliveryTests { + enum ControlKind: String, CaseIterable, Sendable, CustomTestStringConvertible { + case pushButton + case checkbox + case radioButton + case switchControl + case stepper + case segmentedControl + case slider + + var testDescription: String { rawValue } + + func makeControl() -> NSControl { + switch self { + case .pushButton: + NSButton(title: "Push", target: nil, action: nil) + case .checkbox: + NSButton(checkboxWithTitle: "Check", target: nil, action: nil) + case .radioButton: + NSButton(radioButtonWithTitle: "Radio", target: nil, action: nil) + case .switchControl: + NSSwitch() + case .stepper: + NSStepper() + case .segmentedControl: + NSSegmentedControl(labels: ["A", "B"], trackingMode: .selectOne, target: nil, action: nil) + case .slider: + NSSlider(value: 0.5, minValue: 0, maxValue: 1, target: nil, action: nil) + } + } + } + + init() { + // NB: 'performClick' routes through 'NSApplication.sendAction(_:to:from:)', which silently + // does nothing when no application object exists yet. + _ = NSApplication.shared + } + + /// On macOS 27 a click delivers `primaryActionTriggered` *and* `valueChanged` (a stepper even + /// delivers `valueChanged` twice), so listening for both ran every closure several times. + @Test("one click runs a closure action exactly once", arguments: ControlKind.allCases) + func oneClickRunsClosureActionOnce(_ controlKind: ControlKind) { + let control = controlKind.makeControl() + var closureCallCount = 0 + control.addAction { _ in closureCallCount += 1 } + + control.performClick(nil) + + #expect(closureCallCount == 1) + } + + /// Code that sends a control's action itself must reach closure actions too, as it did when + /// the library owned the control's target-action pair. + @Test( + "sending the action programmatically runs a closure action exactly once", + arguments: ControlKind.allCases + ) + func sendingTheActionRunsClosureActionOnce(_ controlKind: ControlKind) { + let actionRecipient = ActionRecipient() + let control = controlKind.makeControl() + control.target = actionRecipient + control.action = #selector(ActionRecipient.receiveAction(_:)) + var closureCallCount = 0 + control.addAction { _ in closureCallCount += 1 } + + control.sendAction(control.action, to: control.target) + + #expect(closureCallCount == 1) + } + + private final class ActionRecipient: NSObject { + @objc func receiveAction(_ sender: Any?) {} + } + } +#endif diff --git a/Tests/AppKitNavigationTests/TargetActionTests.swift b/Tests/AppKitNavigationTests/TargetActionTests.swift index ed91e337d8..e54418b612 100644 --- a/Tests/AppKitNavigationTests/TargetActionTests.swift +++ b/Tests/AppKitNavigationTests/TargetActionTests.swift @@ -65,9 +65,9 @@ XCTAssertEqual(closureCallCount, 0) } - /// From macOS 27 on, AppKit delivers `primaryActionTriggered` / `valueChanged` to additional - /// targets, so the proxy no longer has to seize the control's own pair. Below that it does, - /// because only tracking events are sent and those do not stand for "the action fired". + /// From macOS 27 on, AppKit delivers `primaryActionTriggered` to additional targets, so the + /// proxy no longer has to seize the control's own pair. Below that it does, because only + /// tracking events are sent and those do not stand for "the action fired". @MainActor func testProxyOnlySeizesTargetActionBelowMacOS27() { let recipient = ActionRecipient() @@ -85,8 +85,8 @@ } } - /// A text field reports every keystroke through the notification on every OS version, which is - /// why `valueChanged` is deliberately not registered for text fields. + /// A text field reports every keystroke through the notification on every OS version; the + /// control events only cover the action it sends on Return. @MainActor func testTextFieldWritesBackOnEveryEdit() { @UIBinding var text = "" From a142871a2f74aee2ddad6e681bc79606170ae94c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:26:01 +0800 Subject: [PATCH 044/141] fix(appkit): reset the binding when the user dismisses a presented view controller A view controller presented through `present(isPresented:style:)` or `sheet(isSheeted:)` never wrote `false` / `nil` back when it was dismissed from its own UI (a Cancel button wired to `dismissController:`, a transient popover closing). The binding stayed set, so setting it again did nothing and the content could not be presented a second time. Three separate defects, each confirmed by a test that failed before: - The dismissal hook was never connected. The shim calls `_AppKitNavigation_onDismiss` from `viewDidDisappear`, but nothing ever assigned it (the Swift bridge to it was unused), and the shim flagged the *presenter* as being dismissed rather than the controller passed to `dismissViewController:`, and only after the original implementation had run. Flag the dismissed controller, before handing over, and only when it is actually presented; connect the hook for every presentation that goes through `destination`. The flag accessors are prefixed now, so they cannot collide with methods AppKit adds to `NSViewController`. - `sheet(isSheeted:)` with view controller content dismissed itself the moment it appeared. The generic sheet path resets the binding once `beginSheet(for:)` returns, which for windows means "the sheet ended", but `presentAsSheet` returns as soon as the sheet is up. Suspend until the dismissal is reported instead. - When the binding was set again in the same main-queue turn as the dismissal wrote `false` back, `observe` re-ran only once, saw a non-nil value with the same identity, and took the dismissed content for a live one. Mark a navigation as ended as soon as its content reports the end, and finish it before starting the next one. Adds `ViewControllerPresentationTests`, which drive real sheets in an offscreen window by spinning the main run loop. --- .../Navigation/NavigationObserver.swift | 27 ++- .../Navigation/Presentation.swift | 55 ++++-- .../Navigation/SheetContent.swift | 21 ++- Sources/AppKitNavigationShim/shim.m | 59 +++++-- .../ViewControllerPresentationTests.swift | 158 ++++++++++++++++++ 5 files changed, 278 insertions(+), 42 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift index ce952a080a..eff9e4c2cc 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift @@ -32,14 +32,26 @@ class NavigationObserver: NSObject guard let self else { return } if let unwrappedItem = UIBinding(item) { if let navigated = navigatedByID[key] { - guard let navigationID = navigated.id, - navigationID != id(unwrappedItem.wrappedValue) - else { - return + if navigated.hasEnded { + // NB: The content was closed from its own UI, and the binding was set again before + // this re-ran, so the 'nil' in between was never observed. Finish the old + // navigation before starting the new one instead of mistaking it for live. + if let content = navigated.content { + end(content, transaction) + } + navigatedByID[key] = nil + } else { + guard let navigationID = navigated.id, + navigationID != id(unwrappedItem.wrappedValue) + else { + return + } } } let content = content(unwrappedItem) - let onEndNavigation = { [navigationID = id(unwrappedItem.wrappedValue)] in + let navigated = Navigated(content, id: id(unwrappedItem.wrappedValue)) + let onEndNavigation = { [weak navigated, navigationID = id(unwrappedItem.wrappedValue)] in + navigated?.hasEnded = true if let wrappedValue = item.wrappedValue, navigationID == id(wrappedValue) { item.wrappedValue = nil @@ -47,7 +59,7 @@ class NavigationObserver: NSObject } content.onEndNavigation = onEndNavigation - self.navigatedByID[key] = Navigated(content, id: id(unwrappedItem.wrappedValue)) + self.navigatedByID[key] = navigated let work = { withUITransaction(transaction) { begin(content, transaction) @@ -72,6 +84,9 @@ class NavigationObserver: NSObject class Navigated { weak var content: Content? let id: AnyHashable? + /// Whether the content has already ended on its own, closed from its own UI rather than through + /// the binding. + var hasEnded = false func clearup() {} deinit { MainActor._assumeIsolated { diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index eb2abef201..2369e09685 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -80,7 +80,11 @@ extension NSViewController { } } dismiss: { [weak self] child, transaction in guard let self else { return } - self.dismiss(child) + // NB: When the user closed the child, AppKit has already dismissed it by the time the + // binding is reset and this runs. + if self.presentedViewControllers?.contains(child) == true { + self.dismiss(child) + } onDismiss?() } } @@ -113,13 +117,12 @@ extension NSViewController { _ transaction: UITransaction ) -> Void ) -> ObserveToken { - let presentationObserver: PresentationObserver = presentationObserver() - return presentationObserver.observe( + observePresentation( item: item, id: { _ in nil }, content: content, - begin: present, - end: dismiss + present: present, + dismiss: dismiss ) } @@ -137,8 +140,35 @@ extension NSViewController { _ transaction: UITransaction ) -> Void ) -> ObserveToken { - let presentationObserver: PresentationObserver = presentationObserver() - return presentationObserver.observe(item: item, id: { $0[keyPath: id] }, content: content, begin: present, end: dismiss) + observePresentation( + item: item, + id: { $0[keyPath: id] }, + content: content, + present: present, + dismiss: dismiss + ) + } + + private func observePresentation( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping (_ child: NSViewController, _ transaction: UITransaction) -> Void, + dismiss: @escaping (_ child: NSViewController, _ transaction: UITransaction) -> Void + ) -> ObserveToken { + presentationObserver().observe( + item: item, + id: id, + content: content, + begin: { child, transaction in + // NB: The user closes a presented controller without going through the binding — a + // Cancel button wired to 'dismissController:', a transient popover closing — so the + // shim reports the dismissal, and this resets the binding from there. + child._AppKitNavigation_onDismiss = child.onEndNavigation + present(child, transaction) + }, + end: dismiss + ) } private static var presentationObserverKey = malloc(1)! @@ -154,17 +184,6 @@ extension NSViewController { } } -extension NavigationContent where Self: NSViewController { - var _onEndNavigation: (() -> Void)? { - set { - _AppKitNavigation_onDismiss = newValue - } - get { - _AppKitNavigation_onDismiss - } - } -} - extension Navigated where Content: NSViewController { func clearup() { content?.dismiss(nil) diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index 299a4145df..e58e29d72e 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -1,6 +1,8 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit +import AppKitNavigationShim +import SwiftNavigation @MainActor protocol SheetContent: NavigationContent { @@ -54,12 +56,25 @@ extension NSSavePanel { extension NSViewController: SheetContent { var currentWindow: NSWindow? { view.window } - + var attachedContent: (any SheetContent)? { currentWindow?.attachedSheet?.contentViewController } - + func beginSheet(for content: any SheetContent) async { guard let viewController = content as? NSViewController else { return } - presentAsSheet(viewController) + // NB: Unlike a window's 'beginSheet', 'presentAsSheet' returns as soon as the sheet is up, and + // the caller resets the binding the moment this returns. Suspend until the sheet is + // dismissed instead, which the shim reports from the dismissed controller's + // 'viewDidDisappear'. + await withCheckedContinuation { continuation in + MainActor._assumeIsolated { + let onDismiss = viewController._AppKitNavigation_onDismiss + viewController._AppKitNavigation_onDismiss = { + onDismiss?() + continuation.resume() + } + presentAsSheet(viewController) + } + } } func endSheet(for content: any SheetContent) { diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index 5f422637ab..adb0c61c38 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -41,9 +41,33 @@ + (void)load { @end static void *hasViewAppearedKey = &hasViewAppearedKey; +static void *isBeingDismissedKey = &isBeingDismissedKey; static void *onDismissKey = &onDismissKey; static void *onViewAppearKey = &onViewAppearKey; +@interface NSViewController (AppKitNavigationDismissal) + +// NB: Set from 'dismissViewController:' on the controller being dismissed and consumed by its +// next 'viewDidDisappear'. Prefixed like everything else this file adds to AppKit's classes, so +// it cannot collide with a method AppKit adds later. +@property (setter=set_AppKitNavigation_isBeingDismissed:) BOOL _AppKitNavigation_isBeingDismissed; + +@end + +@implementation NSViewController (AppKitNavigationDismissal) + +- (BOOL)_AppKitNavigation_isBeingDismissed { + return [objc_getAssociatedObject(self, isBeingDismissedKey) boolValue]; +} + +- (void)set_AppKitNavigation_isBeingDismissed:(BOOL)isBeingDismissed { + objc_setAssociatedObject( + self, isBeingDismissedKey, @(isBeingDismissed), OBJC_ASSOCIATION_COPY_NONATOMIC + ); +} + +@end + @implementation NSViewController (AppKitNavigation) - (void)AppKitNavigation_viewDidAppear { @@ -62,27 +86,32 @@ - (void)AppKitNavigation_viewDidAppear { self._AppKitNavigation_onViewAppear = @[]; } -- (void)setBeingDismissed:(BOOL)beingDismissed { - objc_setAssociatedObject(self, @selector(isBeingDismissed), @(beingDismissed), OBJC_ASSOCIATION_COPY); -} - -- (BOOL)isBeingDismissed { - return [objc_getAssociatedObject(self, @selector(isBeingDismissed)) boolValue]; -} - - (void)AppKitNavigation_viewDidDisappear { [self AppKitNavigation_viewDidDisappear]; - if ((self.isBeingDismissed) && self._AppKitNavigation_onDismiss != NULL) { - self._AppKitNavigation_onDismiss(); - self._AppKitNavigation_onDismiss = nil; - [self setBeingDismissed:NO]; + if (!self._AppKitNavigation_isBeingDismissed) { + return; + } + self._AppKitNavigation_isBeingDismissed = NO; + + void (^onDismiss)(void) = self._AppKitNavigation_onDismiss; + self._AppKitNavigation_onDismiss = nil; + if (onDismiss != NULL) { + onDismiss(); } } -- (void)AppKitNavigation_dismissViewController:(NSViewController *)sender { - [self AppKitNavigation_dismissViewController:sender]; - [self setBeingDismissed:YES]; +- (void)AppKitNavigation_dismissViewController:(NSViewController *)viewController { + // NB: The argument is the controller being dismissed; the receiver is its presenter (or the + // controller itself, when it dismisses itself). The flag belongs on the argument, and it + // has to be set before handing over, because a dismissal without animation reaches + // 'viewDidDisappear' before the original implementation returns. Only a controller that is + // actually presented is marked, so a stray call cannot leave a flag behind for some later, + // unrelated disappearance to act on. + if (viewController.presentingViewController != nil) { + viewController._AppKitNavigation_isBeingDismissed = YES; + } + [self AppKitNavigation_dismissViewController:viewController]; } - (BOOL)_AppKitNavigation_hasViewAppeared { diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift new file mode 100644 index 0000000000..b9845d0927 --- /dev/null +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -0,0 +1,158 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// Presentations whose content is a view controller, through `present(isPresented:style:)` and + /// `sheet(isSheeted:)`. + /// + /// These run as synchronous XCTest methods on purpose: they wait by spinning the main run loop, + /// which is what drives sheet animations, window ordering and the main-queue re-runs of + /// `observe`. + final class ViewControllerPresentationTests: XCTestCase { + override func setUp() { + super.setUp() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + @MainActor + func testUserDismissingAPresentedSheetWritesFalseBack() { + let host = makeHost() + @UIBinding var isPresented = false + let sheetViewController = makeContentViewController() + host.viewController.present(isPresented: $isPresented, style: .sheet) { + sheetViewController + } + + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + + // What a Cancel button wired to 'dismissController:' does. + sheetViewController.dismiss(nil) + + XCTAssertTrue(waitUntil { !isPresented }, "Dismissing the sheet did not write 'false' back") + } + + @MainActor + func testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt() { + let host = makeHost() + @UIBinding var isPresented = false + host.viewController.present(isPresented: $isPresented, style: .sheet) { + self.makeContentViewController() + } + + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + host.window.attachedSheet?.contentViewController?.dismiss(nil) + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet never went away") + + // NB: No waiting here on purpose. The dismissal writes 'false' back synchronously, but + // 'observe' only re-runs on a later turn of the main queue, so setting 'true' again + // straight away is exactly the case where the 'false' in between is never observed. + isPresented = true + + XCTAssertTrue( + waitUntil { host.window.attachedSheet != nil }, + "Setting the binding to 'true' again did not present the sheet again" + ) + } + + @MainActor + func testSettingTheBindingToFalseDismissesAPresentedSheet() { + let host = makeHost() + @UIBinding var isPresented = false + host.viewController.present(isPresented: $isPresented, style: .sheet) { + self.makeContentViewController() + } + + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + + isPresented = false + + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not dismissed") + } + + @MainActor + func testViewControllerSheetStaysPresentedUntilItIsDismissed() { + let host = makeHost() + @UIBinding var isSheeted = false + host.viewController.sheet(isSheeted: $isSheeted) { + self.makeContentViewController() + } + + isSheeted = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + spinRunLoop(for: 0.5) + + XCTAssertTrue(isSheeted, "The sheet dismissed itself right after it appeared") + } + + @MainActor + func testUserDismissingAViewControllerSheetWritesFalseBack() { + let host = makeHost() + @UIBinding var isSheeted = false + let sheetViewController = makeContentViewController() + host.viewController.sheet(isSheeted: $isSheeted) { sheetViewController } + + isSheeted = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + spinRunLoop(for: 0.5) + + sheetViewController.dismiss(nil) + + XCTAssertTrue(waitUntil { !isSheeted }, "Dismissing the sheet did not write 'false' back") + } + + // MARK: - Support + + @MainActor + private struct Host { + let window: NSWindow + let viewController: NSViewController + } + + @MainActor + private func makeHost() -> Host { + let viewController = makeContentViewController(width: 480, height: 320) + let window = NSWindow(contentViewController: viewController) + window.isReleasedWhenClosed = false + window.orderFront(nil) + addTeardownBlock { @MainActor in + if let attachedSheet = window.attachedSheet { + window.endSheet(attachedSheet) + } + window.close() + } + return Host(window: window, viewController: viewController) + } + + @MainActor + private func makeContentViewController( + width: CGFloat = 200, height: CGFloat = 120 + ) -> NSViewController { + let viewController = NSViewController() + viewController.view = NSView(frame: NSRect(x: 0, y: 0, width: width, height: height)) + return viewController + } + + @MainActor + private func waitUntil(timeout: TimeInterval = 3, _ condition: () -> Bool) -> Bool { + let deadline = Date(timeIntervalSinceNow: timeout) + while !condition(), Date() < deadline { + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) + } + return condition() + } + + @MainActor + private func spinRunLoop(for duration: TimeInterval) { + let deadline = Date(timeIntervalSinceNow: duration) + while Date() < deadline { + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) + } + } + } +#endif From d41f0c75427b22f0ea9fc1c77a5da75049767865 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:30:04 +0800 Subject: [PATCH 045/141] fix(appkit): let the binding end modal presentations, and reset it when they close Three defects in `modal(isModaled:)` / `modalSession(isModaled:)`, each confirmed by a test that failed before: - Setting the binding to `nil` / `false` could not end a `modal` presentation. The modal loop was started from a main-queue block, and the main queue is serial: nothing else enqueued on it ran until the loop ended. That includes the `observe` re-run that calls `stopModal()`, and every main-actor task. Measured: a binding reset scheduled half a second in never ran; the loop only ended when the test's five-second safety timer aborted it. Start the loop from a run-loop block instead, in the default mode, so it also cannot begin inside a modal loop that was just asked to stop. - The window stayed on screen after a `modal` loop ended: ending a modal loop does not order its window out. Order it out. - Closing a `modalSession` window from its own UI ended the session but never reset the binding. Reset it when the window closes. Closing a session's window now always goes through the close notification, which ends the session in one place; programmatic dismissal used to end it there *and* beforehand. That double end had no observable effect in tests, so it is a simplification rather than a fix. Adds `ModalPresentationTests`. --- .../Internal/ModalWindowsObserver.swift | 14 +- .../AppKitNavigation/Navigation/Modal.swift | 58 ++++---- .../ModalPresentationTests.swift | 129 ++++++++++++++++++ 3 files changed, 176 insertions(+), 25 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ModalPresentationTests.swift diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift index 55de75fb8f..5c0c3aef45 100644 --- a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift +++ b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift @@ -11,7 +11,18 @@ class ModalWindowsObserver: NSObject { var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:] - func observeWindow(_ window: NSWindow, modalSession: NSApplication.ModalSession? = nil) { + /// Ends the window's modal session, or stops its modal loop, when the window closes. + /// + /// - Parameters: + /// - window: The window shown modally. + /// - modalSession: The session the window was shown in, if it was shown through + /// `beginModalSession(for:)` rather than a modal loop. + /// - onClose: Runs once the session has ended, after the window started closing. + func observeWindow( + _ window: NSWindow, + modalSession: NSApplication.ModalSession? = nil, + onClose: (() -> Void)? = nil + ) { if let modalSession { modalSessionByWindow[window] = modalSession } @@ -26,6 +37,7 @@ class ModalWindowsObserver: NSObject { modalSessionByWindow.removeValue(forKey: window) windowsCancellable[window]?.cancel() windowsCancellable.removeValue(forKey: window) + onClose?() } } } diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 46ed6d42f5..666b637010 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -276,17 +276,23 @@ extension NSObject { if NSApplication.shared.modalWindow != nil { NSApplication.shared.stopModal() onDismiss?() - DispatchQueue.main.async { - ModalWindowsObserver.shared.observeWindow(modalContent.window) - modalContent.appKitNavigationRunModal() - modalContent.onEndNavigation?() - modalContent.onEndNavigation = nil - } - - } else { - DispatchQueue.main.async { + } + // NB: The modal loop must not be started from a main-queue block. The main queue is serial, + // so nothing else enqueued on it would run until the loop ended — not the 'observe' + // re-run that stops the loop when the binding is set to 'nil', nor any main-actor task. + // A run-loop block is not a main-queue block. Running it in the default mode only also + // keeps it from starting inside a modal loop that was just asked to stop but has not + // returned yet. + nonisolated(unsafe) let modalContent = modalContent + RunLoop.main.perform(inModes: [.default]) { + MainActor._assumeIsolated { ModalWindowsObserver.shared.observeWindow(modalContent.window) modalContent.appKitNavigationRunModal() + // NB: Ending a modal loop does not take its window off screen. Alerts and panels order + // themselves out; a plain window stays up unless it is ordered out here. + if modalContent.window.isVisible { + modalContent.window.orderOut(nil) + } modalContent.onEndNavigation?() modalContent.onEndNavigation = nil } @@ -349,27 +355,31 @@ extension NSObject { _modal(item: item, id: id) { $item in content($item) } beginModal: { modalContent, _ in - if let modaledWindow = NSApplication.shared.modalWindow, let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] { - NSApplication.shared.endModalSession(modalSession) - modaledWindow.window.close() + // NB: Closing a session's window is what ends the session: 'ModalWindowsObserver' ends it + // when the window closes, whether the window was closed from its own UI or from here. + if let modaledWindow = NSApplication.shared.modalWindow, + ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] != nil + { + modaledWindow.close() onDismiss?() - DispatchQueue.main.async { - let modalSession = modalContent.appKitNavigationBeginModalSession() - ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) - } - - } else { - DispatchQueue.main.async { - let modalSession = modalContent.appKitNavigationBeginModalSession() - ModalWindowsObserver.shared.observeWindow(modalContent.window, modalSession: modalSession) + } + DispatchQueue.main.async { + let modalSession = modalContent.appKitNavigationBeginModalSession() + ModalWindowsObserver.shared.observeWindow( + modalContent.window, + modalSession: modalSession + ) { + // NB: Resets the binding when the window was closed from its own UI. When the binding + // is what closed it, this finds the binding already reset and does nothing. + modalContent.onEndNavigation?() + modalContent.onEndNavigation = nil } } } endModal: { modalContent, _ in - if let modalSession = ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] { - NSApplication.shared.endModalSession(modalSession) + if ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] != nil { modalContent.window.close() - onDismiss?() } + onDismiss?() } } diff --git a/Tests/AppKitNavigationTests/ModalPresentationTests.swift b/Tests/AppKitNavigationTests/ModalPresentationTests.swift new file mode 100644 index 0000000000..f76506b79a --- /dev/null +++ b/Tests/AppKitNavigationTests/ModalPresentationTests.swift @@ -0,0 +1,129 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// Windows presented through `modal(isModaled:)` and `modalSession(isModaled:)`. + /// + /// Synchronous XCTest methods on purpose: they wait by spinning the main run loop, which also + /// services the modal loop that `modal` runs from a main-queue block. + final class ModalPresentationTests: XCTestCase { + override func setUp() { + super.setUp() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + // MARK: - Modal session + + @MainActor + func testUserClosingAModalSessionWindowWritesFalseBack() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isModaled = false + host.modalSession(isModaled: $isModaled) { window } + + isModaled = true + XCTAssertTrue(waitUntil { window.isVisible }, "The window never appeared") + + // What the window's close button does once 'windowShouldClose' agrees. + window.close() + + XCTAssertTrue(waitUntil { !isModaled }, "Closing the window did not write 'false' back") + } + + @MainActor + func testSettingTheBindingToFalseEndsTheModalSession() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isModaled = false + host.modalSession(isModaled: $isModaled) { window } + + isModaled = true + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow === window }, "The modal session never began" + ) + + isModaled = false + + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow == nil && !window.isVisible }, + "The modal session did not end, or its window stayed on screen" + ) + } + + // MARK: - Modal loop + + @MainActor + func testSettingTheBindingToFalseTakesTheModalWindowOffScreen() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isModaled = false + host.modal(isModaled: $isModaled) { window } + abortModalLoop(after: 5) + + // NB: 'modal' runs the modal loop from a main-queue block, so the loop is running by the + // time this fires, and it fires from inside it. + let start = Date() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { + isModaled = false + } + isModaled = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + """ + The modal loop only ended when the safety timer aborted it: setting the binding to 'false' \ + could not stop it + """ + ) + XCTAssertTrue( + waitUntil { !window.isVisible }, "The window stayed on screen after the modal loop ended" + ) + } + + // MARK: - Support + + @MainActor + private func makeWindow() -> NSWindow { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 160), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + addTeardownBlock { @MainActor in + window.close() + } + return window + } + + /// Guards against a modal loop that never stops, which would otherwise hang the test run. + @MainActor + private func abortModalLoop(after timeout: TimeInterval) { + let timer = Timer(timeInterval: timeout, repeats: false) { _ in + MainActor.assumeIsolated { + if NSApplication.shared.modalWindow != nil { + NSApplication.shared.abortModal() + } + } + } + RunLoop.main.add(timer, forMode: .common) + addTeardownBlock { @MainActor in + timer.invalidate() + } + } + + @MainActor + private func waitUntil(timeout: TimeInterval = 3, _ condition: () -> Bool) -> Bool { + let deadline = Date(timeIntervalSinceNow: timeout) + while !condition(), Date() < deadline { + RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) + } + return condition() + } + } +#endif From 416c369b34a690bd9d24b2643eb959e3f8e90501 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:31:54 +0800 Subject: [PATCH 046/141] fix(appkit): stop writing to a binding once it is unbound or replaced MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bind(_:to:set:)` registers a write-back closure with the action proxy as a *binding* action, but its token removed the ID from the proxy's list of *closure* actions, where it never was. Unbinding, or binding the same key path again, therefore left the old closure in place: the control kept writing every edit into the old binding, and kept its model alive. A reused table cell bound to the next row's model overwrote the previous row's data on every keystroke. `NSFontManager.swift` carries a copy of the same code and the same defect; both now remove the binding action. The save and open panel bindings had a defect of the same family. Binding again replaced the stored token, whose release cancelled it, and cancelling cleared the URL hook — by then the hook the *new* binding had just installed. Cancel the previous binding first. Adds `ControlBindingLifetimeTests`; all four of its tests failed before. --- .../Bindings/NSFontManager.swift | 2 +- .../Bindings/NSSaveOpenPanel.swift | 6 ++ .../Bindings/TargetActionProtocol.swift | 2 +- .../ControlBindingLifetimeTests.swift | 68 +++++++++++++++++++ 4 files changed, 76 insertions(+), 2 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 9100f81d4d..f96601a7fc 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -150,7 +150,7 @@ extension NSFontManager { } let observationToken = ObserveToken { [weak self] in MainActor._assumeIsolated { - self?.actionProxy?.removeAction(for: actionID) + self?.actionProxy?.removeBindingAction(for: actionID) } token.cancel() observation.invalidate() diff --git a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift index aca52dab7c..2e753ee60f 100755 --- a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift @@ -11,6 +11,10 @@ extension NSSavePanel { @discardableResult public func bind(url binding: UIBinding) -> ObserveToken { + // NB: The previous binding's token has to be cancelled before the new hook is installed. + // Left to be released when its entry is replaced below, it would clear the hook it no + // longer owns. + unbindURL() appKitNavigation_onFinalURL = { url in binding.wrappedValue = url } @@ -39,6 +43,8 @@ extension NSOpenPanel { @discardableResult public func bind(urls binding: UIBinding<[URL]>) -> ObserveToken { + // NB: See 'NSSavePanel.bind(url:)'. + unbindURLs() appKitNavigation_onFinalURLs = { urls in binding.wrappedValue = urls } diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index acc34394fd..80787025dc 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -92,7 +92,7 @@ extension TargetActionProtocol { } let observationToken = ObserveToken { [weak self] in MainActor._assumeIsolated { - self?.actionProxy?.removeAction(for: actionID) + self?.actionProxy?.removeBindingAction(for: actionID) } token.cancel() observation.invalidate() diff --git a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift new file mode 100644 index 0000000000..2727e77719 --- /dev/null +++ b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift @@ -0,0 +1,68 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + @MainActor + @Suite struct ControlBindingLifetimeTests { + /// What a reused table cell does: the same text field is bound to the next row's model. + @Test("rebinding a text field stops writing edits to the previous binding") + func rebindingStopsWritingToThePreviousBinding() { + @UIBinding var firstRowName = "first" + @UIBinding var secondRowName = "second" + let textField = NSTextField(text: $firstRowName) + + textField.bind(text: $secondRowName) + edit(textField, to: "edited") + + #expect(firstRowName == "first") + } + + @Test("unbinding a text field stops writing edits to the binding") + func unbindingStopsWritingToTheBinding() { + @UIBinding var name = "original" + let textField = NSTextField(text: $name) + + textField.unbind(\.stringValue) + edit(textField, to: "edited") + + #expect(name == "original") + } + + /// The panel reports the URL the user confirmed through its private 'setFinalURL:' setter, + /// which is what the binding hooks. + @Test("rebinding a save panel keeps reporting the confirmed URL") + func rebindingASavePanelKeepsReportingTheConfirmedURL() { + @UIBinding var firstURL: URL? = nil + @UIBinding var secondURL: URL? = nil + let savePanel = NSSavePanel() + savePanel.bind(url: $firstURL) + savePanel.bind(url: $secondURL) + + let confirmedURL = URL(filePath: "/tmp/confirmed.txt") + savePanel.perform(NSSelectorFromString("setFinalURL:"), with: confirmedURL) + + #expect(secondURL == confirmedURL) + } + + @Test("rebinding an open panel keeps reporting the confirmed URLs") + func rebindingAnOpenPanelKeepsReportingTheConfirmedURLs() { + @UIBinding var firstURLs: [URL] = [] + @UIBinding var secondURLs: [URL] = [] + let openPanel = NSOpenPanel() + openPanel.bind(urls: $firstURLs) + openPanel.bind(urls: $secondURLs) + + let confirmedURLs = [URL(filePath: "/tmp/first.txt"), URL(filePath: "/tmp/second.txt")] + openPanel.perform(NSSelectorFromString("setFinalURLs:"), with: confirmedURLs) + + #expect(secondURLs == confirmedURLs) + } + + /// Types into the field the way the field editor reports it. + private func edit(_ textField: NSTextField, to text: String) { + textField.stringValue = text + NotificationCenter.default.post(name: NSControl.textDidChangeNotification, object: textField) + } + } +#endif From 520738f6fefa8e1db8c19504f265ac21624b0e30 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:33:20 +0800 Subject: [PATCH 047/141] fix(appkit): keep forwarding responder-chain actions after taking over target-action MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the action proxy takes over a target-action pair — on every menu item and toolbar item, and on controls below macOS 27 — it forwards the original action, but only when the original *target* was non-nil. A nil target means "send the action up the responder chain", which is how menu items normally work (Copy, Paste, every item wired to the first responder), so after the first `addAction` or binding such an item silently stopped doing what it did before. The font manager's proxy had the same condition, and the shared font manager's target is nil by design: binding a font cut every text view in the app off from the font panel's `changeFont:`. `NSApplication.sendAction(_:to:from:)` already routes a nil target up the responder chain, so forward the action whenever there is one. Adds `ResponderChainForwardingTests`; both tests failed before. --- .../Bindings/NSFontManager.swift | 5 +- .../Bindings/TargetActionProxy.swift | 6 +- .../ResponderChainForwardingTests.swift | 71 +++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index f96601a7fc..3f01da1559 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -211,7 +211,10 @@ private class FontManagerProxy: NSObject { } @objc func invokeAction(_ sender: Any?) { - if let originTarget, let originAction { + // NB: The font manager's target is 'nil' unless an app changes it: 'changeFont:' travels up + // the responder chain to whichever text view is first responder. Forward a 'nil' target + // as 'nil', which 'sendAction(_:to:from:)' routes there. + if let originAction { NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } bindingActions.forEach { $0.invoke(sender) } diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 2d956790b2..dde31f6dcf 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -89,7 +89,11 @@ class TargetActionProxy: NSObject { @objc func invokeAction(_ sender: Any?) { // NB: When registered as an additional target the original pair is still installed on the // control, so AppKit delivers to it directly and forwarding here would double up. - if !registersAsAdditionalTarget, let originTarget, let originAction { + // + // A 'nil' original target is forwarded as 'nil': it means "up the responder chain", which + // is where 'sendAction(_:to:from:)' routes it. Menu items, and controls wired to the + // first responder, rely on that. + if !registersAsAdditionalTarget, let originAction { NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } bindingActions.forEach { $0.invoke(sender) } diff --git a/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift new file mode 100644 index 0000000000..b7da748cc6 --- /dev/null +++ b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift @@ -0,0 +1,71 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// An action whose target is `nil` travels up the responder chain. When the library takes over a + /// target-action pair, that action still has to reach the chain. + /// + /// The chain ends at the application's delegate, so a recipient installed there receives the + /// action without any window on screen. + @MainActor + @Suite struct ResponderChainForwardingTests { + private final class ApplicationDelegateRecipient: NSObject, NSApplicationDelegate { + var recordedActionCount = 0 + var changeFontCount = 0 + + @objc func recordAction(_ sender: Any?) { + recordedActionCount += 1 + } + + @objc func changeFont(_ sender: NSFontManager?) { + changeFontCount += 1 + } + } + + private func withApplicationDelegate( + _ recipient: ApplicationDelegateRecipient, _ body: () -> Void + ) { + let application = NSApplication.shared + let previousDelegate = application.delegate + application.delegate = recipient + defer { application.delegate = previousDelegate } + body() + } + + @Test("a menu item's responder-chain action keeps firing alongside closure actions") + func menuItemResponderChainActionKeepsFiring() { + let recipient = ApplicationDelegateRecipient() + withApplicationDelegate(recipient) { + let menuItem = NSMenuItem( + title: "Record", + action: #selector(ApplicationDelegateRecipient.recordAction(_:)), + keyEquivalent: "" + ) + let menu = NSMenu() + menu.addItem(menuItem) + menuItem.addAction { _ in } + + menu.performActionForItem(at: 0) + } + + #expect(recipient.recordedActionCount == 1) + } + + /// The font panel sends `changeFont:` up the responder chain through the shared font manager, + /// whose target is `nil`; binding a font must not cut text views off from it. + @Test("binding a font keeps the font manager's responder-chain action firing") + func bindingAFontKeepsTheResponderChainActionFiring() { + let recipient = ApplicationDelegateRecipient() + withApplicationDelegate(recipient) { + @UIBinding var font = NSFont.systemFont(ofSize: 12) + let fontManager = NSFontManager.shared + fontManager.bind(font: $font) + + fontManager.sendAction() + } + + #expect(recipient.changeFontCount == 1) + } + } +#endif From 2d59cfdab96959cbc09de76cc972f773718885ba Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:35:44 +0800 Subject: [PATCH 048/141] fix(appkit): stop replacing AppKit's text-field selection handling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bind(selection:)` learned about selection changes by giving `NSTextField` a `textViewDidChangeSelection(_:)` method in an extension (with retroactive `NSTextDelegate` / `NSTextViewDelegate` conformances). AppKit implements that delegate method itself — on `NSControl`, and on `NSTextField` from macOS 27.2 on — so the extension replaced AppKit's implementation for every text field in any app linking the module, bound or not. On 27.2 the method resolved into the client binary instead of AppKit. Listen to `NSTextView.didChangeSelectionNotification` instead, which the field editor posts alongside the delegate call, and keep to the field editor whose delegate is this text field. The public conformances and the public `textViewDidChangeSelection(_:)` method are gone with it. Two more defects in the same binding, each with a test that failed before: - The selection was converted with `Character` offsets, while the field editor counts UTF-16 code units, so any emoji or combining mark before the selection shifted it. Convert through the UTF-16 view both ways. - Binding the selection again left the old binding's token to be released when its entry was replaced, and its cancellation removed the selection observer the new binding had just installed. Cancel the old binding first. The selection is now only written back when it changed, since applying the binding moves the selection and reports it again. Adds `TextFieldSelectionTests`; all four of its tests failed before. --- .../Bindings/NSTextField.swift | 113 ++++++++---------- .../TextFieldSelectionTests.swift | 89 ++++++++++++++ 2 files changed, 139 insertions(+), 63 deletions(-) create mode 100644 Tests/AppKitNavigationTests/TextFieldSelectionTests.swift diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 0e3ed6730b..84a3d790a9 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -3,9 +3,7 @@ public import AppKit import Combine public import SwiftNavigation -@MainActor -extension NSTextField: @retroactive NSTextDelegate {} -extension NSTextField: @retroactive NSTextViewDelegate { +extension NSTextField { /// Creates a new text field with the specified frame and registers the binding against its /// text. /// @@ -57,29 +55,51 @@ extension NSTextField: @retroactive NSTextViewDelegate { /// - Returns: A cancel token. @discardableResult public func bind(selection: UIBinding) -> ObserveToken { - let editingChangedAction = NotificationCenter.default.publisher(for: NSTextField.textDidChangeNotification, object: self) + // NB: Cancel the previous binding first, so its observers are gone before the new ones + // report anything. + observationTokens[\NSTextField.selectedRange]?.cancel() + + let reportSelection: @MainActor (NSTextField) -> Void = { textField in + // NB: Applying the binding below moves the selection, which is reported here again; + // writing back only what actually changed keeps that from going round forever. + let textSelection = textField.textSelection + if selection.wrappedValue != textSelection { + selection.wrappedValue = textSelection + } + } + let editingChangedAction = NotificationCenter.default + .publisher(for: NSTextField.textDidChangeNotification, object: self) .sink { [weak self] _ in guard let self else { return } - selection.wrappedValue = self.textSelection + MainActor._assumeIsolated { reportSelection(self) } } - let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in selection.wrappedValue = nil } + // NB: The field editor reports selection changes to its delegate, which is the text field + // being edited. AppKit implements that delegate method on text fields itself, so it + // must not be replaced; the notification the field editor posts alongside carries the + // same news. One field editor serves every field in a window, hence the delegate check. + let selectionChangedAction = NotificationCenter.default + .publisher(for: NSTextView.didChangeSelectionNotification) + .sink { [weak self] notification in + guard + let self, + let fieldEditor = notification.object as? NSTextView, + fieldEditor.delegate === self + else { return } + MainActor._assumeIsolated { reportSelection(self) } + } + let editingDidEndAction = NotificationCenter.default + .publisher(for: NSTextField.textDidEndEditingNotification, object: self) + .sink { _ in selection.wrappedValue = nil } let token = observe { [weak self] in guard let self else { return } textSelection = selection.wrappedValue } - textSelectionObserver = TextSelectionObserver { control in - MainActor._assumeIsolated { - selection.wrappedValue = control.textSelection - } - } - let observationToken = ObserveToken { [weak self] in - MainActor._assumeIsolated { - editingChangedAction.cancel() - editingDidEndAction.cancel() - token.cancel() - self?.textSelectionObserver = nil - } + let observationToken = ObserveToken { + editingChangedAction.cancel() + selectionChangedAction.cancel() + editingDidEndAction.cancel() + token.cancel() } observationTokens[\NSTextField.selectedRange] = observationToken return observationToken @@ -95,48 +115,16 @@ extension NSTextField: @retroactive NSTextViewDelegate { } } - fileprivate class TextSelectionObserver: NSObject { - let observer: (NSTextField) -> Void - - init(observer: @escaping (NSTextField) -> Void) { - self.observer = observer - } - } - - private static let textSelectionObserverKey = malloc(1)! - private var textSelectionObserver: TextSelectionObserver? { - set { - objc_setAssociatedObject(self, Self.textSelectionObserverKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - objc_getAssociatedObject(self, Self.textSelectionObserverKey) as? TextSelectionObserver - } - } - - public func textViewDidChangeSelection(_ notification: Notification) { - textSelectionObserver?.observer(self) - } - + // NB: The field editor counts in UTF-16 code units, which differ from 'Character' offsets as + // soon as the text holds an emoji or a combining mark, so every conversion goes through + // the string's UTF-16 view. fileprivate var textSelection: AppKitTextSelection? { get { - guard - let textRange = selectedRange - else { - return nil - } + guard let textRange = selectedRange else { return nil } let text = stringValue - let lowerBound = - text.index( - text.startIndex, - offsetBy: textRange.location, - limitedBy: text.endIndex - ) ?? text.endIndex - let upperBound = - text.index( - text.startIndex, - offsetBy: NSMaxRange(textRange), - limitedBy: text.endIndex - ) ?? text.endIndex + let utf16Count = text.utf16.count + let lowerBound = String.Index(utf16Offset: min(textRange.location, utf16Count), in: text) + let upperBound = String.Index(utf16Offset: min(NSMaxRange(textRange), utf16Count), in: text) return AppKitTextSelection(range: lowerBound ..< upperBound) } set { @@ -145,13 +133,12 @@ extension NSTextField: @retroactive NSTextViewDelegate { return } let text = stringValue - let from = text.distance( - from: text.startIndex, to: min(selection.lowerBound, text.endIndex) - ) - let to = text.distance( - from: text.startIndex, to: min(selection.upperBound, text.endIndex) + let lowerBound = min(selection.lowerBound, text.endIndex) + let upperBound = min(selection.upperBound, text.endIndex) + selectedRange = NSRange( + location: text.utf16.distance(from: text.startIndex, to: lowerBound), + length: text.utf16.distance(from: lowerBound, to: upperBound) ) - selectedRange = .init(location: from, length: to - from) } } diff --git a/Tests/AppKitNavigationTests/TextFieldSelectionTests.swift b/Tests/AppKitNavigationTests/TextFieldSelectionTests.swift new file mode 100644 index 0000000000..ab8607bba9 --- /dev/null +++ b/Tests/AppKitNavigationTests/TextFieldSelectionTests.swift @@ -0,0 +1,89 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + @MainActor + @Suite struct TextFieldSelectionTests { + /// AppKit implements `textViewDidChangeSelection:` itself — on `NSControl` everywhere, and on + /// `NSTextField` from macOS 27.2 on. A method of that name added to `NSTextField` by an + /// extension replaces it for every text field in the process, bound or not. + @Test("AppKit's own selection handling stays in place on every text field") + func appKitsSelectionHandlingStaysInPlace() throws { + let method = try #require( + class_getInstanceMethod(NSTextField.self, NSSelectorFromString("textViewDidChangeSelection:")) + ) + var imageInfo = Dl_info() + let implementation = unsafeBitCast(method_getImplementation(method), to: UnsafeRawPointer.self) + try #require(dladdr(implementation, &imageInfo) != 0) + let imagePath = String(cString: try #require(imageInfo.dli_fname)) + + #expect(imagePath.hasSuffix("/AppKit"), "Implemented in \(imagePath)") + } + + @Test("moving the selection reports it at the right characters when the text has emoji") + func movingTheSelectionReportsTheRightCharacters() throws { + let editingSession = try EditingSession(text: "👍ab") + @UIBinding var selection: AppKitTextSelection? = nil + editingSession.textField.bind(selection: $selection) + + // "a": the thumbs-up sign takes two UTF-16 code units. + editingSession.fieldEditor.selectedRange = NSRange(location: 2, length: 1) + + let selectedRange = try #require(selection?.range) + #expect(editingSession.textField.stringValue[selectedRange] == "a") + } + + @Test("setting the binding selects the right characters when the text has emoji") + func settingTheBindingSelectsTheRightCharacters() async throws { + let editingSession = try EditingSession(text: "👍ab") + let text = editingSession.textField.stringValue + @UIBinding var selection: AppKitTextSelection? = nil + editingSession.textField.bind(selection: $selection) + + let rangeOfA = try #require(text.range(of: "a")) + selection = AppKitTextSelection(range: rangeOfA) + // NB: 'observe' applies the new value on a later turn of the main queue. + await Task.yield() + + #expect(editingSession.fieldEditor.selectedRange == NSRange(location: 2, length: 1)) + } + + @Test("rebinding the selection keeps reporting selection changes") + func rebindingKeepsReportingSelectionChanges() throws { + let editingSession = try EditingSession(text: "hello") + @UIBinding var firstSelection: AppKitTextSelection? = nil + @UIBinding var secondSelection: AppKitTextSelection? = nil + editingSession.textField.bind(selection: $firstSelection) + editingSession.textField.bind(selection: $secondSelection) + + editingSession.fieldEditor.selectedRange = NSRange(location: 1, length: 3) + + let selectedRange = try #require(secondSelection?.range) + #expect(editingSession.textField.stringValue[selectedRange] == "ell") + } + + /// A text field in a window, being edited, so that it has a field editor. + @MainActor + private struct EditingSession { + let window: NSWindow + let textField: NSTextField + let fieldEditor: NSText + + init(text: String) throws { + textField = NSTextField(string: text) + textField.frame = NSRect(x: 20, y: 20, width: 200, height: 24) + window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 64), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView?.addSubview(textField) + window.makeFirstResponder(textField) + fieldEditor = try #require(textField.currentEditor(), "The text field did not start editing") + } + } + } +#endif From 49716a9db15547b4e4d9899e58cf2a7ca4527876 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:38:17 +0800 Subject: [PATCH 049/141] fix(appkit): report a text field's focus as soon as it gains it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `bind(focus:equals:)` learned that the field gained focus from `textDidBeginEditingNotification`, which AppKit only posts with the first change to the text — `NSText.didBeginEditingNotification` is documented as "posted when an NSText object begins any operation that changes characters". Clicking into a field or tabbing to it left the binding at `nil` until the user typed. Report focus from the field editor's selection change instead, which arrives as soon as the field editor is set up for the field, and only while the field editor is first responder with this field as its delegate, since one field editor serves every field in a window. Losing focus keeps using the end-editing notification, which is posted whether or not anything was typed. Moving focus to the field now asks the window, through `makeFirstResponder(_:)`, rather than calling `becomeFirstResponder()`, which AppKit documents as not to be called directly. That part had no observable symptom in tests. Adds `TextFieldFocusTests`; the focus-gained test failed before, and the focus-lost test only passed because focus was never reported in the first place. --- .../Bindings/NSTextField.swift | 31 +++++- .../TextFieldFocusTests.swift | 94 +++++++++++++++++++ 2 files changed, 120 insertions(+), 5 deletions(-) create mode 100644 Tests/AppKitNavigationTests/TextFieldFocusTests.swift diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 84a3d790a9..4a8931242e 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -210,10 +210,29 @@ extension NSTextField { focus: UIBinding, equals value: Value ) -> ObserveToken { focusToken?.cancel() - let editingDidBeginAction = NotificationCenter.default.publisher(for: NSTextField.textDidBeginEditingNotification, object: self).sink { _ in - focus.wrappedValue = value - } + // NB: Gaining focus has no notification of its own. The begin-editing notification only + // arrives with the first change to the text, not when the field is clicked into or + // tabbed to. What does arrive at that moment is a selection change from the field + // editor, once it has been set up for this field: the field editor being first + // responder, with this field as its delegate, is what it means for the field to have + // focus. One field editor serves every field in a window, hence both checks. + let focusGainedAction = NotificationCenter.default + .publisher(for: NSTextView.didChangeSelectionNotification) + .sink { [weak self] notification in + MainActor._assumeIsolated { + guard + let self, + let fieldEditor = notification.object as? NSTextView, + fieldEditor.delegate === self, + fieldEditor.window?.firstResponder === fieldEditor, + focus.wrappedValue != value + else { return } + focus.wrappedValue = value + } + } + // NB: Unlike its begin counterpart, this is posted whenever focus leaves the field, edited + // or not. let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in guard focus.wrappedValue == value else { return } focus.wrappedValue = nil @@ -223,7 +242,9 @@ extension NSTextField { guard let self else { return } switch (focus.wrappedValue, currentEditor() != nil) { case (value, false): - becomeFirstResponder() + // NB: The window hands out first-responder status; 'becomeFirstResponder()' only + // asks whether the field accepts it and is not meant to be called directly. + window?.makeFirstResponder(self) case (nil, true): window?.makeFirstResponder(nil) default: @@ -231,7 +252,7 @@ extension NSTextField { } } let outerToken = ObserveToken { - editingDidBeginAction.cancel() + focusGainedAction.cancel() editingDidEndAction.cancel() innerToken.cancel() } diff --git a/Tests/AppKitNavigationTests/TextFieldFocusTests.swift b/Tests/AppKitNavigationTests/TextFieldFocusTests.swift new file mode 100644 index 0000000000..cea8e636aa --- /dev/null +++ b/Tests/AppKitNavigationTests/TextFieldFocusTests.swift @@ -0,0 +1,94 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + @MainActor + @Suite struct TextFieldFocusTests { + enum Field: Hashable { + case name + case email + } + + /// Clicking into a field, or tabbing to it, makes it first responder without changing any text. + @Test("focusing a field reports it before anything is typed") + func focusingAFieldReportsItBeforeTyping() { + let form = Form() + @UIBinding var focus: Field? = nil + form.nameField.bind(focus: $focus, equals: .name) + + form.window.makeFirstResponder(form.nameField) + + #expect(focus == .name) + } + + @Test("moving focus to another field writes nil back") + func movingFocusAwayWritesNilBack() throws { + let form = Form() + @UIBinding var focus: Field? = nil + form.nameField.bind(focus: $focus, equals: .name) + form.window.makeFirstResponder(form.nameField) + try #require(focus == .name, "The field never reported gaining focus") + + form.window.makeFirstResponder(form.emailField) + + #expect(focus == nil) + } + + @Test("setting the binding focuses the field") + func settingTheBindingFocusesTheField() async { + let form = Form() + @UIBinding var focus: Field? = nil + form.nameField.bind(focus: $focus, equals: .name) + + focus = .name + // NB: 'observe' applies the new value on a later turn of the main queue. + await Task.yield() + + #expect(form.focusedField === form.nameField) + } + + @Test("setting the binding to nil takes focus away from the field") + func settingTheBindingToNilRemovesFocus() async { + let form = Form() + @UIBinding var focus: Field? = nil + form.nameField.bind(focus: $focus, equals: .name) + form.window.makeFirstResponder(form.nameField) + focus = .name + await Task.yield() + + focus = nil + await Task.yield() + + #expect(form.focusedField == nil) + } + + /// Two text fields in a window. + @MainActor + private struct Form { + let window: NSWindow + let nameField = NSTextField(string: "") + let emailField = NSTextField(string: "") + + init() { + window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 96), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + nameField.frame = NSRect(x: 20, y: 56, width: 200, height: 24) + emailField.frame = NSRect(x: 20, y: 20, width: 200, height: 24) + window.contentView?.addSubview(nameField) + window.contentView?.addSubview(emailField) + } + + /// The text field being edited: the window's first responder is then the field editor, + /// whose delegate is that text field. + var focusedField: NSTextField? { + (window.firstResponder as? NSTextView)?.delegate as? NSTextField + } + } + } +#endif From 930b66c853f9999765294c314536aee6086dc56c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:42:24 +0800 Subject: [PATCH 050/141] fix(appkit): apply font panel changes to the bound font MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `NSFontManager.bind(font:)` read the new font as `convert(.systemFont(ofSize: 0))`. `convert(_:)` applies the font panel's latest change to the font it is given, so the binding received the change applied to the system font: binding Helvetica 20 and choosing Bold produced the 13-point bold system font, and every later action reset it to the plain system font. Convert the selected font instead, which the binding itself records through `setSelectedFont(_:isMultiple:)`. Measured while writing the test: the font manager only sends its action while some responder in the chain implements `changeFont(_:)`; without one, `sendAction()` returns false and `addFontTrait(_:)` does nothing. That is AppKit's behaviour, not something the binding can work around, so it is now documented on `bind(font:)`. Also removes two pieces of dead code from the file — a private delegate type that was never instantiated, and a text-change handler the font manager's proxy never registered — and replaces doc comments copied from the date picker binding. `NSFontManager()` does return the shared instance, so `init(font:)` stays; its documentation now says so. Adds `FontManagerBindingTests`, which failed before on the family name and point size. The tests bind a font held in a value, since `@UIBinding` deprecates wrapping a class instance directly. --- .../Bindings/NSFontManager.swift | 68 ++++++------------- .../FontManagerBindingTests.swift | 44 ++++++++++++ .../ResponderChainForwardingTests.swift | 10 ++- 3 files changed, 74 insertions(+), 48 deletions(-) create mode 100644 Tests/AppKitNavigationTests/FontManagerBindingTests.swift diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 3f01da1559..ff123a04f1 100755 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -4,56 +4,34 @@ public import AppKit public import IdentifiedCollections -@MainActor -extension NSFontManager: @unchecked @retroactive Sendable { - private static let appkitNavigationDelegateKey = malloc(1)! - - private var appkitNavigationDelegate: Delegate { - set { - objc_setAssociatedObject(self, Self.appkitNavigationDelegateKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - if let delegate = objc_getAssociatedObject(self, Self.appkitNavigationDelegateKey) as? Delegate { - return delegate - } else { - let delegate = Delegate() - target = delegate - self.appkitNavigationDelegate = delegate - return delegate - } - } - } - - private class Delegate: NSObject, NSFontChanging { - var target: AnyObject? - var action: Selector? - - func changeFont(_ sender: NSFontManager?) { - if let action { - NSApplication.shared.sendAction(action, to: target, from: sender) - } - } - } -} +extension NSFontManager: @unchecked @retroactive Sendable {} @MainActor extension NSFontManager { - /// Creates a new date picker with the specified frame and registers the binding against the - /// selected date. + /// Returns the shared font manager, with the binding registered against its selected font. /// - /// - Parameters: - /// - frame: The frame rectangle for the view, measured in points. - /// - date: The binding to read from for the selected date, and write to when the selected - /// date changes. + /// `NSFontManager()` returns the shared font manager, so this binds the same instance as + /// `NSFontManager.shared.bind(font:)`. + /// + /// - Parameter font: The binding to read from for the selected font, and write to when a + /// change from the font panel or the font menu is applied. public convenience init(font: UIBinding) { self.init() bind(font: font) } - /// Establishes a two-way connection between a binding and the date picker's selected date. + /// Establishes a two-way connection between a binding and the font manager's selected font. + /// + /// The binding's font becomes the selected font that the font panel shows. When the user changes + /// it from the font panel or the font menu, the change is applied to the binding's font, the way + /// a text view applies it to its own. + /// + /// > Important: The font manager only sends font changes while some responder in the chain + /// > implements `changeFont(_:)` — usually the text view being edited. While none does, changes + /// > from the font panel do not reach the binding either. /// - /// - Parameter date: The binding to read from for the selected date, and write to when the - /// selected date changes. + /// - Parameter font: The binding to read from for the selected font, and write to when a + /// change from the font panel or the font menu is applied. /// - Returns: A cancel token. @discardableResult public func bind(font: UIBinding) -> ObserveToken { @@ -62,7 +40,10 @@ extension NSFontManager { @objc private var _selectedFont: NSFont { set { setSelectedFont(newValue, isMultiple: false) } - get { convert(.systemFont(ofSize: 0)) } + // NB: 'convert(_:)' applies the font panel's latest change to the font it is given. That has + // to be the bound font, which the setter above recorded as the selected font; converting + // anything else keeps only the change and loses the bound font's family and size. + get { convert(selectedFont ?? .systemFont(ofSize: 0)) } } } @@ -205,11 +186,6 @@ private class FontManagerProxy: NSObject { owner.action = #selector(invokeAction(_:)) } - @objc func controlTextDidChange(_ obj: Notification) { - bindingActions.forEach { $0.invoke(obj.object) } - actions.forEach { $0.invoke(obj.object) } - } - @objc func invokeAction(_ sender: Any?) { // NB: The font manager's target is 'nil' unless an app changes it: 'changeFont:' travels up // the responder chain to whichever text view is first responder. Forward a 'nil' target diff --git a/Tests/AppKitNavigationTests/FontManagerBindingTests.swift b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift new file mode 100644 index 0000000000..6feb1796f6 --- /dev/null +++ b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift @@ -0,0 +1,44 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + @MainActor + @Suite struct FontManagerBindingTests { + /// Stands in for the text view the font panel normally edits. The font manager only sends its + /// action while some responder implements `changeFont:`, and the responder chain ends at the + /// application's delegate, so installing one there works without any window. + private final class ChangeFontResponder: NSObject, NSApplicationDelegate { + @objc func changeFont(_ sender: NSFontManager?) {} + } + + /// The font panel's trait buttons and menu items go through `addFontTrait(_:)`, which records + /// the change and sends the font manager's action; `convert(_:)` then applies it to a font. + @Test("a change from the font panel is applied to the bound font") + func fontPanelChangeIsAppliedToTheBoundFont() throws { + let responder = ChangeFontResponder() + let application = NSApplication.shared + let previousDelegate = application.delegate + application.delegate = responder + defer { application.delegate = previousDelegate } + + @UIBinding var textStyle = TextStyle(font: try #require(NSFont(name: "Helvetica", size: 20))) + let fontManager = NSFontManager.shared + fontManager.bind(font: $textStyle.font) + + let boldMenuItem = NSMenuItem() + boldMenuItem.tag = Int(NSFontTraitMask.boldFontMask.rawValue) + fontManager.addFontTrait(boldMenuItem) + + #expect(textStyle.font.familyName == "Helvetica") + #expect(textStyle.font.pointSize == 20) + #expect(fontManager.traits(of: textStyle.font).contains(.boldFontMask)) + } + + /// Holds the font in a value, the way a model would, rather than binding a class instance + /// directly. + private struct TextStyle { + var font: NSFont + } + } +#endif diff --git a/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift index b7da748cc6..9ae6e6119f 100644 --- a/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift +++ b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift @@ -58,14 +58,20 @@ func bindingAFontKeepsTheResponderChainActionFiring() { let recipient = ApplicationDelegateRecipient() withApplicationDelegate(recipient) { - @UIBinding var font = NSFont.systemFont(ofSize: 12) + @UIBinding var textStyle = TextStyle(font: NSFont.systemFont(ofSize: 12)) let fontManager = NSFontManager.shared - fontManager.bind(font: $font) + fontManager.bind(font: $textStyle.font) fontManager.sendAction() } #expect(recipient.changeFontCount == 1) } + + /// Holds the font in a value, the way a model would, rather than binding a class instance + /// directly. + private struct TextStyle { + var font: NSFont + } } #endif From 914908233894970b5f00527e0dba9b0f87e7199d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:46:16 +0800 Subject: [PATCH 051/141] fix(appkit): validate taken-over menu and toolbar items like their original action MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit AppKit enables a menu item or a toolbar item by asking its target. After the action proxy took over an item's target-action pair, the proxy was the one asked; it implemented neither validation method, so every such item stayed enabled whatever its original target said — and an item whose responder-chain action nothing could handle stayed enabled too. The proxy now answers as the original pair would have been answered: it finds the receiver of the original action (the original target, or the responder chain when that target is nil) and asks it, falling back to `validateUserInterfaceItem(_:)` and then to enabled, as AppKit does. With no receiver it disables the item, as AppKit would have. An item that only runs closure actions has no one else to ask and stays enabled. Adds `ItemValidationTests`, which ask the item's target through the validation protocols AppKit uses; all of them failed before. Going through `NSMenu.update()` was not deterministic in the test process — within one turn of the event loop AppKit reused earlier validation results for the same action, so outcomes depended on test order. --- .../Bindings/TargetActionProxy.swift | 37 +++++++++ .../ItemValidationTests.swift | 79 +++++++++++++++++++ 2 files changed, 116 insertions(+) create mode 100644 Tests/AppKitNavigationTests/ItemValidationTests.swift diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index dde31f6dcf..7a702ac17a 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -131,4 +131,41 @@ class TargetActionProxy: NSObject { } } +/// AppKit enables a menu item or a toolbar item by asking its target. Once the proxy has taken the +/// item's target-action pair over, it is the one asked, so it answers the way the original pair +/// would have been answered. +extension TargetActionProxy: NSMenuItemValidation, NSToolbarItemValidation { + func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { + validateOriginalAction(for: menuItem) { receiver in + receiver.validateMenuItem?(menuItem) + } + } + + func validateToolbarItem(_ item: NSToolbarItem) -> Bool { + validateOriginalAction(for: item) { receiver in + receiver.validateToolbarItem?(item) + } + } + + private func validateOriginalAction( + for item: any NSValidatedUserInterfaceItem, + asking askReceiver: (AnyObject) -> Bool? + ) -> Bool { + // NB: An item that only runs closure actions has no one else to ask. + guard let originAction else { return true } + // NB: With no receiver for the original action, AppKit would have disabled the item. + guard + let receiver = NSApplication.shared.target( + forAction: originAction, to: originTarget, from: item + ) as AnyObject? + else { return false } + // NB: Looked up dynamically rather than through a protocol cast, since a receiver may + // implement these methods without declaring the protocols, as AppKit long allowed. + if let answer = askReceiver(receiver) { + return answer + } + return receiver.validateUserInterfaceItem?(item) ?? true + } +} + #endif diff --git a/Tests/AppKitNavigationTests/ItemValidationTests.swift b/Tests/AppKitNavigationTests/ItemValidationTests.swift new file mode 100644 index 0000000000..fad9b45840 --- /dev/null +++ b/Tests/AppKitNavigationTests/ItemValidationTests.swift @@ -0,0 +1,79 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// Menu items and toolbar items are enabled by asking whoever receives their action. When the + /// library takes over the target-action pair, that answer must not change. + /// + /// These ask the item's target directly, through the validation protocols AppKit itself uses. + /// Going through `NSMenu.update()` instead is not deterministic in a test process: within one + /// turn of the event loop AppKit reuses earlier validation results for the same action, so + /// the outcome depended on which test ran first. + @MainActor + @Suite struct ItemValidationTests { + private final class Validator: NSObject, NSMenuItemValidation, NSToolbarItemValidation { + let isValid: Bool + + init(isValid: Bool) { + self.isValid = isValid + } + + @objc func performItemAction(_ sender: Any?) {} + + func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { isValid } + + func validateToolbarItem(_ item: NSToolbarItem) -> Bool { isValid } + } + + @Test("a menu item's target still answers as its original target would", arguments: [false, true]) + func menuItemFollowsItsOriginalTarget(isValid: Bool) throws { + let validator = Validator(isValid: isValid) + let menuItem = NSMenuItem( + title: "Item", action: #selector(Validator.performItemAction(_:)), keyEquivalent: "" + ) + menuItem.target = validator + menuItem.addAction { _ in } + + let validation = try #require(menuItem.target as? any NSMenuItemValidation) + + #expect(validation.validateMenuItem(menuItem) == isValid) + } + + /// A responder-chain action that nothing in the chain handles leaves the item disabled. + @Test("a menu item stays disabled when nothing handles its responder-chain action") + func menuItemWithUnhandledResponderChainActionStaysDisabled() throws { + let menuItem = NSMenuItem( + title: "Item", action: NSSelectorFromString("actionNothingHandles:"), keyEquivalent: "" + ) + menuItem.addAction { _ in } + + let validation = try #require(menuItem.target as? any NSMenuItemValidation) + + #expect(!validation.validateMenuItem(menuItem)) + } + + @Test("a menu item with only closure actions is enabled") + func menuItemWithOnlyClosureActionsIsEnabled() throws { + let menuItem = NSMenuItem(title: "Item", action: nil, keyEquivalent: "") + menuItem.addAction { _ in } + + let validation = try #require(menuItem.target as? any NSMenuItemValidation) + + #expect(validation.validateMenuItem(menuItem)) + } + + @Test("a toolbar item's target still answers as its original target would", arguments: [false, true]) + func toolbarItemFollowsItsOriginalTarget(isValid: Bool) throws { + let validator = Validator(isValid: isValid) + let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier("item")) + toolbarItem.target = validator + toolbarItem.action = #selector(Validator.performItemAction(_:)) + toolbarItem.addAction { _ in } + + let validation = try #require(toolbarItem.target as? any NSToolbarItemValidation) + + #expect(validation.validateToolbarItem(toolbarItem) == isValid) + } + } +#endif From c2175df07b2052e362f714fc16fe1eec150dfb14 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:48:50 +0800 Subject: [PATCH 052/141] docs: record review findings that were not fixed, and why Adds `Documentations/`, with an index and `Internal/ReviewDecisions.md`: the findings from the AppKitNavigation review that turned out to be false positives or had no observable effect, the confirmed ones deferred to the navigation refactor, a sibling defect left to upstream in UIKitNavigation, an AppKit limitation of the font binding, and the one dismissal path that could not be verified at runtime. The next review checks this list first. --- Documentations/Internal/ReviewDecisions.md | 59 ++++++++++++++++++++++ Documentations/README.md | 7 +++ Package.resolved | 11 +--- 3 files changed, 67 insertions(+), 10 deletions(-) create mode 100644 Documentations/Internal/ReviewDecisions.md create mode 100644 Documentations/README.md diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md new file mode 100644 index 0000000000..cea48da313 --- /dev/null +++ b/Documentations/Internal/ReviewDecisions.md @@ -0,0 +1,59 @@ +# 审查裁决清单 + +记录审查中判为误报、不值得修或暂缓处理的发现,以及没能在运行时验证的部分。每次审查之前先对照这份清单:已裁决、且理由仍然成立的条目直接跳过;新证据推翻了当初理由的,更新条目并重新裁决。 + +已修复的问题不在这里,它们的原因与验证写在各自的 commit message 和回归测试里。 + +## 误报或未复现 + +### `modalSession` 由 binding 关闭时结束了两次模态会话 + +- **裁决**:未复现出后果,不按 bug 处理。(2026-11-03) +- **理由**:binding 置空时,旧代码先调用 `endModalSession`、再关窗,关窗通知里又调用一次。可在 macOS 27.2 上测试,模态会话正常结束,`NSApp.modalWindow` 也归零,看不到任何异常。 +- **现状**:修复「用户关窗不回写」时,结束会话的位置已经统一到窗口关闭通知这一处,顺带消除了重复调用。 + +### 焦点绑定直接调用 `becomeFirstResponder()` + +- **裁决**:未复现症状,不按 bug 处理。(2026-11-03) +- **理由**:Apple 文档写明不要直接调用它,应改用 `NSWindow.makeFirstResponder(_:)`。但实测通过 binding 设置焦点一直能正常生效,`NSTextField` 自己的实现会把字段编辑器设为第一响应者。 +- **现状**:已按文档改用 `makeFirstResponder(_:)`,行为不变。 + +### `NSFontManager(font:)` 会建出一个和字体面板无关的新实例 + +- **裁决**:误报。(2026-11-03) +- **理由**:在 macOS 27.2 上实测,`NSFontManager()` 返回的就是 `NSFontManager.shared`。 +- **复查条件**:将来某个系统版本上它不再返回共享实例时。 + +## 暂缓处理 + +### `Navigated` 各约束扩展里的 `clearup()` 从不执行 + +- **裁决**:确认是死代码,暂不修。(2026-11-03) +- **理由**:`Navigated` 是泛型类,`deinit` 里调用的 `clearup()` 在编译期就静态绑定到类里那份空实现,`where Content: …` 扩展里的同名方法永远不会被调用。导航观察者被释放时,原本打算关掉仍在显示的内容,但目前没有构造出现实中看得见的后果。直接把它激活反而有风险:模态那份会无条件调用 `stopModal()`,可能停掉一个并非本库发起的模态循环。 +- **复查条件**:收敛导航相关重载的重构时,连同下一条一起处理。 + +### `present(...)` 替换已弹出的视图控制器时,不分来源都调用本 binding 的 `onDismiss` + +- **裁决**:读代码确认,影响面小,暂不修。(2026-11-03) +- **理由**:同一个 presenter 已经有一个弹出的视图控制器时,新的 `present` 会先把它关掉,并调用*本 binding* 的 `onDismiss`,不管它是不是本 binding 弹出来的。UIKit 那边用一个 presenter 标记来区分。只有在同一个 presenter 上挂了两个 binding 时才会触发。另外,被关掉的那个 binding 现在能正确收到回写。 +- **复查条件**:同上。 + +### 上游 `UIKitNavigation` 的 `UITextField` 选区绑定同样把 UTF-16 偏移当成字符数 + +- **裁决**:确认是同类问题,fork 内不修。(2026-11-03) +- **理由**:AppKit 那份已按 UTF-16 换算修好。UIKit 那份是上游拥有的代码,fork 保持与上游一致,在 fork 里改会让以后的合并持续冲突。 +- **复查条件**:决定是否给上游提 issue 或 PR 时。 + +## 系统限制 + +### 字体绑定只在响应链上有对象实现 `changeFont(_:)` 时生效 + +- **裁决**:AppKit 自身的行为,库里无法绕开。(2026-11-03) +- **理由**:实测发现,响应链上没有实现 `changeFont(_:)` 的对象时,`NSFontManager.sendAction()` 返回 `false`,`addFontTrait(_:)` 也什么都不做,字体面板的改动根本不会发出来。 +- **现状**:已写进 `NSFontManager.bind(font:)` 的文档注释。 + +## 未在运行时验证 + +### transient popover 被点外部关闭时的回写 + +- `present(style: .popover(...))` 在用户关闭时把 binding 写回 `nil`,依靠的是 AppKit 调用 `dismissViewController:`。用 `dismiss(nil)` 关闭的情形有测试覆盖;点击 popover 外部触发的 transient 关闭,在单元测试里没法模拟,所以 AppKit 在这条路径上是否也调用 `dismissViewController:`,还没有验证。 diff --git a/Documentations/README.md b/Documentations/README.md new file mode 100644 index 0000000000..65f5ab3e0b --- /dev/null +++ b/Documentations/README.md @@ -0,0 +1,7 @@ +# 文档索引 + +这个 fork 自己的文档。库的公开 API 文档在各 target 的 `Documentation.docc` 里,与上游共用。 + +## Internal + +- [ReviewDecisions.md](Internal/ReviewDecisions.md):审查中判为误报、不修或暂缓的发现及理由,以及没能在运行时验证的部分;每次审查前先对照。 diff --git a/Package.resolved b/Package.resolved index 0d2d3b35f9..50771dcbd0 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "b529d85a44e8b6d00b50a6e6af790949b66026862c64c367ff5b0eb658f4a4fa", + "originHash" : "74e727c830d417f6c86e1fbb1d47fac60b8f2940261641d2c894fe935b28a825", "pins" : [ { "identity" : "swift-case-paths", @@ -55,15 +55,6 @@ "version" : "1.1.1" } }, - { - "identity" : "swift-issue-reporting", - "kind" : "remoteSourceControl", - "location" : "https://github.com/pointfreeco/swift-issue-reporting", - "state" : { - "revision" : "71c7c9a761d1ca6ed4ccb6ced040fe1c1a39e8e7", - "version" : "2.1.0" - } - }, { "identity" : "swift-macro-testing", "kind" : "remoteSourceControl", From 12af389048df82a026d6ad171db23344a61debb9 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 22:52:54 +0800 Subject: [PATCH 053/141] test(appkit): keep the AppKit test target compiling with Swift 6.2 Built with Xcode 26.6 (Swift 6.2, macOS 26 SDK), the new test files failed to compile: under `InternalImportsByDefault`, Swift 6.2 rejects an Objective-C protocol conformance on an `NSObject` subclass as public unless the protocol's module is imported publicly, even when the class is private, and it rejected a `CustomTestStringConvertible` conformance the same way. Swift 6.4 accepts all of them. - The validation tests' receiver now implements the validation methods without declaring the protocols, which the library supports anyway and which the tests now cover. - The two files whose recipient has to be an application delegate import AppKit publicly. - The control-kind argument no longer conforms to `CustomTestStringConvertible`. The library itself already compiled with Swift 6.2. `swift test` as a whole still does not with Xcode 26.6: `SwiftNavigationTests` and `SwiftUINavigationTests` fail the same way, unchanged from main. --- Package.resolved | 11 +++++++- .../ControlActionDeliveryTests.swift | 4 +-- .../FontManagerBindingTests.swift | 18 +++++++------ .../ItemValidationTests.swift | 27 ++++++++++--------- .../ResponderChainForwardingTests.swift | 26 +++++++++--------- 5 files changed, 50 insertions(+), 36 deletions(-) diff --git a/Package.resolved b/Package.resolved index 50771dcbd0..0d2d3b35f9 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "74e727c830d417f6c86e1fbb1d47fac60b8f2940261641d2c894fe935b28a825", + "originHash" : "b529d85a44e8b6d00b50a6e6af790949b66026862c64c367ff5b0eb658f4a4fa", "pins" : [ { "identity" : "swift-case-paths", @@ -55,6 +55,15 @@ "version" : "1.1.1" } }, + { + "identity" : "swift-issue-reporting", + "kind" : "remoteSourceControl", + "location" : "https://github.com/pointfreeco/swift-issue-reporting", + "state" : { + "revision" : "71c7c9a761d1ca6ed4ccb6ced040fe1c1a39e8e7", + "version" : "2.1.0" + } + }, { "identity" : "swift-macro-testing", "kind" : "remoteSourceControl", diff --git a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift index 730b86a001..cdca77add3 100644 --- a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift +++ b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift @@ -5,7 +5,7 @@ @MainActor @Suite struct ControlActionDeliveryTests { - enum ControlKind: String, CaseIterable, Sendable, CustomTestStringConvertible { + enum ControlKind: String, CaseIterable, Sendable { case pushButton case checkbox case radioButton @@ -14,8 +14,6 @@ case segmentedControl case slider - var testDescription: String { rawValue } - func makeControl() -> NSControl { switch self { case .pushButton: diff --git a/Tests/AppKitNavigationTests/FontManagerBindingTests.swift b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift index 6feb1796f6..dbc2af272f 100644 --- a/Tests/AppKitNavigationTests/FontManagerBindingTests.swift +++ b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift @@ -1,17 +1,19 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - import AppKit + // NB: Imported publicly because Swift 6.2 rejects the 'NSApplicationDelegate' conformance below + // as public otherwise, even on a private class. Later compilers accept either import. + public import AppKit import AppKitNavigation import Testing + /// Stands in for the text view the font panel normally edits. The font manager only sends its + /// action while some responder implements `changeFont:`, and the responder chain ends at the + /// application's delegate, so installing one there works without any window. + private final class ChangeFontResponder: NSObject, NSApplicationDelegate { + @objc func changeFont(_ sender: NSFontManager?) {} + } + @MainActor @Suite struct FontManagerBindingTests { - /// Stands in for the text view the font panel normally edits. The font manager only sends its - /// action while some responder implements `changeFont:`, and the responder chain ends at the - /// application's delegate, so installing one there works without any window. - private final class ChangeFontResponder: NSObject, NSApplicationDelegate { - @objc func changeFont(_ sender: NSFontManager?) {} - } - /// The font panel's trait buttons and menu items go through `addFontTrait(_:)`, which records /// the change and sends the font manager's action; `convert(_:)` then applies it to a font. @Test("a change from the font panel is applied to the bound font") diff --git a/Tests/AppKitNavigationTests/ItemValidationTests.swift b/Tests/AppKitNavigationTests/ItemValidationTests.swift index fad9b45840..c8aef48f42 100644 --- a/Tests/AppKitNavigationTests/ItemValidationTests.swift +++ b/Tests/AppKitNavigationTests/ItemValidationTests.swift @@ -10,22 +10,25 @@ /// Going through `NSMenu.update()` instead is not deterministic in a test process: within one /// turn of the event loop AppKit reuses earlier validation results for the same action, so /// the outcome depended on which test ran first. - @MainActor - @Suite struct ItemValidationTests { - private final class Validator: NSObject, NSMenuItemValidation, NSToolbarItemValidation { - let isValid: Bool - - init(isValid: Bool) { - self.isValid = isValid - } + /// Implements the validation methods without declaring `NSMenuItemValidation` or + /// `NSToolbarItemValidation`, as AppKit has long allowed, so the tests also cover a receiver + /// that only implements them informally. + private final class Validator: NSObject { + let isValid: Bool + + init(isValid: Bool) { + self.isValid = isValid + } - @objc func performItemAction(_ sender: Any?) {} + @objc func performItemAction(_ sender: Any?) {} - func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { isValid } + @objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool { isValid } - func validateToolbarItem(_ item: NSToolbarItem) -> Bool { isValid } - } + @objc func validateToolbarItem(_ item: NSToolbarItem) -> Bool { isValid } + } + @MainActor + @Suite struct ItemValidationTests { @Test("a menu item's target still answers as its original target would", arguments: [false, true]) func menuItemFollowsItsOriginalTarget(isValid: Bool) throws { let validator = Validator(isValid: isValid) diff --git a/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift index 9ae6e6119f..45d9a0bd70 100644 --- a/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift +++ b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift @@ -1,5 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - import AppKit + // NB: Imported publicly because Swift 6.2 rejects the 'NSApplicationDelegate' conformance below + // as public otherwise, even on a private class. Later compilers accept either import. + public import AppKit import AppKitNavigation import Testing @@ -8,21 +10,21 @@ /// /// The chain ends at the application's delegate, so a recipient installed there receives the /// action without any window on screen. - @MainActor - @Suite struct ResponderChainForwardingTests { - private final class ApplicationDelegateRecipient: NSObject, NSApplicationDelegate { - var recordedActionCount = 0 - var changeFontCount = 0 + private final class ApplicationDelegateRecipient: NSObject, NSApplicationDelegate { + var recordedActionCount = 0 + var changeFontCount = 0 - @objc func recordAction(_ sender: Any?) { - recordedActionCount += 1 - } + @objc func recordAction(_ sender: Any?) { + recordedActionCount += 1 + } - @objc func changeFont(_ sender: NSFontManager?) { - changeFontCount += 1 - } + @objc func changeFont(_ sender: NSFontManager?) { + changeFontCount += 1 } + } + @MainActor + @Suite struct ResponderChainForwardingTests { private func withApplicationDelegate( _ recipient: ApplicationDelegateRecipient, _ body: () -> Void ) { From 6139da907cb64413bb8babf6476b5104e8da71d5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 23:01:48 +0800 Subject: [PATCH 054/141] docs: record the decision not to report the UIKit selection defect upstream for now --- Documentations/Internal/ReviewDecisions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index cea48da313..51301fd8ee 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -40,9 +40,9 @@ ### 上游 `UIKitNavigation` 的 `UITextField` 选区绑定同样把 UTF-16 偏移当成字符数 -- **裁决**:确认是同类问题,fork 内不修。(2026-11-03) +- **裁决**:确认是同类问题,fork 内不修,暂不向上游报告。(2026-11-03,暂不报告由用户决定) - **理由**:AppKit 那份已按 UTF-16 换算修好。UIKit 那份是上游拥有的代码,fork 保持与上游一致,在 fork 里改会让以后的合并持续冲突。 -- **复查条件**:决定是否给上游提 issue 或 PR 时。 +- **复查条件**:上游自己修了,或者 fork 的 UIKit 用户撞上这个问题时。 ## 系统限制 From f4ed1402aae5a452fe645f7300d82acaa4c92a26 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 3 Nov 2026 23:01:48 +0800 Subject: [PATCH 055/141] chore: ignore .worktrees/ --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index f2c6e1ebaf..8cd6b44bc6 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,4 @@ xcuserdata/ DerivedData/ .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata +.worktrees/ From da65875f7d248bcd44e6f17fa103c4b59d729d46 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 20:31:49 +0800 Subject: [PATCH 056/141] docs: propose an AppKitNavigation cleanup Clear the AppKitNavigation build warnings, fold the font manager's copy of the action proxy back into the shared one, drop the IdentifiedCollections dependency, prefix the Objective-C members added to AppKit classes, stop publishing AnyCancellable's retroactive Sendable conformance, and remove the UIKit pages left in the AppKitNavigation documentation catalog. Public usage does not change. --- Documentations/Evolutions/README.md | 9 ++++ .../draft-appkit-navigation-cleanup.md | 41 +++++++++++++++++++ Documentations/README.md | 5 +++ 3 files changed, 55 insertions(+) create mode 100644 Documentations/Evolutions/README.md create mode 100644 Documentations/Evolutions/draft-appkit-navigation-cleanup.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md new file mode 100644 index 0000000000..d49a5e3431 --- /dev/null +++ b/Documentations/Evolutions/README.md @@ -0,0 +1,9 @@ +# Evolutions + +- **项目类型**: library + +这个 fork 的改动提案。编号在实现合进 `main` 时才分配,进行中的提案叫 `draft-.md`。 + +| # | 标题 | 状态 | +|---|------|------| +| draft | [AppKitNavigation 清理:警告、重复代理和多余依赖](draft-appkit-navigation-cleanup.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md new file mode 100644 index 0000000000..950148778b --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -0,0 +1,41 @@ +# Draft - AppKitNavigation 清理:警告、重复代理和多余依赖 + +- **状态**: Accepted +- **创建日期**: 2026-11-04 +- **最后更新**: 2026-11-04 +- **实现分支**: `appkit-navigation-cleanup` + +## 摘要 + +不改用法,把 AppKitNavigation 收拾干净:清掉现有的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。 + +## 方案 + +先补测试,再动代码: + +1. **补测试作安全网**:每个类型化的 `bind`(开关、滑块、步进器、日期、颜色、路径、分段、颜色面板)各补一条双向测试。`NSSavePanel.bind(url:)` 与 `NSOpenPanel.bind(urls:)` 靠交换私有方法 `setFinalURL:` / `setFinalURLs:` 工作,系统去掉它们时现在只会静默失效;补一条测试,让那种情况立即变红。 +2. **清警告**: + - `NSControl`、`NSToolbarItem`、`NSColorPanel` 的 `@retroactive Sendable` 改成 `@unchecked @retroactive Sendable`,与 `NSMenuItem`、`NSFontManager` 一致。 + - 两处没用在公开声明里的 `public import Combine` 改成内部导入。 + - 上一批加的 `ControlActionDeliveryTests` 有 7 条并发警告:`makeControl()` 改为 `@MainActor`。 +3. **合并字体管理器的代理**:删掉 `FontManagerProxy` 和 `NSFontManager` 扩展里复制的 `bind(_:to:set:)`,改走 `TargetActionProxy` 和同一份绑定实现。`NSFontManager.action` 是非可选的 `Selector`,遵循不了 `TargetActionProtocol`,所以只共享内部实现,公开签名不变。 +4. **去掉 `IdentifiedCollections`**:动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,与上游一致;两条 `public import IdentifiedCollections` 的警告一并消失。 +5. **加库前缀**:`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。 +6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**:它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 +7. **文档**:删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。 + +没有询问就采用的假设: + +- 公开 API 除第 6 条外不变。第 6 条严格说去掉了一个公开遵循;本机依赖这个 fork 的 7 个项目,都没有在 import AppKitNavigation 的文件里用 `AnyCancellable`,所以按轻量档处理。 +- 这 7 个项目也都没有自己 import `IdentifiedCollections`,去掉依赖不影响它们。 +- 保留 `TargetActionProtocol` 的 `Sendable` 要求和各控件的 `Sendable` 遵循:去掉它们才是真正的破坏性改动。 +- 只动 fork 独有的文件,不碰与上游共用的 `SwiftNavigation` 和 UIKit 部分;四份清单的改动是向上游靠拢。 +- 验证:Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 +- 不在这一批:弹出相关三个文件(约 1,300 行)的重载收敛,连同 `Navigated.clearup()` 死代码(见 [ReviewDecisions.md](../Internal/ReviewDecisions.md)),属于大型重构,另起完整档提案;新功能各自另起提案。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-04 | Created as Draft | 修 bug 的那一批已落地,按审查清单的顺序接着处理优化项;这一批只收不改用法的清理 | +| 2026-11-04 | Accepted | 用户批准,开始实现 | diff --git a/Documentations/README.md b/Documentations/README.md index 65f5ab3e0b..8972e6fe70 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -2,6 +2,11 @@ 这个 fork 自己的文档。库的公开 API 文档在各 target 的 `Documentation.docc` 里,与上游共用。 +## Evolutions + +- [Evolutions/README.md](Evolutions/README.md):提案索引与状态。 +- [draft-appkit-navigation-cleanup.md](Evolutions/draft-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 + ## Internal - [ReviewDecisions.md](Internal/ReviewDecisions.md):审查中判为误报、不修或暂缓的发现及理由,以及没能在运行时验证的部分;每次审查前先对照。 From 98ec3002ca474f255c1b4fd21bb5d26ee6be3551 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 20:38:22 +0800 Subject: [PATCH 057/141] test(appkit): cover each typed control binding before the cleanup Every typed binding now has a test that it shows the bound value, follows later changes, and writes the user's changes back, so the cleanup that follows cannot quietly break one. The font manager gains a rebinding test, since the cleanup rewrites the code that drops the previous binding's write-back. The panel bindings hook the private setters 'setFinalURL:' and 'setFinalURLs:'. A new test fails as soon as AppKit drops them, and the existing panel tests check for them before messaging, so a missing setter fails those tests instead of crashing the whole run. The color panel is left out: 'NSColorPanel.bind(color:)' crashes on its first call, because it reads the panel's 'action' through KVC, which cannot return a selector. That predates this work and is recorded as a follow-up. --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-navigation-cleanup.md | 12 +- .../ControlBindingLifetimeTests.swift | 18 +- .../ControlBindingRoundTripTests.swift | 158 ++++++++++++++++++ .../FontManagerBindingTests.swift | 58 +++++-- 5 files changed, 227 insertions(+), 21 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index d49a5e3431..1521da64dd 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -6,4 +6,4 @@ | # | 标题 | 状态 | |---|------|------| -| draft | [AppKitNavigation 清理:警告、重复代理和多余依赖](draft-appkit-navigation-cleanup.md) | Accepted | +| draft | [AppKitNavigation 清理:警告、重复代理和多余依赖](draft-appkit-navigation-cleanup.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 950148778b..791667ebe2 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -1,6 +1,6 @@ # Draft - AppKitNavigation 清理:警告、重复代理和多余依赖 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-04 - **最后更新**: 2026-11-04 - **实现分支**: `appkit-navigation-cleanup` @@ -13,7 +13,7 @@ 先补测试,再动代码: -1. **补测试作安全网**:每个类型化的 `bind`(开关、滑块、步进器、日期、颜色、路径、分段、颜色面板)各补一条双向测试。`NSSavePanel.bind(url:)` 与 `NSOpenPanel.bind(urls:)` 靠交换私有方法 `setFinalURL:` / `setFinalURLs:` 工作,系统去掉它们时现在只会静默失效;补一条测试,让那种情况立即变红。 +1. **补测试作安全网**(已完成):每个类型化的 `bind`(开关、滑块、步进器、日期、颜色、路径、分段)各补一条双向测试,颜色面板除外(见决策日志);字体管理器补一条重新绑定的测试。`NSSavePanel.bind(url:)` 与 `NSOpenPanel.bind(urls:)` 靠交换私有方法 `setFinalURL:` / `setFinalURLs:` 工作,系统去掉它们时现在只会静默失效;补一条测试,让那种情况立即变红。 2. **清警告**: - `NSControl`、`NSToolbarItem`、`NSColorPanel` 的 `@retroactive Sendable` 改成 `@unchecked @retroactive Sendable`,与 `NSMenuItem`、`NSFontManager` 一致。 - 两处没用在公开声明里的 `public import Combine` 改成内部导入。 @@ -33,9 +33,17 @@ - 验证:Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 - 不在这一批:弹出相关三个文件(约 1,300 行)的重载收敛,连同 `Navigated.clearup()` 死代码(见 [ReviewDecisions.md](../Internal/ReviewDecisions.md)),属于大型重构,另起完整档提案;新功能各自另起提案。 +## 后续项 + +- `NSColorPanel.bind(color:)` 一调用就崩溃:它经 KVC 读面板的 `action`,而 KVC 返回不了 `SEL`,抛出 `NSUnknownKeyException`。原本就有,由第 1 步的测试发现,不在这一批修。 +- `NSPathControl` 的便捷构造器把 URL 绑定的参数标签写成了 `date:`,应为 `url:`;改它要动公开 API,不在这一批。 + ## 决策日志 | 日期 | 决定 | 理由 | |------|------|------| | 2026-11-04 | Created as Draft | 修 bug 的那一批已落地,按审查清单的顺序接着处理优化项;这一批只收不改用法的清理 | | 2026-11-04 | Accepted | 用户批准,开始实现 | +| 2026-11-04 | 第 1 步不含颜色面板的双向测试 | 写测试时发现 `NSColorPanel.bind(color:)` 一调用就崩溃(见后续项),崩溃的测试会中断整个测试进程;修它属于修 bug,不在这一批的范围里 | +| 2026-11-04 | 字体管理器补一条重新绑定的测试 | 第 3 步改动的正是解绑时移除回写动作的那段代码,现有测试没覆盖它 | +| 2026-11-04 | 现有的两条面板测试在调用私有方法前先确认它存在 | 方法不在时直接调用会让整个测试进程崩溃,金丝雀测试的结果也就看不到了 | diff --git a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift index 2727e77719..c7f78ee6cc 100644 --- a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift +++ b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift @@ -32,7 +32,7 @@ /// The panel reports the URL the user confirmed through its private 'setFinalURL:' setter, /// which is what the binding hooks. @Test("rebinding a save panel keeps reporting the confirmed URL") - func rebindingASavePanelKeepsReportingTheConfirmedURL() { + func rebindingASavePanelKeepsReportingTheConfirmedURL() throws { @UIBinding var firstURL: URL? = nil @UIBinding var secondURL: URL? = nil let savePanel = NSSavePanel() @@ -40,13 +40,13 @@ savePanel.bind(url: $secondURL) let confirmedURL = URL(filePath: "/tmp/confirmed.txt") - savePanel.perform(NSSelectorFromString("setFinalURL:"), with: confirmedURL) + try confirm(confirmedURL, in: savePanel, through: "setFinalURL:") #expect(secondURL == confirmedURL) } @Test("rebinding an open panel keeps reporting the confirmed URLs") - func rebindingAnOpenPanelKeepsReportingTheConfirmedURLs() { + func rebindingAnOpenPanelKeepsReportingTheConfirmedURLs() throws { @UIBinding var firstURLs: [URL] = [] @UIBinding var secondURLs: [URL] = [] let openPanel = NSOpenPanel() @@ -54,11 +54,21 @@ openPanel.bind(urls: $secondURLs) let confirmedURLs = [URL(filePath: "/tmp/first.txt"), URL(filePath: "/tmp/second.txt")] - openPanel.perform(NSSelectorFromString("setFinalURLs:"), with: confirmedURLs) + try confirm(confirmedURLs, in: openPanel, through: "setFinalURLs:") #expect(secondURLs == confirmedURLs) } + /// Reports a confirmed choice the way the panel itself does. Checks for the private setter + /// first: messaging a selector the panel no longer has would crash the whole test run. + private func confirm( + _ confirmedChoice: Any, in panel: NSSavePanel, through setterName: String + ) throws { + let setter = NSSelectorFromString(setterName) + try #require(panel.responds(to: setter)) + panel.perform(setter, with: confirmedChoice) + } + /// Types into the field the way the field editor reports it. private func edit(_ textField: NSTextField, to text: String) { textField.stringValue = text diff --git a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift new file mode 100644 index 0000000000..afc53a6d79 --- /dev/null +++ b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift @@ -0,0 +1,158 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// Each typed binding keeps its control and its source of truth in step: the control shows the + /// bound value, follows later changes to it, and writes the user's changes back. + @MainActor + @Suite struct ControlBindingRoundTripTests { + init() { + // NB: A control sends its action through 'NSApplication.sendAction(_:to:from:)', which + // silently does nothing when no application object exists yet. + _ = NSApplication.shared + } + + @Test("a switch stays in step with its binding") + func switchStaysInStep() async { + @UIBinding var isOn = true + let switchControl = NSSwitch(isOn: $isOn) + #expect(switchControl.state == .on) + + isOn = false + await Task.yield() + #expect(switchControl.state == .off) + + // NB: A click changes the switch's state without going through the property the binding + // observes, so only the action can carry the change back. + switchControl.performClick(nil) + #expect(isOn) + } + + @Test("a slider stays in step with its binding") + func sliderStaysInStep() async { + @UIBinding var value: Float = 0.25 + let slider = NSSlider(value: $value) + #expect(slider.floatValue == 0.25) + + value = 0.75 + await Task.yield() + #expect(slider.floatValue == 0.75) + + slider.floatValue = 0.5 + sendAction(of: slider) + #expect(value == 0.5) + } + + @Test("a stepper stays in step with its binding") + func stepperStaysInStep() async { + @UIBinding var value: Double = 3 + let stepper = NSStepper(value: $value) + #expect(stepper.doubleValue == 3) + + value = 7 + await Task.yield() + #expect(stepper.doubleValue == 7) + + stepper.doubleValue = 5 + sendAction(of: stepper) + #expect(value == 5) + } + + @Test("a date picker stays in step with its binding") + func datePickerStaysInStep() async { + @UIBinding var date = Date(timeIntervalSinceReferenceDate: 0) + let datePicker = NSDatePicker(date: $date) + #expect(datePicker.dateValue == Date(timeIntervalSinceReferenceDate: 0)) + + date = Date(timeIntervalSinceReferenceDate: 86_400) + await Task.yield() + #expect(datePicker.dateValue == Date(timeIntervalSinceReferenceDate: 86_400)) + + datePicker.dateValue = Date(timeIntervalSinceReferenceDate: 172_800) + sendAction(of: datePicker) + #expect(date == Date(timeIntervalSinceReferenceDate: 172_800)) + } + + @Test("a color well stays in step with its binding") + func colorWellStaysInStep() async { + @UIBinding var swatch = Swatch(color: Self.red) + let colorWell = NSColorWell(color: $swatch.color) + #expect(colorWell.color == Self.red) + + swatch.color = Self.blue + await Task.yield() + #expect(colorWell.color == Self.blue) + + colorWell.color = Self.green + sendAction(of: colorWell) + #expect(swatch.color == Self.green) + } + + @Test("a path control stays in step with its binding") + func pathControlStaysInStep() async { + @UIBinding var url: URL? = URL(filePath: "/System") + let pathControl = NSPathControl() + pathControl.bind(url: $url) + #expect(pathControl.url?.lastPathComponent == "System") + + url = URL(filePath: "/Library") + await Task.yield() + #expect(pathControl.url?.lastPathComponent == "Library") + + pathControl.url = URL(filePath: "/Applications") + sendAction(of: pathControl) + #expect(url?.lastPathComponent == "Applications") + } + + @Test("a segmented control stays in step with its binding") + func segmentedControlStaysInStep() async { + @UIBinding var segment = Segment.second + let segmentedControl = NSSegmentedControl( + labels: ["First", "Second", "Third"], trackingMode: .selectOne, target: nil, action: nil + ) + segmentedControl.bind(selectedSegment: $segment) + #expect(segmentedControl.selectedSegment == 1) + + segment = .third + await Task.yield() + #expect(segmentedControl.selectedSegment == 2) + + segmentedControl.selectedSegment = 0 + sendAction(of: segmentedControl) + #expect(segment == .first) + } + + /// `NSSavePanel.bind(url:)` and `NSOpenPanel.bind(urls:)` hook the private setters through + /// which a panel records what the user confirmed. Should AppKit drop or rename them, the + /// bindings would stop being written without any error; this test is what notices. + @Test( + "the private setters the panel bindings hook still exist", + arguments: ["setFinalURL:", "setFinalURLs:"] + ) + func panelSettersStillExist(_ selectorName: String) { + #expect(NSSavePanel.instancesRespond(to: NSSelectorFromString(selectorName))) + } + + private enum Segment: Int { + case first + case second + case third + } + + /// Holds the color in a value, the way a model would, rather than binding a class instance + /// directly. + private struct Swatch { + var color: NSColor + } + + private static let red = NSColor(srgbRed: 1, green: 0, blue: 0, alpha: 1) + private static let green = NSColor(srgbRed: 0, green: 1, blue: 0, alpha: 1) + private static let blue = NSColor(srgbRed: 0, green: 0, blue: 1, alpha: 1) + + /// What a control does once the user has changed its value. + private func sendAction(of control: NSControl) { + control.sendAction(control.action, to: control.target) + } + } +#endif diff --git a/Tests/AppKitNavigationTests/FontManagerBindingTests.swift b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift index dbc2af272f..0e7dea5e20 100644 --- a/Tests/AppKitNavigationTests/FontManagerBindingTests.swift +++ b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift @@ -18,23 +18,33 @@ /// the change and sends the font manager's action; `convert(_:)` then applies it to a font. @Test("a change from the font panel is applied to the bound font") func fontPanelChangeIsAppliedToTheBoundFont() throws { - let responder = ChangeFontResponder() - let application = NSApplication.shared - let previousDelegate = application.delegate - application.delegate = responder - defer { application.delegate = previousDelegate } + try withChangeFontResponder { + @UIBinding var textStyle = TextStyle(font: try Self.helvetica()) + let fontManager = NSFontManager.shared + fontManager.bind(font: $textStyle.font) - @UIBinding var textStyle = TextStyle(font: try #require(NSFont(name: "Helvetica", size: 20))) - let fontManager = NSFontManager.shared - fontManager.bind(font: $textStyle.font) + fontManager.addFontTrait(Self.boldMenuItem()) - let boldMenuItem = NSMenuItem() - boldMenuItem.tag = Int(NSFontTraitMask.boldFontMask.rawValue) - fontManager.addFontTrait(boldMenuItem) + #expect(textStyle.font.familyName == "Helvetica") + #expect(textStyle.font.pointSize == 20) + #expect(fontManager.traits(of: textStyle.font).contains(.boldFontMask)) + } + } + + @Test("rebinding the font manager stops writing changes to the previous binding") + func rebindingStopsWritingToThePreviousBinding() throws { + try withChangeFontResponder { + @UIBinding var previousStyle = TextStyle(font: try Self.helvetica()) + @UIBinding var currentStyle = TextStyle(font: try Self.helvetica()) + let fontManager = NSFontManager.shared + fontManager.bind(font: $previousStyle.font) + fontManager.bind(font: $currentStyle.font) - #expect(textStyle.font.familyName == "Helvetica") - #expect(textStyle.font.pointSize == 20) - #expect(fontManager.traits(of: textStyle.font).contains(.boldFontMask)) + fontManager.addFontTrait(Self.boldMenuItem()) + + #expect(fontManager.traits(of: currentStyle.font).contains(.boldFontMask)) + #expect(!fontManager.traits(of: previousStyle.font).contains(.boldFontMask)) + } } /// Holds the font in a value, the way a model would, rather than binding a class instance @@ -42,5 +52,25 @@ private struct TextStyle { var font: NSFont } + + private static func helvetica() throws -> NSFont { + try #require(NSFont(name: "Helvetica", size: 20)) + } + + /// The font menu's Bold item, which `addFontTrait(_:)` reads the trait to add from. + private static func boldMenuItem() -> NSMenuItem { + let boldMenuItem = NSMenuItem() + boldMenuItem.tag = Int(NSFontTraitMask.boldFontMask.rawValue) + return boldMenuItem + } + + private func withChangeFontResponder(_ body: () throws -> Void) rethrows { + let responder = ChangeFontResponder() + let application = NSApplication.shared + let previousDelegate = application.delegate + application.delegate = responder + defer { application.delegate = previousDelegate } + try body() + } } #endif From d6868bc6a0a5f345d33c5e3149dd55a5e46ef0c5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 20:39:08 +0800 Subject: [PATCH 058/141] fix(appkit): clear the AppKitNavigation build warnings - Mark the retroactive Sendable conformances of NSControl, NSToolbarItem and NSColorPanel '@unchecked', as NSMenuItem's and NSFontManager's already are. Without it, a future language mode rejects them. - Import Combine internally where no public declaration uses it. - Isolate the control factory in the action delivery tests to the main actor, since it calls main-actor initializers. The two unused public imports of IdentifiedCollections go away with the dependency itself. --- Documentations/Evolutions/draft-appkit-navigation-cleanup.md | 2 +- Sources/AppKitNavigation/Bindings/NSColorPanel.swift | 2 +- Sources/AppKitNavigation/Bindings/NSControl.swift | 2 +- Sources/AppKitNavigation/Bindings/NSToolbarItem.swift | 2 +- Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift | 2 +- .../Internal/PopoverPresentationsObserver.swift | 2 +- Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 791667ebe2..aee60a01b0 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -14,7 +14,7 @@ 先补测试,再动代码: 1. **补测试作安全网**(已完成):每个类型化的 `bind`(开关、滑块、步进器、日期、颜色、路径、分段)各补一条双向测试,颜色面板除外(见决策日志);字体管理器补一条重新绑定的测试。`NSSavePanel.bind(url:)` 与 `NSOpenPanel.bind(urls:)` 靠交换私有方法 `setFinalURL:` / `setFinalURLs:` 工作,系统去掉它们时现在只会静默失效;补一条测试,让那种情况立即变红。 -2. **清警告**: +2. **清警告**(已完成): - `NSControl`、`NSToolbarItem`、`NSColorPanel` 的 `@retroactive Sendable` 改成 `@unchecked @retroactive Sendable`,与 `NSMenuItem`、`NSFontManager` 一致。 - 两处没用在公开声明里的 `public import Combine` 改成内部导入。 - 上一批加的 `ControlActionDeliveryTests` 有 7 条并发警告:`makeControl()` 改为 `@MainActor`。 diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index b6c8092242..b8b5c71f9c 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -2,7 +2,7 @@ public import AppKit -extension NSColorPanel: @retroactive Sendable {} +extension NSColorPanel: @unchecked @retroactive Sendable {} extension NSColorPanel: TargetActionProtocol { public var target: AnyObject? { set { setTarget(newValue) } diff --git a/Sources/AppKitNavigation/Bindings/NSControl.swift b/Sources/AppKitNavigation/Bindings/NSControl.swift index 1dc9a83188..aabd124ba7 100755 --- a/Sources/AppKitNavigation/Bindings/NSControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -2,7 +2,7 @@ import AppKit -extension NSControl: @retroactive Sendable {} +extension NSControl: @unchecked @retroactive Sendable {} extension NSControl: TargetActionProtocol {} extension NSControl {} diff --git a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift index e90fec934d..cbc57bcde0 100644 --- a/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift +++ b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift @@ -2,7 +2,7 @@ import AppKit -extension NSToolbarItem: @retroactive Sendable {} +extension NSToolbarItem: @unchecked @retroactive Sendable {} extension NSToolbarItem: TargetActionProtocol {} #endif diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift index 5c0c3aef45..0130c42463 100644 --- a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift +++ b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift @@ -1,7 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit -public import Combine +import Combine @MainActor class ModalWindowsObserver: NSObject { diff --git a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift index f03a8e6c32..d0fe2e0acc 100644 --- a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift +++ b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift @@ -1,7 +1,7 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit -public import Combine +import Combine @MainActor final class PopoverPresentationsObserver: NSObject { diff --git a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift index cdca77add3..b6deb7d3e5 100644 --- a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift +++ b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift @@ -14,7 +14,7 @@ case segmentedControl case slider - func makeControl() -> NSControl { + @MainActor func makeControl() -> NSControl { switch self { case .pushButton: NSButton(title: "Push", target: nil, action: nil) From b4602722cdbfa09a38587ff3612de59b6be2cbc7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 20:43:12 +0800 Subject: [PATCH 059/141] refactor(appkit): run font manager bindings through the shared action proxy NSFontManager carried its own copy of the action proxy and of the binding implementation, because its non-optional 'action' keeps it from conforming to TargetActionProtocol. The copies drifted: the last round of fixes had to repair the same two defects in both. TargetActionProxy now has an initializer that takes the font manager's target-action pair over, and the body of 'bind(_:to:set:)' moves into one internal function that TargetActionProtocol and NSFontManager both call. The public API is unchanged. --- .../draft-appkit-navigation-cleanup.md | 2 +- .../Bindings/NSFontManager.swift | 147 ++---------------- .../Bindings/TargetActionProtocol.swift | 118 ++++++++------ .../Bindings/TargetActionProxy.swift | 25 ++- 4 files changed, 99 insertions(+), 193 deletions(-) mode change 100755 => 100644 Sources/AppKitNavigation/Bindings/NSFontManager.swift diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index aee60a01b0..adafe1ab50 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -18,7 +18,7 @@ - `NSControl`、`NSToolbarItem`、`NSColorPanel` 的 `@retroactive Sendable` 改成 `@unchecked @retroactive Sendable`,与 `NSMenuItem`、`NSFontManager` 一致。 - 两处没用在公开声明里的 `public import Combine` 改成内部导入。 - 上一批加的 `ControlActionDeliveryTests` 有 7 条并发警告:`makeControl()` 改为 `@MainActor`。 -3. **合并字体管理器的代理**:删掉 `FontManagerProxy` 和 `NSFontManager` 扩展里复制的 `bind(_:to:set:)`,改走 `TargetActionProxy` 和同一份绑定实现。`NSFontManager.action` 是非可选的 `Selector`,遵循不了 `TargetActionProtocol`,所以只共享内部实现,公开签名不变。 +3. **合并字体管理器的代理**(已完成):删掉 `FontManagerProxy` 和 `NSFontManager` 扩展里复制的 `bind(_:to:set:)`,改走 `TargetActionProxy` 和同一份绑定实现。`NSFontManager.action` 是非可选的 `Selector`,遵循不了 `TargetActionProtocol`,所以只共享内部实现,公开签名不变。实际做法:`TargetActionProxy` 加一个接管字体管理器的构造器;绑定的主体提成内部函数 `establishBinding(_:to:of:through:set:)`,两边的 `bind(_:to:set:)` 都转给它。 4. **去掉 `IdentifiedCollections`**:动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,与上游一致;两条 `public import IdentifiedCollections` 的警告一并消失。 5. **加库前缀**:`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。 6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**:它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift old mode 100755 new mode 100644 index ff123a04f1..6d9335a9c9 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -2,7 +2,6 @@ @_spi(Internals) public import SwiftNavigation public import AppKit -public import IdentifiedCollections extension NSFontManager: @unchecked @retroactive Sendable {} @@ -66,25 +65,6 @@ extension NSFontManager { } } - private var actionProxy: FontManagerProxy? { - set { - objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - objc_getAssociatedObject(self, actionProxyKey) as? FontManagerProxy - } - } - - private func createActionProxyIfNeeded() -> FontManagerProxy { - if let actionProxy { - return actionProxy - } else { - let actionProxy = FontManagerProxy(owner: self) - self.actionProxy = actionProxy - return actionProxy - } - } - /// Establishes a two-way connection between a source of truth and a property of this control. /// /// - Parameters: @@ -101,130 +81,21 @@ extension NSFontManager { to keyPath: KeyPath, set: @escaping (_ control: NSFontManager, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObserveToken { - unbind(keyPath) - let actionProxy = createActionProxyIfNeeded() - let actionID = actionProxy.addBindingAction { [weak self] _ in - guard let self else { return } - binding.wrappedValue = self[keyPath: keyPath] - } - - let isSetting = LockIsolated(false) - let token = observe { [weak self] transaction in - guard let self else { return } - isSetting.withLock { $0 = true } - defer { isSetting.withLock { $0 = false } } - set( - self, - binding.wrappedValue, - transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations - ? binding.transaction - : transaction - ) - } - // NB: This key path must only be accessed on the main actor - nonisolated(unsafe) let uncheckedKeyPath = keyPath - let observation = observe(keyPath) { control, _ in - guard isSetting.withLock({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: uncheckedKeyPath] - } - } - let observationToken = ObserveToken { [weak self] in - MainActor._assumeIsolated { - self?.actionProxy?.removeBindingAction(for: actionID) - } - token.cancel() - observation.invalidate() - } - observationTokens[keyPath] = observationToken - return observationToken + establishBinding(binding, to: keyPath, of: self, through: createActionProxyIfNeeded(), set: set) } public func unbind(_ keyPath: KeyPath) { - observationTokens[keyPath]?.cancel() - observationTokens[keyPath] = nil + removeBinding(to: keyPath) } -} - -@MainActor -private let observationTokensKey = malloc(1)! -@MainActor -private let actionProxyKey = malloc(1)! -@MainActor -private class FontManagerProxy: NSObject { - typealias ActionClosure = (Any?) -> Void - - typealias ActionIdentifier = UUID - - private struct Action: Identifiable { - let id = UUID() - - var closure: ActionClosure - - func invoke(_ sender: Any?) { - closure(sender) - } - } - - private var bindingActions: IdentifiedArrayOf = [] - - private var actions: IdentifiedArrayOf = [] - - private var originTarget: AnyObject? - - private var originAction: Selector? - - weak var owner: NSFontManager? - - required init(owner: NSFontManager) { - self.owner = owner - super.init() - self.originTarget = owner.target - self.originAction = owner.action - owner.target = self - owner.action = #selector(invokeAction(_:)) - } - - @objc func invokeAction(_ sender: Any?) { - // NB: The font manager's target is 'nil' unless an app changes it: 'changeFont:' travels up - // the responder chain to whichever text view is first responder. Forward a 'nil' target - // as 'nil', which 'sendAction(_:to:from:)' routes there. - if let originAction { - NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) + private func createActionProxyIfNeeded() -> TargetActionProxy { + if let actionProxy { + return actionProxy + } else { + let actionProxy = TargetActionProxy(fontManager: self) + self.actionProxy = actionProxy + return actionProxy } - bindingActions.forEach { $0.invoke(sender) } - actions.forEach { $0.invoke(sender) } - } - - @discardableResult - func addAction(_ actionClosure: @escaping ActionClosure) -> ActionIdentifier { - let action = Action(closure: actionClosure) - actions.append(action) - return action.id - } - - func removeAction(for id: ActionIdentifier) { - actions.remove(id: id) - } - - func removeAllActions() { - actions.removeAll() - } - - @discardableResult - func addBindingAction(_ bindingActionClosure: @escaping ActionClosure) -> ActionIdentifier { - let bindingAction = Action(closure: bindingActionClosure) - bindingActions.append(bindingAction) - return bindingAction.id - } - - func removeBindingAction(for id: ActionIdentifier) { - bindingActions.remove(id: id) - } - - func removeAllBindingActions() { - bindingActions.removeAll() } } diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index 80787025dc..2a15d7931c 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -27,15 +27,6 @@ extension TargetActionProtocol { } } - var actionProxy: TargetActionProxy? { - set { - objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - } - get { - objc_getAssociatedObject(self, actionProxyKey) as? TargetActionProxy - } - } - func createActionProxyIfNeeded() -> TargetActionProxy { if let actionProxy { return actionProxy @@ -62,48 +53,11 @@ extension TargetActionProtocol { to keyPath: KeyPath, set: @escaping (_ control: Self, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObserveToken { - unbind(keyPath) - let actionProxy = createActionProxyIfNeeded() - let actionID = actionProxy.addBindingAction { [weak self] _ in - guard let self else { return } - binding.wrappedValue = self[keyPath: keyPath] - } - - let isSetting = LockIsolated(false) - let token = observe { [weak self] transaction in - guard let self else { return } - isSetting.withLock { $0 = true } - defer { isSetting.withLock { $0 = false } } - set( - self, - binding.wrappedValue, - transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations - ? binding.transaction - : transaction - ) - } - // NB: This key path must only be accessed on the main actor - nonisolated(unsafe) let uncheckedKeyPath = keyPath - let observation = observe(keyPath) { control, _ in - guard isSetting.withLock({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = control[keyPath: uncheckedKeyPath] - } - } - let observationToken = ObserveToken { [weak self] in - MainActor._assumeIsolated { - self?.actionProxy?.removeBindingAction(for: actionID) - } - token.cancel() - observation.invalidate() - } - observationTokens[keyPath] = observationToken - return observationToken + establishBinding(binding, to: keyPath, of: self, through: createActionProxyIfNeeded(), set: set) } public func unbind(_ keyPath: KeyPath) { - observationTokens[keyPath]?.cancel() - observationTokens[keyPath] = nil + removeBinding(to: keyPath) } @discardableResult @@ -123,6 +77,58 @@ extension TargetActionProtocol { } } +/// Establishes a two-way connection between a binding and a property of an object whose +/// target-action pair `actionProxy` runs: the object's action writes the property back to the +/// binding, and changes to the binding are applied with `set`. +/// +/// ``TargetActionProtocol`` and `NSFontManager` both bind through this. The font manager cannot +/// conform to the protocol, since its `action` is not optional. +@MainActor +func establishBinding( + _ binding: UIBinding, + to keyPath: KeyPath, + of owner: Owner, + through actionProxy: TargetActionProxy, + set: @escaping (_ owner: Owner, _ newValue: Value, _ transaction: UITransaction) -> Void +) -> ObserveToken { + owner.removeBinding(to: keyPath) + let actionID = actionProxy.addBindingAction { [weak owner] _ in + guard let owner else { return } + binding.wrappedValue = owner[keyPath: keyPath] + } + + let isSetting = LockIsolated(false) + let token = owner.observe { [weak owner] transaction in + guard let owner else { return } + isSetting.withLock { $0 = true } + defer { isSetting.withLock { $0 = false } } + set( + owner, + binding.wrappedValue, + transaction.appKit.animation == nil && !transaction.appKit.disablesAnimations + ? binding.transaction + : transaction + ) + } + // NB: This key path must only be accessed on the main actor + nonisolated(unsafe) let uncheckedKeyPath = keyPath + let observation = owner.observe(keyPath) { owner, _ in + guard isSetting.withLock({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = owner[keyPath: uncheckedKeyPath] + } + } + let observationToken = ObserveToken { [weak actionProxy] in + MainActor._assumeIsolated { + actionProxy?.removeBindingAction(for: actionID) + } + token.cancel() + observation.invalidate() + } + owner.observationTokens[keyPath] = observationToken + return observationToken +} + @MainActor extension NSObject { var observationTokens: [AnyKeyPath: ObserveToken] { @@ -136,6 +142,22 @@ extension NSObject { ) } } + + /// The proxy that runs this object's binding and closure actions, once one has been installed. + var actionProxy: TargetActionProxy? { + set { + objc_setAssociatedObject(self, actionProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + get { + objc_getAssociatedObject(self, actionProxyKey) as? TargetActionProxy + } + } + + /// Cancels the binding established to `keyPath`, if there is one. + func removeBinding(to keyPath: AnyKeyPath) { + observationTokens[keyPath]?.cancel() + observationTokens[keyPath] = nil + } } @MainActor diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 7a702ac17a..5a93a83c28 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -37,10 +37,7 @@ class TargetActionProxy: NSObject { /// keyboard-driven button never tracks), so the proxy still has to take the pair over. private let registersAsAdditionalTarget: Bool - weak var owner: (any TargetActionProtocol)? - - required init(owner: any TargetActionProtocol) { - self.owner = owner + init(owner: any TargetActionProtocol) { if #available(macOS 27, *) { registersAsAdditionalTarget = owner is NSControl } else { @@ -81,6 +78,20 @@ class TargetActionProxy: NSObject { } } + /// Takes the font manager's target-action pair over. + /// + /// The font manager cannot conform to ``TargetActionProtocol``, since its `action` is not + /// optional, and it is no control, so it has no additional targets to register with on any OS + /// version. + init(fontManager: NSFontManager) { + registersAsAdditionalTarget = false + super.init() + originTarget = fontManager.target + originAction = fontManager.action + fontManager.target = self + fontManager.action = #selector(invokeAction(_:)) + } + @objc func controlTextDidChange(_ obj: Notification) { bindingActions.forEach { $0.invoke(obj.object) } actions.forEach { $0.invoke(obj.object) } @@ -91,8 +102,10 @@ class TargetActionProxy: NSObject { // control, so AppKit delivers to it directly and forwarding here would double up. // // A 'nil' original target is forwarded as 'nil': it means "up the responder chain", which - // is where 'sendAction(_:to:from:)' routes it. Menu items, and controls wired to the - // first responder, rely on that. + // is where 'sendAction(_:to:from:)' routes it. Menu items, controls wired to the first + // responder, and the font manager rely on that: unless an app changes it, the font + // manager's target is 'nil', and its 'changeFont:' travels up the chain to whichever text + // view is first responder. if !registersAsAdditionalTarget, let originAction { NSApplication.shared.sendAction(originAction, to: originTarget, from: sender) } From 964518e95c84f948e20bd64ddfa524ecb294d7dc Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 20:43:38 +0800 Subject: [PATCH 060/141] docs: record the upstream warning the cleanup leaves in AppKitAnimation --- .../Evolutions/draft-appkit-navigation-cleanup.md | 3 ++- Documentations/Internal/ReviewDecisions.md | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index adafe1ab50..dc10744378 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -7,7 +7,7 @@ ## 摘要 -不改用法,把 AppKitNavigation 收拾干净:清掉现有的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。 +不改用法,把 AppKitNavigation 收拾干净:清掉 fork 自己代码里的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。 ## 方案 @@ -47,3 +47,4 @@ | 2026-11-04 | 第 1 步不含颜色面板的双向测试 | 写测试时发现 `NSColorPanel.bind(color:)` 一调用就崩溃(见后续项),崩溃的测试会中断整个测试进程;修它属于修 bug,不在这一批的范围里 | | 2026-11-04 | 字体管理器补一条重新绑定的测试 | 第 3 步改动的正是解绑时移除回写动作的那段代码,现有测试没覆盖它 | | 2026-11-04 | 现有的两条面板测试在调用私有方法前先确认它存在 | 方法不在时直接调用会让整个测试进程崩溃,金丝雀测试的结果也就看不到了 | +| 2026-11-04 | `AppKitAnimation.swift` 里的一条 `Sendable` 警告不改,记进 [ReviewDecisions.md](../Internal/ReviewDecisions.md) | 起草时的 14 条是增量构建统计的,漏了这个没重新编译的文件;用全新的构建目录重编一遍才看到它。它是与上游共用的代码,按上面的假设不碰 | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index 51301fd8ee..028b000b2b 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -44,6 +44,12 @@ - **理由**:AppKit 那份已按 UTF-16 换算修好。UIKit 那份是上游拥有的代码,fork 保持与上游一致,在 fork 里改会让以后的合并持续冲突。 - **复查条件**:上游自己修了,或者 fork 的 UIKit 用户撞上这个问题时。 +### `AppKitAnimation.swift` 的一条 `Sendable` 捕获警告 + +- **裁决**:上游的代码,fork 不修。(2026-11-04) +- **理由**:`AppKitAnimation.perform(_:completion:)` 把不是 `Sendable` 的 `completion` 捕获进 `NSAnimationContext` 的 `@Sendable` 完成回调,编译器因此报警告。这个文件属于上游的 AppKitNavigation,fork 与上游只差一行注释;在 fork 里改,以后合并上游时就多一处冲突。 +- **复查条件**:上游修了它时。 + ## 系统限制 ### 字体绑定只在响应链上有对象实现 `changeFont(_:)` 时生效 From b5c35097c18ce6fc4bfe4bb9d1e07457bd8c4e33 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 20:44:20 +0800 Subject: [PATCH 061/141] chore(appkit): drop the IdentifiedCollections dependency AppKitNavigation only used it for the two private action lists of the target-action proxy, which plain arrays serve just as well. Each of the four package manifests loses the dependency, and the lockfile loses it along with swift-collections, which only it pulled in. The lockfile's pins now match upstream's. --- .../draft-appkit-navigation-cleanup.md | 2 +- Package.resolved | 20 +------------------ Package.swift | 2 -- Package@swift-6.0.swift | 2 -- Package@swift-6.1.swift | 2 -- Package@swift-6.2.swift | 2 -- .../Bindings/TargetActionProxy.swift | 9 ++++----- 7 files changed, 6 insertions(+), 33 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index dc10744378..732426105b 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -19,7 +19,7 @@ - 两处没用在公开声明里的 `public import Combine` 改成内部导入。 - 上一批加的 `ControlActionDeliveryTests` 有 7 条并发警告:`makeControl()` 改为 `@MainActor`。 3. **合并字体管理器的代理**(已完成):删掉 `FontManagerProxy` 和 `NSFontManager` 扩展里复制的 `bind(_:to:set:)`,改走 `TargetActionProxy` 和同一份绑定实现。`NSFontManager.action` 是非可选的 `Selector`,遵循不了 `TargetActionProtocol`,所以只共享内部实现,公开签名不变。实际做法:`TargetActionProxy` 加一个接管字体管理器的构造器;绑定的主体提成内部函数 `establishBinding(_:to:of:through:set:)`,两边的 `bind(_:to:set:)` 都转给它。 -4. **去掉 `IdentifiedCollections`**:动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,与上游一致;两条 `public import IdentifiedCollections` 的警告一并消失。 +4. **去掉 `IdentifiedCollections`**(已完成):动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,依赖条目与上游一致(只剩 `originHash` 不同);两条 `public import IdentifiedCollections` 的警告一并消失。 5. **加库前缀**:`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。 6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**:它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 7. **文档**:删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。 diff --git a/Package.resolved b/Package.resolved index 0d2d3b35f9..b1255becc1 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "b529d85a44e8b6d00b50a6e6af790949b66026862c64c367ff5b0eb658f4a4fa", + "originHash" : "696fb0ef1c5b1570c6d08c3cd197a39c299326aa7f71e9fa5fc3bea7474942de", "pins" : [ { "identity" : "swift-case-paths", @@ -10,15 +10,6 @@ "version" : "1.10.0" } }, - { - "identity" : "swift-collections", - "kind" : "remoteSourceControl", - "location" : "https://github.com/apple/swift-collections", - "state" : { - "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", - "version" : "1.6.0" - } - }, { "identity" : "swift-custom-dump", "kind" : "remoteSourceControl", @@ -46,15 +37,6 @@ "version" : "1.0.0" } }, - { - "identity" : "swift-identified-collections", - "kind" : "remoteSourceControl", - "location" : "https://github.com/pointfreeco/swift-identified-collections", - "state" : { - "revision" : "322d9ffeeba85c9f7c4984b39422ec7cc3c56597", - "version" : "1.1.1" - } - }, { "identity" : "swift-issue-reporting", "kind" : "remoteSourceControl", diff --git a/Package.swift b/Package.swift index 90bdeb2084..94c9bb185f 100644 --- a/Package.swift +++ b/Package.swift @@ -62,7 +62,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-issue-reporting", from: "2.1.0"), .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), - .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.7.0"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.10.1"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -189,7 +188,6 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", - .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 6650ec5c71..7114d91e40 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -35,7 +35,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.6.0"), .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), - .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.10.1"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.13.0"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -117,7 +116,6 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", - .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Package@swift-6.1.swift b/Package@swift-6.1.swift index e8c5f80af1..4b5af868b4 100644 --- a/Package@swift-6.1.swift +++ b/Package@swift-6.1.swift @@ -62,7 +62,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.6.0"), .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), - .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.10.1"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.13.0"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -195,7 +194,6 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", - .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift index df361cb96a..b7e08743af 100644 --- a/Package@swift-6.2.swift +++ b/Package@swift-6.2.swift @@ -62,7 +62,6 @@ let package = Package( .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.6.0"), .package(url: "https://github.com/pointfreeco/swift-perception", "1.3.4"..<"3.0.0"), - .package(url: "https://github.com/pointfreeco/swift-identified-collections", from: "1.1.0"), .package(url: "https://github.com/pointfreeco/swift-sharing", from: "2.10.1"), .package(url: "https://github.com/pointfreeco/xctest-dynamic-overlay", from: "1.13.0"), .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.0.0"), @@ -196,7 +195,6 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", - .product(name: "IdentifiedCollections", package: "swift-identified-collections"), ] ), .target( diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 5a93a83c28..dc15deea70 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -1,7 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit -public import IdentifiedCollections import AppKitNavigationShim @MainActor @@ -20,9 +19,9 @@ class TargetActionProxy: NSObject { } } - private var bindingActions: IdentifiedArrayOf = [] + private var bindingActions: [Action] = [] - private var actions: IdentifiedArrayOf = [] + private var actions: [Action] = [] private var originTarget: AnyObject? @@ -121,7 +120,7 @@ class TargetActionProxy: NSObject { } func removeAction(for id: ActionIdentifier) { - actions.remove(id: id) + actions.removeAll { $0.id == id } } func removeAllActions() { @@ -136,7 +135,7 @@ class TargetActionProxy: NSObject { } func removeBindingAction(for id: ActionIdentifier) { - bindingActions.remove(id: id) + bindingActions.removeAll { $0.id == id } } func removeAllBindingActions() { From a5c7d481be5b8ec74ef830ee12ef9e4b6847eb03 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 21:07:53 +0800 Subject: [PATCH 062/141] refactor(appkit): name the Objective-C members added to AppKit classes after the library A method a Swift extension adds to an AppKit class replaces any method the class has, or gains later, under the same selector, for every instance in the app. That is how an unprefixed 'textViewDidChangeSelection:' broke every text field's selection handling. NSSwitch's 'boolValue' and NSFontManager's '_selectedFont' risked the same, so they become 'appKitNavigationIsOn' and 'appKitNavigationSelectedFont'. Neither is public. A new test scans the classes of AppKit, Foundation and the Objective-C runtime for methods implemented in the library and requires each to carry its name, except the five the shim replaces on purpose. It runs on the main actor: naming 'NSView' from a background thread runs its '+initialize' there and ties AppKit to the wrong thread, which made other tests running in parallel trap in event handling or raise "already on an AppKit thread". --- .../draft-appkit-navigation-cleanup.md | 4 +- .../Bindings/NSFontManager.swift | 6 +- .../AppKitNavigation/Bindings/NSSwitch.swift | 8 +- .../ObjectiveCMethodNamingTests.swift | 106 ++++++++++++++++++ 4 files changed, 118 insertions(+), 6 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 732426105b..a8b736b9ac 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -20,7 +20,7 @@ - 上一批加的 `ControlActionDeliveryTests` 有 7 条并发警告:`makeControl()` 改为 `@MainActor`。 3. **合并字体管理器的代理**(已完成):删掉 `FontManagerProxy` 和 `NSFontManager` 扩展里复制的 `bind(_:to:set:)`,改走 `TargetActionProxy` 和同一份绑定实现。`NSFontManager.action` 是非可选的 `Selector`,遵循不了 `TargetActionProtocol`,所以只共享内部实现,公开签名不变。实际做法:`TargetActionProxy` 加一个接管字体管理器的构造器;绑定的主体提成内部函数 `establishBinding(_:to:of:through:set:)`,两边的 `bind(_:to:set:)` 都转给它。 4. **去掉 `IdentifiedCollections`**(已完成):动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,依赖条目与上游一致(只剩 `originHash` 不同);两条 `public import IdentifiedCollections` 的警告一并消失。 -5. **加库前缀**:`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。 +5. **加库前缀**(已完成):`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字(`appKitNavigationIsOn`、`appKitNavigationSelectedFont`)。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。另加一条测试守住这一类:扫描本库加在系统类上的 Objective-C 方法,名字里都要带库名,shim 有意替换的五个方法除外。 6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**:它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 7. **文档**:删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。 @@ -48,3 +48,5 @@ | 2026-11-04 | 字体管理器补一条重新绑定的测试 | 第 3 步改动的正是解绑时移除回写动作的那段代码,现有测试没覆盖它 | | 2026-11-04 | 现有的两条面板测试在调用私有方法前先确认它存在 | 方法不在时直接调用会让整个测试进程崩溃,金丝雀测试的结果也就看不到了 | | 2026-11-04 | `AppKitAnimation.swift` 里的一条 `Sendable` 警告不改,记进 [ReviewDecisions.md](../Internal/ReviewDecisions.md) | 起草时的 14 条是增量构建统计的,漏了这个没重新编译的文件;用全新的构建目录重编一遍才看到它。它是与上游共用的代码,按上面的假设不碰 | +| 2026-11-04 | 第 5 步加一条命名测试,扫描本库加在系统类上的方法 | 只改两个名字,管不住以后再加的成员;测试先红(正好报出这两个成员的四个方法),改名后变绿 | +| 2026-11-04 | 命名测试放在主线程上跑 | 第一版没标 `@MainActor`:在后台线程写出 `NSView.self` 会在那条线程上执行 `+initialize`,让 AppKit 认错了线程。并行跑的其他测试随后在主线程处理事件时陷入断言陷阱,或者在打开面板时抛出 `already on an AppKit thread`,10 次里崩了 4 次;放到主线程后连跑 20 次没有再崩 | diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index 6d9335a9c9..d97250bae0 100644 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -34,10 +34,12 @@ extension NSFontManager { /// - Returns: A cancel token. @discardableResult public func bind(font: UIBinding) -> ObserveToken { - bind(font, to: \._selectedFont) + bind(font, to: \.appKitNavigationSelectedFont) } - @objc private var _selectedFont: NSFont { + // NB: Exposed to Objective-C so the binding can observe it, and named after the library so that + // it can never replace a method AppKit has, or adds later, under the same selector. + @objc private var appKitNavigationSelectedFont: NSFont { set { setSelectedFont(newValue, isMultiple: false) } // NB: 'convert(_:)' applies the font panel's latest change to the font it is given. That has // to be the bound font, which the setter above recorded as the selected font; converting diff --git a/Sources/AppKitNavigation/Bindings/NSSwitch.swift b/Sources/AppKitNavigation/Bindings/NSSwitch.swift index e643487ec0..fcba9fe359 100755 --- a/Sources/AppKitNavigation/Bindings/NSSwitch.swift +++ b/Sources/AppKitNavigation/Bindings/NSSwitch.swift @@ -21,12 +21,14 @@ extension NSSwitch { /// - Returns: A cancel token. @discardableResult public func bind(isOn: UIBinding) -> ObserveToken { - bind(isOn, to: \.boolValue) { control, isOn, transaction in - control.boolValue = isOn + bind(isOn, to: \.appKitNavigationIsOn) { control, isOn, transaction in + control.appKitNavigationIsOn = isOn } } - @objc var boolValue: Bool { + // NB: Exposed to Objective-C so the binding can observe it, and named after the library so + // that it can never replace a method AppKit has, or adds later, under the same selector. + @objc var appKitNavigationIsOn: Bool { set { state = newValue ? .on : .off } get { state == .on } } diff --git a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift new file mode 100644 index 0000000000..7727046b59 --- /dev/null +++ b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift @@ -0,0 +1,106 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import MachO + import ObjectiveC + import Testing + + /// A method the library adds to a class it does not own replaces whatever method that class has, + /// or gains in a later release, under the same selector — silently, for every instance in the + /// app. An unprefixed `textViewDidChangeSelection:` added to `NSTextField` once broke the + /// selection handling of every text field that way. Carrying the library's name in every such + /// selector keeps the two apart. + // NB: On the main actor because naming an AppKit class from Swift runs its '+initialize' on + // the calling thread. Doing that for 'NSView' on a background thread, while other tests run + // in parallel, left AppKit tied to the wrong thread: event handling on the main thread then + // trapped, and open panels raised "already on an AppKit thread". + @MainActor + @Suite struct ObjectiveCMethodNamingTests { + @Test("every Objective-C method the library adds to a system class carries its name") + func methodsAddedToSystemClassesCarryTheLibraryName() throws { + let addedMethods = try Self.methodsImplementedInThisBinary( + inClassesFromImagesOf: [NSView.self, NotificationCenter.self, NSObject.self] + ) + // NB: The library is linked into the test binary. Should that change, the scan would find + // nothing and pass for the wrong reason. + try #require( + addedMethods.contains("-[NSViewController _AppKitNavigation_hasViewAppeared]"), + "The scan must find the library's own methods" + ) + + let unnamedMethods = addedMethods.filter { method in + !method.localizedCaseInsensitiveContains("AppKitNavigation") + && !Self.deliberatelyReplacedMethods.contains(method) + } + + #expect(unnamedMethods.isEmpty, "Methods without the library's name: \(unnamedMethods)") + } + + /// The methods the library replaces on purpose: the shim exchanges its own implementations in + /// for these, to learn when a view controller appears, disappears or is dismissed, and what + /// the user confirmed in a save panel. + private static let deliberatelyReplacedMethods: Set = [ + "-[NSViewController viewDidAppear]", + "-[NSViewController viewDidDisappear]", + "-[NSViewController dismissViewController:]", + "-[NSSavePanel setFinalURL:]", + "-[NSSavePanel setFinalURLs:]", + ] + + /// Every method of the classes defined in the given classes' images whose implementation + /// lives in this test binary, formatted the way Objective-C prints a method. + private static func methodsImplementedInThisBinary( + inClassesFromImagesOf representativeClasses: [AnyClass] + ) throws -> [String] { + let codeRange = try codeRangeOfThisBinary() + var methodDescriptions: [String] = [] + for representativeClass in representativeClasses { + let imageName = try #require(class_getImageName(representativeClass)) + var classCount: UInt32 = 0 + let classNames = try #require(objc_copyClassNamesForImage(imageName, &classCount)) + defer { free(classNames) } + for classIndex in 0.., prefix: String, + className: String + ) -> [String] { + var methodCount: UInt32 = 0 + guard let methodList = class_copyMethodList(methodOwner, &methodCount) else { return [] } + defer { free(methodList) } + var methodDescriptions: [String] = [] + for methodIndex in 0.. Range { + let header = #dsohandle.assumingMemoryBound(to: mach_header_64.self) + var codeSize: UInt = 0 + let codeStart = UInt(bitPattern: try #require(getsegmentdata(header, "__TEXT", &codeSize))) + return codeStart..<(codeStart + codeSize) + } + } +#endif From e5c029462f2019edef902408c0be475eec39c100 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 21:09:53 +0800 Subject: [PATCH 063/141] test(appkit): drop a redundant check from the method naming test 'getsegmentdata' is imported as implicitly unwrapped, so requiring its result to be non-nil only produced a warning. The test already fails if the scan finds none of the library's own methods. --- .../ObjectiveCMethodNamingTests.swift | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift index 7727046b59..e6cff2e598 100644 --- a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift +++ b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift @@ -52,7 +52,7 @@ private static func methodsImplementedInThisBinary( inClassesFromImagesOf representativeClasses: [AnyClass] ) throws -> [String] { - let codeRange = try codeRangeOfThisBinary() + let codeRange = codeRangeOfThisBinary() var methodDescriptions: [String] = [] for representativeClass in representativeClasses { let imageName = try #require(class_getImageName(representativeClass)) @@ -96,10 +96,13 @@ /// Where this binary's code is loaded. Comparing addresses against it is much faster than /// asking 'dladdr' about each of the system's tens of thousands of methods. - private static func codeRangeOfThisBinary() throws -> Range { + /// + /// Should it ever come back empty, the scan finds none of the library's own methods, and the + /// test fails on that instead. + private static func codeRangeOfThisBinary() -> Range { let header = #dsohandle.assumingMemoryBound(to: mach_header_64.self) var codeSize: UInt = 0 - let codeStart = UInt(bitPattern: try #require(getsegmentdata(header, "__TEXT", &codeSize))) + let codeStart = UInt(bitPattern: getsegmentdata(header, "__TEXT", &codeSize)) return codeStart..<(codeStart + codeSize) } } From 96609a0a7da7e9db8751bba7bc492ed41e4d099b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 21:09:53 +0800 Subject: [PATCH 064/141] refactor(appkit): stop publishing a Sendable conformance for AnyCancellable The text field bindings declared 'AnyCancellable: @unchecked @retroactive Sendable' only so that their observation tokens could capture Combine subscriptions. As a public retroactive conformance on a Combine type, it applied to every client of the library and could clash with the same conformance declared elsewhere. The subscriptions are now captured through 'nonisolated(unsafe)' constants instead, the way the library already captures key paths. --- .../draft-appkit-navigation-cleanup.md | 2 +- .../Bindings/NSTextField.swift | 18 +++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index a8b736b9ac..2da0f0392a 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -21,7 +21,7 @@ 3. **合并字体管理器的代理**(已完成):删掉 `FontManagerProxy` 和 `NSFontManager` 扩展里复制的 `bind(_:to:set:)`,改走 `TargetActionProxy` 和同一份绑定实现。`NSFontManager.action` 是非可选的 `Selector`,遵循不了 `TargetActionProtocol`,所以只共享内部实现,公开签名不变。实际做法:`TargetActionProxy` 加一个接管字体管理器的构造器;绑定的主体提成内部函数 `establishBinding(_:to:of:through:set:)`,两边的 `bind(_:to:set:)` 都转给它。 4. **去掉 `IdentifiedCollections`**(已完成):动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,依赖条目与上游一致(只剩 `originHash` 不同);两条 `public import IdentifiedCollections` 的警告一并消失。 5. **加库前缀**(已完成):`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字(`appKitNavigationIsOn`、`appKitNavigationSelectedFont`)。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。另加一条测试守住这一类:扫描本库加在系统类上的 Objective-C 方法,名字里都要带库名,shim 有意替换的五个方法除外。 -6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**:它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 +6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**(已完成):它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 7. **文档**:删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。 没有询问就采用的假设: diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index 4a8931242e..a03b7d09ff 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -67,7 +67,10 @@ extension NSTextField { selection.wrappedValue = textSelection } } - let editingChangedAction = NotificationCenter.default + // NB: The subscriptions are only cancelled from the token below, on the main actor, but + // 'AnyCancellable' is not 'Sendable', so the token's closure has to capture them + // unchecked. + nonisolated(unsafe) let editingChangedAction = NotificationCenter.default .publisher(for: NSTextField.textDidChangeNotification, object: self) .sink { [weak self] _ in guard let self else { return } @@ -77,7 +80,7 @@ extension NSTextField { // being edited. AppKit implements that delegate method on text fields itself, so it // must not be replaced; the notification the field editor posts alongside carries the // same news. One field editor serves every field in a window, hence the delegate check. - let selectionChangedAction = NotificationCenter.default + nonisolated(unsafe) let selectionChangedAction = NotificationCenter.default .publisher(for: NSTextView.didChangeSelectionNotification) .sink { [weak self] notification in guard @@ -87,7 +90,7 @@ extension NSTextField { else { return } MainActor._assumeIsolated { reportSelection(self) } } - let editingDidEndAction = NotificationCenter.default + nonisolated(unsafe) let editingDidEndAction = NotificationCenter.default .publisher(for: NSTextField.textDidEndEditingNotification, object: self) .sink { _ in selection.wrappedValue = nil } let token = observe { [weak self] in @@ -216,7 +219,10 @@ extension NSTextField { // editor, once it has been set up for this field: the field editor being first // responder, with this field as its delegate, is what it means for the field to have // focus. One field editor serves every field in a window, hence both checks. - let focusGainedAction = NotificationCenter.default + // + // Both subscriptions are captured unchecked by the token below; see + // 'bind(selection:)'. + nonisolated(unsafe) let focusGainedAction = NotificationCenter.default .publisher(for: NSTextView.didChangeSelectionNotification) .sink { [weak self] notification in MainActor._assumeIsolated { @@ -233,7 +239,7 @@ extension NSTextField { // NB: Unlike its begin counterpart, this is posted whenever focus leaves the field, edited // or not. - let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in + nonisolated(unsafe) let editingDidEndAction = NotificationCenter.default.publisher(for: NSTextField.textDidEndEditingNotification, object: self).sink { _ in guard focus.wrappedValue == value else { return } focus.wrappedValue = nil } @@ -346,6 +352,4 @@ public struct AppKitTextSelection: Hashable, Sendable { } } -extension AnyCancellable: @unchecked @retroactive Sendable {} - #endif From 259b8136adb21a5d366a632e0316eebf4febf25e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 21:14:38 +0800 Subject: [PATCH 065/141] docs(appkit): replace the UIKit leftovers in the AppKitNavigation documentation The documentation catalog carried twelve pages copied from UIKitNavigation, none of which resolved, and the landing page listed none of the bindings or presentations. The pages go, and the landing page gains an overview and a topic group for each. Doc comments get the same treatment: the text field focus bindings documented UIKit examples and linked UIKit symbols, several comments described parameters that do not exist, and the segmented control's spoke of a color well. DocC now reports 3 warnings for the module instead of 23; the remaining ones come from content shared with upstream. --- .../draft-appkit-navigation-cleanup.md | 2 +- .../Bindings/NSColorPanel.swift | 6 +- .../Bindings/NSFontManager.swift | 2 - .../Bindings/NSSegmentedControl.swift | 24 ++- .../Bindings/NSTextField.swift | 83 ++++----- .../Bindings/TargetActionProtocol.swift | 2 - .../Documentation.docc/AppKitNavigation.md | 36 ++++ .../Extensions/UIColorWell.md | 8 - .../Extensions/UIControlProtocol.md | 8 - .../Extensions/UIDatePicker.md | 8 - .../Extensions/UIKitAnimation.md | 35 ---- .../Extensions/UIPageControl.md | 8 - .../Documentation.docc/Extensions/UISlider.md | 8 - .../Extensions/UIStepper.md | 8 - .../Documentation.docc/Extensions/UISwitch.md | 8 - .../Extensions/UITextField.md | 22 --- .../Extensions/UIViewController.md | 26 --- .../Documentation.docc/Extensions/observe.md | 7 - .../Documentation.docc/UIKitNavigation.md | 165 ------------------ 19 files changed, 94 insertions(+), 372 deletions(-) delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIColorWell.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIControlProtocol.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIDatePicker.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIKitAnimation.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIPageControl.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UISlider.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIStepper.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UISwitch.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UITextField.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/UIViewController.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/Extensions/observe.md delete mode 100644 Sources/AppKitNavigation/Documentation.docc/UIKitNavigation.md diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 2da0f0392a..119757285d 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -22,7 +22,7 @@ 4. **去掉 `IdentifiedCollections`**(已完成):动作列表改用普通数组。四份 `Package*.swift` 删掉这个依赖,`Package.resolved` 随之少掉 `swift-identified-collections` 和 `swift-collections`,依赖条目与上游一致(只剩 `originHash` 不同);两条 `public import IdentifiedCollections` 的警告一并消失。 5. **加库前缀**(已完成):`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字(`appKitNavigationIsOn`、`appKitNavigationSelectedFont`)。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。另加一条测试守住这一类:扫描本库加在系统类上的 Objective-C 方法,名字里都要带库名,shim 有意替换的五个方法除外。 6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**(已完成):它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 -7. **文档**:删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。 +7. **文档**(已完成):删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加一段概述和「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。实际还顺带修了 fork 自己的文档注释:文本框焦点绑定的示例和说明是从 UIKit 抄的,改成 AppKit 的写法;删掉不存在的参数说明,补上分段控件缺的参数说明。AppKitNavigation 的 DocC 警告从 23 条降到 3 条,剩下的都来自与上游共用的内容。 没有询问就采用的假设: diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index b8b5c71f9c..a006a52ea9 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -19,10 +19,8 @@ extension NSColorPanel { /// Creates a new color panel and registers the binding against the /// selected color. /// - /// - Parameters: - /// - frame: The frame rectangle for the view, measured in points. - /// - color: The binding to read from for the selected color, and write to when the - /// selected color is changes. + /// - Parameter color: The binding to read from for the selected color, and write to when the + /// selected color changes. public convenience init(color: UIBinding) { self.init() bind(color: color) diff --git a/Sources/AppKitNavigation/Bindings/NSFontManager.swift b/Sources/AppKitNavigation/Bindings/NSFontManager.swift index d97250bae0..5b53b65a1b 100644 --- a/Sources/AppKitNavigation/Bindings/NSFontManager.swift +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -55,7 +55,6 @@ extension NSFontManager { /// - Parameters: /// - binding: A source of truth for the control's value. /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. /// - Returns: A cancel token. @discardableResult public func bind( @@ -72,7 +71,6 @@ extension NSFontManager { /// - Parameters: /// - binding: A source of truth for the control's value. /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. /// - set: A closure that is called when the binding's value changes with a weakly-captured /// control, a new value that can be used to configure the control, and a transaction, which /// can be used to determine how and if the change should be animated. diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift index 929c5744e3..1575ee768f 100755 --- a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -2,13 +2,17 @@ public import AppKit extension NSSegmentedControl { - /// Creates a new color well with the specified frame and registers the binding against the - /// selected color. + /// Creates a new segmented control with the specified frame and registers the binding against + /// the selected segment. /// /// - Parameters: /// - frame: The frame rectangle for the view, measured in points. - /// - selectedSegment: The binding to read from for the selected color, and write to when the - /// selected color is changes. + /// - selectedSegment: The binding to read from for the selected segment, and write to when the + /// selected segment changes. + /// - fileID: The source `#fileID` associated with the control. + /// - filePath: The source `#filePath` associated with the control. + /// - line: The source `#line` associated with the control. + /// - column: The source `#column` associated with the control. public convenience init( frame: CGRect = .zero, selectedSegment: UIBinding>, fileID: StaticString = #fileID, @@ -26,10 +30,16 @@ extension NSSegmentedControl { ) } - /// Establishes a two-way connection between a binding and the color well's selected color. + /// Establishes a two-way connection between a binding and the segmented control's selected + /// segment. /// - /// - Parameter selectedSegment: The binding to read from for the selected color, and write to - /// when the selected color changes. + /// - Parameters: + /// - selectedSegment: The binding to read from for the selected segment, and write to when the + /// selected segment changes. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. /// - Returns: A cancel token. @discardableResult public func bind( diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift index a03b7d09ff..1137407250 100755 --- a/Sources/AppKitNavigation/Bindings/NSTextField.swift +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -151,12 +151,12 @@ extension NSTextField { /// the `value`. Typically, you create an enumeration of fields that may receive focus, bind an /// instance of this enumeration, and assign its cases to focusable text fields. /// - /// The following example uses the cases of a `LoginForm` enumeration to bind the focus state of - /// two `UITextField` views. A sign-in button validates the fields and sets the bound - /// `focusedField` value to any field that requires the user to correct a problem. + /// The following example uses the cases of a `Field` enumeration to bind the focus state of two + /// text fields. A sign-in button validates the fields and sets the bound `focusedField` value to + /// any field that requires the user to correct a problem. /// /// ```swift - /// final class LoginViewController: UIViewController { + /// final class LoginViewController: NSViewController { /// enum Field { /// case usernameField /// case passwordField @@ -171,41 +171,37 @@ extension NSTextField { /// override func viewDidLoad() { /// super.viewDidLoad() /// - /// let usernameTextField = UITextField(text: $username) - /// usernameTextField.focus($focusedField, equals: .usernameField) + /// let usernameTextField = NSTextField(text: $username) + /// usernameTextField.bind(focus: $focusedField, equals: .usernameField) /// - /// let passwordTextField = UITextField(text: $password) - /// passwordTextField.focus($focusedField, equals: .passwordField) - /// passwordTextField.isSecureTextEntry = true + /// let passwordTextField = NSSecureTextField(text: $password) + /// passwordTextField.bind(focus: $focusedField, equals: .passwordField) /// - /// let signInButton = UIButton( - /// style: .system, - /// primaryAction: UIAction { [weak self] _ in - /// guard let self else { return } - /// if username.isEmpty { - /// focusedField = .usernameField - /// } else if password.isEmpty { - /// focusedField = .passwordField - /// } else { - /// handleLogin(username, password) - /// } + /// let signInButton = NSButton(title: "Sign In", target: nil, action: nil) + /// signInButton.addAction { [weak self] _ in + /// guard let self else { return } + /// if username.isEmpty { + /// focusedField = .usernameField + /// } else if password.isEmpty { + /// focusedField = .passwordField + /// } else { + /// handleLogin(username, password) /// } - /// ) - /// signInButton.setTitle("Sign In", for: .normal) + /// } /// /// // ... /// } /// } /// ``` /// - /// To control focus using a Boolean, use the ``UIKit/UITextField/bind(focus:)`` method instead. + /// To control focus using a Boolean, use the ``AppKit/NSTextField/bind(focus:)`` method instead. /// /// - Parameters: /// - focus: The state binding to register. When focus moves to the text field, the binding /// sets the bound value to the corresponding match value. If a caller sets the state value /// programmatically to the matching value, then focus moves to the text field. When focus /// leaves the text field, the binding sets the bound value to `nil`. If a caller sets the - /// value to `nil`, UIKit automatically dismisses focus. + /// value to `nil`, the text field loses focus. /// - value: The value to match against when determining whether the binding should change. /// - Returns: A cancel token. @discardableResult @@ -272,49 +268,46 @@ extension NSTextField { /// is `true`. You can use this method to observe the focus state of a text field, or /// programmatically set and remove focus from the text field. /// - /// In the following example, a single `UITextField` accepts a user's desired `username`. The - /// text field binds its focus state to the Boolean value `usernameFieldIsFocused`. A "Submit" + /// In the following example, a single text field accepts a user's desired `username`. The text + /// field binds its focus state to the Boolean value `usernameFieldIsFocused`. A "Submit" /// button's action verifies whether the name is available. If the name is unavailable, the /// button sets `usernameFieldIsFocused` to `true`, which causes focus to return to the text /// field, so the user can enter a different name. /// /// ```swift - /// final class LoginViewController: UIViewController { - /// @UIBindable private var username = "" - /// @UIBindable private var usernameFieldIsFocused = false + /// final class SignUpViewController: NSViewController { + /// @UIBinding private var username = "" + /// @UIBinding private var usernameFieldIsFocused = false /// /// // ... /// /// override func viewDidLoad() { /// super.viewDidLoad() /// - /// let textField = UITextField(text: $username) - /// textField.focus($usernameFieldIsFocused) + /// let textField = NSTextField(text: $username) + /// textField.bind(focus: $usernameFieldIsFocused) /// - /// let submitButton = UIButton( - /// style: .system, - /// primaryAction: UIAction { [weak self] _ in - /// guard let self else { return } - /// if !isUserNameAvailable(username: username) { - /// usernameFieldIsFocused = true - /// } + /// let submitButton = NSButton(title: "Submit", target: nil, action: nil) + /// submitButton.addAction { [weak self] _ in + /// guard let self else { return } + /// if !isUserNameAvailable(username: username) { + /// usernameFieldIsFocused = true /// } - /// ) - /// submitButton.setTitle("Sign In", for: .normal) + /// } /// /// // ... /// } /// } /// ``` /// - /// To control focus by matching a value, use the ``UIKit/UITextField/bind(focus:equals:)`` + /// To control focus by matching a value, use the ``AppKit/NSTextField/bind(focus:equals:)`` /// method instead. /// /// - Parameter condition: The focus state to bind. When focus moves to the text field, the - /// binding sets the bound value to `true`. If a caller sets the value to `true` + /// binding sets the bound value to `true`. If a caller sets the value to `true` /// programmatically, then focus moves to the text field. When focus leaves the text field, - /// the binding sets the value to `false`. If a caller sets the value to `false`, UIKit - /// automatically dismisses focus. + /// the binding sets the value to `false`. If a caller sets the value to `false`, the text + /// field loses focus. /// - Returns: A cancel token. @discardableResult public func bind(focus condition: UIBinding) -> ObserveToken { @@ -335,7 +328,7 @@ extension NSTextField { /// Represents a selection of text. /// -/// Like SwiftUI's `TextSelection`, but for UIKit. +/// Like SwiftUI's `TextSelection`, but for AppKit. public struct AppKitTextSelection: Hashable, Sendable { public var range: Range diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index 2a15d7931c..23eb512d01 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -15,7 +15,6 @@ extension TargetActionProtocol { /// - Parameters: /// - binding: A source of truth for the control's value. /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. /// - Returns: A cancel token. @discardableResult public func bind( @@ -42,7 +41,6 @@ extension TargetActionProtocol { /// - Parameters: /// - binding: A source of truth for the control's value. /// - keyPath: A key path to the control's value. - /// - event: The control-specific events for which the binding is updated. /// - set: A closure that is called when the binding's value changes with a weakly-captured /// control, a new value that can be used to configure the control, and a transaction, which /// can be used to determine how and if the change should be animated. diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 691e284b43..70da586bb3 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -2,6 +2,13 @@ Tools for making AppKit navigation simpler, more ergonomic and more precise. +## Overview + +AppKitNavigation drives AppKit from observable models. Controls bind to a model's state in both +directions: they show its value and write the user's changes back. Sheets, modal windows and +popovers follow optional state: they are presented when it gains a value, dismissed when it becomes +`nil`, and write `nil` back when the user dismisses them. + ## Additional Resources - [GitHub Repo](https://github.com/pointfreeco/swift-navigation) @@ -21,3 +28,32 @@ Tools for making AppKit navigation simpler, more ergonomic and more precise. - ``NSViewRepresenting`` - ``NSViewControllerRepresenting`` + +### Binding controls to state + +- ``TargetActionProtocol`` +- ``AppKit/NSControl`` +- ``AppKit/NSTextField`` +- ``AppKitTextSelection`` +- ``AppKit/NSSwitch`` +- ``AppKit/NSSlider`` +- ``AppKit/NSStepper`` +- ``AppKit/NSDatePicker`` +- ``AppKit/NSColorWell`` +- ``AppKit/NSPathControl`` +- ``AppKit/NSSegmentedControl`` +- ``AppKit/NSProgressIndicator`` +- ``AppKit/NSMenuItem`` +- ``AppKit/NSColorPanel`` +- ``AppKit/NSFontManager`` +- ``AppKit/NSSavePanel`` +- ``AppKit/NSOpenPanel`` + +### Presenting content from state + +- ``AppKit/NSViewController`` +- ``AppKit/NSWindow`` +- ``AppKit/NSView`` +- ``AppKit/NSToolbarItem`` +- ``ObjectiveC/NSObject`` +- ``AppKit/NSAlert`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIColorWell.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIColorWell.md deleted file mode 100644 index 33ca0c8aa8..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIColorWell.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKit/UIColorWell`` - -## Topics - -### Binding to observable state - -- ``UIKit/UIColorWell/init(frame:selectedColor:)`` -- ``UIKit/UIColorWell/bind(selectedColor:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIControlProtocol.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIControlProtocol.md deleted file mode 100644 index 669a617e88..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIControlProtocol.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKitNavigation/UIControlProtocol`` - -## Topics - -### Binding to observable state - -- ``bind(_:to:for:)`` -- ``bind(_:to:for:set:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIDatePicker.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIDatePicker.md deleted file mode 100644 index dceb86bc9b..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIDatePicker.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKit/UIDatePicker`` - -## Topics - -### Binding to observable state - -- ``UIKit/UIDatePicker/init(frame:date:)`` -- ``UIKit/UIDatePicker/bind(date:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIKitAnimation.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIKitAnimation.md deleted file mode 100644 index fee55a5dbf..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIKitAnimation.md +++ /dev/null @@ -1,35 +0,0 @@ -# ``UIKitNavigation/UIKitAnimation`` - -## Topics - -### Getting the default animation - -- ``default`` - -### Getting linear animations - -- ``linear`` -- ``linear(duration:)`` - -### Getting eased animations - -- ``easeIn`` -- ``easeIn(duration:)`` -- ``easeOut`` -- ``easeOut(duration:)`` -- ``easeInOut`` -- ``easeInOut(duration:)`` - -### Creating custom animations - -- ``animate(withDuration:delay:options:)`` -- ``animate(withDuration:delay:usingSpringWithDamping:initialSpringVelocity:options:)`` -- ``animate(springDuration:bounce:initialSpringVelocity:delay:options:)`` -- ``init(_:)`` - -### Configuring an animation - -- ``delay(_:)`` -- ``repeatCount(_:autoreverses:)`` -- ``repeatForever(autoreverses:)`` -- ``speed(_:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIPageControl.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIPageControl.md deleted file mode 100644 index 94fd9d8cf6..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIPageControl.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKit/UIPageControl`` - -## Topics - -### Binding to observable state - -- ``UIKit/UIPageControl/init(frame:currentPage:)`` -- ``UIKit/UIPageControl/bind(currentPage:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UISlider.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UISlider.md deleted file mode 100644 index 833cfa9d96..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UISlider.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKit/UISlider`` - -## Topics - -### Binding to observable state - -- ``UIKit/UISlider/init(frame:value:)`` -- ``UIKit/UISlider/bind(value:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIStepper.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIStepper.md deleted file mode 100644 index b716f43afc..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIStepper.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKit/UIStepper`` - -## Topics - -### Binding to observable state - -- ``UIKit/UIStepper/init(frame:value:)`` -- ``UIKit/UIStepper/bind(value:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UISwitch.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UISwitch.md deleted file mode 100644 index 630ef43f03..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UISwitch.md +++ /dev/null @@ -1,8 +0,0 @@ -# ``UIKit/UISwitch`` - -## Topics - -### Binding to observable state - -- ``UIKit/UISwitch/init(frame:isOn:)`` -- ``UIKit/UISwitch/bind(isOn:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UITextField.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UITextField.md deleted file mode 100644 index 64484959fa..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UITextField.md +++ /dev/null @@ -1,22 +0,0 @@ -# ``UIKit/UITextField`` - -## Topics - -### Binding to observable text - -- ``UIKit/UITextField/init(frame:text:)`` -- ``UIKit/UITextField/bind(text:)`` - -### Binding to attributed text - -- ``UIKit/UITextField/init(frame:attributedText:)`` -- ``UIKit/UITextField/bind(attributedText:)`` - -### Binding to focus state - -- ``UIKit/UITextField/bind(focus:)`` -- ``UIKit/UITextField/bind(focus:equals:)`` - -### Binding to text selection - -- ``UIKit/UITextField/bind(selection:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIViewController.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/UIViewController.md deleted file mode 100644 index 23737ce72d..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/UIViewController.md +++ /dev/null @@ -1,26 +0,0 @@ -# ``UIKit/UIViewController`` - -## Topics - -### Tree-based navigation - -- ``UIKit/UIViewController/present(isPresented:onDismiss:content:)`` -- ``UIKit/UIViewController/present(item:onDismiss:content:)-34iup`` -- ``UIKit/UIViewController/present(item:onDismiss:content:)-86u3v`` -- ``UIKit/UIViewController/present(item:id:onDismiss:content:)-8grlt`` -- ``UIKit/UIViewController/present(item:id:onDismiss:content:)-2fmzj`` -- ``UIKit/UIViewController/navigationDestination(isPresented:content:)`` -- ``UIKit/UIViewController/navigationDestination(item:content:)-367r6`` -- ``UIKit/UIViewController/navigationDestination(item:content:)-4pmzx`` - -### Custom tree-based navigation - -- ``UIKit/UIViewController/destination(isPresented:content:present:dismiss:)`` -- ``UIKit/UIViewController/destination(item:content:present:dismiss:)`` -- ``UIKit/UIViewController/destination(item:id:content:present:dismiss:)`` - -### Stack-based navigation - -- ``NavigationStackController`` -- ``UIKit/UIViewController/navigationDestination(for:destination:)`` -- ``UIKit/UIViewController/push(value:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Extensions/observe.md b/Sources/AppKitNavigation/Documentation.docc/Extensions/observe.md deleted file mode 100644 index c5b82f2319..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/Extensions/observe.md +++ /dev/null @@ -1,7 +0,0 @@ -# ``UIKitNavigation/ObjectiveC/NSObject/observe(_:)-1trvu`` - -## Topics - -### Observing with a transaction - -- ``UIKitNavigation/ObjectiveC/NSObject/observe(_:)-1r7fl`` diff --git a/Sources/AppKitNavigation/Documentation.docc/UIKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/UIKitNavigation.md deleted file mode 100644 index b54525f892..0000000000 --- a/Sources/AppKitNavigation/Documentation.docc/UIKitNavigation.md +++ /dev/null @@ -1,165 +0,0 @@ -# ``UIKitNavigation`` - -Tools for making SwiftUI navigation simpler, more ergonomic and more precise. - -## Additional Resources - -- [GitHub Repo](https://github.com/pointfreeco/swift-navigation) -- [Discussions](https://github.com/pointfreeco/swift-navigation/discussions) -- [Point-Free Videos](https://www.pointfree.co/collections/ukit) - -## Overview - -UIKit provides a few simple tools for navigation, but none of them are state-driven. Its navigation -tools are what is known as "fire-and-forget", which means you simply invoke a method to trigger -a navigation, but there is no representation of that event in your feature's state. - - -For example, to present a sheet from a button press one can simply do: - -```swift -let button = UIButton(type: .system, primaryAction: UIAction { [weak self] _ in - present(SettingsViewController(), animated: true) -}) -``` - -This makes it easy to get started with navigation, but there are a few problems with this: - -* It is difficult to determine from your feature's logic what child features are currently -presented. You can check the `presentedViewController` property on `UIViewController` directly, -but then that logic must exist in the view (and so hard to test), and you have to do extra work -to inspect the type-erased controller to truly see what is being presented. -* It is difficult to perform deep-linking to any feature of your app. You must duplicate the -logic that invokes `present` or `pushViewController` in another part of your app in order to -deep-link into child features. - -SwiftUI has taught us, it is incredibly powerful to be able to drive navigation from state. It -allows you to encapsulate more of your feature's logic in an isolated and testable domain, and it -unlocks deep linking for free since one just needs to construct a piece of state that represents -where you want to navigate to, hand it to SwiftUI, and let SwiftUI do the rest. - -The UIKitNavigation library brings a powerful suite of navigation tools to UIKit that are heavily -inspired by SwiftUI. For example, if you have a feature that can navigate to 3 different screens, -you can model that as an enum with 3 cases and some optional state: - -```swift -@Observable -class FeatureModel { - var destination: Destination? - - enum Destination { - case addItem(AddItemModel) - case deleteItemAlert - case editItem(EditItemModel) - } -} -``` - -This allows us to prove that at most one of these destinations can be active at a time. And it -would be great if we could present and dismiss these child features based on the value of -`destination`. - -This is possible, but first we have to make one small change to the `Destination` enum by annotating -it with the `@CasePathable` macro: - -```diff -+@CasePathable - enum Destination { - // ... - } -``` - -This allows us to derive key paths and properties for each case of an enum, which is not currently -possible in native Swift. - -With that done one can drive navigation in a _view controller_ using tools in the library: - -```swift -class FeatureViewController: UIViewController { - @UIBindable var model: FeatureModel - - func viewDidLoad() { - super.viewDidLoad() - - // Set up view hierarchy - - present(item: $model.destination.addItem) { addItemModel in - AddItemViewController(model: addItemModel) - } - present(isPresented: Binding($model.destination.deleteItemAlert)) { - let alert = UIAlertController(title: "Delete?", message: message, preferredStyle: .alert) - alert.addAction(UIAlertAction(title: "Yes", style: .destructive)) - alert.addAction(UIAlertAction(title: "No", style: .cancel)) - return alert - } - navigationDestination(item: $model.destination.editItem) { editItemModel in - EditItemViewController(model: editItemModel) - } - } -} -``` - -By using the libraries navigation tools we can be guaranteed that the model will be kept in sync -with the view. When the state becomes non-`nil` the corresponding form of navigation will be -triggered, and when the presented view is dismissed, the state will be `nil`'d out. - -Another powerful aspect of SwiftUI is its ability to update its UI whenever state in an observable -model changes. And thanks to Swift's observation tools this can be done done implicitly and -minimally: whichever fields are accessed in the `body` of the view are automatically tracked -so that when they change the view updates. - -Our UIKitNavigation library comes with a tool that brings this power to UIKit, and it's called -``observe(isolation:_:)-93yzu``: - -```swift -observe { [weak self] in - guard let self else { return } - - countLabel.text = "Count: \(model.count)" - factLabel.isHidden = model.fact == nil - if let fact = model.fact { - factLabel.text = fact - } - activityIndicator.isHidden = !model.isLoadingFact -} -``` - -Whichever fields are accessed inside `observe` (such as `count`, `fact` and `isLoadingFact` above) -are automatically tracked, so that whenever they are mutated the trailing closure of `observe` -will be invoked again, allowing us to update the UI with the freshest data. - -All of these tools are built on top of Swift's powerful Observation framework. However, that -framework only works on newer versions of Apple's platforms: iOS 17+, macOS 14+, tvOS 17+ and -watchOS 10+. However, thanks to our back-port of Swift's observation tools (see -[Perception](http://github.com/pointfreeco/swift-perception)), you can make use of our tools -right away, going all the way back to the iOS 13 era of platforms. - - -## Topics - -### Observing changes to state - -- ``ObjectiveC/NSObject/observe(_:)-1trvu`` - -### Animations - -- ``withUIKitAnimation(_:_:completion:)`` -- ``UIKitAnimation`` - -### Controls - -- ``UIControlProtocol`` -- ``UIKit/UIColorWell`` -- ``UIKit/UIDatePicker`` -- ``UIKit/UIPageControl`` -- ``UIKit/UISegmentedControl`` -- ``UIKit/UISlider`` -- ``UIKit/UIStepper`` -- ``UIKit/UISwitch`` -- ``UIKit/UITextField`` - -### Navigation - -- ``UIKit/UIViewController`` -- ``UIKit/UIAlertController`` -- ``UIKit/UITraitCollection`` From 75c6b541c209d9a70c4e42d6af7055d8e6ea5373 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 21:17:11 +0800 Subject: [PATCH 066/141] docs: record that the AppKitNavigation cleanup is implemented --- Documentations/Evolutions/draft-appkit-navigation-cleanup.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 119757285d..0d430abe81 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -50,3 +50,5 @@ | 2026-11-04 | `AppKitAnimation.swift` 里的一条 `Sendable` 警告不改,记进 [ReviewDecisions.md](../Internal/ReviewDecisions.md) | 起草时的 14 条是增量构建统计的,漏了这个没重新编译的文件;用全新的构建目录重编一遍才看到它。它是与上游共用的代码,按上面的假设不碰 | | 2026-11-04 | 第 5 步加一条命名测试,扫描本库加在系统类上的方法 | 只改两个名字,管不住以后再加的成员;测试先红(正好报出这两个成员的四个方法),改名后变绿 | | 2026-11-04 | 命名测试放在主线程上跑 | 第一版没标 `@MainActor`:在后台线程写出 `NSView.self` 会在那条线程上执行 `+initialize`,让 AppKit 认错了线程。并行跑的其他测试随后在主线程处理事件时陷入断言陷阱,或者在打开面板时抛出 `already on an AppKit thread`,10 次里崩了 4 次;放到主线程后连跑 20 次没有再崩 | +| 2026-11-04 | 文档一步顺带修了 fork 自己的文档注释 | 生成文档时这些注释贡献了大部分 DocC 警告,而且文本框焦点绑定的示例是 UIKit 代码,照着写编不过 | +| 2026-11-04 | 实现完成,待用户看过后收尾 | 七步都已提交。Xcode 27.2 上 AppKit 测试全过(XCTest 16 条、Swift Testing 31 条),整个包只剩基线上本来就失败的 `ButtonStateTests.testAsyncAnimationWarning`;Xcode 26.6 编得过 AppKit 的库和测试;全新构建目录下 AppKit 只剩上游那一条警告。文档判断:README 不用改(用法没变);不需要使用指南或实现说明(没有新的调用契约);没有新术语;`swift-navigation-bindings` skill 不用改(公开用法没变) | From 03f45a54b7747e8f7d9f1f90624b43b9b55d68ff Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 21:39:45 +0800 Subject: [PATCH 067/141] fix(appkit): stop the color panel binding from crashing on its first call Binding a color panel takes its target-action pair over, which reads the panel's current action first so the binding can keep forwarding it. The SDK declares no getter for that action, and the conformance read it through key-value coding, which cannot return a selector: every call to 'NSColorPanel.bind(color:)' or 'NSColorPanel(color:)' raised NSUnknownKeyException. It has done so since the color panel binding was added. AppKit implements the getter all the same, in every release checked from macOS 12 through 27, so the conformance now calls it directly, and reports no action instead of crashing should a release lack it. Two tests cover it: the panel reports the action it was given, and a color panel binding stays in step with the panel. Both crashed before the fix. --- .../draft-appkit-navigation-cleanup.md | 9 ++- .../Bindings/NSColorPanel.swift | 12 +++- .../ColorPanelBindingTests.swift | 64 +++++++++++++++++++ 3 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ColorPanelBindingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 0d430abe81..541a16f351 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -7,7 +7,7 @@ ## 摘要 -不改用法,把 AppKitNavigation 收拾干净:清掉 fork 自己代码里的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。 +不改用法,把 AppKitNavigation 收拾干净:清掉 fork 自己代码里的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。实现中发现 `NSColorPanel.bind(color:)` 一调用就崩溃,用户决定在这一批一起修掉。 ## 方案 @@ -23,6 +23,7 @@ 5. **加库前缀**(已完成):`NSSwitch.boolValue`、`NSFontManager._selectedFont` 改成带 `appKitNavigation` 前缀的名字(`appKitNavigationIsOn`、`appKitNavigationSelectedFont`)。macOS 27.2 的 AppKit 里还没有同名方法,可一旦重名,Swift 扩展会悄悄替换掉系统实现——上一批修的 `textViewDidChangeSelection:` 就是这样坏的。两者都不是公开成员。另加一条测试守住这一类:扫描本库加在系统类上的 Objective-C 方法,名字里都要带库名,shim 有意替换的五个方法除外。 6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**(已完成):它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 7. **文档**(已完成):删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加一段概述和「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。实际还顺带修了 fork 自己的文档注释:文本框焦点绑定的示例和说明是从 UIKit 抄的,改成 AppKit 的写法;删掉不存在的参数说明,补上分段控件缺的参数说明。AppKitNavigation 的 DocC 警告从 23 条降到 3 条,剩下的都来自与上游共用的内容。 +8. **修颜色面板绑定的崩溃**(已完成,实现中加入):`NSColorPanel` 遵循 `TargetActionProtocol` 时,`action` 的 getter 经 KVC 读面板的 action,而 KVC 返回不了 selector,抛出 `NSUnknownKeyException`;绑定在接管面板的 target/action 前要先读它,所以每次调用 `bind(color:)` 都崩溃。改为直接调用 AppKit 未公开但一直实现着的 `-action`,并用 `responds(to:)` 兜底。先补两条测试(面板能报出设置给它的 action;颜色面板的双向绑定),修之前崩溃,修之后通过。 没有询问就采用的假设: @@ -35,7 +36,7 @@ ## 后续项 -- `NSColorPanel.bind(color:)` 一调用就崩溃:它经 KVC 读面板的 `action`,而 KVC 返回不了 `SEL`,抛出 `NSUnknownKeyException`。原本就有,由第 1 步的测试发现,不在这一批修。 +- AppKit 的 Swift Testing 测试偶尔会中途结束,退出码却是 0,没跑完的测试结果就此丢失;`main` 上同样存在。用 lldb 查到:分段控件的 `performClick`、保存和打开面板的创建(`-[NSSavePanel _initBridgeAndStuff]` 等待远程面板的信号量)都会跑嵌套 run loop,偶尔把一个 `CFRunLoopStop` 漏给外层;而测试进程的主执行器在主 run loop 一返回就 `exit(0)`。去掉分段控件的点击用例不能根治,来源不止一处。修法要改测试基础设施,例如把这类测试移到 XCTest,或在主 run loop 退出时接着运行,留给另一批。 - `NSPathControl` 的便捷构造器把 URL 绑定的参数标签写成了 `date:`,应为 `url:`;改它要动公开 API,不在这一批。 ## 决策日志 @@ -52,3 +53,7 @@ | 2026-11-04 | 命名测试放在主线程上跑 | 第一版没标 `@MainActor`:在后台线程写出 `NSView.self` 会在那条线程上执行 `+initialize`,让 AppKit 认错了线程。并行跑的其他测试随后在主线程处理事件时陷入断言陷阱,或者在打开面板时抛出 `already on an AppKit thread`,10 次里崩了 4 次;放到主线程后连跑 20 次没有再崩 | | 2026-11-04 | 文档一步顺带修了 fork 自己的文档注释 | 生成文档时这些注释贡献了大部分 DocC 警告,而且文本框焦点绑定的示例是 UIKit 代码,照着写编不过 | | 2026-11-04 | 实现完成,待用户看过后收尾 | 七步都已提交。Xcode 27.2 上 AppKit 测试全过(XCTest 16 条、Swift Testing 31 条),整个包只剩基线上本来就失败的 `ButtonStateTests.testAsyncAnimationWarning`;Xcode 26.6 编得过 AppKit 的库和测试;全新构建目录下 AppKit 只剩上游那一条警告。文档判断:README 不用改(用法没变);不需要使用指南或实现说明(没有新的调用契约);没有新术语;`swift-navigation-bindings` skill 不用改(公开用法没变) | +| 2026-11-04 | 颜色面板绑定的崩溃在这条分支上一起修(第 8 步) | 用户看过汇报后决定收尾前一起修,不另开一批 | +| 2026-11-04 | 修法:直接调用 AppKit 未公开的 `-action`,用 `responds(to:)` 兜底 | 让 getter 直接返回 `nil` 也不会崩,但绑定接管面板的 target/action 之后,就转发不了用户原先设的 action;改成监听颜色变化的通知、不再接管,又得改公开的 `TargetActionProtocol` 遵循。本机导出的 AppKit 头文件里,macOS 12.0.1、26.4–26.6、27.0、27.2 都有这个 getter。出问题的写法是 2024-10-11 加入颜色面板绑定时写下的,之后没改过,也没人修过;本机依赖这个 fork 的项目都没用到这个绑定 | +| 2026-11-04 | 测试进程中途以 0 退出的问题查明原因,不在这批修(见后续项) | 加入颜色面板测试后截断变得频繁,于是追查:问题出在 AppKit 嵌套 run loop 与测试进程主执行器的交互上,`main` 上本来就有;试着去掉分段控件的点击用例,并不能根治,已恢复原样。根治要改测试基础设施,超出这一批的范围 | +| 2026-11-04 | 第 8 步完成,重新验证 | Xcode 27.2 上 AppKit 测试完整跑通(Swift Testing 33 条、XCTest 16 条,有汇总行为证);Xcode 26.6 编得过 AppKit 的库和测试,只剩上游那一条警告 | diff --git a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift index a006a52ea9..97ba500fa4 100755 --- a/Sources/AppKitNavigation/Bindings/NSColorPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -11,7 +11,17 @@ extension NSColorPanel: TargetActionProtocol { public var action: Selector? { set { setAction(newValue) } - get { value(forKeyPath: "action") as? Selector } + get { + // NB: The SDK declares no getter for the panel's action, and key-value coding cannot + // return a selector: asking it for "action" raises an exception. AppKit implements + // the getter all the same (every release checked, macOS 12 through 27, has it), so + // it is called directly, and a panel without one reports no action rather than + // crashing. The target is an object, which key-value coding returns just fine. + let getter = NSSelectorFromString("action") + guard responds(to: getter) else { return nil } + typealias ActionGetter = @convention(c) (NSColorPanel, Selector) -> Selector? + return unsafeBitCast(method(for: getter), to: ActionGetter.self)(self, getter) + } } } diff --git a/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift b/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift new file mode 100644 index 0000000000..b9ea401fb6 --- /dev/null +++ b/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift @@ -0,0 +1,64 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// The color panel is one per application, so these tests share it and must not overlap. + @MainActor + @Suite(.serialized) struct ColorPanelBindingTests { + init() { + // NB: The panel sends its action through 'NSApplication.sendAction(_:to:from:)', which + // silently does nothing when no application object exists yet. + _ = NSApplication.shared + } + + /// The binding takes the panel's target-action pair over and has to keep forwarding the + /// original one, so it reads the panel's action first. The panel has no public getter for it, + /// and reading it through key-value coding raised an exception, since KVC cannot return a + /// selector: every call to `bind(color:)` crashed. + @Test("the color panel reports the action it was given") + func colorPanelReportsTheActionItWasGiven() { + let colorPanel = NSColorPanel.shared + let previousAction = colorPanel.action + defer { colorPanel.action = previousAction } + + colorPanel.action = #selector(ColorRecipient.takeColor(_:)) + + #expect(colorPanel.action == #selector(ColorRecipient.takeColor(_:))) + } + + @Test("the color panel stays in step with its binding") + func colorPanelStaysInStep() async throws { + @UIBinding var swatch = Swatch(color: Self.red) + let colorPanel = NSColorPanel.shared + colorPanel.bind(color: $swatch.color) + defer { colorPanel.unbind(\.color) } + #expect(colorPanel.color == Self.red) + + swatch.color = Self.blue + await Task.yield() + #expect(colorPanel.color == Self.blue) + + // NB: What the panel does when the user picks a color. + colorPanel.color = Self.green + NSApplication.shared.sendAction( + try #require(colorPanel.action), to: colorPanel.target, from: colorPanel + ) + #expect(swatch.color == Self.green) + } + + private final class ColorRecipient: NSObject { + @objc func takeColor(_ sender: Any?) {} + } + + /// Holds the color in a value, the way a model would, rather than binding a class instance + /// directly. + private struct Swatch { + var color: NSColor + } + + private static let red = NSColor(srgbRed: 1, green: 0, blue: 0, alpha: 1) + private static let green = NSColor(srgbRed: 0, green: 1, blue: 0, alpha: 1) + private static let blue = NSColor(srgbRed: 0, green: 0, blue: 1, alpha: 1) + } +#endif From e58c16564cb57c7026d656ae2844cf8ad3cc3b32 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 22:09:36 +0800 Subject: [PATCH 068/141] fix: clear the remaining Swift 6.4 warnings in SwiftNavigation and AppKitNavigation - AppKitAnimation.perform(_:completion:) now takes a @Sendable completion, since NSAnimationContext's completion handler is @Sendable and captured it. Its one caller only captures Sendable values. That caller now builds the completion with an 'if' instead of a ternary: Swift 6.4 fails to type-check a ternary whose branch is a closure of optional @Sendable function type ("failed to produce diagnostic for expression"). - The two observe(_:) overloads suppress ConversionFromIsolatedAnyToSynchronous with SE-0522's @diagnose. Observation tracking needs the closure to run synchronously, which drops its @isolated(any); later runs still hop to its isolation. Keeping @isolated(any) in the signature preserves 'observe { @MainActor in ... }' isolation overrides. Compilers without the attribute (Swift 6.2) still warn, which the review decisions record. Both files are shared with upstream, so later upstream merges may conflict here. --- Documentations/Internal/ReviewDecisions.md | 10 ++++---- .../AppKitNavigation/AppKitAnimation.swift | 2 +- Sources/AppKitNavigation/UITransaction.swift | 23 +++++++++++-------- Sources/SwiftNavigation/Observe.swift | 19 +++++++++++++++ 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index 028b000b2b..54c1887613 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -44,13 +44,13 @@ - **理由**:AppKit 那份已按 UTF-16 换算修好。UIKit 那份是上游拥有的代码,fork 保持与上游一致,在 fork 里改会让以后的合并持续冲突。 - **复查条件**:上游自己修了,或者 fork 的 UIKit 用户撞上这个问题时。 -### `AppKitAnimation.swift` 的一条 `Sendable` 捕获警告 +## 系统限制 -- **裁决**:上游的代码,fork 不修。(2026-11-04) -- **理由**:`AppKitAnimation.perform(_:completion:)` 把不是 `Sendable` 的 `completion` 捕获进 `NSAnimationContext` 的 `@Sendable` 完成回调,编译器因此报警告。这个文件属于上游的 AppKitNavigation,fork 与上游只差一行注释;在 fork 里改,以后合并上游时就多一处冲突。 -- **复查条件**:上游修了它时。 +### Xcode 26.6 上 `observe(_:)` 的两条 `@isolated(any)` 转换警告 -## 系统限制 +- **裁决**:旧编译器的限制,不修。(2026-11-04) +- **理由**:`observe(_:)` 必须同步执行传入的 `@isolated(any)` 闭包,编译器为此报「converting @isolated(any) function … to synchronous function type」。Swift 6.4 上用 `@diagnose(ConversionFromIsolatedAnyToSynchronous, as: ignored)` 屏蔽了;Swift 6.2(Xcode 26.6)不认识这个属性,只能去掉签名里的 `@isolated(any)`,而那会让 `observe { @MainActor in … }` 这类显式指定隔离的写法退化。 +- **复查条件**:不再支持 Xcode 26.6 时,这一条直接删掉。 ### 字体绑定只在响应链上有对象实现 `changeFont(_:)` 时生效 diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 5b3c0f2fc4..b5655aaeb7 100644 --- a/Sources/AppKitNavigation/AppKitAnimation.swift +++ b/Sources/AppKitNavigation/AppKitAnimation.swift @@ -36,7 +36,7 @@ @MainActor func perform( _ body: () throws -> Result, - completion: (/*@Sendable*/ (Bool?) -> Void)? = nil + completion: (@Sendable (Bool?) -> Void)? = nil ) rethrows -> Result { switch framework { case .appKit(let animation): diff --git a/Sources/AppKitNavigation/UITransaction.swift b/Sources/AppKitNavigation/UITransaction.swift index e8c8813ba1..fbd6a2c096 100644 --- a/Sources/AppKitNavigation/UITransaction.swift +++ b/Sources/AppKitNavigation/UITransaction.swift @@ -34,16 +34,21 @@ completion(true) } } else if let animation = value.animation { - return animation.perform( - { operation() }, - completion: value.animationCompletions.isEmpty - ? nil - : { - for completion in value.animationCompletions { - completion($0) - } + // NB: Spelled out with 'if' rather than a ternary: Swift 6.4 fails to type-check a + // ternary whose branch is a closure of optional '@Sendable' function type ("failed + // to produce diagnostic for expression"). + let completions = value.animationCompletions + let completion: (@Sendable (Bool?) -> Void)? + if completions.isEmpty { + completion = nil + } else { + completion = { isFinished in + for completion in completions { + completion(isFinished) } - ) + } + } + return animation.perform({ operation() }, completion: completion) } else { operation() for completion in value.animationCompletions { diff --git a/Sources/SwiftNavigation/Observe.swift b/Sources/SwiftNavigation/Observe.swift index 49e99b54cd..c1dba09c81 100644 --- a/Sources/SwiftNavigation/Observe.swift +++ b/Sources/SwiftNavigation/Observe.swift @@ -62,6 +62,18 @@ #if !Perception @available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) #endif + // NB: Observation tracking needs 'apply' to run synchronously, which takes converting it to a + // synchronous function type and so drops its '@isolated(any)'. That is deliberate: every + // later run hops to 'apply.isolation', and the first one runs right here, in the caller's + // context, which '@_inheritActorContext' makes the closure's own. The one case it does not + // cover is a closure that names a different isolation, such as 'observe { @MainActor in }' + // from another actor: its first run still happens in the caller's context. + #if hasAttribute(diagnose) + @diagnose( + ConversionFromIsolatedAnyToSynchronous, as: ignored, + reason: "The first run must be synchronous for tracking; later runs hop to its isolation." + ) + #endif public func observe( @_inheritActorContext _ apply: @escaping @isolated(any) @Sendable () -> Void @@ -84,6 +96,13 @@ #if !Perception @available(iOS 17, macOS 14, tvOS 17, watchOS 10, *) #endif + // NB: See the overload above. + #if hasAttribute(diagnose) + @diagnose( + ConversionFromIsolatedAnyToSynchronous, as: ignored, + reason: "The first run must be synchronous for tracking; later runs hop to its isolation." + ) + #endif public func observe( @_inheritActorContext _ apply: @escaping @isolated(any) @Sendable (_ transaction: UITransaction) -> Void From b17f3cd3da8765d63fd55953d1e6c3b5644457a7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 22:09:36 +0800 Subject: [PATCH 069/141] fix(examples): import IssueReporting now that XCTestDynamicOverlay is gone Since the package moved to swift-issue-reporting 2.0, nothing in the example apps' dependency graph provides the XCTestDynamicOverlay module, so CaseStudies failed with "Unable to resolve module dependency: 'XCTestDynamicOverlay'". The three files that imported it now import IssueReporting and call reportIssue in place of XCTFail. The workspace's package lockfile is resolved afresh. The old one pinned a swift-case-paths branch and kept the old xctest-dynamic-overlay URL, whose products clash with swift-issue-reporting's, so a clean resolution from the command line failed outright. The new pins match what Xcode resolves. --- .../ConnectToNetworkModel.swift | 8 +-- .../NetworkDetailModel.swift | 4 +- Examples/Inventory/ItemRow.swift | 2 +- .../xcshareddata/swiftpm/Package.resolved | 55 ++++++++----------- 4 files changed, 30 insertions(+), 39 deletions(-) diff --git a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift index 305710387b..954cbc2e29 100644 --- a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift @@ -1,16 +1,16 @@ import Foundation -import XCTestDynamicOverlay +import IssueReporting @Observable @MainActor class ConnectToNetworkModel: Identifiable { var incorrectPasswordAlertIsPresented = false var isConnecting = false - var onCancel: () -> Void = { - XCTFail("ConnectToNetworkModel.onCancel unimplemented.") + var onCancel: () -> Void = { + reportIssue("ConnectToNetworkModel.onCancel unimplemented.") } var onConnect: (Network) -> Void = { _ in - XCTFail("ConnectToNetworkModel.onConnect unimplemented.") + reportIssue("ConnectToNetworkModel.onConnect unimplemented.") } let network: Network diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift index db0101b467..a37d722187 100644 --- a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift @@ -1,12 +1,12 @@ import Foundation -import XCTestDynamicOverlay +import IssueReporting @MainActor @Observable class NetworkDetailModel: Identifiable { var forgetAlertIsPresented = false var onConfirmForget: () -> Void = { - XCTFail("NetworkDetailModel.onConfirmForget unimplemented.") + reportIssue("NetworkDetailModel.onConfirmForget unimplemented.") } let network: Network diff --git a/Examples/Inventory/ItemRow.swift b/Examples/Inventory/ItemRow.swift index dba4e45e14..9265a87af9 100644 --- a/Examples/Inventory/ItemRow.swift +++ b/Examples/Inventory/ItemRow.swift @@ -1,6 +1,6 @@ +import IssueReporting import SwiftUI import SwiftUINavigation -import XCTestDynamicOverlay @Observable class ItemRowModel: Identifiable { diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index e8e2a2bd30..528aa53ec5 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,13 +1,13 @@ { - "originHash" : "556faf476a22c66a001c9e0e2869bdf97eab5490bd68796c4d4263a81098fdc2", + "originHash" : "44d2db2fa3620bdeb8f6f8122273f67ead312b3392d40f1c94c6ce6189f6538e", "pins" : [ { "identity" : "combine-schedulers", "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/combine-schedulers", "state" : { - "revision" : "dcccb979a2183b8df3334237e3dc1ae2b4116a86", - "version" : "1.2.0" + "revision" : "114354e8c1667a2edc4993700fb9fa4f90157b56", + "version" : "1.2.2" } }, { @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-case-paths", "state" : { - "branch" : "macro-spec", - "revision" : "cdfbedad1014028667110642217fc731495be0ad" + "revision" : "cb4cba6a8a46a86db0d37dbe09935ead6b24c91a", + "version" : "1.10.0" } }, { @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-clocks", "state" : { - "revision" : "72d749bf341b78851203066ab421869b783ec42a", - "version" : "1.1.0" + "revision" : "82440fa0a8b1c381a6d1e8e0fc7bbba53ec63204", + "version" : "1.1.1" } }, { @@ -33,8 +33,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-collections", "state" : { - "revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a", - "version" : "1.6.0" + "revision" : "f96b909e1a9e469620bc5037c1e24e00153f376f", + "version" : "1.7.5" } }, { @@ -42,8 +42,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-concurrency-extras.git", "state" : { - "revision" : "a90e2e40a7a840a853dd29e57cbef5dbb72c9d5b", - "version" : "1.4.0" + "revision" : "8a4260f7373493435bd21194585c95b72bfdd401", + "version" : "1.4.3" } }, { @@ -51,8 +51,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-custom-dump", "state" : { - "revision" : "a8cd6c976f335ed361dcecddb0dc39ebda51bc3e", - "version" : "1.6.1" + "revision" : "4fb9e7cbb4b8f5a7354005db39447f570d6b3e19", + "version" : "1.7.3" } }, { @@ -60,8 +60,8 @@ "kind" : "remoteSourceControl", "location" : "http://github.com/pointfreeco/swift-dependencies", "state" : { - "revision" : "8dc1fbf2f6255a73dec53b4648164884898db4c5", - "version" : "1.14.1" + "revision" : "2f83b70a6fbf45795dd40ccaa907bad3c8d93fe1", + "version" : "1.17.2" } }, { @@ -96,8 +96,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-issue-reporting", "state" : { - "revision" : "71c7c9a761d1ca6ed4ccb6ced040fe1c1a39e8e7", - "version" : "2.1.0" + "revision" : "b23bb4493c439d3e05152bc167014235ba3d47fc", + "version" : "2.1.2" } }, { @@ -114,8 +114,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-perception", "state" : { - "revision" : "25ac73741c3436605d61eceb5207e896973918e7", - "version" : "2.0.10" + "revision" : "597afd46249f4a71885b95d26b26cc5b893daf32", + "version" : "2.0.12" } }, { @@ -123,8 +123,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/pointfreeco/swift-snapshot-testing", "state" : { - "revision" : "ad5e3190cc63dc288f28546f9c6827efc1e9d495", - "version" : "1.19.2" + "revision" : "1488390b0735e726564b948bf08b384398bdab5c", + "version" : "1.19.7" } }, { @@ -132,8 +132,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/swiftlang/swift-syntax", "state" : { - "revision" : "79e4b74a295b6eb74a8b585e3a39d29e70c1dbd1", - "version" : "603.0.2" + "revision" : "050f1a346fbbac0ca2cfb15a95274f7bd1cf0ccf", + "version" : "604.0.0" } }, { @@ -144,15 +144,6 @@ "revision" : "3907a9438f5b57d317001dc99f3f11b46882272b", "version" : "0.10.0" } - }, - { - "identity" : "xctest-dynamic-overlay", - "kind" : "remoteSourceControl", - "location" : "https://github.com/pointfreeco/xctest-dynamic-overlay", - "state" : { - "revision" : "401bf70d95bfe8db2a1dc619f9e175a85c089321", - "version" : "1.10.1" - } } ], "version" : 3 From 974c878cc768e7b3d6dd75baf7bed1407bb3a68f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 22:09:36 +0800 Subject: [PATCH 070/141] docs: record the warning and example fixes requested after review --- .../Evolutions/draft-appkit-navigation-cleanup.md | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md index 541a16f351..5d7800ac5e 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/draft-appkit-navigation-cleanup.md @@ -7,7 +7,7 @@ ## 摘要 -不改用法,把 AppKitNavigation 收拾干净:清掉 fork 自己代码里的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。实现中发现 `NSColorPanel.bind(color:)` 一调用就崩溃,用户决定在这一批一起修掉。 +不改用法,把 AppKitNavigation 收拾干净:清掉 fork 自己代码里的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。实现中发现 `NSColorPanel.bind(color:)` 一调用就崩溃,用户决定在这一批一起修掉;用户看过后,又要求修掉与上游共用代码里的警告和 Examples 的编译错误(第 9 步)。 ## 方案 @@ -24,6 +24,11 @@ 6. **收回 `AnyCancellable` 的公开 `Sendable` 遵循**(已完成):它只是为了在 `ObserveToken` 的闭包里捕获订阅,改用局部的 `nonisolated(unsafe) let`,库里已有同样的写法。 7. **文档**(已完成):删掉 `AppKitNavigation.docc` 里从 UIKit 抄来的 12 个页面(上游的 AppKitNavigation 没有它们),首页加一段概述和「绑定」「导航」两组目录;生成一次文档,确认没有新的 DocC 警告。实际还顺带修了 fork 自己的文档注释:文本框焦点绑定的示例和说明是从 UIKit 抄的,改成 AppKit 的写法;删掉不存在的参数说明,补上分段控件缺的参数说明。AppKitNavigation 的 DocC 警告从 23 条降到 3 条,剩下的都来自与上游共用的内容。 8. **修颜色面板绑定的崩溃**(已完成,实现中加入):`NSColorPanel` 遵循 `TargetActionProtocol` 时,`action` 的 getter 经 KVC 读面板的 action,而 KVC 返回不了 selector,抛出 `NSUnknownKeyException`;绑定在接管面板的 target/action 前要先读它,所以每次调用 `bind(color:)` 都崩溃。改为直接调用 AppKit 未公开但一直实现着的 `-action`,并用 `responds(to:)` 兜底。先补两条测试(面板能报出设置给它的 action;颜色面板的双向绑定),修之前崩溃,修之后通过。 +9. **用户看过后追加的修复**(已完成): + - `AppKitAnimation.perform(_:completion:)` 的 `completion` 改为 `@Sendable`,消掉它被捕获进 `NSAnimationContext` 完成回调时的警告;唯一的调用方原本就只捕获 `Sendable` 的值。调用方原来的三目写法在 Swift 6.4 下会让类型检查器报「failed to produce diagnostic」,改成 `if` 赋值。 + - `observe(_:)` 的两个重载在 Swift 6.4 上加 `@diagnose(ConversionFromIsolatedAnyToSynchronous, as: ignored, …)`(SE-0522),屏蔽「`@isolated(any)` 函数转成同步函数」的警告。这次同步转换是有意的:观察追踪要求同步执行;签名保留 `@isolated(any)`,因为上游靠它支持 `observe { @MainActor in … }` 这类显式指定隔离的写法。旧编译器不认这个属性,用 `#if hasAttribute(diagnose)` 包起来。 + - Examples 里三处 `import XCTestDynamicOverlay` 改成 `import IssueReporting`,`XCTFail` 改成 `reportIssue`。上游把依赖升到 `swift-issue-reporting` 2.0 后,依赖图里不再有 `XCTestDynamicOverlay` 这个模块,CaseStudies 因此编不过。 + - 工作区锁定文件 `SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved` 重新解析。原来那份和上游一样过时:钉着 `swift-case-paths` 的一个分支,还拉进旧地址的 `xctest-dynamic-overlay`,和 `swift-issue-reporting` 产品名冲突,命令行从零解析时直接失败。新的 pin 与 Xcode 实际解析出的版本一致。 没有询问就采用的假设: @@ -57,3 +62,7 @@ | 2026-11-04 | 修法:直接调用 AppKit 未公开的 `-action`,用 `responds(to:)` 兜底 | 让 getter 直接返回 `nil` 也不会崩,但绑定接管面板的 target/action 之后,就转发不了用户原先设的 action;改成监听颜色变化的通知、不再接管,又得改公开的 `TargetActionProtocol` 遵循。本机导出的 AppKit 头文件里,macOS 12.0.1、26.4–26.6、27.0、27.2 都有这个 getter。出问题的写法是 2024-10-11 加入颜色面板绑定时写下的,之后没改过,也没人修过;本机依赖这个 fork 的项目都没用到这个绑定 | | 2026-11-04 | 测试进程中途以 0 退出的问题查明原因,不在这批修(见后续项) | 加入颜色面板测试后截断变得频繁,于是追查:问题出在 AppKit 嵌套 run loop 与测试进程主执行器的交互上,`main` 上本来就有;试着去掉分段控件的点击用例,并不能根治,已恢复原样。根治要改测试基础设施,超出这一批的范围 | | 2026-11-04 | 第 8 步完成,重新验证 | Xcode 27.2 上 AppKit 测试完整跑通(Swift Testing 33 条、XCTest 16 条,有汇总行为证);Xcode 26.6 编得过 AppKit 的库和测试,只剩上游那一条警告 | +| 2026-11-04 | 按用户要求修与上游共用代码里的警告和 Examples 的编译错误(第 9 步) | 用户在 Xcode 里看到了这几条警告和 CaseStudies 的报错,要求一并修掉。这推翻了「只动 fork 独有的文件」那条假设,代价是以后合并上游时 `Observe.swift`、`AppKitAnimation.swift`、`UITransaction.swift` 和 Examples 可能冲突;原先记进裁决清单的「`AppKitAnimation.swift` 警告不修」随之删除 | +| 2026-11-04 | `observe(_:)` 用 `@diagnose` 屏蔽警告,不改签名 | 编译器对这类转换没有豁免写法,官方建议只有改成 async 或去掉 `@isolated(any)`:前者做不到(观察追踪必须同步),后者会让显式指定隔离的写法退化。代价是 Xcode 26.6(Swift 6.2)不认识这个属性,那两条警告在旧编译器上仍在,记进裁决清单 | +| 2026-11-04 | 工作区锁定文件一并更新 | 不更新的话,命令行和全新 clone 解析 Examples 的依赖时会因产品名冲突失败;新 pin 与 Xcode 里实际用的版本逐个核对过 | +| 2026-11-04 | 第 9 步完成,重新验证 | 全新构建目录下,Xcode 27.2 编 SwiftNavigation、AppKitNavigation 和 AppKit 测试零警告;整个包的测试只剩基线上的 `ButtonStateTests.testAsyncAnimationWarning`;CaseStudies 与 Inventory 用 xcodebuild 编 macOS 版成功(Inventory 关掉签名);Xcode 26.6 编得过 | From 8602608d6f707f20d7e175c188474b5b2c8561af Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Wed, 4 Nov 2026 22:42:30 +0800 Subject: [PATCH 071/141] docs: number the AppKitNavigation cleanup proposal 0001 and mark it implemented --- ...vigation-cleanup.md => 0001-appkit-navigation-cleanup.md} | 5 +++-- Documentations/Evolutions/README.md | 2 +- Documentations/README.md | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) rename Documentations/Evolutions/{draft-appkit-navigation-cleanup.md => 0001-appkit-navigation-cleanup.md} (96%) diff --git a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md similarity index 96% rename from Documentations/Evolutions/draft-appkit-navigation-cleanup.md rename to Documentations/Evolutions/0001-appkit-navigation-cleanup.md index 5d7800ac5e..7554312f4c 100644 --- a/Documentations/Evolutions/draft-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md @@ -1,6 +1,6 @@ -# Draft - AppKitNavigation 清理:警告、重复代理和多余依赖 +# 0001 - AppKitNavigation 清理:警告、重复代理和多余依赖 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-04 - **最后更新**: 2026-11-04 - **实现分支**: `appkit-navigation-cleanup` @@ -66,3 +66,4 @@ | 2026-11-04 | `observe(_:)` 用 `@diagnose` 屏蔽警告,不改签名 | 编译器对这类转换没有豁免写法,官方建议只有改成 async 或去掉 `@isolated(any)`:前者做不到(观察追踪必须同步),后者会让显式指定隔离的写法退化。代价是 Xcode 26.6(Swift 6.2)不认识这个属性,那两条警告在旧编译器上仍在,记进裁决清单 | | 2026-11-04 | 工作区锁定文件一并更新 | 不更新的话,命令行和全新 clone 解析 Examples 的依赖时会因产品名冲突失败;新 pin 与 Xcode 里实际用的版本逐个核对过 | | 2026-11-04 | 第 9 步完成,重新验证 | 全新构建目录下,Xcode 27.2 编 SwiftNavigation、AppKitNavigation 和 AppKit 测试零警告;整个包的测试只剩基线上的 `ButtonStateTests.testAsyncAnimationWarning`;CaseStudies 与 Inventory 用 xcodebuild 编 macOS 版成功(Inventory 关掉签名);Xcode 26.6 编得过 | +| 2026-11-04 | Implemented,编号 0001,落地到 `main` | 用户看过效果后要求收尾。九步全部完成;没做的两项留在后续项(测试进程中途以 0 退出、`NSPathControl` 构造器标签)。文档判断:不需要使用指南或实现说明,没有新的调用契约,难懂的决定都写在代码注释和本提案里;没有新术语;README 和 `swift-navigation-bindings` skill 不用改,公开用法没变 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 1521da64dd..4224f6f3e8 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -6,4 +6,4 @@ | # | 标题 | 状态 | |---|------|------| -| draft | [AppKitNavigation 清理:警告、重复代理和多余依赖](draft-appkit-navigation-cleanup.md) | In Progress | +| 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index 8972e6fe70..f19195c804 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -5,7 +5,7 @@ ## Evolutions - [Evolutions/README.md](Evolutions/README.md):提案索引与状态。 -- [draft-appkit-navigation-cleanup.md](Evolutions/draft-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 +- [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 ## Internal From add85dc27cdeb221b7e3b24d504309c546420b04 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 22:29:08 +0800 Subject: [PATCH 072/141] docs: propose keeping the main run loop alive under swift test AppKit's nested event loops occasionally leave a CFRunLoopStop behind for the outermost run loop. Under swift test that loop belongs to Swift's async main, which exits with status 0 the moment it returns, so the test run silently ends early. Restart the main run loop when that happens, from a test trait that installs itself before any test runs and stays inactive under Xcode. --- Documentations/Evolutions/README.md | 1 + .../draft-appkit-test-run-loop-exit.md | 30 +++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 32 insertions(+) create mode 100644 Documentations/Evolutions/draft-appkit-test-run-loop-exit.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 4224f6f3e8..a2ffe20f65 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -7,3 +7,4 @@ | # | 标题 | 状态 | |---|------|------| | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | +| draft | [AppKit 测试在 `swift test` 下不再中途以 0 退出](draft-appkit-test-run-loop-exit.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md new file mode 100644 index 0000000000..e689d04909 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md @@ -0,0 +1,30 @@ +# Draft - AppKit 测试在 `swift test` 下不再中途以 0 退出 + +- **状态**: Accepted +- **创建日期**: 2026-11-05 +- **最后更新**: 2026-11-05 +- **实现分支**: `appkit-test-run-loop-exit` + +## 摘要 + +本地用 `swift test` 跑 AppKit 的 Swift Testing 测试,偶尔跑到一半进程就结束了,退出码却是 0,没跑的测试结果直接丢失——一次没跑完的测试会被当成通过。原因在 [0001](0001-appkit-navigation-cleanup.md) 的后续项里已经查明:`swift test` 让 Swift Testing 跑在一个 `async` main 的进程里,主线程上的 `CFRunLoopRun()` 一返回,Swift 运行时就 `exit(0)`;分段控件的 `performClick`、保存和打开面板的创建会跑嵌套的事件循环,偶尔给最外层留下一个 `CFRunLoopStop`。这次让测试进程在主 run loop 被这样停下时接着跑,与真实 app 里 `NSApplication.run` 的表现一致。CI 用 `xcodebuild` 跑测试,不受这个问题影响。 + +## 方案 + +1. **先写必定变红的回归测试**:一个 exit test,在子进程里从主线程停掉最外层的 run loop(代替 AppKit 留下的那个 `CFRunLoopStop`),再要求主 actor 还能接着执行,最后以一个约定的退出码结束。没有修复时,子进程在 run loop 停下的那一刻以 0 退出,测试失败。它只在主 run loop 由 Swift 的 `async` main 驱动时运行(即 `swift test`);Xcode 里没有这个问题,跳过。 +2. **加一个测试 trait**(暂名 `.keepsMainRunLoopRunning`):Swift Testing 在开始跑任何测试之前调用 trait 的 `prepare(for:)`,它在那时给主 run loop 装一个观察者,数 run loop 的进出层数;最外层那次运行一退出(只可能是被误停,因为 Swift Testing 自己用 `exit()` 结束进程),就在原地重新运行主 run loop。只在主 run loop 由 Swift 的 `async` main 驱动时安装,Xcode 与 `xcodebuild` 下什么都不做。 +3. **给会跑嵌套事件循环的套件标上这个 trait**:`ControlActionDeliveryTests`、`ControlBindingLifetimeTests`、`ControlBindingRoundTripTests`。装一次就保护整个进程;标在这几个套件上,是为了让人看出谁需要它。 +4. **验证**:Xcode 27.2 上 `--no-parallel` 连跑 30 次 AppKit 的 Swift Testing 测试,次次都有完整的汇总行(修之前 30 次里截断 4–7 次);默认并行再跑 10 次;`xcodebuild test` 跑一遍,确认 Xcode 下照常;Xcode 26.6 编过测试 target。 + +没有询问就采用的假设: + +- trait 放在 `AppKitNavigationTests` 里,不新建 `TestingSupport` target:只有这一个 target 需要它,新建 target 又要改四份与上游共用的包清单。 +- 不改 `swift test` 的调用方式,也不动 Swift Testing 的运行器。 +- `NSPathControl` 构造器标签的修复(`date:` 直接改名为 `url:`)在同一分支上单独提交,不属于这份提案。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-05 | 让主 run loop 被误停后接着跑,不把相关测试移到 XCTest,也不改用 `xcodebuild` 判定 | 用户选定。移到 XCTest 只修了已知的几处,以后在 Swift Testing 里写同类测试还会复发;只换成 `xcodebuild` 则 `swift test` 照样不可靠 | +| 2026-11-05 | 用户批准,开始实现 | | diff --git a/Documentations/README.md b/Documentations/README.md index f19195c804..dac73b85ee 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -6,6 +6,7 @@ - [Evolutions/README.md](Evolutions/README.md):提案索引与状态。 - [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 +- [draft-appkit-test-run-loop-exit.md](Evolutions/draft-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 ## Internal From 6d427dd94057475479af6f925a3c561f0787f5af Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 22:35:55 +0800 Subject: [PATCH 073/141] test(appkit): keep the main run loop running when AppKit stops it from inside Under swift test, Swift Testing runs in a process whose async main runs the main run loop and exits with status 0 as soon as that run loop returns. Clicking a segmented control and creating a save or open panel run nested event loops that occasionally leave a CFRunLoopStop for the outermost run loop, so a run could end partway through and still report success. The keepsMainRunLoopRunning trait installs a run loop observer before any test runs. When the run loop of Swift's async main exits, which only a stray stop can cause, the observer runs the main run loop again from its callout. It installs nothing when Swift's async main does not run the main run loop, as under Xcode. An exit test stops the outermost run loop on purpose and fails with status 0 without the trait. --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-test-run-loop-exit.md | 9 +- .../ControlActionDeliveryTests.swift | 2 +- .../ControlBindingLifetimeTests.swift | 2 +- .../ControlBindingRoundTripTests.swift | 2 +- .../MainRunLoopKeeper.swift | 102 ++++++++++++++++++ .../MainRunLoopKeeperTests.swift | 29 +++++ 7 files changed, 140 insertions(+), 8 deletions(-) create mode 100644 Tests/AppKitNavigationTests/MainRunLoopKeeper.swift create mode 100644 Tests/AppKitNavigationTests/MainRunLoopKeeperTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index a2ffe20f65..e6e191a71a 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -7,4 +7,4 @@ | # | 标题 | 状态 | |---|------|------| | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | -| draft | [AppKit 测试在 `swift test` 下不再中途以 0 退出](draft-appkit-test-run-loop-exit.md) | Accepted | +| draft | [AppKit 测试在 `swift test` 下不再中途以 0 退出](draft-appkit-test-run-loop-exit.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md index e689d04909..57fbce7a0d 100644 --- a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md +++ b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md @@ -1,6 +1,6 @@ # Draft - AppKit 测试在 `swift test` 下不再中途以 0 退出 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-05 - **最后更新**: 2026-11-05 - **实现分支**: `appkit-test-run-loop-exit` @@ -11,9 +11,9 @@ ## 方案 -1. **先写必定变红的回归测试**:一个 exit test,在子进程里从主线程停掉最外层的 run loop(代替 AppKit 留下的那个 `CFRunLoopStop`),再要求主 actor 还能接着执行,最后以一个约定的退出码结束。没有修复时,子进程在 run loop 停下的那一刻以 0 退出,测试失败。它只在主 run loop 由 Swift 的 `async` main 驱动时运行(即 `swift test`);Xcode 里没有这个问题,跳过。 -2. **加一个测试 trait**(暂名 `.keepsMainRunLoopRunning`):Swift Testing 在开始跑任何测试之前调用 trait 的 `prepare(for:)`,它在那时给主 run loop 装一个观察者,数 run loop 的进出层数;最外层那次运行一退出(只可能是被误停,因为 Swift Testing 自己用 `exit()` 结束进程),就在原地重新运行主 run loop。只在主 run loop 由 Swift 的 `async` main 驱动时安装,Xcode 与 `xcodebuild` 下什么都不做。 -3. **给会跑嵌套事件循环的套件标上这个 trait**:`ControlActionDeliveryTests`、`ControlBindingLifetimeTests`、`ControlBindingRoundTripTests`。装一次就保护整个进程;标在这几个套件上,是为了让人看出谁需要它。 +1. **先写必定变红的回归测试**(已完成):一个 exit test,在子进程里从主线程停掉最外层的 run loop(代替 AppKit 留下的那个 `CFRunLoopStop`),再要求主 actor 还能接着执行,最后以一个约定的退出码结束。没有修复时,子进程在 run loop 停下的那一刻以 0 退出,测试失败。它只在主 run loop 由 Swift 的 `async` main 驱动时运行(即 `swift test`);Xcode 里没有这个问题,跳过。修复前实测:子进程以 0 退出,测试失败;修复后通过。 +2. **加一个测试 trait `.keepsMainRunLoopRunning`**(已完成):Swift Testing 在开始跑任何测试之前调用 trait 的 `prepare(for:)`,它在那时给主 run loop 装一个观察者,数 run loop 的进出层数;最外层那次运行一退出(只可能是被误停,因为 Swift Testing 自己用 `exit()` 结束进程),就在原地重新运行主 run loop。只在主 run loop 由 Swift 的 `async` main 驱动时安装,Xcode 与 `xcodebuild` 下什么都不做。实现在 `Tests/AppKitNavigationTests/MainRunLoopKeeper.swift`。 +3. **给会跑嵌套事件循环的套件标上这个 trait**(已完成):`ControlActionDeliveryTests`、`ControlBindingLifetimeTests`、`ControlBindingRoundTripTests`。装一次就保护整个进程;标在这几个套件上,是为了让人看出谁需要它。 4. **验证**:Xcode 27.2 上 `--no-parallel` 连跑 30 次 AppKit 的 Swift Testing 测试,次次都有完整的汇总行(修之前 30 次里截断 4–7 次);默认并行再跑 10 次;`xcodebuild test` 跑一遍,确认 Xcode 下照常;Xcode 26.6 编过测试 target。 没有询问就采用的假设: @@ -28,3 +28,4 @@ |------|------|------| | 2026-11-05 | 让主 run loop 被误停后接着跑,不把相关测试移到 XCTest,也不改用 `xcodebuild` 判定 | 用户选定。移到 XCTest 只修了已知的几处,以后在 Swift Testing 里写同类测试还会复发;只换成 `xcodebuild` 则 `swift test` 照样不可靠 | | 2026-11-05 | 用户批准,开始实现 | | +| 2026-11-05 | 判断「主 run loop 是否由 Swift 的 `async` main 驱动」,要在 run loop 的回调里读调用栈,安装观察者也放在那里做 | 第一版在 trait 的异步上下文里读 `Thread.callStackSymbols`,回归测试因此被误判为不需要而跳过:在 Swift 任务里取到的调用栈只有任务自己的异步帧,看不到底下的 run loop 和 `swift_task_asyncMainDrainQueue`。改为用 `CFRunLoopPerformBlock` 让最外层的 run loop 执行这段代码,同时保证观察者从最外层那次运行开始计数 | diff --git a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift index b6deb7d3e5..3b9fbcfc2e 100644 --- a/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift +++ b/Tests/AppKitNavigationTests/ControlActionDeliveryTests.swift @@ -4,7 +4,7 @@ import Testing @MainActor - @Suite struct ControlActionDeliveryTests { + @Suite(.keepsMainRunLoopRunning) struct ControlActionDeliveryTests { enum ControlKind: String, CaseIterable, Sendable { case pushButton case checkbox diff --git a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift index c7f78ee6cc..486382eae1 100644 --- a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift +++ b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift @@ -4,7 +4,7 @@ import Testing @MainActor - @Suite struct ControlBindingLifetimeTests { + @Suite(.keepsMainRunLoopRunning) struct ControlBindingLifetimeTests { /// What a reused table cell does: the same text field is bound to the next row's model. @Test("rebinding a text field stops writing edits to the previous binding") func rebindingStopsWritingToThePreviousBinding() { diff --git a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift index afc53a6d79..f25529f842 100644 --- a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift +++ b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift @@ -6,7 +6,7 @@ /// Each typed binding keeps its control and its source of truth in step: the control shows the /// bound value, follows later changes to it, and writes the user's changes back. @MainActor - @Suite struct ControlBindingRoundTripTests { + @Suite(.keepsMainRunLoopRunning) struct ControlBindingRoundTripTests { init() { // NB: A control sends its action through 'NSApplication.sendAction(_:to:from:)', which // silently does nothing when no application object exists yet. diff --git a/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift b/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift new file mode 100644 index 0000000000..561887bfa4 --- /dev/null +++ b/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift @@ -0,0 +1,102 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import Foundation + import Testing + + /// A trait that keeps the main run loop running when an AppKit event loop leaves a stray stop + /// behind. + /// + /// `swift test` runs Swift Testing in a process whose `async` main runs the main run loop and + /// calls `exit(0)` as soon as that run loop returns. Some AppKit calls run a nested event loop — + /// `performClick(_:)` on a segmented control, creating a save or open panel — and occasionally + /// leave a `CFRunLoopStop` that reaches the outermost run loop instead. The process then ends + /// partway through with status 0, and the tests that had not run yet are never reported. + /// + /// The testing library prepares the traits of every test before it runs any of them, so this + /// trait protects the whole process even if only one suite has it. Add it to every suite whose + /// tests drive an AppKit event loop anyway, so that it shows which suites need it. + struct KeepsMainRunLoopRunningTrait: SuiteTrait { + func prepare(for test: Test) async throws { + await MainRunLoopKeeper.start() + } + } + + extension Trait where Self == KeepsMainRunLoopRunningTrait { + /// Keeps the main run loop running when an AppKit event loop leaves a stray stop behind. + static var keepsMainRunLoopRunning: Self { Self() } + } + + /// Restarts the main run loop when the run loop Swift's `async` main is running gets stopped. + @MainActor + enum MainRunLoopKeeper { + private static var isStarted = false + + /// How many activations of the main run loop in its common modes are running, counting the one + /// Swift's `async` main runs. + private static var activationDepth = 0 + + /// Whether Swift's `async` main runs the main run loop, so that stopping it ends the process: + /// true under `swift test`, false under Xcode, which runs tests from a synchronous main. + static var isNeeded: Bool { + get async { + await performOnMainRunLoop { isMainRunLoopRunByAsyncMain } + } + } + + /// Starts watching the main run loop, if Swift's `async` main runs it. Call this before any test + /// runs a nested event loop. + static func start() async { + await performOnMainRunLoop { startWatching() } + } + + // NB: Inside a Swift task the backtrace only lists the task's own async frames, so this has to + // be read in a run loop callout to see what runs the run loop. + private static var isMainRunLoopRunByAsyncMain: Bool { + Thread.callStackSymbols.contains { $0.contains("swift_task_asyncMainDrainQueue") } + } + + private static func startWatching() { + guard !isStarted, isMainRunLoopRunByAsyncMain else { return } + isStarted = true + // NB: This runs in a callout of the run loop Swift's `async` main runs, before any test runs + // a nested one. + activationDepth = 1 + let observer = CFRunLoopObserverCreateWithHandler( + kCFAllocatorDefault, + CFRunLoopActivity([.entry, .exit]).rawValue, + true, + // NB: Runs after every other observer of a run loop that exits, AppKit's autorelease pool + // included. + CFIndex.max + ) { _, activity in + MainActor.assumeIsolated { + observe(activity) + } + } + CFRunLoopAddObserver(CFRunLoopGetMain(), observer, .commonModes) + } + + private static func observe(_ activity: CFRunLoopActivity) { + activationDepth += activity == .entry ? 1 : -1 + guard activationDepth == 0 else { return } + // NB: The run loop of Swift's `async` main is returning, and the process exits once it has. + // Swift Testing ends a run by calling `exit` itself, so only a stray stop gets here. + // Running the main run loop again from this callout keeps the tests going; Core + // Foundation never calls an observer that is still running, so nothing re-enters this. + while true { + CFRunLoopRun() + } + } + + /// Runs `body` in a callout of the main run loop rather than in a Swift task. + private static func performOnMainRunLoop( + _ body: @escaping @MainActor @Sendable () -> Value + ) async -> Value { + await withCheckedContinuation { continuation in + CFRunLoopPerformBlock(CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) { + continuation.resume(returning: MainActor.assumeIsolated(body)) + } + CFRunLoopWakeUp(CFRunLoopGetMain()) + } + } + } +#endif diff --git a/Tests/AppKitNavigationTests/MainRunLoopKeeperTests.swift b/Tests/AppKitNavigationTests/MainRunLoopKeeperTests.swift new file mode 100644 index 0000000000..0694d73286 --- /dev/null +++ b/Tests/AppKitNavigationTests/MainRunLoopKeeperTests.swift @@ -0,0 +1,29 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import Foundation + import Testing + + @Suite struct MainRunLoopKeeperTests { + /// How the exit test's child process ends when it gets past the stray stop. + static let finishedExitCode: CInt = 42 + + /// Stands in for the stop an AppKit event loop occasionally leaves for the outermost run loop: + /// the child process stops the main run loop, then needs it again to finish. + @Test( + "a stray stop of the main run loop does not end the test process", + .enabled("Only Swift's async main ends the process when its run loop stops") { + await MainRunLoopKeeper.isNeeded + } + ) + func strayStopDoesNotEndTheProcess() async { + await #expect(processExitsWith: .exitCode(MainRunLoopKeeperTests.finishedExitCode)) { + await MainRunLoopKeeper.start() + await MainActor.run { + CFRunLoopStop(CFRunLoopGetMain()) + } + // NB: Only a running main run loop gets back to the main actor. + await MainActor.run {} + exit(MainRunLoopKeeperTests.finishedExitCode) + } + } + } +#endif From b23d7326e7f9d147d40a1244f3204618bc080a2b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 22:52:19 +0800 Subject: [PATCH 074/141] test(appkit): compile the main run loop trait with Swift 6.2 Swift 6.2 treats the trait's conformance to SuiteTrait as public and so requires a public import of Testing, which Swift 6.4 does not. Import Testing publicly only for compilers older than 6.4. Record the verification in the proposal: 40 runs under swift test all finished, against 3 truncated runs out of 30 without the trait on the same machine, and the trait stays inactive under Xcode's test runner. Note the two older problems that verification turned up as follow-ups, and point the follow-ups of the AppKitNavigation cleanup proposal at their fixes. --- .../Evolutions/0001-appkit-navigation-cleanup.md | 4 ++-- .../Evolutions/draft-appkit-test-run-loop-exit.md | 15 +++++++++++++-- .../AppKitNavigationTests/MainRunLoopKeeper.swift | 8 +++++++- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md index 7554312f4c..3b9b8b07bb 100644 --- a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md @@ -41,8 +41,8 @@ ## 后续项 -- AppKit 的 Swift Testing 测试偶尔会中途结束,退出码却是 0,没跑完的测试结果就此丢失;`main` 上同样存在。用 lldb 查到:分段控件的 `performClick`、保存和打开面板的创建(`-[NSSavePanel _initBridgeAndStuff]` 等待远程面板的信号量)都会跑嵌套 run loop,偶尔把一个 `CFRunLoopStop` 漏给外层;而测试进程的主执行器在主 run loop 一返回就 `exit(0)`。去掉分段控件的点击用例不能根治,来源不止一处。修法要改测试基础设施,例如把这类测试移到 XCTest,或在主 run loop 退出时接着运行,留给另一批。 -- `NSPathControl` 的便捷构造器把 URL 绑定的参数标签写成了 `date:`,应为 `url:`;改它要动公开 API,不在这一批。 +- AppKit 的 Swift Testing 测试偶尔会中途结束,退出码却是 0,没跑完的测试结果就此丢失;`main` 上同样存在。用 lldb 查到:分段控件的 `performClick`、保存和打开面板的创建(`-[NSSavePanel _initBridgeAndStuff]` 等待远程面板的信号量)都会跑嵌套 run loop,偶尔把一个 `CFRunLoopStop` 漏给外层;而测试进程的主执行器在主 run loop 一返回就 `exit(0)`。去掉分段控件的点击用例不能根治,来源不止一处。修法要改测试基础设施,例如把这类测试移到 XCTest,或在主 run loop 退出时接着运行,留给另一批。(已修:在主 run loop 被误停时接着运行,见 [draft-appkit-test-run-loop-exit.md](draft-appkit-test-run-loop-exit.md)。) +- `NSPathControl` 的便捷构造器把 URL 绑定的参数标签写成了 `date:`,应为 `url:`;改它要动公开 API,不在这一批。(已修:直接改名为 `url:`,与上一项在同一分支上提交。) ## 决策日志 diff --git a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md index 57fbce7a0d..e3d1073d39 100644 --- a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md +++ b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md @@ -7,14 +7,17 @@ ## 摘要 -本地用 `swift test` 跑 AppKit 的 Swift Testing 测试,偶尔跑到一半进程就结束了,退出码却是 0,没跑的测试结果直接丢失——一次没跑完的测试会被当成通过。原因在 [0001](0001-appkit-navigation-cleanup.md) 的后续项里已经查明:`swift test` 让 Swift Testing 跑在一个 `async` main 的进程里,主线程上的 `CFRunLoopRun()` 一返回,Swift 运行时就 `exit(0)`;分段控件的 `performClick`、保存和打开面板的创建会跑嵌套的事件循环,偶尔给最外层留下一个 `CFRunLoopStop`。这次让测试进程在主 run loop 被这样停下时接着跑,与真实 app 里 `NSApplication.run` 的表现一致。CI 用 `xcodebuild` 跑测试,不受这个问题影响。 +本地用 `swift test` 跑 AppKit 的 Swift Testing 测试,偶尔跑到一半进程就结束了,退出码却是 0,没跑的测试结果直接丢失——一次没跑完的测试会被当成通过。原因在 [0001](0001-appkit-navigation-cleanup.md) 的后续项里已经查明:`swift test` 让 Swift Testing 跑在一个 `async` main 的进程里,主线程上的 `CFRunLoopRun()` 一返回,Swift 运行时就 `exit(0)`;分段控件的 `performClick`、保存和打开面板的创建会跑嵌套的事件循环,偶尔给最外层留下一个 `CFRunLoopStop`。这次让测试进程在主 run loop 被这样停下时接着跑,与真实 app 里 `NSApplication.run` 的表现一致。CI 的 `xcodebuild` 测试计划里没有 AppKit 的测试,它们只在本地跑:用 `swift test`,或在 Xcode 里直接打开包;后者不经过 `async` main,没有这个问题。 ## 方案 1. **先写必定变红的回归测试**(已完成):一个 exit test,在子进程里从主线程停掉最外层的 run loop(代替 AppKit 留下的那个 `CFRunLoopStop`),再要求主 actor 还能接着执行,最后以一个约定的退出码结束。没有修复时,子进程在 run loop 停下的那一刻以 0 退出,测试失败。它只在主 run loop 由 Swift 的 `async` main 驱动时运行(即 `swift test`);Xcode 里没有这个问题,跳过。修复前实测:子进程以 0 退出,测试失败;修复后通过。 2. **加一个测试 trait `.keepsMainRunLoopRunning`**(已完成):Swift Testing 在开始跑任何测试之前调用 trait 的 `prepare(for:)`,它在那时给主 run loop 装一个观察者,数 run loop 的进出层数;最外层那次运行一退出(只可能是被误停,因为 Swift Testing 自己用 `exit()` 结束进程),就在原地重新运行主 run loop。只在主 run loop 由 Swift 的 `async` main 驱动时安装,Xcode 与 `xcodebuild` 下什么都不做。实现在 `Tests/AppKitNavigationTests/MainRunLoopKeeper.swift`。 3. **给会跑嵌套事件循环的套件标上这个 trait**(已完成):`ControlActionDeliveryTests`、`ControlBindingLifetimeTests`、`ControlBindingRoundTripTests`。装一次就保护整个进程;标在这几个套件上,是为了让人看出谁需要它。 -4. **验证**:Xcode 27.2 上 `--no-parallel` 连跑 30 次 AppKit 的 Swift Testing 测试,次次都有完整的汇总行(修之前 30 次里截断 4–7 次);默认并行再跑 10 次;`xcodebuild test` 跑一遍,确认 Xcode 下照常;Xcode 26.6 编过测试 target。 +4. **验证**(已完成): + - Xcode 27.2 上用 `swift test` 跑 AppKit 的 Swift Testing 测试,`--no-parallel` 连跑 30 次、默认并行 10 次,40 次都有完整的汇总行,退出码都是 0。同一台机器上临时去掉 trait 作对照,串行 30 次里截断 3 次,退出码同样是 0,正是要修的那种「没跑完却算通过」。 + - Xcode 的测试运行器下(`xcodebuild test`,包自己的 `swift-navigation-Package` scheme)没有卡住,回归测试按设计跳过,XCTest 16 条通过。唯一的失败是 `TextFieldSelectionTests` 的一条,与本次改动无关,见后续项。 + - Xcode 26.6 编过 AppKit 的测试 target;Xcode 27.2 全新构建整个包,本包代码零警告(只有依赖 `swift-issue-reporting` 的两条链接器警告)。 没有询问就采用的假设: @@ -22,6 +25,11 @@ - 不改 `swift test` 的调用方式,也不动 Swift Testing 的运行器。 - `NSPathControl` 构造器标签的修复(`date:` 直接改名为 `url:`)在同一分支上单独提交,不属于这份提案。 +## 后续项 + +- 根目录的 `Package.resolved` 与上游保持一致,仍钉着 `swift-issue-reporting` 的旧名字 `xctest-dynamic-overlay`。`swift test` 不受影响;但用 Xcode 27 直接打开这个包(或对包跑 `xcodebuild`)时,计算依赖图失败:`PIFLoader: GUID 'PRODUCTREF-PACKAGE-PRODUCT:IssueReporting-…-dynamic' has already been registered`。加 `-IDEEnableNewPackagePIFBuilder=NO` 也一样。换成不含旧名字的 pin 就能编,但根目录这份就和上游不一致了。 +- `TextFieldSelectionTests` 的「AppKit's own selection handling stays in place on every text field」在 Xcode 的测试运行器下失败:Xcode 测试时加载的主线程检查器替换了 `textViewDidChangeSelection:` 的实现,查到的实现所在镜像是 `libMainThreadChecker.dylib`,不是 AppKit。`swift test` 下通过。`main` 上同样如此(这个测试和它测的代码在本分支上没有改动)。 + ## 决策日志 | 日期 | 决定 | 理由 | @@ -29,3 +37,6 @@ | 2026-11-05 | 让主 run loop 被误停后接着跑,不把相关测试移到 XCTest,也不改用 `xcodebuild` 判定 | 用户选定。移到 XCTest 只修了已知的几处,以后在 Swift Testing 里写同类测试还会复发;只换成 `xcodebuild` 则 `swift test` 照样不可靠 | | 2026-11-05 | 用户批准,开始实现 | | | 2026-11-05 | 判断「主 run loop 是否由 Swift 的 `async` main 驱动」,要在 run loop 的回调里读调用栈,安装观察者也放在那里做 | 第一版在 trait 的异步上下文里读 `Thread.callStackSymbols`,回归测试因此被误判为不需要而跳过:在 Swift 任务里取到的调用栈只有任务自己的异步帧,看不到底下的 run loop 和 `swift_task_asyncMainDrainQueue`。改为用 `CFRunLoopPerformBlock` 让最外层的 run loop 执行这段代码,同时保证观察者从最外层那次运行开始计数 | +| 2026-11-05 | 编译器低于 6.4 时公开导入 `Testing`(`#if compiler(<6.4)`),6.4 起保持内部导入 | Xcode 26.6 编测试 target 时,Swift 6.2 把 `KeepsMainRunLoopRunningTrait` 对 `SuiteTrait` 的遵循当成公开的,要求公开导入 `Testing`;6.4 没有这个要求。手头只能验证 6.2 和 6.4,没装 6.3,所以条件写成低于 6.4 | +| 2026-11-05 | 用 `xcodebuild` 验证时,临时用工作区那份锁定文件顶替根目录那份,跑完还原 | CI 的测试计划不含 AppKit 测试,只能用包自己的 scheme;根目录那份锁定文件让 Xcode 27 算不出依赖图(见后续项) | +| 2026-11-05 | 用 `xcodebuild` 验证时发现的两个旧问题记进后续项,不在这条分支上修 | 都与本次改动无关,`main` 上同样存在 | diff --git a/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift b/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift index 561887bfa4..645d841099 100644 --- a/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift +++ b/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift @@ -1,6 +1,12 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import Foundation - import Testing + #if compiler(<6.4) + // NB: Swift 6.2 treats the trait's conformance to 'SuiteTrait' below as public, and a public + // conformance needs a public import. + public import Testing + #else + import Testing + #endif /// A trait that keeps the main run loop running when an AppKit event loop leaves a stray stop /// behind. From d4a721154d558d344cdc6afeb45d35b8e84fab63 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 22:53:25 +0800 Subject: [PATCH 075/141] fix(appkit)!: label the path control initializer's binding url The convenience initializer took the binding to the selected URL under the label date:, the same label as the date picker's initializer it sits next to. Rename it to url: to match bind(url:). The round-trip test now creates its path control through this initializer. BREAKING CHANGE: NSPathControl(frame:date:) is now NSPathControl(frame:url:). --- Sources/AppKitNavigation/Bindings/NSPathControl.swift | 6 +++--- .../ControlBindingRoundTripTests.swift | 3 +-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/Sources/AppKitNavigation/Bindings/NSPathControl.swift b/Sources/AppKitNavigation/Bindings/NSPathControl.swift index 3a9b53f9c0..e705e16d45 100755 --- a/Sources/AppKitNavigation/Bindings/NSPathControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSPathControl.swift @@ -8,11 +8,11 @@ extension NSPathControl { /// /// - Parameters: /// - frame: The frame rectangle for the view, measured in points. - /// - date: The binding to read from for the selected url, and write to when the selected + /// - url: The binding to read from for the selected url, and write to when the selected /// url changes. - public convenience init(frame: CGRect = .zero, date: UIBinding) { + public convenience init(frame: CGRect = .zero, url: UIBinding) { self.init(frame: frame) - bind(url: date) + bind(url: url) } /// Establishes a two-way connection between a binding and the path control's selected url. diff --git a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift index f25529f842..533f723c6f 100644 --- a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift +++ b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift @@ -92,8 +92,7 @@ @Test("a path control stays in step with its binding") func pathControlStaysInStep() async { @UIBinding var url: URL? = URL(filePath: "/System") - let pathControl = NSPathControl() - pathControl.bind(url: $url) + let pathControl = NSPathControl(url: $url) #expect(pathControl.url?.lastPathComponent == "System") url = URL(filePath: "/Library") From 3d4912d32a305577bd8ff495e08239e4635d5cc8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 22:54:18 +0800 Subject: [PATCH 076/141] docs: record that the main run loop fix is implemented --- Documentations/Evolutions/draft-appkit-test-run-loop-exit.md | 1 + 1 file changed, 1 insertion(+) diff --git a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md index e3d1073d39..f37081cc91 100644 --- a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md +++ b/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md @@ -40,3 +40,4 @@ | 2026-11-05 | 编译器低于 6.4 时公开导入 `Testing`(`#if compiler(<6.4)`),6.4 起保持内部导入 | Xcode 26.6 编测试 target 时,Swift 6.2 把 `KeepsMainRunLoopRunningTrait` 对 `SuiteTrait` 的遵循当成公开的,要求公开导入 `Testing`;6.4 没有这个要求。手头只能验证 6.2 和 6.4,没装 6.3,所以条件写成低于 6.4 | | 2026-11-05 | 用 `xcodebuild` 验证时,临时用工作区那份锁定文件顶替根目录那份,跑完还原 | CI 的测试计划不含 AppKit 测试,只能用包自己的 scheme;根目录那份锁定文件让 Xcode 27 算不出依赖图(见后续项) | | 2026-11-05 | 用 `xcodebuild` 验证时发现的两个旧问题记进后续项,不在这条分支上修 | 都与本次改动无关,`main` 上同样存在 | +| 2026-11-05 | 实现完成,待用户看过后收尾 | 四步全部完成;Xcode 27.2 上全量 `swift test` 只有已知的 `ButtonStateTests.testAsyncAnimationWarning` 失败,`main` 上同样如此。文档判断:不需要使用指南或实现说明,trait 的用法和原理写在它的文档注释里,取舍写在本提案里;README、DocC 和 `swift-navigation-bindings` skill 都不用改(DocC 只链接到 `NSPathControl` 扩展本身,skill 没提这个构造器的标签) | From 525f5897121505734b080caaddab3672bbf2cf67 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 22:58:08 +0800 Subject: [PATCH 077/141] docs: number the main run loop fix proposal 0002 and mark it implemented --- Documentations/Evolutions/0001-appkit-navigation-cleanup.md | 4 ++-- ...st-run-loop-exit.md => 0002-appkit-test-run-loop-exit.md} | 5 +++-- Documentations/Evolutions/README.md | 2 +- Documentations/README.md | 2 +- 4 files changed, 7 insertions(+), 6 deletions(-) rename Documentations/Evolutions/{draft-appkit-test-run-loop-exit.md => 0002-appkit-test-run-loop-exit.md} (95%) diff --git a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md index 3b9b8b07bb..a5366b1ccd 100644 --- a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md @@ -41,8 +41,8 @@ ## 后续项 -- AppKit 的 Swift Testing 测试偶尔会中途结束,退出码却是 0,没跑完的测试结果就此丢失;`main` 上同样存在。用 lldb 查到:分段控件的 `performClick`、保存和打开面板的创建(`-[NSSavePanel _initBridgeAndStuff]` 等待远程面板的信号量)都会跑嵌套 run loop,偶尔把一个 `CFRunLoopStop` 漏给外层;而测试进程的主执行器在主 run loop 一返回就 `exit(0)`。去掉分段控件的点击用例不能根治,来源不止一处。修法要改测试基础设施,例如把这类测试移到 XCTest,或在主 run loop 退出时接着运行,留给另一批。(已修:在主 run loop 被误停时接着运行,见 [draft-appkit-test-run-loop-exit.md](draft-appkit-test-run-loop-exit.md)。) -- `NSPathControl` 的便捷构造器把 URL 绑定的参数标签写成了 `date:`,应为 `url:`;改它要动公开 API,不在这一批。(已修:直接改名为 `url:`,与上一项在同一分支上提交。) +- AppKit 的 Swift Testing 测试偶尔会中途结束,退出码却是 0,没跑完的测试结果就此丢失;`main` 上同样存在。用 lldb 查到:分段控件的 `performClick`、保存和打开面板的创建(`-[NSSavePanel _initBridgeAndStuff]` 等待远程面板的信号量)都会跑嵌套 run loop,偶尔把一个 `CFRunLoopStop` 漏给外层;而测试进程的主执行器在主 run loop 一返回就 `exit(0)`。去掉分段控件的点击用例不能根治,来源不止一处。修法要改测试基础设施,例如把这类测试移到 XCTest,或在主 run loop 退出时接着运行,留给另一批。(已修:在主 run loop 被误停时接着运行,见 [0002](0002-appkit-test-run-loop-exit.md)。) +- `NSPathControl` 的便捷构造器把 URL 绑定的参数标签写成了 `date:`,应为 `url:`;改它要动公开 API,不在这一批。(已修:直接改名为 `url:`,与 [0002](0002-appkit-test-run-loop-exit.md) 在同一分支上提交。) ## 决策日志 diff --git a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md b/Documentations/Evolutions/0002-appkit-test-run-loop-exit.md similarity index 95% rename from Documentations/Evolutions/draft-appkit-test-run-loop-exit.md rename to Documentations/Evolutions/0002-appkit-test-run-loop-exit.md index f37081cc91..03a3aa41e2 100644 --- a/Documentations/Evolutions/draft-appkit-test-run-loop-exit.md +++ b/Documentations/Evolutions/0002-appkit-test-run-loop-exit.md @@ -1,6 +1,6 @@ -# Draft - AppKit 测试在 `swift test` 下不再中途以 0 退出 +# 0002 - AppKit 测试在 `swift test` 下不再中途以 0 退出 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-05 - **最后更新**: 2026-11-05 - **实现分支**: `appkit-test-run-loop-exit` @@ -41,3 +41,4 @@ | 2026-11-05 | 用 `xcodebuild` 验证时,临时用工作区那份锁定文件顶替根目录那份,跑完还原 | CI 的测试计划不含 AppKit 测试,只能用包自己的 scheme;根目录那份锁定文件让 Xcode 27 算不出依赖图(见后续项) | | 2026-11-05 | 用 `xcodebuild` 验证时发现的两个旧问题记进后续项,不在这条分支上修 | 都与本次改动无关,`main` 上同样存在 | | 2026-11-05 | 实现完成,待用户看过后收尾 | 四步全部完成;Xcode 27.2 上全量 `swift test` 只有已知的 `ButtonStateTests.testAsyncAnimationWarning` 失败,`main` 上同样如此。文档判断:不需要使用指南或实现说明,trait 的用法和原理写在它的文档注释里,取舍写在本提案里;README、DocC 和 `swift-navigation-bindings` skill 都不用改(DocC 只链接到 `NSPathControl` 扩展本身,skill 没提这个构造器的标签) | +| 2026-11-05 | Implemented,编号 0002,落地到 `main` | 用户看过后要求收尾。四步全部完成,没有未做的项;验证时发现的两个旧问题留在后续项。文档判断:没有新术语,也不需要使用指南或实现说明 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index e6e191a71a..997a6208d7 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -7,4 +7,4 @@ | # | 标题 | 状态 | |---|------|------| | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | -| draft | [AppKit 测试在 `swift test` 下不再中途以 0 退出](draft-appkit-test-run-loop-exit.md) | In Progress | +| 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index dac73b85ee..784a69365b 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -6,7 +6,7 @@ - [Evolutions/README.md](Evolutions/README.md):提案索引与状态。 - [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 -- [draft-appkit-test-run-loop-exit.md](Evolutions/draft-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 +- [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 ## Internal From 0e1660415fd25e33d3b1d87540213357d112fbc8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:25:04 +0800 Subject: [PATCH 078/141] docs: propose typed bindings for common AppKit controls Seven local apps hand-write the same wiring about fifty times: pop-up buttons and segmented controls mapped to enums by their index in allCases, checkbox state synced with a Bool or with set membership, and split view collapse and tab selection driven from the model in one direction only. Add two-way bindings for checkboxes, pop-up buttons, segmented controls (single selection and per-segment), split view item collapse, tab view controller selection and menu item checkmarks, in the shape of the existing typed binds. --- Documentations/Evolutions/README.md | 1 + .../draft-appkit-common-control-bindings.md | 53 +++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 55 insertions(+) create mode 100644 Documentations/Evolutions/draft-appkit-common-control-bindings.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 997a6208d7..1280e9e66b 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -8,3 +8,4 @@ |---|------|------| | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | +| draft | [AppKit 常用控件的类型化绑定](draft-appkit-common-control-bindings.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md new file mode 100644 index 0000000000..114443aa8d --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -0,0 +1,53 @@ +# Draft - AppKit 常用控件的类型化绑定 + +- **状态**: Accepted +- **创建日期**: 2026-11-05 +- **最后更新**: 2026-11-05 +- **实现分支**: `appkit-common-control-bindings` + +## 摘要 + +调查了本机依赖这个 fork 的 7 个 macOS 项目,约 50 处代码在手写同一类连接:弹出按钮和分段控件按 `allCases` 的下标对应枚举,勾选框的 `state` 与 `Bool` 或集合成员互相同步,分栏的折叠状态和标签页的选中项只从模型往界面单向同步。库现有的类型化绑定覆盖不到这些控件:`bind(selectedSegment:)` 只接受以 `Int` 为原始值的枚举,勾选框、弹出按钮、分栏、标签页和菜单项勾号都没有对应的绑定。这次补上八种双向绑定,写法与现有的 `bind(isOn:)`、`bind(selectedSegment:)` 一致。 + +## 方案 + +调用点: + +```swift +NSButton(checkboxWithTitle: "Dump Objective-C", isOn: $model.dumpsObjectiveC) +NSButton(checkboxWithTitle: kind.title, isOn: $model.declarationKinds, contains: kind) +NSPopUpButton(selection: $model.weight, options: SymbolWeight.allCases, title: \.displayName) +segmentedControl.bind(selection: $model.segment, options: EntitySegment.allCases) +paneToggleControl.bind(isSelected: $model.isSidebarVisible, forSegment: 0) +inspectorItem.bind(isCollapsed: $model.isInspectorCollapsed) +tabViewController.bind(selection: $model.mode, options: MainSidebarMode.allCases) +NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) +``` + +1. **整理内部的绑定机制**:现有的 `establishBinding` 同时要求 target/action 和 KVO。拆成可选的三部分——用户操作后读回的值、要不要 KVO、token 存在哪个键下——让分栏、标签页这类没有 target/action 的对象,以及每段各绑一个值的分段控件也能用。现有绑定的行为不变。 +2. **勾选框**:`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 +3. **从一组选项里选一个**:`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 +4. **多选分段控件的单段**:`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 +5. **分栏折叠**:`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 +6. **标签页**:`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 +7. **菜单项勾号**:`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 +8. **文档与验证**:DocC 首页「绑定」一组登记新符号;`swift-navigation-bindings` skill 的类型化绑定清单补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 + +没有询问就采用的假设: + +- 参数标签用 `selection:`、`options:`,照 SwiftUI 的 `Picker(selection:)` 和 Cocoa 绑定的 `content` / `selectedObject`;现有的 `bind(selectedSegment:)` 保留不动。 +- 模型里的值不在 `options` 里时,用 `reportIssue` 报出来:弹出按钮和分段控件取消选中,标签页保持原样。用户选中了 `options` 之外的项(例如菜单里另加的项)时,同样报出来,不写回。 +- 勾选框不支持混合状态:`.on` 对应 `true`,其余都是 `false`。 +- 选项列表在绑定时一次给定;菜单内容随模型变化的情况这次不做。 +- 分栏折叠只在 `withAppKitAnimation` 里才带动画,与库里其他绑定的做法一致。 +- 分栏和标签页不加便捷构造器:它们随视图控制器创建,构造器没有可省的步骤。 +- 只改 fork 独有的 AppKitNavigation,不碰与上游共用的 SwiftNavigation 核心。各项目改用新绑定不在这一批。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-05 | 先做常用控件的类型化绑定,表格选中绑定、状态驱动的独立窗口、简化 `observe` 写法留到以后 | 用户选定。调查中这一块手写代码的处数最多,写法与现有绑定一致,没有设计上的未知数 | +| 2026-11-05 | 选中值按选项数组的顺序对应界面上的项,不按菜单项里存的值 | 用户选定。与各项目现有按 `allCases` 下标的写法一致,任意 `Equatable` 值都能用;代价是菜单里不能夹别的项,便捷构造器按选项生成菜单项来保证顺序 | +| 2026-11-05 | 集合成员勾选框、多选分段控件的单段、菜单项勾号三种附加绑定一起做 | 用户选定 | +| 2026-11-05 | 用户批准,开始实现 | | diff --git a/Documentations/README.md b/Documentations/README.md index 784a69365b..97e82a0614 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -7,6 +7,7 @@ - [Evolutions/README.md](Evolutions/README.md):提案索引与状态。 - [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 +- [draft-appkit-common-control-bindings.md](Evolutions/draft-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 ## Internal From 3dca0d697a300fe89fd0d7023b20a94359863e6d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:28:50 +0800 Subject: [PATCH 079/141] refactor(appkit): let a binding leave out target-action or key-value observation establishBinding required both a target-action pair and an Objective-C key path to observe. Make each optional, and let the caller choose the value an action writes back, so that objects without a target-action pair, properties key-value observation cannot reach, and menu items, whose state an action does not change, can bind through the same code. Existing bindings pass the same arguments as before. --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-common-control-bindings.md | 4 +- .../Bindings/TargetActionProtocol.swift | 55 ++++++++++++++----- 3 files changed, 43 insertions(+), 18 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 1280e9e66b..8658259b8f 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -8,4 +8,4 @@ |---|------|------| | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | -| draft | [AppKit 常用控件的类型化绑定](draft-appkit-common-control-bindings.md) | Accepted | +| draft | [AppKit 常用控件的类型化绑定](draft-appkit-common-control-bindings.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 114443aa8d..82f81bf320 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -1,6 +1,6 @@ # Draft - AppKit 常用控件的类型化绑定 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-05 - **最后更新**: 2026-11-05 - **实现分支**: `appkit-common-control-bindings` @@ -24,7 +24,7 @@ tabViewController.bind(selection: $model.mode, options: MainSidebarMode.allCases NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) ``` -1. **整理内部的绑定机制**:现有的 `establishBinding` 同时要求 target/action 和 KVO。拆成可选的三部分——用户操作后读回的值、要不要 KVO、token 存在哪个键下——让分栏、标签页这类没有 target/action 的对象,以及每段各绑一个值的分段控件也能用。现有绑定的行为不变。 +1. **整理内部的绑定机制**(已完成):现有的 `establishBinding` 同时要求 target/action 和 KVO。改成三部分都可选——target/action、KVO、用户操作后读回的值——让分栏、标签页这类没有 target/action 的对象,以及每段各绑一个值的分段控件也能用。现有绑定的行为不变,现有测试全部通过。 2. **勾选框**:`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 3. **从一组选项里选一个**:`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 4. **多选分段控件的单段**:`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index 23eb512d01..362f930d50 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -75,24 +75,42 @@ extension TargetActionProtocol { } } -/// Establishes a two-way connection between a binding and a property of an object whose -/// target-action pair `actionProxy` runs: the object's action writes the property back to the -/// binding, and changes to the binding are applied with `set`. +/// Establishes a two-way connection between a binding and a property of an object: changes to +/// the binding are applied with `set`, and the user's changes are written back to the binding. /// -/// ``TargetActionProtocol`` and `NSFontManager` both bind through this. The font manager cannot -/// conform to the protocol, since its `action` is not optional. +/// The user's changes arrive through the object's target-action pair, which `actionProxy` runs, +/// and through key-value observation of the property; either can be left out. +/// ``TargetActionProtocol`` and `NSFontManager` use both. The font manager cannot conform to the +/// protocol, since its `action` is not optional. Objects without a target-action pair, such as a +/// split view item, pass no proxy, and properties that key-value observation cannot reach, such +/// as the selection of one segment, opt out of it. +/// +/// - Parameters: +/// - binding: The binding to keep in step with the property. +/// - keyPath: The property. The binding is stored under this key path, so binding the same +/// property again replaces it. It must be an Objective-C key path unless `observesKeyPath` is +/// `false`. +/// - owner: The object that has the property. +/// - actionProxy: The proxy that runs the object's target-action pair, or `nil` if it has none. +/// - observesKeyPath: Whether changes that key-value observation of the property reports are +/// written back too. +/// - valueAfterAction: The value to write back when the object sends its action. Defaults to +/// the property's value. +/// - set: Applies a new value of the binding to the object. @MainActor func establishBinding( _ binding: UIBinding, to keyPath: KeyPath, of owner: Owner, - through actionProxy: TargetActionProxy, + through actionProxy: TargetActionProxy?, + observesKeyPath: Bool = true, + valueAfterAction: ((_ owner: Owner) -> Value)? = nil, set: @escaping (_ owner: Owner, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObserveToken { owner.removeBinding(to: keyPath) - let actionID = actionProxy.addBindingAction { [weak owner] _ in + let actionID = actionProxy?.addBindingAction { [weak owner] _ in guard let owner else { return } - binding.wrappedValue = owner[keyPath: keyPath] + binding.wrappedValue = valueAfterAction?(owner) ?? owner[keyPath: keyPath] } let isSetting = LockIsolated(false) @@ -110,18 +128,25 @@ func establishBinding( } // NB: This key path must only be accessed on the main actor nonisolated(unsafe) let uncheckedKeyPath = keyPath - let observation = owner.observe(keyPath) { owner, _ in - guard isSetting.withLock({ !$0 }) else { return } - MainActor._assumeIsolated { - binding.wrappedValue = owner[keyPath: uncheckedKeyPath] + let observation: NSKeyValueObservation? + if observesKeyPath { + observation = owner.observe(keyPath) { owner, _ in + guard isSetting.withLock({ !$0 }) else { return } + MainActor._assumeIsolated { + binding.wrappedValue = owner[keyPath: uncheckedKeyPath] + } } + } else { + observation = nil } let observationToken = ObserveToken { [weak actionProxy] in - MainActor._assumeIsolated { - actionProxy?.removeBindingAction(for: actionID) + if let actionID { + MainActor._assumeIsolated { + actionProxy?.removeBindingAction(for: actionID) + } } token.cancel() - observation.invalidate() + observation?.invalidate() } owner.observationTokens[keyPath] = observationToken return observationToken From bf8a423a1d39d507d74b4467ba507e58ac10780a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:30:25 +0800 Subject: [PATCH 080/141] feat(appkit): bind a checkbox to a Bool or to set membership NSButton.bind(isOn:) keeps a button's state in step with a Bool, and bind(isOn:contains:) with whether a SetAlgebra value, option sets included, contains a member: turning the button on inserts the member, turning it off removes it. Each comes with a checkbox initializer in the shape of NSButton(checkboxWithTitle:target:action:). --- .../draft-appkit-common-control-bindings.md | 2 +- .../AppKitNavigation/Bindings/NSButton.swift | 99 +++++++++++++++++++ .../Internal/KeyPathArgument.swift | 27 +++++ .../CommonControlBindingTests.swift | 84 ++++++++++++++++ 4 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSButton.swift create mode 100644 Sources/AppKitNavigation/Internal/KeyPathArgument.swift create mode 100644 Tests/AppKitNavigationTests/CommonControlBindingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 82f81bf320..784d6f4e5f 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -25,7 +25,7 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) ``` 1. **整理内部的绑定机制**(已完成):现有的 `establishBinding` 同时要求 target/action 和 KVO。改成三部分都可选——target/action、KVO、用户操作后读回的值——让分栏、标签页这类没有 target/action 的对象,以及每段各绑一个值的分段控件也能用。现有绑定的行为不变,现有测试全部通过。 -2. **勾选框**:`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 +2. **勾选框**(已完成):`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 3. **从一组选项里选一个**:`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 4. **多选分段控件的单段**:`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 5. **分栏折叠**:`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 diff --git a/Sources/AppKitNavigation/Bindings/NSButton.swift b/Sources/AppKitNavigation/Bindings/NSButton.swift new file mode 100644 index 0000000000..7df8501ece --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSButton.swift @@ -0,0 +1,99 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +extension NSButton { + /// Creates a checkbox with the specified title and registers the binding against whether or + /// not it is checked. + /// + /// - Parameters: + /// - title: The title displayed next to the checkbox. + /// - isOn: The binding to read from for whether the checkbox is checked, and write to when + /// the user checks or unchecks it. + public convenience init(checkboxWithTitle title: String, isOn: UIBinding) { + self.init(checkboxWithTitle: title, target: nil, action: nil) + bind(isOn: isOn) + } + + /// Creates a checkbox with the specified title that is checked whenever a set contains a + /// member. + /// + /// - Parameters: + /// - title: The title displayed next to the checkbox. + /// - options: The binding to read from for whether the checkbox is checked, and write to + /// when the user checks or unchecks it. + /// - member: The member that checking the checkbox inserts into the set, and unchecking it + /// removes. + public convenience init( + checkboxWithTitle title: String, + isOn options: UIBinding, + contains member: Options.Element + ) { + self.init(checkboxWithTitle: title, target: nil, action: nil) + bind(isOn: options, contains: member) + } + + /// Establishes a two-way connection between a binding and whether the button is on. + /// + /// Use this with checkboxes, and with other buttons whose state the user toggles. A mixed + /// state counts as off. + /// + /// - Parameter isOn: The binding to read from for whether the button is on, and write to when + /// the user turns it on or off. + /// - Returns: A cancel token. + @discardableResult + public func bind(isOn: UIBinding) -> ObserveToken { + bind(isOn, to: \.appKitNavigationIsOn) { button, isOn, _ in + button.appKitNavigationIsOn = isOn + } + } + + /// Establishes a two-way connection between whether the button is on and whether a set + /// contains a member. + /// + /// Turning the button on inserts the member into the set, and turning it off removes it. Any + /// `SetAlgebra` works, option sets included: + /// + /// ```swift + /// for kind in DeclarationKind.allCases { + /// let checkbox = NSButton( + /// checkboxWithTitle: kind.title, isOn: $model.shownKinds, contains: kind + /// ) + /// stackView.addArrangedSubview(checkbox) + /// } + /// ``` + /// + /// - Parameters: + /// - options: The binding to read from for whether the button is on, and write to when the + /// user turns it on or off. + /// - member: The member that turning the button on inserts into the set, and turning it off + /// removes. + /// - Returns: A cancel token. + @discardableResult + public func bind( + isOn options: UIBinding, + contains member: Options.Element + ) -> ObserveToken { + bind(isOn: options[containsMember: KeyPathArgument(member)]) + } + + // NB: Exposed to Objective-C so the binding can observe it, and named after the library so + // that it can never replace a method AppKit has, or adds later, under the same selector. + @objc var appKitNavigationIsOn: Bool { + set { state = newValue ? .on : .off } + get { state == .on } + } +} + +extension SetAlgebra { + fileprivate subscript(containsMember member: KeyPathArgument) -> Bool { + get { contains(member.value) } + set { + if newValue { + insert(member.value) + } else { + remove(member.value) + } + } + } +} +#endif diff --git a/Sources/AppKitNavigation/Internal/KeyPathArgument.swift b/Sources/AppKitNavigation/Internal/KeyPathArgument.swift new file mode 100644 index 0000000000..a1be214272 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/KeyPathArgument.swift @@ -0,0 +1,27 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +/// A value passed to a key path subscript, compared and hashed by identity. +/// +/// The arguments of a key path subscript must be `Hashable`. A binding derived through such a +/// subscript — whether a set contains a member, or where a value sits among some options — would +/// otherwise demand that the member or the options be hashable too. Each binding wraps its own +/// argument, so identity is all the key path needs. +final class KeyPathArgument: Hashable, @unchecked Sendable { + // NB: Unchecked, since the value need not be sendable. Bindings only read it on the main + // actor, and nothing ever changes it. + let value: Value + + init(_ value: Value) { + self.value = value + } + + static func == (lhs: KeyPathArgument, rhs: KeyPathArgument) -> Bool { + lhs === rhs + } + + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(self)) + } +} + +#endif diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift new file mode 100644 index 0000000000..3062176c9a --- /dev/null +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -0,0 +1,84 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// The typed bindings for checkboxes, pop-up buttons, segmented controls, split view items, tab + /// view controllers and menu items keep the user interface and the source of truth in step: it + /// shows the bound value, follows later changes to it, and writes the user's changes back. + @MainActor + @Suite struct CommonControlBindingTests { + init() { + // NB: A control sends its action through 'NSApplication.sendAction(_:to:from:)', which + // silently does nothing when no application object exists yet. + _ = NSApplication.shared + } + + // MARK: - Checkboxes + + @Test("a checkbox stays in step with its binding") + func checkboxStaysInStep() async { + @UIBinding var isOn = true + let checkbox = NSButton(checkboxWithTitle: "Option", isOn: $isOn) + #expect(checkbox.state == .on) + + isOn = false + await Task.yield() + #expect(checkbox.state == .off) + + checkbox.state = .on + sendAction(of: checkbox) + #expect(isOn) + } + + @Test("a checkbox stays in step with whether a set contains its member") + func setMembershipCheckboxStaysInStep() async { + @UIBinding var kinds: Set = [.classes] + let checkbox = NSButton(checkboxWithTitle: "Protocols", isOn: $kinds, contains: .protocols) + #expect(checkbox.state == .off) + + kinds.insert(.protocols) + await Task.yield() + #expect(checkbox.state == .on) + + checkbox.state = .off + sendAction(of: checkbox) + #expect(kinds == [.classes]) + } + + /// An option set's elements are the option set itself, which need not be hashable. + @Test("a checkbox stays in step with whether an option set contains its option") + func optionSetMembershipCheckboxStaysInStep() async { + @UIBinding var options: DumpOptions = [.comments] + let checkbox = NSButton(checkboxWithTitle: "Offsets", isOn: $options, contains: .offsets) + #expect(checkbox.state == .off) + + checkbox.state = .on + sendAction(of: checkbox) + #expect(options == [.comments, .offsets]) + + options = [] + await Task.yield() + #expect(checkbox.state == .off) + } + + // MARK: - Helpers + + private enum DeclarationKind { + case classes + case protocols + } + + private struct DumpOptions: OptionSet { + let rawValue: Int + + static let comments = DumpOptions(rawValue: 1 << 0) + static let offsets = DumpOptions(rawValue: 1 << 1) + } + + /// What a control does once the user has changed its value. + private func sendAction(of control: NSControl) { + control.sendAction(control.action, to: control.target) + } + } +#endif From 3ed6659b1cf42d41d1ad035dc4fb409fdcc706b6 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:32:37 +0800 Subject: [PATCH 081/141] feat(appkit): bind a pop-up button or segmented control to one of several options NSPopUpButton and NSSegmentedControl gain bind(selection:options:): the item or segment at position i stands for options[i], and the bound value only has to be Equatable, where bind(selectedSegment:) needs an Int raw value. Their initializers take a title for each option and create the items or segments to match. A value outside the options selects nothing, and choosing an item past the last option changes nothing; both are reported as issues. --- .../draft-appkit-common-control-bindings.md | 2 +- .../Bindings/NSPopUpButton.swift | 103 ++++++++++++++++++ .../Bindings/NSSegmentedControl.swift | 93 ++++++++++++++++ .../Internal/OptionIndex.swift | 54 +++++++++ .../CommonControlBindingTests.swift | 100 +++++++++++++++++ 5 files changed, 351 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSPopUpButton.swift create mode 100644 Sources/AppKitNavigation/Internal/OptionIndex.swift diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 784d6f4e5f..275114c4b4 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -26,7 +26,7 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) 1. **整理内部的绑定机制**(已完成):现有的 `establishBinding` 同时要求 target/action 和 KVO。改成三部分都可选——target/action、KVO、用户操作后读回的值——让分栏、标签页这类没有 target/action 的对象,以及每段各绑一个值的分段控件也能用。现有绑定的行为不变,现有测试全部通过。 2. **勾选框**(已完成):`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 -3. **从一组选项里选一个**:`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 +3. **从一组选项里选一个**(已完成):`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 4. **多选分段控件的单段**:`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 5. **分栏折叠**:`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 6. **标签页**:`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 diff --git a/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift b/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift new file mode 100644 index 0000000000..9fd7807bde --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift @@ -0,0 +1,103 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +extension NSPopUpButton { + /// Creates a pop-up button with an item for each option, and registers the binding against + /// the selected one. + /// + /// ```swift + /// let weightPopUpButton = NSPopUpButton( + /// selection: $model.weight, options: Weight.allCases, title: \.displayName + /// ) + /// ``` + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - selection: The binding to read from for the selected option, and write to when the + /// user chooses another one. + /// - options: The options, in the order of their items. + /// - title: The title of the item for an option. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + public convenience init( + frame: CGRect = .zero, + selection: UIBinding, + options: [Value], + title: (Value) -> String, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + self.init(frame: frame, pullsDown: false) + // NB: Added through the menu, since 'addItem(withTitle:)' first removes an item that has + // the same title, which would leave two options sharing one item. + for option in options { + menu?.addItem(withTitle: title(option), action: nil, keyEquivalent: "") + } + bind( + selection: selection, + options: options, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Establishes a two-way connection between a binding and the item the pop-up button has + /// selected, the item at the same position as the bound value among `options`. + /// + /// The pop-up button's items must match the options one for one, in order, which + /// ``AppKit/NSPopUpButton/init(frame:selection:options:title:fileID:filePath:line:column:)`` + /// takes care of. A value that is not one of the options selects no item, and choosing an + /// item past the last option leaves the binding alone; both are reported as issues. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user chooses another one. + /// - options: The options, in the order of the pop-up button's items. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: [Value], + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + let index = selection.optionIndex( + among: options, fileID: fileID, filePath: filePath, line: line, column: column + ) + return bind(index, to: \.appKitNavigationIndexOfSelectedItem) { popUpButton, index, _ in + if index == -1 { + reportIssue( + """ + A pop-up button's selection ('\(selection.wrappedValue)') is not one of its \ + options, so no item is selected. + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + popUpButton.appKitNavigationIndexOfSelectedItem = index + } + } + + // NB: Exposed to Objective-C so the binding can observe it, and named after the library so + // that it can never replace a method AppKit has, or adds later, under the same selector. + @objc var appKitNavigationIndexOfSelectedItem: Int { + set { selectItem(at: newValue) } + get { indexOfSelectedItem } + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift index 1575ee768f..e11ff786a5 100755 --- a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -56,6 +56,99 @@ extension NSSegmentedControl { to: \.selectedSegment ) } + + /// Creates a segmented control with a segment for each option, and registers the binding + /// against the selected one. + /// + /// ```swift + /// let layoutControl = NSSegmentedControl( + /// selection: $model.layout, options: Layout.allCases, title: \.title + /// ) + /// ``` + /// + /// - Parameters: + /// - frame: The frame rectangle for the view, measured in points. + /// - selection: The binding to read from for the selected option, and write to when the + /// user selects another one. + /// - options: The options, in the order of their segments. + /// - title: The label of the segment for an option. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + public convenience init( + frame: CGRect = .zero, + selection: UIBinding, + options: [Value], + title: (Value) -> String, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + self.init(frame: frame) + segmentCount = options.count + for (segment, option) in options.enumerated() { + setLabel(title(option), forSegment: segment) + } + trackingMode = .selectOne + bind( + selection: selection, + options: options, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Establishes a two-way connection between a binding and the selected segment, the segment + /// at the same position as the bound value among `options`. + /// + /// Unlike ``AppKit/NSSegmentedControl/bind(selectedSegment:fileID:filePath:line:column:)``, + /// the value need not be raw-representable: any equatable value works. The segments must + /// match the options one for one, in order, which + /// ``AppKit/NSSegmentedControl/init(frame:selection:options:title:fileID:filePath:line:column:)`` + /// takes care of. A value that is not one of the options selects no segment, and selecting a + /// segment past the last option leaves the binding alone; both are reported as issues. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user selects another one. + /// - options: The options, in the order of the segments. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: [Value], + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + let index = selection.optionIndex( + among: options, fileID: fileID, filePath: filePath, line: line, column: column + ) + return bind(index, to: \.selectedSegment) { segmentedControl, index, _ in + if index == -1 { + reportIssue( + """ + A segmented control's selection ('\(selection.wrappedValue)') is not one of \ + its options, so no segment is selected. + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + segmentedControl.selectedSegment = index + } + } } extension RawRepresentable { diff --git a/Sources/AppKitNavigation/Internal/OptionIndex.swift b/Sources/AppKitNavigation/Internal/OptionIndex.swift new file mode 100644 index 0000000000..58f333dee1 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/OptionIndex.swift @@ -0,0 +1,54 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +extension UIBinding where Value: Equatable { + /// A binding to the position of this binding's value among some options. + /// + /// The position is `-1` when the value is not one of the options. Writing a position chooses + /// the option there; writing one that matches no option is reported and changes nothing. + func optionIndex( + among options: [Value], + fileID: StaticString, + filePath: StaticString, + line: UInt, + column: UInt + ) -> UIBinding { + self[ + indexAmong: KeyPathArgument(options), + fileID: HashableStaticString(rawValue: fileID), + filePath: HashableStaticString(rawValue: filePath), + line: line, + column: column + ] + } +} + +extension Equatable { + fileprivate subscript( + indexAmong options: KeyPathArgument<[Self]>, + fileID fileID: HashableStaticString, + filePath filePath: HashableStaticString, + line line: UInt, + column column: UInt + ) -> Int { + get { options.value.firstIndex(of: self) ?? -1 } + set { + guard options.value.indices.contains(newValue) + else { + reportIssue( + """ + A selection binding was given position \(newValue), which matches none of its \ + \(options.value.count) options. + """, + fileID: fileID.rawValue, + filePath: filePath.rawValue, + line: line, + column: column + ) + return + } + self = options.value[newValue] + } + } +} + +#endif diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift index 3062176c9a..655529078b 100644 --- a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -62,8 +62,108 @@ #expect(checkbox.state == .off) } + // MARK: - Choosing one of several options + + @Test("a pop-up button stays in step with its selection") + func popUpButtonStaysInStep() async { + @UIBinding var weight = Weight.regular + let popUpButton = NSPopUpButton(selection: $weight, options: Weight.allCases, title: \.title) + #expect(popUpButton.itemTitles == ["Light", "Regular", "Bold"]) + #expect(popUpButton.indexOfSelectedItem == 1) + + weight = .bold + await Task.yield() + #expect(popUpButton.indexOfSelectedItem == 2) + + popUpButton.selectItem(at: 0) + sendAction(of: popUpButton) + #expect(weight == .light) + } + + /// Adding items by title would merge two options that share one. + @Test("a pop-up button keeps an item for each option, even when titles repeat") + func popUpButtonKeepsAnItemForEachOption() { + @UIBinding var weight = Weight.bold + let popUpButton = NSPopUpButton( + selection: $weight, options: Weight.allCases, title: { _ in "Same" } + ) + #expect(popUpButton.numberOfItems == 3) + #expect(popUpButton.indexOfSelectedItem == 2) + } + + @Test("a segmented control stays in step with its selection") + func segmentedControlStaysInStep() async { + @UIBinding var layout = Layout.list + let segmentedControl = NSSegmentedControl( + selection: $layout, options: [.icons, .list, .columns], title: \.title + ) + #expect(segmentedControl.segmentCount == 3) + #expect(segmentedControl.label(forSegment: 2) == "Columns") + #expect(segmentedControl.selectedSegment == 1) + + layout = .columns + await Task.yield() + #expect(segmentedControl.selectedSegment == 2) + + segmentedControl.selectedSegment = 0 + sendAction(of: segmentedControl) + #expect(layout == .icons) + } + + @Test("a selection that is not one of the options is reported and selects nothing") + func selectionOutsideTheOptionsIsReported() { + @UIBinding var weight = Weight.bold + var popUpButton: NSPopUpButton? + withKnownIssue { + popUpButton = NSPopUpButton(selection: $weight, options: [.light, .regular], title: \.title) + } + #expect(popUpButton?.indexOfSelectedItem == -1) + } + + @Test("choosing an item that is not one of the options is reported and changes nothing") + func choosingAnItemOutsideTheOptionsIsReported() { + @UIBinding var weight = Weight.regular + let popUpButton = NSPopUpButton(selection: $weight, options: Weight.allCases, title: \.title) + popUpButton.menu?.addItem(withTitle: "Custom…", action: nil, keyEquivalent: "") + + popUpButton.selectItem(at: 3) + withKnownIssue { + sendAction(of: popUpButton) + } + #expect(weight == .regular) + } + // MARK: - Helpers + private enum Weight: CaseIterable { + case light + case regular + case bold + + var title: String { + switch self { + case .light: "Light" + case .regular: "Regular" + case .bold: "Bold" + } + } + } + + /// Not raw-representable, unlike what `bind(selectedSegment:)` takes. + private enum Layout { + case icons + case list + case columns + + var title: String { + switch self { + case .icons: "Icons" + case .list: "List" + case .columns: "Columns" + } + } + } + private enum DeclarationKind { case classes case protocols From adbd5e313e245f601d43e1eb53b132135324571f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:33:33 +0800 Subject: [PATCH 082/141] feat(appkit): bind each segment of a segmented control to a Bool of its own bind(isSelected:forSegment:) keeps one segment's selection in step with a binding, for segmented controls that let the user select several segments at once, such as a toolbar's pane toggles. Each segment's binding is stored on its own, so binding a second segment does not replace the first. --- .../draft-appkit-common-control-bindings.md | 2 +- .../Bindings/NSSegmentedControl.swift | 34 +++++++++++++++++++ .../CommonControlBindingTests.swift | 25 ++++++++++++++ 3 files changed, 60 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 275114c4b4..36662e5ca1 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -27,7 +27,7 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) 1. **整理内部的绑定机制**(已完成):现有的 `establishBinding` 同时要求 target/action 和 KVO。改成三部分都可选——target/action、KVO、用户操作后读回的值——让分栏、标签页这类没有 target/action 的对象,以及每段各绑一个值的分段控件也能用。现有绑定的行为不变,现有测试全部通过。 2. **勾选框**(已完成):`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 3. **从一组选项里选一个**(已完成):`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 -4. **多选分段控件的单段**:`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 +4. **多选分段控件的单段**(已完成):`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 5. **分栏折叠**:`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 6. **标签页**:`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 7. **菜单项勾号**:`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift index e11ff786a5..cde64465e7 100755 --- a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -149,6 +149,40 @@ extension NSSegmentedControl { segmentedControl.selectedSegment = index } } + + /// Establishes a two-way connection between a binding and whether a segment is selected. + /// + /// Use this when the tracking mode lets the user select several segments at once, such as + /// `selectAny`, binding each segment to a value of its own: + /// + /// ```swift + /// paneToggleControl.bind(isSelected: $model.isSidebarVisible, forSegment: 0) + /// paneToggleControl.bind(isSelected: $model.isInspectorVisible, forSegment: 1) + /// ``` + /// + /// - Parameters: + /// - isSelected: The binding to read from for whether the segment is selected, and write to + /// when the user selects or deselects it. + /// - segment: The index of the segment. + /// - Returns: A cancel token. + @discardableResult + public func bind(isSelected: UIBinding, forSegment segment: Int) -> ObserveToken { + // NB: The selection of one segment is not a property that key-value observation can + // watch, so the action alone carries the user's changes back. + establishBinding( + isSelected, + to: \NSSegmentedControl.[isSelectedForSegment: segment], + of: self, + through: createActionProxyIfNeeded(), + observesKeyPath: false + ) { segmentedControl, isSelected, _ in + segmentedControl.setSelected(isSelected, forSegment: segment) + } + } + + fileprivate subscript(isSelectedForSegment segment: Int) -> Bool { + isSelected(forSegment: segment) + } } extension RawRepresentable { diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift index 655529078b..f4d36882cb 100644 --- a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -133,6 +133,31 @@ #expect(weight == .regular) } + // MARK: - Segments selected on their own + + @Test("each segment of a segmented control can stay in step with a binding of its own") + func segmentSelectionStaysInStep() async { + @UIBinding var showsSidebar = true + @UIBinding var showsInspector = false + let segmentedControl = NSSegmentedControl( + labels: ["Sidebar", "Inspector"], trackingMode: .selectAny, target: nil, action: nil + ) + segmentedControl.bind(isSelected: $showsSidebar, forSegment: 0) + segmentedControl.bind(isSelected: $showsInspector, forSegment: 1) + #expect(segmentedControl.isSelected(forSegment: 0)) + #expect(!segmentedControl.isSelected(forSegment: 1)) + + showsInspector = true + await Task.yield() + #expect(segmentedControl.isSelected(forSegment: 1)) + + // NB: Binding the second segment must not have replaced the first one's binding. + segmentedControl.setSelected(false, forSegment: 0) + sendAction(of: segmentedControl) + #expect(!showsSidebar) + #expect(showsInspector) + } + // MARK: - Helpers private enum Weight: CaseIterable { From 46b56657a29f494499b844e08041b887d111b060 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:36:10 +0800 Subject: [PATCH 083/141] feat(appkit): bind whether a split view item is collapsed NSSplitViewItem.bind(isCollapsed:) writes the user's collapsing and expanding back through key-value observation, which the documentation of 'collapsed' promises, and collapses or expands the item through its animator when the change comes with an animation. unbindIsCollapsed() removes the binding. The SDK declares NSSplitViewItem explicitly non-Sendable and does not isolate it to the main actor, so establishBinding no longer requires a Sendable owner, and the extension is marked @MainActor. --- .../draft-appkit-common-control-bindings.md | 4 +- .../Bindings/NSSplitViewItem.swift | 55 ++++++++++++++++++ .../Bindings/TargetActionProtocol.swift | 5 +- .../CommonControlBindingTests.swift | 56 +++++++++++++++++++ 4 files changed, 118 insertions(+), 2 deletions(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSSplitViewItem.swift diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 36662e5ca1..07d87a9e34 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -28,7 +28,7 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) 2. **勾选框**(已完成):`NSButton.bind(isOn:)` 把 `state` 与 `Bool` 双向同步;`bind(isOn:contains:)` 把勾选状态与一个 `SetAlgebra`(`Set`、`OptionSet`)里是否含有某个成员同步,勾上插入、取消移除。各配一个 `NSButton(checkboxWithTitle:isOn:)` 形式的便捷构造器。 3. **从一组选项里选一个**(已完成):`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 4. **多选分段控件的单段**(已完成):`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 -5. **分栏折叠**:`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 +5. **分栏折叠**(已完成):`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 6. **标签页**:`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 7. **菜单项勾号**:`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 8. **文档与验证**:DocC 首页「绑定」一组登记新符号;`swift-navigation-bindings` skill 的类型化绑定清单补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 @@ -51,3 +51,5 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) | 2026-11-05 | 选中值按选项数组的顺序对应界面上的项,不按菜单项里存的值 | 用户选定。与各项目现有按 `allCases` 下标的写法一致,任意 `Equatable` 值都能用;代价是菜单里不能夹别的项,便捷构造器按选项生成菜单项来保证顺序 | | 2026-11-05 | 集合成员勾选框、多选分段控件的单段、菜单项勾号三种附加绑定一起做 | 用户选定 | | 2026-11-05 | 用户批准,开始实现 | | +| 2026-11-05 | 内部的 `establishBinding` 不再要求被绑定的对象是 `Sendable`;分栏的扩展标 `@MainActor` | SDK 明确声明 `NSSplitViewItem` 不能是 `Sendable`,也没有把它隔离到主 actor,所以既不能像 `NSControl` 那样补一个 `@unchecked Sendable`,它的扩展也默认不在主 actor 上。KVO 回调里改用 `nonisolated(unsafe)` 把对象交给主 actor:这些对象只在主线程上变化、发通知 | +| 2026-11-05 | 分栏折叠带动画时,在绑定里自己用事务的动画包一层 | `observe` 已经会把更新放进环境事务的动画组里,但绑定自带的事务(`$model.x.animation(…)`)不走那一层;自己包一层,两种情况都经 `animator()` 带上同一个动画 | diff --git a/Sources/AppKitNavigation/Bindings/NSSplitViewItem.swift b/Sources/AppKitNavigation/Bindings/NSSplitViewItem.swift new file mode 100644 index 0000000000..59988674ca --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSplitViewItem.swift @@ -0,0 +1,55 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +// NB: Unlike the views and view controllers it describes, a split view item is not isolated to the +// main actor, but bindings are. +@MainActor +extension NSSplitViewItem { + /// Establishes a two-way connection between a binding and whether the split view item is + /// collapsed. + /// + /// When the user collapses or expands the item — by dragging its divider, or with a sidebar + /// or inspector toggle — the change is written back to the binding. A change to the binding + /// made with an animation, inside ``withAppKitAnimation(_:_:completion:)`` or through a + /// binding's own transaction, collapses or expands the item with that animation; any other + /// change applies at once. + /// + /// ```swift + /// inspectorItem.bind(isCollapsed: $model.isInspectorCollapsed) + /// + /// withAppKitAnimation(.easeInOut(duration: 0.2)) { + /// model.isInspectorCollapsed.toggle() + /// } + /// ``` + /// + /// - Parameter isCollapsed: The binding to read from for whether the item is collapsed, and + /// write to when the user collapses or expands it. + /// - Returns: A cancel token. + @discardableResult + public func bind(isCollapsed: UIBinding) -> ObserveToken { + // NB: No target-action pair: AppKit reports the user's changes through key-value + // observation, which the documentation of 'collapsed' promises. + establishBinding(isCollapsed, to: \.isCollapsed, of: self, through: nil) { + splitViewItem, isCollapsed, transaction in + guard splitViewItem.isCollapsed != isCollapsed else { return } + if let animation = transaction.appKit.animation, + !transaction.appKit.disablesAnimations + { + // NB: Collapsing animates only through the animator proxy. The animation runs + // here rather than relying on the one 'observe' sets up, since a binding's own + // transaction arrives without it. + animation.perform { + splitViewItem.animator().isCollapsed = isCollapsed + } + } else { + splitViewItem.isCollapsed = isCollapsed + } + } + } + + /// Removes the binding established with ``AppKit/NSSplitViewItem/bind(isCollapsed:)``. + public func unbindIsCollapsed() { + removeBinding(to: \NSSplitViewItem.isCollapsed) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index 362f930d50..a1a9156bed 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -98,7 +98,7 @@ extension TargetActionProtocol { /// the property's value. /// - set: Applies a new value of the binding to the object. @MainActor -func establishBinding( +func establishBinding( _ binding: UIBinding, to keyPath: KeyPath, of owner: Owner, @@ -132,6 +132,9 @@ func establishBinding( if observesKeyPath { observation = owner.observe(keyPath) { owner, _ in guard isSetting.withLock({ !$0 }) else { return } + // NB: The owner need not be sendable — a split view item is explicitly not — but these + // objects only change, and so only report changes, on the main thread. + nonisolated(unsafe) let owner = owner MainActor._assumeIsolated { binding.wrappedValue = owner[keyPath: uncheckedKeyPath] } diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift index f4d36882cb..1afa83be0d 100644 --- a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -158,8 +158,64 @@ #expect(showsInspector) } + // MARK: - Split view items + + @Test("a split view item stays in step with whether it is collapsed") + func splitViewItemStaysInStep() async { + @UIBinding var isCollapsed = false + let splitViewItem = NSSplitViewItem(viewController: PlaceholderViewController()) + splitViewItem.bind(isCollapsed: $isCollapsed) + #expect(!splitViewItem.isCollapsed) + + isCollapsed = true + await Task.yield() + #expect(splitViewItem.isCollapsed) + + // NB: What AppKit does when the user drags the divider or clicks the sidebar button. + splitViewItem.isCollapsed = false + #expect(!isCollapsed) + } + + @Test("collapsing a split view item with an animation leaves it and its binding collapsed") + func animatedCollapseStaysCollapsed() async throws { + @UIBinding var isCollapsed = false + let splitViewController = NSSplitViewController() + let splitViewItem = NSSplitViewItem(sidebarWithViewController: PlaceholderViewController()) + splitViewController.addSplitViewItem(splitViewItem) + splitViewController.addSplitViewItem( + NSSplitViewItem(viewController: PlaceholderViewController()) + ) + splitViewItem.bind(isCollapsed: $isCollapsed) + + withAppKitAnimation(.linear(duration: 0.05)) { + isCollapsed = true + } + try await Task.sleep(for: .milliseconds(300)) + + #expect(splitViewItem.isCollapsed) + #expect(isCollapsed) + } + + @Test("unbinding a split view item stops writing to the binding") + func unbindingASplitViewItemStopsWriting() { + @UIBinding var isCollapsed = false + let splitViewItem = NSSplitViewItem(viewController: PlaceholderViewController()) + splitViewItem.bind(isCollapsed: $isCollapsed) + + splitViewItem.unbindIsCollapsed() + splitViewItem.isCollapsed = true + + #expect(!isCollapsed) + } + // MARK: - Helpers + private final class PlaceholderViewController: NSViewController { + override func loadView() { + view = NSView() + } + } + private enum Weight: CaseIterable { case light case regular From 1fc494099c3be7ee2a6bb29b5c012b0af072665a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:37:41 +0800 Subject: [PATCH 084/141] feat(appkit): bind a tab view controller's selected tab to one of several options NSTabViewController.bind(selection:options:) keeps the selected tab, the tab at the bound value's position among the options, in step with the binding. The user's tab changes come back through key-value observation of selectedTabViewItemIndex. A value outside the options, or without a tab, leaves the selection alone and is reported. unbindSelection() removes the binding. --- .../draft-appkit-common-control-bindings.md | 2 +- .../Bindings/NSTabViewController.swift | 69 +++++++++++++++++++ .../CommonControlBindingTests.swift | 41 +++++++++++ 3 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSTabViewController.swift diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 07d87a9e34..7cd27f4415 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -29,7 +29,7 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) 3. **从一组选项里选一个**(已完成):`NSPopUpButton` 与 `NSSegmentedControl` 加 `bind(selection:options:)`,第 i 项对应 `options[i]`,值只要求 `Equatable`。便捷构造器多一个 `title:`,按选项生成菜单项或分段标签,保证顺序一致。 4. **多选分段控件的单段**(已完成):`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 5. **分栏折叠**(已完成):`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 -6. **标签页**:`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 +6. **标签页**(已完成):`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 7. **菜单项勾号**:`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 8. **文档与验证**:DocC 首页「绑定」一组登记新符号;`swift-navigation-bindings` skill 的类型化绑定清单补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 diff --git a/Sources/AppKitNavigation/Bindings/NSTabViewController.swift b/Sources/AppKitNavigation/Bindings/NSTabViewController.swift new file mode 100644 index 0000000000..9539c215dc --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTabViewController.swift @@ -0,0 +1,69 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +extension NSTabViewController { + /// Establishes a two-way connection between a binding and the selected tab, the tab at the + /// same position as the bound value among `options`. + /// + /// Add the tab view items first: the tabs must match the options one for one, in order. When + /// the user selects another tab, its option is written back to the binding. + /// + /// ```swift + /// tabViewController.addTabViewItem(NSTabViewItem(viewController: allSymbolsViewController)) + /// tabViewController.addTabViewItem(NSTabViewItem(viewController: symbolKindsViewController)) + /// tabViewController.bind(selection: $model.mode, options: SidebarMode.allCases) + /// ``` + /// + /// A value that is not one of the options, or one with no tab, leaves the selected tab as it + /// is and is reported as an issue. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user selects another tab. + /// - options: The options, in the order of the tabs. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: [Value], + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + let index = selection.optionIndex( + among: options, fileID: fileID, filePath: filePath, line: line, column: column + ) + // NB: No target-action pair: the selected index is key-value observable, and changes when + // the user picks another tab. + return establishBinding(index, to: \.selectedTabViewItemIndex, of: self, through: nil) { + tabViewController, index, _ in + guard tabViewController.tabViewItems.indices.contains(index) + else { + reportIssue( + """ + A tab view controller's selection ('\(selection.wrappedValue)') is not one of \ + its options, or has no tab, so the selected tab stays as it is. + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + return + } + tabViewController.selectedTabViewItemIndex = index + } + } + + /// Removes the binding established with + /// ``AppKit/NSTabViewController/bind(selection:options:fileID:filePath:line:column:)``. + public func unbindSelection() { + removeBinding(to: \NSTabViewController.selectedTabViewItemIndex) + } +} +#endif diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift index 1afa83be0d..3aaf01d7b4 100644 --- a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -208,8 +208,49 @@ #expect(!isCollapsed) } + // MARK: - Tab view controllers + + @Test("a tab view controller stays in step with its selection") + func tabViewControllerStaysInStep() async { + @UIBinding var layout = Layout.list + let tabViewController = makeTabViewController(tabCount: 3) + tabViewController.bind(selection: $layout, options: [.icons, .list, .columns]) + #expect(tabViewController.selectedTabViewItemIndex == 1) + + layout = .columns + await Task.yield() + #expect(tabViewController.selectedTabViewItemIndex == 2) + + // NB: What happens when the user picks another tab: the tab view selects it, and tells its + // controller. + tabViewController.tabView.selectTabViewItem(at: 0) + #expect(layout == .icons) + } + + @Test("unbinding a tab view controller stops writing to the binding") + func unbindingATabViewControllerStopsWriting() { + @UIBinding var layout = Layout.list + let tabViewController = makeTabViewController(tabCount: 3) + tabViewController.bind(selection: $layout, options: [.icons, .list, .columns]) + + tabViewController.unbindSelection() + tabViewController.tabView.selectTabViewItem(at: 0) + + #expect(layout == .list) + } + // MARK: - Helpers + private func makeTabViewController(tabCount: Int) -> NSTabViewController { + let tabViewController = NSTabViewController() + for _ in 0.. Date: Thu, 5 Nov 2026 23:38:55 +0800 Subject: [PATCH 085/141] feat(appkit): bind a menu item's checkmark to a Bool NSMenuItem.bind(isOn:) shows a checkmark while the bound value is true, and choosing the item toggles the value: a menu sends the item's action without changing its state, so the action writes back the opposite of the checkmark. NSMenuItem(title:isOn:keyEquivalent:) creates such an item. --- .../draft-appkit-common-control-bindings.md | 3 +- .../Bindings/NSMenuItem.swift | 52 ++++++++++++++++++- .../CommonControlBindingTests.swift | 27 ++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 7cd27f4415..576756d983 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -30,7 +30,7 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) 4. **多选分段控件的单段**(已完成):`NSSegmentedControl.bind(isSelected:forSegment:)`,每段各绑一个 `Bool`,名字照 AppKit 的 `isSelected(forSegment:)`。 5. **分栏折叠**(已完成):`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 6. **标签页**(已完成):`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 -7. **菜单项勾号**:`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 +7. **菜单项勾号**(已完成):`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 8. **文档与验证**:DocC 首页「绑定」一组登记新符号;`swift-navigation-bindings` skill 的类型化绑定清单补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 没有询问就采用的假设: @@ -52,4 +52,5 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) | 2026-11-05 | 集合成员勾选框、多选分段控件的单段、菜单项勾号三种附加绑定一起做 | 用户选定 | | 2026-11-05 | 用户批准,开始实现 | | | 2026-11-05 | 内部的 `establishBinding` 不再要求被绑定的对象是 `Sendable`;分栏的扩展标 `@MainActor` | SDK 明确声明 `NSSplitViewItem` 不能是 `Sendable`,也没有把它隔离到主 actor,所以既不能像 `NSControl` 那样补一个 `@unchecked Sendable`,它的扩展也默认不在主 actor 上。KVO 回调里改用 `nonisolated(unsafe)` 把对象交给主 actor:这些对象只在主线程上变化、发通知 | +| 2026-11-05 | 菜单项的新扩展同样标 `@MainActor` | `NSMenuItem` 也没有隔离到主 actor,新加的构造器和绑定要调用主 actor 上的绑定机制 | | 2026-11-05 | 分栏折叠带动画时,在绑定里自己用事务的动画包一层 | `observe` 已经会把更新放进环境事务的动画组里,但绑定自带的事务(`$model.x.animation(…)`)不走那一层;自己包一层,两种情况都经 `animator()` 带上同一个动画 | diff --git a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift index 663c1302e9..5e64c2c1e0 100755 --- a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift +++ b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift @@ -1,7 +1,57 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit +public import AppKit extension NSMenuItem: TargetActionProtocol, @unchecked @retroactive Sendable {} +// NB: A menu item is not isolated to the main actor, but bindings are. +@MainActor +extension NSMenuItem { + /// Creates a menu item with the specified title whose checkmark follows a binding. + /// + /// - Parameters: + /// - title: The title of the menu item. + /// - isOn: The binding to read from for whether the menu item shows a checkmark, and write + /// to when the user chooses it. + /// - keyEquivalent: The key equivalent of the menu item. + public convenience init(title: String, isOn: UIBinding, keyEquivalent: String = "") { + self.init(title: title, action: nil, keyEquivalent: keyEquivalent) + bind(isOn: isOn) + } + + /// Establishes a two-way connection between a binding and the menu item's checkmark. + /// + /// The menu item shows a checkmark while the bound value is `true`, and choosing it toggles + /// the value. + /// + /// ```swift + /// viewMenu.addItem(NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles)) + /// ``` + /// + /// - Parameter isOn: The binding to read from for whether the menu item shows a checkmark, + /// and write to when the user chooses it. + /// - Returns: A cancel token. + @discardableResult + public func bind(isOn: UIBinding) -> ObserveToken { + // NB: Choosing a menu item sends its action without changing its state, so the action + // writes back the opposite of what the checkmark showed. + establishBinding( + isOn, + to: \.appKitNavigationIsOn, + of: self, + through: createActionProxyIfNeeded(), + valueAfterAction: { menuItem in !menuItem.appKitNavigationIsOn } + ) { menuItem, isOn, _ in + menuItem.appKitNavigationIsOn = isOn + } + } + + // NB: Exposed to Objective-C so the binding can observe it, and named after the library so + // that it can never replace a method AppKit has, or adds later, under the same selector. + @objc var appKitNavigationIsOn: Bool { + set { state = newValue ? .on : .off } + get { state == .on } + } +} + #endif diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift index 3aaf01d7b4..c56783c707 100644 --- a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -239,8 +239,35 @@ #expect(layout == .list) } + // MARK: - Menu items + + @Test("a menu item's checkmark stays in step with its binding") + func menuItemCheckmarkStaysInStep() async { + @UIBinding var showsHiddenFiles = false + let menuItem = NSMenuItem(title: "Show Hidden Files", isOn: $showsHiddenFiles) + #expect(menuItem.state == .off) + + showsHiddenFiles = true + await Task.yield() + #expect(menuItem.state == .on) + + choose(menuItem) + #expect(!showsHiddenFiles) + + await Task.yield() + #expect(menuItem.state == .off) + } + // MARK: - Helpers + /// What a menu does when the user chooses one of its items: it sends the item's action, and + /// leaves the item's state alone. + private func choose(_ menuItem: NSMenuItem) { + let menu = NSMenu() + menu.addItem(menuItem) + menu.performActionForItem(at: menu.index(of: menuItem)) + } + private func makeTabViewController(tabCount: Int) -> NSTabViewController { let tabViewController = NSTabViewController() for _ in 0.. Date: Thu, 5 Nov 2026 23:43:45 +0800 Subject: [PATCH 086/141] docs(appkit): list the new control bindings and record that they are implemented Add NSButton, NSPopUpButton, NSSplitViewItem and NSTabViewController to the bindings group of the AppKitNavigation documentation. Record the verification in the proposal, and the follow-ups: a fork release the apps can resolve, menus whose items follow the model, and the checkbox mixed state. --- .../draft-appkit-common-control-bindings.md | 14 ++++++++++++-- .../Documentation.docc/AppKitNavigation.md | 4 ++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/draft-appkit-common-control-bindings.md index 576756d983..a1715c210c 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-common-control-bindings.md @@ -31,7 +31,10 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) 5. **分栏折叠**(已完成):`NSSplitViewItem.bind(isCollapsed:)`,用户拖动分隔条或点侧栏按钮折叠时经 KVO 写回;在 `withAppKitAnimation` 里改模型时经 `animator()` 带动画。配 `unbindIsCollapsed()`。 6. **标签页**(已完成):`NSTabViewController.bind(selection:options:)`,对应 `selectedTabViewItemIndex`,用户切换标签时经 KVO 写回。配 `unbindSelection()`。 7. **菜单项勾号**(已完成):`NSMenuItem.bind(isOn:)`,勾号跟随 `Bool`,用户选中菜单项时取反写回。配 `NSMenuItem(title:isOn:keyEquivalent:)`。 -8. **文档与验证**:DocC 首页「绑定」一组登记新符号;`swift-navigation-bindings` skill 的类型化绑定清单补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 +8. **文档与验证**(已完成): + - DocC 首页「绑定」一组登记了 `NSButton`、`NSPopUpButton`、`NSSplitViewItem`、`NSTabViewController`;生成文档没有新的 DocC 警告,仍是与上游共用内容的那 3 条。 + - `swift-navigation-bindings` skill 的绑定清单补上新绑定,常见错误表加了两条。 + - 每种绑定先写双向测试再实现,新测试在 `Tests/AppKitNavigationTests/CommonControlBindingTests.swift`。Xcode 27.2 上全量 `swift test` 只有已知的 `ButtonStateTests.testAsyncAnimationWarning` 失败;AppKit 的 Swift Testing 49 条(含 2 条故意触发的已知问题)、XCTest 16 条全部通过。Xcode 26.6 编过 AppKit 的测试 target;Xcode 27.2 全新构建,本包代码零警告。 没有询问就采用的假设: @@ -39,10 +42,16 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) - 模型里的值不在 `options` 里时,用 `reportIssue` 报出来:弹出按钮和分段控件取消选中,标签页保持原样。用户选中了 `options` 之外的项(例如菜单里另加的项)时,同样报出来,不写回。 - 勾选框不支持混合状态:`.on` 对应 `true`,其余都是 `false`。 - 选项列表在绑定时一次给定;菜单内容随模型变化的情况这次不做。 -- 分栏折叠只在 `withAppKitAnimation` 里才带动画,与库里其他绑定的做法一致。 +- 分栏折叠只在改模型时带了动画(`withAppKitAnimation`,或绑定自带的事务)才带动画,与库里其他绑定的做法一致。 - 分栏和标签页不加便捷构造器:它们随视图控制器创建,构造器没有可省的步骤。 - 只改 fork 独有的 AppKitNavigation,不碰与上游共用的 SwiftNavigation 核心。各项目改用新绑定不在这一批。 +## 后续项 + +- 各项目要用新绑定,得先给 fork 打一个包含它们的新版本(目前最新是 2.11.100),再把约 50 处手写代码换掉。 +- 菜单内容随模型变化(比如 XCOrganizer 在 `observe {}` 里重建标签菜单)还得手写:`options` 只在绑定时给一次。 +- 勾选框的混合状态没有对应的绑定。 + ## 决策日志 | 日期 | 决定 | 理由 | @@ -54,3 +63,4 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) | 2026-11-05 | 内部的 `establishBinding` 不再要求被绑定的对象是 `Sendable`;分栏的扩展标 `@MainActor` | SDK 明确声明 `NSSplitViewItem` 不能是 `Sendable`,也没有把它隔离到主 actor,所以既不能像 `NSControl` 那样补一个 `@unchecked Sendable`,它的扩展也默认不在主 actor 上。KVO 回调里改用 `nonisolated(unsafe)` 把对象交给主 actor:这些对象只在主线程上变化、发通知 | | 2026-11-05 | 菜单项的新扩展同样标 `@MainActor` | `NSMenuItem` 也没有隔离到主 actor,新加的构造器和绑定要调用主 actor 上的绑定机制 | | 2026-11-05 | 分栏折叠带动画时,在绑定里自己用事务的动画包一层 | `observe` 已经会把更新放进环境事务的动画组里,但绑定自带的事务(`$model.x.animation(…)`)不走那一层;自己包一层,两种情况都经 `animator()` 带上同一个动画 | +| 2026-11-05 | 实现完成,待用户看过后收尾 | 八步全部完成。文档判断:不需要使用指南或实现说明,用法写在各绑定的文档注释和 `swift-navigation-bindings` skill 里,取舍写在本提案里;README 不用改(上游的 README 不列 AppKit 的绑定);没有新术语 | diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 70da586bb3..6d05a6a482 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -35,15 +35,19 @@ popovers follow optional state: they are presented when it gains a value, dismis - ``AppKit/NSControl`` - ``AppKit/NSTextField`` - ``AppKitTextSelection`` +- ``AppKit/NSButton`` - ``AppKit/NSSwitch`` - ``AppKit/NSSlider`` - ``AppKit/NSStepper`` - ``AppKit/NSDatePicker`` - ``AppKit/NSColorWell`` - ``AppKit/NSPathControl`` +- ``AppKit/NSPopUpButton`` - ``AppKit/NSSegmentedControl`` - ``AppKit/NSProgressIndicator`` - ``AppKit/NSMenuItem`` +- ``AppKit/NSSplitViewItem`` +- ``AppKit/NSTabViewController`` - ``AppKit/NSColorPanel`` - ``AppKit/NSFontManager`` - ``AppKit/NSSavePanel`` From 74c2f948da67ed73bbc2e4afd67311a42b177d67 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:46:20 +0800 Subject: [PATCH 087/141] docs: number the common control bindings proposal 0003 and mark it implemented --- ...ol-bindings.md => 0003-appkit-common-control-bindings.md} | 5 +++-- Documentations/Evolutions/README.md | 2 +- Documentations/README.md | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) rename Documentations/Evolutions/{draft-appkit-common-control-bindings.md => 0003-appkit-common-control-bindings.md} (95%) diff --git a/Documentations/Evolutions/draft-appkit-common-control-bindings.md b/Documentations/Evolutions/0003-appkit-common-control-bindings.md similarity index 95% rename from Documentations/Evolutions/draft-appkit-common-control-bindings.md rename to Documentations/Evolutions/0003-appkit-common-control-bindings.md index a1715c210c..3ec463bfd2 100644 --- a/Documentations/Evolutions/draft-appkit-common-control-bindings.md +++ b/Documentations/Evolutions/0003-appkit-common-control-bindings.md @@ -1,6 +1,6 @@ -# Draft - AppKit 常用控件的类型化绑定 +# 0003 - AppKit 常用控件的类型化绑定 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-05 - **最后更新**: 2026-11-05 - **实现分支**: `appkit-common-control-bindings` @@ -64,3 +64,4 @@ NSMenuItem(title: "Show Hidden Files", isOn: $model.showsHiddenFiles) | 2026-11-05 | 菜单项的新扩展同样标 `@MainActor` | `NSMenuItem` 也没有隔离到主 actor,新加的构造器和绑定要调用主 actor 上的绑定机制 | | 2026-11-05 | 分栏折叠带动画时,在绑定里自己用事务的动画包一层 | `observe` 已经会把更新放进环境事务的动画组里,但绑定自带的事务(`$model.x.animation(…)`)不走那一层;自己包一层,两种情况都经 `animator()` 带上同一个动画 | | 2026-11-05 | 实现完成,待用户看过后收尾 | 八步全部完成。文档判断:不需要使用指南或实现说明,用法写在各绑定的文档注释和 `swift-navigation-bindings` skill 里,取舍写在本提案里;README 不用改(上游的 README 不列 AppKit 的绑定);没有新术语 | +| 2026-11-05 | Implemented,编号 0003,落地到 `main` | 用户看过后要求收尾。八步全部完成;没做的三项留在后续项(打 fork 新版本供各项目使用、随模型变化的菜单内容、勾选框的混合状态)。文档判断同上一行,没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 8658259b8f..6ae3f0dd85 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -8,4 +8,4 @@ |---|------|------| | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | -| draft | [AppKit 常用控件的类型化绑定](draft-appkit-common-control-bindings.md) | In Progress | +| 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index 97e82a0614..d046ea98e9 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -7,7 +7,7 @@ - [Evolutions/README.md](Evolutions/README.md):提案索引与状态。 - [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 -- [draft-appkit-common-control-bindings.md](Evolutions/draft-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 +- [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 ## Internal From 54cc10f0496e28af8b4a48728c055c9547ead2ea Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:55:33 +0800 Subject: [PATCH 088/141] docs: propose selection and expansion bindings for table and outline views Keeping a table's or an outline's selection in step with a model is the largest block of hand-written logic in the local apps: a delegate method writes the selected row's item to the model, an observe closure selects the model's item again, and flags keep that selection from writing back. Add a single-selection binding to NSTableView, which outline views inherit, that maps rows and identifiers through two lookup functions, with a shorthand for NSTableViewDiffableDataSource, and a binding between an outline's expanded items and a set of identifiers. --- Documentations/Evolutions/README.md | 1 + .../draft-appkit-table-selection-bindings.md | 56 +++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 58 insertions(+) create mode 100644 Documentations/Evolutions/draft-appkit-table-selection-bindings.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 6ae3f0dd85..22a858a185 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -9,3 +9,4 @@ | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | +| draft | [表格与大纲的选中绑定、大纲的展开状态绑定](draft-appkit-table-selection-bindings.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md new file mode 100644 index 0000000000..1f25601638 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md @@ -0,0 +1,56 @@ +# Draft - 表格与大纲的选中绑定、大纲的展开状态绑定 + +- **状态**: Accepted +- **创建日期**: 2026-11-05 +- **最后更新**: 2026-11-05 +- **实现分支**: `appkit-table-selection-bindings` + +## 摘要 + +本机依赖这个 fork 的项目里,表格和大纲的选中同步约 20 处,是手写逻辑最多的一块:在选中变化的代理方法里按行查出条目写进模型,在 `observe {}` 里再按模型把行选回去,还有 3 处要靠 `isSyncingSelection` 一类的标志位,挡住「把行选回去」触发的选中通知再写回模型。XCOrganizer 另外手写了大纲展开、折叠状态与模型的同步。库里没有任何对应的绑定。这次给 `NSTableView`(因而也包括 `NSOutlineView`)加单选的双向绑定,给 `NSOutlineView` 加展开状态的双向绑定,标志位交给库内部处理。 + +## 方案 + +调用点: + +```swift +// diffable 数据源(AppKit 自带的或 AppKitPlus 的):传它的两个查找方法 +outlineView.bind( + selection: $model.selectedItem, + row: dataSource.row(forItemIdentifier:), + itemIdentifier: dataSource.itemIdentifier(forRow:) +) +// AppKit 自带的 diffable 数据源,简写 +tableView.bind(selection: $model.selectedApplicationID, dataSource: dataSource) +// 普通数组 +tableView.bind( + selection: $model.selectedCategoryKey, + row: { key in model.categories.firstIndex { $0.key == key } }, + itemIdentifier: { row in model.categories[row].key } +) +// 大纲的展开状态 +outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource.itemIdentifier(forRow:)) +``` + +1. **单选绑定**:`NSTableView.bind(selection:row:itemIdentifier:)`,绑定一个可选的标识。模型变了就按 `row` 找到行选中;用户改了选中(表格发出选中变化的通知),就按 `itemIdentifier` 查出标识写回。绑定自己选行时发出的通知不写回。表格变成没有选中行时写回 `nil`——用户点空白处、选中的行被删掉或被折叠隐藏都算。模型里的标识对应不到可见的行时,表格取消选中,模型保留原值。配 `unbindSelection()`。 +2. **AppKit 自带 diffable 数据源的简写**:`bind(selection:dataSource:)`,用 `NSTableViewDiffableDataSource` 的两个查找方法。 +3. **大纲的展开状态**:`NSOutlineView.bind(expandedItems:itemIdentifier:)`,绑定一个标识的 `Set`。模型变了就从上到下逐行展开或折叠,展开父项后露出的子项接着处理;用户展开或折叠(大纲发出展开、折叠的通知)时把标识加进或移出集合。配 `unbindExpandedItems()`。 +4. **文档与验证**:DocC 首页「绑定」一组登记 `NSTableView`、`NSOutlineView`;`swift-navigation-bindings` skill 补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 + +没有询问就采用的假设: + +- 只做单选;多选以后另做。 +- 标识要求 `Hashable`,与 diffable 数据源和展开状态用的 `Set` 一致。 +- 通过表格、大纲发出的通知得知用户的改动,不占用、也不替换 app 自己的 delegate。 +- 绑定不负责滚动到选中的行。 +- 数据重新加载后,绑定在两种情况下重新对一次选中和展开:绑定的值变了,或者 `row`、`itemIdentifier` 闭包里读到的可观察状态变了。diffable 数据源应用快照时,表格自己会让选中跟着条目走;新条目的展开状态应该放进快照里。 +- 只改 fork 独有的 AppKitNavigation;各项目改用新绑定不在这一批。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-05 | 行和标识用两个查找函数对应,另给 AppKit 自带的 diffable 数据源一个简写 | 用户选定。diffable 数据源直接传它自己的两个方法,普通数组和对象树写两个闭包,任何数据源都能用 | +| 2026-11-05 | 表格变成没有选中行时,模型写回 `nil` | 用户选定。模型如实反映表格;XCOrganizer「折叠后把选中移到父项」这类逻辑改由模型自己处理 | +| 2026-11-05 | 一起做大纲的展开状态绑定;多选、`NSCollectionView` 的选中以后再说 | 用户选定 | +| 2026-11-05 | 用户批准,开始实现 | | diff --git a/Documentations/README.md b/Documentations/README.md index d046ea98e9..b606dc5baa 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -8,6 +8,7 @@ - [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 +- [draft-appkit-table-selection-bindings.md](Evolutions/draft-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 ## Internal From 71de018153e1022ca54c07afc66918757e4707ae Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Thu, 5 Nov 2026 23:59:31 +0800 Subject: [PATCH 089/141] feat(appkit): bind a table's or an outline's selected row to an identifier NSTableView.bind(selection:row:itemIdentifier:) keeps the selected row in step with an optional identifier, translating through two lookups a diffable data source already has. The user's changes arrive through the selection notification, under the outline's own name for outline views, and an empty selection writes nil. Selecting a row for the binding writes nothing back, which replaces the flags apps kept for that. bind(selection:dataSource:) uses an NSTableViewDiffableDataSource's lookups, and unbindSelection() removes the binding. --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-table-selection-bindings.md | 6 +- .../Bindings/NSTableView.swift | 114 ++++++++ .../Internal/NotificationObserver.swift | 33 +++ .../TableSelectionBindingTests.swift | 243 ++++++++++++++++++ 5 files changed, 394 insertions(+), 4 deletions(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSTableView.swift create mode 100644 Sources/AppKitNavigation/Internal/NotificationObserver.swift create mode 100644 Tests/AppKitNavigationTests/TableSelectionBindingTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 22a858a185..397de8f223 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -9,4 +9,4 @@ | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | -| draft | [表格与大纲的选中绑定、大纲的展开状态绑定](draft-appkit-table-selection-bindings.md) | Accepted | +| draft | [表格与大纲的选中绑定、大纲的展开状态绑定](draft-appkit-table-selection-bindings.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md index 1f25601638..2420013619 100644 --- a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md +++ b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md @@ -1,6 +1,6 @@ # Draft - 表格与大纲的选中绑定、大纲的展开状态绑定 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-05 - **最后更新**: 2026-11-05 - **实现分支**: `appkit-table-selection-bindings` @@ -32,8 +32,8 @@ tableView.bind( outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource.itemIdentifier(forRow:)) ``` -1. **单选绑定**:`NSTableView.bind(selection:row:itemIdentifier:)`,绑定一个可选的标识。模型变了就按 `row` 找到行选中;用户改了选中(表格发出选中变化的通知),就按 `itemIdentifier` 查出标识写回。绑定自己选行时发出的通知不写回。表格变成没有选中行时写回 `nil`——用户点空白处、选中的行被删掉或被折叠隐藏都算。模型里的标识对应不到可见的行时,表格取消选中,模型保留原值。配 `unbindSelection()`。 -2. **AppKit 自带 diffable 数据源的简写**:`bind(selection:dataSource:)`,用 `NSTableViewDiffableDataSource` 的两个查找方法。 +1. **单选绑定**(已完成):`NSTableView.bind(selection:row:itemIdentifier:)`,绑定一个可选的标识。模型变了就按 `row` 找到行选中;用户改了选中(表格发出选中变化的通知),就按 `itemIdentifier` 查出标识写回。绑定自己选行时发出的通知不写回。表格变成没有选中行时写回 `nil`——用户点空白处、选中的行被删掉或被折叠隐藏都算。模型里的标识对应不到可见的行时,表格取消选中,模型保留原值。配 `unbindSelection()`。 +2. **AppKit 自带 diffable 数据源的简写**(已完成):`bind(selection:dataSource:)`,用 `NSTableViewDiffableDataSource` 的两个查找方法。 3. **大纲的展开状态**:`NSOutlineView.bind(expandedItems:itemIdentifier:)`,绑定一个标识的 `Set`。模型变了就从上到下逐行展开或折叠,展开父项后露出的子项接着处理;用户展开或折叠(大纲发出展开、折叠的通知)时把标识加进或移出集合。配 `unbindExpandedItems()`。 4. **文档与验证**:DocC 首页「绑定」一组登记 `NSTableView`、`NSOutlineView`;`swift-navigation-bindings` skill 补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 diff --git a/Sources/AppKitNavigation/Bindings/NSTableView.swift b/Sources/AppKitNavigation/Bindings/NSTableView.swift new file mode 100644 index 0000000000..b9a5dc3c25 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTableView.swift @@ -0,0 +1,114 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +@_spi(Internals) public import SwiftNavigation +public import AppKit + +extension NSTableView { + /// Establishes a two-way connection between a binding and the table's selected row. + /// + /// The binding holds the identifier of the selected item, and two functions translate between + /// identifiers and rows. A diffable data source has both: + /// + /// ```swift + /// outlineView.bind( + /// selection: $model.selectedItem, + /// row: dataSource.row(forItemIdentifier:), + /// itemIdentifier: dataSource.itemIdentifier(forRow:) + /// ) + /// ``` + /// + /// When the binding changes, the table selects the identifier's row, or no row if `row` finds + /// none. When the selection changes otherwise — the user clicks or uses the keyboard, or the + /// selected row goes away — the selected row's identifier is written back, and `nil` when no + /// row is selected. Selecting a row for the binding writes nothing back, so the binding and the + /// table never echo each other. + /// + /// The selection is matched again whenever the binding changes, and whenever observable state + /// that `row` reads changes: look rows up in an observable model to have the selection follow + /// a reload. A diffable data source's snapshots keep the selection on the same items already. + /// + /// This binds a single selection; outline views bind theirs the same way. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected item, and write to when the + /// selection changes. + /// - row: The row of an item, or `nil` (or a negative row) when it has none. + /// - itemIdentifier: The identifier of the item in a row, or `nil` when the row has none. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + row: @escaping (ItemIdentifier) -> Int?, + itemIdentifier: @escaping (Int) -> ItemIdentifier? + ) -> ObserveToken { + unbindSelection() + let isSelecting = LockIsolated(false) + let token = observe { [weak self] in + guard let self else { return } + var rowsToSelect = IndexSet() + if let identifier = selection.wrappedValue, let row = row(identifier), row >= 0 { + rowsToSelect.insert(row) + } + guard selectedRowIndexes != rowsToSelect else { return } + isSelecting.withLock { $0 = true } + defer { isSelecting.withLock { $0 = false } } + selectRowIndexes(rowsToSelect, byExtendingSelection: false) + } + // NB: An outline view posts its own notification instead of the table's. + let notificationName = + self is NSOutlineView + ? NSOutlineView.selectionDidChangeNotification + : NSTableView.selectionDidChangeNotification + let observer = NotificationObserver(name: notificationName, object: self) { + [weak self] _ in + guard let self, isSelecting.withLock({ !$0 }) else { return } + let identifier = selectedRow >= 0 ? itemIdentifier(selectedRow) : nil + guard selection.wrappedValue != identifier else { return } + selection.wrappedValue = identifier + } + let observationToken = ObserveToken { + token.cancel() + MainActor._assumeIsolated { + observer.invalidate() + } + } + observationTokens[\NSTableView.selectedRowIndexes] = observationToken + return observationToken + } + + /// Establishes a two-way connection between a binding and the table's selected row, through + /// the row lookups of the table's diffable data source. + /// + /// ```swift + /// tableView.bind(selection: $model.selectedApplicationID, dataSource: dataSource) + /// ``` + /// + /// See ``AppKit/NSTableView/bind(selection:row:itemIdentifier:)`` for how the binding and the + /// selection follow each other. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected item, and write to when the + /// selection changes. + /// - dataSource: The table's diffable data source. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + dataSource: NSTableViewDiffableDataSource + ) -> ObserveToken { + // NB: Held weakly: the table keeps this binding for as long as it lives, and the data + // source may hold on to the table. + bind( + selection: selection, + row: { [weak dataSource] identifier in dataSource?.row(forItemIdentifier: identifier) }, + itemIdentifier: { [weak dataSource] row in dataSource?.itemIdentifier(forRow: row) } + ) + } + + /// Removes the binding established with + /// ``AppKit/NSTableView/bind(selection:row:itemIdentifier:)`` or + /// ``AppKit/NSTableView/bind(selection:dataSource:)``. + public func unbindSelection() { + removeBinding(to: \NSTableView.selectedRowIndexes) + } +} +#endif diff --git a/Sources/AppKitNavigation/Internal/NotificationObserver.swift b/Sources/AppKitNavigation/Internal/NotificationObserver.swift new file mode 100644 index 0000000000..8d09fcd7c8 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/NotificationObserver.swift @@ -0,0 +1,33 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + + /// Runs a closure for each notification of a name that an object posts, until invalidated. + /// + /// Observes through a selector rather than a block: a block observer's closure has to be + /// sendable, and bindings hand it closures that are not, such as an app's lookup of a row's + /// item. The objects bindings observe post their notifications on the main thread. + @MainActor + final class NotificationObserver: NSObject { + private let handler: (Notification) -> Void + + init( + name: Notification.Name, + object: AnyObject, + handler: @escaping (Notification) -> Void + ) { + self.handler = handler + super.init() + NotificationCenter.default.addObserver( + self, selector: #selector(receive(_:)), name: name, object: object + ) + } + + func invalidate() { + NotificationCenter.default.removeObserver(self) + } + + @objc private func receive(_ notification: Notification) { + handler(notification) + } + } +#endif diff --git a/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift new file mode 100644 index 0000000000..ce0c23a7e4 --- /dev/null +++ b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift @@ -0,0 +1,243 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// A table's or an outline's selected row, and an outline's expanded items, stay in step with a + /// binding: the view follows the bound value, and writes back what the user changes, but not + /// what the binding itself changed. + @MainActor + @Suite struct TableSelectionBindingTests { + // MARK: - Selection + + @Test("a table view's selection stays in step with its binding") + func tableViewSelectionStaysInStep() async { + let categories = ["Colors", "Shapes", "Weather"] + let rowCount = RowCount(categories.count) + let tableView = makeTableView(dataSource: rowCount) + @UIBinding var selectedCategory: String? = "Shapes" + tableView.bind( + selection: $selectedCategory, + row: { category in categories.firstIndex(of: category) }, + itemIdentifier: { row in categories[row] } + ) + #expect(tableView.selectedRow == 1) + + selectedCategory = "Weather" + await Task.yield() + #expect(tableView.selectedRow == 2) + + // NB: What the table does when the user clicks a row. + tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) + #expect(selectedCategory == "Colors") + } + + @Test("a table view with no selected row writes nil to its binding") + func clearingTheSelectionWritesNil() { + let categories = ["Colors", "Shapes"] + let rowCount = RowCount(categories.count) + let tableView = makeTableView(dataSource: rowCount) + @UIBinding var selectedCategory: String? = "Shapes" + tableView.bind( + selection: $selectedCategory, + row: { category in categories.firstIndex(of: category) }, + itemIdentifier: { row in categories[row] } + ) + + tableView.deselectAll(nil) + + #expect(selectedCategory == nil) + } + + @Test("an identifier with no visible row deselects the table and stays in the binding") + func identifierWithoutARowDeselectsTheTable() async { + let categories = ["Colors", "Shapes"] + let rowCount = RowCount(categories.count) + let tableView = makeTableView(dataSource: rowCount) + @UIBinding var selectedCategory: String? = "Shapes" + tableView.bind( + selection: $selectedCategory, + row: { category in categories.firstIndex(of: category) }, + itemIdentifier: { row in categories[row] } + ) + + selectedCategory = "Hidden" + await Task.yield() + + #expect(tableView.selectedRow == -1) + #expect(selectedCategory == "Hidden") + } + + @Test("unbinding a table view's selection stops writing to the binding") + func unbindingTheSelectionStopsWriting() { + let categories = ["Colors", "Shapes"] + let rowCount = RowCount(categories.count) + let tableView = makeTableView(dataSource: rowCount) + @UIBinding var selectedCategory: String? = "Shapes" + tableView.bind( + selection: $selectedCategory, + row: { category in categories.firstIndex(of: category) }, + itemIdentifier: { row in categories[row] } + ) + + tableView.unbindSelection() + tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) + + #expect(selectedCategory == "Shapes") + } + + @Test("a table view's selection stays in step through its diffable data source") + func selectionThroughADiffableDataSource() { + let tableView = NSTableView() + tableView.addTableColumn(NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Column"))) + let dataSource = NSTableViewDiffableDataSource(tableView: tableView) { + _, _, _, _ in NSView() + } + retain(dataSource, by: tableView) + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(["Colors", "Shapes", "Weather"]) + dataSource.apply(snapshot, animatingDifferences: false) + @UIBinding var selectedCategory: String? = "Weather" + tableView.bind(selection: $selectedCategory, dataSource: dataSource) + #expect(tableView.selectedRow == 2) + + tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) + #expect(selectedCategory == "Colors") + } + + /// An outline reports its selection under its own notification name, not the table's. + @Test("an outline view's selection stays in step with its binding") + func outlineViewSelectionStaysInStep() async { + let tree = Tree.fruitsAndVegetables + let outlineView = makeOutlineView(dataSource: tree) + outlineView.expandItem(tree.node(named: "Fruits")) + @UIBinding var selection: String? = "Pear" + bindSelection($selection, of: outlineView, in: tree) + #expect(outlineView.selectedRow == 2) + + // NB: What the outline does when the user clicks a row. + outlineView.selectRowIndexes(IndexSet(integer: 3), byExtendingSelection: false) + #expect(selection == "Vegetables") + } + + @Test("collapsing the parent of the selected item clears the binding") + func collapsingTheSelectedItemsParentClearsTheSelection() async { + let tree = Tree.fruitsAndVegetables + let outlineView = makeOutlineView(dataSource: tree) + outlineView.expandItem(tree.node(named: "Fruits")) + @UIBinding var selection: String? = "Apple" + bindSelection($selection, of: outlineView, in: tree) + #expect(outlineView.selectedRow == 1) + + outlineView.collapseItem(tree.node(named: "Fruits")) + + #expect(selection == nil) + } + + // MARK: - Helpers + + private func bindSelection( + _ selection: UIBinding, of outlineView: NSOutlineView, in tree: Tree + ) { + outlineView.bind( + selection: selection, + row: { [weak outlineView] name in outlineView?.row(forItem: tree.node(named: name)) }, + itemIdentifier: { [weak outlineView] row in + (outlineView?.item(atRow: row) as? Node)?.name + } + ) + } + + private func makeTableView(dataSource: some NSTableViewDataSource) -> NSTableView { + let tableView = NSTableView() + tableView.addTableColumn(NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Column"))) + tableView.dataSource = dataSource + retain(dataSource, by: tableView) + tableView.reloadData() + return tableView + } + + private func makeOutlineView(dataSource: some NSOutlineViewDataSource) -> NSOutlineView { + let outlineView = NSOutlineView() + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Column")) + outlineView.addTableColumn(column) + outlineView.outlineTableColumn = column + outlineView.dataSource = dataSource + retain(dataSource, by: outlineView) + outlineView.reloadData() + return outlineView + } + + /// A table only holds its data source weakly, and a test may stop using its data source long + /// before the table is done with it. + private func retain(_ dataSource: AnyObject, by tableView: NSTableView) { + objc_setAssociatedObject( + tableView, Self.dataSourceKey, dataSource, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + + private static let dataSourceKey = malloc(1)! + + /// A table's rows, with nothing in them. + private final class RowCount: NSObject, NSTableViewDataSource { + let count: Int + + init(_ count: Int) { + self.count = count + } + + func numberOfRows(in tableView: NSTableView) -> Int { + count + } + } + + private final class Node: NSObject { + let name: String + let children: [Node] + + init(_ name: String, children: [Node] = []) { + self.name = name + self.children = children + } + } + + /// An outline's items. + private final class Tree: NSObject, NSOutlineViewDataSource { + let roots: [Node] + + init(_ roots: [Node]) { + self.roots = roots + } + + /// Fruits, with Apple and Pear inside, then Vegetables, with Carrot inside. + static var fruitsAndVegetables: Tree { + Tree([ + Node("Fruits", children: [Node("Apple"), Node("Pear")]), + Node("Vegetables", children: [Node("Carrot")]), + ]) + } + + func node(named name: String) -> Node? { + var pending = roots + while let node = pending.popLast() { + if node.name == name { return node } + pending += node.children + } + return nil + } + + func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { + (item as? Node)?.children.count ?? roots.count + } + + func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { + (item as? Node)?.children[index] ?? roots[index] + } + + func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { + !((item as? Node)?.children.isEmpty ?? true) + } + } + } +#endif From eccd472e421489d4281078ea31a7ecc4584f3fcb Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 00:00:58 +0800 Subject: [PATCH 090/141] feat(appkit): bind an outline's expanded items to a set of identifiers NSOutlineView.bind(expandedItems:itemIdentifier:) expands and collapses the outline's items to match the set, row by row from the top so that a child expands once its parent shows it, and inserts or removes an item's identifier when the user expands or collapses it. Expanding and collapsing for the binding writes nothing back. unbindExpandedItems() removes the binding. --- .../draft-appkit-table-selection-bindings.md | 2 +- .../Bindings/NSOutlineView.swift | 118 ++++++++++++++++++ .../TableSelectionBindingTests.swift | 57 +++++++++ 3 files changed, 176 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSOutlineView.swift diff --git a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md index 2420013619..b443ae159a 100644 --- a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md +++ b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md @@ -34,7 +34,7 @@ outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource 1. **单选绑定**(已完成):`NSTableView.bind(selection:row:itemIdentifier:)`,绑定一个可选的标识。模型变了就按 `row` 找到行选中;用户改了选中(表格发出选中变化的通知),就按 `itemIdentifier` 查出标识写回。绑定自己选行时发出的通知不写回。表格变成没有选中行时写回 `nil`——用户点空白处、选中的行被删掉或被折叠隐藏都算。模型里的标识对应不到可见的行时,表格取消选中,模型保留原值。配 `unbindSelection()`。 2. **AppKit 自带 diffable 数据源的简写**(已完成):`bind(selection:dataSource:)`,用 `NSTableViewDiffableDataSource` 的两个查找方法。 -3. **大纲的展开状态**:`NSOutlineView.bind(expandedItems:itemIdentifier:)`,绑定一个标识的 `Set`。模型变了就从上到下逐行展开或折叠,展开父项后露出的子项接着处理;用户展开或折叠(大纲发出展开、折叠的通知)时把标识加进或移出集合。配 `unbindExpandedItems()`。 +3. **大纲的展开状态**(已完成):`NSOutlineView.bind(expandedItems:itemIdentifier:)`,绑定一个标识的 `Set`。模型变了就从上到下逐行展开或折叠,展开父项后露出的子项接着处理;用户展开或折叠(大纲发出展开、折叠的通知)时把标识加进或移出集合。配 `unbindExpandedItems()`。 4. **文档与验证**:DocC 首页「绑定」一组登记 `NSTableView`、`NSOutlineView`;`swift-navigation-bindings` skill 补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 没有询问就采用的假设: diff --git a/Sources/AppKitNavigation/Bindings/NSOutlineView.swift b/Sources/AppKitNavigation/Bindings/NSOutlineView.swift new file mode 100644 index 0000000000..c958424cbd --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSOutlineView.swift @@ -0,0 +1,118 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +@_spi(Internals) public import SwiftNavigation +public import AppKit + +extension NSOutlineView { + /// Establishes a two-way connection between a binding and the items the outline has expanded. + /// + /// The binding holds the identifiers of the expanded items, and `itemIdentifier` finds the + /// identifier of the item in a row; a diffable data source has it: + /// + /// ```swift + /// outlineView.bind( + /// expandedItems: $model.expandedItems, + /// itemIdentifier: dataSource.itemIdentifier(forRow:) + /// ) + /// ``` + /// + /// When the binding changes, the outline expands and collapses its items row by row from the + /// top, so an item whose parent the binding also expands is expanded once its row shows. When + /// the user expands or collapses an item, its identifier is inserted into the set or removed + /// from it. Expanding and collapsing for the binding writes nothing back. + /// + /// The items are matched again whenever the binding changes, and whenever observable state + /// that `itemIdentifier` reads changes. Items a diffable data source adds later should carry + /// their expansion in the snapshot. + /// + /// - Parameters: + /// - expandedItems: The binding to read from for the expanded items, and write to when the + /// user expands or collapses an item. + /// - itemIdentifier: The identifier of the item in a row, or `nil` when the row has none. + /// - Returns: A cancel token. + @discardableResult + public func bind( + expandedItems: UIBinding>, + itemIdentifier: @escaping (Int) -> ItemIdentifier? + ) -> ObserveToken { + unbindExpandedItems() + let isApplying = LockIsolated(false) + let token = observe { [weak self] in + guard let self else { return } + let identifiersToExpand = expandedItems.wrappedValue + isApplying.withLock { $0 = true } + defer { isApplying.withLock { $0 = false } } + // NB: The row count is read again on every pass: expanding an item shows its children + // right below it, which is where the loop goes next. + var row = 0 + while row < numberOfRows { + if let item = item(atRow: row), isExpandable(item), + let identifier = itemIdentifier(row) + { + let shouldExpand = identifiersToExpand.contains(identifier) + if shouldExpand, !isItemExpanded(item) { + expandItem(item) + } else if !shouldExpand, isItemExpanded(item) { + collapseItem(item) + } + } + row += 1 + } + } + let expandObserver = NotificationObserver( + name: NSOutlineView.itemDidExpandNotification, object: self + ) { [weak self] notification in + guard let self, isApplying.withLock({ !$0 }), + let identifier = identifier(ofItemIn: notification, using: itemIdentifier), + !expandedItems.wrappedValue.contains(identifier) + else { return } + expandedItems.wrappedValue.insert(identifier) + } + let collapseObserver = NotificationObserver( + name: NSOutlineView.itemDidCollapseNotification, object: self + ) { [weak self] notification in + guard let self, isApplying.withLock({ !$0 }), + let identifier = identifier(ofItemIn: notification, using: itemIdentifier), + expandedItems.wrappedValue.contains(identifier) + else { return } + expandedItems.wrappedValue.remove(identifier) + } + let observationToken = ObserveToken { + token.cancel() + MainActor._assumeIsolated { + expandObserver.invalidate() + collapseObserver.invalidate() + } + } + expandedItemsToken = observationToken + return observationToken + } + + /// Removes the binding established with + /// ``AppKit/NSOutlineView/bind(expandedItems:itemIdentifier:)``. + public func unbindExpandedItems() { + expandedItemsToken?.cancel() + expandedItemsToken = nil + } + + /// The identifier of the item an expansion or a collapse notification is about. + private func identifier( + ofItemIn notification: Notification, + using itemIdentifier: (Int) -> ItemIdentifier? + ) -> ItemIdentifier? { + guard let item = notification.userInfo?["NSObject"] else { return nil } + let row = row(forItem: item) + return row >= 0 ? itemIdentifier(row) : nil + } + + private var expandedItemsToken: ObserveToken? { + get { objc_getAssociatedObject(self, Self.expandedItemsTokenKey) as? ObserveToken } + set { + objc_setAssociatedObject( + self, Self.expandedItemsTokenKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + + private static let expandedItemsTokenKey = malloc(1)! +} +#endif diff --git a/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift index ce0c23a7e4..2e1184a8ee 100644 --- a/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift +++ b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift @@ -135,8 +135,56 @@ #expect(selection == nil) } + // MARK: - Expansion + + @Test("an outline view's expanded items stay in step with their binding") + func expandedItemsStayInStep() async { + let tree = Tree.nestedFruitsAndVegetables + let outlineView = makeOutlineView(dataSource: tree) + @UIBinding var expandedItems: Set = ["Fruits", "Citrus"] + bindExpandedItems($expandedItems, of: outlineView) + // NB: Citrus only has a row once Fruits is expanded. + #expect(outlineView.isItemExpanded(tree.node(named: "Fruits"))) + #expect(outlineView.isItemExpanded(tree.node(named: "Citrus"))) + #expect(!outlineView.isItemExpanded(tree.node(named: "Vegetables"))) + + expandedItems = ["Citrus", "Vegetables"] + await Task.yield() + #expect(!outlineView.isItemExpanded(tree.node(named: "Fruits"))) + #expect(outlineView.isItemExpanded(tree.node(named: "Vegetables"))) + + // NB: What the outline does when the user clicks a disclosure triangle. + outlineView.expandItem(tree.node(named: "Fruits")) + #expect(expandedItems == ["Fruits", "Citrus", "Vegetables"]) + + outlineView.collapseItem(tree.node(named: "Vegetables")) + #expect(expandedItems == ["Fruits", "Citrus"]) + } + + @Test("unbinding an outline view's expanded items stops writing to the binding") + func unbindingTheExpandedItemsStopsWriting() { + let tree = Tree.nestedFruitsAndVegetables + let outlineView = makeOutlineView(dataSource: tree) + @UIBinding var expandedItems: Set = [] + bindExpandedItems($expandedItems, of: outlineView) + + outlineView.unbindExpandedItems() + outlineView.expandItem(tree.node(named: "Fruits")) + + #expect(expandedItems.isEmpty) + } + // MARK: - Helpers + private func bindExpandedItems(_ expandedItems: UIBinding>, of outlineView: NSOutlineView) { + outlineView.bind( + expandedItems: expandedItems, + itemIdentifier: { [weak outlineView] row in + (outlineView?.item(atRow: row) as? Node)?.name + } + ) + } + private func bindSelection( _ selection: UIBinding, of outlineView: NSOutlineView, in tree: Tree ) { @@ -218,6 +266,15 @@ ]) } + /// Fruits, with Apple and Citrus inside and Lemon inside Citrus, then Vegetables, with Carrot + /// inside. + static var nestedFruitsAndVegetables: Tree { + Tree([ + Node("Fruits", children: [Node("Apple"), Node("Citrus", children: [Node("Lemon")])]), + Node("Vegetables", children: [Node("Carrot")]), + ]) + } + func node(named name: String) -> Node? { var pending = roots while let node = pending.popLast() { From 765954c56da50762893ff12fd984bef9383a7960 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 00:06:37 +0800 Subject: [PATCH 091/141] docs(appkit): list the table and outline bindings and record that they are implemented Add NSTableView and NSOutlineView to the bindings group of the documentation. Mark bind(selection:dataSource:) available from macOS 11, since the manifests for Swift 6.2 and earlier still support macOS 10.15, and import AppKit publicly in the new tests for compilers older than 6.4, which treat the test data sources' conformances as public. Record the verification and the follow-ups in the proposal. --- .../draft-appkit-table-selection-bindings.md | 15 +++++++++++++-- .../AppKitNavigation/Bindings/NSTableView.swift | 3 +++ .../Documentation.docc/AppKitNavigation.md | 2 ++ .../TableSelectionBindingTests.swift | 8 +++++++- 4 files changed, 25 insertions(+), 3 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md index b443ae159a..9a05a0ff47 100644 --- a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md +++ b/Documentations/Evolutions/draft-appkit-table-selection-bindings.md @@ -2,7 +2,7 @@ - **状态**: In Progress - **创建日期**: 2026-11-05 -- **最后更新**: 2026-11-05 +- **最后更新**: 2026-11-06 - **实现分支**: `appkit-table-selection-bindings` ## 摘要 @@ -35,7 +35,10 @@ outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource 1. **单选绑定**(已完成):`NSTableView.bind(selection:row:itemIdentifier:)`,绑定一个可选的标识。模型变了就按 `row` 找到行选中;用户改了选中(表格发出选中变化的通知),就按 `itemIdentifier` 查出标识写回。绑定自己选行时发出的通知不写回。表格变成没有选中行时写回 `nil`——用户点空白处、选中的行被删掉或被折叠隐藏都算。模型里的标识对应不到可见的行时,表格取消选中,模型保留原值。配 `unbindSelection()`。 2. **AppKit 自带 diffable 数据源的简写**(已完成):`bind(selection:dataSource:)`,用 `NSTableViewDiffableDataSource` 的两个查找方法。 3. **大纲的展开状态**(已完成):`NSOutlineView.bind(expandedItems:itemIdentifier:)`,绑定一个标识的 `Set`。模型变了就从上到下逐行展开或折叠,展开父项后露出的子项接着处理;用户展开或折叠(大纲发出展开、折叠的通知)时把标识加进或移出集合。配 `unbindExpandedItems()`。 -4. **文档与验证**:DocC 首页「绑定」一组登记 `NSTableView`、`NSOutlineView`;`swift-navigation-bindings` skill 补上新绑定。每种绑定先写双向测试再实现;Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 +4. **文档与验证**(已完成): + - DocC 首页「绑定」一组登记了 `NSTableView`、`NSOutlineView`;生成文档没有新的 DocC 警告,仍是与上游共用内容的那 3 条。`swift-navigation-bindings` skill 补上了新绑定和一条常见错误。 + - 每种绑定先写双向测试再实现,测试在 `Tests/AppKitNavigationTests/TableSelectionBindingTests.swift`,共 9 条,含普通数组、diffable 数据源、对象树的大纲、折叠父项清空选中、嵌套展开。 + - Xcode 27.2 上全量 `swift test` 只有已知的 `ButtonStateTests.testAsyncAnimationWarning` 失败;AppKit 的 Swift Testing 58 条(含 2 条故意触发的已知问题)、XCTest 16 条全部通过。Xcode 26.6 编过 AppKit 的测试 target;Xcode 27.2 全新构建,本包代码零警告。 没有询问就采用的假设: @@ -46,6 +49,11 @@ outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource - 数据重新加载后,绑定在两种情况下重新对一次选中和展开:绑定的值变了,或者 `row`、`itemIdentifier` 闭包里读到的可观察状态变了。diffable 数据源应用快照时,表格自己会让选中跟着条目走;新条目的展开状态应该放进快照里。 - 只改 fork 独有的 AppKitNavigation;各项目改用新绑定不在这一批。 +## 后续项 + +- 多选(绑定一个 `Set`)和 `NSCollectionView` 的选中这次没做。 +- 各项目要用,得先给 fork 打一个包含它们的新版本,再把约 20 处手写的选中同步换掉。 + ## 决策日志 | 日期 | 决定 | 理由 | @@ -54,3 +62,6 @@ outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource | 2026-11-05 | 表格变成没有选中行时,模型写回 `nil` | 用户选定。模型如实反映表格;XCOrganizer「折叠后把选中移到父项」这类逻辑改由模型自己处理 | | 2026-11-05 | 一起做大纲的展开状态绑定;多选、`NSCollectionView` 的选中以后再说 | 用户选定 | | 2026-11-05 | 用户批准,开始实现 | | +| 2026-11-06 | `bind(selection:dataSource:)` 标 `@available(macOS 11, *)` | Swift 6.2 及更早用的包清单最低支持 macOS 10.15,早于 diffable 数据源;Xcode 26.6 编译时报错 | +| 2026-11-06 | 测试文件在编译器低于 6.4 时公开导入 `AppKit` | 与 0002 的 trait 同一个 Swift 6.2 毛病:测试里私有数据源类对 AppKit 协议的遵循被当成公开的 | +| 2026-11-06 | 实现完成,待用户看过后收尾 | 四步全部完成。文档判断:不需要使用指南或实现说明,用法写在各绑定的文档注释和 `swift-navigation-bindings` skill 里,取舍写在本提案里;README 不用改;没有新术语 | diff --git a/Sources/AppKitNavigation/Bindings/NSTableView.swift b/Sources/AppKitNavigation/Bindings/NSTableView.swift index b9a5dc3c25..4f00d3107f 100644 --- a/Sources/AppKitNavigation/Bindings/NSTableView.swift +++ b/Sources/AppKitNavigation/Bindings/NSTableView.swift @@ -90,6 +90,9 @@ extension NSTableView { /// selection changes. /// - dataSource: The table's diffable data source. /// - Returns: A cancel token. + // NB: The manifests for Swift 6.2 and earlier support macOS releases before diffable data + // sources. + @available(macOS 11, *) @discardableResult public func bind( selection: UIBinding, diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 6d05a6a482..9adecefabb 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -45,6 +45,8 @@ popovers follow optional state: they are presented when it gains a value, dismis - ``AppKit/NSPopUpButton`` - ``AppKit/NSSegmentedControl`` - ``AppKit/NSProgressIndicator`` +- ``AppKit/NSTableView`` +- ``AppKit/NSOutlineView`` - ``AppKit/NSMenuItem`` - ``AppKit/NSSplitViewItem`` - ``AppKit/NSTabViewController`` diff --git a/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift index 2e1184a8ee..35ffaf2fee 100644 --- a/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift +++ b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift @@ -1,5 +1,11 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - import AppKit + #if compiler(<6.4) + // NB: Swift 6.2 treats the data sources' conformances below as public, and a public + // conformance needs a public import. + public import AppKit + #else + import AppKit + #endif import AppKitNavigation import Testing From 09efa19416a016403a5cb8db5311b938c0d431c4 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 00:13:05 +0800 Subject: [PATCH 092/141] docs: number the table selection bindings proposal 0004 and mark it implemented --- ...n-bindings.md => 0004-appkit-table-selection-bindings.md} | 5 +++-- Documentations/Evolutions/README.md | 2 +- Documentations/README.md | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) rename Documentations/Evolutions/{draft-appkit-table-selection-bindings.md => 0004-appkit-table-selection-bindings.md} (94%) diff --git a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md b/Documentations/Evolutions/0004-appkit-table-selection-bindings.md similarity index 94% rename from Documentations/Evolutions/draft-appkit-table-selection-bindings.md rename to Documentations/Evolutions/0004-appkit-table-selection-bindings.md index 9a05a0ff47..2ca444eb64 100644 --- a/Documentations/Evolutions/draft-appkit-table-selection-bindings.md +++ b/Documentations/Evolutions/0004-appkit-table-selection-bindings.md @@ -1,6 +1,6 @@ -# Draft - 表格与大纲的选中绑定、大纲的展开状态绑定 +# 0004 - 表格与大纲的选中绑定、大纲的展开状态绑定 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-05 - **最后更新**: 2026-11-06 - **实现分支**: `appkit-table-selection-bindings` @@ -65,3 +65,4 @@ outlineView.bind(expandedItems: $model.expandedItems, itemIdentifier: dataSource | 2026-11-06 | `bind(selection:dataSource:)` 标 `@available(macOS 11, *)` | Swift 6.2 及更早用的包清单最低支持 macOS 10.15,早于 diffable 数据源;Xcode 26.6 编译时报错 | | 2026-11-06 | 测试文件在编译器低于 6.4 时公开导入 `AppKit` | 与 0002 的 trait 同一个 Swift 6.2 毛病:测试里私有数据源类对 AppKit 协议的遵循被当成公开的 | | 2026-11-06 | 实现完成,待用户看过后收尾 | 四步全部完成。文档判断:不需要使用指南或实现说明,用法写在各绑定的文档注释和 `swift-navigation-bindings` skill 里,取舍写在本提案里;README 不用改;没有新术语 | +| 2026-11-06 | Implemented,编号 0004,落地到 `main` | 用户看过后要求收尾。四步全部完成;多选、`NSCollectionView` 的选中和给 fork 打新版本留在后续项。文档判断同上一行,没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 397de8f223..adea28e49a 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -9,4 +9,4 @@ | 0001 | [AppKitNavigation 清理:警告、重复代理和多余依赖](0001-appkit-navigation-cleanup.md) | Implemented | | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | -| draft | [表格与大纲的选中绑定、大纲的展开状态绑定](draft-appkit-table-selection-bindings.md) | In Progress | +| 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index b606dc5baa..ed9ec6d876 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -8,7 +8,7 @@ - [0001-appkit-navigation-cleanup.md](Evolutions/0001-appkit-navigation-cleanup.md):AppKitNavigation 清理——警告、重复代理和多余依赖。 - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 -- [draft-appkit-table-selection-bindings.md](Evolutions/draft-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 +- [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 ## Internal From 51eda426b3901fcd54c55149abca7f2c06f4735b Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 22:13:34 +0800 Subject: [PATCH 093/141] docs: propose redesigning the AppKit presentation APIs Move the lifecycle of modals, sheets, popovers and presented view controllers into one shared layer, fix the defects a review of that code found, and merge the per-content overloads behind a public ModalContent protocol. --- Documentations/Evolutions/README.md | 1 + .../draft-appkit-presentation-redesign.md | 382 ++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 384 insertions(+) create mode 100644 Documentations/Evolutions/draft-appkit-presentation-redesign.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index adea28e49a..39e68dbbdf 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -10,3 +10,4 @@ | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | | 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | +| draft | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](draft-appkit-presentation-redesign.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md new file mode 100644 index 0000000000..5e4586dd53 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -0,0 +1,382 @@ +# Draft - AppKit 弹出 API 重做:生命周期收进一层,重载合并 + +- **状态**: Accepted +- **作者**: JH +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-06 +- **所属愿景**: 无 +- **关联提案**: [0001 - AppKitNavigation 清理](0001-appkit-navigation-cleanup.md)(把这次重构留给了单独的完整档提案) +- **实现分支 / PR**: `appkit-presentation-redesign` +- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 + +## 摘要 + +把 AppKitNavigation 的弹出 API(`modal`、`modalSession`、`sheet`、`popover`、`present`)重做成「一层通用代码管生命周期,各弹出方式只写怎么弹、怎么关」。新的通用层在内容显示期间强持有它;换 id 时先等旧内容下屏再弹新的;`onDismiss` 每次恰好调用一次,在内容下屏之后;宿主释放时收起内容;锚点还没显示时等它显示再弹。modal 可以叠在 modal 上,不再误停别人的模态循环、误关别人的 sheet。公开 API 同时收敛:参数标签统一为 `isPresented:`,删掉与 `present(style: .sheet)` 重复的 `NSViewController.sheet`,modal 和 sheet 的内容合并到公开协议 `ModalContent`,公开重载从 58 个降到 33 个。起因是审查这块代码读出 8 个问题,其中 5 个行为缺陷都出在同一个结构上:每种弹出方式各写一遍替换和收尾。 + +## 动机 + +### 读出的问题 + +都在 `main` 上,不是最近的改动引入的。都是读代码确认的,运行时由落地第 1 步的测试坐实;本机依赖这个 fork 的 7 个项目都还没踩到(见「下游影响」)。 + +| # | 问题 | 怎么触发 | 原因 | 以前修过吗 | +|---|---|---|---|---| +| 1 | popover 被用户关掉时不调用 `onDismiss` | 点外部或按 Esc 关掉 popover:binding 复位了,回调不来 | `Navigated` 弱引用内容(`Sources/AppKitNavigation/Navigation/NavigationObserver.swift:85`);`_PopoverPresentation` 只被关闭通知的订阅持有,通知一到就释放(`Internal/PopoverPresentationsObserver.swift:16-19`);`observe` 在下一拍才重跑(`Sources/SwiftNavigation/NSObject+Observe.swift:135`),找不到内容就跳过 `end`(`NavigationObserver.swift:69-74`),而 `onDismiss` 只在 `end` 里调用。App 没有留着内容对象时,alert、每次新建的窗口和视图控制器同样会漏 | 2026-06 修过同一处「不回写 binding」,当时只管了回写 | +| 2 | 在 modal 里再弹 modal,外层被停掉 | modal 窗口里弹确认 alert:窗口消失、alert 单独出现,还调用了 alert 那个 binding 的 `onDismiss` | 开始时只要有模态窗口就 `stopModal()`(`Navigation/Modal.swift:276-279`),新循环又只在默认模式里启动(`Modal.swift:287`),嵌套本来就起不来;关闭时也不看是谁的就 `stopModal()`(`Modal.swift:300-302`) | 移植时就这样;2026-11-03 修 modal 时保留了 | +| 3 | popover 换了 id,旧的不关 | `popover(item:)` 换成另一项:新旧同时在屏上;`.applicationDefined` 时旧的再也关不掉,也不调用 `onDismiss` | 只有 popover 的开始闭包不处理替换(`Navigation/Popover.swift:247-253`),本该兜底的 `clearup()` 是死代码 | 加 popover 时就这样 | +| 4 | modal 结束后,窗口一直被全局表持有 | alert、被 binding 关掉的窗口都不发关闭通知,`ModalWindowsObserver.shared` 里的条目连同窗口永远留着,每弹一次漏一个 | 条目只在 `willClose` 时移除(`Internal/ModalWindowsObserver.swift:29-41`),而 alert 和被停掉的模态只是 `orderOut` | 没修过 | +| 5 | 替换时不分来源 | 新 sheet 会关掉窗口上别的 binding 或 App 自己弹的 sheet;`modalSession` 会关掉本库开的任何会话窗口;`present` 会关掉第一个被弹出的视图控制器;三处都调用本 binding 的 `onDismiss` | `Sheet.swift:262-264`、`Modal.swift:360-365`、`Presentation.swift:74-77` 都只看「现在有没有」,不看是谁弹的 | `present` 那处 2026-11-03 记进[裁决清单](../Internal/ReviewDecisions.md)暂缓,复查条件就是这次重构 | +| 6 | 带 `id:` 的绑定版重载少了 `@_disfavoredOverload` | 闭包写成 `{ _ in … }` 时两个重载都能用,编译报歧义 | `Modal.swift:52、105、158、211`,`Sheet.swift:49、99、149、199`,`Popover.swift:116、384`;UIKit 版(`Sources/UIKitNavigation/Navigation/Presentation.swift:123`)和本库的 `present` 都标了 | 没修过 | +| 7 | 视图控制器的 sheet 有两套实现 | `sheet(isSheeted:)` 不等视图出现就弹,`present(style: .sheet)` 会等;同一件事两套代码 | `Sheet.swift:160-208` 与 `Presentation.swift` 各走一条路 | 2026-11-03 修「用户关闭不回写」时两边各修了一遍 | +| 8 | alert 和存取面板作为 sheet 时没走它们自己的 API | `window.sheet { NSAlert() }` 用 `NSWindow.beginSheet(alert.window)` 弹出,没调用 `beginSheetModal(for:)`:alert 可能没排版、按钮可能关不掉 sheet,存取面板同理(具体症状待测试坐实) | 默认实现把父窗口当接收者(`Navigation/SheetContent.swift:18-21`),`NSAlert`、`NSSavePanel` 自己的实现(`SheetContent.swift:33-55`)永远走不到 | 没修过;起草本提案时发现 | + +### 结构上的问题 + +- **重复**:四个文件共 1,485 行。公开重载 58 个:`modal` 15 个、`modalSession` 5 个、`NSWindow.sheet` 15 个、`NSViewController.sheet` 5 个、`popover` 10 个、`present` 5 个、`destination` 3 个。每个公开重载先转给同形的 `fileprivate` 重载,再转给私有核心,一共三层。 +- **生命周期分散**:替换、收尾、`onDismiss` 由各弹出方式的开始和结束闭包各写一遍,通用的 `NavigationObserver` 只负责比对 binding。缺陷 1–5 都出在这里。 +- **死代码**:`Navigated` 的四个 `clearup()`(裁决清单里的暂缓项:泛型类的 `deinit` 只会调用类里那份空实现)、`onBeginNavigation`、`PresentationContent` 协议及其两个方法。 +- **机制杂**:每次弹出的状态挂在内容对象的关联对象上,按类型分 key(`AssociatedKeys`);有两个全局单例(`ModalWindowsObserver`、`PopoverPresentationsObserver`);调度方式有五种(run loop 块、`DispatchQueue.main.async`、`Task`、continuation、Combine 订阅),先后顺序全靠隐含约定,2026-11-03 那次「binding 停不掉 modal」就是其中两种的顺序问题。 +- **API 不一致**:标签 `isModaled`、`isSheeted` 与 `popover`、`present` 的 `isPresented` 不一致;公开 API 都没有文档注释。 + +### 为什么现在做 + +- 0001 清理时把「弹出三个文件的重载收敛连同 `clearup()` 死代码」留给了单独的完整档提案;裁决清单里两条暂缓项的复查条件也是这次重构。 +- 下游只有 5 处调用,而且都不受这次的破坏性改动影响,这是改公开 API 代价最低的时候。 + +## 前期调研 + +- **现状代码怎么走的**: + - 公开重载 → `fileprivate` 同形重载 → 私有核心 → `xxxObserver()` 取出挂在宿主上的 `NavigationObserver`(每种内容类型一个)→ `NavigationObserver.observe(item:id:content:begin:end:)`(`NavigationObserver.swift:17-76`)。 + - 用户自己关掉内容时,靠挂在内容对象上的 `onEndNavigation` 闭包写回 binding;各方式报告「结束」的途径各不相同:modal 是 `runModal` 返回,modalSession 是窗口的 `willClose`,sheet 是 `beginSheet` 的 async 返回,popover 是 `didCloseNotification`,`present` 是 shim 在 `viewDidDisappear` 里报告的 dismiss。 + - `observe` 的重跑走 `DispatchQueue.main.async`(`NSObject+Observe.swift:134-136`),所以用户关闭后,binding 的写回要到下一拍才被看到。 +- **上游是否已有**:没有。`upstream/main`(2026-08-31)的 `Sources/AppKitNavigation` 下没有 `Navigation` 目录,这些弹出 API 都是 fork 独有的,改名不影响合并上游。 +- **前人怎么做的**: + - UIKit 版(`Sources/UIKitNavigation/Navigation/Presentation.swift`):用一个 presenter 标记区分「是不是自己弹的」再决定是否替换,`onDismiss` 在 `dismiss(animated:)` 的完成回调里调用(下屏之后);用户关闭时用 `inFlightController` 临时强引用被关的控制器,保证下一拍还能收尾;宿主释放时 `Presented.deinit` 收起内容;`UIBinding` 版重载都标了 `@_disfavoredOverload`。 + - SwiftUI 的 `sheet(isPresented:onDismiss:content:)`、`popover(isPresented:)` 用名词作基名、`isPresented:` 作标签,内容是泛型 `Content: View`。 +- **AppKit 的事实**(macOS 27.2 SDK): + - 窗口已有 sheet 时,`beginSheet` 会排队,等前一个结束才显示;critical sheet 跳过排队(`NSWindow.h:581-582`)。 + - `NSView.window` 声明为 `unsafe_unretained`,没有标注支持 KVO;进出窗口只能靠覆写点 `viewWillMoveToWindow:` / `viewDidMoveToWindow`(`NSView.h:86、107-108`)。 + - 窗口显示与否可以从 `occlusionState` 和 `NSWindowDidChangeOcclusionStateNotification` 得知(`NSWindow.h:638、985`)。 + - `NSAlert`、`NSSavePanel` 有自己的 `beginSheetModal(for:completionHandler:)` 和 `runModal()`;`NSApplication.runModal(for:)` 可以嵌套。 +- **下游用法**(在本机依赖这个 fork 的 7 个项目里搜过):XCOrganizer 的 `MainWindowController.swift:94、103` 用 `NSWindow.sheet(item:)`,内容是窗口;SymbolViewer 的 `MainSplitViewController.swift:50、62` 和 ApplicationScaffold 模板的 `MainViewController.swift:46` 用 `present(isPresented:style: .sheet)`。`modal`、`modalSession`、`popover`、`NSViewController.sheet`、`isModaled`、`isSheeted`、`onDismiss` 都没有人用。 +- **现有测试**:`ModalPresentationTests` 3 条、`ViewControllerPresentationTests` 5 条;popover、alert 和存取面板、`onDismiss`、换 id 都没有测试。 +- **验证过什么**:目前只读了代码和 git 历史,还没在运行时复现。曾怀疑 popover 的锚点视图不在窗口里时 AppKit 会抛异常,但在 macOS 27.2 的 AppKit 里没搜到对应的断言文字,没有坐实,不作为动机。 + +## 提议方案 + +**一层通用代码管生命周期**,每次调用 `modal`、`sheet`、`popover`、`present` 各建一个,由宿主持有: + +- 内容在显示期间被强持有,直到它下屏,不再依赖「App 有没有留着它」。 +- binding 有值时,先等锚点能显示内容,再建内容、弹出;还没显示就被复位的,直接取消,不调用 `onDismiss`。 +- 换 id 时,先请旧内容下屏,等它真正下屏、调用过 `onDismiss`,再弹新的。 +- `onDismiss` 每次弹出恰好调用一次,在内容下屏之后,不论是用户关的、binding 关的、换 id 替换的,还是宿主释放收起的。用户关的,先把 binding 写回 `nil`,再调用 `onDismiss`。 +- 宿主释放时,收起正在显示的内容。取消返回的 token 只是不再跟随 binding:内容留到用户关闭,那时仍写回 binding、调用 `onDismiss`。 +- 只动自己弹出的内容:窗口上已经有别人的 sheet 时,交给 AppKit 排队;要关的 modal 上面还叠着别的模态时,等上面那些先结束。 + +**各弹出方式只写「怎么弹、怎么关」**: + +- `modal` 的模态循环可以在外层模态循环里启动,叠在上面;结束时只停自己的循环。 +- `sheet` 让内容用它自己的 API 弹出:窗口用 `beginSheet`,alert 和存取面板用 `beginSheetModal(for:)`。 +- popover 用每次弹出各自的通知观察代替全局单例;`animates` 同时参考参数和 transaction 的 `appKit.disablesAnimations`。窗口 sheet、模态窗口和视图控制器的弹出,AppKit 没有关动画的公开办法,照常带动画。 +- `present` 保持现有的「等 `viewDidAppear`」;窗口等它显示出来;视图等它进窗口、窗口显示出来;工具栏项等它所在的窗口显示出来。 + +**公开 API 收敛**: + +- 参数标签统一为 `isPresented:`:`modal(isPresented:)`、`modalSession(isPresented:)`、`NSWindow.sheet(isPresented:)`。 +- 删掉 `NSViewController.sheet`,视图控制器的 sheet 一律用 `present(…, style: .sheet)`。 +- modal 和 `NSWindow.sheet` 的内容改为泛型 `Content: ModalContent`。`ModalContent` 是公开协议,`NSWindow`(以及所有面板)和 `NSAlert` 遵循;协议要求带下划线、不出现在文档里,不作为给 App 扩展用的入口。取这个名字,是因为 AppKit 把 sheet 也算作一种模态(document-modal)。 +- `UIBinding` 版重载都标 `@_disfavoredOverload`;泛型参数写完整的 `Identifier`(调用方看不到,不影响源码兼容)。 +- 公开 API 全部补上文档注释。 +- 不保留旧名:保留旧名会让重载翻倍,而下游没有调用点会受影响。 + +### 非目标 + +- 不新增弹出方式,例如 `NSPrintPanel` 或 `NSPageLayout`。 +- 不把 `ModalContent` 或内部的弹出方式开放成扩展点;视图控制器的自定义转场继续用 `destination`。 +- 不改 `NSViewController.TransitionStyle` 的成员,不改 `destination` 的签名。 +- 不碰与上游共用的 `SwiftNavigation`、UIKit、SwiftUI 部分。 +- 不发版;发版另外决定。 +- `present(style: .popover)` 在 transient popover 被点外部关闭时的回写,单元测试里仍然没法模拟,裁决清单里那条「未在运行时验证」照旧保留。 + +## 详细设计 + +### 公开 API + +```swift +/// Content that AppKit shows in a window of its own — a window, an alert, or a save or open +/// panel — either attached to another window as a sheet, or run as an application-modal window. +/// +/// `NSWindow`, and through it every panel, conforms, as does `NSAlert`. The requirements are +/// implementation details of AppKitNavigation; conforming other types is not supported. +@MainActor +public protocol ModalContent: AnyObject { + @_documentation(visibility: private) + var _appKitNavigationWindow: NSWindow { get } + + @_documentation(visibility: private) + func _appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) + + @_documentation(visibility: private) + func _appKitNavigationRunModal() +} + +// Save and open panels take their own `beginSheetModal(for:)` and `runModal()`, chosen inside the +// window's implementation. +extension NSWindow: ModalContent { /* … */ } +extension NSAlert: ModalContent { /* … */ } + +@MainActor +extension NSObject { + @discardableResult + public func modal( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken + + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken + + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken + + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken + + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken + + // `modalSession` has the same five shapes. Its content stays a plain `NSWindow`: a modal session + // needs a window that the app runs itself, which an alert or a panel is not. + @discardableResult + public func modalSession( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken +} + +extension NSWindow { + // The same five shapes as `modal`, generic over `Content: ModalContent`. + @discardableResult + public func sheet( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken +} +``` + +`NSView.popover`、`NSToolbarItem.popover`、`NSViewController.present` 和 `destination` 的签名不变,只给 `UIBinding` 版补 `@_disfavoredOverload`、把泛型参数 `ID` 写成 `Identifier`。 + +改完后的调用点: + +```swift +window.sheet(isPresented: $model.isConfirmingDelete) { makeDeleteAlert() } +window.sheet(item: $model.tagEditor) { editor in TagEditor.makeWindow(viewModel: editor) } +modal(item: $model.failure) { failure in NSAlert(error: failure) } +present(isPresented: $model.isSettingsPresented, style: .sheet) { SettingsViewController() } +view.popover(isPresented: $model.isInfoShown, preferredEdge: .maxY) { InfoViewController() } +``` + +### 生命周期(内部) + +```swift +/// One way of showing content: as a sheet, a modal loop or session, a popover, or a presented +/// view controller. +@MainActor +protocol PresentationStyle { + associatedtype Content: AnyObject + + /// Calls `body` once the anchor can show content: right away when it already can, otherwise + /// once it gets on screen. Returns a closure that cancels a wait that is no longer wanted. + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void + + /// Shows `content` and calls `didEnd` exactly once, after the content has left the screen, + /// whatever ended it. + func begin( + _ content: Content, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) + + /// Asks `content` to leave the screen, which leads to the `didEnd` passed to `begin`. Works + /// from the content's side, so that it still works while the owner is being deallocated. + func end(_ content: Content, transaction: UITransaction) +} + +/// Shows content while a binding holds a value: one per call of `modal`, `sheet`, `popover` or +/// `present`, kept alive by the object it was called on. +@MainActor +final class BindingPresenter { + init(style: Style, onDismiss: (() -> Void)?) + + func observe( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> Style.Content + ) -> ObserveToken +} +``` + +`BindingPresenter` 的状态转换: + +| 状态 | binding 有值 | binding 变成 `nil` | `didEnd` 到来 | 宿主释放 | +|---|---|---|---|---| +| 空闲 | 等锚点就绪,就绪后建内容、`begin`,进入「显示中」 | — | — | — | +| 等就绪 | 记下最新的值,就绪时用它 | 取消等待,回到空闲;没显示过,不调用 `onDismiss` | — | 取消等待 | +| 显示中 | id 相同不动;id 不同就 `end` 旧内容,记下新值,进入「结束中」 | `end`,进入「结束中」 | 用户关的:id 仍相符就写回 `nil`,调用 `onDismiss`,回到空闲 | `end`,进入「结束中」 | +| 结束中 | 更新记下的新值 | 清掉记下的新值 | 调用 `onDismiss`;有记下的新值就去「等就绪」,否则回到空闲 | 不再接受新值 | + +`didEnd` 同步地把状态改回空闲,所以「用户关闭写回 `nil` 后,同一拍里 binding 又被设回有值」不再需要现在的 `hasEnded` 标记:下一次重跑看到的就是空闲加有值,照常弹出。 + +### 各弹出方式 + +| 方式 | 锚点就绪 | 开始 | `didEnd` 的来源 | `end` | +|---|---|---|---|---| +| `modal` | 立即 | 在默认和模态面板两种 run loop 模式里排一个块,块里调用 `_appKitNavigationRunModal()`;窗口被关闭且它是最上层模态时 `stopModal()` | 模态循环返回、窗口已下屏 | 是最上层模态就 `stopModal()`;否则挂一个 run loop 观察者,在每次等待前检查,轮到自己时再停 | +| `modalSession` | 立即 | `beginModalSession(for:)` | 窗口关闭、会话结束 | 是最上层就关窗口;否则同上,等轮到自己 | +| `NSWindow.sheet` | 父窗口显示出来 | `_appKitNavigationBeginSheet(attachedTo:completionHandler:)`;父窗口已有别的 sheet 时由 AppKit 排队 | AppKit 的 completion handler | `sheetParent?.endSheet(_:)`;还在排队的 sheet 怎么撤,实现时先测 | +| `NSView.popover` | 视图进了窗口,且窗口显示出来 | 新建 `NSPopover` 并显示 | `NSPopover.didCloseNotification` | `close()` | +| `NSToolbarItem.popover` | 工具栏所在的窗口显示出来 | 同上,用 `show(relativeTo:)` | 同上 | 同上 | +| `present` / `destination` | `viewDidAppear`(shim 现有的机制) | `present(_:for:)`,或调用方传入的 `present` 闭包 | shim 在 `viewDidDisappear` 里报告的 dismiss | 仍在 `presentedViewControllers` 里才 `dismiss(_:)` | + +- **等窗口显示**:`isVisible` 为真就立即开始;否则在 `NSWindowDidChangeOcclusionStateNotification`、成为 key 或 main 窗口时重新检查。 +- **等视图进窗口**:shim 再交换一个 `-[NSView viewDidMoveToWindow]`,在原实现之后执行挂在这个视图上的回调;视图上没有回调时只多一次关联对象查找。这个方法要加进 `ObjectiveCMethodNamingTests` 的「有意替换」名单。 +- **工具栏项**:从 `NSApp.windows` 里找 `toolbar === item.toolbar` 的窗口,再等它显示;item 还没加进工具栏时,先等 `NSToolbar.willAddItemNotification`。实现时先测 AppKit 在工具栏还没显示时 `show(relativeTo:)` 怎么表现,AppKit 自己能处理就不加这层等待。 +- **嵌套 modal 的顺序**:binding 刚请外层停止、新的 modal 就在它返回前启动时,停止标记应该只属于外层,实现时用测试确认。 + +### 存放与清理 + +- 每个 `BindingPresenter` 存进宿主上的一个数组(一个关联对象)。宿主释放时数组随之释放,`BindingPresenter` 在 `deinit` 里收起正在显示的内容。 +- 每次弹出用到的通知观察(窗口关闭、popover 关闭)用现有的 `NotificationObserver`,挂在那次弹出上,`didEnd` 时注销。不再有全局表,也就没有缺陷 4 那种泄漏。 +- 删除:`NavigationObserver.swift`、`NavigationContent.swift`、`SheetContent.swift`、`PopoverContent.swift`、`PresentationContent.swift`、`Internal/ModalWindowsObserver.swift`、`Internal/PopoverPresentationsObserver.swift`、`Internal/AssociatedKeys.swift`(这三个都只被弹出代码使用),以及 `NSWindow` 上的 `@objc` 方法 `__appKitNavigationRunModal`。 +- 存取面板走自己的 API,由 `NSWindow` 实现里的 `self as? NSSavePanel` 判断。这是实现内部对一个子类的特判,不是对外的能力判断,也免得在 `NSWindow` 上多加 Objective-C 方法。 + +### 测试 + +- 现有行为先补测试,改动前就要通过:每种方式 binding 打开、binding 关闭、用户关闭写回。 +- 8 条问题各一条测试。行为缺陷先用严格模式的 `XCTExpectFailure` 标成预期失败,确认它现在确实失败;修好的那一步去掉标记。第 6 条是编译期问题:只需编译的测试文件在修复那一步加入,加入前先在本地确认它编不过。 +- 新行为各一条测试:嵌套 modal、等锚点显示、`onDismiss` 恰好一次且在下屏后、换 id 的先后顺序、宿主释放收起、取消 token 后用户关闭仍写回。 +- 把下游的调用写法搬进一个只需编译的测试:XCOrganizer 那种多语句、两处 `return` 的闭包,`{ _ in … }`,以及 `{ $item in … }`。 +- 照现有测试的写法,用同步的 XCTest 方法、靠转动主 run loop 等待。机器闲置时动画可能不跑,测试卡住时先用 `caffeinate -u` 排除。 + +## 替代方案考量 + +- **在现有结构上逐条修**:改动小,但 5 个行为缺陷都出在同一个结构上,逐条修完重构时又得重写一遍。用户选择直接重构。 +- **改名但保留旧名过渡**:API 设计规范的默认做法是改名时保留旧名并标 `renamed:`。没有采用:这些 API 是 fork 独有的,下游没有调用点受影响,保留旧名会让重载数量不降反升。 +- **公开 API 一点不动**:标签不一致、重复的 sheet、每种内容各一套重载都会留下来,被否。 +- **嵌套 modal 排队,或拒绝并报警告**:都偏离 AppKit 原生 `runModal` 的嵌套行为,被否。 +- **锚点没显示时不等、只报警告,或保持现状**:「一启动就弹」的场景得由调用方自己推迟,而 `present` 已经在等,被否。 +- **`onDismiss` 在开始关闭时调用,或换 id 替换时不调用**:前者在回调里马上再弹东西,可能和还在退场的内容撞上;后者与 UIKit 版不一致。都被否。 +- **每种内容保留一套重载**:公开重载数量不变,被否。**把 `ModalContent` 开放成扩展点**:App 可以让自己的类型也能弹出,但多一个要长期维护的契约,眼下没有需求,被否。 +- **取消 token 时也收起内容,或宿主释放时也不收起**:前者让取消变成破坏性操作,后者留着 `clearup()` 原本要解决的问题。都被否。 +- **继续弱引用内容,像 UIKit 版那样在用户关闭时临时强引用**:AppKit 这边的 popover 包装和 alert 没有别人持有,弱引用正是缺陷 1 的根源,直接在显示期间强持有更简单。 +- **用 KVO 观察 `NSView.window`**:头文件没有标注它支持 KVO,将来可能悄悄失效,所以改用交换 `viewDidMoveToWindow`。 +- **保留全局单例、只修泄漏**:每次弹出各自观察以后,全局状态就没有存在的理由了。 +- **存取面板沿用 `@objc` 方法加子类覆写**:现在的 `__appKitNavigationRunModal` 就是这么做的,但这要在 `NSWindow` 上加 Objective-C 方法;改成实现内部的类型判断更简单。 + +## 影响 + +### 源码兼容性(source compatibility) + +**有破坏。** 需要修改的调用写法: + +| 改前 | 改后 | +|---|---| +| `modal(isModaled: $flag) { window }` | `modal(isPresented: $flag) { window }` | +| `modalSession(isModaled: $flag) { window }` | `modalSession(isPresented: $flag) { window }` | +| `window.sheet(isSheeted: $flag) { alert }` | `window.sheet(isPresented: $flag) { alert }` | +| `viewController.sheet(isSheeted: $flag) { child }` | `viewController.present(isPresented: $flag, style: .sheet) { child }` | +| `viewController.sheet(item: $item) { item in child(item) }` | `viewController.present(item: $item, style: .sheet) { item in child(item) }` | + +- `modal(item:)`、`NSWindow.sheet(item:)` 的写法不变;内容闭包的返回类型从三种具体类型变成泛型,返回 `NSWindow`、`NSAlert`、`NSSavePanel` 及其子类的调用点照常编译。不同分支返回不同类型的闭包,改前也编不过。 +- 新增公开协议 `ModalContent`,以及 `NSWindow`、`NSAlert` 对它的遵循。 +- 行为变化(不影响编译): + - `onDismiss` 总会调用一次,在下屏之后;之前有时漏调,binding 关闭时则在开始关闭时就调用。 + - 嵌套 modal 不再停掉外层。 + - 新的 sheet 不再关掉别人的 sheet,改由 AppKit 排队。 + - sheet 和 popover 等锚点显示后才弹出。 + - 宿主释放时收起内容。 + - alert 和存取面板作为 sheet 时走它们自己的 API。 + - popover 遵守 transaction 的关动画设置。 +- 不提供 `@available(*, deprecated, renamed:)` 的过渡版本,理由见「API 演进与废弃策略」。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`AppKitNavigation`、`AppKitNavigationShim`(多交换一个 `viewDidMoveToWindow`)、`AppKitNavigationTests`。Examples 里 AppKit 的案例只用 `present(item:id:style:)` 和 `present(isPresented:style:)`,不受影响。 +- 下游仓库:XCOrganizer 的 2 处 `NSWindow.sheet(item:)`、SymbolViewer 的 2 处和 ApplicationScaffold 模板的 1 处 `present(isPresented:style: .sheet)`,写法都不用改。其余 4 个依赖这个 fork 的项目没有用到弹出 API。这些项目在下次重新解析依赖、拿到新版本时,只会碰到上面那些行为变化:XCOrganizer 的 sheet 的 item 初始为 `nil`,等锚点那一条对它没有影响;它们都没有用 `onDismiss`。 + +### 文档与示例 + +- 公开 API 全部补上文档注释,包括 `ModalContent`。 +- DocC 首页(`Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md`)的「Presenting content from state」一组:加上 `ModalContent`,去掉只剩下划线成员的 `AppKit/NSAlert`。 +- `swift-navigation-bindings` skill 里 AppKit 那张表:标签、泛型内容、删掉的 `NSViewController.sheet`;顺带更正 `modalSession` 的内容只能是 `NSWindow`(现在那张表写成了和 `modal` 一样)。 +- [裁决清单](../Internal/ReviewDecisions.md):两条暂缓项(`clearup()` 死代码、`present` 替换时不分来源)随这次修掉,从清单里删除;「transient popover 被点外部关闭时的回写」保留。 +- README 没有提到 AppKit 的弹出 API,不用改。 + +## API 演进与废弃策略 + +- 被替代的旧 API 直接删除,不标 `deprecated`、不设废弃期。理由:这些 API 是 fork 独有的,上游没有;本机依赖这个 fork 的项目没有调用点受影响;保留旧名会让重载数量翻倍,和这次收敛重载的目标相反。这偏离了 API 设计规范「改名时保留旧名并标 `renamed:`」的默认做法,偏离的理由就是上面这几条。 +- 不跃迁 semver major:fork 的版本号跟随上游的 2.11,自己的改动用 100 以上的补丁号(最近一次是 2.11.101)。下一个版本号在发版时再定。 + +## 落地步骤 + +1. **补测试作安全网**:按「测试」一节补现有行为的测试(改动前就通过)和问题的测试(先标预期失败)。 +2. **通用层与 modal**:加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。 +3. **sheet**:`NSWindow.sheet` 改成泛型并迁过去,加上等父窗口显示;删除 `NSViewController.sheet`。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。 +4. **popover**:`NSView` 和 `NSToolbarItem` 的 popover 迁过去,加上等锚点显示(shim 交换 `viewDidMoveToWindow`)和 transaction 的关动画;删除 `PopoverPresentationsObserver`。修掉缺陷 1、3。 +5. **present 与 destination**:迁过去,替换时只动自己弹的。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。 +6. **清理**:删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;给全部 `UIBinding` 版重载补 `@_disfavoredOverload`,加入第 6 条和下游写法的编译测试。 +7. **文档**:按「文档与示例」一节更新文档注释、DocC 首页、`swift-navigation-bindings` skill 和裁决清单。 +8. **完整验证**:Xcode 27.2 跑 AppKit 的全部测试,成败只认原始退出码,弹出相关的测试连跑 10 次;Xcode 26.6 编译库和测试;用 xcodebuild 编译 Examples 里 macOS 版的 CaseStudies。 + +每一步都能单独构建通过、测试全绿:第 2–5 步迁移期间,还没迁的方式继续走旧的 `NavigationObserver`,第 6 步才删除。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 有「从 API 签名看不出来的调用方契约」就写使用指南;有「下次维护会踩、代码本身看不出来的决策」就写实现说明。写了就登记到头部的「配套文档」。候选的实现说明内容:模态循环为什么要在两种 run loop 模式里启动、为什么要等上层模态先结束、内容为什么要强持有。 +- **有没有引入新术语** —— 有就同批次登记进术语表(项目级 `Documentations/Glossary.md`,跨项目通用的登记到全局术语表)。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-06 | Created as Draft | 审查弹出代码读出 8 个问题和大量重复重载;0001 把这块重构留给了单独的完整档提案 | +| 2026-11-06 | 重构而不是逐条修 | 5 个行为缺陷出在同一个结构上,逐条修完重构时又得重写 | +| 2026-11-06 | 公开 API 直接改,不保留旧名 | fork 独有,下游没有调用点受影响;保留旧名会让重载翻倍。偏离 API 设计规范的默认做法,理由记在「API 演进与废弃策略」 | +| 2026-11-06 | modal 可以叠在 modal 上 | 与 AppKit 原生 `runModal` 的嵌套一致;排队、拒绝两种做法被否 | +| 2026-11-06 | 锚点没显示时等它显示再弹 | 与 `present` 的现有行为和 UIKit 版一致;「不等、报警告」「保持现状」被否 | +| 2026-11-06 | `onDismiss` 在下屏后恰好调用一次,换 id 替换也算 | 与 UIKit 版一致;「开始关闭时调用」「替换时不调用」被否 | +| 2026-11-06 | modal 与 sheet 的内容合并到公开协议 `ModalContent`,要求带下划线 | 每个动词从 15 个重载降到 5 个;开放成扩展点、保留每种一套被否 | +| 2026-11-06 | 宿主释放时收起内容,取消 token 不收起 | 补上 `clearup()` 原本要做的事,与 UIKit 版一致;「两种都收起」「都不收起」被否 | +| 2026-11-06 | 其余默认做法经用户确认 | 强持有内容、换 id 的顺序、不碰别人的内容、等上层模态结束、取消后仍写回、popover 遵守关动画、补 `@_disfavoredOverload`、测试先行、文档同步、发版另定 | +| 2026-11-06 | 起草时查出第 8 条问题 | alert 和存取面板作为 sheet 时没走自己的 `beginSheetModal(for:)`;方案里 `ModalContent` 的 sheet 要求本来就按类型各走各的 API,不改变方向 | +| 2026-11-06 | Accepted | 用户批准,开始实现 | diff --git a/Documentations/README.md b/Documentations/README.md index ed9ec6d876..88295e4b0d 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -9,6 +9,7 @@ - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 - [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 +- [draft-appkit-presentation-redesign.md](Evolutions/draft-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并(Accepted)。 ## Internal From b3cfe05142059c0443c1a5197bf736ea939c5d80 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 22:24:37 +0800 Subject: [PATCH 094/141] test(appkit): cover presentations and reproduce their defects Add tests for what modal, modal session, sheet, popover and view controller presentations already do right, and a test for each defect the presentation redesign proposal lists. The defect tests fail on this code, and are marked with strict XCTExpectFailure until the step that fixes them: a nested modal stops the one under it, a modal window stays held after its modal ends, a new sheet or session or presentation ends another binding's one, a popover closed by the user never calls onDismiss, a popover for a new item leaves the old one open, and a save panel attached as a sheet cannot be cancelled. An alert attached the same way works, so that part of the suspected defect is recorded as a false positive. Shared waiting and window helpers move into PresentationTestSupport.swift. --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-presentation-redesign.md | 15 +- Documentations/Internal/ReviewDecisions.md | 6 + Documentations/README.md | 2 +- .../ModalPresentationTests.swift | 228 +++++++++++++++--- .../PopoverPresentationTests.swift | 146 +++++++++++ .../PresentationTestSupport.swift | 168 +++++++++++++ .../SheetPresentationTests.swift | 203 ++++++++++++++++ .../ViewControllerPresentationTests.swift | 127 +++++----- 9 files changed, 798 insertions(+), 99 deletions(-) create mode 100644 Tests/AppKitNavigationTests/PopoverPresentationTests.swift create mode 100644 Tests/AppKitNavigationTests/PresentationTestSupport.swift create mode 100644 Tests/AppKitNavigationTests/SheetPresentationTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 39e68dbbdf..fbd20e386b 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -10,4 +10,4 @@ | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | | 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | -| draft | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](draft-appkit-presentation-redesign.md) | Accepted | +| draft | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](draft-appkit-presentation-redesign.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index 5e4586dd53..e589401695 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -1,6 +1,6 @@ # Draft - AppKit 弹出 API 重做:生命周期收进一层,重载合并 -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-06 - **最后更新**: 2026-11-06 @@ -17,7 +17,7 @@ ### 读出的问题 -都在 `main` 上,不是最近的改动引入的。都是读代码确认的,运行时由落地第 1 步的测试坐实;本机依赖这个 fork 的 7 个项目都还没踩到(见「下游影响」)。 +都在 `main` 上,不是最近的改动引入的。起草时是读代码确认的;落地第 1 步的测试在 macOS 27.2 上复现了 1–5 和 8,第 8 条里对 alert 的猜测被测试否定(见该行)。本机依赖这个 fork 的 7 个项目都还没踩到(见「下游影响」)。 | # | 问题 | 怎么触发 | 原因 | 以前修过吗 | |---|---|---|---|---| @@ -28,7 +28,7 @@ | 5 | 替换时不分来源 | 新 sheet 会关掉窗口上别的 binding 或 App 自己弹的 sheet;`modalSession` 会关掉本库开的任何会话窗口;`present` 会关掉第一个被弹出的视图控制器;三处都调用本 binding 的 `onDismiss` | `Sheet.swift:262-264`、`Modal.swift:360-365`、`Presentation.swift:74-77` 都只看「现在有没有」,不看是谁弹的 | `present` 那处 2026-11-03 记进[裁决清单](../Internal/ReviewDecisions.md)暂缓,复查条件就是这次重构 | | 6 | 带 `id:` 的绑定版重载少了 `@_disfavoredOverload` | 闭包写成 `{ _ in … }` 时两个重载都能用,编译报歧义 | `Modal.swift:52、105、158、211`,`Sheet.swift:49、99、149、199`,`Popover.swift:116、384`;UIKit 版(`Sources/UIKitNavigation/Navigation/Presentation.swift:123`)和本库的 `present` 都标了 | 没修过 | | 7 | 视图控制器的 sheet 有两套实现 | `sheet(isSheeted:)` 不等视图出现就弹,`present(style: .sheet)` 会等;同一件事两套代码 | `Sheet.swift:160-208` 与 `Presentation.swift` 各走一条路 | 2026-11-03 修「用户关闭不回写」时两边各修了一遍 | -| 8 | alert 和存取面板作为 sheet 时没走它们自己的 API | `window.sheet { NSAlert() }` 用 `NSWindow.beginSheet(alert.window)` 弹出,没调用 `beginSheetModal(for:)`:alert 可能没排版、按钮可能关不掉 sheet,存取面板同理(具体症状待测试坐实) | 默认实现把父窗口当接收者(`Navigation/SheetContent.swift:18-21`),`NSAlert`、`NSSavePanel` 自己的实现(`SheetContent.swift:33-55`)永远走不到 | 没修过;起草本提案时发现 | +| 8 | 存取面板作为 sheet 时没走它自己的 API | `window.sheet { NSSavePanel() }` 用 `NSWindow.beginSheet(_:)` 附上面板,没调用 `beginSheetModal(for:)`:点「取消」关不掉 sheet,binding 也不复位。alert 同样没走 `beginSheetModal(for:)`,但测试表明它的文字照常排版、按钮照常结束 sheet,不受影响 | 默认实现把父窗口当接收者(`Navigation/SheetContent.swift:18-21`),`NSAlert`、`NSSavePanel` 自己的实现(`SheetContent.swift:33-55`)永远走不到 | 没修过;起草本提案时发现 | ### 结构上的问题 @@ -349,7 +349,7 @@ final class BindingPresenter { ## 落地步骤 -1. **补测试作安全网**:按「测试」一节补现有行为的测试(改动前就通过)和问题的测试(先标预期失败)。 +1. **补测试作安全网**(已完成):按「测试」一节补现有行为的测试(改动前就通过)和问题的测试(先标预期失败)。共享的等待、建窗口、记录 popover 的辅助放进 `PresentationTestSupport.swift`,两份原有测试改用它。新增 `SheetPresentationTests`、`PopoverPresentationTests`,`ModalPresentationTests`、`ViewControllerPresentationTests` 各有补充;AppKit 测试共 39 条 XCTest、58 条 Swift Testing,全部通过。 2. **通用层与 modal**:加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。 3. **sheet**:`NSWindow.sheet` 改成泛型并迁过去,加上等父窗口显示;删除 `NSViewController.sheet`。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。 4. **popover**:`NSView` 和 `NSToolbarItem` 的 popover 迁过去,加上等锚点显示(shim 交换 `viewDidMoveToWindow`)和 transaction 的关动画;删除 `PopoverPresentationsObserver`。修掉缺陷 1、3。 @@ -365,6 +365,10 @@ final class BindingPresenter { - **要不要配套专题文章** —— 有「从 API 签名看不出来的调用方契约」就写使用指南;有「下次维护会踩、代码本身看不出来的决策」就写实现说明。写了就登记到头部的「配套文档」。候选的实现说明内容:模态循环为什么要在两种 run loop 模式里启动、为什么要等上层模态先结束、内容为什么要强持有。 - **有没有引入新术语** —— 有就同批次登记进术语表(项目级 `Documentations/Glossary.md`,跨项目通用的登记到全局术语表)。 +## 后续项 + +- AppKit 测试的共享辅助(`PresentationTestSupport.swift` 里的等待、建窗口、记录 popover)将来可以移进一个独立的 `TestingSupport` 测试库;这要改四份 `Package*.swift`,不在这一批。 + ## 决策日志 | 日期 | 变更 | 说明 | @@ -380,3 +384,6 @@ final class BindingPresenter { | 2026-11-06 | 其余默认做法经用户确认 | 强持有内容、换 id 的顺序、不碰别人的内容、等上层模态结束、取消后仍写回、popover 遵守关动画、补 `@_disfavoredOverload`、测试先行、文档同步、发版另定 | | 2026-11-06 | 起草时查出第 8 条问题 | alert 和存取面板作为 sheet 时没走自己的 `beginSheetModal(for:)`;方案里 `ModalContent` 的 sheet 要求本来就按类型各走各的 API,不改变方向 | | 2026-11-06 | Accepted | 用户批准,开始实现 | +| 2026-11-06 | 第 1 步:缺陷 1–5 与 8 在 macOS 27.2 上复现 | 每条都由一条先失败的测试证实,现在用严格模式的 `XCTExpectFailure` 标着。第 8 条原以为 alert 也受影响,测试表明 alert 的文字和按钮都正常,只有存取面板点「取消」关不掉 sheet;alert 那半记进裁决清单的误报一节 | +| 2026-11-06 | 第 7 条不写先变红的测试 | 它的修法是删掉重复的 `NSViewController.sheet`;留下的 `present(style: .sheet)` 本来就等视图出现,那条测试从一开始就是绿的。没有对要删的 API 写红测试,也免得冒险:视图不在窗口里时调用 `presentAsSheet` 会怎样,还不清楚 | +| 2026-11-06 | 共享的测试辅助放在测试 target 里的一个文件,不另建 `TestingSupport` 库 | 另建库要改四份 `Package*.swift`,超出本提案范围;记为后续项 | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index 54c1887613..a8fef95215 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -18,6 +18,12 @@ - **理由**:Apple 文档写明不要直接调用它,应改用 `NSWindow.makeFirstResponder(_:)`。但实测通过 binding 设置焦点一直能正常生效,`NSTextField` 自己的实现会把字段编辑器设为第一响应者。 - **现状**:已按文档改用 `makeFirstResponder(_:)`,行为不变。 +### alert 作为 sheet 时没走 `beginSheetModal(for:)`,会不排版、按钮关不掉 + +- **裁决**:误报。(2026-11-06) +- **理由**:`NSWindow.sheet` 把 alert 的窗口直接交给 `NSWindow.beginSheet(_:)`,确实没调用 `NSAlert.beginSheetModal(for:)`。但在 macOS 27.2 上测试,alert 的标题和说明文字照常排版显示,点按钮也照常结束 sheet、把 binding 写回 `false`。同一处代码对存取面板是真问题:点「取消」关不掉 sheet,见提案 [draft-appkit-presentation-redesign](../Evolutions/draft-appkit-presentation-redesign.md) 第 8 条。 +- **现状**:那份提案让 alert 改走自己的 `beginSheetModal(for:)`,`SheetPresentationTests` 里两条 alert 测试守着上面两点。 + ### `NSFontManager(font:)` 会建出一个和字体面板无关的新实例 - **裁决**:误报。(2026-11-03) diff --git a/Documentations/README.md b/Documentations/README.md index 88295e4b0d..9bd7984827 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -9,7 +9,7 @@ - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 - [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 -- [draft-appkit-presentation-redesign.md](Evolutions/draft-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并(Accepted)。 +- [draft-appkit-presentation-redesign.md](Evolutions/draft-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并(In Progress)。 ## Internal diff --git a/Tests/AppKitNavigationTests/ModalPresentationTests.swift b/Tests/AppKitNavigationTests/ModalPresentationTests.swift index f76506b79a..b13d1ea2d6 100644 --- a/Tests/AppKitNavigationTests/ModalPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ModalPresentationTests.swift @@ -3,10 +3,7 @@ import AppKitNavigation import XCTest - /// Windows presented through `modal(isModaled:)` and `modalSession(isModaled:)`. - /// - /// Synchronous XCTest methods on purpose: they wait by spinning the main run loop, which also - /// services the modal loop that `modal` runs from a main-queue block. + /// Content presented through `modal(isModaled:)` and `modalSession(isModaled:)`. final class ModalPresentationTests: XCTestCase { override func setUp() { super.setUp() @@ -53,6 +50,47 @@ ) } + @MainActor + func testStartingAModalSessionLeavesAnotherBindingsSessionInPlace() { + let host = NSObject() + let firstWindow = makeWindow() + let secondWindow = makeWindow() + @UIBinding var isFirstModaled = false + @UIBinding var isSecondModaled = false + var secondDismissCount = 0 + host.modalSession(isModaled: $isFirstModaled) { firstWindow } + host.modalSession(isModaled: $isSecondModaled, onDismiss: { secondDismissCount += 1 }) { + secondWindow + } + + isFirstModaled = true + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow === firstWindow }, + "The first modal session never began" + ) + isSecondModaled = true + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow === secondWindow }, + "The second modal session never began" + ) + spinRunLoop(for: 0.3) + + XCTExpectFailure("Starting a modal session closes whatever session window the library runs") { + XCTAssertTrue(isFirstModaled, "Starting the second session ended the first binding's session") + XCTAssertTrue(firstWindow.isVisible, "Starting the second session closed the first window") + XCTAssertEqual( + secondDismissCount, 0, + "The second binding's 'onDismiss' ran for a session it never started" + ) + } + + isSecondModaled = false + isFirstModaled = false + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow == nil }, "The modal sessions never ended" + ) + } + // MARK: - Modal loop @MainActor @@ -61,12 +99,10 @@ let window = makeWindow() @UIBinding var isModaled = false host.modal(isModaled: $isModaled) { window } - abortModalLoop(after: 5) + abortModalLoops(after: 5) - // NB: 'modal' runs the modal loop from a main-queue block, so the loop is running by the - // time this fires, and it fires from inside it. let start = Date() - DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { + perform(after: 0.5) { isModaled = false } isModaled = true @@ -84,46 +120,168 @@ ) } - // MARK: - Support + @MainActor + func testUserClosingAModalWindowWritesFalseBack() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isModaled = false + host.modal(isModaled: $isModaled) { window } + abortModalLoops(after: 5) + + let start = Date() + perform(after: 0.5) { + // What the window's close button does once 'windowShouldClose' agrees. + window.close() + } + isModaled = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "Closing the window did not write 'false' back") + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + "The modal loop only ended when the safety timer aborted it: closing the window did not stop it" + ) + } @MainActor - private func makeWindow() -> NSWindow { - let window = NSWindow( - contentRect: NSRect(x: 0, y: 0, width: 240, height: 160), - styleMask: [.titled, .closable], - backing: .buffered, - defer: false + func testSettingTheBindingToFalseCallsOnDismissOnce() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isModaled = false + var dismissCount = 0 + host.modal(isModaled: $isModaled, onDismiss: { dismissCount += 1 }) { window } + abortModalLoops(after: 5) + + perform(after: 0.5) { + isModaled = false + } + isModaled = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + spinRunLoop(for: 0.3) + XCTAssertEqual(dismissCount, 1) + } + + @MainActor + func testSettingTheBindingToFalseStopsAModalAlert() { + let host = NSObject() + let alert = NSAlert() + alert.messageText = "Discard the changes?" + alert.addButton(withTitle: "Discard") + @UIBinding var isModaled = false + host.modal(isModaled: $isModaled) { alert } + abortModalLoops(after: 5) + + let start = Date() + perform(after: 0.5) { + isModaled = false + } + isModaled = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + "The alert only ended when the safety timer aborted it: setting the binding to 'false' could not stop it" ) - window.isReleasedWhenClosed = false - addTeardownBlock { @MainActor in - window.close() + XCTAssertTrue(waitUntil { !alert.window.isVisible }, "The alert stayed on screen") + } + + @MainActor + func testSettingTheBindingToFalseStopsAModalSavePanel() { + let host = NSObject() + let savePanel = NSSavePanel() + @UIBinding var isModaled = false + host.modal(isModaled: $isModaled) { savePanel } + abortModalLoops(after: 8) + + let start = Date() + perform(after: 1) { + isModaled = false } - return window + isModaled = true + + XCTAssertTrue(waitUntil(timeout: 7) { !isModaled }, "The binding was never reset") + XCTAssertLessThan( + Date().timeIntervalSince(start), 6, + "The panel only ended when the safety timer aborted it: setting the binding to 'false' could not stop it" + ) } - /// Guards against a modal loop that never stops, which would otherwise hang the test run. @MainActor - private func abortModalLoop(after timeout: TimeInterval) { - let timer = Timer(timeInterval: timeout, repeats: false) { _ in - MainActor.assumeIsolated { - if NSApplication.shared.modalWindow != nil { - NSApplication.shared.abortModal() - } - } + func testModalPresentedFromAModalStaysOnTopOfIt() { + let host = NSObject() + let window = makeWindow() + let alert = NSAlert() + alert.messageText = "Discard the changes?" + alert.addButton(withTitle: "Discard") + @UIBinding var isWindowModaled = false + @UIBinding var isAlertModaled = false + host.modal(isModaled: $isWindowModaled) { window } + host.modal(isModaled: $isAlertModaled) { alert } + abortModalLoops(after: 6) + + let windowStayedModaled = Recorded(false) + let windowStayedVisible = Recorded(false) + let alertWasOnTop = Recorded(false) + perform(after: 0.4) { + isAlertModaled = true + } + perform(after: 1.2) { + windowStayedModaled.value = isWindowModaled + windowStayedVisible.value = window.isVisible + alertWasOnTop.value = NSApplication.shared.modalWindow === alert.window + isAlertModaled = false } - RunLoop.main.add(timer, forMode: .common) - addTeardownBlock { @MainActor in - timer.invalidate() + perform(after: 1.8) { + isWindowModaled = false + } + isWindowModaled = true + + XCTAssertTrue( + waitUntil(timeout: 5) { + !isWindowModaled && !isAlertModaled && NSApplication.shared.modalWindow == nil + }, + "The modals never all ended" + ) + XCTExpectFailure( + """ + Presenting a modal stops whatever modal loop is running, and only starts its own loop in the \ + default run loop mode + """ + ) { + XCTAssertTrue(windowStayedModaled.value, "Presenting the alert ended the window's modal") + XCTAssertTrue(windowStayedVisible.value, "Presenting the alert took the window off screen") + XCTAssertTrue(alertWasOnTop.value, "The alert did not run on top of the window") } } @MainActor - private func waitUntil(timeout: TimeInterval = 3, _ condition: () -> Bool) -> Bool { - let deadline = Date(timeIntervalSinceNow: timeout) - while !condition(), Date() < deadline { - RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) + func testAWindowIsReleasedOnceItsModalEnds() { + let host = NSObject() + weak var presentedWindow: NSWindow? + @UIBinding var isModaled = false + host.modal(isModaled: $isModaled) { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 160), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + presentedWindow = window + return window + } + abortModalLoops(after: 5) + + perform(after: 0.5) { + isModaled = false + } + isModaled = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + spinRunLoop(for: 0.3) + XCTExpectFailure("A process-wide table keeps every modal window that is not closed") { + XCTAssertNil(presentedWindow, "The window is still held after its modal ended") } - return condition() } } #endif diff --git a/Tests/AppKitNavigationTests/PopoverPresentationTests.swift b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift new file mode 100644 index 0000000000..bc9bf43e80 --- /dev/null +++ b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift @@ -0,0 +1,146 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// Popovers shown from a view through `NSView.popover`. + final class PopoverPresentationTests: XCTestCase { + override func setUp() { + super.setUp() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + @MainActor + func testSettingTheBindingToTrueShowsThePopover() { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + host.view.popover(isPresented: $isPresented) { self.makeViewController() } + + isPresented = true + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + } + + @MainActor + func testSettingTheBindingToFalseClosesThePopover() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + host.view.popover(isPresented: $isPresented) { self.makeViewController() } + + isPresented = true + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + let popover = try XCTUnwrap(recorder.shownPopovers.first) + + isPresented = false + + XCTAssertTrue(waitUntil { !popover.isShown }, "The popover was not closed") + } + + @MainActor + func testUserClosingThePopoverWritesFalseBack() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + host.view.popover(isPresented: $isPresented) { self.makeViewController() } + + isPresented = true + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + let popover = try XCTUnwrap(recorder.shownPopovers.first) + + // What a click outside a transient popover does. + popover.close() + + XCTAssertTrue(waitUntil { !isPresented }, "Closing the popover did not write 'false' back") + } + + @MainActor + func testPopoverCanBeShownAgainAfterTheUserClosedIt() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + host.view.popover(isPresented: $isPresented) { self.makeViewController() } + + isPresented = true + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + try XCTUnwrap(recorder.shownPopovers.first).close() + XCTAssertTrue(waitUntil { !isPresented }, "Closing the popover did not write 'false' back") + + isPresented = true + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.count == 2 && recorder.shownPopovers[1].isShown }, + "Setting the binding to 'true' again did not show the popover again" + ) + } + + @MainActor + func testUserClosingThePopoverCallsOnDismissOnce() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + var dismissCount = 0 + host.view.popover(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { + self.makeViewController() + } + + isPresented = true + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + try XCTUnwrap(recorder.shownPopovers.first).close() + XCTAssertTrue(waitUntil { !isPresented }, "Closing the popover did not write 'false' back") + spinRunLoop(for: 0.3) + + XCTExpectFailure( + """ + The popover is released as soon as it closes, before 'observe' re-runs, and 'onDismiss' only \ + runs from that re-run + """ + ) { + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run once the user closed the popover") + } + } + + @MainActor + func testChangingTheItemClosesThePreviousPopover() throws { + struct Item: Identifiable { + let id: Int + } + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var item: Item? + host.view.popover(item: $item, behavior: .applicationDefined) { _ in + self.makeViewController() + } + + item = Item(id: 1) + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, + "The first item's popover never appeared" + ) + let firstPopover = try XCTUnwrap(recorder.shownPopovers.first) + item = Item(id: 2) + XCTAssertTrue( + waitUntil { recorder.shownPopovers.count == 2 && recorder.shownPopovers[1].isShown }, + "The second item's popover never appeared" + ) + spinRunLoop(for: 0.5) + + XCTExpectFailure("Showing the next item's popover leaves the previous one open") { + XCTAssertFalse(firstPopover.isShown, "The previous item's popover is still open") + } + } + } +#endif diff --git a/Tests/AppKitNavigationTests/PresentationTestSupport.swift b/Tests/AppKitNavigationTests/PresentationTestSupport.swift new file mode 100644 index 0000000000..2becb6ab43 --- /dev/null +++ b/Tests/AppKitNavigationTests/PresentationTestSupport.swift @@ -0,0 +1,168 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import XCTest + + // NB: The presentation tests are synchronous XCTest methods on purpose. They wait by spinning + // the main run loop, which is what drives sheet and popover animations, window ordering, the + // main-queue re-runs of 'observe', and the modal loops that 'modal' runs. A modal loop blocks + // whatever spins the run loop until the loop ends, so anything a test does while a modal is + // up has to be scheduled with 'perform(after:_:)' before the modal starts. + extension XCTestCase { + /// Spins the main run loop until `condition` holds or `timeout` passes, and returns whether it + /// holds. + @MainActor + func waitUntil(timeout: TimeInterval = 3, _ condition: () -> Bool) -> Bool { + let deadline = Date(timeIntervalSinceNow: timeout) + while !condition(), Date() < deadline { + spinRunLoopOnce() + } + return condition() + } + + /// Spins the main run loop for `duration`. + @MainActor + func spinRunLoop(for duration: TimeInterval) { + let deadline = Date(timeIntervalSinceNow: duration) + while Date() < deadline { + spinRunLoopOnce() + } + } + + // NB: Each turn drains an autorelease pool of its own, so that an object the presentation code + // no longer holds is gone by the time a test looks for it. + @MainActor + private func spinRunLoopOnce() { + autoreleasepool { + _ = RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) + } + } + + /// Runs `work` on the main actor once `delay` has passed, from whichever loop is turning the + /// main run loop then — a modal loop that blocks the test method included. + @MainActor + func perform(after delay: TimeInterval, _ work: @escaping @MainActor () -> Void) { + DispatchQueue.main.asyncAfter(deadline: .now() + delay) { + MainActor.assumeIsolated { + work() + } + } + } + + /// Aborts every modal loop still running once `timeout` has passed, so that a loop that never + /// stops fails its test instead of hanging the whole run. + @MainActor + func abortModalLoops(after timeout: TimeInterval) { + let timer = Timer(fire: Date(timeIntervalSinceNow: timeout), interval: 0.2, repeats: true) { + _ in + MainActor.assumeIsolated { + if NSApplication.shared.modalWindow != nil { + NSApplication.shared.abortModal() + } + } + } + RunLoop.main.add(timer, forMode: .common) + addTeardownBlock { @MainActor in + timer.invalidate() + } + } + + /// A titled, closable window that is closed when the test ends. + @MainActor + func makeWindow(width: CGFloat = 240, height: CGFloat = 160) -> NSWindow { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: width, height: height), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + addTeardownBlock { @MainActor in + window.close() + } + return window + } + + /// A view controller whose view is a plain view of the given size. + @MainActor + func makeViewController(width: CGFloat = 200, height: CGFloat = 120) -> NSViewController { + let viewController = NSViewController() + viewController.view = NSView(frame: NSRect(x: 0, y: 0, width: width, height: height)) + return viewController + } + + /// A window on screen whose content is a view controller, closed when the test ends. + @MainActor + func makeHost(width: CGFloat = 480, height: CGFloat = 320) -> PresentationHost { + let viewController = makeViewController(width: width, height: height) + let window = NSWindow(contentViewController: viewController) + window.isReleasedWhenClosed = false + window.orderFront(nil) + addTeardownBlock { @MainActor in + while let attachedSheet = window.attachedSheet { + window.endSheet(attachedSheet) + } + window.close() + } + return PresentationHost(window: window, viewController: viewController) + } + + /// Starts collecting the popovers shown from now until the test ends, and closes any that are + /// still open then. + @MainActor + func recordShownPopovers() -> PopoverRecorder { + let recorder = PopoverRecorder() + addTeardownBlock { @MainActor in + recorder.stopRecording() + for popover in recorder.shownPopovers where popover.isShown { + popover.close() + } + } + return recorder + } + } + + /// A window on screen and the view controller that is its content. + @MainActor + struct PresentationHost { + let window: NSWindow + let viewController: NSViewController + + var view: NSView { viewController.view } + } + + /// Collects the popovers that are shown while it records. + @MainActor + final class PopoverRecorder: NSObject { + private(set) var shownPopovers: [NSPopover] = [] + + override init() { + super.init() + NotificationCenter.default.addObserver( + self, + selector: #selector(popoverWillShow(_:)), + name: NSPopover.willShowNotification, + object: nil + ) + } + + func stopRecording() { + NotificationCenter.default.removeObserver(self) + } + + @objc private func popoverWillShow(_ notification: Notification) { + guard let popover = notification.object as? NSPopover else { return } + shownPopovers.append(popover) + } + } + + /// A value that work scheduled with `perform(after:_:)` sets, for the test to check once that + /// work has run. + @MainActor + final class Recorded { + var value: Value + + init(_ value: Value) { + self.value = value + } + } +#endif diff --git a/Tests/AppKitNavigationTests/SheetPresentationTests.swift b/Tests/AppKitNavigationTests/SheetPresentationTests.swift new file mode 100644 index 0000000000..22b0e9b2f9 --- /dev/null +++ b/Tests/AppKitNavigationTests/SheetPresentationTests.swift @@ -0,0 +1,203 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// Content attached to a window as a sheet through `NSWindow.sheet`: a window, an alert or a + /// save panel. + final class SheetPresentationTests: XCTestCase { + override func setUp() { + super.setUp() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + // MARK: - Window content + + @MainActor + func testSettingTheBindingToTrueAttachesTheWindowAsASheet() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isSheeted = false + host.window.sheet(isSheeted: $isSheeted) { sheetWindow } + + isSheeted = true + + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + } + + @MainActor + func testSettingTheBindingToFalseEndsTheSheet() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isSheeted = false + host.window.sheet(isSheeted: $isSheeted) { sheetWindow } + + isSheeted = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + + isSheeted = false + + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not ended") + } + + @MainActor + func testUserEndingTheSheetWritesFalseBack() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isSheeted = false + host.window.sheet(isSheeted: $isSheeted) { sheetWindow } + + isSheeted = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + + // What a Cancel button in the sheet does. + host.window.endSheet(sheetWindow) + + XCTAssertTrue(waitUntil { !isSheeted }, "Ending the sheet did not write 'false' back") + } + + @MainActor + func testSettingTheBindingToFalseCallsOnDismissOnce() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isSheeted = false + var dismissCount = 0 + host.window.sheet(isSheeted: $isSheeted, onDismiss: { dismissCount += 1 }) { sheetWindow } + + isSheeted = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + isSheeted = false + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not ended") + spinRunLoop(for: 0.3) + + XCTAssertEqual(dismissCount, 1) + } + + @MainActor + func testPresentingASheetLeavesAnotherBindingsSheetInPlace() { + let host = makeHost() + let firstSheet = makeWindow() + let secondSheet = makeWindow() + @UIBinding var isFirstSheeted = false + @UIBinding var isSecondSheeted = false + var secondDismissCount = 0 + host.window.sheet(isSheeted: $isFirstSheeted) { firstSheet } + host.window.sheet(isSheeted: $isSecondSheeted, onDismiss: { secondDismissCount += 1 }) { + secondSheet + } + + isFirstSheeted = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === firstSheet }, "The first sheet never appeared" + ) + isSecondSheeted = true + spinRunLoop(for: 0.5) + + XCTExpectFailure( + "A new sheet ends whatever sheet the window has, and calls its own onDismiss for it" + ) { + XCTAssertTrue(isFirstSheeted, "Presenting the second sheet ended the first binding's sheet") + XCTAssertEqual( + secondDismissCount, 0, + "The second binding's 'onDismiss' ran for a sheet it never presented" + ) + } + + isFirstSheeted = false + isSecondSheeted = false + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheets never went away") + } + + // MARK: - Alert content + + @MainActor + func testClickingAButtonOfAnAlertSheetEndsTheSheetAndWritesFalseBack() throws { + let host = makeHost() + let alert = NSAlert() + alert.messageText = "Delete the item?" + alert.addButton(withTitle: "Delete") + @UIBinding var isSheeted = false + host.window.sheet(isSheeted: $isSheeted) { alert } + + isSheeted = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === alert.window }, + "The alert never appeared as a sheet" + ) + let deleteButton = try XCTUnwrap(alert.buttons.first) + deleteButton.performClick(nil) + + XCTAssertTrue( + waitUntil { host.window.attachedSheet == nil && !isSheeted }, + "Clicking the alert's button did not end the sheet" + ) + } + + @MainActor + func testAnAlertSheetShowsItsMessage() { + let host = makeHost() + let alert = NSAlert() + alert.messageText = "Delete the item?" + alert.informativeText = "This can't be undone." + alert.addButton(withTitle: "Delete") + @UIBinding var isSheeted = false + host.window.sheet(isSheeted: $isSheeted) { alert } + + isSheeted = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === alert.window }, + "The alert never appeared as a sheet" + ) + + let shownTexts = Self.texts(in: alert.window.contentView) + XCTAssertTrue( + shownTexts.contains("Delete the item?") && shownTexts.contains("This can't be undone."), + "The alert sheet does not show its texts: \(shownTexts)" + ) + } + + @MainActor + private static func texts(in view: NSView?) -> [String] { + guard let view else { return [] } + let ownText = (view as? NSTextField).map { [$0.stringValue] } ?? [] + return ownText + view.subviews.flatMap { texts(in: $0) } + } + + // MARK: - Save panel content + + @MainActor + func testCancellingASavePanelSheetEndsTheSheetAndWritesFalseBack() { + let host = makeHost() + let savePanel = NSSavePanel() + @UIBinding var isSheeted = false + host.window.sheet(isSheeted: $isSheeted) { savePanel } + + isSheeted = true + XCTAssertTrue( + waitUntil(timeout: 8) { host.window.attachedSheet === savePanel }, + "The save panel never appeared as a sheet" + ) + // What the panel's Cancel button does. + savePanel.cancel(nil) + + XCTExpectFailure( + "A save panel is attached with NSWindow.beginSheet(_:) instead of its own beginSheetModal(for:)" + ) { + XCTAssertTrue( + waitUntil(timeout: 5) { host.window.attachedSheet == nil && !isSheeted }, + "Cancelling the panel did not end the sheet" + ) + } + } + } +#endif diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift index b9845d0927..99b0e8ec24 100644 --- a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -5,10 +5,6 @@ /// Presentations whose content is a view controller, through `present(isPresented:style:)` and /// `sheet(isSheeted:)`. - /// - /// These run as synchronous XCTest methods on purpose: they wait by spinning the main run loop, - /// which is what drives sheet animations, window ordering and the main-queue re-runs of - /// `observe`. final class ViewControllerPresentationTests: XCTestCase { override func setUp() { super.setUp() @@ -21,7 +17,7 @@ func testUserDismissingAPresentedSheetWritesFalseBack() { let host = makeHost() @UIBinding var isPresented = false - let sheetViewController = makeContentViewController() + let sheetViewController = makeViewController() host.viewController.present(isPresented: $isPresented, style: .sheet) { sheetViewController } @@ -40,7 +36,7 @@ let host = makeHost() @UIBinding var isPresented = false host.viewController.present(isPresented: $isPresented, style: .sheet) { - self.makeContentViewController() + self.makeViewController() } isPresented = true @@ -64,7 +60,7 @@ let host = makeHost() @UIBinding var isPresented = false host.viewController.present(isPresented: $isPresented, style: .sheet) { - self.makeContentViewController() + self.makeViewController() } isPresented = true @@ -75,12 +71,76 @@ XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not dismissed") } + @MainActor + func testPresentedSheetWaitsUntilTheViewAppears() { + let viewController = makeViewController(width: 480, height: 320) + // Already 'true' when the presentation is set up, before the view is in any window. + @UIBinding var isPresented = true + viewController.present(isPresented: $isPresented, style: .sheet) { + self.makeViewController() + } + spinRunLoop(for: 0.2) + + let window = NSWindow(contentViewController: viewController) + window.isReleasedWhenClosed = false + addTeardownBlock { @MainActor in + while let attachedSheet = window.attachedSheet { + window.endSheet(attachedSheet) + } + window.close() + } + window.orderFront(nil) + + XCTAssertTrue( + waitUntil { window.attachedSheet != nil }, "The sheet never appeared once the view did" + ) + } + + @MainActor + func testPresentingLeavesAnotherBindingsPresentationInPlace() { + let host = makeHost() + let firstViewController = makeViewController() + @UIBinding var isFirstPresented = false + @UIBinding var isSecondPresented = false + var secondDismissCount = 0 + host.viewController.present(isPresented: $isFirstPresented, style: .sheet) { + firstViewController + } + host.viewController.present( + isPresented: $isSecondPresented, style: .sheet, onDismiss: { secondDismissCount += 1 } + ) { + self.makeViewController() + } + + isFirstPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet?.contentViewController === firstViewController }, + "The first sheet never appeared" + ) + isSecondPresented = true + spinRunLoop(for: 0.5) + + XCTExpectFailure( + "present(…) dismisses whatever view controller is presented, and calls its own onDismiss for it" + ) { + XCTAssertTrue(isFirstPresented, "Presenting the second sheet dismissed the first binding's sheet") + XCTAssertEqual( + secondDismissCount, 0, + "The second binding's 'onDismiss' ran for a sheet it never presented" + ) + } + + isFirstPresented = false + isSecondPresented = false + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheets never went away") + } + @MainActor func testViewControllerSheetStaysPresentedUntilItIsDismissed() { let host = makeHost() @UIBinding var isSheeted = false host.viewController.sheet(isSheeted: $isSheeted) { - self.makeContentViewController() + self.makeViewController() } isSheeted = true @@ -94,7 +154,7 @@ func testUserDismissingAViewControllerSheetWritesFalseBack() { let host = makeHost() @UIBinding var isSheeted = false - let sheetViewController = makeContentViewController() + let sheetViewController = makeViewController() host.viewController.sheet(isSheeted: $isSheeted) { sheetViewController } isSheeted = true @@ -105,54 +165,5 @@ XCTAssertTrue(waitUntil { !isSheeted }, "Dismissing the sheet did not write 'false' back") } - - // MARK: - Support - - @MainActor - private struct Host { - let window: NSWindow - let viewController: NSViewController - } - - @MainActor - private func makeHost() -> Host { - let viewController = makeContentViewController(width: 480, height: 320) - let window = NSWindow(contentViewController: viewController) - window.isReleasedWhenClosed = false - window.orderFront(nil) - addTeardownBlock { @MainActor in - if let attachedSheet = window.attachedSheet { - window.endSheet(attachedSheet) - } - window.close() - } - return Host(window: window, viewController: viewController) - } - - @MainActor - private func makeContentViewController( - width: CGFloat = 200, height: CGFloat = 120 - ) -> NSViewController { - let viewController = NSViewController() - viewController.view = NSView(frame: NSRect(x: 0, y: 0, width: width, height: height)) - return viewController - } - - @MainActor - private func waitUntil(timeout: TimeInterval = 3, _ condition: () -> Bool) -> Bool { - let deadline = Date(timeIntervalSinceNow: timeout) - while !condition(), Date() < deadline { - RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) - } - return condition() - } - - @MainActor - private func spinRunLoop(for duration: TimeInterval) { - let deadline = Date(timeIntervalSinceNow: duration) - while Date() < deadline { - RunLoop.current.run(mode: .default, before: Date(timeIntervalSinceNow: 0.01)) - } - } } #endif From d389a94ace20401925880420e966a193d56532f0 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 22:41:54 +0800 Subject: [PATCH 095/141] feat(appkit): run modals through one presentation lifecycle Add BindingPresenter, which decides when content is shown and ended for every presentation, and PresentationStyle, which each kind of presentation implements to say how. Move modal and modalSession onto it, rename their isModaled: label to isPresented:, and take any ModalContent - a window, an alert, or a save or open panel - through one generic overload per shape instead of one per type. This fixes three defects the tests reproduced: - A modal presented from inside another modal stopped the one under it. It now runs on top of it, and a covered modal asked to end waits until it is on top. - Every modal window that was not closed stayed in a process-wide table. Each presentation now observes its own window and lets go once it ends. - Starting a modal session closed another binding's session and called the new binding's onDismiss. onDismiss now runs exactly once, after the content has left the screen, including for content the user ended and nothing else held. Releasing the owner ends its modal; cancelling the token only stops following the binding. A loop asked to stop loses that request if another loop starts on top of it before it returns, so new loops wait until stopped ones have returned. --- .../draft-appkit-presentation-redesign.md | 9 +- .../Internal/ModalWindowsObserver.swift | 45 - .../Navigation/BindingPresenter.swift | 266 ++++++ .../AppKitNavigation/Navigation/Modal.swift | 813 ++++++++++-------- .../Navigation/ModalContent.swift | 104 ++- .../Navigation/SheetContent.swift | 2 +- .../ModalPresentationTests.swift | 382 ++++++-- .../PresentationTestSupport.swift | 6 + 8 files changed, 1089 insertions(+), 538 deletions(-) delete mode 100644 Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift create mode 100644 Sources/AppKitNavigation/Navigation/BindingPresenter.swift diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index e589401695..46ce637a05 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -267,7 +267,7 @@ final class BindingPresenter { - **等窗口显示**:`isVisible` 为真就立即开始;否则在 `NSWindowDidChangeOcclusionStateNotification`、成为 key 或 main 窗口时重新检查。 - **等视图进窗口**:shim 再交换一个 `-[NSView viewDidMoveToWindow]`,在原实现之后执行挂在这个视图上的回调;视图上没有回调时只多一次关联对象查找。这个方法要加进 `ObjectiveCMethodNamingTests` 的「有意替换」名单。 - **工具栏项**:从 `NSApp.windows` 里找 `toolbar === item.toolbar` 的窗口,再等它显示;item 还没加进工具栏时,先等 `NSToolbar.willAddItemNotification`。实现时先测 AppKit 在工具栏还没显示时 `show(relativeTo:)` 怎么表现,AppKit 自己能处理就不加这层等待。 -- **嵌套 modal 的顺序**:binding 刚请外层停止、新的 modal 就在它返回前启动时,停止标记应该只属于外层,实现时用测试确认。 +- **嵌套 modal 的顺序**:测试表明,模态循环被请求停止后、真正返回之前,若有新的模态循环在它上面启动,AppKit 会丢掉那次停止请求,旧循环再也不返回。所以本库请某个循环停下后,新的模态循环先排队,等它返回再启动;窗口关闭按钮触发的停止也走同一条路。 ### 存放与清理 @@ -350,7 +350,7 @@ final class BindingPresenter { ## 落地步骤 1. **补测试作安全网**(已完成):按「测试」一节补现有行为的测试(改动前就通过)和问题的测试(先标预期失败)。共享的等待、建窗口、记录 popover 的辅助放进 `PresentationTestSupport.swift`,两份原有测试改用它。新增 `SheetPresentationTests`、`PopoverPresentationTests`,`ModalPresentationTests`、`ViewControllerPresentationTests` 各有补充;AppKit 测试共 39 条 XCTest、58 条 Swift Testing,全部通过。 -2. **通用层与 modal**:加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。 +2. **通用层与 modal**(已完成):加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签、补文档注释;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。`ModalPresentationTests` 共 17 条,连跑 5 次全部通过。 3. **sheet**:`NSWindow.sheet` 改成泛型并迁过去,加上等父窗口显示;删除 `NSViewController.sheet`。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。 4. **popover**:`NSView` 和 `NSToolbarItem` 的 popover 迁过去,加上等锚点显示(shim 交换 `viewDidMoveToWindow`)和 transaction 的关动画;删除 `PopoverPresentationsObserver`。修掉缺陷 1、3。 5. **present 与 destination**:迁过去,替换时只动自己弹的。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。 @@ -387,3 +387,8 @@ final class BindingPresenter { | 2026-11-06 | 第 1 步:缺陷 1–5 与 8 在 macOS 27.2 上复现 | 每条都由一条先失败的测试证实,现在用严格模式的 `XCTExpectFailure` 标着。第 8 条原以为 alert 也受影响,测试表明 alert 的文字和按钮都正常,只有存取面板点「取消」关不掉 sheet;alert 那半记进裁决清单的误报一节 | | 2026-11-06 | 第 7 条不写先变红的测试 | 它的修法是删掉重复的 `NSViewController.sheet`;留下的 `present(style: .sheet)` 本来就等视图出现,那条测试从一开始就是绿的。没有对要删的 API 写红测试,也免得冒险:视图不在窗口里时调用 `presentAsSheet` 会怎样,还不清楚 | | 2026-11-06 | 共享的测试辅助放在测试 target 里的一个文件,不另建 `TestingSupport` 库 | 另建库要改四份 `Package*.swift`,超出本提案范围;记为后续项 | +| 2026-11-06 | 第 2 步:新的模态循环等本库刚停下的循环返回后再启动 | 测试「同一拍里结束一个 modal、弹出另一个」时发现:新循环在旧循环返回前启动,AppKit 会丢掉旧循环的停止请求,旧窗口一直挂着。提案原以为停止标记只属于外层,被测试否定 | +| 2026-11-06 | 模态循环由 style 自己从 run loop 块里启动,`begin` 不等它结束就返回 | 循环若在 `BindingPresenter` 的方法里阻塞,presenter 会一直留在调用栈上、不会释放,宿主释放时就收不起内容 | +| 2026-11-06 | 通用层不再把 `begin` 包在 `withUITransaction` 里 | 模态循环会在 `begin` 里一直跑,事务会漏给循环里处理的所有事件;需要事务的 style 自己取用 | +| 2026-11-06 | 宿主释放、内容被收起后,binding 若还指着那一项就写回 `nil` | 让 binding 与屏幕一致;方案原来只写了「收起并调用 `onDismiss`」 | +| 2026-11-06 | `BindingPresenter` 继承 `NSObject` | 沿用 `NSObject.observe` 在主队列上重跑、把 token 存在对象上的做法,与原来的 `NavigationObserver` 一致 | diff --git a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift b/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift deleted file mode 100644 index 0130c42463..0000000000 --- a/Sources/AppKitNavigation/Internal/ModalWindowsObserver.swift +++ /dev/null @@ -1,45 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -public import AppKit -import Combine - -@MainActor -class ModalWindowsObserver: NSObject { - static let shared = ModalWindowsObserver() - - var windowsCancellable: [NSWindow: AnyCancellable] = [:] - - var modalSessionByWindow: [NSWindow: NSApplication.ModalSession] = [:] - - /// Ends the window's modal session, or stops its modal loop, when the window closes. - /// - /// - Parameters: - /// - window: The window shown modally. - /// - modalSession: The session the window was shown in, if it was shown through - /// `beginModalSession(for:)` rather than a modal loop. - /// - onClose: Runs once the session has ended, after the window started closing. - func observeWindow( - _ window: NSWindow, - modalSession: NSApplication.ModalSession? = nil, - onClose: (() -> Void)? = nil - ) { - if let modalSession { - modalSessionByWindow[window] = modalSession - } - windowsCancellable[window] = NotificationCenter.default.publisher(for: NSWindow.willCloseNotification, object: window) - .sink { [weak self] _ in - guard let self else { return } - if let modalSession = modalSessionByWindow[window] { - NSApplication.shared.endModalSession(modalSession) - } else if NSApplication.shared.modalWindow === window { - NSApplication.shared.stopModal() - } - modalSessionByWindow.removeValue(forKey: window) - windowsCancellable[window]?.cancel() - windowsCancellable.removeValue(forKey: window) - onClose?() - } - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/BindingPresenter.swift b/Sources/AppKitNavigation/Navigation/BindingPresenter.swift new file mode 100644 index 0000000000..b9960505ea --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/BindingPresenter.swift @@ -0,0 +1,266 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + + import AppKit + import SwiftNavigation + + /// One way of showing content: as a sheet, in a modal loop or session, in a popover, or as a + /// presented view controller. + /// + /// A style only knows how to show and hide content. When to do either is up to the + /// ``BindingPresenter`` that uses it. + @MainActor + protocol PresentationStyle { + associatedtype Content: AnyObject + + /// Calls `body` once the anchor can show content — right away when it already can — and + /// returns a closure that cancels a wait that is no longer wanted. + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void + + /// Shows `content`, and calls `didEnd` exactly once, after the content has left the screen, + /// whatever ended it: the user, ``end(_:transaction:)``, or AppKit. + /// + /// Returns without waiting for the content to end. + func begin( + _ content: Content, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) + + /// Asks `content` to leave the screen, which leads to the `didEnd` given to + /// ``begin(_:transaction:didEnd:)``. + /// + /// Works from the content's side rather than the anchor's, so that it still works while the + /// object that owns the presentation is being deallocated. + func end(_ content: Content, transaction: UITransaction) + } + + extension PresentationStyle { + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + body() + return {} + } + } + + /// Shows content while a binding holds a value: one for every call of `modal`, `sheet`, + /// `popover` or `present`, kept alive by the object it was called on. + /// + /// - Content is held here while it is on screen, rather than by whoever made it. + /// - A new item, told apart by its identifier, replaces the content only once the previous + /// content has left the screen. + /// - `onDismiss` runs exactly once for every content that was shown, after it left the screen, + /// whatever ended it. Content that was never shown does not call it. + /// - Content that ends on its own — the user closed it — writes `nil` back to the binding before + /// `onDismiss` runs. + /// - When the object that owns this presenter goes away, the content on screen is ended. + /// - Once the returned token is cancelled, the binding no longer shows or ends anything, but + /// content the user ends still writes back and calls `onDismiss`. + @MainActor + final class BindingPresenter: NSObject { + private let style: Style + private let onDismiss: (() -> Void)? + private var source: Source? + private var phase = Phase.idle + private var waitCount = 0 + private var observation: ObserveToken? + + init(style: Style, onDismiss: (() -> Void)?) { + self.style = style + self.onDismiss = onDismiss + super.init() + } + + deinit { + // NB: The owner, a window, view, view controller or other AppKit object, is released on the + // main thread. + MainActor._assumeIsolated { + endBecauseTheOwnerWentAway() + } + } + + /// Starts following `item`, showing what `content` makes while it holds a value. + func observe( + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + content: @escaping (UIBinding) -> Style.Content + ) -> ObserveToken { + source = Source( + currentItem: { + guard let unwrappedItem = UIBinding(item) else { return nil } + return Source.Item(identity: id(unwrappedItem.wrappedValue)) { + content(unwrappedItem) + } + }, + clearItem: { identity in + if let wrappedValue = item.wrappedValue, id(wrappedValue) == identity { + item.wrappedValue = nil + } + } + ) + let observation = observe { [weak self] transaction in + self?.update(transaction: transaction) + } + self.observation = observation + return observation + } + + private func update(transaction: UITransaction) { + guard let source else { return } + let currentItem = source.currentItem() + switch phase { + case .idle: + if currentItem != nil { + waitUntilReady(transaction: transaction) + } + + case let .waiting(cancelWait): + if currentItem == nil { + cancelWait() + phase = .idle + } + + case let .presented(presentation): + guard let currentItem else { + end(presentation, transaction: transaction) + return + } + if let identity = presentation.identity, identity != currentItem.identity { + end(presentation, transaction: transaction) + } + + case .ending: + // NB: Whatever the binding holds once the content has left the screen decides what comes + // next. + break + } + } + + private func waitUntilReady(transaction: UITransaction) { + waitCount += 1 + let wait = waitCount + phase = .waiting(cancel: {}) + let cancelWait = style.whenReady { [weak self] in + guard let self, case .waiting = self.phase, self.waitCount == wait else { return } + self.show(transaction: transaction) + } + if case .waiting = phase, waitCount == wait { + phase = .waiting(cancel: cancelWait) + } + } + + private func show(transaction: UITransaction) { + guard let source, let currentItem = source.currentItem() else { + phase = .idle + return + } + let presentation = Presentation( + content: currentItem.makeContent(), + identity: currentItem.identity, + clearItem: { [identity = currentItem.identity] in + source.clearItem(identity) + } + ) + phase = .presented(presentation) + let onDismiss = onDismiss + style.begin(presentation.content, transaction: transaction) { [weak self] in + guard !presentation.hasEnded else { return } + presentation.hasEnded = true + if let self { + self.didEnd(presentation) + } else { + // NB: The owner went away while the content was on screen, which is what ended it. + presentation.clearItem() + onDismiss?() + } + } + } + + private func end(_ presentation: Presentation, transaction: UITransaction) { + phase = .ending(presentation) + style.end(presentation.content, transaction: transaction) + } + + private func didEnd(_ presentation: Presentation) { + switch phase { + case let .presented(current) where current === presentation: + // NB: Nothing asked the content to end, so the user did. + phase = .idle + presentation.clearItem() + case let .ending(current) where current === presentation: + phase = .idle + default: + break + } + onDismiss?() + if observation?.isCancelled != true { + update(transaction: UITransaction()) + } + } + + private func endBecauseTheOwnerWentAway() { + switch phase { + case let .waiting(cancelWait): + cancelWait() + case let .presented(presentation): + style.end(presentation.content, transaction: UITransaction()) + case .idle, .ending: + break + } + } + + private enum Phase { + case idle + case waiting(cancel: @MainActor () -> Void) + case presented(Presentation) + case ending(Presentation) + } + + private final class Presentation { + let content: Style.Content + let identity: AnyHashable? + let clearItem: () -> Void + var hasEnded = false + + init(content: Style.Content, identity: AnyHashable?, clearItem: @escaping () -> Void) { + self.content = content + self.identity = identity + self.clearItem = clearItem + } + } + + private struct Source { + struct Item { + let identity: AnyHashable? + let makeContent: () -> Style.Content + } + + /// The item the binding holds now, if any. + let currentItem: () -> Item? + /// Writes `nil` to the binding if it still holds the item with the given identity. + let clearItem: (AnyHashable?) -> Void + } + } + + @MainActor + private let presentersKey = malloc(1)! + + extension NSObject { + /// Shows content in the given style while `item` holds a value, for as long as this object + /// lives. + @MainActor + func bindPresentation( + _ style: Style, + item: UIBinding, + id: @escaping (Item) -> AnyHashable?, + onDismiss: (() -> Void)?, + content: @escaping (UIBinding) -> Style.Content + ) -> ObserveToken { + let presenter = BindingPresenter(style: style, onDismiss: onDismiss) + let presenters = objc_getAssociatedObject(self, presentersKey) as? [NSObject] ?? [] + objc_setAssociatedObject( + self, presentersKey, presenters + [presenter], .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + return presenter.observe(item: item, id: id, content: content) + } + } + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 666b637010..696dede7eb 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -1,426 +1,475 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -public import AppKit - -@MainActor -private var ModalObserverKeys = AssociatedKeys() - -private typealias ModalObserver = NavigationObserver - -// MARK: - Modal Session - NSWindow - -@MainActor -extension NSObject { - @discardableResult - public func modalSession( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow - ) -> ObserveToken { - _modalSession(isModaled: isModaled, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modalSession(item: item, id: id, onDismiss: onDismiss, content: content) - } -} - -// MARK: - Modal - NSWindow - -@MainActor -extension NSObject { - @discardableResult - public func modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow - ) -> ObserveToken { - _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } -} - -// MARK: - Modal - NSAlert + public import AppKit + + // MARK: - Modal loop + + @MainActor + extension NSObject { + /// Runs a window, an alert, or a save or open panel modally while a binding to a Boolean value + /// you provide is true. + /// + /// The content runs in an application-modal loop: the rest of the app takes no input until + /// the loop ends. Setting the binding to `false` ends it. When the user ends the content — + /// closes the window, clicks a button of the alert, dismisses the panel — the binding is set + /// to `false`. A modal presented while another one is running runs on top of it. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to run the content. + /// - onDismiss: The closure to execute once the content has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to run. + /// - Returns: A token that stops following the binding once cancelled. Content that is + /// running then keeps running until the user ends it. + @discardableResult + public func modal( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + bindPresentation( + ModalLoopStyle(), + item: isPresented.toOptionalUnit, + id: { $0.id }, + onDismiss: onDismiss + ) { _ in + content() + } + } -@MainActor -extension NSObject { - @discardableResult - public func modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSAlert - ) -> ObserveToken { - _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) - } + /// Runs a window, an alert, or a save or open panel modally while a binding to an optional + /// item holds a value. + /// + /// The content runs in an application-modal loop, as with + /// ``modal(isPresented:onDismiss:content:)``. If the item's identity changes, the content + /// ends, and once it has left the screen, content for the new item runs. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the content. While it holds a + /// value, the value is passed to `content`. When the user ends the content, the binding is + /// set to `nil`. + /// - onDismiss: The closure to execute once the content has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to run for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + bindPresentation(ModalLoopStyle(), item: item, id: { $0.id }, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } + /// Runs a window, an alert, or a save or open panel modally while a binding to an optional + /// item holds a value, passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the content. While it holds a + /// value, a binding to the value is passed to `content`. When the user ends the content, + /// the binding is set to `nil`. + /// - onDismiss: The closure to execute once the content has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to run for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + bindPresentation( + ModalLoopStyle(), item: item, id: { $0.id }, onDismiss: onDismiss, content: content + ) + } - @_disfavoredOverload - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } + /// Runs a window, an alert, or a save or open panel modally while a binding to an optional + /// item holds a value, telling items apart by the identifier at a key path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the content. While it holds a + /// value, the value is passed to `content`. When the user ends the content, the binding is + /// set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the content ends, and once + /// it has left the screen, content for the new item runs. + /// - onDismiss: The closure to execute once the content has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to run for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + bindPresentation( + ModalLoopStyle(), item: item, id: { $0[keyPath: id] }, onDismiss: onDismiss + ) { + content($0.wrappedValue) + } + } - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) + /// Runs a window, an alert, or a save or open panel modally while a binding to an optional + /// item holds a value, telling items apart by the identifier at a key path and passing the + /// content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the content. While it holds a + /// value, a binding to the value is passed to `content`. When the user ends the content, + /// the binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the content ends, and once + /// it has left the screen, content for the new item runs. + /// - onDismiss: The closure to execute once the content has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to run for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func modal( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + bindPresentation( + ModalLoopStyle(), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss, + content: content + ) + } } - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } -} + // MARK: - Modal session + + @MainActor + extension NSObject { + /// Shows a window in a modal session while a binding to a Boolean value you provide is true. + /// + /// Unlike ``modal(isPresented:onDismiss:content:)``, nothing waits for the session to end: the + /// window takes the app's input while the rest of the app keeps running. Setting the binding to + /// `false` closes the window, which ends the session. When the user closes the window, the + /// binding is set to `false`. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to show the window. + /// - onDismiss: The closure to execute once the window has closed. + /// - content: A closure that returns the window to show. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func modalSession( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSWindow + ) -> ObserveToken { + bindPresentation( + ModalSessionStyle(), + item: isPresented.toOptionalUnit, + id: { $0.id }, + onDismiss: onDismiss + ) { _ in + content() + } + } -// MARK: - Modal - NSSavePanel + /// Shows a window in a modal session while a binding to an optional item holds a value. + /// + /// If the item's identity changes, the window closes, and a window for the new item opens. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the window. While it holds a value, + /// the value is passed to `content`. When the user closes the window, the binding is set + /// to `nil`. + /// - onDismiss: The closure to execute once the window has closed. + /// - content: A closure that returns the window to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + bindPresentation(ModalSessionStyle(), item: item, id: { $0.id }, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } -@MainActor -extension NSObject { - @discardableResult - public func modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSSavePanel - ) -> ObserveToken { - _modal(isModaled: isModaled, onDismiss: onDismiss, content: content) - } + /// Shows a window in a modal session while a binding to an optional item holds a value, + /// passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the window. While it holds a value, + /// a binding to the value is passed to `content`. When the user closes the window, the + /// binding is set to `nil`. + /// - onDismiss: The closure to execute once the window has closed. + /// - content: A closure that returns the window to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func modalSession( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + bindPresentation( + ModalSessionStyle(), item: item, id: { $0.id }, onDismiss: onDismiss, content: content + ) + } - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) - } + /// Shows a window in a modal session while a binding to an optional item holds a value, + /// telling items apart by the identifier at a key path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the window. While it holds a value, + /// the value is passed to `content`. When the user closes the window, the binding is set + /// to `nil`. + /// - id: The key path to the item's identifier. When it changes, the window closes, and a + /// window for the new item opens. + /// - onDismiss: The closure to execute once the window has closed. + /// - content: A closure that returns the window to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSWindow + ) -> ObserveToken { + bindPresentation( + ModalSessionStyle(), item: item, id: { $0[keyPath: id] }, onDismiss: onDismiss + ) { + content($0.wrappedValue) + } + } - @_disfavoredOverload - @discardableResult - public func modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, onDismiss: onDismiss, content: content) + /// Shows a window in a modal session while a binding to an optional item holds a value, + /// telling items apart by the identifier at a key path and passing the content a binding to + /// the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the window. While it holds a value, + /// a binding to the value is passed to `content`. When the user closes the window, the + /// binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the window closes, and a + /// window for the new item opens. + /// - onDismiss: The closure to execute once the window has closed. + /// - content: A closure that returns the window to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func modalSession( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSWindow + ) -> ObserveToken { + bindPresentation( + ModalSessionStyle(), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss, + content: content + ) + } } - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) - } + // MARK: - Styles + + /// Runs content in an application-modal loop of its own. + @MainActor + private struct ModalLoopStyle: PresentationStyle { + func begin( + _ content: Content, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + let window = content._appKitNavigationWindow + nonisolated(unsafe) let content = content + ModalStack.startLoop { + guard !ModalStack.takeEndRequest(for: window) else { + // NB: Ended before it got to run. + didEnd() + return + } + // NB: A window's close button closes the window but leaves the modal loop running it. + let closeObserver = NotificationObserver( + name: NSWindow.willCloseNotification, object: window + ) { _ in + if NSApplication.shared.modalWindow === window { + ModalStack.end(window) { + NSApplication.shared.stopModal() + } + } + } + content._appKitNavigationRunModal() + closeObserver.invalidate() + ModalStack.modalDidEnd(window) + // NB: Ending a modal loop does not take its window off screen. Alerts and panels order + // themselves out; a plain window stays up unless it is ordered out here. + if window.isVisible { + window.orderOut(nil) + } + didEnd() + } + } - @discardableResult - public func modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss, content: content) + func end(_ content: Content, transaction: UITransaction) { + ModalStack.end(content._appKitNavigationWindow) { + NSApplication.shared.stopModal() + } + } } -} -// MARK: - Private Modal + /// Shows a window in a modal session: the window takes the app's input, but nothing waits for + /// it. + @MainActor + private struct ModalSessionStyle: PresentationStyle { + func begin( + _ window: NSWindow, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + let session = NSApplication.shared.beginModalSession(for: window) + let closeObserver = OneTimeObserver() + // NB: Closing the window is what ends the session, whether the user closed it or 'end' did. + closeObserver.observer = NotificationObserver( + name: NSWindow.willCloseNotification, object: window + ) { _ in + closeObserver.invalidate() + NSApplication.shared.endModalSession(session) + ModalStack.modalDidEnd(window) + didEnd() + } + } -@MainActor -extension NSObject { - @discardableResult - fileprivate func _modal( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content - ) -> ObserveToken { - _modal(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } + func end(_ window: NSWindow, transaction: UITransaction) { + ModalStack.end(window) { + window.close() + } + } } - @discardableResult - fileprivate func _modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) - } + /// Keeps a notification observer alive until it has fired once. + @MainActor + private final class OneTimeObserver { + var observer: NotificationObserver? - @_disfavoredOverload - @discardableResult - fileprivate func _modal( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modal(item: item, id: \.id, onDismiss: onDismiss, content: content) - } - - @discardableResult - fileprivate func _modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modal(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) + func invalidate() { + observer?.invalidate() + observer = nil } } - @discardableResult - fileprivate func _modal( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modal(item: item, id: id) { $item in - content($item) - } beginModal: { modalContent, _ in - if NSApplication.shared.modalWindow != nil { - NSApplication.shared.stopModal() - onDismiss?() - } - // NB: The modal loop must not be started from a main-queue block. The main queue is serial, - // so nothing else enqueued on it would run until the loop ended — not the 'observe' - // re-run that stops the loop when the binding is set to 'nil', nor any main-actor task. - // A run-loop block is not a main-queue block. Running it in the default mode only also - // keeps it from starting inside a modal loop that was just asked to stop but has not - // returned yet. - nonisolated(unsafe) let modalContent = modalContent - RunLoop.main.perform(inModes: [.default]) { + /// Starts and ends the modal loops and sessions this library runs, in an order AppKit can follow. + /// + /// - AppKit only stops the innermost modal: asked to stop one that has another modal on top, it + /// stops that other one instead. So a modal asked to end while it is covered ends once the + /// modals above it have ended, and one asked to end before it got to run does not run at all. + /// - A modal loop asked to stop goes on running until it handles its next event. A loop started + /// on top of it in the meantime makes AppKit lose that request, and the first loop never + /// returns. So new loops wait until every loop asked to stop has returned. + @MainActor + private enum ModalStack { + private static var windowsToEnd: [(window: NSWindow, end: @MainActor () -> Void)] = [] + private static var endingWindows: [NSWindow] = [] + private static var loopsToStart: [@MainActor () -> Void] = [] + private static var runLoopObserver: CFRunLoopObserver? + + /// Runs `run`, which runs a modal loop, from a run-loop block once no modal loop is on its way + /// out. + /// + /// Never from a main-queue block, such as the 'observe' re-run that presents the content: the + /// main queue is serial, so nothing else enqueued on it would run until the loop ended — not + /// the re-run that ends the loop when the binding is set to 'nil', nor any main-actor task. + /// Not from inside the presenter either, which would then stay on the stack, and alive, for as + /// long as the loop runs, and could not end the loop when its owner goes away. The block runs + /// in the modal panel mode as well as the default one, so that a modal presented from inside + /// another modal loop starts on top of it. + static func startLoop(_ run: @escaping @MainActor () -> Void) { + RunLoop.main.perform(inModes: [.default, .modalPanel]) { MainActor._assumeIsolated { - ModalWindowsObserver.shared.observeWindow(modalContent.window) - modalContent.appKitNavigationRunModal() - // NB: Ending a modal loop does not take its window off screen. Alerts and panels order - // themselves out; a plain window stays up unless it is ordered out here. - if modalContent.window.isVisible { - modalContent.window.orderOut(nil) + if endingWindows.isEmpty { + run() + } else { + loopsToStart.append(run) } - modalContent.onEndNavigation?() - modalContent.onEndNavigation = nil } } - } endModal: { _, _ in - NSApplication.shared.stopModal() - onDismiss?() } - } - // MARK: - Modal Session + /// Ends the modal showing `window` with `end`: right away if it is the topmost modal, + /// otherwise once it is. + static func end(_ window: NSWindow, with end: @escaping @MainActor () -> Void) { + if NSApplication.shared.modalWindow === window { + endingWindows.append(window) + end() + return + } + windowsToEnd.append((window, end)) + startObserving() + } - @discardableResult - fileprivate func _modalSession( - isModaled: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content - ) -> ObserveToken { - _modalSession(item: isModaled.toOptionalUnit, onDismiss: onDismiss) { _ in content() } - } + /// Whether `window` was asked to end before its modal started, and forgets the request. + static func takeEndRequest(for window: NSWindow) -> Bool { + guard windowsToEnd.contains(where: { $0.window === window }) else { return false } + modalDidEnd(window) + return true + } - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) - } + /// Forgets everything about the modal showing `window`, once it has ended, and starts the + /// loops that were waiting for it. + static func modalDidEnd(_ window: NSWindow) { + windowsToEnd.removeAll { $0.window === window } + if windowsToEnd.isEmpty { + stopObserving() + } + endingWindows.removeAll { $0 === window } + guard endingWindows.isEmpty, !loopsToStart.isEmpty else { return } + let loops = loopsToStart + loopsToStart = [] + for loop in loops { + startLoop(loop) + } + } - @_disfavoredOverload - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modalSession(item: item, id: \.id, onDismiss: onDismiss, content: content) - } + private static func startObserving() { + guard runLoopObserver == nil else { return } + // NB: Checked each time the run loop is about to wait, in every mode a modal loop runs in. + let runLoopObserver = CFRunLoopObserverCreateWithHandler( + nil, CFRunLoopActivity.beforeWaiting.rawValue, true, 0 + ) { _, _ in + MainActor._assumeIsolated { + ModalStack.endTheTopmostModalIfAsked() + } + } + CFRunLoopAddObserver(CFRunLoopGetMain(), runLoopObserver, .commonModes) + self.runLoopObserver = runLoopObserver + } - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _modalSession(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) + private static func stopObserving() { + guard let runLoopObserver else { return } + CFRunLoopObserverInvalidate(runLoopObserver) + self.runLoopObserver = nil } - } - @discardableResult - fileprivate func _modalSession( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _modal(item: item, id: id) { $item in - content($item) - } beginModal: { modalContent, _ in - // NB: Closing a session's window is what ends the session: 'ModalWindowsObserver' ends it - // when the window closes, whether the window was closed from its own UI or from here. - if let modaledWindow = NSApplication.shared.modalWindow, - ModalWindowsObserver.shared.modalSessionByWindow[modaledWindow] != nil - { - modaledWindow.close() - onDismiss?() + private static func endTheTopmostModalIfAsked() { + guard + let topmostWindow = NSApplication.shared.modalWindow, + let index = windowsToEnd.firstIndex(where: { $0.window === topmostWindow }) + else { return } + let end = windowsToEnd.remove(at: index).end + if windowsToEnd.isEmpty { + stopObserving() } + endingWindows.append(topmostWindow) + // NB: Ended from a main-queue block, the way the binding ends a modal, rather than from + // inside the run loop's observer callout. DispatchQueue.main.async { - let modalSession = modalContent.appKitNavigationBeginModalSession() - ModalWindowsObserver.shared.observeWindow( - modalContent.window, - modalSession: modalSession - ) { - // NB: Resets the binding when the window was closed from its own UI. When the binding - // is what closed it, this finds the binding already reset and does nothing. - modalContent.onEndNavigation?() - modalContent.onEndNavigation = nil + MainActor._assumeIsolated { + end() } } - } endModal: { modalContent, _ in - if ModalWindowsObserver.shared.modalSessionByWindow[modalContent.window] != nil { - modalContent.window.close() - } - onDismiss?() } } - private func _modal( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> Content, - beginModal: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void, - endModal: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let modalObserver: ModalObserver = modalObserver() - return modalObserver.observe( - item: item, - id: { $0[keyPath: id] }, - content: content, - begin: beginModal, - end: endModal - ) - } - - private func modalObserver() -> ModalObserver { - if let observer = objc_getAssociatedObject(self, ModalObserverKeys.key(of: Content.self)) as? ModalObserver { - return observer - } else { - let observer = ModalObserver(owner: self) - objc_setAssociatedObject(self, ModalObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return observer - } - } -} - -extension Navigated where Content: ModalContent { - func clearup() { - NSApplication.shared.stopModal() - } -} - #endif diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/ModalContent.swift index 3098e6a589..1a5093cf87 100644 --- a/Sources/AppKitNavigation/Navigation/ModalContent.swift +++ b/Sources/AppKitNavigation/Navigation/ModalContent.swift @@ -1,46 +1,86 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import AppKit + public import AppKit -@MainActor -protocol ModalContent: NavigationContent { - @discardableResult func appKitNavigationRunModal() -> NSApplication.ModalResponse - var window: NSWindow { get } -} + /// Content that AppKit shows in a window of its own — a window, an alert, or a save or open + /// panel — either attached to another window as a sheet, or run as an application-modal window. + /// + /// Return a conforming value from the `content` closure of + /// ``AppKit/NSWindow/sheet(isPresented:onDismiss:content:)`` to attach it as a sheet, or of + /// ``ObjectiveC/NSObject/modal(isPresented:onDismiss:content:)`` to run it as a modal. + /// `NSWindow`, and through it every panel, conforms, as does `NSAlert`. + /// + /// The requirements are implementation details of AppKitNavigation. Conforming other types is not + /// supported. + @MainActor + public protocol ModalContent: AnyObject { + /// The window that shows the content. + @_documentation(visibility: private) + var _appKitNavigationWindow: NSWindow { get } -@MainActor -protocol ModalSessionContent: ModalContent { - func appKitNavigationBeginModalSession() -> NSApplication.ModalSession -} + /// Attaches the content to `parentWindow` as a sheet, and calls `completionHandler` once the + /// sheet has ended. + @_documentation(visibility: private) + func _appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) -extension NSWindow: ModalContent { - var window: NSWindow { self } - - func appKitNavigationRunModal() -> NSApplication.ModalResponse { - __appKitNavigationRunModal() + /// Runs the content in an application-modal loop, and returns once the loop has ended. + @_documentation(visibility: private) + func _appKitNavigationRunModal() } - @objc func __appKitNavigationRunModal() -> NSApplication.ModalResponse { - NSApplication.shared.runModal(for: self) - } -} + extension NSWindow: ModalContent { + @_documentation(visibility: private) + public var _appKitNavigationWindow: NSWindow { self } -extension NSWindow: ModalSessionContent { - func appKitNavigationBeginModalSession() -> NSApplication.ModalSession { - NSApplication.shared.beginModalSession(for: self) - } -} + @_documentation(visibility: private) + public func _appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) { + // NB: A save or open panel has to go through its own method. Attached like a plain window, + // its Cancel button cannot end the sheet. + if let savePanel = self as? NSSavePanel { + savePanel.beginSheetModal(for: parentWindow) { _ in + completionHandler() + } + } else { + parentWindow.beginSheet(self) { _ in + completionHandler() + } + } + } -extension NSSavePanel { - override func __appKitNavigationRunModal() -> NSApplication.ModalResponse { - runModal() + @_documentation(visibility: private) + public func _appKitNavigationRunModal() { + if let savePanel = self as? NSSavePanel { + _ = savePanel.runModal() + } else { + _ = NSApplication.shared.runModal(for: self) + } + } } -} -extension NSAlert: ModalContent { - func appKitNavigationRunModal() -> NSApplication.ModalResponse { - runModal() + extension NSAlert: ModalContent { + @_documentation(visibility: private) + public var _appKitNavigationWindow: NSWindow { window } + + @_documentation(visibility: private) + public func _appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) { + beginSheetModal(for: parentWindow) { _ in + completionHandler() + } + } + + @_documentation(visibility: private) + public func _appKitNavigationRunModal() { + _ = runModal() + } } -} #endif diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift index e58e29d72e..da9fa3ee7b 100644 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ b/Sources/AppKitNavigation/Navigation/SheetContent.swift @@ -50,7 +50,7 @@ extension NSSavePanel { } func endSheet(for content: any SheetContent) { - content.currentWindow?.endSheet(window) + content.currentWindow?.endSheet(self) } } diff --git a/Tests/AppKitNavigationTests/ModalPresentationTests.swift b/Tests/AppKitNavigationTests/ModalPresentationTests.swift index b13d1ea2d6..9a12f554ab 100644 --- a/Tests/AppKitNavigationTests/ModalPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ModalPresentationTests.swift @@ -3,7 +3,8 @@ import AppKitNavigation import XCTest - /// Content presented through `modal(isModaled:)` and `modalSession(isModaled:)`. + /// Content presented through `modal(isPresented:)` and `modalSession(isPresented:)`, and the + /// lifecycle every presentation shares, tried out on modals. final class ModalPresentationTests: XCTestCase { override func setUp() { super.setUp() @@ -18,31 +19,31 @@ func testUserClosingAModalSessionWindowWritesFalseBack() { let host = NSObject() let window = makeWindow() - @UIBinding var isModaled = false - host.modalSession(isModaled: $isModaled) { window } + @UIBinding var isPresented = false + host.modalSession(isPresented: $isPresented) { window } - isModaled = true + isPresented = true XCTAssertTrue(waitUntil { window.isVisible }, "The window never appeared") // What the window's close button does once 'windowShouldClose' agrees. window.close() - XCTAssertTrue(waitUntil { !isModaled }, "Closing the window did not write 'false' back") + XCTAssertTrue(waitUntil { !isPresented }, "Closing the window did not write 'false' back") } @MainActor func testSettingTheBindingToFalseEndsTheModalSession() { let host = NSObject() let window = makeWindow() - @UIBinding var isModaled = false - host.modalSession(isModaled: $isModaled) { window } + @UIBinding var isPresented = false + host.modalSession(isPresented: $isPresented) { window } - isModaled = true + isPresented = true XCTAssertTrue( waitUntil { NSApplication.shared.modalWindow === window }, "The modal session never began" ) - isModaled = false + isPresented = false XCTAssertTrue( waitUntil { NSApplication.shared.modalWindow == nil && !window.isVisible }, @@ -55,37 +56,34 @@ let host = NSObject() let firstWindow = makeWindow() let secondWindow = makeWindow() - @UIBinding var isFirstModaled = false - @UIBinding var isSecondModaled = false + @UIBinding var isFirstPresented = false + @UIBinding var isSecondPresented = false var secondDismissCount = 0 - host.modalSession(isModaled: $isFirstModaled) { firstWindow } - host.modalSession(isModaled: $isSecondModaled, onDismiss: { secondDismissCount += 1 }) { + host.modalSession(isPresented: $isFirstPresented) { firstWindow } + host.modalSession(isPresented: $isSecondPresented, onDismiss: { secondDismissCount += 1 }) { secondWindow } - isFirstModaled = true + isFirstPresented = true XCTAssertTrue( waitUntil { NSApplication.shared.modalWindow === firstWindow }, "The first modal session never began" ) - isSecondModaled = true + isSecondPresented = true XCTAssertTrue( waitUntil { NSApplication.shared.modalWindow === secondWindow }, "The second modal session never began" ) spinRunLoop(for: 0.3) - XCTExpectFailure("Starting a modal session closes whatever session window the library runs") { - XCTAssertTrue(isFirstModaled, "Starting the second session ended the first binding's session") - XCTAssertTrue(firstWindow.isVisible, "Starting the second session closed the first window") - XCTAssertEqual( - secondDismissCount, 0, - "The second binding's 'onDismiss' ran for a session it never started" - ) - } + XCTAssertTrue(isFirstPresented, "Starting the second session ended the first binding's session") + XCTAssertTrue(firstWindow.isVisible, "Starting the second session closed the first window") + XCTAssertEqual( + secondDismissCount, 0, "The second binding's 'onDismiss' ran for a session it never started" + ) - isSecondModaled = false - isFirstModaled = false + isSecondPresented = false + isFirstPresented = false XCTAssertTrue( waitUntil { NSApplication.shared.modalWindow == nil }, "The modal sessions never ended" ) @@ -97,17 +95,17 @@ func testSettingTheBindingToFalseTakesTheModalWindowOffScreen() { let host = NSObject() let window = makeWindow() - @UIBinding var isModaled = false - host.modal(isModaled: $isModaled) { window } + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { window } abortModalLoops(after: 5) let start = Date() perform(after: 0.5) { - isModaled = false + isPresented = false } - isModaled = true + isPresented = true - XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "The binding was never reset") XCTAssertLessThan( Date().timeIntervalSince(start), 3, """ @@ -124,8 +122,8 @@ func testUserClosingAModalWindowWritesFalseBack() { let host = NSObject() let window = makeWindow() - @UIBinding var isModaled = false - host.modal(isModaled: $isModaled) { window } + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { window } abortModalLoops(after: 5) let start = Date() @@ -133,9 +131,11 @@ // What the window's close button does once 'windowShouldClose' agrees. window.close() } - isModaled = true + isPresented = true - XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "Closing the window did not write 'false' back") + XCTAssertTrue( + waitUntil(timeout: 4) { !isPresented }, "Closing the window did not write 'false' back" + ) XCTAssertLessThan( Date().timeIntervalSince(start), 3, "The modal loop only ended when the safety timer aborted it: closing the window did not stop it" @@ -146,38 +146,66 @@ func testSettingTheBindingToFalseCallsOnDismissOnce() { let host = NSObject() let window = makeWindow() - @UIBinding var isModaled = false + @UIBinding var isPresented = false var dismissCount = 0 - host.modal(isModaled: $isModaled, onDismiss: { dismissCount += 1 }) { window } + host.modal(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { window } abortModalLoops(after: 5) perform(after: 0.5) { - isModaled = false + isPresented = false } - isModaled = true + isPresented = true - XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "The binding was never reset") spinRunLoop(for: 0.3) XCTAssertEqual(dismissCount, 1) } + @MainActor + func testUserEndingAModalAlertCallsOnDismissOnce() { + let host = NSObject() + let presentedAlert = WeakReference() + @UIBinding var isPresented = false + let dismissCount = Recorded(0) + host.modal(isPresented: $isPresented, onDismiss: { dismissCount.value += 1 }) { + // NB: Made here, and held by nothing but the presentation. + let alert = NSAlert() + alert.messageText = "Discard the changes?" + alert.addButton(withTitle: "Discard") + presentedAlert.object = alert + return alert + } + abortModalLoops(after: 5) + + perform(after: 0.5) { + presentedAlert.object?.buttons.first?.performClick(nil) + } + isPresented = true + + XCTAssertTrue( + waitUntil(timeout: 4) { !isPresented }, "Clicking the alert's button did not write 'false' back" + ) + spinRunLoop(for: 0.3) + XCTAssertEqual(dismissCount.value, 1, "'onDismiss' did not run once the user ended the alert") + } + @MainActor func testSettingTheBindingToFalseStopsAModalAlert() { let host = NSObject() let alert = NSAlert() alert.messageText = "Discard the changes?" alert.addButton(withTitle: "Discard") - @UIBinding var isModaled = false - host.modal(isModaled: $isModaled) { alert } + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { alert } abortModalLoops(after: 5) let start = Date() perform(after: 0.5) { - isModaled = false + isPresented = false } - isModaled = true + isPresented = true - XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "The binding was never reset") XCTAssertLessThan( Date().timeIntervalSince(start), 3, "The alert only ended when the safety timer aborted it: setting the binding to 'false' could not stop it" @@ -189,23 +217,67 @@ func testSettingTheBindingToFalseStopsAModalSavePanel() { let host = NSObject() let savePanel = NSSavePanel() - @UIBinding var isModaled = false - host.modal(isModaled: $isModaled) { savePanel } + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { savePanel } abortModalLoops(after: 8) let start = Date() perform(after: 1) { - isModaled = false + isPresented = false } - isModaled = true + isPresented = true - XCTAssertTrue(waitUntil(timeout: 7) { !isModaled }, "The binding was never reset") + XCTAssertTrue(waitUntil(timeout: 7) { !isPresented }, "The binding was never reset") XCTAssertLessThan( Date().timeIntervalSince(start), 6, "The panel only ended when the safety timer aborted it: setting the binding to 'false' could not stop it" ) } + @MainActor + func testChangingTheItemEndsTheModalBeforeTheNextOneRuns() { + struct Item: Identifiable { + let id: Int + } + let host = NSObject() + let firstWindow = makeWindow() + let secondWindow = makeWindow() + @UIBinding var item: Item? + let dismissCount = Recorded(0) + host.modal(item: $item, onDismiss: { dismissCount.value += 1 }) { currentItem in + currentItem.id == 1 ? firstWindow : secondWindow + } + abortModalLoops(after: 6) + + let firstWasGoneWhenSecondRan = Recorded(false) + let dismissCountWhenSecondRan = Recorded(-1) + perform(after: 0.5) { + item = Item(id: 2) + } + perform(after: 1.2) { + firstWasGoneWhenSecondRan.value = + !firstWindow.isVisible && NSApplication.shared.modalWindow === secondWindow + dismissCountWhenSecondRan.value = dismissCount.value + item = nil + } + item = Item(id: 1) + + XCTAssertTrue( + waitUntil(timeout: 5) { item == nil && NSApplication.shared.modalWindow == nil }, + "The modals never ended" + ) + XCTAssertTrue( + firstWasGoneWhenSecondRan.value, + "The second item's modal did not run in place of the first item's" + ) + XCTAssertEqual( + dismissCountWhenSecondRan.value, 1, + "'onDismiss' did not run exactly once for the first item before the second item's modal ran" + ) + spinRunLoop(for: 0.3) + XCTAssertEqual(dismissCount.value, 2) + } + @MainActor func testModalPresentedFromAModalStaysOnTopOfIt() { let host = NSObject() @@ -213,53 +285,124 @@ let alert = NSAlert() alert.messageText = "Discard the changes?" alert.addButton(withTitle: "Discard") - @UIBinding var isWindowModaled = false - @UIBinding var isAlertModaled = false - host.modal(isModaled: $isWindowModaled) { window } - host.modal(isModaled: $isAlertModaled) { alert } + @UIBinding var isWindowPresented = false + @UIBinding var isAlertPresented = false + host.modal(isPresented: $isWindowPresented) { window } + host.modal(isPresented: $isAlertPresented) { alert } abortModalLoops(after: 6) - let windowStayedModaled = Recorded(false) + let windowStayedPresented = Recorded(false) let windowStayedVisible = Recorded(false) let alertWasOnTop = Recorded(false) perform(after: 0.4) { - isAlertModaled = true + isAlertPresented = true } perform(after: 1.2) { - windowStayedModaled.value = isWindowModaled + windowStayedPresented.value = isWindowPresented windowStayedVisible.value = window.isVisible alertWasOnTop.value = NSApplication.shared.modalWindow === alert.window - isAlertModaled = false + isAlertPresented = false } perform(after: 1.8) { - isWindowModaled = false + isWindowPresented = false } - isWindowModaled = true + isWindowPresented = true XCTAssertTrue( waitUntil(timeout: 5) { - !isWindowModaled && !isAlertModaled && NSApplication.shared.modalWindow == nil + !isWindowPresented && !isAlertPresented && NSApplication.shared.modalWindow == nil }, "The modals never all ended" ) - XCTExpectFailure( - """ - Presenting a modal stops whatever modal loop is running, and only starts its own loop in the \ - default run loop mode - """ - ) { - XCTAssertTrue(windowStayedModaled.value, "Presenting the alert ended the window's modal") - XCTAssertTrue(windowStayedVisible.value, "Presenting the alert took the window off screen") - XCTAssertTrue(alertWasOnTop.value, "The alert did not run on top of the window") + XCTAssertTrue(windowStayedPresented.value, "Presenting the alert ended the window's modal") + XCTAssertTrue(windowStayedVisible.value, "Presenting the alert took the window off screen") + XCTAssertTrue(alertWasOnTop.value, "The alert did not run on top of the window") + } + + @MainActor + func testEndingAModalCoveredByAnotherWaitsUntilItIsOnTop() { + let host = NSObject() + let window = makeWindow() + let alert = NSAlert() + alert.messageText = "Discard the changes?" + alert.addButton(withTitle: "Discard") + @UIBinding var isWindowPresented = false + @UIBinding var isAlertPresented = false + host.modal(isPresented: $isWindowPresented) { window } + host.modal(isPresented: $isAlertPresented) { alert } + abortModalLoops(after: 6) + + let alertStayedOnTop = Recorded(false) + let windowStayedUnderIt = Recorded(false) + let isFinished = Recorded(false) + perform(after: 0.4) { + isAlertPresented = true + } + perform(after: 1.0) { + isWindowPresented = false + } + perform(after: 1.5) { + alertStayedOnTop.value = NSApplication.shared.modalWindow === alert.window + windowStayedUnderIt.value = window.isVisible + isAlertPresented = false + isFinished.value = true } + isWindowPresented = true + + XCTAssertTrue( + waitUntil(timeout: 5) { + isFinished.value && NSApplication.shared.modalWindow == nil && !window.isVisible + }, + "The window's modal never ended once the alert on top of it had" + ) + XCTAssertTrue(alertStayedOnTop.value, "Ending the window's modal ended the alert on top of it") + XCTAssertTrue( + windowStayedUnderIt.value, "The window left the screen while the alert was still on top of it" + ) + } + + @MainActor + func testEndingOneModalAndPresentingAnotherInTheSameTurnRunsTheNewOne() { + let host = NSObject() + let window = makeWindow() + let alert = NSAlert() + alert.messageText = "Discard the changes?" + alert.addButton(withTitle: "Discard") + @UIBinding var isWindowPresented = false + @UIBinding var isAlertPresented = false + host.modal(isPresented: $isWindowPresented) { window } + host.modal(isPresented: $isAlertPresented) { alert } + abortModalLoops(after: 6) + + let alertRan = Recorded(false) + let windowEnded = Recorded(false) + perform(after: 0.5) { + isWindowPresented = false + isAlertPresented = true + } + perform(after: 1.2) { + alertRan.value = NSApplication.shared.modalWindow === alert.window + windowEnded.value = !window.isVisible + isAlertPresented = false + } + isWindowPresented = true + + XCTAssertTrue( + waitUntil(timeout: 5) { + NSApplication.shared.modalWindow == nil && !isWindowPresented && !isAlertPresented + }, + "The modals never all ended" + ) + XCTAssertTrue(alertRan.value, "The alert did not run") + XCTAssertTrue(windowEnded.value, "The window's modal did not end") } @MainActor func testAWindowIsReleasedOnceItsModalEnds() { let host = NSObject() weak var presentedWindow: NSWindow? - @UIBinding var isModaled = false - host.modal(isModaled: $isModaled) { + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { let window = NSWindow( contentRect: NSRect(x: 0, y: 0, width: 240, height: 160), styleMask: [.titled, .closable], @@ -273,15 +416,102 @@ abortModalLoops(after: 5) perform(after: 0.5) { - isModaled = false + isPresented = false } - isModaled = true + isPresented = true - XCTAssertTrue(waitUntil(timeout: 4) { !isModaled }, "The binding was never reset") + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "The binding was never reset") spinRunLoop(for: 0.3) - XCTExpectFailure("A process-wide table keeps every modal window that is not closed") { - XCTAssertNil(presentedWindow, "The window is still held after its modal ended") + XCTAssertNil(presentedWindow, "The window is still held after its modal ended") + } + + // MARK: - Owner and token + + @MainActor + func testReleasingTheOwnerEndsItsModal() { + let owner = Recorded(NSObject()) + let window = makeWindow() + @UIBinding var isPresented = false + let dismissCount = Recorded(0) + owner.value?.modal(isPresented: $isPresented, onDismiss: { dismissCount.value += 1 }) { + window + } + abortModalLoops(after: 5) + + let start = Date() + perform(after: 0.5) { + owner.value = nil } + isPresented = true + + XCTAssertTrue( + waitUntil(timeout: 4) { !isPresented }, "Releasing the owner did not end its modal" + ) + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + "The modal loop only ended when the safety timer aborted it: releasing the owner did not stop it" + ) + XCTAssertTrue(waitUntil { !window.isVisible }, "The window stayed on screen") + spinRunLoop(for: 0.3) + XCTAssertEqual(dismissCount.value, 1) + } + + @MainActor + func testCancellingTheTokenStopsFollowingTheBinding() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + let token = host.modal(isPresented: $isPresented) { window } + abortModalLoops(after: 5) + + let windowStayedModal = Recorded(false) + let isFinished = Recorded(false) + perform(after: 0.5) { + token.cancel() + isPresented = false + } + perform(after: 1) { + windowStayedModal.value = NSApplication.shared.modalWindow === window + window.close() + isFinished.value = true + } + isPresented = true + + XCTAssertTrue( + waitUntil(timeout: 4) { isFinished.value && NSApplication.shared.modalWindow == nil }, + "The modal never ended" + ) + XCTAssertTrue( + windowStayedModal.value, + "Setting the binding to 'false' still ended the modal after the token was cancelled" + ) + } + + @MainActor + func testUserEndingContentAfterTheTokenIsCancelledStillWritesBack() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + let dismissCount = Recorded(0) + let token = host.modal(isPresented: $isPresented, onDismiss: { dismissCount.value += 1 }) { + window + } + abortModalLoops(after: 5) + + perform(after: 0.5) { + token.cancel() + } + perform(after: 0.8) { + window.close() + } + isPresented = true + + XCTAssertTrue( + waitUntil(timeout: 4) { !isPresented }, + "Closing the window after the token was cancelled did not write 'false' back" + ) + spinRunLoop(for: 0.3) + XCTAssertEqual(dismissCount.value, 1) } } #endif diff --git a/Tests/AppKitNavigationTests/PresentationTestSupport.swift b/Tests/AppKitNavigationTests/PresentationTestSupport.swift index 2becb6ab43..8589f72285 100644 --- a/Tests/AppKitNavigationTests/PresentationTestSupport.swift +++ b/Tests/AppKitNavigationTests/PresentationTestSupport.swift @@ -165,4 +165,10 @@ self.value = value } } + + /// An object that work scheduled with `perform(after:_:)` can reach without keeping it alive. + @MainActor + final class WeakReference { + weak var object: Object? + } #endif From d01a4ae6110c41b088a53fc1194b748679901cf5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 22:49:27 +0800 Subject: [PATCH 096/141] feat(appkit): attach sheets through the shared presentation lifecycle Move NSWindow.sheet onto BindingPresenter, rename its isSheeted: label to isPresented:, and take any ModalContent through one generic overload per shape. Each kind of content now begins its sheet through its own API, so a save or open panel attached as a sheet can be cancelled again. A new sheet no longer ends whatever sheet the window has and calls its own onDismiss for it: AppKit queues it behind the other one, and a queued sheet whose binding ends is taken off the queue. A sheet set to show before its window is on screen waits until the window is, and onDismiss runs once the sheet has left the screen rather than when its completion handler runs, which is while it is still rolling up. Modal sessions wait the same way after their window starts closing. Remove NSViewController.sheet(isSheeted:): present(isPresented:style: .sheet) does the same, and the two implementations had drifted apart. The waits check their condition each time the main run loop is about to wait, because a test process, never the active app, gets no occlusion, key or main window notification when a window comes on screen. Update the two modal(isModaled:) calls in the Wi-Fi case study. --- .../draft-appkit-presentation-redesign.md | 21 +- ...ppKit+ConnectToNetworkViewController.swift | 2 +- .../AppKit+NetworkDetailViewController.swift | 2 +- .../Internal/RunLoopWait.swift | 44 ++ .../AppKitNavigation/Navigation/Modal.swift | 3 +- .../AppKitNavigation/Navigation/Sheet.swift | 479 +++++++----------- .../Navigation/SheetContent.swift | 86 ---- .../ModalPresentationTests.swift | 23 + .../SheetPresentationTests.swift | 195 +++++-- .../ViewControllerPresentationTests.swift | 31 +- 10 files changed, 411 insertions(+), 475 deletions(-) create mode 100644 Sources/AppKitNavigation/Internal/RunLoopWait.swift delete mode 100644 Sources/AppKitNavigation/Navigation/SheetContent.swift diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index 46ce637a05..5fd79f5c58 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -264,9 +264,11 @@ final class BindingPresenter { | `NSToolbarItem.popover` | 工具栏所在的窗口显示出来 | 同上,用 `show(relativeTo:)` | 同上 | 同上 | | `present` / `destination` | `viewDidAppear`(shim 现有的机制) | `present(_:for:)`,或调用方传入的 `present` 闭包 | shim 在 `viewDidDisappear` 里报告的 dismiss | 仍在 `presentedViewControllers` 里才 `dismiss(_:)` | -- **等窗口显示**:`isVisible` 为真就立即开始;否则在 `NSWindowDidChangeOcclusionStateNotification`、成为 key 或 main 窗口时重新检查。 -- **等视图进窗口**:shim 再交换一个 `-[NSView viewDidMoveToWindow]`,在原实现之后执行挂在这个视图上的回调;视图上没有回调时只多一次关联对象查找。这个方法要加进 `ObjectiveCMethodNamingTests` 的「有意替换」名单。 -- **工具栏项**:从 `NSApp.windows` 里找 `toolbar === item.toolbar` 的窗口,再等它显示;item 还没加进工具栏时,先等 `NSToolbar.willAddItemNotification`。实现时先测 AppKit 在工具栏还没显示时 `show(relativeTo:)` 怎么表现,AppKit 自己能处理就不加这层等待。 +- **怎么等**:所有「等」——等窗口显示、等视图进窗口、等工具栏显示、等 sheet 离开屏幕——都用一个挂在主 run loop 上的观察者,在每次等待之前检查条件(`Internal/RunLoopWait.swift`),只在有东西在等时挂着。测试表明通知靠不住:测试进程不是活跃的 App,窗口显示出来时遮挡状态、key、main 三种通知一个都没发;视图进窗口本来就没有通知;sheet 的 completion handler 在 sheet 开始收起、还在屏幕上时就调用了。 +- **等窗口显示**:等 `isVisible` 为真。 +- **等视图进窗口**:等视图有窗口、且窗口显示出来。不用交换 `viewDidMoveToWindow`。 +- **工具栏项**:从 `NSApp.windows` 里找 `toolbar === item.toolbar` 的窗口,等它显示。实现时先测 AppKit 在工具栏还没显示时 `show(relativeTo:)` 怎么表现,AppKit 自己能处理就不加这层等待。 +- **「下屏之后」**:sheet 在 completion handler 之后再等 sheet 窗口不可见;modal session 在窗口 `willClose` 之后同样再等;模态循环返回后由本库把窗口 `orderOut`,随即算作下屏。 - **嵌套 modal 的顺序**:测试表明,模态循环被请求停止后、真正返回之前,若有新的模态循环在它上面启动,AppKit 会丢掉那次停止请求,旧循环再也不返回。所以本库请某个循环停下后,新的模态循环先排队,等它返回再启动;窗口关闭按钮触发的停止也走同一条路。 ### 存放与清理 @@ -295,7 +297,8 @@ final class BindingPresenter { - **每种内容保留一套重载**:公开重载数量不变,被否。**把 `ModalContent` 开放成扩展点**:App 可以让自己的类型也能弹出,但多一个要长期维护的契约,眼下没有需求,被否。 - **取消 token 时也收起内容,或宿主释放时也不收起**:前者让取消变成破坏性操作,后者留着 `clearup()` 原本要解决的问题。都被否。 - **继续弱引用内容,像 UIKit 版那样在用户关闭时临时强引用**:AppKit 这边的 popover 包装和 alert 没有别人持有,弱引用正是缺陷 1 的根源,直接在显示期间强持有更简单。 -- **用 KVO 观察 `NSView.window`**:头文件没有标注它支持 KVO,将来可能悄悄失效,所以改用交换 `viewDidMoveToWindow`。 +- **用 KVO 观察 `NSView.window`**:头文件没有标注它支持 KVO,将来可能悄悄失效。 +- **交换 `viewDidMoveToWindow`、监听窗口的遮挡与 key、main 通知**:起草时的方案。前者要替换每个视图的一个系统方法;后者在测试进程里一个都不发(见「怎么等」)。实现时改用 run loop 观察者检查条件,两者都不需要了。 - **保留全局单例、只修泄漏**:每次弹出各自观察以后,全局状态就没有存在的理由了。 - **存取面板沿用 `@objc` 方法加子类覆写**:现在的 `__appKitNavigationRunModal` 就是这么做的,但这要在 `NSWindow` 上加 Objective-C 方法;改成实现内部的类型判断更简单。 @@ -331,7 +334,7 @@ final class BindingPresenter { ### 下游影响 -- 本仓库:`AppKitNavigation`、`AppKitNavigationShim`(多交换一个 `viewDidMoveToWindow`)、`AppKitNavigationTests`。Examples 里 AppKit 的案例只用 `present(item:id:style:)` 和 `present(isPresented:style:)`,不受影响。 +- 本仓库:`AppKitNavigation`、`AppKitNavigationTests`。Examples 里 Wi-Fi 案例的两处 `modal(isModaled:)` 随这次改成 `modal(isPresented:)`;它的 `modalSession(item:)` 和其余案例的 `present(...)` 写法不变。(起草时只搜了带点号的调用,漏掉了这两处省略 `self` 的写法,第 3 步发现后更正。) - 下游仓库:XCOrganizer 的 2 处 `NSWindow.sheet(item:)`、SymbolViewer 的 2 处和 ApplicationScaffold 模板的 1 处 `present(isPresented:style: .sheet)`,写法都不用改。其余 4 个依赖这个 fork 的项目没有用到弹出 API。这些项目在下次重新解析依赖、拿到新版本时,只会碰到上面那些行为变化:XCOrganizer 的 sheet 的 item 初始为 `nil`,等锚点那一条对它没有影响;它们都没有用 `onDismiss`。 ### 文档与示例 @@ -351,8 +354,8 @@ final class BindingPresenter { 1. **补测试作安全网**(已完成):按「测试」一节补现有行为的测试(改动前就通过)和问题的测试(先标预期失败)。共享的等待、建窗口、记录 popover 的辅助放进 `PresentationTestSupport.swift`,两份原有测试改用它。新增 `SheetPresentationTests`、`PopoverPresentationTests`,`ModalPresentationTests`、`ViewControllerPresentationTests` 各有补充;AppKit 测试共 39 条 XCTest、58 条 Swift Testing,全部通过。 2. **通用层与 modal**(已完成):加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签、补文档注释;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。`ModalPresentationTests` 共 17 条,连跑 5 次全部通过。 -3. **sheet**:`NSWindow.sheet` 改成泛型并迁过去,加上等父窗口显示;删除 `NSViewController.sheet`。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。 -4. **popover**:`NSView` 和 `NSToolbarItem` 的 popover 迁过去,加上等锚点显示(shim 交换 `viewDidMoveToWindow`)和 transaction 的关动画;删除 `PopoverPresentationsObserver`。修掉缺陷 1、3。 +3. **sheet**(已完成):`NSWindow.sheet` 改成泛型并迁过去、补文档注释,加上等父窗口显示;删除 `NSViewController.sheet` 和 `SheetContent.swift`;Examples 跟着改标签。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。`SheetPresentationTests` 共 12 条,AppKit 测试共 50 条 XCTest、58 条 Swift Testing,全部通过。 +4. **popover**:`NSView` 和 `NSToolbarItem` 的 popover 迁过去,加上等锚点显示(用 `RunLoopWait`)和 transaction 的关动画;删除 `PopoverPresentationsObserver`。修掉缺陷 1、3。 5. **present 与 destination**:迁过去,替换时只动自己弹的。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。 6. **清理**:删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;给全部 `UIBinding` 版重载补 `@_disfavoredOverload`,加入第 6 条和下游写法的编译测试。 7. **文档**:按「文档与示例」一节更新文档注释、DocC 首页、`swift-navigation-bindings` skill 和裁决清单。 @@ -392,3 +395,7 @@ final class BindingPresenter { | 2026-11-06 | 通用层不再把 `begin` 包在 `withUITransaction` 里 | 模态循环会在 `begin` 里一直跑,事务会漏给循环里处理的所有事件;需要事务的 style 自己取用 | | 2026-11-06 | 宿主释放、内容被收起后,binding 若还指着那一项就写回 `nil` | 让 binding 与屏幕一致;方案原来只写了「收起并调用 `onDismiss`」 | | 2026-11-06 | `BindingPresenter` 继承 `NSObject` | 沿用 `NSObject.observe` 在主队列上重跑、把 token 存在对象上的做法,与原来的 `NavigationObserver` 一致 | +| 2026-11-06 | 第 3 步:「等」一律改用 run loop 观察者检查条件,不交换 `viewDidMoveToWindow`、不靠窗口通知 | 测试里父窗口显示出来后,遮挡、key、main 三种通知一个都没来,sheet 一直等不到;检查条件只在有东西等时才挂着,成本可以忽略,还省掉了对每个视图生效的方法交换 | +| 2026-11-06 | sheet 与 modal session 在 AppKit 的结束回调之后,再等窗口离开屏幕才算结束 | 测试表明 sheet 的 completion handler 在 sheet 还在屏幕上时就调用了,`onDismiss` 会比「下屏之后」早;session 的 `willClose` 同理 | +| 2026-11-06 | 撤掉还在排队的 sheet 时,对父窗口调用 `endSheet(_:)` | 排队中的 sheet 还没有 `sheetParent`;测试表明这样能把它从队列里撤掉,它之后不会再出现 | +| 2026-11-06 | 更正下游影响:Examples 的 Wi-Fi 案例用了两处 `modal(isModaled:)` | 起草时只搜了带点号的调用;本分支一并改成 `modal(isPresented:)`。本机下游项目用更宽的写法重搜过,仍然没有用到改名的 API | diff --git a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift index 5fbc9378f0..376df845f2 100644 --- a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift @@ -130,7 +130,7 @@ final class ConnectToNetworkViewController: XiblessViewController { progressStackView.isHidden = !model.isConnecting } - modal(isModaled: $model.incorrectPasswordAlertIsPresented) { [unowned self] in + modal(isPresented: $model.incorrectPasswordAlertIsPresented) { [unowned self] in let alert = NSAlert() alert.messageText = "Incorrect password for “\(model.network.name)”" alert.addButton(withTitle: "OK") diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift index 6f7b7c61fa..1e6ca6e18a 100644 --- a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift @@ -37,7 +37,7 @@ final class NetworkDetailViewController: XiblessViewController { // forgetButton.isHidden = model.network.id != model.selectedNetworkID } - modal(isModaled: $model.forgetAlertIsPresented) { [unowned self] in + modal(isPresented: $model.forgetAlertIsPresented) { [unowned self] in let alert = NSAlert() alert.messageText = "Forget Wi-Fi Network “\(model.network.name)”?" alert.informativeText = """ diff --git a/Sources/AppKitNavigation/Internal/RunLoopWait.swift b/Sources/AppKitNavigation/Internal/RunLoopWait.swift new file mode 100644 index 0000000000..d0397f9617 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/RunLoopWait.swift @@ -0,0 +1,44 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + + import AppKit + + /// Waits for something on screen to change — a window to come on screen, a view to get into a + /// window, a sheet to finish leaving the screen — by checking each time the main run loop is + /// about to wait. + /// + /// Notifications are not reliable for this. A window brought on screen in a process that is not + /// the active app — a test runner, for one — posts no occlusion, key or main window notification + /// at all, a view has none for getting into a window, and a sheet's completion handler runs + /// before the sheet has left the screen. The check costs a closure call per turn of the run + /// loop, and only while something is waiting. + @MainActor + enum RunLoopWait { + /// Calls `body` once `condition` holds — right away when it already does — and returns a + /// closure that cancels the wait. + static func until( + _ condition: @escaping @MainActor () -> Bool, + then body: @escaping @MainActor () -> Void + ) -> @MainActor () -> Void { + if condition() { + body() + return {} + } + // NB: In the common modes, so that the wait goes on inside modal loops and while the mouse + // is tracking. + nonisolated(unsafe) let observer = CFRunLoopObserverCreateWithHandler( + nil, CFRunLoopActivity.beforeWaiting.rawValue, true, 0 + ) { observer, _ in + MainActor._assumeIsolated { + guard condition() else { return } + CFRunLoopObserverInvalidate(observer) + body() + } + } + CFRunLoopAddObserver(CFRunLoopGetMain(), observer, .commonModes) + return { + CFRunLoopObserverInvalidate(observer) + } + } + } + +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 696dede7eb..eb5712cfea 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -338,7 +338,8 @@ closeObserver.invalidate() NSApplication.shared.endModalSession(session) ModalStack.modalDidEnd(window) - didEnd() + // NB: The window is still on screen while it is about to close. + _ = RunLoopWait.until({ !window.isVisible }, then: didEnd) } } diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 5bb6f70211..4a65c6ab65 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -1,324 +1,191 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -public import AppKit - -private typealias SheetObserver = NavigationObserver - -@MainActor -private var sheetObserverKeys = AssociatedKeys() - -extension NSWindow { - @discardableResult - public func sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSWindow - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSWindow - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } -} - -extension NSWindow { - @discardableResult - public func sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSAlert - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSAlert - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } -} - -extension NSWindow { - @discardableResult - public func sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSSavePanel - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSSavePanel - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } -} - -extension NSViewController { - @discardableResult - public func sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - _sheet(isSheeted: isSheeted, onDismiss: onDismiss, content: content) - } - - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } - - @_disfavoredOverload - @discardableResult - public func sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _sheet(item: item, onDismiss: onDismiss, content: content) - } + public import AppKit + + extension NSWindow { + /// Attaches a window, an alert, or a save or open panel to this window as a sheet while a + /// binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet(isPresented:onDismiss:content:)`, but for AppKit. Setting the binding + /// to `false` ends the sheet. When the user ends it — a button that ends the sheet, a button of + /// the alert, the panel's Cancel button — the binding is set to `false`. A sheet set to show + /// before this window is on screen waits until it is; one set to show while this window + /// already has a sheet is queued by AppKit until that sheet ends. + /// + /// To present a view controller as a sheet, use + /// ``AppKit/NSViewController/present(isPresented:style:onDismiss:content:)`` with the + /// ``AppKit/NSViewController/TransitionStyle/sheet`` style. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to attach the sheet. + /// - onDismiss: The closure to execute once the sheet has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to attach. + /// - Returns: A token that stops following the binding once cancelled. An attached sheet then + /// stays until the user ends it. + @discardableResult + public func sheet( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> Content + ) -> ObserveToken { + bindPresentation( + SheetStyle(parentWindow: self), + item: isPresented.toOptionalUnit, + id: { $0.id }, + onDismiss: onDismiss + ) { _ in + content() + } + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } + /// Attaches a window, an alert, or a save or open panel to this window as a sheet while a + /// binding to an optional item holds a value. + /// + /// The sheet behaves as with ``sheet(isPresented:onDismiss:content:)``. If the item's identity + /// changes, the sheet ends, and once it has left the screen, a sheet for the new item is + /// attached. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the sheet. While it holds a value, + /// the value is passed to `content`. When the user ends the sheet, the binding is set to + /// `nil`. + /// - onDismiss: The closure to execute once the sheet has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to attach for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + bindPresentation( + SheetStyle(parentWindow: self), item: item, id: { $0.id }, onDismiss: onDismiss + ) { + content($0.wrappedValue) + } + } - @discardableResult - public func sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss, content: content) - } -} + /// Attaches a window, an alert, or a save or open panel to this window as a sheet while a + /// binding to an optional item holds a value, passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the sheet. While it holds a value, + /// a binding to the value is passed to `content`. When the user ends the sheet, the + /// binding is set to `nil`. + /// - onDismiss: The closure to execute once the sheet has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to attach for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + bindPresentation( + SheetStyle(parentWindow: self), + item: item, + id: { $0.id }, + onDismiss: onDismiss, + content: content + ) + } -extension SheetContent { - @discardableResult - fileprivate func _sheet( - isSheeted: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> Content - ) -> ObserveToken { - _sheet(item: isSheeted.toOptionalUnit, onDismiss: onDismiss) { _ in content() } - } + /// Attaches a window, an alert, or a save or open panel to this window as a sheet while a + /// binding to an optional item holds a value, telling items apart by the identifier at a key + /// path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the sheet. While it holds a value, + /// the value is passed to `content`. When the user ends the sheet, the binding is set to + /// `nil`. + /// - id: The key path to the item's identifier. When it changes, the sheet ends, and once it + /// has left the screen, a sheet for the new item is attached. + /// - onDismiss: The closure to execute once the sheet has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to attach for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> Content + ) -> ObserveToken { + bindPresentation( + SheetStyle(parentWindow: self), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss + ) { + content($0.wrappedValue) + } + } - @discardableResult - fileprivate func _sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) + /// Attaches a window, an alert, or a save or open panel to this window as a sheet while a + /// binding to an optional item holds a value, telling items apart by the identifier at a key + /// path and passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the sheet. While it holds a value, + /// a binding to the value is passed to `content`. When the user ends the sheet, the + /// binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the sheet ends, and once it + /// has left the screen, a sheet for the new item is attached. + /// - onDismiss: The closure to execute once the sheet has ended and left the screen. + /// - content: A closure that returns the window, alert or panel to attach for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func sheet( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> Content + ) -> ObserveToken { + bindPresentation( + SheetStyle(parentWindow: self), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss, + content: content + ) + } } - @_disfavoredOverload - @discardableResult - fileprivate func _sheet( - item: UIBinding, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _sheet(item: item, id: \.id, onDismiss: onDismiss, content: content) - } + /// Attaches content to a window as a sheet. + @MainActor + private struct SheetStyle: PresentationStyle { + weak var parentWindow: NSWindow? - @discardableResult - fileprivate func _sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> Content - ) -> ObserveToken { - _sheet(item: item, id: id, onDismiss: onDismiss) { - content($0.wrappedValue) + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + RunLoopWait.until( + { [weak parentWindow] in parentWindow?.isVisible == true }, + then: body + ) } - } - @discardableResult - fileprivate func _sheet( - item: UIBinding, - id: KeyPath, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> Content - ) -> ObserveToken { - _sheet(item: item, id: id) { $item in - content($item) - } beginSheet: { [weak self] child, _ in - guard let self else { return } - if let attachedContent = attachedContent { - self.endSheet(for: attachedContent) - onDismiss?() - Task { @MainActor in - await self.beginSheet(for: child) - child.onEndNavigation?() - child.onEndNavigation = nil - } - } else { - Task { @MainActor in - await self.beginSheet(for: child) - child.onEndNavigation?() - child.onEndNavigation = nil - } + func begin( + _ content: Content, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + guard let parentWindow else { + didEnd() + return + } + let sheetWindow = content._appKitNavigationWindow + content._appKitNavigationBeginSheet(attachedTo: parentWindow) { + // NB: The completion handler runs as the sheet starts to leave, while it is still on + // screen. + _ = RunLoopWait.until({ !sheetWindow.isVisible }, then: didEnd) } - } endSheet: { [weak self] content, _ in - self?.endSheet(for: content) - onDismiss?() } - } - private func _sheet( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> Content, - beginSheet: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void, - endSheet: @escaping ( - _ child: Content, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let sheetObserver: SheetObserver = sheetObserver() - return sheetObserver.observe( - item: item, - id: { $0[keyPath: id] }, - content: content, - begin: beginSheet, - end: endSheet - ) - } - - private func sheetObserver() -> SheetObserver { - if let observer = objc_getAssociatedObject(self, sheetObserverKeys.key(of: Content.self)) as? SheetObserver { - return observer - } else { - let observer = SheetObserver(owner: self) - objc_setAssociatedObject(self, sheetObserverKeys.key(of: Content.self), observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return observer + func end(_ content: Content, transaction: UITransaction) { + let sheetWindow = content._appKitNavigationWindow + // NB: A sheet still queued behind another one has no sheet parent yet. + (sheetWindow.sheetParent ?? parentWindow)?.endSheet(sheetWindow) } } -} - -extension Navigated where Content: SheetContent { - func clearup() { - guard let window = content?.currentWindow else { return } - window.sheetParent?.endSheet(window) - } -} #endif diff --git a/Sources/AppKitNavigation/Navigation/SheetContent.swift b/Sources/AppKitNavigation/Navigation/SheetContent.swift deleted file mode 100644 index da9fa3ee7b..0000000000 --- a/Sources/AppKitNavigation/Navigation/SheetContent.swift +++ /dev/null @@ -1,86 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit -import AppKitNavigationShim -import SwiftNavigation - -@MainActor -protocol SheetContent: NavigationContent { - var currentWindow: NSWindow? { get } - var attachedContent: (any SheetContent)? { get } - func beginSheet(for content: any SheetContent) async - func endSheet(for content: any SheetContent) -} - -extension SheetContent { - var attachedContent: (any SheetContent)? { currentWindow?.attachedSheet } - - func beginSheet(for content: any SheetContent) async { - guard let sheetedWindow = content.currentWindow else { return } - await currentWindow?.beginSheet(sheetedWindow) - } - - func endSheet(for content: any SheetContent) { - guard let sheetedWindow = content.currentWindow else { return } - currentWindow?.endSheet(sheetedWindow) - } -} - -extension NSWindow: SheetContent { - var currentWindow: NSWindow? { self } -} - -extension NSAlert: SheetContent { - var currentWindow: NSWindow? { window } - - func beginSheet(for content: any SheetContent) async { - guard let parentWindow = content.currentWindow else { return } - await beginSheetModal(for: parentWindow) - } - - func endSheet(for content: any SheetContent) { - content.currentWindow?.endSheet(window) - } -} - -extension NSSavePanel { - func beginSheet(for content: any SheetContent) async { - guard let parentWindow = content.currentWindow else { return } - await beginSheetModal(for: parentWindow) - } - - func endSheet(for content: any SheetContent) { - content.currentWindow?.endSheet(self) - } -} - -extension NSViewController: SheetContent { - var currentWindow: NSWindow? { view.window } - - var attachedContent: (any SheetContent)? { currentWindow?.attachedSheet?.contentViewController } - - func beginSheet(for content: any SheetContent) async { - guard let viewController = content as? NSViewController else { return } - // NB: Unlike a window's 'beginSheet', 'presentAsSheet' returns as soon as the sheet is up, and - // the caller resets the binding the moment this returns. Suspend until the sheet is - // dismissed instead, which the shim reports from the dismissed controller's - // 'viewDidDisappear'. - await withCheckedContinuation { continuation in - MainActor._assumeIsolated { - let onDismiss = viewController._AppKitNavigation_onDismiss - viewController._AppKitNavigation_onDismiss = { - onDismiss?() - continuation.resume() - } - presentAsSheet(viewController) - } - } - } - - func endSheet(for content: any SheetContent) { - guard let viewController = content as? NSViewController else { return } - dismiss(viewController) - } -} - -#endif diff --git a/Tests/AppKitNavigationTests/ModalPresentationTests.swift b/Tests/AppKitNavigationTests/ModalPresentationTests.swift index 9a12f554ab..6325ba1c26 100644 --- a/Tests/AppKitNavigationTests/ModalPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ModalPresentationTests.swift @@ -51,6 +51,29 @@ ) } + @MainActor + func testOnDismissRunsOnceTheSessionWindowHasLeftTheScreen() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + var windowWasVisibleAtDismiss: Bool? + host.modalSession( + isPresented: $isPresented, + onDismiss: { windowWasVisibleAtDismiss = window.isVisible } + ) { + window + } + + isPresented = true + XCTAssertTrue(waitUntil { window.isVisible }, "The window never appeared") + window.close() + XCTAssertTrue(waitUntil { windowWasVisibleAtDismiss != nil }, "'onDismiss' never ran") + + XCTAssertEqual( + windowWasVisibleAtDismiss, false, "'onDismiss' ran while the window was on screen" + ) + } + @MainActor func testStartingAModalSessionLeavesAnotherBindingsSessionInPlace() { let host = NSObject() diff --git a/Tests/AppKitNavigationTests/SheetPresentationTests.swift b/Tests/AppKitNavigationTests/SheetPresentationTests.swift index 22b0e9b2f9..ec0b828755 100644 --- a/Tests/AppKitNavigationTests/SheetPresentationTests.swift +++ b/Tests/AppKitNavigationTests/SheetPresentationTests.swift @@ -19,10 +19,10 @@ func testSettingTheBindingToTrueAttachesTheWindowAsASheet() { let host = makeHost() let sheetWindow = makeWindow() - @UIBinding var isSheeted = false - host.window.sheet(isSheeted: $isSheeted) { sheetWindow } + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" @@ -33,15 +33,15 @@ func testSettingTheBindingToFalseEndsTheSheet() { let host = makeHost() let sheetWindow = makeWindow() - @UIBinding var isSheeted = false - host.window.sheet(isSheeted: $isSheeted) { sheetWindow } + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" ) - isSheeted = false + isPresented = false XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not ended") } @@ -50,10 +50,10 @@ func testUserEndingTheSheetWritesFalseBack() { let host = makeHost() let sheetWindow = makeWindow() - @UIBinding var isSheeted = false - host.window.sheet(isSheeted: $isSheeted) { sheetWindow } + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" ) @@ -61,63 +61,162 @@ // What a Cancel button in the sheet does. host.window.endSheet(sheetWindow) - XCTAssertTrue(waitUntil { !isSheeted }, "Ending the sheet did not write 'false' back") + XCTAssertTrue(waitUntil { !isPresented }, "Ending the sheet did not write 'false' back") } @MainActor func testSettingTheBindingToFalseCallsOnDismissOnce() { let host = makeHost() let sheetWindow = makeWindow() - @UIBinding var isSheeted = false + @UIBinding var isPresented = false var dismissCount = 0 - host.window.sheet(isSheeted: $isSheeted, onDismiss: { dismissCount += 1 }) { sheetWindow } + host.window.sheet(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { + sheetWindow + } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" ) - isSheeted = false + isPresented = false XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not ended") spinRunLoop(for: 0.3) XCTAssertEqual(dismissCount, 1) } + @MainActor + func testOnDismissRunsOnceTheSheetHasLeftTheScreen() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isPresented = false + var sheetWasVisibleAtDismiss: Bool? + host.window.sheet( + isPresented: $isPresented, + onDismiss: { sheetWasVisibleAtDismiss = sheetWindow.isVisible } + ) { + sheetWindow + } + + isPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + isPresented = false + XCTAssertTrue(waitUntil { sheetWasVisibleAtDismiss != nil }, "'onDismiss' never ran") + + XCTAssertEqual(sheetWasVisibleAtDismiss, false, "'onDismiss' ran while the sheet was on screen") + } + + @MainActor + func testSheetWaitsUntilTheParentWindowIsShown() { + let parentWindow = makeWindow(width: 480, height: 320) + let sheetWindow = makeWindow() + // Already 'true' when the sheet is set up, before the window is on screen. + @UIBinding var isPresented = true + parentWindow.sheet(isPresented: $isPresented) { sheetWindow } + spinRunLoop(for: 0.3) + XCTAssertNil(parentWindow.attachedSheet, "The sheet was attached to a window off screen") + + parentWindow.orderFront(nil) + + XCTAssertTrue( + waitUntil { parentWindow.attachedSheet === sheetWindow }, + "The sheet never appeared once the window was on screen" + ) + parentWindow.endSheet(sheetWindow) + } + + @MainActor + func testChangingTheItemEndsTheSheetBeforeTheNextOneIsAttached() { + struct Item: Identifiable { + let id: Int + } + let host = makeHost() + let firstSheet = makeWindow() + let secondSheet = makeWindow() + @UIBinding var item: Item? + var dismissCount = 0 + host.window.sheet(item: $item, onDismiss: { dismissCount += 1 }) { currentItem in + currentItem.id == 1 ? firstSheet : secondSheet + } + + item = Item(id: 1) + XCTAssertTrue( + waitUntil { host.window.attachedSheet === firstSheet }, "The first sheet never appeared" + ) + item = Item(id: 2) + XCTAssertTrue( + waitUntil { host.window.attachedSheet === secondSheet }, + "The second item's sheet never took the first one's place" + ) + + XCTAssertFalse(firstSheet.isVisible, "The first item's sheet is still on screen") + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run exactly once for the first item") + item = nil + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The second sheet never ended") + } + @MainActor func testPresentingASheetLeavesAnotherBindingsSheetInPlace() { let host = makeHost() let firstSheet = makeWindow() let secondSheet = makeWindow() - @UIBinding var isFirstSheeted = false - @UIBinding var isSecondSheeted = false + @UIBinding var isFirstPresented = false + @UIBinding var isSecondPresented = false var secondDismissCount = 0 - host.window.sheet(isSheeted: $isFirstSheeted) { firstSheet } - host.window.sheet(isSheeted: $isSecondSheeted, onDismiss: { secondDismissCount += 1 }) { + host.window.sheet(isPresented: $isFirstPresented) { firstSheet } + host.window.sheet(isPresented: $isSecondPresented, onDismiss: { secondDismissCount += 1 }) { secondSheet } - isFirstSheeted = true + isFirstPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === firstSheet }, "The first sheet never appeared" ) - isSecondSheeted = true + isSecondPresented = true spinRunLoop(for: 0.5) - XCTExpectFailure( - "A new sheet ends whatever sheet the window has, and calls its own onDismiss for it" - ) { - XCTAssertTrue(isFirstSheeted, "Presenting the second sheet ended the first binding's sheet") - XCTAssertEqual( - secondDismissCount, 0, - "The second binding's 'onDismiss' ran for a sheet it never presented" - ) - } + XCTAssertTrue(isFirstPresented, "Presenting the second sheet ended the first binding's sheet") + XCTAssertEqual( + secondDismissCount, 0, "The second binding's 'onDismiss' ran for a sheet it never presented" + ) - isFirstSheeted = false - isSecondSheeted = false + isFirstPresented = false + XCTAssertTrue( + waitUntil { host.window.attachedSheet === secondSheet }, + "The queued sheet never appeared once the first one ended" + ) + isSecondPresented = false XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheets never went away") } + @MainActor + func testEndingAQueuedSheetKeepsItFromAppearing() { + let host = makeHost() + let firstSheet = makeWindow() + let secondSheet = makeWindow() + @UIBinding var isFirstPresented = false + @UIBinding var isSecondPresented = false + host.window.sheet(isPresented: $isFirstPresented) { firstSheet } + host.window.sheet(isPresented: $isSecondPresented) { secondSheet } + + isFirstPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === firstSheet }, "The first sheet never appeared" + ) + isSecondPresented = true + spinRunLoop(for: 0.3) + isSecondPresented = false + spinRunLoop(for: 0.3) + isFirstPresented = false + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The first sheet never ended") + spinRunLoop(for: 0.5) + + XCTAssertNil(host.window.attachedSheet, "The second sheet appeared after its binding ended it") + XCTAssertFalse(secondSheet.isVisible, "The second sheet appeared after its binding ended it") + } + // MARK: - Alert content @MainActor @@ -126,10 +225,10 @@ let alert = NSAlert() alert.messageText = "Delete the item?" alert.addButton(withTitle: "Delete") - @UIBinding var isSheeted = false - host.window.sheet(isSheeted: $isSheeted) { alert } + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { alert } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === alert.window }, "The alert never appeared as a sheet" @@ -138,7 +237,7 @@ deleteButton.performClick(nil) XCTAssertTrue( - waitUntil { host.window.attachedSheet == nil && !isSheeted }, + waitUntil { host.window.attachedSheet == nil && !isPresented }, "Clicking the alert's button did not end the sheet" ) } @@ -150,10 +249,10 @@ alert.messageText = "Delete the item?" alert.informativeText = "This can't be undone." alert.addButton(withTitle: "Delete") - @UIBinding var isSheeted = false - host.window.sheet(isSheeted: $isSheeted) { alert } + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { alert } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil { host.window.attachedSheet === alert.window }, "The alert never appeared as a sheet" @@ -179,10 +278,10 @@ func testCancellingASavePanelSheetEndsTheSheetAndWritesFalseBack() { let host = makeHost() let savePanel = NSSavePanel() - @UIBinding var isSheeted = false - host.window.sheet(isSheeted: $isSheeted) { savePanel } + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { savePanel } - isSheeted = true + isPresented = true XCTAssertTrue( waitUntil(timeout: 8) { host.window.attachedSheet === savePanel }, "The save panel never appeared as a sheet" @@ -190,14 +289,10 @@ // What the panel's Cancel button does. savePanel.cancel(nil) - XCTExpectFailure( - "A save panel is attached with NSWindow.beginSheet(_:) instead of its own beginSheetModal(for:)" - ) { - XCTAssertTrue( - waitUntil(timeout: 5) { host.window.attachedSheet == nil && !isSheeted }, - "Cancelling the panel did not end the sheet" - ) - } + XCTAssertTrue( + waitUntil(timeout: 5) { host.window.attachedSheet == nil && !isPresented }, + "Cancelling the panel did not end the sheet" + ) } } #endif diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift index 99b0e8ec24..f198872d2f 100644 --- a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -3,8 +3,7 @@ import AppKitNavigation import XCTest - /// Presentations whose content is a view controller, through `present(isPresented:style:)` and - /// `sheet(isSheeted:)`. + /// Presentations whose content is a view controller, through `present(isPresented:style:)`. final class ViewControllerPresentationTests: XCTestCase { override func setUp() { super.setUp() @@ -135,35 +134,21 @@ XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheets never went away") } + // NB: 'sheet(isSheeted:)' once dismissed a view controller sheet the moment it appeared, while + // its own implementation of sheets still existed next to this one. @MainActor - func testViewControllerSheetStaysPresentedUntilItIsDismissed() { + func testPresentedSheetStaysPresentedUntilItIsDismissed() { let host = makeHost() - @UIBinding var isSheeted = false - host.viewController.sheet(isSheeted: $isSheeted) { + @UIBinding var isPresented = false + host.viewController.present(isPresented: $isPresented, style: .sheet) { self.makeViewController() } - isSheeted = true - XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") - spinRunLoop(for: 0.5) - - XCTAssertTrue(isSheeted, "The sheet dismissed itself right after it appeared") - } - - @MainActor - func testUserDismissingAViewControllerSheetWritesFalseBack() { - let host = makeHost() - @UIBinding var isSheeted = false - let sheetViewController = makeViewController() - host.viewController.sheet(isSheeted: $isSheeted) { sheetViewController } - - isSheeted = true + isPresented = true XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") spinRunLoop(for: 0.5) - sheetViewController.dismiss(nil) - - XCTAssertTrue(waitUntil { !isSheeted }, "Dismissing the sheet did not write 'false' back") + XCTAssertTrue(isPresented, "The sheet dismissed itself right after it appeared") } } #endif From 8523a0021e0cd530d709c7b366fbcb20a4370014 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 22:54:05 +0800 Subject: [PATCH 097/141] feat(appkit): show popovers through the shared presentation lifecycle Move the NSView and NSToolbarItem popovers onto BindingPresenter. The presentation now holds its popover while it is shown, which fixes two defects the tests reproduced: - A popover the user closed wrote false back but never called onDismiss: it was released as soon as it closed, before observe re-ran, and onDismiss only ran from that re-run. - A popover for a new item left the previous item's popover open, which an application-defined popover then kept forever. A popover set to show before its view is in a window on screen, or before its toolbar item's window is, waits until it is. A transaction that disables animations now turns off the popover's animation for that change. Each presentation observes its own popover, so the process-wide PopoverPresentationsObserver goes away. --- .../draft-appkit-presentation-redesign.md | 4 +- .../PopoverPresentationsObserver.swift | 24 - .../AppKitNavigation/Navigation/Popover.swift | 957 +++++++++--------- .../Navigation/PopoverContent.swift | 37 - .../PopoverPresentationTests.swift | 194 +++- 5 files changed, 647 insertions(+), 569 deletions(-) delete mode 100644 Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift delete mode 100644 Sources/AppKitNavigation/Navigation/PopoverContent.swift diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index 5fd79f5c58..e27b11ef97 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -355,7 +355,7 @@ final class BindingPresenter { 1. **补测试作安全网**(已完成):按「测试」一节补现有行为的测试(改动前就通过)和问题的测试(先标预期失败)。共享的等待、建窗口、记录 popover 的辅助放进 `PresentationTestSupport.swift`,两份原有测试改用它。新增 `SheetPresentationTests`、`PopoverPresentationTests`,`ModalPresentationTests`、`ViewControllerPresentationTests` 各有补充;AppKit 测试共 39 条 XCTest、58 条 Swift Testing,全部通过。 2. **通用层与 modal**(已完成):加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签、补文档注释;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。`ModalPresentationTests` 共 17 条,连跑 5 次全部通过。 3. **sheet**(已完成):`NSWindow.sheet` 改成泛型并迁过去、补文档注释,加上等父窗口显示;删除 `NSViewController.sheet` 和 `SheetContent.swift`;Examples 跟着改标签。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。`SheetPresentationTests` 共 12 条,AppKit 测试共 50 条 XCTest、58 条 Swift Testing,全部通过。 -4. **popover**:`NSView` 和 `NSToolbarItem` 的 popover 迁过去,加上等锚点显示(用 `RunLoopWait`)和 transaction 的关动画;删除 `PopoverPresentationsObserver`。修掉缺陷 1、3。 +4. **popover**(已完成):`NSView` 和 `NSToolbarItem` 的 popover 迁过去、补文档注释,加上等锚点显示(用 `RunLoopWait`)和 transaction 的关动画;删除 `PopoverContent.swift` 与 `PopoverPresentationsObserver`。修掉缺陷 1、3。`PopoverPresentationTests` 共 12 条(含工具栏项的两条),AppKit 测试共 56 条 XCTest、58 条 Swift Testing,全部通过。 5. **present 与 destination**:迁过去,替换时只动自己弹的。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。 6. **清理**:删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;给全部 `UIBinding` 版重载补 `@_disfavoredOverload`,加入第 6 条和下游写法的编译测试。 7. **文档**:按「文档与示例」一节更新文档注释、DocC 首页、`swift-navigation-bindings` skill 和裁决清单。 @@ -399,3 +399,5 @@ final class BindingPresenter { | 2026-11-06 | sheet 与 modal session 在 AppKit 的结束回调之后,再等窗口离开屏幕才算结束 | 测试表明 sheet 的 completion handler 在 sheet 还在屏幕上时就调用了,`onDismiss` 会比「下屏之后」早;session 的 `willClose` 同理 | | 2026-11-06 | 撤掉还在排队的 sheet 时,对父窗口调用 `endSheet(_:)` | 排队中的 sheet 还没有 `sheetParent`;测试表明这样能把它从队列里撤掉,它之后不会再出现 | | 2026-11-06 | 更正下游影响:Examples 的 Wi-Fi 案例用了两处 `modal(isModaled:)` | 起草时只搜了带点号的调用;本分支一并改成 `modal(isPresented:)`。本机下游项目用更宽的写法重搜过,仍然没有用到改名的 API | +| 2026-11-06 | 第 4 步:工具栏项照样等它所在的窗口显示,没有先去试 AppKit 自己怎么处理 | 与其他锚点的等待一致,代价只是一次检查;测试覆盖了「窗口还没显示就设成 `true`」 | +| 2026-11-06 | popover 被要求关闭时若已不在屏幕上,直接算作结束 | 从没显示出来、或正在被用户关掉的 popover 不会再发关闭通知,不这样做 presenter 会一直停在「结束中」 | diff --git a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift b/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift deleted file mode 100644 index d0fe2e0acc..0000000000 --- a/Sources/AppKitNavigation/Internal/PopoverPresentationsObserver.swift +++ /dev/null @@ -1,24 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -public import AppKit -import Combine - -@MainActor -final class PopoverPresentationsObserver: NSObject { - static let shared = PopoverPresentationsObserver() - - var popoverCancellables: [NSPopover: AnyCancellable] = [:] - - func observePopover(_ popover: NSPopover, onDidClose: @escaping @MainActor () -> Void) { - popoverCancellables[popover] = NotificationCenter.default - .publisher(for: NSPopover.didCloseNotification, object: popover) - .sink { [weak self] _ in - MainActor._assumeIsolated { - onDidClose() - self?.popoverCancellables.removeValue(forKey: popover) - } - } - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/Popover.swift b/Sources/AppKitNavigation/Navigation/Popover.swift index 0849287468..d0f73ffc00 100644 --- a/Sources/AppKitNavigation/Navigation/Popover.swift +++ b/Sources/AppKitNavigation/Navigation/Popover.swift @@ -1,542 +1,507 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -public import AppKit - -@MainActor -fileprivate final class _PopoverPresentation: NSObject, PopoverContent { - let popover: NSPopover - - init( - viewController: NSViewController, - behavior: NSPopover.Behavior, - animates: Bool - ) { - let popover = NSPopover() - popover.contentViewController = viewController - popover.behavior = behavior - popover.animates = animates - self.popover = popover - super.init() - } -} - -private typealias PopoverObserver = NavigationObserver + public import AppKit + + extension NSView { + /// Shows a view controller in a popover anchored to this view while a binding to a Boolean + /// value you provide is true. + /// + /// Like SwiftUI's `popover(isPresented:attachmentAnchor:arrowEdge:content:)`, but for AppKit. + /// Setting the binding to `false` closes the popover. When the user closes it — by clicking + /// outside a transient popover, or by pressing Escape — the binding is set to `false`. A + /// popover set to show before this view is in a window on screen waits until it is. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to show the popover. + /// - rect: The rectangle, in this view's coordinates, that the popover points at. The + /// default, `.zero`, points at the whole view. + /// - preferredEdge: The edge of `rect` the popover prefers to show from. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show in the popover. + /// - Returns: A token that stops following the binding once cancelled. A popover that is shown + /// then stays until the user closes it. + @discardableResult + public func popover( + isPresented: UIBinding, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(rect: rect, preferredEdge: preferredEdge, behavior: behavior, animates: animates), + item: isPresented.toOptionalUnit, + id: { $0.id }, + onDismiss: onDismiss + ) { _ in + PopoverContent(viewController: content()) + } + } -@MainActor -private let popoverObserverKey = malloc(1)! + /// Shows a view controller in a popover anchored to this view while a binding to an optional + /// item holds a value. + /// + /// The popover behaves as with + /// ``popover(isPresented:relativeTo:preferredEdge:behavior:animates:onDismiss:content:)``. If + /// the item's identity changes, the popover closes, and once it has, a popover for the new + /// item shows. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// the value is passed to `content`. When the user closes the popover, the binding is set + /// to `nil`. + /// - rect: The rectangle, in this view's coordinates, that the popover points at. The + /// default, `.zero`, points at the whole view. + /// - preferredEdge: The edge of `rect` the popover prefers to show from. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func popover( + item: UIBinding, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(rect: rect, preferredEdge: preferredEdge, behavior: behavior, animates: animates), + item: item, + id: { $0.id }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0.wrappedValue)) + } + } -extension NSView { - @discardableResult - public func popover( - isPresented: UIBinding, - relativeTo rect: NSRect = .zero, - preferredEdge: NSRectEdge = .minY, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - _popover( - isPresented: isPresented, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + /// Shows a view controller in a popover anchored to this view while a binding to an optional + /// item holds a value, passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// a binding to the value is passed to `content`. When the user closes the popover, the + /// binding is set to `nil`. + /// - rect: The rectangle, in this view's coordinates, that the popover points at. The + /// default, `.zero`, points at the whole view. + /// - preferredEdge: The edge of `rect` the popover prefers to show from. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func popover( + item: UIBinding, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(rect: rect, preferredEdge: preferredEdge, behavior: behavior, animates: animates), + item: item, + id: { $0.id }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0)) + } + } - @discardableResult - public func popover( - item: UIBinding, - relativeTo rect: NSRect = .zero, - preferredEdge: NSRectEdge = .minY, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + /// Shows a view controller in a popover anchored to this view while a binding to an optional + /// item holds a value, telling items apart by the identifier at a key path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// the value is passed to `content`. When the user closes the popover, the binding is set + /// to `nil`. + /// - id: The key path to the item's identifier. When it changes, the popover closes, and + /// once it has, a popover for the new item shows. + /// - rect: The rectangle, in this view's coordinates, that the popover points at. The + /// default, `.zero`, points at the whole view. + /// - preferredEdge: The edge of `rect` the popover prefers to show from. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(rect: rect, preferredEdge: preferredEdge, behavior: behavior, animates: animates), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0.wrappedValue)) + } + } - @_disfavoredOverload - @discardableResult - public func popover( - item: UIBinding, - relativeTo rect: NSRect = .zero, - preferredEdge: NSRectEdge = .minY, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + /// Shows a view controller in a popover anchored to this view while a binding to an optional + /// item holds a value, telling items apart by the identifier at a key path and passing the + /// content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// a binding to the value is passed to `content`. When the user closes the popover, the + /// binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the popover closes, and + /// once it has, a popover for the new item shows. + /// - rect: The rectangle, in this view's coordinates, that the popover points at. The + /// default, `.zero`, points at the whole view. + /// - preferredEdge: The edge of `rect` the popover prefers to show from. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + relativeTo rect: NSRect = .zero, + preferredEdge: NSRectEdge = .minY, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(rect: rect, preferredEdge: preferredEdge, behavior: behavior, animates: animates), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0)) + } + } - @discardableResult - public func popover( - item: UIBinding, - id: KeyPath, - relativeTo rect: NSRect = .zero, - preferredEdge: NSRectEdge = .minY, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: id, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) + private func popoverStyle( + rect: NSRect, + preferredEdge: NSRectEdge, + behavior: NSPopover.Behavior, + animates: Bool + ) -> PopoverStyle { + PopoverStyle( + anchor: ViewAnchor(view: self, rect: rect, preferredEdge: preferredEdge), + behavior: behavior, + animates: animates + ) + } } - @discardableResult - public func popover( - item: UIBinding, - id: KeyPath, - relativeTo rect: NSRect = .zero, - preferredEdge: NSRectEdge = .minY, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: id, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } -} + @available(macOS 14.0, *) + extension NSToolbarItem { + /// Shows a view controller in a popover anchored to this toolbar item while a binding to a + /// Boolean value you provide is true. + /// + /// Setting the binding to `false` closes the popover. When the user closes it — by clicking + /// outside a transient popover, or by pressing Escape — the binding is set to `false`. A + /// popover set to show before the item's toolbar is on screen waits until it is. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to show the popover. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show in the popover. + /// - Returns: A token that stops following the binding once cancelled. A popover that is shown + /// then stays until the user closes it. + @discardableResult + public func popover( + isPresented: UIBinding, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(behavior: behavior, animates: animates), + item: isPresented.toOptionalUnit, + id: { $0.id }, + onDismiss: onDismiss + ) { _ in + PopoverContent(viewController: content()) + } + } -extension NSView { - @discardableResult - fileprivate func _popover( - isPresented: UIBinding, - relativeTo rect: NSRect, - preferredEdge: NSRectEdge, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - _popover( - item: isPresented.toOptionalUnit, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss - ) { _ in content() } - } + /// Shows a view controller in a popover anchored to this toolbar item while a binding to an + /// optional item holds a value. + /// + /// The popover behaves as with ``popover(isPresented:behavior:animates:onDismiss:content:)``. + /// If the item's identity changes, the popover closes, and once it has, a popover for the new + /// item shows. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// the value is passed to `content`. When the user closes the popover, the binding is set + /// to `nil`. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func popover( + item: UIBinding, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(behavior: behavior, animates: animates), + item: item, + id: { $0.id }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0.wrappedValue)) + } + } - @discardableResult - fileprivate func _popover( - item: UIBinding, - relativeTo rect: NSRect, - preferredEdge: NSRectEdge, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: \.id, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + /// Shows a view controller in a popover anchored to this toolbar item while a binding to an + /// optional item holds a value, passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// a binding to the value is passed to `content`. When the user closes the popover, the + /// binding is set to `nil`. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func popover( + item: UIBinding, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(behavior: behavior, animates: animates), + item: item, + id: { $0.id }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0)) + } + } - @_disfavoredOverload - @discardableResult - fileprivate func _popover( - item: UIBinding, - relativeTo rect: NSRect, - preferredEdge: NSRectEdge, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: \.id, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + /// Shows a view controller in a popover anchored to this toolbar item while a binding to an + /// optional item holds a value, telling items apart by the identifier at a key path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// the value is passed to `content`. When the user closes the popover, the binding is set + /// to `nil`. + /// - id: The key path to the item's identifier. When it changes, the popover closes, and + /// once it has, a popover for the new item shows. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(behavior: behavior, animates: animates), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0.wrappedValue)) + } + } - @discardableResult - fileprivate func _popover( - item: UIBinding, - id: KeyPath, - relativeTo rect: NSRect, - preferredEdge: NSRectEdge, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: id, - relativeTo: rect, - preferredEdge: preferredEdge, - behavior: behavior, - animates: animates, - onDismiss: onDismiss - ) { - content($0.wrappedValue) + /// Shows a view controller in a popover anchored to this toolbar item while a binding to an + /// optional item holds a value, telling items apart by the identifier at a key path and + /// passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the popover. While it holds a value, + /// a binding to the value is passed to `content`. When the user closes the popover, the + /// binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the popover closes, and + /// once it has, a popover for the new item shows. + /// - behavior: Whether the popover closes when the user interacts with something else. + /// - animates: Whether the popover animates showing and closing. A transaction that disables + /// animations turns it off for the change it comes with. + /// - onDismiss: The closure to execute once the popover has closed. + /// - content: A closure that returns the view controller to show for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func popover( + item: UIBinding, + id: KeyPath, + behavior: NSPopover.Behavior = .transient, + animates: Bool = true, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + bindPresentation( + popoverStyle(behavior: behavior, animates: animates), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss + ) { + PopoverContent(viewController: content($0)) + } } - } - @discardableResult - fileprivate func _popover( - item: UIBinding, - id: KeyPath, - relativeTo rect: NSRect, - preferredEdge: NSRectEdge, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover(item: item, id: id) { binding in - _PopoverPresentation( - viewController: content(binding), + private func popoverStyle( + behavior: NSPopover.Behavior, + animates: Bool + ) -> PopoverStyle { + PopoverStyle( + anchor: ToolbarItemAnchor(toolbarItem: self), behavior: behavior, animates: animates ) - } beginPopover: { [weak self] presentation, _ in - guard let self else { return } - presentation.appKitNavigationShowPopover( - relativeTo: rect, - of: self, - preferredEdge: preferredEdge - ) - } endPopover: { presentation, _ in - presentation.appKitNavigationClosePopover() - onDismiss?() } } - private func _popover( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> _PopoverPresentation, - beginPopover: @escaping ( - _ child: _PopoverPresentation, - _ transaction: UITransaction - ) -> Void, - endPopover: @escaping ( - _ child: _PopoverPresentation, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let popoverObserver = popoverObserver() - return popoverObserver.observe( - item: item, - id: { $0[keyPath: id] }, - content: content, - begin: beginPopover, - end: endPopover - ) - } + // MARK: - Style - private func popoverObserver() -> PopoverObserver { - if let observer = objc_getAssociatedObject(self, popoverObserverKey) as? PopoverObserver { - return observer - } else { - let observer = PopoverObserver(owner: self) - objc_setAssociatedObject( - self, - popoverObserverKey, - observer, - .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - return observer - } - } -} + /// What a popover points at: a view, or a toolbar item. + @MainActor + private protocol PopoverAnchor: Sendable { + /// Whether the anchor is on screen, so that a popover can point at it. + var isOnScreen: Bool { get } -extension Navigated where Content: PopoverContent { - func clearup() { - content?.appKitNavigationClosePopover() + func show(_ popover: NSPopover) } -} -@available(macOS 14.0, *) -private typealias ToolbarItemPopoverObserver = NavigationObserver + @MainActor + private struct ViewAnchor: PopoverAnchor { + weak var view: NSView? + let rect: NSRect + let preferredEdge: NSRectEdge -@MainActor -private let toolbarItemPopoverObserverKey = malloc(1)! + var isOnScreen: Bool { + view?.window?.isVisible == true + } -@available(macOS 14.0, *) -extension NSToolbarItem { - @discardableResult - public func popover( - isPresented: UIBinding, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - _popover( - isPresented: isPresented, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) + func show(_ popover: NSPopover) { + guard let view else { return } + popover.show(relativeTo: rect, of: view, preferredEdge: preferredEdge) + } } - @discardableResult - public func popover( - item: UIBinding, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + @available(macOS 14.0, *) + @MainActor + private struct ToolbarItemAnchor: PopoverAnchor { + weak var toolbarItem: NSToolbarItem? - @_disfavoredOverload - @discardableResult - public func popover( - item: UIBinding, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + var isOnScreen: Bool { + guard let toolbar = toolbarItem?.toolbar, toolbar.isVisible else { return false } + return NSApplication.shared.windows.contains { $0.toolbar === toolbar && $0.isVisible } + } - @discardableResult - public func popover( - item: UIBinding, - id: KeyPath, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: id, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) + func show(_ popover: NSPopover) { + guard let toolbarItem else { return } + popover.show(relativeTo: toolbarItem) + } } - @discardableResult - public func popover( - item: UIBinding, - id: KeyPath, - behavior: NSPopover.Behavior = .transient, - animates: Bool = true, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: id, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } -} + /// A popover shown for one item, and what is needed to tell when it has closed. + @MainActor + private final class PopoverContent { + let popover = NSPopover() + var closeObserver: NotificationObserver? + var didEnd: (@MainActor () -> Void)? -@available(macOS 14.0, *) -extension NSToolbarItem { - @discardableResult - fileprivate func _popover( - isPresented: UIBinding, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - _popover( - item: isPresented.toOptionalUnit, - behavior: behavior, - animates: animates, - onDismiss: onDismiss - ) { _ in content() } - } + init(viewController: NSViewController) { + popover.contentViewController = viewController + } - @discardableResult - fileprivate func _popover( - item: UIBinding, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: \.id, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) + /// Reports that the popover has closed, once. + func finish() { + closeObserver?.invalidate() + closeObserver = nil + let didEnd = didEnd + self.didEnd = nil + didEnd?() + } } - @_disfavoredOverload - @discardableResult - fileprivate func _popover( - item: UIBinding, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: \.id, - behavior: behavior, - animates: animates, - onDismiss: onDismiss, - content: content - ) - } + /// Shows content in a popover pointing at an anchor. + @MainActor + private struct PopoverStyle: PresentationStyle { + let anchor: Anchor + let behavior: NSPopover.Behavior + let animates: Bool - @discardableResult - fileprivate func _popover( - item: UIBinding, - id: KeyPath, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - _popover( - item: item, - id: id, - behavior: behavior, - animates: animates, - onDismiss: onDismiss - ) { - content($0.wrappedValue) + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + RunLoopWait.until({ [anchor] in anchor.isOnScreen }, then: body) } - } - @discardableResult - fileprivate func _popover( - item: UIBinding, - id: KeyPath, - behavior: NSPopover.Behavior, - animates: Bool, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - _popover(item: item, id: id) { binding in - _PopoverPresentation( - viewController: content(binding), - behavior: behavior, - animates: animates - ) - } beginPopover: { [weak self] presentation, _ in - guard let self else { return } - presentation.appKitNavigationShowPopover(relativeTo: self) - } endPopover: { presentation, _ in - presentation.appKitNavigationClosePopover() - onDismiss?() + func begin( + _ content: PopoverContent, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + let popover = content.popover + popover.behavior = behavior + popover.animates = animates && !transaction.appKit.disablesAnimations + content.didEnd = didEnd + content.closeObserver = NotificationObserver( + name: NSPopover.didCloseNotification, object: popover + ) { [weak content] _ in + content?.finish() + } + anchor.show(popover) } - } - private func _popover( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> _PopoverPresentation, - beginPopover: @escaping ( - _ child: _PopoverPresentation, - _ transaction: UITransaction - ) -> Void, - endPopover: @escaping ( - _ child: _PopoverPresentation, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let popoverObserver = popoverObserver() - return popoverObserver.observe( - item: item, - id: { $0[keyPath: id] }, - content: content, - begin: beginPopover, - end: endPopover - ) - } - - private func popoverObserver() -> ToolbarItemPopoverObserver { - if let observer = objc_getAssociatedObject(self, toolbarItemPopoverObserverKey) as? ToolbarItemPopoverObserver { - return observer - } else { - let observer = ToolbarItemPopoverObserver(owner: self) - objc_setAssociatedObject( - self, - toolbarItemPopoverObserverKey, - observer, - .OBJC_ASSOCIATION_RETAIN_NONATOMIC - ) - return observer + func end(_ content: PopoverContent, transaction: UITransaction) { + let popover = content.popover + guard popover.isShown else { + // NB: Never got on screen, or is already closing, so no close notification will come. + content.finish() + return + } + popover.animates = animates && !transaction.appKit.disablesAnimations + popover.close() } } -} #endif diff --git a/Sources/AppKitNavigation/Navigation/PopoverContent.swift b/Sources/AppKitNavigation/Navigation/PopoverContent.swift deleted file mode 100644 index 59e4037205..0000000000 --- a/Sources/AppKitNavigation/Navigation/PopoverContent.swift +++ /dev/null @@ -1,37 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -@MainActor -protocol PopoverContent: NavigationContent { - var popover: NSPopover { get } - func appKitNavigationShowPopover(relativeTo rect: NSRect, of view: NSView, preferredEdge: NSRectEdge) - func appKitNavigationClosePopover() -} - -extension PopoverContent { - func appKitNavigationShowPopover(relativeTo rect: NSRect, of view: NSView, preferredEdge: NSRectEdge) { - // `Navigated` holds `self` weakly, and `NSPopover` does not retain its - // `PopoverContent` host, so we must keep `self` alive through the close - // subscription. Otherwise `onEndNavigation` runs on a deallocated `self` - // and the binding is never reset, leaving the popover unable to reopen. - PopoverPresentationsObserver.shared.observePopover(popover) { [self] in - self.onEndNavigation?() - } - popover.show(relativeTo: rect, of: view, preferredEdge: preferredEdge) - } - - @available(macOS 14.0, *) - func appKitNavigationShowPopover(relativeTo toolbarItem: NSToolbarItem) { - PopoverPresentationsObserver.shared.observePopover(popover) { [self] in - self.onEndNavigation?() - } - popover.show(relativeTo: toolbarItem) - } - - func appKitNavigationClosePopover() { - popover.close() - } -} - -#endif diff --git a/Tests/AppKitNavigationTests/PopoverPresentationTests.swift b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift index bc9bf43e80..239f83f3fb 100644 --- a/Tests/AppKitNavigationTests/PopoverPresentationTests.swift +++ b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift @@ -3,7 +3,8 @@ import AppKitNavigation import XCTest - /// Popovers shown from a view through `NSView.popover`. + /// Popovers shown from a view through `NSView.popover`, and from a toolbar item through + /// `NSToolbarItem.popover`. final class PopoverPresentationTests: XCTestCase { override func setUp() { super.setUp() @@ -12,6 +13,8 @@ } } + // MARK: - View anchor + @MainActor func testSettingTheBindingToTrueShowsThePopover() { let host = makeHost() @@ -103,14 +106,30 @@ XCTAssertTrue(waitUntil { !isPresented }, "Closing the popover did not write 'false' back") spinRunLoop(for: 0.3) - XCTExpectFailure( - """ - The popover is released as soon as it closes, before 'observe' re-runs, and 'onDismiss' only \ - runs from that re-run - """ + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run once the user closed the popover") + } + + @MainActor + func testOnDismissRunsOnceThePopoverHasClosed() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + var popoverWasShownAtDismiss: Bool? + host.view.popover( + isPresented: $isPresented, + onDismiss: { popoverWasShownAtDismiss = recorder.shownPopovers.first?.isShown } ) { - XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run once the user closed the popover") + self.makeViewController() } + + isPresented = true + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + isPresented = false + XCTAssertTrue(waitUntil { popoverWasShownAtDismiss != nil }, "'onDismiss' never ran") + + XCTAssertEqual(popoverWasShownAtDismiss, false, "'onDismiss' ran while the popover was open") } @MainActor @@ -121,7 +140,10 @@ let host = makeHost() let recorder = recordShownPopovers() @UIBinding var item: Item? - host.view.popover(item: $item, behavior: .applicationDefined) { _ in + var dismissCount = 0 + host.view.popover( + item: $item, behavior: .applicationDefined, onDismiss: { dismissCount += 1 } + ) { _ in self.makeViewController() } @@ -136,11 +158,161 @@ waitUntil { recorder.shownPopovers.count == 2 && recorder.shownPopovers[1].isShown }, "The second item's popover never appeared" ) - spinRunLoop(for: 0.5) - XCTExpectFailure("Showing the next item's popover leaves the previous one open") { - XCTAssertFalse(firstPopover.isShown, "The previous item's popover is still open") + XCTAssertFalse(firstPopover.isShown, "The previous item's popover is still open") + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run exactly once for the first item") + } + + @MainActor + func testPopoverWaitsUntilItsWindowIsOnScreen() { + let viewController = makeViewController(width: 480, height: 320) + let window = NSWindow(contentViewController: viewController) + window.isReleasedWhenClosed = false + addTeardownBlock { @MainActor in + window.close() } + let recorder = recordShownPopovers() + // Already 'true' when the popover is set up, before the window is on screen. + @UIBinding var isPresented = true + viewController.view.popover(isPresented: $isPresented) { self.makeViewController() } + spinRunLoop(for: 0.3) + XCTAssertTrue(recorder.shownPopovers.isEmpty, "The popover showed for a window off screen") + + window.orderFront(nil) + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, + "The popover never appeared once the window was on screen" + ) + } + + @MainActor + func testPopoverWaitsUntilItsViewIsInAWindow() { + let host = makeHost() + let anchorView = NSView(frame: NSRect(x: 20, y: 20, width: 80, height: 24)) + let recorder = recordShownPopovers() + @UIBinding var isPresented = true + anchorView.popover(isPresented: $isPresented) { self.makeViewController() } + spinRunLoop(for: 0.3) + XCTAssertTrue(recorder.shownPopovers.isEmpty, "The popover showed for a view in no window") + + host.view.addSubview(anchorView) + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, + "The popover never appeared once the view was in a window" + ) + } + + @MainActor + func testATransactionThatDisablesAnimationsShowsThePopoverWithoutAnimating() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + host.view.popover(isPresented: $isPresented) { self.makeViewController() } + + withUITransaction(\.appKit.disablesAnimations, true) { + isPresented = true + } + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + XCTAssertFalse(try XCTUnwrap(recorder.shownPopovers.first).animates) + } + + // MARK: - Toolbar item anchor + + @available(macOS 14.0, *) + @MainActor + func testSettingTheBindingToTrueShowsAToolbarItemsPopover() { + let toolbarHost = makeToolbarHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + toolbarHost.item.popover(isPresented: $isPresented) { self.makeViewController() } + toolbarHost.window.orderFront(nil) + + isPresented = true + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, + "The toolbar item's popover never appeared" + ) + isPresented = false + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == false }, + "The toolbar item's popover was not closed" + ) + } + + @available(macOS 14.0, *) + @MainActor + func testToolbarItemsPopoverWaitsUntilItsWindowIsOnScreen() { + let toolbarHost = makeToolbarHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = true + toolbarHost.item.popover(isPresented: $isPresented) { self.makeViewController() } + spinRunLoop(for: 0.3) + XCTAssertTrue(recorder.shownPopovers.isEmpty, "The popover showed for a window off screen") + + toolbarHost.window.orderFront(nil) + + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, + "The toolbar item's popover never appeared once its window was on screen" + ) + } + + // MARK: - Support + + @MainActor + private struct ToolbarHost { + let window: NSWindow + let item: NSToolbarItem + } + + /// A window, not yet on screen, whose toolbar shows a single item. + @MainActor + private func makeToolbarHost() -> ToolbarHost { + let item = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier("Info")) + item.label = "Info" + item.image = NSImage(systemSymbolName: "info.circle", accessibilityDescription: "Info") + let delegate = SingleItemToolbarDelegate(item: item) + let toolbar = NSToolbar(identifier: "PopoverPresentationTests") + toolbar.delegate = delegate + let window = makeWindow(width: 480, height: 320) + window.styleMask.insert(.resizable) + window.toolbar = toolbar + addTeardownBlock { @MainActor in + // NB: The toolbar does not keep its delegate. + _ = delegate + } + return ToolbarHost(window: window, item: item) + } + } + + @MainActor + private final class SingleItemToolbarDelegate: NSObject, NSToolbarDelegate { + let item: NSToolbarItem + + init(item: NSToolbarItem) { + self.item = item + } + + func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + itemIdentifier == item.itemIdentifier ? item : nil + } + + func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [item.itemIdentifier] + } + + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [item.itemIdentifier] } } #endif From d3b23560d9fed93820e384b2e7405c76cfea1803 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 23:00:07 +0800 Subject: [PATCH 098/141] feat(appkit): present view controllers through the shared presentation lifecycle Move present(isPresented:style:) and destination(...) onto BindingPresenter. Presenting no longer dismisses whatever view controller is already presented and calls its own onDismiss for it: a sheet queues behind another binding's sheet, as AppKit queues sheets, and only the binding's own view controller is replaced when its item changes, once that one has left the screen. The presentation holds its view controller while it is shown, so onDismiss runs once the user dismisses one that nothing else held. Move TransitionStyle next to the API that takes it, and document both. Add tests for the modal window style, which had none, and for destination's own closures. --- .../draft-appkit-presentation-redesign.md | 6 +- .../Navigation/Presentation.swift | 528 ++++++++++++------ .../Navigation/PresentationContent.swift | 41 -- .../ViewControllerPresentationTests.swift | 182 +++++- 4 files changed, 525 insertions(+), 232 deletions(-) delete mode 100644 Sources/AppKitNavigation/Navigation/PresentationContent.swift diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index e27b11ef97..96513133f6 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -356,7 +356,7 @@ final class BindingPresenter { 2. **通用层与 modal**(已完成):加入 `PresentationStyle`、`BindingPresenter`、`ModalContent`,把 `modal` 和 `modalSession` 迁过去、改标签、补文档注释;删除 `ModalWindowsObserver`。通用层的契约(恰好一次的 `onDismiss`、换 id 的顺序、宿主释放、取消 token)先拿 modal 测。修掉缺陷 2、4,以及 1、5 里属于 modal 的部分。`ModalPresentationTests` 共 17 条,连跑 5 次全部通过。 3. **sheet**(已完成):`NSWindow.sheet` 改成泛型并迁过去、补文档注释,加上等父窗口显示;删除 `NSViewController.sheet` 和 `SheetContent.swift`;Examples 跟着改标签。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。`SheetPresentationTests` 共 12 条,AppKit 测试共 50 条 XCTest、58 条 Swift Testing,全部通过。 4. **popover**(已完成):`NSView` 和 `NSToolbarItem` 的 popover 迁过去、补文档注释,加上等锚点显示(用 `RunLoopWait`)和 transaction 的关动画;删除 `PopoverContent.swift` 与 `PopoverPresentationsObserver`。修掉缺陷 1、3。`PopoverPresentationTests` 共 12 条(含工具栏项的两条),AppKit 测试共 56 条 XCTest、58 条 Swift Testing,全部通过。 -5. **present 与 destination**:迁过去,替换时只动自己弹的。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。 +5. **present 与 destination**(已完成):迁过去、补文档注释,替换时只动自己弹的;`TransitionStyle` 移进 `Presentation.swift`,删除 `PresentationContent.swift`。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。`ViewControllerPresentationTests` 共 11 条,新增的覆盖了 `.modalWindow` 风格和 `destination` 的自定义闭包;AppKit 测试共 61 条 XCTest、58 条 Swift Testing,全部通过。 6. **清理**:删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;给全部 `UIBinding` 版重载补 `@_disfavoredOverload`,加入第 6 条和下游写法的编译测试。 7. **文档**:按「文档与示例」一节更新文档注释、DocC 首页、`swift-navigation-bindings` skill 和裁决清单。 8. **完整验证**:Xcode 27.2 跑 AppKit 的全部测试,成败只认原始退出码,弹出相关的测试连跑 10 次;Xcode 26.6 编译库和测试;用 xcodebuild 编译 Examples 里 macOS 版的 CaseStudies。 @@ -401,3 +401,7 @@ final class BindingPresenter { | 2026-11-06 | 更正下游影响:Examples 的 Wi-Fi 案例用了两处 `modal(isModaled:)` | 起草时只搜了带点号的调用;本分支一并改成 `modal(isPresented:)`。本机下游项目用更宽的写法重搜过,仍然没有用到改名的 API | | 2026-11-06 | 第 4 步:工具栏项照样等它所在的窗口显示,没有先去试 AppKit 自己怎么处理 | 与其他锚点的等待一致,代价只是一次检查;测试覆盖了「窗口还没显示就设成 `true`」 | | 2026-11-06 | popover 被要求关闭时若已不在屏幕上,直接算作结束 | 从没显示出来、或正在被用户关掉的 popover 不会再发关闭通知,不这样做 presenter 会一直停在「结束中」 | +| 2026-11-06 | 第 5 步:视图控制器在 shim 报告 dismiss 后,再等它的窗口不可见才算结束 | 测试表明报告到来时 sheet 窗口已经不可见,但父窗口的 `attachedSheet` 还指着它;判断「下屏」看窗口本身,多等这一下是为了有动画时也成立 | +| 2026-11-06 | `destination` 的内容若不是经 AppKit 的弹出机制显示的,调用方的 `dismiss` 闭包返回就算结束 | 比如 `addChild(_:)` 加进来的子控制器,没有任何 dismiss 报告可等;写进了文档注释 | +| 2026-11-06 | 视图控制器的宿主释放时,只经 style 自己的弱引用去 dismiss;引用已空就只报告结束 | `presentingViewController` 是 `assign` 引用,宿主释放过程中读它不安全 | +| 2026-11-06 | `.modalWindow` 风格补了测试 | 以前没有任何测试;测试表明 `presentAsModalWindow` 不阻塞,binding 能正常关掉它 | diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 2369e09685..01f8204c45 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -1,193 +1,377 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -public import SwiftNavigation -public import AppKit -import AppKitNavigationShim - -class PresentationObserver: NavigationObserver { - override func commitWork(_ work: @escaping () -> Void) { - if owner._AppKitNavigation_hasViewAppeared { - work() - } else { - owner._AppKitNavigation_onViewAppear.append(work) + public import AppKit + import AppKitNavigationShim + + extension NSViewController { + /// How a view controller presents another one. + public enum TransitionStyle { + /// Attached to the presenting view controller's window as a sheet. + case sheet + /// In a window of its own, run modally. + case modalWindow + /// In a popover pointing at a rectangle in a view. + /// + /// - Parameters: + /// - rect: The rectangle, in `view`'s coordinates, that the popover points at. + /// - view: The view the popover is anchored to. + /// - preferredEdge: The edge of `rect` the popover prefers to show from. + /// - behavior: Whether the popover closes when the user interacts with something else. + case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) + /// By an animator of your own. + case custom(any NSViewControllerPresentationAnimator) } - } -} - -extension NSViewController { - @discardableResult - public func present( - isPresented: UIBinding, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping () -> NSViewController - ) -> ObserveToken { - present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in content() } - } - @discardableResult - public func present( - item: UIBinding, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) - } + /// Presents a view controller while a binding to a Boolean value you provide is true. + /// + /// Like SwiftUI's `sheet` and `popover` view modifiers, but for AppKit. Setting the binding to + /// `false` dismisses the view controller. When the user dismisses it — a Cancel button wired to + /// `dismissController(_:)`, a transient popover closing — the binding is set to `false`. The + /// view controller is presented once this view controller's view has appeared. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to present the view + /// controller. + /// - style: How to present it. + /// - onDismiss: The closure to execute once the view controller has been dismissed and has + /// left the screen. + /// - content: A closure that returns the view controller to present. + /// - Returns: A token that stops following the binding once cancelled. A view controller that + /// is presented then stays until the user dismisses it. + @discardableResult + public func present( + isPresented: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + present(item: isPresented.toOptionalUnit, style: style, onDismiss: onDismiss) { _ in + content() + } + } - @_disfavoredOverload - @discardableResult - public func present( - item: UIBinding, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) - } + /// Presents a view controller while a binding to an optional item holds a value. + /// + /// The view controller is presented as with + /// ``present(isPresented:style:onDismiss:content:)``. If the item's identity changes, the view + /// controller is dismissed, and once it has left the screen, one for the new item is + /// presented. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, the value is passed to `content`. When the user dismisses the view controller, + /// the binding is set to `nil`. + /// - style: How to present it. + /// - onDismiss: The closure to execute once the view controller has been dismissed and has + /// left the screen. + /// - content: A closure that returns the view controller to present for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func present( + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) + } - @discardableResult - public func present( - item: UIBinding, - id: KeyPath, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (Item) -> NSViewController - ) -> ObserveToken { - present(item: item, id: id, style: style, onDismiss: onDismiss) { - content($0.wrappedValue) + /// Presents a view controller while a binding to an optional item holds a value, passing the + /// content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, a binding to the value is passed to `content`. When the user dismisses the view + /// controller, the binding is set to `nil`. + /// - style: How to present it. + /// - onDismiss: The closure to execute once the view controller has been dismissed and has + /// left the screen. + /// - content: A closure that returns the view controller to present for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + present(item: item, id: \.id, style: style, onDismiss: onDismiss, content: content) } - } - @_disfavoredOverload - @discardableResult - public func present( - item: UIBinding, - id: KeyPath, - style: TransitionStyle, - onDismiss: (() -> Void)? = nil, - content: @escaping (UIBinding) -> NSViewController - ) -> ObserveToken { - destination(item: item, id: id) { $item in - content($item) - } present: { [weak self] child, transaction in - guard let self else { return } - if let presentedViewController = presentedViewControllers?.first { - self.dismiss(presentedViewController) - onDismiss?() - self.present(child, for: style) - } else { - self.present(child, for: style) - } - } dismiss: { [weak self] child, transaction in - guard let self else { return } - // NB: When the user closed the child, AppKit has already dismissed it by the time the - // binding is reset and this runs. - if self.presentedViewControllers?.contains(child) == true { - self.dismiss(child) + /// Presents a view controller while a binding to an optional item holds a value, telling items + /// apart by the identifier at a key path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, the value is passed to `content`. When the user dismisses the view controller, + /// the binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the view controller is + /// dismissed, and once it has left the screen, one for the new item is presented. + /// - style: How to present it. + /// - onDismiss: The closure to execute once the view controller has been dismissed and has + /// left the screen. + /// - content: A closure that returns the view controller to present for the item. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + present(item: item, id: id, style: style, onDismiss: onDismiss) { + content($0.wrappedValue) } - onDismiss?() } - } - @discardableResult - public func destination( - isPresented: UIBinding, - content: @escaping () -> NSViewController, - present: @escaping (NSViewController, UITransaction) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - destination( - item: isPresented.toOptionalUnit, - content: { _ in content() }, - present: present, - dismiss: dismiss - ) - } + /// Presents a view controller while a binding to an optional item holds a value, telling items + /// apart by the identifier at a key path and passing the content a binding to the item. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, a binding to the value is passed to `content`. When the user dismisses the view + /// controller, the binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the view controller is + /// dismissed, and once it has left the screen, one for the new item is presented. + /// - style: How to present it. + /// - onDismiss: The closure to execute once the view controller has been dismissed and has + /// left the screen. + /// - content: A closure that returns the view controller to present for the item. + /// - Returns: A token that stops following the binding once cancelled. + @_disfavoredOverload + @discardableResult + public func present( + item: UIBinding, + id: KeyPath, + style: TransitionStyle, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + bindPresentation( + ViewControllerPresentationStyle(presenter: self, transition: .style(style)), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss, + content: content + ) + } - @discardableResult - public func destination( - item: UIBinding, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping (NSViewController, UITransaction) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - observePresentation( - item: item, - id: { _ in nil }, - content: content, - present: present, - dismiss: dismiss - ) - } + /// Presents a view controller in a way of your own while a binding to a Boolean value you + /// provide is true. + /// + /// This helper powers ``present(isPresented:style:onDismiss:content:)``, and can define custom + /// transitions. A view controller dismissed through `dismiss(_:)` counts as having left the + /// screen once its view has disappeared. One that never went through AppKit's presentation, + /// such as a child added with `addChild(_:)`, counts as having left the screen as soon as + /// `dismiss` returns. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to present the view + /// controller. + /// - content: A closure that returns the view controller to present. + /// - present: The closure to execute to present the view controller. + /// - dismiss: The closure to execute to dismiss the view controller. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func destination( + isPresented: UIBinding, + content: @escaping () -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + destination( + item: isPresented.toOptionalUnit, + content: { _ in content() }, + present: present, + dismiss: dismiss + ) + } - @discardableResult - public func destination( - item: UIBinding, - id: KeyPath, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void, - dismiss: @escaping ( - _ child: NSViewController, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - observePresentation( - item: item, - id: { $0[keyPath: id] }, - content: content, - present: present, - dismiss: dismiss - ) - } + /// Presents a view controller in a way of your own while a binding to an optional item holds a + /// value. + /// + /// The view controller stays the same while the binding holds any value, whatever its + /// identity. To replace it when the item's identity changes, use + /// ``destination(item:id:content:present:dismiss:)``. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, a binding to the value is passed to `content`. When the user dismisses the view + /// controller, the binding is set to `nil`. + /// - content: A closure that returns the view controller to present. + /// - present: The closure to execute to present the view controller. + /// - dismiss: The closure to execute to dismiss the view controller. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func destination( + item: UIBinding, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping (NSViewController, UITransaction) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + bindPresentation( + ViewControllerPresentationStyle( + presenter: self, transition: .custom(present: present, dismiss: dismiss) + ), + item: item, + id: { _ in nil }, + onDismiss: nil, + content: content + ) + } + + /// Presents a view controller in a way of your own while a binding to an optional item holds a + /// value, telling items apart by the identifier at a key path. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, a binding to the value is passed to `content`. When the user dismisses the view + /// controller, the binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the view controller is + /// dismissed, and once it has left the screen, one for the new item is presented. + /// - content: A closure that returns the view controller to present. + /// - present: The closure to execute to present the view controller. + /// - dismiss: The closure to execute to dismiss the view controller. + /// - Returns: A token that stops following the binding once cancelled. + @discardableResult + public func destination( + item: UIBinding, + id: KeyPath, + content: @escaping (UIBinding) -> NSViewController, + present: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void, + dismiss: @escaping ( + _ child: NSViewController, + _ transaction: UITransaction + ) -> Void + ) -> ObserveToken { + bindPresentation( + ViewControllerPresentationStyle( + presenter: self, transition: .custom(present: present, dismiss: dismiss) + ), + item: item, + id: { $0[keyPath: id] }, + onDismiss: nil, + content: content + ) + } - private func observePresentation( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> NSViewController, - present: @escaping (_ child: NSViewController, _ transaction: UITransaction) -> Void, - dismiss: @escaping (_ child: NSViewController, _ transaction: UITransaction) -> Void - ) -> ObserveToken { - presentationObserver().observe( - item: item, - id: id, - content: content, - begin: { child, transaction in - // NB: The user closes a presented controller without going through the binding — a - // Cancel button wired to 'dismissController:', a transient popover closing — so the - // shim reports the dismissal, and this resets the binding from there. - child._AppKitNavigation_onDismiss = child.onEndNavigation - present(child, transaction) - }, - end: dismiss - ) + fileprivate func present(_ viewController: NSViewController, as style: TransitionStyle) { + switch style { + case .sheet: + presentAsSheet(viewController) + case .modalWindow: + presentAsModalWindow(viewController) + case let .popover(rect, view, preferredEdge, behavior): + present( + viewController, + asPopoverRelativeTo: rect, + of: view, + preferredEdge: preferredEdge, + behavior: behavior + ) + case let .custom(animator): + present(viewController, animator: animator) + } + } } - private static var presentationObserverKey = malloc(1)! + /// Presents a view controller from another one, through AppKit's view controller presentation or + /// in a way of the caller's own. + @MainActor + private struct ViewControllerPresentationStyle: PresentationStyle { + enum Transition { + case style(NSViewController.TransitionStyle) + case custom( + present: (NSViewController, UITransaction) -> Void, + dismiss: (NSViewController, UITransaction) -> Void + ) + } + + weak var presenter: NSViewController? + let transition: Transition + + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + guard let presenter, !presenter._AppKitNavigation_hasViewAppeared else { + body() + return {} + } + let wait = CancellableWait() + presenter._AppKitNavigation_onViewAppear.append { + MainActor._assumeIsolated { + guard !wait.isCancelled else { return } + body() + } + } + return { + wait.isCancelled = true + } + } + + func begin( + _ child: NSViewController, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + guard let presenter else { + didEnd() + return + } + // NB: The user dismisses a presented view controller without going through the binding — a + // Cancel button wired to 'dismissController:', a transient popover closing — so the shim + // reports the dismissal, once the view controller's view has disappeared. It counts as + // ended once the window that showed it is off screen too. + child._AppKitNavigation_onDismiss = { [weak child] in + MainActor._assumeIsolated { + _ = RunLoopWait.until({ child?.view.window?.isVisible != true }, then: didEnd) + } + } + switch transition { + case let .style(style): + presenter.present(child, as: style) + case let .custom(present, _): + withUITransaction(transaction) { + present(child, transaction) + } + } + } - private func presentationObserver() -> PresentationObserver { - if let observer = objc_getAssociatedObject(self, Self.presentationObserverKey) as? PresentationObserver { - return observer - } else { - let observer = PresentationObserver(owner: self) - objc_setAssociatedObject(self, Self.presentationObserverKey, observer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) - return observer + func end(_ child: NSViewController, transaction: UITransaction) { + switch transition { + case .style: + // NB: Only through this weak reference: 'presentingViewController' is not one, and is not + // safe to read while the presenter is being deallocated. + if let presenter, presenter.presentedViewControllers?.contains(child) == true { + presenter.dismiss(child) + return + } + case let .custom(_, dismiss): + withUITransaction(transaction) { + dismiss(child, transaction) + } + if presenter?.presentedViewControllers?.contains(child) == true { + return + } + } + // NB: Not presented through AppKit, or no longer, so no dismissal will be reported. + let reportDismissal = child._AppKitNavigation_onDismiss + child._AppKitNavigation_onDismiss = nil + reportDismissal?() } } -} -extension Navigated where Content: NSViewController { - func clearup() { - content?.dismiss(nil) + /// A wait that can be called off after it has been scheduled. + @MainActor + private final class CancellableWait { + var isCancelled = false } -} - #endif diff --git a/Sources/AppKitNavigation/Navigation/PresentationContent.swift b/Sources/AppKitNavigation/Navigation/PresentationContent.swift deleted file mode 100644 index fb6b85ad1a..0000000000 --- a/Sources/AppKitNavigation/Navigation/PresentationContent.swift +++ /dev/null @@ -1,41 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -public import AppKit - -@MainActor -protocol PresentationContent: NavigationContent { - func presented(from presentingViewController: NSViewController, style: NSViewController.TransitionStyle) - func dismiss(from presentingViewController: NSViewController) -} - -extension NSViewController: PresentationContent { - func presented(from presentingViewController: NSViewController, style: TransitionStyle) { - presentingViewController.present(self, for: style) - } - - func dismiss(from presentingViewController: NSViewController) { - presentingViewController.dismiss(self) - } - - public enum TransitionStyle { - case sheet - case modalWindow - case popover(rect: NSRect, view: NSView, preferredEdge: NSRectEdge, behavior: NSPopover.Behavior) - case custom(any NSViewControllerPresentationAnimator) - } - - func present(_ viewControllerToPresent: NSViewController, for style: TransitionStyle) { - switch style { - case .sheet: - presentAsSheet(viewControllerToPresent) - case .modalWindow: - presentAsModalWindow(viewControllerToPresent) - case let .popover(rect, view, preferredEdge, behavior): - present(viewControllerToPresent, asPopoverRelativeTo: rect, of: view, preferredEdge: preferredEdge, behavior: behavior) - case let .custom(animator): - present(viewControllerToPresent, animator: animator) - } - } -} - -#endif diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift index f198872d2f..3d7fe55020 100644 --- a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -3,7 +3,8 @@ import AppKitNavigation import XCTest - /// Presentations whose content is a view controller, through `present(isPresented:style:)`. + /// Presentations whose content is a view controller, through `present(isPresented:style:)` and + /// `destination(isPresented:content:present:dismiss:)`. final class ViewControllerPresentationTests: XCTestCase { override func setUp() { super.setUp() @@ -12,6 +13,8 @@ } } + // MARK: - Sheet style + @MainActor func testUserDismissingAPresentedSheetWritesFalseBack() { let host = makeHost() @@ -30,6 +33,52 @@ XCTAssertTrue(waitUntil { !isPresented }, "Dismissing the sheet did not write 'false' back") } + @MainActor + func testUserDismissingAPresentedSheetCallsOnDismissOnce() { + let host = makeHost() + @UIBinding var isPresented = false + var dismissCount = 0 + host.viewController.present( + isPresented: $isPresented, style: .sheet, onDismiss: { dismissCount += 1 } + ) { + // NB: Made here, and held by nothing but the presentation. + self.makeViewController() + } + + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + host.window.attachedSheet?.contentViewController?.dismiss(nil) + XCTAssertTrue(waitUntil { !isPresented }, "Dismissing the sheet did not write 'false' back") + spinRunLoop(for: 0.3) + + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run once the user dismissed the sheet") + } + + // NB: The window's 'attachedSheet' can still point at a sheet that has already left the screen, + // so the sheet's own window is what tells. + @MainActor + func testOnDismissRunsOnceThePresentedSheetHasLeftTheScreen() throws { + let host = makeHost() + @UIBinding var isPresented = false + var sheetWindow: NSWindow? + var sheetWasVisibleAtDismiss: Bool? + host.viewController.present( + isPresented: $isPresented, + style: .sheet, + onDismiss: { sheetWasVisibleAtDismiss = sheetWindow?.isVisible } + ) { + self.makeViewController() + } + + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + sheetWindow = try XCTUnwrap(host.window.attachedSheet) + isPresented = false + XCTAssertTrue(waitUntil { sheetWasVisibleAtDismiss != nil }, "'onDismiss' never ran") + + XCTAssertEqual(sheetWasVisibleAtDismiss, false, "'onDismiss' ran while the sheet was on screen") + } + @MainActor func testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt() { let host = makeHost() @@ -70,6 +119,23 @@ XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not dismissed") } + // NB: 'sheet(isSheeted:)' once dismissed a view controller sheet the moment it appeared, while + // its own implementation of sheets still existed next to this one. + @MainActor + func testPresentedSheetStaysPresentedUntilItIsDismissed() { + let host = makeHost() + @UIBinding var isPresented = false + host.viewController.present(isPresented: $isPresented, style: .sheet) { + self.makeViewController() + } + + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + spinRunLoop(for: 0.5) + + XCTAssertTrue(isPresented, "The sheet dismissed itself right after it appeared") + } + @MainActor func testPresentedSheetWaitsUntilTheViewAppears() { let viewController = makeViewController(width: 480, height: 320) @@ -95,10 +161,43 @@ ) } + @MainActor + func testChangingTheItemDismissesTheViewControllerBeforeTheNextOneIsPresented() { + struct Item: Identifiable { + let id: Int + } + let host = makeHost() + let firstViewController = makeViewController() + let secondViewController = makeViewController() + @UIBinding var item: Item? + var dismissCount = 0 + host.viewController.present(item: $item, style: .sheet, onDismiss: { dismissCount += 1 }) { + currentItem in + currentItem.id == 1 ? firstViewController : secondViewController + } + + item = Item(id: 1) + XCTAssertTrue( + waitUntil { host.window.attachedSheet?.contentViewController === firstViewController }, + "The first item's sheet never appeared" + ) + item = Item(id: 2) + XCTAssertTrue( + waitUntil { host.window.attachedSheet?.contentViewController === secondViewController }, + "The second item's sheet never took the first one's place" + ) + + XCTAssertNil(firstViewController.presentingViewController, "The first item's sheet is still up") + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run exactly once for the first item") + item = nil + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The second sheet never went away") + } + @MainActor func testPresentingLeavesAnotherBindingsPresentationInPlace() { let host = makeHost() let firstViewController = makeViewController() + let secondViewController = makeViewController() @UIBinding var isFirstPresented = false @UIBinding var isSecondPresented = false var secondDismissCount = 0 @@ -108,7 +207,7 @@ host.viewController.present( isPresented: $isSecondPresented, style: .sheet, onDismiss: { secondDismissCount += 1 } ) { - self.makeViewController() + secondViewController } isFirstPresented = true @@ -119,36 +218,83 @@ isSecondPresented = true spinRunLoop(for: 0.5) - XCTExpectFailure( - "present(…) dismisses whatever view controller is presented, and calls its own onDismiss for it" - ) { - XCTAssertTrue(isFirstPresented, "Presenting the second sheet dismissed the first binding's sheet") - XCTAssertEqual( - secondDismissCount, 0, - "The second binding's 'onDismiss' ran for a sheet it never presented" - ) - } + XCTAssertTrue(isFirstPresented, "Presenting the second sheet dismissed the first binding's sheet") + XCTAssertEqual( + secondDismissCount, 0, "The second binding's 'onDismiss' ran for a sheet it never presented" + ) isFirstPresented = false + XCTAssertTrue( + waitUntil { host.window.attachedSheet?.contentViewController === secondViewController }, + "The queued sheet never appeared once the first one was dismissed" + ) isSecondPresented = false XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheets never went away") } - // NB: 'sheet(isSheeted:)' once dismissed a view controller sheet the moment it appeared, while - // its own implementation of sheets still existed next to this one. + // MARK: - Modal window style + @MainActor - func testPresentedSheetStaysPresentedUntilItIsDismissed() { + func testSettingTheBindingToFalseDismissesAModalWindow() { let host = makeHost() + let presentedViewController = makeViewController() @UIBinding var isPresented = false - host.viewController.present(isPresented: $isPresented, style: .sheet) { + host.viewController.present(isPresented: $isPresented, style: .modalWindow) { + presentedViewController + } + abortModalLoops(after: 5) + + let start = Date() + let wasOnScreen = Recorded(false) + perform(after: 0.5) { + wasOnScreen.value = presentedViewController.view.window?.isVisible == true + isPresented = false + } + isPresented = true + + XCTAssertTrue( + waitUntil(timeout: 4) { !isPresented && presentedViewController.view.window?.isVisible != true }, + "The modal window was not dismissed" + ) + XCTAssertTrue(wasOnScreen.value, "The modal window never appeared") + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + "The modal window only went away when the safety timer aborted it" + ) + } + + // MARK: - Custom presentation + + @MainActor + func testDestinationPresentsAndDismissesThroughTheGivenClosures() { + let host = makeHost() + @UIBinding var isPresented = false + var presentedChildren: [NSViewController] = [] + var dismissedChildren: [NSViewController] = [] + host.viewController.destination(isPresented: $isPresented) { self.makeViewController() + } present: { child, _ in + host.viewController.addChild(child) + host.view.addSubview(child.view) + presentedChildren.append(child) + } dismiss: { child, _ in + child.view.removeFromSuperview() + child.removeFromParent() + dismissedChildren.append(child) } isPresented = true - XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") - spinRunLoop(for: 0.5) + XCTAssertTrue(waitUntil { presentedChildren.count == 1 }, "The child was never presented") + isPresented = false + XCTAssertTrue(waitUntil { dismissedChildren.count == 1 }, "The child was never dismissed") + XCTAssertTrue(dismissedChildren.first === presentedChildren.first) - XCTAssertTrue(isPresented, "The sheet dismissed itself right after it appeared") + isPresented = true + + XCTAssertTrue( + waitUntil { presentedChildren.count == 2 }, + "Setting the binding to 'true' again did not present the child again" + ) } } #endif From 8871d68e8060b0ee2cca4fc2829820e745051953 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 23:02:55 +0800 Subject: [PATCH 099/141] refactor(appkit): remove the presentation code the shared lifecycle replaced Delete NavigationObserver, the NavigationContent associated-object closures and the per-type AssociatedKeys registry, which nothing uses any more, including the four Navigated.clearup() extensions that never ran. Add PresentationOverloadTests: a content closure that ignores its item must pick the overload taking the item, which needs the binding overloads to be disfavored. Without the attribute on modal(item:id:), the file fails with an ambiguous use; the item:id: overloads of modal, modalSession, sheet and popover used to lack it. --- .../draft-appkit-presentation-redesign.md | 2 +- .../Internal/AssociatedKeys.swift | 36 ------ .../Navigation/NavigationContent.swift | 37 ------- .../Navigation/NavigationObserver.swift | 103 ------------------ .../PresentationOverloadTests.swift | 100 +++++++++++++++++ 5 files changed, 101 insertions(+), 177 deletions(-) delete mode 100644 Sources/AppKitNavigation/Internal/AssociatedKeys.swift delete mode 100644 Sources/AppKitNavigation/Navigation/NavigationContent.swift delete mode 100644 Sources/AppKitNavigation/Navigation/NavigationObserver.swift create mode 100644 Tests/AppKitNavigationTests/PresentationOverloadTests.swift diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index 96513133f6..3fc05051c8 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -357,7 +357,7 @@ final class BindingPresenter { 3. **sheet**(已完成):`NSWindow.sheet` 改成泛型并迁过去、补文档注释,加上等父窗口显示;删除 `NSViewController.sheet` 和 `SheetContent.swift`;Examples 跟着改标签。修掉缺陷 7、8,以及 5 里属于 sheet 的部分。`SheetPresentationTests` 共 12 条,AppKit 测试共 50 条 XCTest、58 条 Swift Testing,全部通过。 4. **popover**(已完成):`NSView` 和 `NSToolbarItem` 的 popover 迁过去、补文档注释,加上等锚点显示(用 `RunLoopWait`)和 transaction 的关动画;删除 `PopoverContent.swift` 与 `PopoverPresentationsObserver`。修掉缺陷 1、3。`PopoverPresentationTests` 共 12 条(含工具栏项的两条),AppKit 测试共 56 条 XCTest、58 条 Swift Testing,全部通过。 5. **present 与 destination**(已完成):迁过去、补文档注释,替换时只动自己弹的;`TransitionStyle` 移进 `Presentation.swift`,删除 `PresentationContent.swift`。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。`ViewControllerPresentationTests` 共 11 条,新增的覆盖了 `.modalWindow` 风格和 `destination` 的自定义闭包;AppKit 测试共 61 条 XCTest、58 条 Swift Testing,全部通过。 -6. **清理**:删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;给全部 `UIBinding` 版重载补 `@_disfavoredOverload`,加入第 6 条和下游写法的编译测试。 +6. **清理**(已完成):删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;`UIBinding` 版重载在第 2–5 步重写时都已标 `@_disfavoredOverload`(`destination` 的两个没有同形的 item 版,不需要)。加入 `PresentationOverloadTests`:第 6 条的歧义写法、`{ $item in … }` 写法和 XCOrganizer 那种多语句闭包。先去掉一处标记确认它编不过(报 `ambiguous use of 'modal(item:id:onDismiss:content:)'`),恢复后通过。AppKit 测试共 64 条 XCTest、58 条 Swift Testing,全部通过。 7. **文档**:按「文档与示例」一节更新文档注释、DocC 首页、`swift-navigation-bindings` skill 和裁决清单。 8. **完整验证**:Xcode 27.2 跑 AppKit 的全部测试,成败只认原始退出码,弹出相关的测试连跑 10 次;Xcode 26.6 编译库和测试;用 xcodebuild 编译 Examples 里 macOS 版的 CaseStudies。 diff --git a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift b/Sources/AppKitNavigation/Internal/AssociatedKeys.swift deleted file mode 100644 index f1398d8c8c..0000000000 --- a/Sources/AppKitNavigation/Internal/AssociatedKeys.swift +++ /dev/null @@ -1,36 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import AppKit - -struct AssociatedKeys { - var keys: [AnyHashableMetatype: UnsafeMutableRawPointer] = [:] - - mutating func key(of type: T.Type) -> UnsafeMutableRawPointer { - let key = AnyHashableMetatype(type) - if let associatedKey = keys[key] { - return associatedKey - } else { - let associatedKey = malloc(1)! - keys[key] = associatedKey - return associatedKey - } - } -} - -struct AnyHashableMetatype: Hashable { - static func == (lhs: AnyHashableMetatype, rhs: AnyHashableMetatype) -> Bool { - return lhs.base == rhs.base - } - - let base: Any.Type - - init(_ base: Any.Type) { - self.base = base - } - - func hash(into hasher: inout Hasher) { - hasher.combine(ObjectIdentifier(base)) - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationContent.swift b/Sources/AppKitNavigation/Navigation/NavigationContent.swift deleted file mode 100644 index 8c10f8c664..0000000000 --- a/Sources/AppKitNavigation/Navigation/NavigationContent.swift +++ /dev/null @@ -1,37 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import Foundation - -@MainActor -protocol NavigationContent: AnyObject { - var onBeginNavigation: (() -> Void)? { set get } - var onEndNavigation: (() -> Void)? { set get } -} - -@MainActor -private var onBeginNavigationKeys = AssociatedKeys() - -@MainActor -private var onEndNavigationKeys = AssociatedKeys() - -extension NavigationContent { - var onBeginNavigation: (() -> Void)? { - set { - objc_setAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) - } - get { - objc_getAssociatedObject(self, onBeginNavigationKeys.key(of: Self.self)) as? () -> Void - } - } - - var onEndNavigation: (() -> Void)? { - set { - objc_setAssociatedObject(self, onEndNavigationKeys.key(of: Self.self), newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC) - } - get { - objc_getAssociatedObject(self, onEndNavigationKeys.key(of: Self.self)) as? () -> Void - } - } -} - -#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift b/Sources/AppKitNavigation/Navigation/NavigationObserver.swift deleted file mode 100644 index eff9e4c2cc..0000000000 --- a/Sources/AppKitNavigation/Navigation/NavigationObserver.swift +++ /dev/null @@ -1,103 +0,0 @@ -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -import Foundation -import SwiftNavigation - -@MainActor -class NavigationObserver: NSObject { - private var navigatedByID: [UIBindingIdentifier: Navigated] = [:] - - unowned let owner: Owner - - init(owner: Owner) { - self.owner = owner - super.init() - } - - func observe( - item: UIBinding, - id: @escaping (Item) -> AnyHashable?, - content: @escaping (UIBinding) -> Content, - begin: @escaping ( - _ content: Content, - _ transaction: UITransaction - ) -> Void, - end: @escaping ( - _ content: Content, - _ transaction: UITransaction - ) -> Void - ) -> ObserveToken { - let key = UIBindingIdentifier(item) - return observe { [weak self] transaction in - guard let self else { return } - if let unwrappedItem = UIBinding(item) { - if let navigated = navigatedByID[key] { - if navigated.hasEnded { - // NB: The content was closed from its own UI, and the binding was set again before - // this re-ran, so the 'nil' in between was never observed. Finish the old - // navigation before starting the new one instead of mistaking it for live. - if let content = navigated.content { - end(content, transaction) - } - navigatedByID[key] = nil - } else { - guard let navigationID = navigated.id, - navigationID != id(unwrappedItem.wrappedValue) - else { - return - } - } - } - let content = content(unwrappedItem) - let navigated = Navigated(content, id: id(unwrappedItem.wrappedValue)) - let onEndNavigation = { [weak navigated, navigationID = id(unwrappedItem.wrappedValue)] in - navigated?.hasEnded = true - if let wrappedValue = item.wrappedValue, - navigationID == id(wrappedValue) { - item.wrappedValue = nil - } - } - content.onEndNavigation = onEndNavigation - - self.navigatedByID[key] = navigated - let work = { - withUITransaction(transaction) { - begin(content, transaction) - } - } - commitWork(work) - } else if let navigated = navigatedByID[key] { - if let content = navigated.content { - end(content, transaction) - } - self.navigatedByID[key] = nil - } - } - } - - func commitWork(_ work: @escaping () -> Void) { - work() - } -} - -@MainActor -class Navigated { - weak var content: Content? - let id: AnyHashable? - /// Whether the content has already ended on its own, closed from its own UI rather than through - /// the binding. - var hasEnded = false - func clearup() {} - deinit { - MainActor._assumeIsolated { - clearup() - } - } - - required init(_ content: Content, id: AnyHashable?) { - self.content = content - self.id = id - } -} - -#endif diff --git a/Tests/AppKitNavigationTests/PresentationOverloadTests.swift b/Tests/AppKitNavigationTests/PresentationOverloadTests.swift new file mode 100644 index 0000000000..2053aadf15 --- /dev/null +++ b/Tests/AppKitNavigationTests/PresentationOverloadTests.swift @@ -0,0 +1,100 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// Call shapes the presentation overloads must accept. + /// + /// These guard the overload sets more than any behavior: each call only has to type-check. The + /// bindings never hold a value, so nothing is ever presented. + final class PresentationOverloadTests: XCTestCase { + private struct Item: Identifiable { + let id: Int + } + + // NB: Every presentation has an overload whose content takes the item and one whose content + // takes a binding to it. A closure that ignores its parameter fits both, so these calls only + // compile while the binding overloads are disfavored. + @MainActor + func testAClosureThatIgnoresItsItemPicksTheOverloadTakingTheItem() { + let host = makeHost() + @UIBinding var item: Item? + + host.window.modal(item: $item) { _ in NSAlert() } + host.window.modal(item: $item, id: \.id) { _ in NSAlert() } + host.window.modalSession(item: $item) { _ in NSWindow() } + host.window.modalSession(item: $item, id: \.id) { _ in NSWindow() } + host.window.sheet(item: $item) { _ in NSAlert() } + host.window.sheet(item: $item, id: \.id) { _ in NSAlert() } + host.view.popover(item: $item) { _ in NSViewController() } + host.view.popover(item: $item, id: \.id) { _ in NSViewController() } + host.viewController.present(item: $item, style: .sheet) { _ in NSViewController() } + host.viewController.present(item: $item, id: \.id, style: .sheet) { _ in NSViewController() } + if #available(macOS 14.0, *) { + let toolbarItem = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier("Item")) + toolbarItem.popover(item: $item) { _ in NSViewController() } + toolbarItem.popover(item: $item, id: \.id) { _ in NSViewController() } + } + + spinRunLoop(for: 0.1) + XCTAssertNil(host.window.attachedSheet) + } + + @MainActor + func testAClosureTakingABindingToTheItemPicksTheOverloadTakingABinding() { + let host = makeHost() + @UIBinding var item: Item? + + host.window.modal(item: $item) { $item in Self.makeAlert(for: $item) } + host.window.sheet(item: $item, id: \.id) { $item in Self.makeAlert(for: $item) } + host.view.popover(item: $item) { $item in Self.makeViewController(for: $item) } + host.viewController.present(item: $item, style: .sheet) { $item in + Self.makeViewController(for: $item) + } + + spinRunLoop(for: 0.1) + XCTAssertNil(host.window.attachedSheet) + } + + // NB: The shape XCOrganizer uses: several statements, a weak capture, and two returns. + @MainActor + func testAClosureWithSeveralStatementsAndReturns() { + let host = makeHost() + @UIBinding var item: Item? + + host.window.sheet(item: $item) { [weak host = host.viewController] currentItem in + guard let host else { return Self.makeSheetWindow(for: currentItem) } + return Self.makeSheetWindow(for: currentItem, title: host.title) + } + + spinRunLoop(for: 0.1) + XCTAssertNil(host.window.attachedSheet) + } + + @MainActor + private static func makeAlert(for item: UIBinding) -> NSAlert { + let alert = NSAlert() + alert.messageText = "Item \(item.wrappedValue.id)" + return alert + } + + @MainActor + private static func makeViewController(for item: UIBinding) -> NSViewController { + let viewController = NSViewController() + viewController.title = "Item \(item.wrappedValue.id)" + return viewController + } + + @MainActor + private static func makeSheetWindow(for item: Item, title: String? = nil) -> NSWindow { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 240, height: 160), + styleMask: [.titled], + backing: .buffered, + defer: true + ) + window.title = title ?? "Item \(item.id)" + return window + } + } +#endif From 409a071ddf89ae75a5a0d265652ac456e23e1565 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 23:06:17 +0800 Subject: [PATCH 100/141] docs(appkit): document the presentation lifecycle and close the deferred findings List ModalContent among the presentation APIs on the documentation landing page, and say there what onDismiss now guarantees. Remove the two deferred findings this redesign fixed - the clearup() methods that never ran, and present(...) ending another binding's presentation - from the review decisions. Generating the documentation reports no warnings beyond the three it already had in content shared with upstream. --- .../Evolutions/draft-appkit-presentation-redesign.md | 5 +++-- Documentations/Internal/ReviewDecisions.md | 12 ------------ .../Documentation.docc/AppKitNavigation.md | 4 +++- 3 files changed, 6 insertions(+), 15 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index 3fc05051c8..54b1fe963c 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -340,7 +340,7 @@ final class BindingPresenter { ### 文档与示例 - 公开 API 全部补上文档注释,包括 `ModalContent`。 -- DocC 首页(`Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md`)的「Presenting content from state」一组:加上 `ModalContent`,去掉只剩下划线成员的 `AppKit/NSAlert`。 +- DocC 首页(`Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md`)的「Presenting content from state」一组加上 `ModalContent`,概述里补一句 `onDismiss` 的保证。`AppKit/NSAlert` 留着:它还有 `AlertState` 的构造器和 `addButton` 这些公开成员。 - `swift-navigation-bindings` skill 里 AppKit 那张表:标签、泛型内容、删掉的 `NSViewController.sheet`;顺带更正 `modalSession` 的内容只能是 `NSWindow`(现在那张表写成了和 `modal` 一样)。 - [裁决清单](../Internal/ReviewDecisions.md):两条暂缓项(`clearup()` 死代码、`present` 替换时不分来源)随这次修掉,从清单里删除;「transient popover 被点外部关闭时的回写」保留。 - README 没有提到 AppKit 的弹出 API,不用改。 @@ -358,7 +358,7 @@ final class BindingPresenter { 4. **popover**(已完成):`NSView` 和 `NSToolbarItem` 的 popover 迁过去、补文档注释,加上等锚点显示(用 `RunLoopWait`)和 transaction 的关动画;删除 `PopoverContent.swift` 与 `PopoverPresentationsObserver`。修掉缺陷 1、3。`PopoverPresentationTests` 共 12 条(含工具栏项的两条),AppKit 测试共 56 条 XCTest、58 条 Swift Testing,全部通过。 5. **present 与 destination**(已完成):迁过去、补文档注释,替换时只动自己弹的;`TransitionStyle` 移进 `Presentation.swift`,删除 `PresentationContent.swift`。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。`ViewControllerPresentationTests` 共 11 条,新增的覆盖了 `.modalWindow` 风格和 `destination` 的自定义闭包;AppKit 测试共 61 条 XCTest、58 条 Swift Testing,全部通过。 6. **清理**(已完成):删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;`UIBinding` 版重载在第 2–5 步重写时都已标 `@_disfavoredOverload`(`destination` 的两个没有同形的 item 版,不需要)。加入 `PresentationOverloadTests`:第 6 条的歧义写法、`{ $item in … }` 写法和 XCOrganizer 那种多语句闭包。先去掉一处标记确认它编不过(报 `ambiguous use of 'modal(item:id:onDismiss:content:)'`),恢复后通过。AppKit 测试共 64 条 XCTest、58 条 Swift Testing,全部通过。 -7. **文档**:按「文档与示例」一节更新文档注释、DocC 首页、`swift-navigation-bindings` skill 和裁决清单。 +7. **文档**(已完成):文档注释已随第 2–5 步写好;本步更新 DocC 首页、`swift-navigation-bindings` skill(在 iCloud 的全局 skill 目录里,不在本仓库)和裁决清单(删掉已修好的两条暂缓项)。生成一次 AppKitNavigation 的文档:只剩上游共用内容里原有的 3 条链接警告,没有新增;生成时被 DocC 插件改写的 `Package.resolved` 已还原。 8. **完整验证**:Xcode 27.2 跑 AppKit 的全部测试,成败只认原始退出码,弹出相关的测试连跑 10 次;Xcode 26.6 编译库和测试;用 xcodebuild 编译 Examples 里 macOS 版的 CaseStudies。 每一步都能单独构建通过、测试全绿:第 2–5 步迁移期间,还没迁的方式继续走旧的 `NavigationObserver`,第 6 步才删除。 @@ -405,3 +405,4 @@ final class BindingPresenter { | 2026-11-06 | `destination` 的内容若不是经 AppKit 的弹出机制显示的,调用方的 `dismiss` 闭包返回就算结束 | 比如 `addChild(_:)` 加进来的子控制器,没有任何 dismiss 报告可等;写进了文档注释 | | 2026-11-06 | 视图控制器的宿主释放时,只经 style 自己的弱引用去 dismiss;引用已空就只报告结束 | `presentingViewController` 是 `assign` 引用,宿主释放过程中读它不安全 | | 2026-11-06 | `.modalWindow` 风格补了测试 | 以前没有任何测试;测试表明 `presentAsModalWindow` 不阻塞,binding 能正常关掉它 | +| 2026-11-06 | 第 7 步:DocC 首页保留 `AppKit/NSAlert` | 方案原以为它只剩下划线成员,实际还有 `AlertState` 的构造器和 `addButton`,页面仍有内容 | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index a8fef95215..39c34a82ae 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -32,18 +32,6 @@ ## 暂缓处理 -### `Navigated` 各约束扩展里的 `clearup()` 从不执行 - -- **裁决**:确认是死代码,暂不修。(2026-11-03) -- **理由**:`Navigated` 是泛型类,`deinit` 里调用的 `clearup()` 在编译期就静态绑定到类里那份空实现,`where Content: …` 扩展里的同名方法永远不会被调用。导航观察者被释放时,原本打算关掉仍在显示的内容,但目前没有构造出现实中看得见的后果。直接把它激活反而有风险:模态那份会无条件调用 `stopModal()`,可能停掉一个并非本库发起的模态循环。 -- **复查条件**:收敛导航相关重载的重构时,连同下一条一起处理。 - -### `present(...)` 替换已弹出的视图控制器时,不分来源都调用本 binding 的 `onDismiss` - -- **裁决**:读代码确认,影响面小,暂不修。(2026-11-03) -- **理由**:同一个 presenter 已经有一个弹出的视图控制器时,新的 `present` 会先把它关掉,并调用*本 binding* 的 `onDismiss`,不管它是不是本 binding 弹出来的。UIKit 那边用一个 presenter 标记来区分。只有在同一个 presenter 上挂了两个 binding 时才会触发。另外,被关掉的那个 binding 现在能正确收到回写。 -- **复查条件**:同上。 - ### 上游 `UIKitNavigation` 的 `UITextField` 选区绑定同样把 UTF-16 偏移当成字符数 - **裁决**:确认是同类问题,fork 内不修,暂不向上游报告。(2026-11-03,暂不报告由用户决定) diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 9adecefabb..6c35451c50 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -7,7 +7,8 @@ Tools for making AppKit navigation simpler, more ergonomic and more precise. AppKitNavigation drives AppKit from observable models. Controls bind to a model's state in both directions: they show its value and write the user's changes back. Sheets, modal windows and popovers follow optional state: they are presented when it gains a value, dismissed when it becomes -`nil`, and write `nil` back when the user dismisses them. +`nil`, and write `nil` back when the user dismisses them. Their `onDismiss` closures run once for +each presentation, after it has left the screen, however it ended. ## Additional Resources @@ -57,6 +58,7 @@ popovers follow optional state: they are presented when it gains a value, dismis ### Presenting content from state +- ``ModalContent`` - ``AppKit/NSViewController`` - ``AppKit/NSWindow`` - ``AppKit/NSView`` From e34c400e7c478f9aea768d9ceb0f3cb97b9049a9 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 23:18:25 +0800 Subject: [PATCH 101/141] test(appkit): build the popover tests with compilers before Swift 6.4 Swift 6.3 treats the test's NSToolbarDelegate conformance as public and asks for a public import of AppKit, the same quirk TableSelectionBindingTests works around. Record the final verification in the proposal: the AppKit tests pass on Xcode 27.2, the presentation tests pass ten runs in a row, Xcode 26.6 builds the library and its tests, and the macOS case studies build. --- .../Evolutions/draft-appkit-presentation-redesign.md | 8 +++++++- .../AppKitNavigationTests/PopoverPresentationTests.swift | 8 +++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/draft-appkit-presentation-redesign.md index 54b1fe963c..d2ffd15e8f 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/draft-appkit-presentation-redesign.md @@ -359,7 +359,11 @@ final class BindingPresenter { 5. **present 与 destination**(已完成):迁过去、补文档注释,替换时只动自己弹的;`TransitionStyle` 移进 `Presentation.swift`,删除 `PresentationContent.swift`。修掉缺陷 5 剩下的部分(裁决清单里的那条暂缓项)。`ViewControllerPresentationTests` 共 11 条,新增的覆盖了 `.modalWindow` 风格和 `destination` 的自定义闭包;AppKit 测试共 61 条 XCTest、58 条 Swift Testing,全部通过。 6. **清理**(已完成):删除旧的 `NavigationObserver`、`NavigationContent`、各 `*Content.swift` 和 `AssociatedKeys`;`UIBinding` 版重载在第 2–5 步重写时都已标 `@_disfavoredOverload`(`destination` 的两个没有同形的 item 版,不需要)。加入 `PresentationOverloadTests`:第 6 条的歧义写法、`{ $item in … }` 写法和 XCOrganizer 那种多语句闭包。先去掉一处标记确认它编不过(报 `ambiguous use of 'modal(item:id:onDismiss:content:)'`),恢复后通过。AppKit 测试共 64 条 XCTest、58 条 Swift Testing,全部通过。 7. **文档**(已完成):文档注释已随第 2–5 步写好;本步更新 DocC 首页、`swift-navigation-bindings` skill(在 iCloud 的全局 skill 目录里,不在本仓库)和裁决清单(删掉已修好的两条暂缓项)。生成一次 AppKitNavigation 的文档:只剩上游共用内容里原有的 3 条链接警告,没有新增;生成时被 DocC 插件改写的 `Package.resolved` 已还原。 -8. **完整验证**:Xcode 27.2 跑 AppKit 的全部测试,成败只认原始退出码,弹出相关的测试连跑 10 次;Xcode 26.6 编译库和测试;用 xcodebuild 编译 Examples 里 macOS 版的 CaseStudies。 +8. **完整验证**(已完成):Xcode 27.2 跑 AppKit 的全部测试,成败只认原始退出码,弹出相关的测试连跑 10 次;Xcode 26.6 编译库和测试;用 xcodebuild 编译 Examples 里 macOS 版的 CaseStudies。结果: + - Xcode 27.2:AppKit 测试 64 条 XCTest、58 条 Swift Testing,退出码 0;弹出相关的 56 条连跑 10 次,全部通过。 + - Xcode 26.6(Swift 6.3.3):库和 AppKit 测试 target 编译通过,AppKit 部分没有警告。为此给 `PopoverPresentationTests` 加了 Swift 6.4 以前用的 `public import AppKit`:旧编译器把测试里 `NSToolbarDelegate` 的遵循当成公开的,与 `TableSelectionBindingTests` 的处理相同。 + - Examples:`CaseStudies` 的 macOS 版用 xcodebuild 编译成功。 + - 两份锁定文件构建后都已还原,没有改动。 每一步都能单独构建通过、测试全绿:第 2–5 步迁移期间,还没迁的方式继续走旧的 `NavigationObserver`,第 6 步才删除。 @@ -371,6 +375,7 @@ final class BindingPresenter { ## 后续项 - AppKit 测试的共享辅助(`PresentationTestSupport.swift` 里的等待、建窗口、记录 popover)将来可以移进一个独立的 `TestingSupport` 测试库;这要改四份 `Package*.swift`,不在这一批。 +- 「宿主释放时收起内容」只在 modal 上有测试。sheet、popover 和视图控制器的情形没有测:AppKit 在内容显示期间多半还持有宿主(sheet 的父窗口、popover 的锚点视图、弹出它的控制器),宿主能不能在那时释放,还没有验证。 ## 决策日志 @@ -406,3 +411,4 @@ final class BindingPresenter { | 2026-11-06 | 视图控制器的宿主释放时,只经 style 自己的弱引用去 dismiss;引用已空就只报告结束 | `presentingViewController` 是 `assign` 引用,宿主释放过程中读它不安全 | | 2026-11-06 | `.modalWindow` 风格补了测试 | 以前没有任何测试;测试表明 `presentAsModalWindow` 不阻塞,binding 能正常关掉它 | | 2026-11-06 | 第 7 步:DocC 首页保留 `AppKit/NSAlert` | 方案原以为它只剩下划线成员,实际还有 `AlertState` 的构造器和 `addButton`,页面仍有内容 | +| 2026-11-06 | 实现完成,待用户看过后收尾 | 八步都已提交并推送功能分支,验证结果见第 8 步。文档判断:不需要使用指南,调用方要遵守的契约(`onDismiss` 的时机、等锚点显示、宿主释放与取消 token、`destination` 的 `dismiss` 约定)都写在文档注释和 `swift-navigation-bindings` skill 里;暂不需要实现说明,难懂的决定(模态循环从 run loop 块启动、等被停下的循环返回、用 run loop 检查代替通知、内容强持有)写在代码的 NB 注释和本提案里,收尾时再判断一次;没有要登记的新术语 | diff --git a/Tests/AppKitNavigationTests/PopoverPresentationTests.swift b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift index 239f83f3fb..e304e2ec30 100644 --- a/Tests/AppKitNavigationTests/PopoverPresentationTests.swift +++ b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift @@ -1,5 +1,11 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - import AppKit + #if compiler(<6.4) + // NB: Compilers before Swift 6.4 treat the toolbar delegate's conformance below as public, + // and a public conformance needs a public import. + public import AppKit + #else + import AppKit + #endif import AppKitNavigation import XCTest From c63e05a49fbd437ead6a7d6f7986d09e51655704 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 6 Nov 2026 23:38:26 +0800 Subject: [PATCH 102/141] docs: number the presentation redesign proposal 0005 and mark it implemented --- .../Evolutions/0001-appkit-navigation-cleanup.md | 2 +- ...-redesign.md => 0005-appkit-presentation-redesign.md} | 9 +++++---- Documentations/Evolutions/README.md | 2 +- Documentations/Internal/ReviewDecisions.md | 2 +- Documentations/README.md | 2 +- 5 files changed, 9 insertions(+), 8 deletions(-) rename Documentations/Evolutions/{draft-appkit-presentation-redesign.md => 0005-appkit-presentation-redesign.md} (97%) diff --git a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md index a5366b1ccd..c91e40392e 100644 --- a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md +++ b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md @@ -37,7 +37,7 @@ - 保留 `TargetActionProtocol` 的 `Sendable` 要求和各控件的 `Sendable` 遵循:去掉它们才是真正的破坏性改动。 - 只动 fork 独有的文件,不碰与上游共用的 `SwiftNavigation` 和 UIKit 部分;四份清单的改动是向上游靠拢。 - 验证:Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译 AppKit 的库和测试。 -- 不在这一批:弹出相关三个文件(约 1,300 行)的重载收敛,连同 `Navigated.clearup()` 死代码(见 [ReviewDecisions.md](../Internal/ReviewDecisions.md)),属于大型重构,另起完整档提案;新功能各自另起提案。 +- 不在这一批:弹出相关三个文件(约 1,300 行)的重载收敛,连同 `Navigated.clearup()` 死代码(见 [ReviewDecisions.md](../Internal/ReviewDecisions.md)),属于大型重构,另起完整档提案;新功能各自另起提案。(已由 [0005](0005-appkit-presentation-redesign.md) 完成。) ## 后续项 diff --git a/Documentations/Evolutions/draft-appkit-presentation-redesign.md b/Documentations/Evolutions/0005-appkit-presentation-redesign.md similarity index 97% rename from Documentations/Evolutions/draft-appkit-presentation-redesign.md rename to Documentations/Evolutions/0005-appkit-presentation-redesign.md index d2ffd15e8f..471c07d50d 100644 --- a/Documentations/Evolutions/draft-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/0005-appkit-presentation-redesign.md @@ -1,13 +1,13 @@ -# Draft - AppKit 弹出 API 重做:生命周期收进一层,重载合并 +# 0005 - AppKit 弹出 API 重做:生命周期收进一层,重载合并 -- **状态**: In Progress +- **状态**: Implemented - **作者**: JH - **创建日期**: 2026-11-06 - **最后更新**: 2026-11-06 - **所属愿景**: 无 - **关联提案**: [0001 - AppKitNavigation 清理](0001-appkit-navigation-cleanup.md)(把这次重构留给了单独的完整档提案) -- **实现分支 / PR**: `appkit-presentation-redesign` -- **配套文档**: 待定 —— 落地时登记实现说明 / 使用指南的链接 +- **实现分支 / PR**: `appkit-presentation-redesign`,已合进 `main` +- **配套文档**: 无(调用方契约写在文档注释里,难懂的实现决定写在代码注释和本提案里) ## 摘要 @@ -412,3 +412,4 @@ final class BindingPresenter { | 2026-11-06 | `.modalWindow` 风格补了测试 | 以前没有任何测试;测试表明 `presentAsModalWindow` 不阻塞,binding 能正常关掉它 | | 2026-11-06 | 第 7 步:DocC 首页保留 `AppKit/NSAlert` | 方案原以为它只剩下划线成员,实际还有 `AlertState` 的构造器和 `addButton`,页面仍有内容 | | 2026-11-06 | 实现完成,待用户看过后收尾 | 八步都已提交并推送功能分支,验证结果见第 8 步。文档判断:不需要使用指南,调用方要遵守的契约(`onDismiss` 的时机、等锚点显示、宿主释放与取消 token、`destination` 的 `dismiss` 约定)都写在文档注释和 `swift-navigation-bindings` skill 里;暂不需要实现说明,难懂的决定(模态循环从 run loop 块启动、等被停下的循环返回、用 run loop 检查代替通知、内容强持有)写在代码的 NB 注释和本提案里,收尾时再判断一次;没有要登记的新术语 | +| 2026-11-06 | Implemented,编号 0005,落地到 `main` | 用户看过效果后要求收尾。八步全部完成,没做的两项留在后续项(独立的 `TestingSupport` 库;sheet、popover、视图控制器的「宿主释放时收起」没有测试)。验证沿用第 8 步那一轮的结果:合进 `main` 时 `main` 没有别的新提交,合并后的代码与测过的功能分支完全相同。文档判断:不需要使用指南,契约都在文档注释和 `swift-navigation-bindings` skill 里;不需要实现说明,难懂的决定都写在代码的 NB 注释和本提案里,下一任维护者读代码就能看到;没有要登记的新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index fbd20e386b..1162b5f0be 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -10,4 +10,4 @@ | 0002 | [AppKit 测试在 `swift test` 下不再中途以 0 退出](0002-appkit-test-run-loop-exit.md) | Implemented | | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | | 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | -| draft | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](draft-appkit-presentation-redesign.md) | In Progress | +| 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index 39c34a82ae..65f280bdab 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -21,7 +21,7 @@ ### alert 作为 sheet 时没走 `beginSheetModal(for:)`,会不排版、按钮关不掉 - **裁决**:误报。(2026-11-06) -- **理由**:`NSWindow.sheet` 把 alert 的窗口直接交给 `NSWindow.beginSheet(_:)`,确实没调用 `NSAlert.beginSheetModal(for:)`。但在 macOS 27.2 上测试,alert 的标题和说明文字照常排版显示,点按钮也照常结束 sheet、把 binding 写回 `false`。同一处代码对存取面板是真问题:点「取消」关不掉 sheet,见提案 [draft-appkit-presentation-redesign](../Evolutions/draft-appkit-presentation-redesign.md) 第 8 条。 +- **理由**:`NSWindow.sheet` 把 alert 的窗口直接交给 `NSWindow.beginSheet(_:)`,确实没调用 `NSAlert.beginSheetModal(for:)`。但在 macOS 27.2 上测试,alert 的标题和说明文字照常排版显示,点按钮也照常结束 sheet、把 binding 写回 `false`。同一处代码对存取面板是真问题:点「取消」关不掉 sheet,见提案 [0005-appkit-presentation-redesign](../Evolutions/0005-appkit-presentation-redesign.md) 第 8 条。 - **现状**:那份提案让 alert 改走自己的 `beginSheetModal(for:)`,`SheetPresentationTests` 里两条 alert 测试守着上面两点。 ### `NSFontManager(font:)` 会建出一个和字体面板无关的新实例 diff --git a/Documentations/README.md b/Documentations/README.md index 9bd7984827..2c98c4b373 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -9,7 +9,7 @@ - [0002-appkit-test-run-loop-exit.md](Evolutions/0002-appkit-test-run-loop-exit.md):AppKit 测试在 `swift test` 下不再中途以 0 退出。 - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 - [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 -- [draft-appkit-presentation-redesign.md](Evolutions/draft-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并(In Progress)。 +- [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 ## Internal From 036dfb8f38a35569c8425317dc8a1bc71745f28f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 8 Nov 2026 01:42:27 +0800 Subject: [PATCH 103/141] refactor(appkit): rename ModalContent to WindowBackedContent The protocol constrains the content of NSWindow.sheet as much as that of modal, so a name about modals reads as if it served only one of them. What its conforming types share is that each comes with a window of its own: a window is one, and an alert or a save or open panel has one. The protocol has not shipped in any release and nothing downstream names it, so the old name is not kept. Add the proposal and point to it from 0005. --- .../0005-appkit-presentation-redesign.md | 1 + Documentations/Evolutions/README.md | 1 + .../draft-appkit-window-backed-content.md | 29 +++++++++++++++++++ Documentations/README.md | 1 + .../Documentation.docc/AppKitNavigation.md | 2 +- .../AppKitNavigation/Navigation/Modal.swift | 12 ++++---- .../AppKitNavigation/Navigation/Sheet.swift | 12 ++++---- ...ontent.swift => WindowBackedContent.swift} | 6 ++-- 8 files changed, 48 insertions(+), 16 deletions(-) create mode 100644 Documentations/Evolutions/draft-appkit-window-backed-content.md rename Sources/AppKitNavigation/Navigation/{ModalContent.swift => WindowBackedContent.swift} (95%) diff --git a/Documentations/Evolutions/0005-appkit-presentation-redesign.md b/Documentations/Evolutions/0005-appkit-presentation-redesign.md index 471c07d50d..fefcb4ae00 100644 --- a/Documentations/Evolutions/0005-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/0005-appkit-presentation-redesign.md @@ -413,3 +413,4 @@ final class BindingPresenter { | 2026-11-06 | 第 7 步:DocC 首页保留 `AppKit/NSAlert` | 方案原以为它只剩下划线成员,实际还有 `AlertState` 的构造器和 `addButton`,页面仍有内容 | | 2026-11-06 | 实现完成,待用户看过后收尾 | 八步都已提交并推送功能分支,验证结果见第 8 步。文档判断:不需要使用指南,调用方要遵守的契约(`onDismiss` 的时机、等锚点显示、宿主释放与取消 token、`destination` 的 `dismiss` 约定)都写在文档注释和 `swift-navigation-bindings` skill 里;暂不需要实现说明,难懂的决定(模态循环从 run loop 块启动、等被停下的循环返回、用 run loop 检查代替通知、内容强持有)写在代码的 NB 注释和本提案里,收尾时再判断一次;没有要登记的新术语 | | 2026-11-06 | Implemented,编号 0005,落地到 `main` | 用户看过效果后要求收尾。八步全部完成,没做的两项留在后续项(独立的 `TestingSupport` 库;sheet、popover、视图控制器的「宿主释放时收起」没有测试)。验证沿用第 8 步那一轮的结果:合进 `main` 时 `main` 没有别的新提交,合并后的代码与测过的功能分支完全相同。文档判断:不需要使用指南,契约都在文档注释和 `swift-navigation-bindings` skill 里;不需要实现说明,难懂的决定都写在代码的 NB 注释和本提案里,下一任维护者读代码就能看到;没有要登记的新术语 | +| 2026-11-08 | 落地后,协议 `ModalContent` 改名为 `WindowBackedContent` | 这个名字读起来像只给 `modal` 用,而 `NSWindow.sheet` 也用它;改名的理由与做法见 [draft-appkit-window-backed-content](draft-appkit-window-backed-content.md)。本提案正文保持落地时的原样 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 1162b5f0be..72a7575eec 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -11,3 +11,4 @@ | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | | 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | | 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | +| draft | [把 `ModalContent` 改名为 `WindowBackedContent`](draft-appkit-window-backed-content.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-window-backed-content.md b/Documentations/Evolutions/draft-appkit-window-backed-content.md new file mode 100644 index 0000000000..ff17e70d37 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-window-backed-content.md @@ -0,0 +1,29 @@ +# Draft - 把 `ModalContent` 改名为 `WindowBackedContent` + +- **状态**: In Progress +- **创建日期**: 2026-11-08 +- **最后更新**: 2026-11-08 +- **实现分支**: `appkit-window-backed-content` + +## 摘要 + +[0005](0005-appkit-presentation-redesign.md) 新增的公开协议 `ModalContent`(`NSWindow`、`NSAlert` 与存取面板遵循)改名为 `WindowBackedContent`。这个协议同时是 `modal(...)` 和 `NSWindow.sheet(...)` 的内容约束,叫 `ModalContent` 读起来像只给 `modal` 用;遵循它的几种类型真正的共同点是各自带一个窗口,新名字直接说出这一点。 + +## 方案 + +- 协议、它所在的文件(`ModalContent.swift` → `WindowBackedContent.swift`)、`modal` 与 `NSWindow.sheet` 的泛型约束、两个内部 style 的约束一并改名。协议要求(`_appKitNavigation…`)不变。 +- 不保留旧名:这个协议还没随任何版本发布,下游也没有代码直接写它的名字,与 0005 不保留旧名的理由相同。 +- 同步文档注释、DocC 首页和 `swift-navigation-bindings` skill。0005 的正文保持原样,只在它的决策日志里记一行指向本提案。 + +没有询问就采用的假设: + +- 验证:Xcode 27.2 跑 AppKit 的全部测试,再生成一次 AppKitNavigation 的文档,确认符号链接都能解析。改动只是改名,不另用 Xcode 26.6 编译。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-08 | Created as Draft | `ModalContent` 读起来像只给 `modal` 用,而 `NSWindow.sheet` 也用它 | +| 2026-11-08 | 采用 `WindowBackedContent`,不采用 `NavigationContent` | 后者比实际范围宽:popover 与 `present` 收的 `NSViewController` 不遵循这个协议,叫它会让人以为所有导航 API 都收它;遵循者的共同点是各自带一个窗口,`NSWindow` 本身就是,`NSAlert` 与存取面板也都有自己的窗口 | +| 2026-11-08 | Accepted | 用户批准;做完在本地合进 `main`,不推送 | +| 2026-11-08 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试 64 条 XCTest、58 条 Swift Testing 全部通过;生成文档只有上游共用内容里原有的 3 条链接警告,新名字的符号页正常生成。文档判断:文档注释、DocC 首页、`swift-navigation-bindings` skill 已同步,0005 只加了一行指向本提案;不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/README.md b/Documentations/README.md index 2c98c4b373..7edd534fc8 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -10,6 +10,7 @@ - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 - [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 - [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 +- [draft-appkit-window-backed-content.md](Evolutions/draft-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`(In Progress)。 ## Internal diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 6c35451c50..9b76ae5a3f 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -58,7 +58,7 @@ each presentation, after it has left the screen, however it ended. ### Presenting content from state -- ``ModalContent`` +- ``WindowBackedContent`` - ``AppKit/NSViewController`` - ``AppKit/NSWindow`` - ``AppKit/NSView`` diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index eb5712cfea..56fe0893a1 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -21,7 +21,7 @@ /// - Returns: A token that stops following the binding once cancelled. Content that is /// running then keeps running until the user ends it. @discardableResult - public func modal( + public func modal( isPresented: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content @@ -51,7 +51,7 @@ /// - content: A closure that returns the window, alert or panel to run for the item. /// - Returns: A token that stops following the binding once cancelled. @discardableResult - public func modal( + public func modal( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content @@ -73,7 +73,7 @@ /// - Returns: A token that stops following the binding once cancelled. @_disfavoredOverload @discardableResult - public func modal( + public func modal( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content @@ -96,7 +96,7 @@ /// - content: A closure that returns the window, alert or panel to run for the item. /// - Returns: A token that stops following the binding once cancelled. @discardableResult - public func modal( + public func modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -124,7 +124,7 @@ /// - Returns: A token that stops following the binding once cancelled. @_disfavoredOverload @discardableResult - public func modal( + public func modal( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -277,7 +277,7 @@ /// Runs content in an application-modal loop of its own. @MainActor - private struct ModalLoopStyle: PresentationStyle { + private struct ModalLoopStyle: PresentationStyle { func begin( _ content: Content, transaction: UITransaction, diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 4a65c6ab65..7040828588 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -23,7 +23,7 @@ /// - Returns: A token that stops following the binding once cancelled. An attached sheet then /// stays until the user ends it. @discardableResult - public func sheet( + public func sheet( isPresented: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping () -> Content @@ -53,7 +53,7 @@ /// - content: A closure that returns the window, alert or panel to attach for the item. /// - Returns: A token that stops following the binding once cancelled. @discardableResult - public func sheet( + public func sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (Item) -> Content @@ -77,7 +77,7 @@ /// - Returns: A token that stops following the binding once cancelled. @_disfavoredOverload @discardableResult - public func sheet( + public func sheet( item: UIBinding, onDismiss: (() -> Void)? = nil, content: @escaping (UIBinding) -> Content @@ -105,7 +105,7 @@ /// - content: A closure that returns the window, alert or panel to attach for the item. /// - Returns: A token that stops following the binding once cancelled. @discardableResult - public func sheet( + public func sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -136,7 +136,7 @@ /// - Returns: A token that stops following the binding once cancelled. @_disfavoredOverload @discardableResult - public func sheet( + public func sheet( item: UIBinding, id: KeyPath, onDismiss: (() -> Void)? = nil, @@ -154,7 +154,7 @@ /// Attaches content to a window as a sheet. @MainActor - private struct SheetStyle: PresentationStyle { + private struct SheetStyle: PresentationStyle { weak var parentWindow: NSWindow? func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { diff --git a/Sources/AppKitNavigation/Navigation/ModalContent.swift b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift similarity index 95% rename from Sources/AppKitNavigation/Navigation/ModalContent.swift rename to Sources/AppKitNavigation/Navigation/WindowBackedContent.swift index 1a5093cf87..4e33e132b0 100644 --- a/Sources/AppKitNavigation/Navigation/ModalContent.swift +++ b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift @@ -13,7 +13,7 @@ /// The requirements are implementation details of AppKitNavigation. Conforming other types is not /// supported. @MainActor - public protocol ModalContent: AnyObject { + public protocol WindowBackedContent: AnyObject { /// The window that shows the content. @_documentation(visibility: private) var _appKitNavigationWindow: NSWindow { get } @@ -31,7 +31,7 @@ func _appKitNavigationRunModal() } - extension NSWindow: ModalContent { + extension NSWindow: WindowBackedContent { @_documentation(visibility: private) public var _appKitNavigationWindow: NSWindow { self } @@ -63,7 +63,7 @@ } } - extension NSAlert: ModalContent { + extension NSAlert: WindowBackedContent { @_documentation(visibility: private) public var _appKitNavigationWindow: NSWindow { window } From e86773072dda34206d4255d7bc8731b2be69c243 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 8 Nov 2026 02:09:30 +0800 Subject: [PATCH 104/141] docs(examples): add AppKit case studies for presentations and selection bindings Add a Presentation group to the AppKit case studies: every presentation style, from windows, alerts and save panels run modally or attached as sheets to view controllers presented in popovers; a modal alert running on top of a modal window; and a sheet ended by the user, by its state, and by a new item, with a log of each onDismiss call. Add two binding case studies: controls that pick one of several options, and table and outline selection with outline expansion. Fix the Basics case study's description, which said UIKit, and drop the two TODOs these case studies cover. --- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-appkit-case-studies.md | 38 +++ Documentations/README.md | 1 + ...ppKit+BasicsNavigationViewController.swift | 4 +- .../AppKit/AppKit+CaseStudySupport.swift | 123 ++++++++ .../AppKit+DismissalViewController.swift | 90 ++++++ .../AppKit+NestedModalViewController.swift | 97 ++++++ .../AppKit+OptionBindingsViewController.swift | 139 ++++++++ ...it+PresentationGalleryViewController.swift | 298 ++++++++++++++++++ .../AppKit+TableSelectionViewController.swift | 185 +++++++++++ .../AppKit/AppKitCaseStudies.swift | 9 +- Examples/Examples.xcodeproj/project.pbxproj | 24 ++ 12 files changed, 1005 insertions(+), 4 deletions(-) create mode 100644 Documentations/Evolutions/draft-appkit-case-studies.md create mode 100644 Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 72a7575eec..0fb4be0edc 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -12,3 +12,4 @@ | 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | | 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | | draft | [把 `ModalContent` 改名为 `WindowBackedContent`](draft-appkit-window-backed-content.md) | In Progress | +| draft | [给 AppKit 案例补上弹出与新控件绑定的演示](draft-appkit-case-studies.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-case-studies.md b/Documentations/Evolutions/draft-appkit-case-studies.md new file mode 100644 index 0000000000..24d58dbb21 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-case-studies.md @@ -0,0 +1,38 @@ +# Draft - 给 AppKit 案例补上弹出与新控件绑定的演示 + +- **状态**: In Progress +- **创建日期**: 2026-11-08 +- **最后更新**: 2026-11-08 +- **实现分支**: `appkit-window-backed-content` + +## 摘要 + +Examples 里的 AppKit 案例只演示了用 `present` 弹 sheet 和一个打开面板的 modal:[0005](0005-appkit-presentation-redesign.md) 重做后的弹出行为、[0003](0003-appkit-common-control-bindings.md) 和 [0004](0004-appkit-table-selection-bindings.md) 加的控件绑定都没有案例。这一批在 AppKit 案例列表里补上五个案例,让这些 API 有可以照着写、可以运行起来看的样子。 + +## 方案 + +新增一组「Presentation」,三个案例: + +- **弹出方式总览**:一个页面挨个演示窗口、alert、存取面板作为 sheet 和 modal,modal session,视图和工具栏项的 popover,以及视图控制器的三种 `present`。每种都在页面底部记下 `onDismiss` 的调用。 +- **嵌套 modal**:模态运行的设置窗口里,「重置」按钮先弹一个确认 alert,叠在设置窗口上面;绑定在 alert 还开着时要求关掉设置窗口,会等 alert 先结束。 +- **关闭与 `onDismiss`**:同一个 sheet 分别由用户关、由 binding 关、换成另一项,日志列出每次 `onDismiss` 的调用和当时 binding 的值。 + +「Bindings」一组加两个案例: + +- **选项绑定**:弹出按钮、分段控件、标签页控制器绑到同一个枚举,三者互相跟随;分段控件的每一段绑一个 `Bool`;下拉菜单里一个菜单项的勾号绑一个 `Bool`。 +- **表格与大纲的选中**:表格用 diffable data source 绑定选中项;大纲用一棵静态的树,绑定选中项和展开的项。 + +顺带的小改动:`Basics` 案例的说明把 AppKit 写成了 UIKit,改正;案例列表里已经由这一批覆盖的两条 TODO(alert 状态、关闭)删掉。 + +没有询问就采用的假设: + +- 新文件手工登记进 `Examples.xcodeproj`:官方 Xcode MCP 操作的是用户当前打开的 Xcode,而这个 worktree 里的工程没有打开,另一个工程文件工具这次会话里也没有。 +- 验证只编译 `CaseStudies` 的 macOS 版,不打开界面去点。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-08 | Created as Draft | 0005 的弹出行为和 0003、0004 的控件绑定都还没有可以运行的示例 | +| 2026-11-08 | Accepted | 用户选定了全部四块内容并批准;控件绑定那一块拆成两个案例,免得一个页面太挤。做完在本地合进 `main`,不推送 | +| 2026-11-08 | 实现完成,待用户看过后收尾 | 五个案例和一个共享辅助文件已登记进 `Examples.xcodeproj`;用 xcodebuild 编译 `CaseStudies` 的 macOS 版一次通过,新文件没有警告。没有打开界面去点。文档判断:案例本身就是示例文档,各自带说明;仓库 README 里关于案例的那一句来自上游,AppKit 案例此前就有,不用改;不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/README.md b/Documentations/README.md index 7edd534fc8..60843ab9ca 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -11,6 +11,7 @@ - [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 - [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 - [draft-appkit-window-backed-content.md](Evolutions/draft-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`(In Progress)。 +- [draft-appkit-case-studies.md](Evolutions/draft-appkit-case-studies.md):给 AppKit 案例补上弹出与新控件绑定的演示(In Progress)。 ## Internal diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index 6140afcab0..df3671ec08 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -6,8 +6,8 @@ import AppKitNavigation class BasicsNavigationViewController: XiblessViewController, AppKitCaseStudy { let caseStudyTitle = "Basics" let readMe = """ - This case study demonstrates how to perform every major form of navigation in UIKit (alerts, \ - sheets, drill-downs) by driving navigation off of optional and boolean state. + This case study demonstrates how to perform every major form of navigation in AppKit (modal \ + panels, sheets) by driving navigation off of optional and boolean state. """ @UIBindable var model = Model() diff --git a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift new file mode 100644 index 0000000000..e523e6734a --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift @@ -0,0 +1,123 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +// Small pieces the presentation and binding case studies share. + +/// A push button that runs `action` when clicked. +@MainActor +func makeButton(_ title: String, action: @escaping () -> Void) -> NSButton { + let button = NSButton(title: title, target: nil, action: nil) + button.addAction { _ in action() } + return button +} + +/// A bold label that heads a group of controls. +@MainActor +func makeSectionLabel(_ title: String) -> NSTextField { + let label = NSTextField(labelWithString: title) + label.font = .boldSystemFont(ofSize: NSFont.systemFontSize) + return label +} + +/// Lays `views` out in a column pinned to the top of `view`, and returns the column. +@MainActor +@discardableResult +func addColumn(of views: [NSView], to view: NSView) -> NSStackView { + let column = NSStackView(views: views) + column.orientation = .vertical + column.alignment = .leading + column.spacing = 10 + column.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(column) + NSLayoutConstraint.activate([ + column.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20), + column.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), + column.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20), + ]) + return column +} + +/// A titled, closable window showing a message above a row of buttons. +@MainActor +func makeWindow(title: String, message: String, buttons: [NSButton]) -> NSWindow { + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 380, height: 150), + styleMask: [.titled, .closable], + backing: .buffered, + defer: false + ) + window.title = title + window.isReleasedWhenClosed = false + + let messageLabel = NSTextField(wrappingLabelWithString: message) + let buttonRow = NSStackView(views: buttons) + buttonRow.orientation = .horizontal + buttonRow.spacing = 8 + let column = NSStackView(views: [messageLabel, buttonRow]) + column.orientation = .vertical + column.alignment = .leading + column.spacing = 16 + column.translatesAutoresizingMaskIntoConstraints = false + + let contentView = NSView() + contentView.addSubview(column) + NSLayoutConstraint.activate([ + column.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20), + column.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20), + column.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20), + column.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20), + messageLabel.widthAnchor.constraint(equalToConstant: 340), + ]) + window.contentView = contentView + window.center() + return window +} + +/// A view controller to present: a message above a row of buttons. +/// +/// Its Done button dismisses it the way a user would, through `dismiss(_:)`, so the presentation +/// learns about it from the dismissal and clears its state. +class MessageViewController: XiblessViewController { + private let message: String + private let extraButtons: [NSButton] + + init(message: String, extraButtons: [NSButton] = []) { + self.message = message + self.extraButtons = extraButtons + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + + let messageLabel = NSTextField(wrappingLabelWithString: message) + let doneButton = makeButton("Done") { [weak self] in + self?.dismiss(nil) + } + doneButton.keyEquivalent = "\r" + let buttonRow = NSStackView(views: extraButtons + [doneButton]) + buttonRow.orientation = .horizontal + buttonRow.spacing = 8 + let column = NSStackView(views: [messageLabel, buttonRow]) + column.orientation = .vertical + column.alignment = .leading + column.spacing = 16 + column.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(column) + NSLayoutConstraint.activate([ + column.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), + column.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), + column.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20), + column.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20), + messageLabel.widthAnchor.constraint(equalToConstant: 300), + ]) + } +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift new file mode 100644 index 0000000000..4166419f68 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift @@ -0,0 +1,90 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class DismissalViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Dismissal" + let readMe = """ + Presented content ends in one of three ways: you dismiss it, its state is cleared, or its state \ + switches to another item. Each way calls 'onDismiss' exactly once, after the content has left \ + the screen. When you dismiss it yourself, the state is cleared before 'onDismiss' runs. When the \ + item changes, the next item's sheet only comes up once the previous one has gone. + + The sheet's buttons try all three; the log lists each 'onDismiss' call with what the state held \ + at the time. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let presentButton = makeButton("Present the first fruit") { [weak self] in + self?.model.fruit = .apple + } + let logLabel = NSTextField(wrappingLabelWithString: "") + logLabel.textColor = .secondaryLabelColor + addColumn(of: [presentButton, makeSectionLabel("onDismiss log"), logLabel], to: view) + + observe { [weak self] in + guard let self else { return } + logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") + } + + present(item: $model.fruit, style: .sheet, onDismiss: { [weak self] in + guard let self else { return } + model.record("onDismiss ran; the state holds \(model.fruit?.name ?? "nothing")") + }) { [unowned self] fruit in + MessageViewController( + message: """ + This sheet shows \(fruit.name). Done dismisses it yourself; the other buttons change \ + its state instead. + """, + extraButtons: [ + makeButton("Clear the state") { [weak self] in + self?.model.record("Cleared the state") + self?.model.fruit = nil + }, + makeButton("Switch to \(fruit.next.name)") { [weak self] in + self?.model.record("Switched the state to \(fruit.next.name)") + self?.model.fruit = fruit.next + }, + ] + ) + } + } + + @Observable + class Model { + var fruit: Fruit? + var log: [String] = [] + + func record(_ event: String) { + log = Array((log + [event]).suffix(10)) + } + } + + enum Fruit: Int, Identifiable { + case apple + case banana + case cherry + + var id: Self { self } + + var name: String { + switch self { + case .apple: "an apple" + case .banana: "a banana" + case .cherry: "a cherry" + } + } + + var next: Self { + Self(rawValue: rawValue + 1) ?? .apple + } + } +} + +#Preview { + DismissalViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift new file mode 100644 index 0000000000..d35a8bba1f --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift @@ -0,0 +1,97 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class NestedModalViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Nested modals" + let readMe = """ + A modal can present another modal on top of itself. Here a settings window runs modally, and \ + its Reset button asks for confirmation with an alert that runs on top of the window. Ending the \ + alert returns to the settings window, which is still running. + + The settings window can also be closed from its state while the alert is up — try "Close in 3 \ + seconds" and then "Reset…". AppKit only stops the innermost modal, so the window waits until \ + the alert has ended, and then closes. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let openButton = makeButton("Open the settings") { [weak self] in + self?.model.isSettingsPresented = true + } + let statusLabel = NSTextField(wrappingLabelWithString: "") + addColumn(of: [openButton, statusLabel], to: view) + + observe { [weak self] in + guard let self else { return } + statusLabel.stringValue = """ + Settings window: \(model.isSettingsPresented ? "open" : "closed") + Confirmation alert: \(model.resetConfirmation != nil ? "open" : "closed") + Resets: \(model.resetCount) + """ + } + + modal(isPresented: $model.isSettingsPresented) { [unowned self] in + makeWindow( + title: "Settings", + message: "This window runs modally. Reset asks for confirmation with an alert on top of it.", + buttons: [ + makeButton("Reset…") { [weak self] in + self?.model.resetConfirmation = .reset + }, + makeButton("Close in 3 seconds") { [weak self] in + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { + self?.model.isSettingsPresented = false + } + }, + makeButton("Close") { [weak self] in + self?.model.isSettingsPresented = false + }, + ] + ) + } + + modal(item: $model.resetConfirmation) { [unowned self] alert in + NSAlert(state: alert) { [weak self] action in + if action == .reset { + self?.model.resetCount += 1 + } + } + } + } + + @Observable + class Model { + var isSettingsPresented = false + var resetConfirmation: AlertState? + var resetCount = 0 + + enum ConfirmationAction { + case reset + } + } +} + +extension AlertState where Action == NestedModalViewController.Model.ConfirmationAction { + static var reset: Self { + AlertState { + TextState("Reset all settings?") + } actions: { + ButtonState(role: .destructive, action: .reset) { + TextState("Reset") + } + ButtonState(role: .cancel) { + TextState("Cancel") + } + } message: { + TextState("The settings go back to how they were when the app was installed.") + } + } +} + +#Preview { + NestedModalViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift new file mode 100644 index 0000000000..0dedc08540 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift @@ -0,0 +1,139 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class OptionBindingsViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Options" + let readMe = """ + Controls that pick one of several options bind to the option itself. The pop-up button, the \ + segmented control and the tabs all follow the same fruit, so picking a fruit in any of them \ + moves the other two. + + A segmented control that lets you pick any number of segments binds each segment to a Bool of \ + its own, and a menu item binds its checkmark to a Bool. + """ + @UIBindable var model = Model() + private let tabViewController = NSTabViewController() + + override func viewDidLoad() { + super.viewDidLoad() + + let popUpButton = NSPopUpButton(selection: $model.fruit, options: Fruit.allCases, title: \.title) + let segmentedControl = NSSegmentedControl( + selection: $model.fruit, options: Fruit.allCases, title: \.title + ) + + for fruit in Fruit.allCases { + let tabViewItem = NSTabViewItem(viewController: FruitViewController(fruit: fruit)) + tabViewItem.label = fruit.title + tabViewController.addTabViewItem(tabViewItem) + } + tabViewController.tabStyle = .segmentedControlOnTop + // NB: Bound once the tabs are in place: the binding selects the tab of the current option. + tabViewController.bind(selection: $model.fruit, options: Fruit.allCases) + addChild(tabViewController) + let tabView = tabViewController.view + tabView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + tabView.widthAnchor.constraint(equalToConstant: 320), + tabView.heightAnchor.constraint(equalToConstant: 110), + ]) + + let styleControl = NSSegmentedControl( + labels: ["Bold", "Italic", "Underline"], trackingMode: .selectAny, target: nil, action: nil + ) + styleControl.bind(isSelected: $model.isBold, forSegment: 0) + styleControl.bind(isSelected: $model.isItalic, forSegment: 1) + styleControl.bind(isSelected: $model.isUnderlined, forSegment: 2) + + let viewOptionsButton = NSPopUpButton(frame: .zero, pullsDown: true) + viewOptionsButton.addItem(withTitle: "View options") + viewOptionsButton.menu?.addItem(NSMenuItem(title: "Show the grid", isOn: $model.showsGrid)) + + let statusLabel = NSTextField(wrappingLabelWithString: "") + statusLabel.textColor = .secondaryLabelColor + + addColumn( + of: [ + makeSectionLabel("One of several options"), + popUpButton, + segmentedControl, + tabView, + makeSectionLabel("A Bool for each segment"), + styleControl, + makeSectionLabel("A menu item's checkmark"), + viewOptionsButton, + statusLabel, + ], + to: view + ) + + observe { [weak self] in + guard let self else { return } + let styles = [ + model.isBold ? "bold" : nil, + model.isItalic ? "italic" : nil, + model.isUnderlined ? "underlined" : nil, + ].compactMap(\.self) + statusLabel.stringValue = """ + Fruit: \(model.fruit.title) + Style: \(styles.isEmpty ? "plain" : styles.joined(separator: ", ")) + Grid: \(model.showsGrid ? "shown" : "hidden") + """ + } + } + + @Observable + class Model { + var fruit = Fruit.banana + var isBold = true + var isItalic = false + var isUnderlined = false + var showsGrid = false + } + + enum Fruit: CaseIterable { + case apple + case banana + case cherry + + var title: String { + switch self { + case .apple: "Apple" + case .banana: "Banana" + case .cherry: "Cherry" + } + } + } +} + +/// The content of one tab: the name of its fruit. +private class FruitViewController: XiblessViewController { + private let fruit: OptionBindingsViewController.Fruit + + init(fruit: OptionBindingsViewController.Fruit) { + self.fruit = fruit + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + let label = NSTextField(labelWithString: "This tab is about the \(fruit.title.lowercased()).") + label.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(label) + NSLayoutConstraint.activate([ + label.centerXAnchor.constraint(equalTo: view.centerXAnchor), + label.centerYAnchor.constraint(equalTo: view.centerYAnchor), + ]) + } +} + +#Preview { + OptionBindingsViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift new file mode 100644 index 0000000000..0551163cb1 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift @@ -0,0 +1,298 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class PresentationGalleryViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Presentation styles" + let readMe = """ + This case study shows every way AppKitNavigation presents content from state. A window, an \ + alert or a save panel runs modally, or is attached to a window as a sheet; a window can also be \ + shown in a modal session, which takes the app's input without blocking. A view or a toolbar \ + item shows a popover, and a view controller presents another one as a sheet, in a modal window \ + or in a popover. + + Every presentation is driven by the model alone: setting its state presents the content, \ + clearing it dismisses the content, and dismissing the content yourself clears the state. The \ + log lists each 'onDismiss' call, which comes once the content has left the screen. + """ + @UIBindable var model = Model() + private var documentWindow: NSWindow? + private let toolbarDelegate = InfoToolbarDelegate() + + override func viewDidLoad() { + super.viewDidLoad() + + let modalWindowButton = makeButton("Run a window modally") { [weak self] in + self?.model.isModalWindowPresented = true + } + let modalAlertButton = makeButton("Run an alert modally") { [weak self] in + self?.model.modalAlert = .discardChanges + } + let modalSessionButton = makeButton("Show a window in a modal session") { [weak self] in + self?.model.isModalSessionPresented = true + } + let popoverButton = makeButton("Show a popover from this button") { [weak self] in + self?.model.isPopoverPresented = true + } + let viewControllerSheetButton = makeButton("Present as a sheet") { [weak self] in + self?.model.isViewControllerSheetPresented = true + } + let viewControllerWindowButton = makeButton("Present in a modal window") { [weak self] in + self?.model.isViewControllerWindowPresented = true + } + let viewControllerPopoverButton = makeButton("Present in a popover") { [weak self] in + self?.model.isViewControllerPopoverPresented = true + } + let documentWindowButton = makeButton("Open a document window") { [weak self] in + self?.openDocumentWindow() + } + let logLabel = NSTextField(wrappingLabelWithString: "") + logLabel.textColor = .secondaryLabelColor + + addColumn( + of: [ + makeSectionLabel("Windows, alerts and panels"), + modalWindowButton, + modalAlertButton, + modalSessionButton, + documentWindowButton, + makeSectionLabel("Popovers"), + popoverButton, + makeSectionLabel("View controllers"), + viewControllerSheetButton, + viewControllerWindowButton, + viewControllerPopoverButton, + makeSectionLabel("onDismiss log"), + logLabel, + ], + to: view + ) + + observe { [weak self] in + guard let self else { return } + logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") + } + + // MARK: Modals + + modal(isPresented: $model.isModalWindowPresented, onDismiss: { [weak self] in + self?.model.record("Modal window") + }) { [unowned self] in + makeWindow( + title: "Modal window", + message: "This window runs modally. Close it from its title bar, or with the button.", + buttons: [ + makeButton("Close") { [weak self] in + self?.model.isModalWindowPresented = false + } + ] + ) + } + + modal(item: $model.modalAlert, onDismiss: { [weak self] in + self?.model.record("Modal alert") + }) { [unowned self] alert in + NSAlert(state: alert) { [weak self] action in + self?.model.record("Modal alert action: \(action.map { "\($0)" } ?? "cancel")") + } + } + + modalSession(isPresented: $model.isModalSessionPresented, onDismiss: { [weak self] in + self?.model.record("Modal session window") + }) { [unowned self] in + makeWindow( + title: "Modal session", + message: "This window is in a modal session: it takes the app's input, yet nothing waits for it.", + buttons: [ + makeButton("Close") { [weak self] in + self?.model.isModalSessionPresented = false + } + ] + ) + } + + // MARK: Popovers + + popoverButton.popover( + isPresented: $model.isPopoverPresented, + preferredEdge: .maxX, + onDismiss: { [weak self] in self?.model.record("Popover from a button") } + ) { + MessageViewController(message: "A popover anchored to a button. Click outside it to close it.") + } + + // MARK: View controllers + + present(isPresented: $model.isViewControllerSheetPresented, style: .sheet, onDismiss: { [weak self] in + self?.model.record("View controller sheet") + }) { + MessageViewController(message: "A view controller presented as a sheet.") + } + + present(isPresented: $model.isViewControllerWindowPresented, style: .modalWindow, onDismiss: { [weak self] in + self?.model.record("View controller modal window") + }) { + MessageViewController(message: "A view controller presented in a modal window.") + } + + present( + isPresented: $model.isViewControllerPopoverPresented, + style: .popover( + rect: viewControllerPopoverButton.bounds, + view: viewControllerPopoverButton, + preferredEdge: .maxX, + behavior: .transient + ), + onDismiss: { [weak self] in self?.model.record("View controller popover") } + ) { + MessageViewController(message: "A view controller presented in a popover.") + } + } + + override func viewDidDisappear() { + super.viewDidDisappear() + documentWindow?.close() + documentWindow = nil + } + + /// Opens a window of the case study's own: sheets attach to it, and its toolbar item shows a + /// popover. + private func openDocumentWindow() { + if let documentWindow { + documentWindow.makeKeyAndOrderFront(nil) + return + } + let window = makeWindow( + title: "Document", + message: "Sheets attach to this window, and its toolbar item shows a popover.", + buttons: [ + makeButton("Window sheet") { [weak self] in + self?.model.isWindowSheetPresented = true + }, + makeButton("Alert sheet") { [weak self] in + self?.model.alertSheet = .discardChanges + }, + makeButton("Save panel sheet") { [weak self] in + self?.model.isSavePanelSheetPresented = true + }, + ] + ) + toolbarDelegate.infoItem.addAction { [weak self] _ in + self?.model.isToolbarPopoverPresented.toggle() + } + let toolbar = NSToolbar(identifier: "PresentationGallery.Document") + toolbar.delegate = toolbarDelegate + window.toolbar = toolbar + + // NB: Set up before the window is on screen: a sheet waits until its window is. + window.sheet(isPresented: $model.isWindowSheetPresented, onDismiss: { [weak self] in + self?.model.record("Window sheet") + }) { [unowned self] in + makeWindow( + title: "Sheet", + message: "A window attached as a sheet.", + buttons: [ + makeButton("Done") { [weak self] in + self?.model.isWindowSheetPresented = false + } + ] + ) + } + window.sheet(item: $model.alertSheet, onDismiss: { [weak self] in + self?.model.record("Alert sheet") + }) { [unowned self] alert in + NSAlert(state: alert) { [weak self] action in + self?.model.record("Alert sheet action: \(action.map { "\($0)" } ?? "cancel")") + } + } + window.sheet(isPresented: $model.isSavePanelSheetPresented, onDismiss: { [weak self] in + guard let self else { return } + model.record("Save panel sheet, chose \(model.savedURL?.lastPathComponent ?? "nothing")") + }) { [unowned self] in + NSSavePanel(url: $model.savedURL) + } + toolbarDelegate.infoItem.popover( + isPresented: $model.isToolbarPopoverPresented, + onDismiss: { [weak self] in self?.model.record("Popover from a toolbar item") } + ) { + MessageViewController(message: "A popover anchored to a toolbar item.") + } + + window.makeKeyAndOrderFront(nil) + documentWindow = window + } + + @Observable + class Model { + var isModalWindowPresented = false + var modalAlert: AlertState? + var isModalSessionPresented = false + var isPopoverPresented = false + var isViewControllerSheetPresented = false + var isViewControllerWindowPresented = false + var isViewControllerPopoverPresented = false + var isWindowSheetPresented = false + var alertSheet: AlertState? + var isSavePanelSheetPresented = false + var savedURL: URL? + var isToolbarPopoverPresented = false + var log: [String] = [] + + enum AlertAction { + case discard + } + + func record(_ event: String) { + log = Array((log + [event]).suffix(8)) + } + } +} + +extension AlertState where Action == PresentationGalleryViewController.Model.AlertAction { + static var discardChanges: Self { + AlertState { + TextState("Discard the changes?") + } actions: { + ButtonState(role: .destructive, action: .discard) { + TextState("Discard") + } + ButtonState(role: .cancel) { + TextState("Cancel") + } + } message: { + TextState("They can't be recovered.") + } + } +} + +/// Provides the document window's toolbar, which holds a single Info item. +@MainActor +private final class InfoToolbarDelegate: NSObject, NSToolbarDelegate { + let infoItem: NSToolbarItem = { + let item = NSToolbarItem(itemIdentifier: NSToolbarItem.Identifier("Info")) + item.label = "Info" + item.image = NSImage(systemSymbolName: "info.circle", accessibilityDescription: "Info") + return item + }() + + func toolbar( + _ toolbar: NSToolbar, + itemForItemIdentifier itemIdentifier: NSToolbarItem.Identifier, + willBeInsertedIntoToolbar flag: Bool + ) -> NSToolbarItem? { + itemIdentifier == infoItem.itemIdentifier ? infoItem : nil + } + + func toolbarDefaultItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [infoItem.itemIdentifier] + } + + func toolbarAllowedItemIdentifiers(_ toolbar: NSToolbar) -> [NSToolbarItem.Identifier] { + [infoItem.itemIdentifier] + } +} + +#Preview { + PresentationGalleryViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift new file mode 100644 index 0000000000..8d885ed187 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift @@ -0,0 +1,185 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class TableSelectionViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Table and outline selection" + let readMe = """ + A table or an outline binds its selected row to the identifier of the selected item, and an \ + outline binds the items it has expanded to a set of identifiers. The model holds identifiers \ + rather than rows, so it does not have to know how the rows are laid out. + + The table uses a diffable data source, which the binding asks for rows directly. The outline \ + uses a data source of its own and gives the binding its row lookups. The buttons change the \ + model; clicking in the table or the outline changes it too. + """ + @UIBindable var model = Model() + private let tableView = NSTableView() + private let outlineView = NSOutlineView() + private let outlineDataSource = PantryOutlineDataSource() + private var tableDataSource: NSTableViewDiffableDataSource? + + override func viewDidLoad() { + super.viewDidLoad() + + // MARK: Table + + let tableColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Planet")) + tableColumn.title = "Planet" + tableView.addTableColumn(tableColumn) + let tableDataSource = NSTableViewDiffableDataSource(tableView: tableView) { + _, _, _, planet in + NSTextField(labelWithString: planet) + } + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(["Mercury", "Venus", "Earth", "Mars", "Jupiter"]) + tableDataSource.apply(snapshot, animatingDifferences: false) + self.tableDataSource = tableDataSource + tableView.bind(selection: $model.selectedPlanet, dataSource: tableDataSource) + + // MARK: Outline + + // NB: Captured weakly below: the outline keeps its bindings, and the bindings keep these + // closures. + let outlineView = self.outlineView + let outlineDataSource = self.outlineDataSource + let outlineColumn = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Item")) + outlineColumn.title = "Pantry" + outlineView.addTableColumn(outlineColumn) + outlineView.outlineTableColumn = outlineColumn + outlineView.dataSource = outlineDataSource + outlineView.delegate = outlineDataSource + outlineView.bind( + selection: $model.selectedPantryItem, + row: { [weak outlineView, weak outlineDataSource] name in + guard let outlineView, let node = outlineDataSource?.node(named: name) else { return nil } + return outlineView.row(forItem: node) + }, + itemIdentifier: { [weak outlineView] row in + (outlineView?.item(atRow: row) as? PantryNode)?.name + } + ) + outlineView.bind( + expandedItems: $model.expandedPantryGroups, + itemIdentifier: { [weak outlineView] row in + (outlineView?.item(atRow: row) as? PantryNode)?.name + } + ) + + let statusLabel = NSTextField(wrappingLabelWithString: "") + statusLabel.textColor = .secondaryLabelColor + + addColumn( + of: [ + makeSectionLabel("Table"), + Self.scrollView(containing: tableView), + makeButton("Select Mars") { [weak self] in + self?.model.selectedPlanet = "Mars" + }, + makeButton("Clear the table's selection") { [weak self] in + self?.model.selectedPlanet = nil + }, + makeSectionLabel("Outline"), + Self.scrollView(containing: outlineView), + makeButton("Select Cherries") { [weak self] in + // NB: Expanded too, since a row only exists while its group is expanded. + self?.model.expandedPantryGroups.insert("Fruit") + self?.model.selectedPantryItem = "Cherries" + }, + makeButton("Expand everything") { [weak self] in + self?.model.expandedPantryGroups = Set(PantryOutlineDataSource.groupNames) + }, + makeButton("Collapse everything") { [weak self] in + self?.model.expandedPantryGroups = [] + }, + statusLabel, + ], + to: view + ) + + observe { [weak self] in + guard let self else { return } + statusLabel.stringValue = """ + Table selection: \(model.selectedPlanet ?? "none") + Outline selection: \(model.selectedPantryItem ?? "none") + Expanded groups: \(model.expandedPantryGroups.isEmpty ? "none" : model.expandedPantryGroups.sorted().joined(separator: ", ")) + """ + } + } + + private static func scrollView(containing tableView: NSTableView) -> NSScrollView { + tableView.headerView = nil + let scrollView = NSScrollView() + scrollView.documentView = tableView + scrollView.hasVerticalScroller = true + scrollView.borderType = .bezelBorder + scrollView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + scrollView.widthAnchor.constraint(equalToConstant: 260), + scrollView.heightAnchor.constraint(equalToConstant: 120), + ]) + return scrollView + } + + @Observable + class Model { + var selectedPlanet: String? + var selectedPantryItem: String? + var expandedPantryGroups: Set = ["Vegetables"] + } +} + +/// An item in the outline: a group of the pantry, or something in it. +private final class PantryNode { + let name: String + let children: [PantryNode] + + init(_ name: String, children: [PantryNode] = []) { + self.name = name + self.children = children + } +} + +/// The outline's data: a fixed tree of groups and the items in them. +@MainActor +private final class PantryOutlineDataSource: NSObject, NSOutlineViewDataSource, NSOutlineViewDelegate { + static let groupNames = ["Fruit", "Vegetables"] + + private let groups = [ + PantryNode("Fruit", children: [PantryNode("Apples"), PantryNode("Cherries")]), + PantryNode("Vegetables", children: [PantryNode("Carrots"), PantryNode("Leeks")]), + ] + + /// The node with the given name, wherever it is in the tree. + func node(named name: String) -> PantryNode? { + for group in groups { + if group.name == name { return group } + if let child = group.children.first(where: { $0.name == name }) { return child } + } + return nil + } + + func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int { + (item as? PantryNode)?.children.count ?? groups.count + } + + func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any { + (item as? PantryNode)?.children[index] ?? groups[index] + } + + func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool { + !((item as? PantryNode)?.children.isEmpty ?? true) + } + + func outlineView( + _ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any + ) -> NSView? { + NSTextField(labelWithString: (item as? PantryNode)?.name ?? "") + } +} + +#Preview { + TableSelectionViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift index 5fb7bee5c3..8127293e0b 100644 --- a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -13,12 +13,18 @@ struct AppKitCaseStudiesView: View { NSControlBindingsViewController() EnumControlsViewController() FocusViewController() + OptionBindingsViewController() + TableSelectionViewController() } CaseStudyGroupView("Optional navigation") { BasicsNavigationViewController() - // TODO: Alert/dialog state ConciseEnumNavigationViewController() } + CaseStudyGroupView("Presentation") { + PresentationGalleryViewController() + NestedModalViewController() + DismissalViewController() + } // CaseStudyGroupView("Stack navigation") { // StaticNavigationStackController() // ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) @@ -26,7 +32,6 @@ struct AppKitCaseStudiesView: View { // } CaseStudyGroupView("Advanced") { // TODO: Deep link - // TODO: Dismissal (show off from VCs and views) WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)) } } diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index 8fd8837a98..de5d831fb4 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -73,6 +73,12 @@ E9CD5B7B2C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */; }; E9CD5B7C2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B7A2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift */; }; E9CD5B7E2C6D14DC00CE7947 /* AppKitCaseStudies.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9CD5B7D2C6D14DC00CE7947 /* AppKitCaseStudies.swift */; }; + E9F0050A2EDA000000000011 /* AppKit+CaseStudySupport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000001 /* AppKit+CaseStudySupport.swift */; }; + E9F0050A2EDA000000000012 /* AppKit+PresentationGalleryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000002 /* AppKit+PresentationGalleryViewController.swift */; }; + E9F0050A2EDA000000000013 /* AppKit+NestedModalViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000003 /* AppKit+NestedModalViewController.swift */; }; + E9F0050A2EDA000000000014 /* AppKit+DismissalViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000004 /* AppKit+DismissalViewController.swift */; }; + E9F0050A2EDA000000000015 /* AppKit+OptionBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */; }; + E9F0050A2EDA000000000016 /* AppKit+TableSelectionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -148,6 +154,12 @@ E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppKit+BasicsNavigationViewController.swift"; sourceTree = ""; }; E9CD5B7A2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "AppKit+ConciseEnumNavigationViewController.swift"; sourceTree = ""; }; E9CD5B7D2C6D14DC00CE7947 /* AppKitCaseStudies.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppKitCaseStudies.swift; sourceTree = ""; }; + E9F0050A2EDA000000000001 /* AppKit+CaseStudySupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+CaseStudySupport.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000002 /* AppKit+PresentationGalleryViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+PresentationGalleryViewController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000003 /* AppKit+NestedModalViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+NestedModalViewController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000004 /* AppKit+DismissalViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+DismissalViewController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+OptionBindingsViewController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+TableSelectionViewController.swift"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -347,6 +359,12 @@ E9CD5B772C6CDEA500CE7947 /* AppKit+FocusViewController.swift */, E9CD5B792C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift */, E9CD5B7A2C6CE1BE00CE7947 /* AppKit+ConciseEnumNavigationViewController.swift */, + E9F0050A2EDA000000000001 /* AppKit+CaseStudySupport.swift */, + E9F0050A2EDA000000000002 /* AppKit+PresentationGalleryViewController.swift */, + E9F0050A2EDA000000000003 /* AppKit+NestedModalViewController.swift */, + E9F0050A2EDA000000000004 /* AppKit+DismissalViewController.swift */, + E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */, + E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */, ); path = AppKit; sourceTree = ""; @@ -593,6 +611,12 @@ E99B059E2C70CF18003D3AFF /* NetworkDetailModel.swift in Sources */, E99B059C2C70CEFE003D3AFF /* ConnectToNetworkModel.swift in Sources */, E9CD5B7B2C6CE1BE00CE7947 /* AppKit+BasicsNavigationViewController.swift in Sources */, + E9F0050A2EDA000000000011 /* AppKit+CaseStudySupport.swift in Sources */, + E9F0050A2EDA000000000012 /* AppKit+PresentationGalleryViewController.swift in Sources */, + E9F0050A2EDA000000000013 /* AppKit+NestedModalViewController.swift in Sources */, + E9F0050A2EDA000000000014 /* AppKit+DismissalViewController.swift in Sources */, + E9F0050A2EDA000000000015 /* AppKit+OptionBindingsViewController.swift in Sources */, + E9F0050A2EDA000000000016 /* AppKit+TableSelectionViewController.swift in Sources */, DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */, E99B05992C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift in Sources */, E99B05A42C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift in Sources */, From 67804fc088aa327a2a4e8678e68e399e01fe164a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 8 Nov 2026 03:15:55 +0800 Subject: [PATCH 105/141] docs: number proposals 0006 and 0007 and mark them implemented --- .../Evolutions/0005-appkit-presentation-redesign.md | 2 +- ...ked-content.md => 0006-appkit-window-backed-content.md} | 7 ++++--- ...-appkit-case-studies.md => 0007-appkit-case-studies.md} | 7 ++++--- Documentations/Evolutions/README.md | 4 ++-- Documentations/README.md | 4 ++-- 5 files changed, 13 insertions(+), 11 deletions(-) rename Documentations/Evolutions/{draft-appkit-window-backed-content.md => 0006-appkit-window-backed-content.md} (82%) rename Documentations/Evolutions/{draft-appkit-case-studies.md => 0007-appkit-case-studies.md} (85%) diff --git a/Documentations/Evolutions/0005-appkit-presentation-redesign.md b/Documentations/Evolutions/0005-appkit-presentation-redesign.md index fefcb4ae00..2a9a89e690 100644 --- a/Documentations/Evolutions/0005-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/0005-appkit-presentation-redesign.md @@ -413,4 +413,4 @@ final class BindingPresenter { | 2026-11-06 | 第 7 步:DocC 首页保留 `AppKit/NSAlert` | 方案原以为它只剩下划线成员,实际还有 `AlertState` 的构造器和 `addButton`,页面仍有内容 | | 2026-11-06 | 实现完成,待用户看过后收尾 | 八步都已提交并推送功能分支,验证结果见第 8 步。文档判断:不需要使用指南,调用方要遵守的契约(`onDismiss` 的时机、等锚点显示、宿主释放与取消 token、`destination` 的 `dismiss` 约定)都写在文档注释和 `swift-navigation-bindings` skill 里;暂不需要实现说明,难懂的决定(模态循环从 run loop 块启动、等被停下的循环返回、用 run loop 检查代替通知、内容强持有)写在代码的 NB 注释和本提案里,收尾时再判断一次;没有要登记的新术语 | | 2026-11-06 | Implemented,编号 0005,落地到 `main` | 用户看过效果后要求收尾。八步全部完成,没做的两项留在后续项(独立的 `TestingSupport` 库;sheet、popover、视图控制器的「宿主释放时收起」没有测试)。验证沿用第 8 步那一轮的结果:合进 `main` 时 `main` 没有别的新提交,合并后的代码与测过的功能分支完全相同。文档判断:不需要使用指南,契约都在文档注释和 `swift-navigation-bindings` skill 里;不需要实现说明,难懂的决定都写在代码的 NB 注释和本提案里,下一任维护者读代码就能看到;没有要登记的新术语 | -| 2026-11-08 | 落地后,协议 `ModalContent` 改名为 `WindowBackedContent` | 这个名字读起来像只给 `modal` 用,而 `NSWindow.sheet` 也用它;改名的理由与做法见 [draft-appkit-window-backed-content](draft-appkit-window-backed-content.md)。本提案正文保持落地时的原样 | +| 2026-11-08 | 落地后,协议 `ModalContent` 改名为 `WindowBackedContent` | 这个名字读起来像只给 `modal` 用,而 `NSWindow.sheet` 也用它;改名的理由与做法见 [0006](0006-appkit-window-backed-content.md)。本提案正文保持落地时的原样 | diff --git a/Documentations/Evolutions/draft-appkit-window-backed-content.md b/Documentations/Evolutions/0006-appkit-window-backed-content.md similarity index 82% rename from Documentations/Evolutions/draft-appkit-window-backed-content.md rename to Documentations/Evolutions/0006-appkit-window-backed-content.md index ff17e70d37..d5e9c0b64a 100644 --- a/Documentations/Evolutions/draft-appkit-window-backed-content.md +++ b/Documentations/Evolutions/0006-appkit-window-backed-content.md @@ -1,9 +1,9 @@ -# Draft - 把 `ModalContent` 改名为 `WindowBackedContent` +# 0006 - 把 `ModalContent` 改名为 `WindowBackedContent` -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-08 - **最后更新**: 2026-11-08 -- **实现分支**: `appkit-window-backed-content` +- **实现分支**: `appkit-window-backed-content`,已合进 `main` ## 摘要 @@ -27,3 +27,4 @@ | 2026-11-08 | 采用 `WindowBackedContent`,不采用 `NavigationContent` | 后者比实际范围宽:popover 与 `present` 收的 `NSViewController` 不遵循这个协议,叫它会让人以为所有导航 API 都收它;遵循者的共同点是各自带一个窗口,`NSWindow` 本身就是,`NSAlert` 与存取面板也都有自己的窗口 | | 2026-11-08 | Accepted | 用户批准;做完在本地合进 `main`,不推送 | | 2026-11-08 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试 64 条 XCTest、58 条 Swift Testing 全部通过;生成文档只有上游共用内容里原有的 3 条链接警告,新名字的符号页正常生成。文档判断:文档注释、DocC 首页、`swift-navigation-bindings` skill 已同步,0005 只加了一行指向本提案;不需要使用指南或实现说明,没有新术语 | +| 2026-11-08 | Implemented,编号 0006,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:AppKit 测试全部通过,文档生成没有新警告;合并后的代码与测过的功能分支相同。文档判断同上一行:不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/draft-appkit-case-studies.md b/Documentations/Evolutions/0007-appkit-case-studies.md similarity index 85% rename from Documentations/Evolutions/draft-appkit-case-studies.md rename to Documentations/Evolutions/0007-appkit-case-studies.md index 24d58dbb21..bbeba2cf86 100644 --- a/Documentations/Evolutions/draft-appkit-case-studies.md +++ b/Documentations/Evolutions/0007-appkit-case-studies.md @@ -1,9 +1,9 @@ -# Draft - 给 AppKit 案例补上弹出与新控件绑定的演示 +# 0007 - 给 AppKit 案例补上弹出与新控件绑定的演示 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-08 - **最后更新**: 2026-11-08 -- **实现分支**: `appkit-window-backed-content` +- **实现分支**: `appkit-window-backed-content`,已合进 `main` ## 摘要 @@ -36,3 +36,4 @@ Examples 里的 AppKit 案例只演示了用 `present` 弹 sheet 和一个打开 | 2026-11-08 | Created as Draft | 0005 的弹出行为和 0003、0004 的控件绑定都还没有可以运行的示例 | | 2026-11-08 | Accepted | 用户选定了全部四块内容并批准;控件绑定那一块拆成两个案例,免得一个页面太挤。做完在本地合进 `main`,不推送 | | 2026-11-08 | 实现完成,待用户看过后收尾 | 五个案例和一个共享辅助文件已登记进 `Examples.xcodeproj`;用 xcodebuild 编译 `CaseStudies` 的 macOS 版一次通过,新文件没有警告。没有打开界面去点。文档判断:案例本身就是示例文档,各自带说明;仓库 README 里关于案例的那一句来自上游,AppKit 案例此前就有,不用改;不需要使用指南或实现说明,没有新术语 | +| 2026-11-08 | Implemented,编号 0007,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:`CaseStudies` 的 macOS 版编译通过;界面没有点过。文档判断同上一行:案例本身就是示例文档,不需要另写使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 0fb4be0edc..c8b37f533b 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -11,5 +11,5 @@ | 0003 | [AppKit 常用控件的类型化绑定](0003-appkit-common-control-bindings.md) | Implemented | | 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | | 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | -| draft | [把 `ModalContent` 改名为 `WindowBackedContent`](draft-appkit-window-backed-content.md) | In Progress | -| draft | [给 AppKit 案例补上弹出与新控件绑定的演示](draft-appkit-case-studies.md) | In Progress | +| 0006 | [把 `ModalContent` 改名为 `WindowBackedContent`](0006-appkit-window-backed-content.md) | Implemented | +| 0007 | [给 AppKit 案例补上弹出与新控件绑定的演示](0007-appkit-case-studies.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index 60843ab9ca..c32f293bfb 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -10,8 +10,8 @@ - [0003-appkit-common-control-bindings.md](Evolutions/0003-appkit-common-control-bindings.md):AppKit 常用控件的类型化绑定。 - [0004-appkit-table-selection-bindings.md](Evolutions/0004-appkit-table-selection-bindings.md):表格与大纲的选中绑定、大纲的展开状态绑定。 - [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 -- [draft-appkit-window-backed-content.md](Evolutions/draft-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`(In Progress)。 -- [draft-appkit-case-studies.md](Evolutions/draft-appkit-case-studies.md):给 AppKit 案例补上弹出与新控件绑定的演示(In Progress)。 +- [0006-appkit-window-backed-content.md](Evolutions/0006-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`。 +- [0007-appkit-case-studies.md](Evolutions/0007-appkit-case-studies.md):给 AppKit 案例补上弹出与新控件绑定的演示。 ## Internal From 9dd9804e2639a99f762af0da9f4e68a89002361a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 20:50:52 +0800 Subject: [PATCH 106/141] docs: propose recommending unowned self in observe, a second batch of AppKit bindings and an animations case study --- Documentations/Evolutions/README.md | 3 + .../draft-appkit-animations-case-study.md | 31 ++++++++ .../draft-appkit-more-control-bindings.md | 77 +++++++++++++++++++ .../Evolutions/draft-observe-unowned-self.md | 56 ++++++++++++++ Documentations/README.md | 3 + 5 files changed, 170 insertions(+) create mode 100644 Documentations/Evolutions/draft-appkit-animations-case-study.md create mode 100644 Documentations/Evolutions/draft-appkit-more-control-bindings.md create mode 100644 Documentations/Evolutions/draft-observe-unowned-self.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index c8b37f533b..4e97a314f6 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -13,3 +13,6 @@ | 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | | 0006 | [把 `ModalContent` 改名为 `WindowBackedContent`](0006-appkit-window-backed-content.md) | Implemented | | 0007 | [给 AppKit 案例补上弹出与新控件绑定的演示](0007-appkit-case-studies.md) | Implemented | +| draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | Accepted | +| draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | Accepted | +| draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-animations-case-study.md b/Documentations/Evolutions/draft-appkit-animations-case-study.md new file mode 100644 index 0000000000..f9bc080380 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-animations-case-study.md @@ -0,0 +1,31 @@ +# Draft - AppKit 动画案例 + +- **状态**: Accepted +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-09 +- **实现分支**: `appkit-more-control-bindings` + +## 摘要 + +AppKit 案例列表里的「Animations」一项一直是注释掉的:UIKit 有这个案例,AppKit 的 `withAppKitAnimation` 和 `UIBinding` 的 `animation(_:)` 却没有能运行的示例。这一批补上 AppKit 版,演示修改模型时界面跟着动画。 + +## 方案 + +新增 `AppKit+AnimationsViewController.swift` 并登记进 `Examples.xcodeproj`,在案例列表的「Observation」一组里取消注释,与 UIKit 版放在同一组。页面内容照 UIKit 版: + +- 一个圆形视图。在页面上点击或拖动时,用 `withAppKitAnimation` 带弹簧动画移到鼠标的位置。 +- 一个 `NSSwitch` 绑到 `$model.isScaled.animation(…)`,切换时圆放大或缩小。 +- 「Cycle colors」按钮依次换几种颜色,每次换色都包在 `withAppKitAnimation` 里。 + +没有询问就采用的假设: + +- 弹簧动画用 SwiftUI 的 `Animation`,要求 macOS 15;更早的系统退回 `.easeInOut`。 +- `NSView` 没有 UIKit 那样的 `transform`,放大缩小改用视图的尺寸实现;具体做法以实现时实测能动起来为准。 +- 只编译 CaseStudies 的 macOS 版,不打开界面去点。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-09 | Created as Draft | AppKit 案例列表里只有动画一项还注释着,用户选定补上 | +| 2026-11-09 | 用户批准,开始实现 | 与另两份提案在同一条分支上实现,做完在本地合进 `main`、不推送 | diff --git a/Documentations/Evolutions/draft-appkit-more-control-bindings.md b/Documentations/Evolutions/draft-appkit-more-control-bindings.md new file mode 100644 index 0000000000..f249eb4c1c --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-more-control-bindings.md @@ -0,0 +1,77 @@ +# Draft - AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中 + +- **状态**: Accepted +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-09 +- **实现分支**: `appkit-more-control-bindings` + +## 摘要 + +[0003](0003-appkit-common-control-bindings.md) 和 [0004](0004-appkit-table-selection-bindings.md) 之后,下游 App 里还剩三类手写的同步: + +- 弹出按钮和分段控件绑定之前,菜单项或分段要先手工生成(PrivateSymbols 3 处);选项随模型变化时,整份菜单要重建(XCOrganizer 的标签菜单)。 +- `NSTextView` 的文本与模型手工同步(XCOrganizer 的检查器)。 +- `NSCollectionView` 的多选与模型手工同步,还要自己防止回写时重复触发(PrivateSymbols 的符号浏览器,约 30 行)。 + +这一批补上对应的绑定,写法沿用现有的 `bind(selection:options:)` 和表格的 `bind(selection:dataSource:)`。 + +## 方案 + +调用点: + +```swift +// Items generated for an existing control, from fixed options +weightPopUpButton.bind(selection: $model.weight, options: SymbolWeight.allCases, title: \.displayName) + +// With an image for each option +visibilityPopUpButton.bind( + selection: $model.visibilityFilter, + options: SymbolVisibilityFilter.allCases, + title: \.displayName, + image: { NSImage(systemSymbolName: $0.iconName, accessibilityDescription: $0.displayName) } +) + +// Options that follow the model: read again whenever what they read changes +tagPopUpButton.bind( + selection: $model.selectedTagID, + options: { [nil] + model.tags.map(\.id) }, + title: { tagID in tagID.flatMap { model.tags[id: $0]?.name } ?? "No Tag" } +) + +textView.bind(text: $model.comment) + +collectionView.bind(selection: $model.selectedSymbolIDs, dataSource: dataSource) // Set +collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) // Symbol.ID? +``` + +1. **按选项生成项**:`NSPopUpButton` 和 `NSSegmentedControl` 加 `bind(selection:options:title:image:)`,`image:` 可以不传。 + - 绑定时按选项生成菜单项或分段,再建立与现有 `bind(selection:options:)` 相同的双向绑定。 + - `options` 传数组时,项只生成一次。传闭包时,闭包与 `title:`、`image:` 在同一次 `observe` 里读取;读到的模型属性一变,就重新生成项并恢复选中。 + - 绑定只管理它生成的项。弹出按钮里 App 另加的项(比如「新建标签…」)留在后面;用户选中这些项时不写回,选中回到绑定的值。 + - 分段控件只管段数、标题和图标;宽度等仍由调用方设置。 + - 现有的便捷构造器 `init(selection:options:title:)` 改为调用新绑定,行为不变。 +2. **文本视图**:`NSTextView.bind(text:)`。 + - 用户每次编辑都写回,与 `NSTextField.bind(text:)` 一致。输入法还在组字(有 marked text)时不写回,组完再写。 + - 模型变化时,只在内容不同时替换文本,选区尽量保留。 + - 不占用 delegate,靠 `NSText.didChangeNotification` 得知编辑。 +3. **集合视图的选中**:`NSCollectionView.bind(selection:dataSource:)`,多选绑 `Set`,单选绑 `ItemIdentifier?`。 + - 另配一个传两个查找函数的版本 `bind(selection:indexPath:itemIdentifier:)`,给不用 diffable data source 的集合视图,写法与表格的 `bind(selection:row:itemIdentifier:)` 对应。 + - 用户的点选、⌘ 或 ⇧ 点选、拖选、全选都写回;模型改变选中时,库自己防止回写。 + - 不占用 delegate。用户改选中时从哪里得知,要先用测试确认:首选用 KVO 观察 `selectionIndexPaths`。头文件没有写明它对用户的操作发通知,这一条不成立时,在决策日志里记下改用的办法。 + - 数据重新加载后,屏幕上的项会丢掉选中外观(PrivateSymbols 现在手工修正),绑定里一并处理。 +4. **示例**:在现有的「选项绑定」和「表格选中」案例里各加上新绑定的演示。 +5. **文档与验证**:每种绑定先写双向测试再实现。DocC 首页「绑定」一组登记 `NSTextView` 和 `NSCollectionView`;`swift-navigation-bindings` skill 的绑定清单补上。Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译库和测试,CaseStudies 的 macOS 版只编译、不点界面。 + +没有询问就采用的假设: + +- 选中值为空的那一项用可选值表达,例如 `options` 里放一个 `nil`,标题写成「No Tag」,不另加参数。 +- 表格和大纲的多选这次不做:下游没有用例;以后照集合视图的 `Set` 版本补上。 +- 文本视图只绑纯文本;富文本、选区和焦点这次不做。 +- 下游 App 改用新绑定不在这一批。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-09 | Created as Draft | 调查依赖这个 fork 的 App 后,用户选定补上随模型变化的选项、文本视图和集合视图多选三种绑定 | +| 2026-11-09 | 用户批准,开始实现 | 照提案做,表格和大纲的多选不在这一批;与另两份提案在同一条分支上实现,做完在本地合进 `main`、不推送 | diff --git a/Documentations/Evolutions/draft-observe-unowned-self.md b/Documentations/Evolutions/draft-observe-unowned-self.md new file mode 100644 index 0000000000..967ea400d8 --- /dev/null +++ b/Documentations/Evolutions/draft-observe-unowned-self.md @@ -0,0 +1,56 @@ +# Draft - 简化 `observe` 闭包里对 `self` 的捕获 + +- **状态**: Accepted +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-09 +- **实现分支**: `appkit-more-control-bindings` + +## 摘要 + +依赖这个 fork 的 4 个 App 里有 55 个 `NSObject.observe` 闭包写了 `[weak self]`:43 个下一行就是 `guard let self else { return }`,11 个写成 `self?.method()`。这些写法只为打破「对象 → 观察令牌 → 闭包 → 对象」的引用环。`NSObject.observe` 把令牌挂在对象自己身上,对象释放时令牌随之释放;之后每次重新运行闭包之前,库都会先检查令牌还在不在,所以闭包不会在对象释放后被调用。因此这里用 `[unowned self]` 是安全的,而且 Swift 允许在 `unowned` 捕获的闭包里省略 `self.`(SE-0269),闭包体不用改。这一批不加新 API:用测试把「对象释放后闭包不再运行」固定为库的保证,并把 `[unowned self]` 写成推荐写法。 + +## 方案 + +调用点: + +```swift +// Before +observe { [weak self] in + guard let self else { return } + titleLabel.stringValue = model.title +} +observe { [weak self] in + self?.applyComment() +} + +// After +observe { [unowned self] in + titleLabel.stringValue = model.title +} +observe { [unowned self] in + applyComment() +} +``` + +1. **测试**:在 AppKitNavigation 的测试里加两条回归测试。闭包用 `[weak self]` 并计数,这样保证一旦失效,测试会失败而不是崩溃。 + - 对象释放后再改模型、转几圈 run loop,闭包一次也没被调用。 + - 令牌被对象以外的东西留住时,对象释放后闭包仍会被调用。这正是推荐写法的前提,文档要写明。 +2. **文档**:AppKitNavigation 的 DocC 首页加一段,说明在 `NSObject.observe` 里推荐写 `[unowned self]` 及其前提;`swift-navigation-bindings` skill 的写法和常见错误同步改。 +3. **示例**:AppKit 案例里的 12 处 `observe { [weak self] in … }` 改成新写法。 + +没有询问就采用的假设: + +- 前提:令牌只由对象自己持有,也就是 `observe` 的默认做法,或存进对象自己的属性。令牌交给别的对象保管时,仍写 `[weak self]`。 +- 只适用于 `NSObject.observe`。全局函数 `observe(_:)` 返回的令牌由调用方保管,不在此列。 +- 不改与上游共用的代码和文档注释(`NSObject+Observe.swift`),说明只写在 fork 自己的文档里。 +- 下游 App 改写法不在这一批。 + +没有采用的写法:新增一个把对象传进闭包的重载。照 KVO 的 `observe(_:options:changeHandler:)` 写成 `observe { owner, transaction in … }`,可以完全不写捕获列表,但闭包里每次访问成员都要加 `owner.`,下游 43 个多行闭包反而更啰嗦。只带一个参数的 `observe { owner in … }` 和现有的 `observe { transaction in … }` 只差参数类型,`observe { _ in … }` 会产生歧义。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-09 | Created as Draft | 下游 4 个 App 的 55 个 `observe` 闭包都写了 `[weak self]`,其中 43 个还要再写一行 `guard let self`;用户选定简化这个写法 | +| 2026-11-09 | 用户选定推荐 `[unowned self]`,不加把对象传进闭包的新重载 | 新重载要在每次访问成员时写 `owner.`,下游多行闭包反而更啰嗦;`[unowned self]` 保留隐式 `self`,闭包体不用改 | +| 2026-11-09 | 用户批准,开始实现 | 与另两份提案在同一条分支 `appkit-more-control-bindings` 上实现,做完在本地合进 `main`、不推送 | diff --git a/Documentations/README.md b/Documentations/README.md index c32f293bfb..8678a3a974 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -12,6 +12,9 @@ - [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 - [0006-appkit-window-backed-content.md](Evolutions/0006-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`。 - [0007-appkit-case-studies.md](Evolutions/0007-appkit-case-studies.md):给 AppKit 案例补上弹出与新控件绑定的演示。 +- [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(Accepted)。 +- [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(Accepted)。 +- [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(Accepted)。 ## Internal From 137f1bc7c97aeb9b115028cdd76e634cd19ddadc Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 20:54:18 +0800 Subject: [PATCH 107/141] docs(appkit): recommend capturing the owner unowned in observe and lock the guarantee with tests --- Documentations/Evolutions/README.md | 6 +- .../draft-appkit-animations-case-study.md | 2 +- .../draft-appkit-more-control-bindings.md | 2 +- .../Evolutions/draft-observe-unowned-self.md | 6 +- Documentations/README.md | 6 +- ...ppKit+BasicsNavigationViewController.swift | 4 +- ...+ConciseEnumNavigationViewController.swift | 4 +- .../AppKit+DismissalViewController.swift | 3 +- .../AppKit+EnumControlsViewController.swift | 4 +- .../AppKit/AppKit+FocusViewController.swift | 4 +- ...Kit+MinimalObservationViewController.swift | 3 +- ...pKit+NSControlBindingsViewController.swift | 4 +- .../AppKit+NestedModalViewController.swift | 3 +- .../AppKit+OptionBindingsViewController.swift | 3 +- ...it+PresentationGalleryViewController.swift | 3 +- .../AppKit+TableSelectionViewController.swift | 3 +- .../AppKit+WiFiSettingsViewController.swift | 3 +- .../Documentation.docc/AppKitNavigation.md | 21 ++++++ .../ObserveLifetimeTests.swift | 75 +++++++++++++++++++ 19 files changed, 119 insertions(+), 40 deletions(-) create mode 100644 Tests/AppKitNavigationTests/ObserveLifetimeTests.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 4e97a314f6..a10ea5ba34 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -13,6 +13,6 @@ | 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | | 0006 | [把 `ModalContent` 改名为 `WindowBackedContent`](0006-appkit-window-backed-content.md) | Implemented | | 0007 | [给 AppKit 案例补上弹出与新控件绑定的演示](0007-appkit-case-studies.md) | Implemented | -| draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | Accepted | -| draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | Accepted | -| draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | Accepted | +| draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | In Progress | +| draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | In Progress | +| draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-animations-case-study.md b/Documentations/Evolutions/draft-appkit-animations-case-study.md index f9bc080380..ee61a59a74 100644 --- a/Documentations/Evolutions/draft-appkit-animations-case-study.md +++ b/Documentations/Evolutions/draft-appkit-animations-case-study.md @@ -1,6 +1,6 @@ # Draft - AppKit 动画案例 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-09 - **最后更新**: 2026-11-09 - **实现分支**: `appkit-more-control-bindings` diff --git a/Documentations/Evolutions/draft-appkit-more-control-bindings.md b/Documentations/Evolutions/draft-appkit-more-control-bindings.md index f249eb4c1c..e143941678 100644 --- a/Documentations/Evolutions/draft-appkit-more-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-more-control-bindings.md @@ -1,6 +1,6 @@ # Draft - AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-09 - **最后更新**: 2026-11-09 - **实现分支**: `appkit-more-control-bindings` diff --git a/Documentations/Evolutions/draft-observe-unowned-self.md b/Documentations/Evolutions/draft-observe-unowned-self.md index 967ea400d8..ef5eed0244 100644 --- a/Documentations/Evolutions/draft-observe-unowned-self.md +++ b/Documentations/Evolutions/draft-observe-unowned-self.md @@ -1,6 +1,6 @@ # Draft - 简化 `observe` 闭包里对 `self` 的捕获 -- **状态**: Accepted +- **状态**: In Progress - **创建日期**: 2026-11-09 - **最后更新**: 2026-11-09 - **实现分支**: `appkit-more-control-bindings` @@ -32,10 +32,10 @@ observe { [unowned self] in } ``` -1. **测试**:在 AppKitNavigation 的测试里加两条回归测试。闭包用 `[weak self]` 并计数,这样保证一旦失效,测试会失败而不是崩溃。 +1. **测试**(已完成):在 AppKitNavigation 的测试里加两条回归测试。闭包用 `[weak self]` 并计数,这样保证一旦失效,测试会失败而不是崩溃。 - 对象释放后再改模型、转几圈 run loop,闭包一次也没被调用。 - 令牌被对象以外的东西留住时,对象释放后闭包仍会被调用。这正是推荐写法的前提,文档要写明。 -2. **文档**:AppKitNavigation 的 DocC 首页加一段,说明在 `NSObject.observe` 里推荐写 `[unowned self]` 及其前提;`swift-navigation-bindings` skill 的写法和常见错误同步改。 +2. **文档**(已完成):AppKitNavigation 的 DocC 首页加一段,说明在 `NSObject.observe` 里推荐写 `[unowned self]` 及其前提;`swift-navigation-bindings` skill 的写法和常见错误同步改。 3. **示例**:AppKit 案例里的 12 处 `observe { [weak self] in … }` 改成新写法。 没有询问就采用的假设: diff --git a/Documentations/README.md b/Documentations/README.md index 8678a3a974..4938c63a4a 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -12,9 +12,9 @@ - [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 - [0006-appkit-window-backed-content.md](Evolutions/0006-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`。 - [0007-appkit-case-studies.md](Evolutions/0007-appkit-case-studies.md):给 AppKit 案例补上弹出与新控件绑定的演示。 -- [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(Accepted)。 -- [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(Accepted)。 -- [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(Accepted)。 +- [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(In Progress)。 +- [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(In Progress)。 +- [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(In Progress)。 ## Internal diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index df3671ec08..cbff0e26d6 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -48,9 +48,7 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) - observe { [weak self] in - guard let self else { return } - + observe { [unowned self] in if let url = model.url { showAlertButton.title = "URL is: \(url)" } else { diff --git a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift index dadfc4e8ad..90f340ccc2 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -53,9 +53,7 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) - observe { [weak self] in - guard let self else { return } - + observe { [unowned self] in showAlertButton.title = "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")" showSheetButton.title = "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")" showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")" diff --git a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift index 4166419f68..a222b29f64 100644 --- a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift @@ -25,8 +25,7 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { logLabel.textColor = .secondaryLabelColor addColumn(of: [presentButton, makeSectionLabel("onDismiss log"), logLabel], to: view) - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") } diff --git a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift index 9ec9f3613c..34031efb38 100644 --- a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift @@ -81,9 +81,7 @@ class EnumControlsViewController: XiblessViewController, AppKitCaseStudy stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) - observe { [weak self] in - guard let self else { return } - + observe { [unowned self] in inStockStack.isHidden = !status.is(\.inStock) outOfStockStack.isHidden = !status.is(\.outOfStock) diff --git a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift index 7623580bbf..a0b779a7fb 100644 --- a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift @@ -90,9 +90,7 @@ class FocusViewController: XiblessViewController, AppKitCaseStudy { .constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -24), ]) - observe { [weak self] in - guard let self else { return } - + observe { [unowned self] in currentFocusLabel.stringValue = "Current focus: \(model.focus?.rawValue ?? "none")" bioTextField.backgroundColor = nil emailTextField.backgroundColor = nil diff --git a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift index f9b51ffca1..0af34c6c56 100644 --- a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift @@ -42,8 +42,7 @@ class MinimalObservationViewController: XiblessViewController, AppKitCas stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), ]) let viewRenderCount = LockIsolated(0) - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in viewRenderCount.withValue { $0 += 1 } if !model.isCountHidden { diff --git a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift index 75fe38967b..8eaa142251 100644 --- a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift @@ -68,9 +68,7 @@ class NSControlBindingsViewController: XiblessViewController, AppKitCaseS colorWell.heightAnchor.constraint(equalToConstant: 50), ]) - observe { [weak self] in - guard let self else { return } - + observe { [unowned self] in contentView.fillColor = model.color let textSelection = model.textSelection.map { diff --git a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift index d35a8bba1f..b67f112171 100644 --- a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift @@ -24,8 +24,7 @@ class NestedModalViewController: XiblessViewController, AppKitCaseStudy let statusLabel = NSTextField(wrappingLabelWithString: "") addColumn(of: [openButton, statusLabel], to: view) - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in statusLabel.stringValue = """ Settings window: \(model.isSettingsPresented ? "open" : "closed") Confirmation alert: \(model.resetConfirmation != nil ? "open" : "closed") diff --git a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift index 0dedc08540..f1ba9e9edb 100644 --- a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift @@ -68,8 +68,7 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu to: view ) - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in let styles = [ model.isBold ? "bold" : nil, model.isItalic ? "italic" : nil, diff --git a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift index 0551163cb1..d04b79926f 100644 --- a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift @@ -68,8 +68,7 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa to: view ) - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") } diff --git a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift index 8d885ed187..74be82521b 100644 --- a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift @@ -98,8 +98,7 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu to: view ) - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in statusLabel.stringValue = """ Table selection: \(model.selectedPlanet ?? "none") Outline selection: \(model.selectedPantryItem ?? "none") diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift index 9f72cd5b61..6539d5deff 100644 --- a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -88,8 +88,7 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas } } - observe { [weak self] in - guard let self else { return } + observe { [unowned self] in dataSource.apply( NSDiffableDataSourceSnapshot(model: model), animatingDifferences: true diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 9b76ae5a3f..3710d6d17f 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -10,6 +10,27 @@ popovers follow optional state: they are presented when it gains a value, dismis `nil`, and write `nil` back when the user dismisses them. Their `onDismiss` closures run once for each presentation, after it has left the screen, however it ended. +### Observing from a view or view controller + +`observe` called on an object keeps its observation for as long as the object lives, and never +calls the closure again once the object is gone. So the closure can capture the object `unowned`, +which keeps `self` implicit inside it: + +```swift +override func viewDidLoad() { + super.viewDidLoad() + + observe { [unowned self] in + titleLabel.stringValue = model.title + saveButton.isEnabled = model.canSave + } +} +``` + +This holds as long as only the object keeps the token that `observe` returns, which is the case +when you ignore the token or store it in one of the object's own properties. If you hand the token +to something that can outlive the object, capture the object `weak` instead. + ## Additional Resources - [GitHub Repo](https://github.com/pointfreeco/swift-navigation) diff --git a/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift b/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift new file mode 100644 index 0000000000..c9ba299748 --- /dev/null +++ b/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift @@ -0,0 +1,75 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// `observe` called on an object keeps its observation for as long as the object lives, and never + /// calls the closure again once the object is gone. That is what makes capturing the object + /// `unowned` in the closure safe, as long as nothing else keeps the token alive. + /// + /// The closures here capture the owner weakly and count their calls, so that a broken guarantee + /// fails the test instead of crashing the test process. + final class ObserveLifetimeTests: XCTestCase { + @MainActor + func testObservationNeverCallsItsClosureOnceTheObjectIsGone() { + let model = CounterModel() + let recorder = CallRecorder() + var owner: Owner? = Owner() + owner?.observe { [weak owner] in + _ = model.count + recorder.record(isOwnerAlive: owner != nil) + } + weak var releasedOwner = owner + + owner = nil + XCTAssertNil(releasedOwner, "The observation should not keep its object alive.") + model.count += 1 + spinRunLoop(for: 0.1) + + XCTAssertEqual(recorder.callCount, 1, "Only the initial call should have happened.") + XCTAssertEqual(recorder.callsAfterOwnerWasGone, 0) + } + + /// The exception the documentation spells out: a token kept elsewhere keeps the observation, + /// and its closure, going after the object is gone. + @MainActor + func testTokenKeptElsewhereKeepsCallingTheClosureAfterTheObjectIsGone() { + let model = CounterModel() + let recorder = CallRecorder() + var owner: Owner? = Owner() + let token = owner?.observe { [weak owner] in + _ = model.count + recorder.record(isOwnerAlive: owner != nil) + } + + owner = nil + model.count += 1 + spinRunLoop(for: 0.1) + + XCTAssertEqual(recorder.callsAfterOwnerWasGone, 1) + withExtendedLifetime(token) {} + } + } + + @MainActor + private final class Owner: NSObject {} + + @MainActor + @Observable + private final class CounterModel { + var count = 0 + } + + @MainActor + private final class CallRecorder { + private(set) var callCount = 0 + private(set) var callsAfterOwnerWasGone = 0 + + func record(isOwnerAlive: Bool) { + callCount += 1 + if !isOwnerAlive { + callsAfterOwnerWasGone += 1 + } + } + } +#endif From 52f41ff1afac4fd1a15c7167cd606ee948ef2014 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:12:40 +0800 Subject: [PATCH 108/141] feat(appkit): make items for bound options that follow the model, and bind text views --- .../draft-appkit-more-control-bindings.md | 8 +- .../Bindings/NSPopUpButton.swift | 238 +++++++++++++++- .../Bindings/NSSegmentedControl.swift | 120 +++++++- .../Bindings/NSTextView.swift | 65 +++++ .../Bindings/TargetActionProtocol.swift | 13 +- .../Internal/OptionIndex.swift | 26 +- .../CommonControlBindingTests.swift | 9 +- .../OptionItemBindingTests.swift | 269 ++++++++++++++++++ .../TextViewBindingTests.swift | 72 +++++ 9 files changed, 790 insertions(+), 30 deletions(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSTextView.swift create mode 100644 Tests/AppKitNavigationTests/OptionItemBindingTests.swift create mode 100644 Tests/AppKitNavigationTests/TextViewBindingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-more-control-bindings.md b/Documentations/Evolutions/draft-appkit-more-control-bindings.md index e143941678..fa0fc08949 100644 --- a/Documentations/Evolutions/draft-appkit-more-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-more-control-bindings.md @@ -44,13 +44,13 @@ collectionView.bind(selection: $model.selectedSymbolIDs, dataSource: dataSource) collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) // Symbol.ID? ``` -1. **按选项生成项**:`NSPopUpButton` 和 `NSSegmentedControl` 加 `bind(selection:options:title:image:)`,`image:` 可以不传。 +1. **按选项生成项**(已完成):`NSPopUpButton` 和 `NSSegmentedControl` 加 `bind(selection:options:title:image:)`,`image:` 可以不传。 - 绑定时按选项生成菜单项或分段,再建立与现有 `bind(selection:options:)` 相同的双向绑定。 - `options` 传数组时,项只生成一次。传闭包时,闭包与 `title:`、`image:` 在同一次 `observe` 里读取;读到的模型属性一变,就重新生成项并恢复选中。 - 绑定只管理它生成的项。弹出按钮里 App 另加的项(比如「新建标签…」)留在后面;用户选中这些项时不写回,选中回到绑定的值。 - 分段控件只管段数、标题和图标;宽度等仍由调用方设置。 - 现有的便捷构造器 `init(selection:options:title:)` 改为调用新绑定,行为不变。 -2. **文本视图**:`NSTextView.bind(text:)`。 +2. **文本视图**(已完成):`NSTextView.bind(text:)`。 - 用户每次编辑都写回,与 `NSTextField.bind(text:)` 一致。输入法还在组字(有 marked text)时不写回,组完再写。 - 模型变化时,只在内容不同时替换文本,选区尽量保留。 - 不占用 delegate,靠 `NSText.didChangeNotification` 得知编辑。 @@ -75,3 +75,7 @@ collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) |------|------|------| | 2026-11-09 | Created as Draft | 调查依赖这个 fork 的 App 后,用户选定补上随模型变化的选项、文本视图和集合视图多选三种绑定 | | 2026-11-09 | 用户批准,开始实现 | 照提案做,表格和大纲的多选不在这一批;与另两份提案在同一条分支上实现,做完在本地合进 `main`、不推送 | +| 2026-11-09 | 便捷构造器也改由新绑定生成项;用户选中 App 自己加的项时,不再报问题,而是不写回、选中回到绑定的值 | 两条路径生成的项由同一套代码管理,行为应当一致。自己搭好菜单再调用 `bind(selection:options:)` 的写法仍按位置对应,选中选项之外的项照旧报问题,测试改为覆盖这种写法 | +| 2026-11-09 | 两个便捷构造器各加一个可省的 `image:` 参数 | 与新绑定的参数一致;不传时与原来相同 | +| 2026-11-09 | 带自身动作的菜单项(如「新建标签…」)靠菜单的 `didSendActionNotification` 得知被选中 | 这类项发送自己的动作,不发弹出按钮的动作,绑定的 target/action 收不到 | +| 2026-11-09 | `NSTextView` 另加 `unbindText()` | 与 `unbindIsCollapsed()`、`unbindSelection()` 一致;文本视图不是控件,用不了 `unbind(_:)` | diff --git a/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift b/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift index 9fd7807bde..1478e5493f 100644 --- a/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift +++ b/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift @@ -11,12 +11,16 @@ extension NSPopUpButton { /// ) /// ``` /// + /// See ``AppKit/NSPopUpButton/bind(selection:options:title:image:fileID:filePath:line:column:)-(_,[Value],_,_,_,_,_,_)`` + /// for how the items and the binding stay in step. + /// /// - Parameters: /// - frame: The frame rectangle for the view, measured in points. /// - selection: The binding to read from for the selected option, and write to when the /// user chooses another one. /// - options: The options, in the order of their items. /// - title: The title of the item for an option. + /// - image: The image of the item for an option, if items show images. /// - fileID: The source `#fileID` associated with the binding. /// - filePath: The source `#filePath` associated with the binding. /// - line: The source `#line` associated with the binding. @@ -25,21 +29,19 @@ extension NSPopUpButton { frame: CGRect = .zero, selection: UIBinding, options: [Value], - title: (Value) -> String, + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, fileID: StaticString = #fileID, filePath: StaticString = #filePath, line: UInt = #line, column: UInt = #column ) { self.init(frame: frame, pullsDown: false) - // NB: Added through the menu, since 'addItem(withTitle:)' first removes an item that has - // the same title, which would leave two options sharing one item. - for option in options { - menu?.addItem(withTitle: title(option), action: nil, keyEquivalent: "") - } bind( selection: selection, options: options, + title: title, + image: image, fileID: fileID, filePath: filePath, line: line, @@ -50,10 +52,11 @@ extension NSPopUpButton { /// Establishes a two-way connection between a binding and the item the pop-up button has /// selected, the item at the same position as the bound value among `options`. /// - /// The pop-up button's items must match the options one for one, in order, which - /// ``AppKit/NSPopUpButton/init(frame:selection:options:title:fileID:filePath:line:column:)`` - /// takes care of. A value that is not one of the options selects no item, and choosing an - /// item past the last option leaves the binding alone; both are reported as issues. + /// The pop-up button's items must match the options one for one, in order. To have the items + /// made for you, pass a `title`, as in + /// ``AppKit/NSPopUpButton/bind(selection:options:title:image:fileID:filePath:line:column:)-(_,[Value],_,_,_,_,_,_)``. + /// A value that is not one of the options selects no item, and choosing an item past the last + /// option leaves the binding alone; both are reported as issues. /// /// - Parameters: /// - selection: The binding to read from for the selected option, and write to when the @@ -93,11 +96,226 @@ extension NSPopUpButton { } } + /// Makes an item for each option at the top of the pop-up button's menu, and establishes a + /// two-way connection between a binding and the chosen option. + /// + /// ```swift + /// visibilityPopUpButton.bind( + /// selection: $model.visibilityFilter, + /// options: VisibilityFilter.allCases, + /// title: \.displayName, + /// image: { NSImage(systemSymbolName: $0.iconName, accessibilityDescription: $0.displayName) } + /// ) + /// ``` + /// + /// The binding manages only the items it makes. Items the app adds below them, such as a + /// "New Tag…" item with an action of its own, stay where they are: choosing one leaves the + /// binding alone, and the pop-up button shows the bound option again afterwards. Binding the + /// pop-up button again reuses the items made before. + /// + /// A value that is not one of the options selects no item, and is reported as an issue. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user chooses another one. + /// - options: The options, in the order of their items. + /// - title: The title of the item for an option. + /// - image: The image of the item for an option, if items show images. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: [Value], + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + bind( + selection: selection, + options: { options }, + title: title, + image: image, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Makes an item for each of the options a closure returns, and keeps the items and the chosen + /// option in step as the options change. + /// + /// The options, titles and images are read in an observation, so the items follow whatever + /// those closures read from an observable model: + /// + /// ```swift + /// tagPopUpButton.bind( + /// selection: $model.selectedTagID, + /// options: { [nil] + model.tags.map(\.id) }, + /// title: { tagID in tagID.flatMap { model.tags[id: $0]?.name } ?? "No Tag" } + /// ) + /// ``` + /// + /// When the number of options changes, items are added or removed at the end of the ones the + /// binding made; otherwise the existing items are retitled in place, so a menu that is open + /// keeps its items. Everything else works as in + /// ``AppKit/NSPopUpButton/bind(selection:options:title:image:fileID:filePath:line:column:)-(_,[Value],_,_,_,_,_,_)``. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user chooses another one. + /// - options: A closure that returns the options, in the order of their items. + /// - title: The title of the item for an option. + /// - image: The image of the item for an option, if items show images. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: @escaping () -> [Value], + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + let index = selection.optionIndex( + among: options, fileID: fileID, filePath: filePath, line: line, column: column + ) + // NB: The key path only files the binding away, so that binding the pop-up button again + // replaces it. Items are matched by identity, not position, since the app may add + // items of its own. + let bindingToken = establishBinding( + index, + to: \NSPopUpButton.appKitNavigationIndexOfSelectedItem, + of: self, + through: createActionProxyIfNeeded(), + observesKeyPath: false, + valueAfterAction: { popUpButton in + popUpButton.indexOfChosenOption(restoringOptionAt: index.wrappedValue) + } + ) { popUpButton, optionIndex, _ in + let currentOptions = options() + popUpButton.updateOptionItems( + titles: currentOptions.map(title), + images: image.map { image in currentOptions.map(image) } + ) + if optionIndex == -1 { + reportIssue( + """ + A pop-up button's selection ('\(selection.wrappedValue)') is not one of its \ + options, so no item is selected. + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + popUpButton.selectOptionItem(at: optionIndex) + } + guard let menu else { return bindingToken } + // NB: An item with an action of its own sends that action instead of the pop-up button's, + // so the binding hears of it only through the menu. + let menuObserver = NotificationObserver( + name: NSMenu.didSendActionNotification, object: menu + ) { [weak self] notification in + guard + let self, + let chosenItem = notification.userInfo?["MenuItem"] as? NSMenuItem, + !appKitNavigationOptionItems.contains(where: { $0 === chosenItem }) + else { return } + selectOptionItem(at: index.wrappedValue) + } + let token = ObserveToken { + bindingToken.cancel() + MainActor._assumeIsolated { + menuObserver.invalidate() + } + } + observationTokens[\NSPopUpButton.appKitNavigationIndexOfSelectedItem] = token + return token + } + // NB: Exposed to Objective-C so the binding can observe it, and named after the library so // that it can never replace a method AppKit has, or adds later, under the same selector. @objc var appKitNavigationIndexOfSelectedItem: Int { set { selectItem(at: newValue) } get { indexOfSelectedItem } } + + /// The items made for the options, in the order of the options. + fileprivate var appKitNavigationOptionItems: [NSMenuItem] { + get { + objc_getAssociatedObject(self, optionItemsKey) as? [NSMenuItem] ?? [] + } + set { + objc_setAssociatedObject(self, optionItemsKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// Makes the items for the options match their titles and images. Items are added or removed + /// only when the number of options changes, at the end of the items made before. + fileprivate func updateOptionItems(titles: [String], images: [NSImage?]?) { + guard let menu else { return } + var optionItems = appKitNavigationOptionItems.filter { $0.menu === menu } + while optionItems.count > titles.count { + menu.removeItem(optionItems.removeLast()) + } + // NB: Inserted through the menu, since 'insertItem(withTitle:at:)' first removes an item + // that has the same title, which would leave two options sharing one item. + var insertionIndex = optionItems.last.map { menu.index(of: $0) + 1 } ?? 0 + while optionItems.count < titles.count { + let optionItem = NSMenuItem(title: "", action: nil, keyEquivalent: "") + menu.insertItem(optionItem, at: insertionIndex) + insertionIndex += 1 + optionItems.append(optionItem) + } + for (position, optionItem) in optionItems.enumerated() { + optionItem.title = titles[position] + optionItem.image = images?[position] + } + appKitNavigationOptionItems = optionItems + } + + /// Selects the item for the option at a position, or no item for a position that matches none. + fileprivate func selectOptionItem(at optionIndex: Int) { + let optionItems = appKitNavigationOptionItems + guard optionItems.indices.contains(optionIndex) else { + // NB: Not 'select(nil)' followed by 'synchronizeTitleAndSelectedItem()', which + // selects the first item again. + selectItem(at: -1) + return + } + select(optionItems[optionIndex]) + // NB: Shows the item's title again when it was retitled in place. + synchronizeTitleAndSelectedItem() + } + + /// The position among the options of the item the user chose. For an item the app added, shows + /// the bound option again and returns `nil`, so that the binding is left alone. + fileprivate func indexOfChosenOption(restoringOptionAt boundIndex: Int) -> Int? { + if let selectedItem, + let position = appKitNavigationOptionItems.firstIndex(where: { $0 === selectedItem }) + { + return position + } + selectOptionItem(at: boundIndex) + return nil + } } + +@MainActor +private let optionItemsKey = malloc(1)! #endif diff --git a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift index cde64465e7..ff7d0ca039 100755 --- a/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -72,6 +72,7 @@ extension NSSegmentedControl { /// user selects another one. /// - options: The options, in the order of their segments. /// - title: The label of the segment for an option. + /// - image: The image of the segment for an option, if segments show images. /// - fileID: The source `#fileID` associated with the binding. /// - filePath: The source `#filePath` associated with the binding. /// - line: The source `#line` associated with the binding. @@ -80,21 +81,71 @@ extension NSSegmentedControl { frame: CGRect = .zero, selection: UIBinding, options: [Value], - title: (Value) -> String, + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, fileID: StaticString = #fileID, filePath: StaticString = #filePath, line: UInt = #line, column: UInt = #column ) { self.init(frame: frame) - segmentCount = options.count - for (segment, option) in options.enumerated() { - setLabel(title(option), forSegment: segment) - } trackingMode = .selectOne bind( selection: selection, options: options, + title: title, + image: image, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + + /// Makes a segment for each option and establishes a two-way connection between a binding and + /// the selected one. + /// + /// ```swift + /// displayModeControl.bind( + /// selection: $model.displayMode, + /// options: DisplayMode.allCases, + /// title: { _ in "" }, + /// image: { NSImage(systemSymbolName: $0.iconName, accessibilityDescription: $0.displayName) } + /// ) + /// ``` + /// + /// The binding sets the number of segments and each segment's label and image; anything else + /// about the segments, such as their widths, is yours to set. Return an empty title to show + /// only the image. A value that is not one of the options selects no segment, and is reported + /// as an issue. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user selects another one. + /// - options: The options, in the order of their segments. + /// - title: The label of the segment for an option. + /// - image: The image of the segment for an option, if segments show images. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: [Value], + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + bind( + selection: selection, + options: { options }, + title: title, + image: image, fileID: fileID, filePath: filePath, line: line, @@ -102,13 +153,70 @@ extension NSSegmentedControl { ) } + /// Makes a segment for each of the options a closure returns, and keeps the segments and the + /// selected option in step as the options change. + /// + /// The options, labels and images are read in an observation, so the segments follow whatever + /// those closures read from an observable model. Everything else works as in the version that + /// takes an array of options. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected option, and write to when the + /// user selects another one. + /// - options: A closure that returns the options, in the order of their segments. + /// - title: The label of the segment for an option. + /// - image: The image of the segment for an option, if segments show images. + /// - fileID: The source `#fileID` associated with the binding. + /// - filePath: The source `#filePath` associated with the binding. + /// - line: The source `#line` associated with the binding. + /// - column: The source `#column` associated with the binding. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + options: @escaping () -> [Value], + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) -> ObserveToken { + let index = selection.optionIndex( + among: options, fileID: fileID, filePath: filePath, line: line, column: column + ) + return bind(index, to: \.selectedSegment) { segmentedControl, index, _ in + let currentOptions = options() + if segmentedControl.segmentCount != currentOptions.count { + segmentedControl.segmentCount = currentOptions.count + } + for (segment, option) in currentOptions.enumerated() { + segmentedControl.setLabel(title(option), forSegment: segment) + segmentedControl.setImage(image?(option), forSegment: segment) + } + if index == -1 { + reportIssue( + """ + A segmented control's selection ('\(selection.wrappedValue)') is not one of \ + its options, so no segment is selected. + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + } + segmentedControl.selectedSegment = index + } + } + /// Establishes a two-way connection between a binding and the selected segment, the segment /// at the same position as the bound value among `options`. /// /// Unlike ``AppKit/NSSegmentedControl/bind(selectedSegment:fileID:filePath:line:column:)``, /// the value need not be raw-representable: any equatable value works. The segments must /// match the options one for one, in order, which - /// ``AppKit/NSSegmentedControl/init(frame:selection:options:title:fileID:filePath:line:column:)`` + /// ``AppKit/NSSegmentedControl/init(frame:selection:options:title:image:fileID:filePath:line:column:)`` /// takes care of. A value that is not one of the options selects no segment, and selecting a /// segment past the last option leaves the binding alone; both are reported as issues. /// diff --git a/Sources/AppKitNavigation/Bindings/NSTextView.swift b/Sources/AppKitNavigation/Bindings/NSTextView.swift new file mode 100644 index 0000000000..6f60a88cbc --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTextView.swift @@ -0,0 +1,65 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +extension NSTextView { + /// Establishes a two-way connection between a binding and the text view's text. + /// + /// ```swift + /// commentTextView.bind(text: $model.comment) + /// ``` + /// + /// The text view shows the bound text, and writes each of the user's edits back, as + /// ``AppKit/NSTextField/bind(text:)`` does for a text field. While an input method is still + /// composing text, nothing is written back until the composition ends. + /// + /// A change to the binding replaces the text only when it differs from what the text view + /// shows, and keeps the selection where it can. Changes that arrive while an input method is + /// composing are skipped, so that the composition survives; the user's next edit writes the + /// text view's text back. + /// + /// The binding learns of edits from notifications, and leaves the text view's delegate alone. + /// + /// - Parameter text: The binding to read from for the text, and write to when the user edits + /// it. + /// - Returns: A cancel token. + @discardableResult + public func bind(text: UIBinding) -> ObserveToken { + let bindingToken = establishBinding( + text, + to: \NSTextView.string, + of: self, + through: nil, + observesKeyPath: false + ) { textView, newText, _ in + guard textView.string != newText, !textView.hasMarkedText() else { return } + let selectedRanges = textView.selectedRanges + textView.string = newText + let length = (newText as NSString).length + textView.selectedRanges = selectedRanges.map { selectedRange in + let range = selectedRange.rangeValue + let location = min(range.location, length) + return NSValue(range: NSRange(location: location, length: min(range.length, length - location))) + } + } + let editObserver = NotificationObserver( + name: NSText.didChangeNotification, object: self + ) { [weak self] _ in + guard let self, !hasMarkedText(), text.wrappedValue != string else { return } + text.wrappedValue = string + } + let token = ObserveToken { + bindingToken.cancel() + MainActor._assumeIsolated { + editObserver.invalidate() + } + } + observationTokens[\NSTextView.string] = token + return token + } + + /// Removes the binding established with ``AppKit/NSTextView/bind(text:)``. + public func unbindText() { + removeBinding(to: \NSTextView.string) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index a1a9156bed..86472d600d 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -94,8 +94,8 @@ extension TargetActionProtocol { /// - actionProxy: The proxy that runs the object's target-action pair, or `nil` if it has none. /// - observesKeyPath: Whether changes that key-value observation of the property reports are /// written back too. -/// - valueAfterAction: The value to write back when the object sends its action. Defaults to -/// the property's value. +/// - valueAfterAction: The value to write back when the object sends its action, or `nil` to +/// leave the binding alone. Defaults to the property's value. /// - set: Applies a new value of the binding to the object. @MainActor func establishBinding( @@ -104,13 +104,18 @@ func establishBinding( of owner: Owner, through actionProxy: TargetActionProxy?, observesKeyPath: Bool = true, - valueAfterAction: ((_ owner: Owner) -> Value)? = nil, + valueAfterAction: ((_ owner: Owner) -> Value?)? = nil, set: @escaping (_ owner: Owner, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObserveToken { owner.removeBinding(to: keyPath) let actionID = actionProxy?.addBindingAction { [weak owner] _ in guard let owner else { return } - binding.wrappedValue = valueAfterAction?(owner) ?? owner[keyPath: keyPath] + if let valueAfterAction { + guard let value = valueAfterAction(owner) else { return } + binding.wrappedValue = value + } else { + binding.wrappedValue = owner[keyPath: keyPath] + } } let isSetting = LockIsolated(false) diff --git a/Sources/AppKitNavigation/Internal/OptionIndex.swift b/Sources/AppKitNavigation/Internal/OptionIndex.swift index 58f333dee1..7cece32f24 100644 --- a/Sources/AppKitNavigation/Internal/OptionIndex.swift +++ b/Sources/AppKitNavigation/Internal/OptionIndex.swift @@ -11,6 +11,21 @@ extension UIBinding where Value: Equatable { filePath: StaticString, line: UInt, column: UInt + ) -> UIBinding { + optionIndex(among: { options }, fileID: fileID, filePath: filePath, line: line, column: column) + } + + /// A binding to the position of this binding's value among options that are read again each + /// time. + /// + /// Reading the position reads the options, so an observation that reads the position also + /// tracks whatever the options read. + func optionIndex( + among options: @escaping () -> [Value], + fileID: StaticString, + filePath: StaticString, + line: UInt, + column: UInt ) -> UIBinding { self[ indexAmong: KeyPathArgument(options), @@ -24,20 +39,21 @@ extension UIBinding where Value: Equatable { extension Equatable { fileprivate subscript( - indexAmong options: KeyPathArgument<[Self]>, + indexAmong options: KeyPathArgument<() -> [Self]>, fileID fileID: HashableStaticString, filePath filePath: HashableStaticString, line line: UInt, column column: UInt ) -> Int { - get { options.value.firstIndex(of: self) ?? -1 } + get { options.value().firstIndex(of: self) ?? -1 } set { - guard options.value.indices.contains(newValue) + let currentOptions = options.value() + guard currentOptions.indices.contains(newValue) else { reportIssue( """ A selection binding was given position \(newValue), which matches none of its \ - \(options.value.count) options. + \(currentOptions.count) options. """, fileID: fileID.rawValue, filePath: filePath.rawValue, @@ -46,7 +62,7 @@ extension Equatable { ) return } - self = options.value[newValue] + self = currentOptions[newValue] } } } diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift index c56783c707..d40534a258 100644 --- a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -120,11 +120,14 @@ #expect(popUpButton?.indexOfSelectedItem == -1) } - @Test("choosing an item that is not one of the options is reported and changes nothing") + /// Items the binding made itself are told apart from the app's own; see + /// `OptionItemBindingTests`. A menu the app built has only positions to go by. + @Test("choosing an item past the options of a menu the app built is reported and changes nothing") func choosingAnItemOutsideTheOptionsIsReported() { @UIBinding var weight = Weight.regular - let popUpButton = NSPopUpButton(selection: $weight, options: Weight.allCases, title: \.title) - popUpButton.menu?.addItem(withTitle: "Custom…", action: nil, keyEquivalent: "") + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + popUpButton.addItems(withTitles: ["Light", "Regular", "Bold", "Custom…"]) + popUpButton.bind(selection: $weight, options: Weight.allCases) popUpButton.selectItem(at: 3) withKnownIssue { diff --git a/Tests/AppKitNavigationTests/OptionItemBindingTests.swift b/Tests/AppKitNavigationTests/OptionItemBindingTests.swift new file mode 100644 index 0000000000..b088fa3e5a --- /dev/null +++ b/Tests/AppKitNavigationTests/OptionItemBindingTests.swift @@ -0,0 +1,269 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// Pop-up buttons and segmented controls make their items from the options they are bound to, + /// keep those items in step with options that change, and leave items the app adds alone. + @MainActor + @Suite struct OptionItemBindingTests { + init() { + // NB: A control sends its action through 'NSApplication.sendAction(_:to:from:)', which + // silently does nothing when no application object exists yet. + _ = NSApplication.shared + } + + // MARK: - Pop-up buttons + + @Test("binding an existing pop-up button makes an item for each option") + func bindingMakesAnItemForEachOption() { + @UIBinding var filter = Filter.publicOnly + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + + popUpButton.bind( + selection: $filter, options: Filter.allCases, title: \.title, image: { $0.image } + ) + + #expect(popUpButton.itemTitles == ["All", "Public", "Private"]) + #expect(popUpButton.itemArray.map(\.image) == Filter.allCases.map(\.image)) + #expect(popUpButton.indexOfSelectedItem == 1) + + popUpButton.selectItem(at: 2) + sendAction(of: popUpButton) + #expect(filter == .privateOnly) + } + + @Test("a pop-up button's items follow options that change with the model") + func itemsFollowOptionsThatChange() async { + @UIBindable var model = TagModel(tags: ["Red", "Blue"], selectedTag: "Blue") + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + popUpButton.bind( + selection: $model.selectedTag, + options: { [nil] + model.tags }, + title: { $0 ?? "No Tag" } + ) + #expect(popUpButton.itemTitles == ["No Tag", "Red", "Blue"]) + + model.tags.insert("Green", at: 0) + await Task.yield() + + #expect(popUpButton.itemTitles == ["No Tag", "Green", "Red", "Blue"]) + #expect(popUpButton.titleOfSelectedItem == "Blue") + } + + @Test("an item whose title changes with the model is retitled in place") + func itemsAreRetitledInPlace() async { + @UIBindable var model = TagModel(tags: ["Red"], selectedTag: "Red") + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + popUpButton.bind( + selection: $model.selectedTag, + options: { model.tags.map(Optional.some) }, + title: { tag in "\(tag ?? "") (\(model.usageCount))" } + ) + let item = popUpButton.itemArray.first + + model.usageCount = 3 + await Task.yield() + + #expect(popUpButton.itemTitles == ["Red (3)"]) + #expect(popUpButton.itemArray.first === item) + } + + @Test("items the app adds stay below the options as the options change") + func appItemsStayBelowTheOptions() async { + @UIBindable var model = TagModel(tags: ["Red"], selectedTag: "Red") + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + popUpButton.bind( + selection: $model.selectedTag, + options: { model.tags.map(Optional.some) }, + title: { $0 ?? "" } + ) + let newTagItem = NSMenuItem(title: "New Tag…", action: nil, keyEquivalent: "") + popUpButton.menu?.addItem(newTagItem) + + model.tags.append("Blue") + await Task.yield() + + #expect(popUpButton.itemTitles == ["Red", "Blue", "New Tag…"]) + #expect(popUpButton.itemArray.last === newTagItem) + } + + @Test("choosing an item the app added leaves the binding alone and shows the option again") + func choosingAnAppItemLeavesTheBindingAlone() { + @UIBindable var model = TagModel(tags: ["Red", "Blue"], selectedTag: "Blue") + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + popUpButton.bind( + selection: $model.selectedTag, + options: { model.tags.map(Optional.some) }, + title: { $0 ?? "" } + ) + popUpButton.menu?.addItem(withTitle: "Custom…", action: nil, keyEquivalent: "") + + popUpButton.selectItem(withTitle: "Custom…") + sendAction(of: popUpButton) + + #expect(model.selectedTag == "Blue") + #expect(popUpButton.titleOfSelectedItem == "Blue") + } + + /// An item with an action of its own sends that action instead of the pop-up button's. + @Test("choosing an item with an action of its own runs it and shows the option again") + func choosingAnItemWithItsOwnActionShowsTheOptionAgain() { + @UIBindable var model = TagModel(tags: ["Red", "Blue"], selectedTag: "Blue") + let popUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + popUpButton.bind( + selection: $model.selectedTag, + options: { model.tags.map(Optional.some) }, + title: { $0 ?? "" } + ) + let recorder = ActionRecorder() + let newTagItem = NSMenuItem( + title: "New Tag…", action: #selector(ActionRecorder.record(_:)), keyEquivalent: "" + ) + newTagItem.target = recorder + popUpButton.menu?.addItem(newTagItem) + + let newTagIndex = popUpButton.index(of: newTagItem) + popUpButton.selectItem(at: newTagIndex) + popUpButton.menu?.performActionForItem(at: newTagIndex) + + #expect(recorder.callCount == 1) + #expect(model.selectedTag == "Blue") + #expect(popUpButton.titleOfSelectedItem == "Blue") + } + + @Test("binding a pop-up button again reuses the items it made") + func bindingAgainReusesTheItems() { + @UIBinding var filter = Filter.privateOnly + let popUpButton = NSPopUpButton(selection: $filter, options: Filter.allCases, title: \.title) + + popUpButton.bind(selection: $filter, options: [.all, .privateOnly], title: \.title) + + #expect(popUpButton.itemTitles == ["All", "Private"]) + #expect(popUpButton.titleOfSelectedItem == "Private") + } + + // MARK: - Segmented controls + + @Test("binding a segmented control makes a segment for each option, as the options change") + func segmentedControlMakesASegmentForEachOption() async { + @UIBindable var model = LayoutModel(layouts: [.icons, .list], layout: .list) + let segmentedControl = NSSegmentedControl() + segmentedControl.bind( + selection: $model.layout, + options: { model.layouts }, + title: \.title, + image: { $0.image } + ) + #expect(segmentedControl.segmentCount == 2) + #expect(segmentedControl.label(forSegment: 1) == "List") + #expect(segmentedControl.image(forSegment: 0) === Layout.icons.image) + #expect(segmentedControl.selectedSegment == 1) + + model.layouts.append(.columns) + await Task.yield() + #expect(segmentedControl.segmentCount == 3) + #expect(segmentedControl.label(forSegment: 2) == "Columns") + #expect(segmentedControl.selectedSegment == 1) + + segmentedControl.selectedSegment = 2 + sendAction(of: segmentedControl) + #expect(model.layout == .columns) + } + + // MARK: - Support + + /// What a control does once the user has changed its value. + private func sendAction(of control: NSControl) { + control.sendAction(control.action, to: control.target) + } + } + + private enum Filter: CaseIterable { + case all + case publicOnly + case privateOnly + + var title: String { + switch self { + case .all: "All" + case .publicOnly: "Public" + case .privateOnly: "Private" + } + } + + @MainActor + var image: NSImage { + switch self { + case .all: Self.allImage + case .publicOnly: Self.publicImage + case .privateOnly: Self.privateImage + } + } + + @MainActor private static let allImage = NSImage(size: NSSize(width: 1, height: 1)) + @MainActor private static let publicImage = NSImage(size: NSSize(width: 2, height: 2)) + @MainActor private static let privateImage = NSImage(size: NSSize(width: 3, height: 3)) + } + + private enum Layout: Equatable { + case icons + case list + case columns + + var title: String { + switch self { + case .icons: "Icons" + case .list: "List" + case .columns: "Columns" + } + } + + @MainActor + var image: NSImage { + switch self { + case .icons: Self.iconsImage + case .list: Self.listImage + case .columns: Self.columnsImage + } + } + + @MainActor private static let iconsImage = NSImage(size: NSSize(width: 1, height: 1)) + @MainActor private static let listImage = NSImage(size: NSSize(width: 2, height: 2)) + @MainActor private static let columnsImage = NSImage(size: NSSize(width: 3, height: 3)) + } + + @MainActor + @Observable + private final class TagModel { + var tags: [String] + var selectedTag: String? + var usageCount = 0 + + init(tags: [String], selectedTag: String?) { + self.tags = tags + self.selectedTag = selectedTag + } + } + + @MainActor + @Observable + private final class LayoutModel { + var layouts: [Layout] + var layout: Layout + + init(layouts: [Layout], layout: Layout) { + self.layouts = layouts + self.layout = layout + } + } + + @MainActor + private final class ActionRecorder: NSObject { + private(set) var callCount = 0 + + @objc func record(_ sender: Any?) { + callCount += 1 + } + } +#endif diff --git a/Tests/AppKitNavigationTests/TextViewBindingTests.swift b/Tests/AppKitNavigationTests/TextViewBindingTests.swift new file mode 100644 index 0000000000..a07ec20f11 --- /dev/null +++ b/Tests/AppKitNavigationTests/TextViewBindingTests.swift @@ -0,0 +1,72 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + /// A text view bound to a string shows it, follows later changes to it, and writes the user's + /// edits back, without getting in the way of an input method that is composing text. + @MainActor + @Suite struct TextViewBindingTests { + @Test("a text view stays in step with its binding") + func textViewStaysInStep() async { + @UIBinding var comment = "First draft" + let textView = NSTextView() + textView.bind(text: $comment) + #expect(textView.string == "First draft") + + comment = "Second draft" + await Task.yield() + #expect(textView.string == "Second draft") + + textView.insertText("!", replacementRange: NSRange(location: 12, length: 0)) + #expect(comment == "Second draft!") + } + + @Test("edits are written back only once an input method finishes composing") + func compositionIsWrittenBackWhenItEnds() { + @UIBinding var comment = "" + let textView = NSTextView() + textView.bind(text: $comment) + + textView.setMarkedText( + "ka", + selectedRange: NSRange(location: 2, length: 0), + replacementRange: NSRange(location: NSNotFound, length: 0) + ) + #expect(textView.hasMarkedText()) + #expect(comment == "") + + textView.insertText("か", replacementRange: NSRange(location: NSNotFound, length: 0)) + #expect(!textView.hasMarkedText()) + #expect(comment == "か") + } + + @Test("a change to the binding keeps the selection where it can") + func bindingChangeKeepsTheSelection() async { + @UIBinding var comment = "Hello" + let textView = NSTextView() + textView.bind(text: $comment) + textView.setSelectedRange(NSRange(location: 1, length: 3)) + + comment = "Hello, world" + await Task.yield() + #expect(textView.selectedRange() == NSRange(location: 1, length: 3)) + + comment = "He" + await Task.yield() + #expect(textView.selectedRange() == NSRange(location: 1, length: 1)) + } + + @Test("unbinding a text view stops writing edits to the binding") + func unbindingStopsWritingEdits() { + @UIBinding var comment = "Original" + let textView = NSTextView() + textView.bind(text: $comment) + + textView.unbindText() + textView.insertText(" text", replacementRange: NSRange(location: 8, length: 0)) + + #expect(comment == "Original") + } + } +#endif From 659c644c5a53fa20ef48d548fa2282e49c8fe0c3 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:28:38 +0800 Subject: [PATCH 109/141] feat(appkit): bind a collection view's selection through a forwarding delegate proxy --- .../draft-appkit-more-control-bindings.md | 10 +- .../Bindings/NSCollectionView.swift | 249 ++++++++++++++++++ .../CollectionViewDelegateProxy.swift | 59 +++++ .../CollectionViewSelectionBindingTests.swift | 187 +++++++++++++ 4 files changed, 501 insertions(+), 4 deletions(-) create mode 100644 Sources/AppKitNavigation/Bindings/NSCollectionView.swift create mode 100644 Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift create mode 100644 Tests/AppKitNavigationTests/CollectionViewSelectionBindingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-more-control-bindings.md b/Documentations/Evolutions/draft-appkit-more-control-bindings.md index fa0fc08949..54e5334e0f 100644 --- a/Documentations/Evolutions/draft-appkit-more-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-more-control-bindings.md @@ -54,11 +54,11 @@ collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) - 用户每次编辑都写回,与 `NSTextField.bind(text:)` 一致。输入法还在组字(有 marked text)时不写回,组完再写。 - 模型变化时,只在内容不同时替换文本,选区尽量保留。 - 不占用 delegate,靠 `NSText.didChangeNotification` 得知编辑。 -3. **集合视图的选中**:`NSCollectionView.bind(selection:dataSource:)`,多选绑 `Set`,单选绑 `ItemIdentifier?`。 +3. **集合视图的选中**(已完成):`NSCollectionView.bind(selection:dataSource:)`,多选绑 `Set`,单选绑 `ItemIdentifier?`。 - 另配一个传两个查找函数的版本 `bind(selection:indexPath:itemIdentifier:)`,给不用 diffable data source 的集合视图,写法与表格的 `bind(selection:row:itemIdentifier:)` 对应。 - - 用户的点选、⌘ 或 ⇧ 点选、拖选、全选都写回;模型改变选中时,库自己防止回写。 - - 不占用 delegate。用户改选中时从哪里得知,要先用测试确认:首选用 KVO 观察 `selectionIndexPaths`。头文件没有写明它对用户的操作发通知,这一条不成立时,在决策日志里记下改用的办法。 - - 数据重新加载后,屏幕上的项会丢掉选中外观(PrivateSymbols 现在手工修正),绑定里一并处理。 + - 用户的点选、⌘ 或 ⇧ 点选、拖选、方向键、全选,以及 App 直接设置 `selectionIndexPaths`,都写回;模型改变选中时,库自己防止回写。 + - 集合视图只把用户的选中变化告诉 delegate,所以绑定在 App 的 delegate 前面放一个转发代理:所有消息原样转给 App 的 delegate,只顺带听选中变化;App 之后另设 delegate 时重新放到前面,解除绑定时把 App 的 delegate 放回去。读 `delegate` 拿到的是代理。 + - 数据源更新删掉选中项、重新加载清掉被重载项的选中时,集合视图什么都不报,这些标识留在绑定里;项出现在屏幕上时,绑定里还有它的标识就重新选上,并补上选中外观(PrivateSymbols 现在手工修的就是这个)。 4. **示例**:在现有的「选项绑定」和「表格选中」案例里各加上新绑定的演示。 5. **文档与验证**:每种绑定先写双向测试再实现。DocC 首页「绑定」一组登记 `NSTextView` 和 `NSCollectionView`;`swift-navigation-bindings` skill 的绑定清单补上。Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译库和测试,CaseStudies 的 macOS 版只编译、不点界面。 @@ -79,3 +79,5 @@ collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) | 2026-11-09 | 两个便捷构造器各加一个可省的 `image:` 参数 | 与新绑定的参数一致;不传时与原来相同 | | 2026-11-09 | 带自身动作的菜单项(如「新建标签…」)靠菜单的 `didSendActionNotification` 得知被选中 | 这类项发送自己的动作,不发弹出按钮的动作,绑定的 target/action 收不到 | | 2026-11-09 | `NSTextView` 另加 `unbindText()` | 与 `unbindIsCollapsed()`、`unbindSelection()` 一致;文本视图不是控件,用不了 `unbind(_:)` | +| 2026-11-09 | 集合视图改用转发代理得知用户的选中变化,不再「不占用 delegate」 | 探针实测:全选、取消全选只回调 delegate,不发 KVO;方向键会发 KVO;删掉选中项、重新加载被重载项都既不发 KVO 也不回调 delegate。用户在三种做法(转发代理、只从模型到界面、先不做)里选了转发代理 | +| 2026-11-09 | 数据源更新拿走或重载掉的选中项,标识留在绑定里;项上屏时按绑定重新选上 | 集合视图对这两种变化什么都不报,绑定无从写回;绑定是选中的来源,项回到屏幕上时以它为准 | diff --git a/Sources/AppKitNavigation/Bindings/NSCollectionView.swift b/Sources/AppKitNavigation/Bindings/NSCollectionView.swift new file mode 100644 index 0000000000..32885d95f6 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSCollectionView.swift @@ -0,0 +1,249 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +extension NSCollectionView { + /// Establishes a two-way connection between a binding and the items the collection view has + /// selected. + /// + /// The binding holds the identifiers of the selected items, and two functions translate + /// between identifiers and index paths. A diffable data source has both, which + /// ``AppKit/NSCollectionView/bind(selection:dataSource:)-(UIBinding>,_)`` + /// passes for you. + /// + /// When the binding changes, the collection view selects the identifiers' items; identifiers + /// without an index path are skipped, and stay in the binding. When the user changes the + /// selection — clicks, extends it, drags a rubber band, uses the arrow keys, or chooses Select + /// All — or the app sets `selectionIndexPaths`, the identifiers of the selected items are + /// written back. Changes the binding itself made are not. + /// + /// A collection view reports the user's selection changes only to its delegate, so the + /// binding puts a proxy in front of the delegate you set. The proxy passes every message on + /// to your delegate, and the binding puts it back in front if you set another delegate later; + /// reading `delegate` returns the proxy. Removing the binding restores your delegate. + /// + /// The collection view says nothing when a data source update takes selected items away, or + /// when a reload deselects the items it makes again. Their identifiers stay in the binding, + /// and the binding selects their items again as they come on screen. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected items, and write to when the + /// selection changes. + /// - indexPath: The index path of the item with an identifier, or `nil` when there is none. + /// - itemIdentifier: The identifier of the item at an index path, or `nil` when it has none. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding>, + indexPath: @escaping (ItemIdentifier) -> IndexPath?, + itemIdentifier: @escaping (IndexPath) -> ItemIdentifier? + ) -> ObserveToken { + bindSelectedItems( + read: { selection.wrappedValue }, + write: { identifiers in selection.wrappedValue = Set(identifiers) }, + indexPath: indexPath, + itemIdentifier: itemIdentifier + ) + } + + /// Establishes a two-way connection between a binding and the one item the collection view has + /// selected. + /// + /// Works as + /// ``AppKit/NSCollectionView/bind(selection:indexPath:itemIdentifier:)-(UIBinding>,_,_)`` + /// does for a set. When several items are selected, the binding holds the first of them. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected item, and write to when the + /// selection changes. + /// - indexPath: The index path of the item with an identifier, or `nil` when there is none. + /// - itemIdentifier: The identifier of the item at an index path, or `nil` when it has none. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + indexPath: @escaping (ItemIdentifier) -> IndexPath?, + itemIdentifier: @escaping (IndexPath) -> ItemIdentifier? + ) -> ObserveToken { + bindSelectedItems( + read: { selection.wrappedValue.map { [$0] } ?? [] }, + write: { identifiers in selection.wrappedValue = identifiers.first }, + indexPath: indexPath, + itemIdentifier: itemIdentifier + ) + } + + /// Establishes a two-way connection between a binding and the items the collection view has + /// selected, through the lookups of the collection view's diffable data source. + /// + /// ```swift + /// collectionView.bind(selection: $model.selectedSymbolIDs, dataSource: dataSource) + /// ``` + /// + /// - Parameters: + /// - selection: The binding to read from for the selected items, and write to when the + /// selection changes. + /// - dataSource: The collection view's diffable data source. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding>, + dataSource: NSCollectionViewDiffableDataSource + ) -> ObserveToken { + // NB: Held weakly: the collection view keeps this binding for as long as it lives, and the + // data source may hold on to the collection view. + bind( + selection: selection, + indexPath: { [weak dataSource] identifier in dataSource?.indexPath(for: identifier) }, + itemIdentifier: { [weak dataSource] indexPath in dataSource?.itemIdentifier(for: indexPath) } + ) + } + + /// Establishes a two-way connection between a binding and the one item the collection view has + /// selected, through the lookups of the collection view's diffable data source. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected item, and write to when the + /// selection changes. + /// - dataSource: The collection view's diffable data source. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + dataSource: NSCollectionViewDiffableDataSource + ) -> ObserveToken { + bind( + selection: selection, + indexPath: { [weak dataSource] identifier in dataSource?.indexPath(for: identifier) }, + itemIdentifier: { [weak dataSource] indexPath in dataSource?.itemIdentifier(for: indexPath) } + ) + } + + /// Removes a binding established with one of the collection view's `bind(selection:…)` + /// methods. + public func unbindSelection() { + removeBinding(to: \NSCollectionView.selectionIndexPaths) + } + + private func bindSelectedItems( + read: @escaping () -> Set, + write: @escaping (_ identifiersInOrder: [ItemIdentifier]) -> Void, + indexPath: @escaping (ItemIdentifier) -> IndexPath?, + itemIdentifier: @escaping (IndexPath) -> ItemIdentifier? + ) -> ObserveToken { + unbindSelection() + let isSelecting = LockIsolated(false) + let token = observe { [weak self] in + guard let self else { return } + let indexPathsToSelect = Set(read().compactMap(indexPath)) + isSelecting.withLock { $0 = true } + defer { isSelecting.withLock { $0 = false } } + if selectionIndexPaths != indexPathsToSelect { + selectionIndexPaths = indexPathsToSelect + } + showSelectionOfVisibleItems() + } + let writeSelectionBack = { [weak self] in + guard let self, isSelecting.withLock({ !$0 }) else { return } + let identifiers = selectionIndexPaths.sorted().compactMap(itemIdentifier) + guard read() != Set(identifiers) else { return } + write(identifiers) + } + let delegateProxy = installDelegateProxy() + delegateProxy.selectionDidChange = writeSelectionBack + // NB: A reload deselects the items it makes again, and says nothing about it. An item + // whose identifier is still bound is selected again as it comes on screen. + delegateProxy.itemWillDisplay = { [weak self] item, displayedIndexPath in + guard + let self, + let identifier = itemIdentifier(displayedIndexPath), + read().contains(identifier) + else { return } + if !selectionIndexPaths.contains(displayedIndexPath) { + isSelecting.withLock { $0 = true } + defer { isSelecting.withLock { $0 = false } } + selectionIndexPaths.insert(displayedIndexPath) + } + item.isSelected = true + } + // NB: Setting 'selectionIndexPaths', and moving the selection with the arrow keys, are + // reported through key-value observation rather than to the delegate. + nonisolated(unsafe) let writeSelectionBackFromObservation = writeSelectionBack + let observation = observe(\.selectionIndexPaths) { _, _ in + MainActor._assumeIsolated { + writeSelectionBackFromObservation() + } + } + let observationToken = ObserveToken { [weak self, weak delegateProxy] in + token.cancel() + observation.invalidate() + MainActor._assumeIsolated { + guard let self, let delegateProxy else { return } + self.removeDelegateProxy(delegateProxy) + } + } + observationTokens[\NSCollectionView.selectionIndexPaths] = observationToken + return observationToken + } + + /// The proxy in front of the delegate the app set, while a selection binding is in place. + fileprivate var appKitNavigationDelegateProxy: CollectionViewDelegateProxy? { + get { + objc_getAssociatedObject(self, delegateProxyKey) as? CollectionViewDelegateProxy + } + set { + objc_setAssociatedObject(self, delegateProxyKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + + /// Puts a proxy in front of the collection view's delegate, and keeps it in front when the + /// app sets another delegate. + private func installDelegateProxy() -> CollectionViewDelegateProxy { + let delegateProxy = CollectionViewDelegateProxy() + delegateProxy.forwardDelegate = delegate + // NB: The collection view holds its delegate weakly. + appKitNavigationDelegateProxy = delegateProxy + delegate = delegateProxy + delegateProxy.delegateObservation = observe(\.delegate) { collectionView, _ in + MainActor._assumeIsolated { + guard + let delegateProxy = collectionView.appKitNavigationDelegateProxy, + (collectionView.delegate as AnyObject?) !== delegateProxy + else { return } + delegateProxy.forwardDelegate = collectionView.delegate + // NB: Set again, so that the collection view asks the proxy afresh which + // messages it answers. + collectionView.delegate = delegateProxy + } + } + return delegateProxy + } + + /// Takes the proxy away and gives the app's delegate back its place. + private func removeDelegateProxy(_ delegateProxy: CollectionViewDelegateProxy) { + delegateProxy.delegateObservation?.invalidate() + delegateProxy.delegateObservation = nil + delegateProxy.selectionDidChange = nil + delegateProxy.itemWillDisplay = nil + if (delegate as AnyObject?) === delegateProxy { + delegate = delegateProxy.forwardDelegate + } + if appKitNavigationDelegateProxy === delegateProxy { + appKitNavigationDelegateProxy = nil + } + } + + /// Marks the visible items at selected index paths as selected. + /// + /// A reload hands the selected index paths freshly made items, which come back unselected, + /// while the selection itself stays the same, so assigning it again would change nothing. + private func showSelectionOfVisibleItems() { + let selectedIndexPaths = selectionIndexPaths + for visibleIndexPath in indexPathsForVisibleItems() where selectedIndexPaths.contains(visibleIndexPath) { + item(at: visibleIndexPath)?.isSelected = true + } + } +} + +@MainActor +private let delegateProxyKey = malloc(1)! +#endif diff --git a/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift b/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift new file mode 100644 index 0000000000..e012402b8b --- /dev/null +++ b/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift @@ -0,0 +1,59 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + + /// Stands in as a collection view's delegate while a selection binding is in place, so that the + /// binding hears of the user's selection changes, and passes every message on to the delegate + /// the app set. + /// + /// A collection view reports the user's clicks, Select All and Deselect All only to its + /// delegate: neither key-value observation of `selectionIndexPaths` nor a notification carries + /// them. + @MainActor + final class CollectionViewDelegateProxy: NSObject, NSCollectionViewDelegate { + // NB: Read by the Objective-C runtime's forwarding, which is not isolated. The collection view + // only messages its delegate on the main thread. + nonisolated(unsafe) weak var forwardDelegate: (any NSCollectionViewDelegate)? + + /// Runs when the user selects or deselects items. + var selectionDidChange: (() -> Void)? + + /// Runs when the collection view is about to show an item. + var itemWillDisplay: ((NSCollectionViewItem, IndexPath) -> Void)? + + /// Puts the proxy back in front when the app sets another delegate. + var delegateObservation: NSKeyValueObservation? + + nonisolated override func responds(to selector: Selector!) -> Bool { + super.responds(to: selector) || (forwardDelegate?.responds(to: selector) ?? false) + } + + nonisolated override func forwardingTarget(for selector: Selector!) -> Any? { + forwardDelegate + } + + func collectionView( + _ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set + ) { + forwardDelegate?.collectionView?(collectionView, didSelectItemsAt: indexPaths) + selectionDidChange?() + } + + func collectionView( + _ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set + ) { + forwardDelegate?.collectionView?(collectionView, didDeselectItemsAt: indexPaths) + selectionDidChange?() + } + + func collectionView( + _ collectionView: NSCollectionView, + willDisplay item: NSCollectionViewItem, + forRepresentedObjectAt indexPath: IndexPath + ) { + itemWillDisplay?(item, indexPath) + forwardDelegate?.collectionView?( + collectionView, willDisplay: item, forRepresentedObjectAt: indexPath + ) + } + } +#endif diff --git a/Tests/AppKitNavigationTests/CollectionViewSelectionBindingTests.swift b/Tests/AppKitNavigationTests/CollectionViewSelectionBindingTests.swift new file mode 100644 index 0000000000..941c639c80 --- /dev/null +++ b/Tests/AppKitNavigationTests/CollectionViewSelectionBindingTests.swift @@ -0,0 +1,187 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + #if compiler(<6.4) + // NB: Swift 6.2 treats the delegate's conformance below as public, and a public conformance + // needs a public import. + public import AppKit + #else + import AppKit + #endif + import AppKitNavigation + import Testing + + /// A collection view's selected items stay in step with a binding: the collection view follows + /// the bound identifiers, and writes back what the user, or the app, changes. + @MainActor + @Suite struct CollectionViewSelectionBindingTests { + @Test("a collection view's selected items stay in step with a set") + func selectedItemsStayInStep() async { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star", "heart", "bolt"]) + @UIBinding var selectedSymbols: Set = ["heart"] + collectionView.bind(selection: $selectedSymbols, dataSource: dataSource) + #expect(collectionView.selectionIndexPaths == [IndexPath(item: 1, section: 0)]) + + selectedSymbols = ["star", "bolt"] + await Task.yield() + #expect( + collectionView.selectionIndexPaths + == [IndexPath(item: 0, section: 0), IndexPath(item: 2, section: 0)] + ) + + // NB: What the collection view does when the user chooses Select All. + collectionView.selectAll(nil) + #expect(selectedSymbols == ["star", "heart", "bolt"]) + + collectionView.deselectAll(nil) + #expect(selectedSymbols.isEmpty) + } + + @Test("a collection view's one selected item stays in step with an optional") + func selectedItemStaysInStep() async { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star", "heart"]) + collectionView.allowsMultipleSelection = false + @UIBinding var selectedSymbol: String? = "heart" + collectionView.bind(selection: $selectedSymbol, dataSource: dataSource) + #expect(collectionView.selectionIndexPaths == [IndexPath(item: 1, section: 0)]) + + selectedSymbol = nil + await Task.yield() + #expect(collectionView.selectionIndexPaths.isEmpty) + + collectionView.selectionIndexPaths = [IndexPath(item: 0, section: 0)] + #expect(selectedSymbol == "star") + } + + @Test("an identifier without an item selects nothing and stays in the binding") + func identifierWithoutAnItemStaysInTheBinding() async { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star"]) + @UIBinding var selectedSymbols: Set = ["star", "moon"] + collectionView.bind(selection: $selectedSymbols, dataSource: dataSource) + + #expect(collectionView.selectionIndexPaths == [IndexPath(item: 0, section: 0)]) + #expect(selectedSymbols == ["star", "moon"]) + } + + /// A collection view reports neither through key-value observation nor to its delegate that + /// a data source update took selected items away. + @Test("a selected item that a data source update takes away stays in the binding") + func removedItemStaysInTheBinding() { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star", "heart"]) + @UIBinding var selectedSymbols: Set = ["star", "heart"] + collectionView.bind(selection: $selectedSymbols, dataSource: dataSource) + + var snapshot = dataSource.snapshot() + snapshot.deleteItems(["heart"]) + dataSource.apply(snapshot, animatingDifferences: false) + + #expect(selectedSymbols == ["star", "heart"]) + } + + @Test("the app's delegate keeps getting its messages, including one set after binding") + func appDelegateKeepsGettingItsMessages() { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star", "heart"]) + let firstDelegate = SelectionRecordingDelegate() + collectionView.delegate = firstDelegate + @UIBinding var selectedSymbols: Set = [] + collectionView.bind(selection: $selectedSymbols, dataSource: dataSource) + + collectionView.selectAll(nil) + #expect(firstDelegate.selectionCount == 1) + #expect(selectedSymbols == ["star", "heart"]) + + let secondDelegate = SelectionRecordingDelegate() + collectionView.delegate = secondDelegate + collectionView.deselectAll(nil) + #expect(secondDelegate.selectionCount == 1) + #expect(selectedSymbols.isEmpty) + + collectionView.unbindSelection() + #expect(collectionView.delegate === secondDelegate) + } + + @Test("a selected item made again by a reload still shows as selected") + func reloadedItemStillShowsAsSelected() throws { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star", "heart"]) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 300, height: 200), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + let scrollView = NSScrollView(frame: NSRect(x: 0, y: 0, width: 300, height: 200)) + scrollView.documentView = collectionView + window.contentView = scrollView + collectionView.layoutSubtreeIfNeeded() + @UIBinding var selectedSymbols: Set = ["heart"] + collectionView.bind(selection: $selectedSymbols, dataSource: dataSource) + + var snapshot = dataSource.snapshot() + snapshot.reloadItems(["heart"]) + dataSource.apply(snapshot, animatingDifferences: false) + collectionView.layoutSubtreeIfNeeded() + + let item = try #require(collectionView.item(at: IndexPath(item: 1, section: 0))) + #expect(item.isSelected) + #expect(collectionView.selectionIndexPaths == [IndexPath(item: 1, section: 0)]) + #expect(selectedSymbols == ["heart"]) + withExtendedLifetime(window) {} + } + + @Test("unbinding a collection view stops writing its selection to the binding") + func unbindingStopsWritingTheSelection() { + let (collectionView, dataSource) = makeCollectionView(symbols: ["star", "heart"]) + @UIBinding var selectedSymbols: Set = [] + collectionView.bind(selection: $selectedSymbols, dataSource: dataSource) + + collectionView.unbindSelection() + collectionView.selectAll(nil) + + #expect(selectedSymbols.isEmpty) + } + + private func makeCollectionView( + symbols: [String] + ) -> (NSCollectionView, NSCollectionViewDiffableDataSource) { + let collectionView = NSCollectionView(frame: NSRect(x: 0, y: 0, width: 300, height: 200)) + let layout = NSCollectionViewFlowLayout() + layout.itemSize = NSSize(width: 40, height: 40) + collectionView.collectionViewLayout = layout + collectionView.isSelectable = true + collectionView.allowsMultipleSelection = true + collectionView.register(SymbolItem.self, forItemWithIdentifier: SymbolItem.identifier) + let dataSource = NSCollectionViewDiffableDataSource( + collectionView: collectionView + ) { collectionView, indexPath, _ in + collectionView.makeItem(withIdentifier: SymbolItem.identifier, for: indexPath) + } + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(symbols, toSection: 0) + dataSource.apply(snapshot, animatingDifferences: false) + return (collectionView, dataSource) + } + } + + private final class SelectionRecordingDelegate: NSObject, NSCollectionViewDelegate { + private(set) var selectionCount = 0 + + func collectionView( + _ collectionView: NSCollectionView, didSelectItemsAt indexPaths: Set + ) { + selectionCount += 1 + } + + func collectionView( + _ collectionView: NSCollectionView, didDeselectItemsAt indexPaths: Set + ) { + selectionCount += 1 + } + } + + private final class SymbolItem: NSCollectionViewItem { + static let identifier = NSUserInterfaceItemIdentifier("SymbolItem") + + override func loadView() { + view = NSView() + } + } +#endif From b122dd651dc447765f712b583683218c03d7eb6f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:36:11 +0800 Subject: [PATCH 110/141] docs(examples): show the new bindings and an animations case study, and record the verification --- .../draft-appkit-animations-case-study.md | 1 + .../draft-appkit-more-control-bindings.md | 6 +- .../Evolutions/draft-observe-unowned-self.md | 3 +- .../AppKit+AnimationsViewController.swift | 116 ++++++++++++++++++ .../AppKit+OptionBindingsViewController.swift | 42 +++++++ .../AppKit+TableSelectionViewController.swift | 83 ++++++++++++- .../AppKit/AppKitCaseStudies.swift | 2 +- Examples/Examples.xcodeproj/project.pbxproj | 4 + .../Bindings/NSCollectionView.swift | 2 + .../Documentation.docc/AppKitNavigation.md | 2 + .../CollectionViewDelegateProxy.swift | 2 +- .../ObserveLifetimeTests.swift | 7 +- .../OptionItemBindingTests.swift | 5 + 13 files changed, 268 insertions(+), 7 deletions(-) create mode 100644 Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift diff --git a/Documentations/Evolutions/draft-appkit-animations-case-study.md b/Documentations/Evolutions/draft-appkit-animations-case-study.md index ee61a59a74..c2624a8d41 100644 --- a/Documentations/Evolutions/draft-appkit-animations-case-study.md +++ b/Documentations/Evolutions/draft-appkit-animations-case-study.md @@ -29,3 +29,4 @@ AppKit 案例列表里的「Animations」一项一直是注释掉的:UIKit 有 |------|------|------| | 2026-11-09 | Created as Draft | AppKit 案例列表里只有动画一项还注释着,用户选定补上 | | 2026-11-09 | 用户批准,开始实现 | 与另两份提案在同一条分支上实现,做完在本地合进 `main`、不推送 | +| 2026-11-09 | 实现完成,待用户看过后收尾 | 新增 `AppKit+AnimationsViewController.swift` 并登记进 `Examples.xcodeproj`,案例列表恢复这一项。CaseStudies 的 macOS 版经 `SwiftNavigation.xcworkspace` 编译通过,新文件没有警告;没有打开界面去点,圆的位移、缩放和换色是否真的有过渡没有实测。文档判断:案例本身就是示例文档,不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/draft-appkit-more-control-bindings.md b/Documentations/Evolutions/draft-appkit-more-control-bindings.md index 54e5334e0f..04cce7011b 100644 --- a/Documentations/Evolutions/draft-appkit-more-control-bindings.md +++ b/Documentations/Evolutions/draft-appkit-more-control-bindings.md @@ -59,8 +59,8 @@ collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) - 用户的点选、⌘ 或 ⇧ 点选、拖选、方向键、全选,以及 App 直接设置 `selectionIndexPaths`,都写回;模型改变选中时,库自己防止回写。 - 集合视图只把用户的选中变化告诉 delegate,所以绑定在 App 的 delegate 前面放一个转发代理:所有消息原样转给 App 的 delegate,只顺带听选中变化;App 之后另设 delegate 时重新放到前面,解除绑定时把 App 的 delegate 放回去。读 `delegate` 拿到的是代理。 - 数据源更新删掉选中项、重新加载清掉被重载项的选中时,集合视图什么都不报,这些标识留在绑定里;项出现在屏幕上时,绑定里还有它的标识就重新选上,并补上选中外观(PrivateSymbols 现在手工修的就是这个)。 -4. **示例**:在现有的「选项绑定」和「表格选中」案例里各加上新绑定的演示。 -5. **文档与验证**:每种绑定先写双向测试再实现。DocC 首页「绑定」一组登记 `NSTextView` 和 `NSCollectionView`;`swift-navigation-bindings` skill 的绑定清单补上。Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译库和测试,CaseStudies 的 macOS 版只编译、不点界面。 +4. **示例**(已完成):在现有的「选项绑定」和「表格选中」案例里各加上新绑定的演示:标签弹出按钮的选项随模型增加,带一个 App 自己的「New Tag…」项;一个绑定到字符串的文本视图;一个多选的集合视图。 +5. **文档与验证**(已完成):每种绑定先写双向测试再实现。DocC 首页「绑定」一组登记 `NSTextView` 和 `NSCollectionView`;`swift-navigation-bindings` skill 的绑定清单补上。Xcode 27.2 跑 AppKit 的全部测试,Xcode 26.6 编译库和测试,CaseStudies 的 macOS 版只编译、不点界面。 没有询问就采用的假设: @@ -81,3 +81,5 @@ collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) | 2026-11-09 | `NSTextView` 另加 `unbindText()` | 与 `unbindIsCollapsed()`、`unbindSelection()` 一致;文本视图不是控件,用不了 `unbind(_:)` | | 2026-11-09 | 集合视图改用转发代理得知用户的选中变化,不再「不占用 delegate」 | 探针实测:全选、取消全选只回调 delegate,不发 KVO;方向键会发 KVO;删掉选中项、重新加载被重载项都既不发 KVO 也不回调 delegate。用户在三种做法(转发代理、只从模型到界面、先不做)里选了转发代理 | | 2026-11-09 | 数据源更新拿走或重载掉的选中项,标识留在绑定里;项上屏时按绑定重新选上 | 集合视图对这两种变化什么都不报,绑定无从写回;绑定是选中的来源,项回到屏幕上时以它为准 | +| 2026-11-09 | 数据源版本的集合视图绑定标 `@available(macOS 10.15.1, *)`;代理类所在文件改为 `public import AppKit`;两份新测试文件在 Swift 6.4 以前的编译器下 `public import Observation` | Xcode 26.6 用 6.2 那份清单,最低系统是 macOS 10.15,而 `NSCollectionViewDiffableDataSource` 从 10.15.1 起才有;Swift 6.2 把这些遵循当成公开的,公开遵循需要公开导入 | +| 2026-11-09 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试全部通过:XCTest 66 条,Swift Testing 77 条(其中 2 条是故意触发的已知问题);Xcode 26.6 编译库和 AppKit 测试通过;生成文档只有与上游共用内容里原有的 3 条链接警告;CaseStudies 的 macOS 版经 `SwiftNavigation.xcworkspace` 编译通过,没有点界面。文档判断:用法和契约(集合视图的转发代理、App 自加的菜单项)写在文档注释和 `swift-navigation-bindings` skill 里,DocC 首页登记了 `NSTextView` 和 `NSCollectionView`;探针得出的 AppKit 行为记在代码注释和本提案里,不另写实现说明;没有新术语 | diff --git a/Documentations/Evolutions/draft-observe-unowned-self.md b/Documentations/Evolutions/draft-observe-unowned-self.md index ef5eed0244..77a9b57fbe 100644 --- a/Documentations/Evolutions/draft-observe-unowned-self.md +++ b/Documentations/Evolutions/draft-observe-unowned-self.md @@ -36,7 +36,7 @@ observe { [unowned self] in - 对象释放后再改模型、转几圈 run loop,闭包一次也没被调用。 - 令牌被对象以外的东西留住时,对象释放后闭包仍会被调用。这正是推荐写法的前提,文档要写明。 2. **文档**(已完成):AppKitNavigation 的 DocC 首页加一段,说明在 `NSObject.observe` 里推荐写 `[unowned self]` 及其前提;`swift-navigation-bindings` skill 的写法和常见错误同步改。 -3. **示例**:AppKit 案例里的 12 处 `observe { [weak self] in … }` 改成新写法。 +3. **示例**(已完成):AppKit 案例里的 12 处 `observe { [weak self] in … }` 改成新写法。 没有询问就采用的假设: @@ -54,3 +54,4 @@ observe { [unowned self] in | 2026-11-09 | Created as Draft | 下游 4 个 App 的 55 个 `observe` 闭包都写了 `[weak self]`,其中 43 个还要再写一行 `guard let self`;用户选定简化这个写法 | | 2026-11-09 | 用户选定推荐 `[unowned self]`,不加把对象传进闭包的新重载 | 新重载要在每次访问成员时写 `owner.`,下游多行闭包反而更啰嗦;`[unowned self]` 保留隐式 `self`,闭包体不用改 | | 2026-11-09 | 用户批准,开始实现 | 与另两份提案在同一条分支 `appkit-more-control-bindings` 上实现,做完在本地合进 `main`、不推送 | +| 2026-11-09 | 实现完成,待用户看过后收尾 | 两条回归测试通过;DocC 首页加了一节「Observing from a view or view controller」,`swift-navigation-bindings` skill 的示例、说明和常见错误同步改成 `[unowned self]`;AppKit 案例 12 处改完,CaseStudies 的 macOS 版编译通过。文档判断:推荐写法和前提都写进了 DocC 和 skill,不需要另写使用指南或实现说明,没有新术语 | diff --git a/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift new file mode 100644 index 0000000000..4b5e422b50 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift @@ -0,0 +1,116 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation +import SwiftUI + +class AnimationsViewController: XiblessViewController, AppKitCaseStudy { + let caseStudyTitle = "Animations" + let readMe = """ + This case study demonstrates how to drive animations from state in an AppKit application. To \ + animate a model mutation, wrap the mutation in 'withAppKitAnimation'. To animate changes to a \ + binding, use the '.animation()' method on 'UIBinding'. + + Click or drag in the gray area to move the circle with a spring, flip the switch to scale it, \ + and cycle through its colors with the button. + """ + @UIBindable var model = Model() + private let canvasView = NSView() + + override func viewDidLoad() { + super.viewDidLoad() + + canvasView.wantsLayer = true + canvasView.layer?.backgroundColor = NSColor.quaternaryLabelColor.cgColor + canvasView.layer?.cornerRadius = 8 + canvasView.translatesAutoresizingMaskIntoConstraints = false + let circleView = NSView() + circleView.wantsLayer = true + canvasView.addSubview(circleView) + + let isScaledLabel = NSTextField(labelWithString: "Is scaled?") + let isScaledSwitch = NSSwitch(isOn: $model.isScaled.animation(Self.springAnimation)) + let scaleRow = NSStackView(views: [isScaledLabel, isScaledSwitch]) + scaleRow.orientation = .horizontal + scaleRow.spacing = 12 + let cycleColorsButton = makeButton("Cycle colors") { [weak self] in + guard let self else { return } + Task { await self.model.cycleColors() } + } + let controls = NSStackView(views: [scaleRow, cycleColorsButton]) + controls.orientation = .vertical + controls.alignment = .centerX + controls.spacing = 12 + controls.translatesAutoresizingMaskIntoConstraints = false + + view.addSubview(controls) + view.addSubview(canvasView) + NSLayoutConstraint.activate([ + controls.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), + controls.centerXAnchor.constraint(equalTo: view.centerXAnchor), + canvasView.topAnchor.constraint(equalTo: controls.bottomAnchor, constant: 20), + canvasView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), + canvasView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20), + canvasView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20), + canvasView.heightAnchor.constraint(greaterThanOrEqualToConstant: 360), + ]) + + observe { [unowned self] in + // NB: 'NSView' has no 'transform' to scale with, so the circle grows by its frame instead. + let diameter: CGFloat = model.isScaled ? 200 : 100 + circleView.frame = NSRect( + x: model.position.x - diameter / 2, + y: model.position.y - diameter / 2, + width: diameter, + height: diameter + ) + circleView.layer?.cornerRadius = diameter / 2 + circleView.layer?.backgroundColor = model.color.cgColor + } + } + + override func mouseDown(with event: NSEvent) { + moveCircle(to: event) + } + + override func mouseDragged(with event: NSEvent) { + moveCircle(to: event) + } + + private func moveCircle(to event: NSEvent) { + let location = canvasView.convert(event.locationInWindow, from: nil) + guard canvasView.bounds.contains(location) else { return } + withAppKitAnimation(Self.springAnimation) { + model.position = location + } + } + + /// A spring where the system has one, which is macOS 15 and later. + private static var springAnimation: AppKitAnimation { + if #available(macOS 15, *) { + AppKitAnimation(.spring(duration: 0.4, bounce: 0.6)) + } else { + .easeInOut(duration: 0.4) + } + } + + @MainActor + @Observable + class Model { + var position = CGPoint(x: 150, y: 180) + var isScaled = false + var color = NSColor.black + + func cycleColors() async { + let colors: [NSColor] = [.systemRed, .systemBlue, .systemTeal, .systemGreen, .systemPink, .systemPurple, .black] + for color in colors { + withAppKitAnimation { self.color = color } + try? await Task.sleep(for: .seconds(1)) + } + } + } +} + +#Preview { + AnimationsViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift index f1ba9e9edb..f978f50a93 100644 --- a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift @@ -11,6 +11,10 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu A segmented control that lets you pick any number of segments binds each segment to a Bool of \ its own, and a menu item binds its checkmark to a Bool. + + The tag pop-up makes its items from options that change: "New Tag…" adds a tag to the model, \ + and the pop-up grows an item for it. "New Tag…" is an item of the app's own, which the binding \ + leaves alone. The text view below it binds its text to a string. """ @UIBindable var model = Model() private let tabViewController = NSTabViewController() @@ -50,6 +54,29 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu viewOptionsButton.addItem(withTitle: "View options") viewOptionsButton.menu?.addItem(NSMenuItem(title: "Show the grid", isOn: $model.showsGrid)) + let tagPopUpButton = NSPopUpButton(frame: .zero, pullsDown: false) + tagPopUpButton.bind( + selection: $model.tag, + options: { [unowned self] in [nil] + model.tags.map(Optional.some) }, + title: { $0 ?? "No Tag" } + ) + tagPopUpButton.menu?.addItem(.separator()) + let newTagItem = NSMenuItem(title: "New Tag…", action: #selector(newTag(_:)), keyEquivalent: "") + newTagItem.target = self + tagPopUpButton.menu?.addItem(newTagItem) + + let noteScrollView = NSTextView.scrollableTextView() + noteScrollView.borderType = .bezelBorder + noteScrollView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + noteScrollView.widthAnchor.constraint(equalToConstant: 320), + noteScrollView.heightAnchor.constraint(equalToConstant: 60), + ]) + if let noteTextView = noteScrollView.documentView as? NSTextView { + noteTextView.isRichText = false + noteTextView.bind(text: $model.note) + } + let statusLabel = NSTextField(wrappingLabelWithString: "") statusLabel.textColor = .secondaryLabelColor @@ -63,6 +90,10 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu styleControl, makeSectionLabel("A menu item's checkmark"), viewOptionsButton, + makeSectionLabel("Options that change"), + tagPopUpButton, + makeSectionLabel("A text view's text"), + noteScrollView, statusLabel, ], to: view @@ -78,10 +109,18 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu Fruit: \(model.fruit.title) Style: \(styles.isEmpty ? "plain" : styles.joined(separator: ", ")) Grid: \(model.showsGrid ? "shown" : "hidden") + Tag: \(model.tag ?? "none") + Note: \(model.note.count) characters """ } } + @objc private func newTag(_ sender: Any?) { + let tag = "Tag \(model.tags.count + 1)" + model.tags.append(tag) + model.tag = tag + } + @Observable class Model { var fruit = Fruit.banana @@ -89,6 +128,9 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu var isItalic = false var isUnderlined = false var showsGrid = false + var tags = ["Red", "Green"] + var tag: String? = "Red" + var note = "Type a note here." } enum Fruit: CaseIterable { diff --git a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift index 74be82521b..3814f1aa1c 100644 --- a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift @@ -3,7 +3,7 @@ import AppKit import AppKitNavigation class TableSelectionViewController: XiblessViewController, AppKitCaseStudy { - let caseStudyTitle = "Table and outline selection" + let caseStudyTitle = "Table, outline and collection selection" let readMe = """ A table or an outline binds its selected row to the identifier of the selected item, and an \ outline binds the items it has expanded to a set of identifiers. The model holds identifiers \ @@ -12,12 +12,17 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu The table uses a diffable data source, which the binding asks for rows directly. The outline \ uses a data source of its own and gives the binding its row lookups. The buttons change the \ model; clicking in the table or the outline changes it too. + + A collection view binds the items it has selected to a set of identifiers. Click, ⌘-click, \ + drag across the colors or choose Select All, and the model follows. """ @UIBindable var model = Model() private let tableView = NSTableView() private let outlineView = NSOutlineView() private let outlineDataSource = PantryOutlineDataSource() private var tableDataSource: NSTableViewDiffableDataSource? + private let collectionView = NSCollectionView() + private var collectionDataSource: NSCollectionViewDiffableDataSource? override func viewDidLoad() { super.viewDidLoad() @@ -67,6 +72,38 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu } ) + // MARK: Collection + + let layout = NSCollectionViewFlowLayout() + layout.itemSize = NSSize(width: 70, height: 28) + layout.minimumInteritemSpacing = 6 + layout.minimumLineSpacing = 6 + collectionView.collectionViewLayout = layout + collectionView.isSelectable = true + collectionView.allowsMultipleSelection = true + collectionView.register(ColorItem.self, forItemWithIdentifier: ColorItem.identifier) + let collectionDataSource = NSCollectionViewDiffableDataSource( + collectionView: collectionView + ) { collectionView, indexPath, colorName in + let item = collectionView.makeItem(withIdentifier: ColorItem.identifier, for: indexPath) + item.textField?.stringValue = colorName + return item + } + var colorSnapshot = NSDiffableDataSourceSnapshot() + colorSnapshot.appendSections([0]) + colorSnapshot.appendItems(ColorItem.colorNames) + collectionDataSource.apply(colorSnapshot, animatingDifferences: false) + self.collectionDataSource = collectionDataSource + collectionView.bind(selection: $model.selectedColors, dataSource: collectionDataSource) + let collectionScrollView = NSScrollView() + collectionScrollView.documentView = collectionView + collectionScrollView.borderType = .bezelBorder + collectionScrollView.translatesAutoresizingMaskIntoConstraints = false + NSLayoutConstraint.activate([ + collectionScrollView.widthAnchor.constraint(equalToConstant: 260), + collectionScrollView.heightAnchor.constraint(equalToConstant: 80), + ]) + let statusLabel = NSTextField(wrappingLabelWithString: "") statusLabel.textColor = .secondaryLabelColor @@ -93,6 +130,14 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu makeButton("Collapse everything") { [weak self] in self?.model.expandedPantryGroups = [] }, + makeSectionLabel("Collection"), + collectionScrollView, + makeButton("Select the warm colors") { [weak self] in + self?.model.selectedColors = ["Red", "Orange", "Yellow"] + }, + makeButton("Clear the colors' selection") { [weak self] in + self?.model.selectedColors = [] + }, statusLabel, ], to: view @@ -103,6 +148,7 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu Table selection: \(model.selectedPlanet ?? "none") Outline selection: \(model.selectedPantryItem ?? "none") Expanded groups: \(model.expandedPantryGroups.isEmpty ? "none" : model.expandedPantryGroups.sorted().joined(separator: ", ")) + Selected colors: \(model.selectedColors.isEmpty ? "none" : ColorItem.colorNames.filter(model.selectedColors.contains).joined(separator: ", ")) """ } } @@ -126,6 +172,41 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu var selectedPlanet: String? var selectedPantryItem: String? var expandedPantryGroups: Set = ["Vegetables"] + var selectedColors: Set = ["Blue"] + } +} + +/// An item in the collection: the name of a color, highlighted while it is selected. +private final class ColorItem: NSCollectionViewItem { + static let identifier = NSUserInterfaceItemIdentifier("ColorItem") + static let colorNames = ["Red", "Orange", "Yellow", "Green", "Blue", "Purple"] + + override func loadView() { + let label = NSTextField(labelWithString: "") + label.alignment = .center + label.translatesAutoresizingMaskIntoConstraints = false + let container = NSView() + container.wantsLayer = true + container.layer?.cornerRadius = 6 + container.layer?.borderWidth = 1 + container.addSubview(label) + NSLayoutConstraint.activate([ + label.centerXAnchor.constraint(equalTo: container.centerXAnchor), + label.centerYAnchor.constraint(equalTo: container.centerYAnchor), + ]) + view = container + textField = label + updateAppearance() + } + + override var isSelected: Bool { + didSet { updateAppearance() } + } + + private func updateAppearance() { + view.layer?.backgroundColor = (isSelected ? NSColor.controlAccentColor : NSColor.clear).cgColor + view.layer?.borderColor = NSColor.separatorColor.cgColor + textField?.textColor = isSelected ? .white : .labelColor } } diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift index 8127293e0b..303265b71f 100644 --- a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -7,7 +7,7 @@ struct AppKitCaseStudiesView: View { List { CaseStudyGroupView("Observation") { MinimalObservationViewController() -// AnimationsViewController() + AnimationsViewController() } CaseStudyGroupView("Bindings") { NSControlBindingsViewController() diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index de5d831fb4..ff4dea3984 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -79,6 +79,7 @@ E9F0050A2EDA000000000014 /* AppKit+DismissalViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000004 /* AppKit+DismissalViewController.swift */; }; E9F0050A2EDA000000000015 /* AppKit+OptionBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */; }; E9F0050A2EDA000000000016 /* AppKit+TableSelectionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */; }; + E9F0050A2EDA000000000017 /* AppKit+AnimationsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -160,6 +161,7 @@ E9F0050A2EDA000000000004 /* AppKit+DismissalViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+DismissalViewController.swift"; sourceTree = ""; }; E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+OptionBindingsViewController.swift"; sourceTree = ""; }; E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+TableSelectionViewController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+AnimationsViewController.swift"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -365,6 +367,7 @@ E9F0050A2EDA000000000004 /* AppKit+DismissalViewController.swift */, E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */, E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */, + E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */, ); path = AppKit; sourceTree = ""; @@ -617,6 +620,7 @@ E9F0050A2EDA000000000014 /* AppKit+DismissalViewController.swift in Sources */, E9F0050A2EDA000000000015 /* AppKit+OptionBindingsViewController.swift in Sources */, E9F0050A2EDA000000000016 /* AppKit+TableSelectionViewController.swift in Sources */, + E9F0050A2EDA000000000017 /* AppKit+AnimationsViewController.swift in Sources */, DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */, E99B05992C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift in Sources */, E99B05A42C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift in Sources */, diff --git a/Sources/AppKitNavigation/Bindings/NSCollectionView.swift b/Sources/AppKitNavigation/Bindings/NSCollectionView.swift index 32885d95f6..18702d4435 100644 --- a/Sources/AppKitNavigation/Bindings/NSCollectionView.swift +++ b/Sources/AppKitNavigation/Bindings/NSCollectionView.swift @@ -85,6 +85,7 @@ extension NSCollectionView { /// - dataSource: The collection view's diffable data source. /// - Returns: A cancel token. @discardableResult + @available(macOS 10.15.1, *) public func bind( selection: UIBinding>, dataSource: NSCollectionViewDiffableDataSource @@ -107,6 +108,7 @@ extension NSCollectionView { /// - dataSource: The collection view's diffable data source. /// - Returns: A cancel token. @discardableResult + @available(macOS 10.15.1, *) public func bind( selection: UIBinding, dataSource: NSCollectionViewDiffableDataSource diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 3710d6d17f..ba66c1da52 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -67,8 +67,10 @@ to something that can outlive the object, capture the object `weak` instead. - ``AppKit/NSPopUpButton`` - ``AppKit/NSSegmentedControl`` - ``AppKit/NSProgressIndicator`` +- ``AppKit/NSTextView`` - ``AppKit/NSTableView`` - ``AppKit/NSOutlineView`` +- ``AppKit/NSCollectionView`` - ``AppKit/NSMenuItem`` - ``AppKit/NSSplitViewItem`` - ``AppKit/NSTabViewController`` diff --git a/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift b/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift index e012402b8b..de2bf68e61 100644 --- a/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift +++ b/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift @@ -1,5 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) - import AppKit + public import AppKit /// Stands in as a collection view's delegate while a selection binding is in place, so that the /// binding hears of the user's selection changes, and passes every message on to the delegate diff --git a/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift b/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift index c9ba299748..71822920aa 100644 --- a/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift +++ b/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift @@ -1,6 +1,11 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit import AppKitNavigation + #if compiler(<6.4) + // NB: Swift 6.2 treats the models' 'Observable' conformances as public, and a public + // conformance needs a public import. + public import Observation + #endif import XCTest /// `observe` called on an object keeps its observation for as long as the object lives, and never @@ -19,7 +24,7 @@ _ = model.count recorder.record(isOwnerAlive: owner != nil) } - weak var releasedOwner = owner + weak let releasedOwner = owner owner = nil XCTAssertNil(releasedOwner, "The observation should not keep its object alive.") diff --git a/Tests/AppKitNavigationTests/OptionItemBindingTests.swift b/Tests/AppKitNavigationTests/OptionItemBindingTests.swift index b088fa3e5a..da1a65a927 100644 --- a/Tests/AppKitNavigationTests/OptionItemBindingTests.swift +++ b/Tests/AppKitNavigationTests/OptionItemBindingTests.swift @@ -1,6 +1,11 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit import AppKitNavigation + #if compiler(<6.4) + // NB: Swift 6.2 treats the models' 'Observable' conformances as public, and a public + // conformance needs a public import. + public import Observation + #endif import Testing /// Pop-up buttons and segmented controls make their items from the options they are bound to, From cd541fb3a0b88d259fd87ec9f8a4854ae415ba04 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:02:41 +0800 Subject: [PATCH 111/141] docs: propose an optional AppKitPlus trait that brings stack navigation to AppKit --- Documentations/Evolutions/README.md | 1 + .../draft-appkit-stack-navigation.md | 282 ++++++++++++++++++ Documentations/README.md | 1 + 3 files changed, 284 insertions(+) create mode 100644 Documentations/Evolutions/draft-appkit-stack-navigation.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index a10ea5ba34..c33141b8ab 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -16,3 +16,4 @@ | draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | In Progress | | draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | In Progress | | draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | In Progress | +| draft | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](draft-appkit-stack-navigation.md) | Draft | diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md new file mode 100644 index 0000000000..c9cb12276a --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -0,0 +1,282 @@ +# Draft - 可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit + +- **状态**: Draft +- **作者**: JH +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-09 +- **所属愿景**: 无 +- **关联提案**: [0005](0005-appkit-presentation-redesign.md)(弹出的共用生命周期)、[0004](0004-appkit-table-selection-bindings.md)(表格与大纲的选中绑定) +- **实现分支 / PR**: `appkit-stack-navigation` +- **配套文档**: 待定 —— 落地时判断要不要写打开 trait 的使用指南 + +## 摘要 + +给 AppKitNavigation 加一个默认关闭的 package trait `AppKitPlus`。打开后,AppKitNavigation 依赖 AppKitPlus-Release(0.21.0 起,只在 macOS 上),借它的 `NSNavigationController` 和 trait 机制,提供 UIKitNavigation 已有的四块能力: + +1. 路径驱动的栈 `NavigationStackController`,以及 `navigationDestination(for:destination:)`、`push(value:)`; +2. 按状态推入的 `navigationDestination(isPresented:)`、`navigationDestination(item:)`; +3. 让内容自己关掉的 `dismiss()`,对推入的内容和经 `present`、`sheet`、`modal`、`modalSession`、`popover` 弹出的内容都生效; +4. 直接接受 AppKitPlus 数据源的表格、大纲选中绑定。 + +trait 关闭时,包的依赖、最低系统(6.2 那份清单除外,见「影响」)和公开 API 都与现在一样。 + +## 动机 + +- **AppKit 没有导航控制器**,所以 AppKitNavigation 缺了 UIKitNavigation 的整块栈式导航:`NavigationStackController`、`push(value:)`、`navigationDestination(for:)`、`navigationDestination(isPresented:/item:)`,以及经 trait 传下去的 `push`、`dismiss` 两个动作。AppKit 案例列表里「Stack navigation」一组至今是注释掉的(`Examples/CaseStudies/AppKit/AppKitCaseStudies.swift`)。 +- **AppKitPlus 正好补上 UIKit 版依赖的两样东西**:一个导航控制器 `NSNavigationController`(移植自 OpenUXKit),和一套与 UIKit 同形的 trait 机制(`NSTraitDefinition`、`traitCollection`、`traitOverrides`)。 +- **内容没法统一地关掉自己。** 被弹出的内容现在只能由宿主改状态,或者按自己是怎么被弹出的去调用不同的 AppKit 方法(`dismiss(_:)`、`endSheet(_:)`、`stopModal()`……)。UIKit 版用一个 `traitCollection.dismiss()` 统一了这件事。 +- **用户自己的 App 在用 AppKitPlus。** 调查过依赖这个 fork 的 6 个 App:4 个依赖 AppKitPlus-Release;XCOrganizer 的内容列表用 AppKitPlus 的 `NSOutlineViewDiffableDataSource`,选中靠代理方法手写同步。没有 App 在用它的导航控制器——栈式导航是给以后用的新能力,不是替换现有的手写代码。 + +## 前期调研 + +- **AppKitPlus 的分发**:Objective-C 框架,经 `AppKitPlus-Release`(`https://github.com/AppKitSupportProgram/AppKitPlus-Release`)以二进制 xcframework 分发:`swift-tools-version: 5.9`、`.macOS(.v12)`、没有依赖、MIT 许可;README 写明不承诺 API 与 ABI 稳定,框架是动态库,要嵌进 App。 + - 要用的 API(`NSNavigationController`、`NSTraitDefinition` 与 `traitOverrides`、`NSOutlineViewDiffableDataSource`)从 0.1.1 起每个版本都有。 + - 0.20.0 删过 `NSNavigationItem` 的几个属性、不再公开 `NSTransitionController`;0.21.0 没有动这几块。 + - 下游 App 现在解析到 0.18 至 0.21。 +- **trait 守着的依赖**(UIFoundation 的提案 0017 在 Swift 6.2 上实测): + - trait 关闭时,只有 trait 用到的依赖不解析、不下载、不进 `Package.resolved`。这是 SwiftPM 6.2 起的行为(swift-package-manager 的 PR 8852,挑进 6.2 的 PR 8948);6.1 上没有验证。 + - trait 打开时,依赖方的清单必须声明 macOS 12 起,否则直接报错:`the library 'Probe' requires macos 10.15, but depends on the product 'AppKitPlus' which requires macos 12.0`。`@available` 和 `#if` 都绕不开。 +- **fork 的清单**:`Package.swift`(tools 6.4,macOS 12,有 trait);`Package@swift-6.2.swift`、`Package@swift-6.1.swift`(macOS 10.15,有 trait);`Package@swift-6.0.swift`(没有 trait)。只被部分 target 用的依赖,已经用 `.product(…, condition: .when(traits: […]))` 声明(CasePaths、CustomDump 等)。Xcode 27 读 `Package.swift`,Xcode 26.x(Swift 6.2、6.3)读 6.2 那份。 +- **在 Xcode 里开 trait**:Xcode 26.4 起可以在工程的 Package Dependencies 里给依赖打开 trait,`project.pbxproj` 记为 `traits = (…);`,本地和远程的包引用都支持(UIFoundation 的示例工程就这样开)。下游 App 打开 UIFoundation 的 `AppKitPlus` trait,都写在自己的 `Package.swift` 里。 +- **AppKitPlus 的 `NSNavigationController`**(`AppKitPlus/Navigation Controller/NSNavigationController.h`): + - `pushViewController(_:animated:)`、`popViewController(animated:)`、`popToViewController(_:animated:)`、`setViewControllers(_:animated:)`;动画只有一个 `BOOL`,没有完成回调,过渡进行中的请求会排队。 + - 用户返回有三条路:控制器自己导航栏里的返回按钮、⌘↑、触控板双指轻扫,都走 `popViewControllerAnimated:` 或 `popToViewController:animated:`。没有专门的「用户返回」回调;代理有 `willShow`、`didShow`(不带 `animated`)和否决用的 `shouldPop`。 + - 弹出控制器时调用 `willMove(toParent: nil)` 和 `removeFromParent()`,**从不调用 `didMove(toParent: nil)`**。UIKit 版正是靠后者得知用户返回的,这里要换一种办法。 + - 它已经在 `NSViewController` 上定义了 `navigationController` 和 `navigationItem`,这两个名字归它。 +- **UIKit 版怎么做的**(`Sources/UIKitNavigation/Navigation/`): + - `NavigationStackController` 继承 `UINavigationController`,`path` 是绑到 `Hashable` 元素集合或 `UINavigationPath` 的 `UIBinding`;在 `observe` 里比对路径与栈,推入、弹出或 `setViewControllers`;包一层代理,在 `didShow` 之后把路径截到栈上还在的那部分。 + - `push(value:)` 和 `dismiss` 经 trait(`traitOverrides`)传给子控制器。 + - `navigationDestination(item:)` 建在私有的 `destination(item:id:content:present:dismiss:)` 上,靠 shim 交换 `didMoveToParentViewController:` 得知用户返回。 +- **`UINavigationPath`** 定义在共用模块 `SwiftNavigation` 里(`Sources/SwiftNavigation/UINavigationPath.swift`),只依赖 Foundation,AppKit 可以直接用。 +- **0005 的弹出生命周期**(`Sources/AppKitNavigation/Navigation/BindingPresenter.swift`):`BindingPresenter` 加 `PresentationStyle`(`whenReady`、`begin(_:transaction:didEnd:)`、`end(_:transaction:)`),已经处理了 id 变化时先收起旧的、`onDismiss` 每次只调一次、用户关闭时写回 `nil`。推入可以作为一种新的 style 接进来。 + +## 提议方案 + +**trait 与依赖** + +- 新 trait `AppKitPlus`,默认关闭,只声明在 `Package.swift` 和 `Package@swift-6.2.swift` 里。6.2 那份的最低系统从 macOS 10.15 抬到 12;`Package@swift-6.1.swift`、`Package@swift-6.0.swift` 不动,这两个工具链用不了这批 API。 +- `AppKitNavigation` 加一个依赖:AppKitPlus-Release 0.21.0 起,条件是 macOS 且 trait 打开。 +- 新代码都放在 `AppKitNavigation` 里,用 `#if AppKitPlus` 包住。trait 关闭时,模块的公开 API 与现在完全一样。 + +**四块能力**(trait 打开后) + +1. **路径驱动的栈**:`NavigationStackController` 继承 AppKitPlus 的 `NSNavigationController`,`path` 绑到 `Hashable` 元素的集合或 `UINavigationPath`。`navigationDestination(for:destination:)` 登记每种元素对应的控制器;`push(value:)` 和 `traitCollection.push(value:)` 往路径上加元素。用户经返回按钮、⌘↑ 或轻扫返回后,路径截到栈上还在的部分。 +2. **按状态推入**:`NSViewController.navigationDestination(isPresented:)`、`navigationDestination(item:)` 等,形状与现有的 `present` 一样。状态有值时推入,变成 `nil` 时弹出,用户返回时写回 `nil`,id 变化时先弹出旧的再推入新的。作为一种新的 `PresentationStyle` 接进 `BindingPresenter`,`onDismiss` 的语义与其他弹出一致。 +3. **`dismiss()`**:`traitCollection.dismiss` 与 `traitCollection.isPresented`。推入的内容,以及经 `present`、`sheet`、`modal`、`modalSession`、`popover` 弹出的内容,在里面调用 `dismiss()` 就经它自己的 binding 关掉,与用户关闭一样写回、调用 `onDismiss`。 +4. **AppKitPlus 数据源的选中绑定**:`NSTableView` 接受 `NSTableViewDiffableReorderableDataSource`、`NSOutlineView` 接受 `NSOutlineViewDiffableDataSource` 的 `bind(selection:dataSource:)`,写法与 0004 的系统数据源版本一致。 + +**示例**:Examples 工程给本地的 fork 引用打开 `AppKitPlus` trait,恢复 AppKit 案例列表里的「Stack navigation」一组,照 UIKit 版补两个栈案例。 + +### 非目标 + +- 不支持 Swift 6.0、6.1 工具链。 +- 不做状态恢复和 deep link(UIKit 版也只写了 TODO)。 +- 不改 AppKitPlus 本身,它的已知限制照单接受。 +- trait 关闭时,不为栈式导航、`dismiss()` 和这些选中绑定提供任何替代实现。 +- 表格和大纲的多选不在这一批。 +- 不发版;下游 App 的迁移不在这一批。 + +## 详细设计 + +清单(`Package.swift` 与 `Package@swift-6.2.swift`): + +```swift +traits: [ + // ...the existing traits... + .trait( + name: "AppKitPlus", + description: "Stack navigation, dismiss actions and AppKitPlus data source bindings in AppKitNavigation." + ), +], +dependencies: [ + .package(url: "https://github.com/AppKitSupportProgram/AppKitPlus-Release", from: "0.21.0"), +], +// In the AppKitNavigation target's dependencies: +.product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) +), +``` + +调用点: + +```swift +// A stack driven by a path +let stackController = NavigationStackController(path: $model.path) { + ListViewController(model: model) +} +listViewController.navigationDestination(for: Planet.self) { planet in + PlanetViewController(planet: planet) +} +traitCollection.push(value: Planet.mars) + +// Pushing from optional state +navigationDestination(item: $model.detail) { detail in + DetailViewController(model: detail) +} + +// Content closing itself, whether it was pushed or presented +traitCollection.dismiss() + +// AppKitPlus data sources +outlineView.bind(selection: $model.selectedItemID, dataSource: outlineDataSource) +``` + +签名(都只在 `#if AppKitPlus` 时存在): + +```swift +open class NavigationStackController: NSNavigationController { + public required init( + navigationBarClass: AnyClass? = nil, + toolbarClass: AnyClass? = nil, + path: UIBinding, + root: () -> NSViewController + ) where Data.Element: Hashable + + public required init( + navigationBarClass: AnyClass? = nil, + toolbarClass: AnyClass? = nil, + path: UIBinding, + root: () -> NSViewController + ) +} + +extension NSViewController { + public func navigationDestination( + for data: Element.Type, + destination: @escaping (Element) -> NSViewController + ) + + public func push(value: Element) + + @discardableResult + public func navigationDestination( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken + + @discardableResult + public func navigationDestination( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken + + // Plus the item:id: shape and the two shapes whose content takes a UIBinding, + // the same five shapes present(...) has, the UIBinding ones @_disfavoredOverload. +} + +@MainActor +public struct AppKitPushAction: Sendable { + public func callAsFunction( + value: Element, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) +} + +@MainActor +public struct AppKitDismissAction: Sendable { + public func callAsFunction() +} + +extension NSTraitCollection { + public var push: AppKitPushAction { get } + public var dismiss: AppKitDismissAction { get } + public var isPresented: Bool { get } +} + +extension NSTableView { + @discardableResult + public func bind( + selection: UIBinding, + dataSource: NSTableViewDiffableReorderableDataSource + ) -> ObserveToken +} + +extension NSOutlineView { + @discardableResult + public func bind( + selection: UIBinding, + dataSource: NSOutlineViewDiffableDataSource + ) -> ObserveToken +} +``` + +几处设计要点: + +- **命名**:两个动作类型照库里 AppKit 专属类型的叫法(`AppKitAnimation`、`AppKitTextSelection`),叫 `AppKitPushAction`、`AppKitDismissAction`,对应 UIKit 的 `UIPushAction`、`UIDismissAction`。控制器照 UIKit 版叫 `NavigationStackController`。 +- **动画**:推入和弹出默认带动画;当前事务的 `appKit.disablesAnimations` 为真时不带,与 popover 的做法一致。 +- **得知用户返回**:AppKitPlus 不发 `didMove(toParent: nil)`。路径驱动的栈像 UIKit 版一样包一层代理,在 `didShow` 之后比对栈与路径。按状态推入的内容可能在任意 `NSNavigationController` 里,不能占用它的代理:实现时先用测试确认 AppKitPlus 弹出控制器时 `willMove(toParent:)`、`removeFromParent()`、视图离开窗口的先后,再决定从哪一处得知,结论记进决策日志。 +- **`dismiss` 怎么传下去**:内容显示之前,在它的 `traitOverrides` 里放一个 `dismiss` 动作,调用时走 `BindingPresenter` 里「用户关闭」那条路——写回 `nil`(身份仍匹配时),收起内容,离屏后调用 `onDismiss`。视图控制器放在它自己身上;窗口与存取面板放在窗口的内容视图控制器上,没有的话放在内容视图上;alert 没有可供调用的地方,不放。 +- **选中绑定**:转调 0004 的 `bind(selection:row:itemIdentifier:)`。AppKitPlus 大纲数据源的 `row(forItemIdentifier:)` 在项不可见时返回 `-1` 而不是 `nil`,转调时换成 `nil`。 + +## 替代方案考量 + +- **另开一个包**(同时依赖 fork 和 AppKitPlus-Release):fork 的清单一行不改;但按状态推入和 `dismiss` 要用 `BindingPresenter` 等内部机制,得把它们作为 SPI 公开,两个包的版本也要一直对齐。用户选了 trait。 +- **trait 只放进 `Package.swift`**:其余清单与上游一致,但 Xcode 26.x 用不了。用户选了 6.4 和 6.2 两份。 +- **连 `Package@swift-6.1.swift` 也加**:6.1 在 trait 关闭时是否仍会解析、钉住 AppKitPlus 没有验证,可能让所有用 6.1 的使用方都去拉一个用不到的二进制包。不做。 +- **自己写一个 AppKit 导航控制器**:返回按钮、轻扫手势、过渡动画都要从头写,AppKitPlus 已有成熟实现。不做。 +- **`dismiss()` 只管推入**:与 UIKit 版不一致,弹出的内容仍要按弹出方式各写各的关闭。用户选了推入和弹出都管。 +- **AppKitPlus 从 0.18.0 或 0.20.0 起**:能少让下游升级,但要另外编译验证旧版本,实现还得避开 0.20 改过的 API。用户选了 0.21.0。 +- **照 UIKit 版交换 `didMoveToParentViewController:`**:AppKitPlus 从不在弹出时发这个回调,换了也收不到。 + +## 影响 + +### 源码兼容性(source compatibility) + +- **纯新增**。trait 关闭时公开 API 不变;打开时只新增上面列出的类型和方法。 +- 打开 trait 后,AppKitPlus 加在系统类上的成员(例如 `NSViewController.navigationController`、`navigationItem`)在 import 了 AppKitNavigation 的文件里也可见,可能与 App 自己的同名扩展冲突。只影响打开了 trait 的使用方。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库:`AppKitNavigation` 多一个条件依赖;`AppKitNavigationTests` 多一组只在 trait 打开时编译的测试;Examples 工程打开 trait、多依赖 AppKitPlus-Release。 +- **`Package@swift-6.2.swift` 的最低系统抬到 macOS 12,不论 trait 开没开都生效**:用 Xcode 26.x 的使用方,部署目标低于 macOS 12 时会编不过。依赖这个 fork 的 App 部署目标都在 macOS 14 以上,不受影响。 +- 下游 App 要用这批 API,要在自己的 `Package.swift` 里打开 trait;XCOrganizer(AppKitPlus 0.18)和 PrivateSymbols(0.19)打开时,AppKitPlus 要一起升到 0.21。不打开就没有任何变化。 + +### 文档与示例 + +- DocC 首页加一组「栈式导航」(注明需要打开 `AppKitPlus` trait),登记新类型与新方法;生成文档时打开 trait。 +- `swift-navigation-bindings` skill 补上栈式导航、`dismiss()` 和新的选中绑定。 +- Examples:恢复 AppKit 案例列表里的「Stack navigation」一组,补两个栈案例。 + +## API 演进与废弃策略 + +- 没有被替代的旧 API,不需要废弃期。 +- 纯新增,fork 下次发版按 minor 处理;这一批不发版。 + +## 落地步骤 + +1. **trait 与依赖**:两份清单加 trait 和依赖,6.2 那份抬到 macOS 12。trait 关闭、打开各编译一次 AppKitNavigation,确认关闭时不解析 AppKitPlus。 +2. **路径驱动的栈**:`NavigationStackController`、`navigationDestination(for:destination:)`、`push(value:)`、`traitCollection.push`。先写测试:改路径时推入、弹出;用户返回后路径被截短。 +3. **按状态推入**:推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 +4. **`dismiss()`**:`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 +5. **AppKitPlus 数据源的选中绑定**:两个 `bind(selection:dataSource:)`,各配双向测试。 +6. **示例**:Examples 工程打开 trait,恢复「Stack navigation」一组,补两个案例;CaseStudies 的 macOS 版只编译,不点界面。 +7. **文档与验证**:DocC 首页与 skill;判断要不要写打开 trait 的使用指南。Xcode 27.2 跑 AppKit 的全部测试,trait 关闭、打开各一次;Xcode 26.6 在 trait 打开时编译库和 AppKit 测试。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 有「从 API 签名看不出来的调用方契约」就写使用指南;有「下次维护会踩、代码本身看不出来的决策」就写实现说明。写了就登记到头部的「配套文档」。 +- **有没有引入新术语** —— 有就同批次登记进术语表。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-09 | Created as Draft | 调查下游 App 时,用户提出可选地集成 AppKitPlus,并把 UIKit 的栈式导航搬到 AppKit;属于完整档,先经三轮澄清提问 | +| 2026-11-09 | 用 package trait 集成,不另开一个包 | 用户选定。同一个包里能直接复用 `BindingPresenter` 等内部机制,不必公开 SPI;做法与 UIFoundation 的 `AppKitPlus` trait 一致 | +| 2026-11-09 | 搬四块:路径驱动的栈、按状态推入、`dismiss()`、AppKitPlus 数据源的选中绑定 | 用户选定 | +| 2026-11-09 | trait 只放进 `Package.swift` 和 `Package@swift-6.2.swift`,后者抬到 macOS 12 | 用户选定。覆盖 Xcode 27 与 Xcode 26.x;6.1 在 trait 关闭时的行为没有验证,不加 | +| 2026-11-09 | `dismiss()` 对推入的内容和现有五种弹出的内容都生效 | 用户选定,与 UIKit 版一致 | +| 2026-11-09 | Examples 打开 trait,补两个栈案例 | 用户选定 | +| 2026-11-09 | AppKitPlus-Release 从 0.21.0 起 | 用户选定,只承诺测过的版本 | +| 2026-11-09 | 代码放在 AppKitNavigation 里用 `#if AppKitPlus` 包住;类型照 UIKit 版命名;路径支持集合和 `UINavigationPath`;推入动画跟随事务;选中绑定覆盖大纲与可重排表格两种数据源 | 提问时补上的默认做法,用户确认 | diff --git a/Documentations/README.md b/Documentations/README.md index 4938c63a4a..a724affeed 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -15,6 +15,7 @@ - [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(In Progress)。 - [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(In Progress)。 - [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(In Progress)。 +- [draft-appkit-stack-navigation.md](Evolutions/draft-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit(Draft)。 ## Internal From 9d573dd0f25ad03fad265ea4a37e877ce9e55f0d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:04:25 +0800 Subject: [PATCH 112/141] docs: accept the AppKit stack navigation proposal --- Documentations/Evolutions/README.md | 2 +- Documentations/Evolutions/draft-appkit-stack-navigation.md | 3 ++- Documentations/README.md | 2 +- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index c33141b8ab..9fa48647d7 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -16,4 +16,4 @@ | draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | In Progress | | draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | In Progress | | draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | In Progress | -| draft | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](draft-appkit-stack-navigation.md) | Draft | +| draft | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](draft-appkit-stack-navigation.md) | Accepted | diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index c9cb12276a..0d4f9bb6c9 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -1,6 +1,6 @@ # Draft - 可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit -- **状态**: Draft +- **状态**: Accepted - **作者**: JH - **创建日期**: 2026-11-09 - **最后更新**: 2026-11-09 @@ -280,3 +280,4 @@ extension NSOutlineView { | 2026-11-09 | Examples 打开 trait,补两个栈案例 | 用户选定 | | 2026-11-09 | AppKitPlus-Release 从 0.21.0 起 | 用户选定,只承诺测过的版本 | | 2026-11-09 | 代码放在 AppKitNavigation 里用 `#if AppKitPlus` 包住;类型照 UIKit 版命名;路径支持集合和 `UINavigationPath`;推入动画跟随事务;选中绑定覆盖大纲与可重排表格两种数据源 | 提问时补上的默认做法,用户确认 | +| 2026-11-09 | Accepted | 用户批准。排在绑定和动画两份提案之后实现,做完在本地合进 `main`、不推送 | diff --git a/Documentations/README.md b/Documentations/README.md index a724affeed..7277572fd3 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -15,7 +15,7 @@ - [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(In Progress)。 - [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(In Progress)。 - [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(In Progress)。 -- [draft-appkit-stack-navigation.md](Evolutions/draft-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit(Draft)。 +- [draft-appkit-stack-navigation.md](Evolutions/draft-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit(Accepted)。 ## Internal From 63bcfbfe409eb33e96a9eea5dc11b4649bb34ec0 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:38:46 +0800 Subject: [PATCH 113/141] build: add an optional AppKitPlus trait to AppKitNavigation --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-stack-navigation.md | 5 +++-- Documentations/README.md | 2 +- Package.swift | 16 ++++++++++++++++ Package@swift-6.2.swift | 18 +++++++++++++++++- 5 files changed, 38 insertions(+), 5 deletions(-) diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 9fa48647d7..702adf2793 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -16,4 +16,4 @@ | draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | In Progress | | draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | In Progress | | draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | In Progress | -| draft | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](draft-appkit-stack-navigation.md) | Accepted | +| draft | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](draft-appkit-stack-navigation.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index 0d4f9bb6c9..bbee45f194 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -1,6 +1,6 @@ # Draft - 可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit -- **状态**: Accepted +- **状态**: In Progress - **作者**: JH - **创建日期**: 2026-11-09 - **最后更新**: 2026-11-09 @@ -255,7 +255,7 @@ extension NSOutlineView { ## 落地步骤 -1. **trait 与依赖**:两份清单加 trait 和依赖,6.2 那份抬到 macOS 12。trait 关闭、打开各编译一次 AppKitNavigation,确认关闭时不解析 AppKitPlus。 +1. **trait 与依赖**(已完成):两份清单加 trait 和依赖,6.2 那份抬到 macOS 12。trait 关闭、打开各编译一次 AppKitNavigation,确认关闭时不解析 AppKitPlus。 2. **路径驱动的栈**:`NavigationStackController`、`navigationDestination(for:destination:)`、`push(value:)`、`traitCollection.push`。先写测试:改路径时推入、弹出;用户返回后路径被截短。 3. **按状态推入**:推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 4. **`dismiss()`**:`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 @@ -281,3 +281,4 @@ extension NSOutlineView { | 2026-11-09 | AppKitPlus-Release 从 0.21.0 起 | 用户选定,只承诺测过的版本 | | 2026-11-09 | 代码放在 AppKitNavigation 里用 `#if AppKitPlus` 包住;类型照 UIKit 版命名;路径支持集合和 `UINavigationPath`;推入动画跟随事务;选中绑定覆盖大纲与可重排表格两种数据源 | 提问时补上的默认做法,用户确认 | | 2026-11-09 | Accepted | 用户批准。排在绑定和动画两份提案之后实现,做完在本地合进 `main`、不推送 | +| 2026-11-09 | trait 关闭时实测不解析 AppKitPlus;打开时要连默认 trait 一起写 | `swift build` 不带 trait 时,`Package.resolved` 里没有 AppKitPlus。`--traits AppKitPlus` 会关掉默认 trait,`Perception` 一关,`observe` 就要求 macOS 14,AppKitNavigation 编不过;使用方在 `Package.swift` 里要写 `traits: [.defaults, "AppKitPlus"]`,写进文档 | diff --git a/Documentations/README.md b/Documentations/README.md index 7277572fd3..8c80e540da 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -15,7 +15,7 @@ - [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(In Progress)。 - [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(In Progress)。 - [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(In Progress)。 -- [draft-appkit-stack-navigation.md](Evolutions/draft-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit(Accepted)。 +- [draft-appkit-stack-navigation.md](Evolutions/draft-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit(In Progress)。 ## Internal diff --git a/Package.swift b/Package.swift index 94c9bb185f..b9f2e28866 100644 --- a/Package.swift +++ b/Package.swift @@ -56,8 +56,14 @@ let package = Package( name: "Sharing", description: "Derive bindings from '@Shared' state" ), + .trait( + name: "AppKitPlus", + description: + "Stack navigation, dismiss actions and AppKitPlus data source bindings in AppKitNavigation, built on AppKitPlus" + ), ], dependencies: [ + .package(url: "https://github.com/AppKitSupportProgram/AppKitPlus-Release", from: "0.21.0"), .package(url: "https://github.com/pointfreeco/swift-case-paths", from: "1.10.0"), .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-issue-reporting", from: "2.1.0"), @@ -188,6 +194,11 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), ] ), .target( @@ -204,6 +215,11 @@ let package = Package( name: "AppKitNavigationTests", dependencies: [ "AppKitNavigation", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), .product(name: "IssueReportingTestSupport", package: "swift-issue-reporting"), ] ), diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift index b7e08743af..9e0611e2de 100644 --- a/Package@swift-6.2.swift +++ b/Package@swift-6.2.swift @@ -13,7 +13,7 @@ let package = Package( name: "swift-navigation", platforms: [ .iOS(.v13), - .macOS(.v10_15), + .macOS(.v12), .tvOS(.v13), .watchOS(.v6), ], @@ -56,8 +56,14 @@ let package = Package( name: "Sharing", description: "Derive bindings from '@Shared' state" ), + .trait( + name: "AppKitPlus", + description: + "Stack navigation, dismiss actions and AppKitPlus data source bindings in AppKitNavigation, built on AppKitPlus" + ), ], dependencies: [ + .package(url: "https://github.com/AppKitSupportProgram/AppKitPlus-Release", from: "0.21.0"), .package(url: "https://github.com/pointfreeco/swift-case-paths", from: "1.10.0"), .package(url: "https://github.com/pointfreeco/swift-custom-dump", from: "1.3.2"), .package(url: "https://github.com/pointfreeco/swift-macro-testing", from: "0.6.0"), @@ -195,6 +201,11 @@ let package = Package( dependencies: [ "SwiftNavigation", "AppKitNavigationShim", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), ] ), .target( @@ -204,6 +215,11 @@ let package = Package( name: "AppKitNavigationTests", dependencies: [ "AppKitNavigation", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), ] ), From 535bcaa237abab85b3eae5b5f0eec74447208e24 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:48:17 +0800 Subject: [PATCH 114/141] feat(appkit): add a path-driven NavigationStackController on top of AppKitPlus --- .../draft-appkit-stack-navigation.md | 6 +- .../AppKitNavigation/Navigation/Dismiss.swift | 86 +++ .../NavigationStackController.swift | 502 ++++++++++++++++++ .../AppKitNavigation/Navigation/Push.swift | 93 ++++ .../NavigationStackControllerTests.swift | 153 ++++++ 5 files changed, 839 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Navigation/Dismiss.swift create mode 100644 Sources/AppKitNavigation/Navigation/NavigationStackController.swift create mode 100644 Sources/AppKitNavigation/Navigation/Push.swift create mode 100644 Tests/AppKitNavigationTests/NavigationStackControllerTests.swift diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index bbee45f194..85aeabc506 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -256,7 +256,7 @@ extension NSOutlineView { ## 落地步骤 1. **trait 与依赖**(已完成):两份清单加 trait 和依赖,6.2 那份抬到 macOS 12。trait 关闭、打开各编译一次 AppKitNavigation,确认关闭时不解析 AppKitPlus。 -2. **路径驱动的栈**:`NavigationStackController`、`navigationDestination(for:destination:)`、`push(value:)`、`traitCollection.push`。先写测试:改路径时推入、弹出;用户返回后路径被截短。 +2. **路径驱动的栈**(已完成):`NavigationStackController`、`navigationDestination(for:destination:)`、`push(value:)`、`traitCollection.push`。先写测试:改路径时推入、弹出;用户返回后路径被截短。 3. **按状态推入**:推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 4. **`dismiss()`**:`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 5. **AppKitPlus 数据源的选中绑定**:两个 `bind(selection:dataSource:)`,各配双向测试。 @@ -282,3 +282,7 @@ extension NSOutlineView { | 2026-11-09 | 代码放在 AppKitNavigation 里用 `#if AppKitPlus` 包住;类型照 UIKit 版命名;路径支持集合和 `UINavigationPath`;推入动画跟随事务;选中绑定覆盖大纲与可重排表格两种数据源 | 提问时补上的默认做法,用户确认 | | 2026-11-09 | Accepted | 用户批准。排在绑定和动画两份提案之后实现,做完在本地合进 `main`、不推送 | | 2026-11-09 | trait 关闭时实测不解析 AppKitPlus;打开时要连默认 trait 一起写 | `swift build` 不带 trait 时,`Package.resolved` 里没有 AppKitPlus。`--traits AppKitPlus` 会关掉默认 trait,`Perception` 一关,`observe` 就要求 macOS 14,AppKitNavigation 编不过;使用方在 `Package.swift` 里要写 `traits: [.defaults, "AppKitPlus"]`,写进文档 | +| 2026-11-09 | `push`、`dismiss` 两个动作装进 `NSObject` 盒子再放进 trait | AppKitPlus 的 trait 存储只认对象:结构体值经 `as? any NSObjectProtocol` 变成 `nil`,写进去等于没写(探针实测) | +| 2026-11-09 | 栈控制器的 `delegate` 读到的是转发代理,不像 UIKit 版那样返回 App 的委托 | AppKitPlus 内部经 `delegate` 属性取委托,getter 若返回 App 的委托,路径代理就被绕过,用户返回时路径不会截短(探针实测)。App 设的委托排在代理后面,所有消息照转 | +| 2026-11-09 | 栈控制器重写 `init(nibName:bundle:)` 并标为不可用 | AppKitPlus 的 `init(navigationBarClass:toolbarClass:)` 内部经它初始化,Swift 子类不实现就会在运行时崩溃 | +| 2026-11-09 | 视图加载时第一次按路径摆放控制器不带动画 | 那时没有可以过渡的画面;测试里这次动画也收不了尾,后面的推入弹出都排在它后面 | diff --git a/Sources/AppKitNavigation/Navigation/Dismiss.swift b/Sources/AppKitNavigation/Navigation/Dismiss.swift new file mode 100644 index 0000000000..e48476bd1f --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Dismiss.swift @@ -0,0 +1,86 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + import AppKit + public import AppKitPlus + import SwiftNavigation + + extension NSTraitCollection { + /// Dismisses the content this trait collection belongs to, through the binding that showed it. + /// + /// Content that a binding pushed onto a ``NavigationStackController``, or showed with + /// `navigationDestination`, `present`, `sheet`, `modal`, `modalSession` or `popover`, can + /// close itself without knowing how it was shown: + /// + /// ```swift + /// let doneButton = NSButton(title: "Done", target: nil, action: nil) + /// doneButton.addAction { [weak self] _ in + /// self?.traitCollection.dismiss() + /// } + /// ``` + /// + /// The content ends as if the user had closed it: the binding is set to `nil`, and the + /// presentation's `onDismiss` runs once the content has left the screen. Content that was not + /// shown through a binding reports an issue instead. + /// + /// Available with the `AppKitPlus` package trait. + public var dismiss: AppKitDismissAction { + self[DismissActionTrait.self]?.action ?? AppKitDismissAction(run: nil) + } + + /// Whether the content this trait collection belongs to was shown through a binding, and so + /// can ``dismiss`` itself. + /// + /// Available with the `AppKitPlus` package trait. + public var isPresented: Bool { dismiss.run != nil } + } + + /// Dismisses content that a binding showed. + /// + /// You will not typically refer to this type directly. Read it from a trait collection, as + /// ``AppKitPlus/NSTraitCollection/dismiss``, and call it as a function. + /// + /// Available with the `AppKitPlus` package trait. + @MainActor + public struct AppKitDismissAction: Sendable { + let run: (@MainActor @Sendable (UITransaction) -> Void)? + + /// Dismisses the content, through the binding that showed it. + public func callAsFunction() { + guard let run else { + reportIssue( + """ + Content requested dismissal, but couldn't be dismissed. + + 'NSTraitCollection.dismiss()' must be called from content that a binding showed, for \ + example with 'NSViewController.present(item:)' or \ + 'NSViewController.navigationDestination(item:)'. + """ + ) + return + } + run(.current) + } + } + + /// Carries a dismiss action through AppKitPlus's trait storage, which keeps only objects: a + /// value that is not one is stored as no value at all. + final class DismissActionBox: NSObject, @unchecked Sendable { + // NB: Unchecked, since the box never changes once made, and the action is sendable. + let action: AppKitDismissAction + + init(_ action: AppKitDismissAction) { + self.action = action + } + } + + enum DismissActionTrait: NSTraitDefinition { + static var defaultValue: DismissActionBox? { nil } + static var identifier: String { "AppKitNavigation.DismissAction" } + } + + extension NSMutableTraits { + var dismiss: AppKitDismissAction { + get { self[DismissActionTrait.self]?.action ?? AppKitDismissAction(run: nil) } + set { self[DismissActionTrait.self] = newValue.run == nil ? nil : DismissActionBox(newValue) } + } + } +#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationStackController.swift b/Sources/AppKitNavigation/Navigation/NavigationStackController.swift new file mode 100644 index 0000000000..32a86a2d92 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationStackController.swift @@ -0,0 +1,502 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + public import AppKit + public import AppKitPlus + public import SwiftNavigation + + /// A navigation controller that manages a stack of view controllers, driven by a path binding. + /// + /// The AppKit counterpart of SwiftUI's `NavigationStack`, built on AppKitPlus's + /// `NSNavigationController`. The path holds data, not view controllers: register how each type + /// of data is shown with ``AppKit/NSViewController/navigationDestination(for:destination:)``, + /// and the controller pushes and pops view controllers as the path changes. + /// + /// ```swift + /// let stackController = NavigationStackController(path: $model.path) { + /// PlanetListViewController(model: model) + /// } + /// + /// // In PlanetListViewController.viewDidLoad(): + /// navigationDestination(for: Planet.self) { planet in + /// PlanetViewController(planet: planet) + /// } + /// ``` + /// + /// When the user goes back — with the back button, ⌘↑ or a swipe — the path loses the elements + /// whose view controllers were popped. Pushes and pops are animated unless the change happens in + /// a transaction that disables animations. + /// + /// Available with the `AppKitPlus` package trait. + #if !Perception + @available(macOS 14, *) + #endif + @MainActor + open class NavigationStackController: NSNavigationController { + fileprivate var destinations: + [DestinationType: (UINavigationPath.Element) -> (NSViewController, AnyHashable)?] = [:] + @UIBinding fileprivate var path: [UINavigationPath.Element] = [] + private let pathDelegate = PathDelegate() + private var root: NSViewController? + private var hasAppliedPath = false + + /// The navigation controller's delegate. + /// + /// The stack controller keeps a proxy in front of the delegate you set, so that it learns of the + /// view controllers the user pops; the proxy passes every message on to your delegate. Reading + /// this property returns the proxy. + // NB: AppKitPlus reads its delegate through this property, so the getter has to hand it the + // proxy. Setting the delegate again makes AppKitPlus ask the proxy afresh which messages + // it answers. + open override weak var delegate: (any NSNavigationControllerDelegate)? { + get { super.delegate } + set { + pathDelegate.base = newValue + super.delegate = nil + super.delegate = pathDelegate + } + } + + /// Creates a navigation stack controller whose stack follows a collection of hashable data. + /// + /// - Parameters: + /// - navigationBarClass: A custom navigation bar class, or `nil` for the default one. + /// - toolbarClass: A custom toolbar class, or `nil` for the default one. + /// - path: A binding to the data the stack shows, above the root view controller. + /// - root: The view controller at the bottom of the stack. + public required init( + navigationBarClass: AnyClass? = nil, + toolbarClass: AnyClass? = nil, + path: UIBinding, + root: () -> NSViewController + ) where Data.Element: Hashable { + super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass) + super.delegate = pathDelegate + self._path = path.path + let root = root() + self.root = root + self.viewControllers = [root] + } + + /// Creates a navigation stack controller whose stack follows a type-erased path. + /// + /// - Parameters: + /// - navigationBarClass: A custom navigation bar class, or `nil` for the default one. + /// - toolbarClass: A custom toolbar class, or `nil` for the default one. + /// - path: A binding to the path the stack shows, above the root view controller. + /// - root: The view controller at the bottom of the stack. + public required init( + navigationBarClass: AnyClass? = nil, + toolbarClass: AnyClass? = nil, + path: UIBinding, + root: () -> NSViewController + ) { + super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass) + super.delegate = pathDelegate + self._path = path.elements + let root = root() + self.root = root + self.viewControllers = [root] + } + + // NB: AppKitPlus's 'init(navigationBarClass:toolbarClass:)' goes through + // 'init(nibName:bundle:)', so a subclass has to implement it. It is not for calling: a + // stack controller needs a path. + @available(*, unavailable) + public override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + open override func viewDidLoad() { + super.viewDidLoad() + + traitOverrides.push = AppKitPushAction { [weak self] value in + self?._push(value: value) + } + + observe { [weak self] transaction in + guard let self else { return } + + // NB: The path first applies while the view loads, when there is nothing to animate from. + let animated = hasAppliedPath && !transaction.appKit.disablesAnimations + hasAppliedPath = true + let newPath = path + + let difference = newPath.difference(from: viewControllers.compactMap(\.navigationID)) + + guard !difference.isEmpty else { + if viewControllers.isEmpty, let root { + setViewControllers([root], animated: animated) + } + return + } + + if difference.count == 1, + case .insert(newPath.count - 1, let navigationID, nil) = difference.first, + let viewController = viewController(for: navigationID) + { + pushViewController(viewController, animated: animated) + } else if difference.count == 1, + case .remove(newPath.count, _, nil) = difference.first + { + popViewController(animated: animated) + } else if difference.insertions.isEmpty, newPath.isEmpty { + popToRootViewController(animated: animated) + } else if difference.insertions.isEmpty, + case let offsets = difference.removals.map(\.offset), + let first = offsets.first, + let last = offsets.last, + offsets.elementsEqual(first...last), + first == newPath.count + { + popToViewController(viewControllers[first], animated: animated) + } else { + var newPath = newPath + let oldViewControllers = + viewControllers.isEmpty + ? root.map { [$0] } ?? [] + : viewControllers + var newViewControllers: [NSViewController] = [] + newViewControllers.reserveCapacity(max(viewControllers.count, newPath.count)) + + loop: for viewController in oldViewControllers { + if let navigationID = viewController.navigationID { + guard navigationID == newPath.first + else { + break loop + } + newViewControllers.append(viewController) + newPath.removeFirst() + } else { + newViewControllers.append(viewController) + } + } + var invalidIndices: [Int] = [] + var didPushNewViewController = false + for (index, navigationID) in newPath.enumerated() { + if let viewController = + viewControllers + .first(where: { $0.navigationID == navigationID }) + { + newViewControllers.append(viewController) + } else if let viewController = viewController(for: navigationID) { + newViewControllers.append(viewController) + didPushNewViewController = true + } else if case .lazy(.element) = navigationID, + !didPushNewViewController, + let elementType = navigationID.elementType + { + reportIssue( + """ + No "navigationDestination(for: \(typeName(elementType))) { … }" was found among \ + the view controllers on the path. + """ + ) + invalidIndices.append(index) + } + } + for invalidIndex in invalidIndices.reversed() { + path.remove(at: invalidIndex) + } + setViewControllers(newViewControllers, animated: animated) + } + } + } + + fileprivate func viewController( + for navigationID: UINavigationPath.Element + ) -> NSViewController? { + guard + let destinationType = navigationID.elementType, + let destination = destinations[DestinationType(destinationType)], + let (viewController, element) = destination(navigationID) + else { + return nil + } + viewController.navigationID = .eager(element) + viewController.traitOverrides.dismiss = AppKitDismissAction { + [weak self, weak viewController] transaction in + guard let self, let viewController else { return } + popFromViewController(viewController, animated: !transaction.appKit.disablesAnimations) + } + return viewController + } + + fileprivate struct DestinationType: Hashable { + let rawValue: Any.Type + init(_ rawValue: Any.Type) { + self.rawValue = rawValue + } + static func == (lhs: Self, rhs: Self) -> Bool { + lhs.rawValue == rhs.rawValue + } + func hash(into hasher: inout Hasher) { + hasher.combine(ObjectIdentifier(rawValue)) + } + } + + /// Stands in as the navigation controller's delegate, so that the path learns of the + /// view controllers the user pops, and passes every message on to the delegate the app set. + /// + /// AppKitPlus's navigation controller has no callback for a pop the user makes; showing the + /// view controller below is the only sign of it. + @MainActor + private final class PathDelegate: NSObject, NSNavigationControllerDelegate { + // NB: Read by the Objective-C runtime's forwarding, which is not isolated. The navigation + // controller only messages its delegate on the main thread. + nonisolated(unsafe) weak var base: (any NSNavigationControllerDelegate)? + + nonisolated override func responds(to selector: Selector!) -> Bool { + selector == #selector(PathDelegate.navigationController(_:didShow:)) + || (base?.responds(to: selector) ?? false) + } + + nonisolated override func forwardingTarget(for selector: Selector!) -> Any? { + base + } + + func navigationController( + _ navigationController: NSNavigationController, + didShow viewController: NSViewController + ) { + defer { + base?.navigationController?(navigationController, didShow: viewController) + } + guard let navigationController = navigationController as? NavigationStackController + else { return } + if let nextIndex = navigationController.path.firstIndex(where: { + guard case .lazy = $0 else { return false } + return true + }) { + let nextElement = navigationController.path[nextIndex] + let hasSeenDestinationType = + nextElement.elementType + .map { navigationController.destinations.keys.contains(DestinationType($0)) } + ?? false + guard hasSeenDestinationType + else { + reportIssue( + """ + Failed to decode item in navigation path at index \(nextIndex). Perhaps the \ + "navigationDestination" declarations have changed since the path was encoded? + """ + ) + if let elementType = nextElement.elementType { + reportIssue( + """ + Missing navigation destination while decoding a "UINavigationPath". No \ + "navigationDestination(for: \(typeName(elementType))) { … }" was found among the \ + view controllers on the path. + """ + ) + } + navigationController.path.removeSubrange(nextIndex...) + return + } + + switch navigationController.path[nextIndex] { + case .lazy(.element(let element)): + navigationController.path[nextIndex] = .eager(element) + + case .eager, .lazy(.codable): + fallthrough + + @unknown default: break + } + return + } + DispatchQueue.main.async { + let oldPath = navigationController.path.filter { + guard case .eager = $0 else { return false } + return true + } + let newPath = navigationController.viewControllers.compactMap(\.navigationID) + if oldPath.count > newPath.count { + navigationController.path = newPath + } + } + } + } + } + + extension NSViewController { + /// Pushes a value onto the current navigation stack controller's path. + /// + /// Outside a ``NavigationStackController``, the push is reported as an issue instead. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameter value: The value to push. + #if !Perception + @available(macOS 14, *) + #endif + public func push(value: Element) { + _push(value: value) + } + + #if !Perception + @available(macOS 14, *) + #endif + fileprivate func _push(value: Element) { + guard let navigationController = navigationController ?? self as? NSNavigationController + else { + reportIssue( + """ + Can't push value: "navigationController" is "nil". + """ + ) + return + } + guard let stackController = navigationController as? NavigationStackController + else { + reportIssue( + """ + Tried to push a value to a non-"NavigationStackController". + """ + ) + return + } + stackController.path.append(.lazy(.element(value))) + } + + /// Registers the view controller that the enclosing ``NavigationStackController`` shows for + /// each element of a type on its path. + /// + /// Call it from a view controller already in the stack, typically the root's `viewDidLoad`, + /// or on the stack controller itself. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - data: The type of data this destination shows. + /// - destination: Makes the view controller for an element of the path. + #if !Perception + @available(macOS 14, *) + #endif + public func navigationDestination( + for data: Element.Type, + destination: @escaping (Element) -> NSViewController + ) { + guard let navigationController = navigationController ?? self as? NSNavigationController + else { + reportIssue( + """ + Can't register navigation destination: "navigationController" is "nil". + """ + ) + return + } + guard let stackController = navigationController as? NavigationStackController + else { + reportIssue( + """ + Tried to apply a "navigationDestination" to a non-"NavigationStackController". + """ + ) + return + } + + stackController.destinations[NavigationStackController.DestinationType(data)] = { + [weak stackController] element in + guard let stackController else { return nil } + + switch element { + case .eager(let value), .lazy(.element(let value)): + return (destination(value as! Element), value) + case .lazy(.codable(let value)): + let index = stackController.path.firstIndex(of: element)! + guard let value = value.decode() + else { + reportIssue( + """ + Failed to decode item in navigation path at index \(index). Perhaps the \ + "navigationDestination" declarations have changed since the path was encoded? + """ + ) + stackController.path.remove(at: index) + return nil + } + return (destination(value as! Element), value) + @unknown default: return nil + } + } + func resolvePath() { + if stackController.path.contains(where: { + guard case .lazy = $0, $0.elementType == Element.self else { return false } + return true + }) { + stackController.path = stackController.path + } + } + #if DEBUG + skippingPerceptionChecking { + resolvePath() + } + #else + resolvePath() + #endif + } + + fileprivate var navigationID: UINavigationPath.Element? { + get { + objc_getAssociatedObject(self, navigationIDKey) as? UINavigationPath.Element + } + set { + objc_setAssociatedObject(self, navigationIDKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + } + + extension NSNavigationController { + /// Pops the given view controller and everything above it. + @discardableResult + func popFromViewController( + _ viewController: NSViewController, animated: Bool + ) -> [NSViewController]? { + guard let index = viewControllers.firstIndex(of: viewController), index != 0 else { + return nil + } + return popToViewController(viewControllers[index - 1], animated: animated) + } + } + + @MainActor + private let navigationIDKey = malloc(1)! + + extension CollectionDifference.Change { + fileprivate var offset: Int { + switch self { + case .insert(let offset, _, _): + return offset + case .remove(let offset, _, _): + return offset + } + } + } + + extension RangeReplaceableCollection + where + Self: RandomAccessCollection, + Element: Hashable + { + fileprivate var path: [UINavigationPath.Element] { + get { map { .eager($0) } } + set { + replaceSubrange( + startIndex.. String { + "\(String(reflecting: type)).self" + } +#endif diff --git a/Sources/AppKitNavigation/Navigation/Push.swift b/Sources/AppKitNavigation/Navigation/Push.swift new file mode 100644 index 0000000000..9b878e7c9a --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Push.swift @@ -0,0 +1,93 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + import AppKit + public import AppKitPlus + + extension NSTraitCollection { + /// Pushes a value onto the navigation stack controller this content is in. + /// + /// Calling ``AppKitPushAction/callAsFunction(value:fileID:filePath:line:column:)`` appends a + /// copy of the value to the path that drives the current ``NavigationStackController``: + /// + /// ```swift + /// let detailButton = NSButton(title: "Details", target: nil, action: nil) + /// detailButton.addAction { [weak self] _ in + /// self?.traitCollection.push(value: Route.detail) + /// } + /// ``` + /// + /// Outside a navigation stack controller, the push is reported as an issue instead. + /// + /// Available with the `AppKitPlus` package trait. + public var push: AppKitPushAction { + self[PushActionTrait.self]?.action ?? AppKitPushAction(run: nil) + } + } + + /// Pushes a value onto a navigation stack controller. + /// + /// You will not typically refer to this type directly. Read it from a trait collection, as + /// ``AppKitPlus/NSTraitCollection/push``, and call it as a function. + /// + /// Available with the `AppKitPlus` package trait. + @MainActor + public struct AppKitPushAction: Sendable { + let run: (@MainActor @Sendable (AnyHashable) -> Void)? + + /// Pushes a value onto the navigation stack controller's path. + /// + /// - Parameters: + /// - value: The value to push. A copy is appended to the path that drives the current + /// ``NavigationStackController``. + /// - fileID: The source `#fileID` associated with the push. + /// - filePath: The source `#filePath` associated with the push. + /// - line: The source `#line` associated with the push. + /// - column: The source `#column` associated with the push. + public func callAsFunction( + value: Element, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + guard let run else { + reportIssue( + """ + Tried to push a value from outside of a navigation stack. + + 'NSTraitCollection.push(value:)' must be called from content in a \ + 'NavigationStackController'. + """, + fileID: fileID, + filePath: filePath, + line: line, + column: column + ) + return + } + run(value) + } + } + + /// Carries a push action through AppKitPlus's trait storage, which keeps only objects: a value + /// that is not one is stored as no value at all. + final class PushActionBox: NSObject, @unchecked Sendable { + // NB: Unchecked, since the box never changes once made, and the action is sendable. + let action: AppKitPushAction + + init(_ action: AppKitPushAction) { + self.action = action + } + } + + enum PushActionTrait: NSTraitDefinition { + static var defaultValue: PushActionBox? { nil } + static var identifier: String { "AppKitNavigation.PushAction" } + } + + extension NSMutableTraits { + var push: AppKitPushAction { + get { self[PushActionTrait.self]?.action ?? AppKitPushAction(run: nil) } + set { self[PushActionTrait.self] = newValue.run == nil ? nil : PushActionBox(newValue) } + } + } +#endif diff --git a/Tests/AppKitNavigationTests/NavigationStackControllerTests.swift b/Tests/AppKitNavigationTests/NavigationStackControllerTests.swift new file mode 100644 index 0000000000..a5ca8bf30a --- /dev/null +++ b/Tests/AppKitNavigationTests/NavigationStackControllerTests.swift @@ -0,0 +1,153 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + import AppKit + import AppKitNavigation + #if compiler(<6.4) + // NB: Swift 6.2 treats the delegate's conformance below as public, and a public conformance + // needs a public import. + public import AppKitPlus + #else + import AppKitPlus + #endif + import XCTest + + /// A navigation stack controller pushes and pops view controllers as its path changes, and + /// writes the path back when the user goes back or content dismisses itself. + final class NavigationStackControllerTests: XCTestCase { + @MainActor + func testChangingThePathPushesAndPopsViewControllers() { + @UIBinding var path: [Int] = [] + let stackController = makeStackController(path: $path) + + withoutAnimation { path = [1] } + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 2 }) + XCTAssertEqual(numbers(in: stackController), [1]) + + withoutAnimation { path = [1, 2, 3] } + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 4 }) + XCTAssertEqual(numbers(in: stackController), [1, 2, 3]) + + withoutAnimation { path = [1] } + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 2 }) + + withoutAnimation { path = [] } + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 1 }) + } + + @MainActor + func testStartsWithTheViewControllersOfThePath() { + @UIBinding var path = [4, 5] + let stackController = makeStackController(path: $path) + + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 3 }) + XCTAssertEqual(numbers(in: stackController), [4, 5]) + } + + /// The back button, ⌘↑ and the swipe all pop through the navigation controller. + @MainActor + func testGoingBackTrimsThePath() { + @UIBinding var path = [1, 2] + let stackController = makeStackController(path: $path) + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 3 }) + + stackController.popViewController(animated: false) + + XCTAssertTrue(waitUntil { path == [1] }) + } + + @MainActor + func testPushingAValueAppendsItToThePath() throws { + @UIBinding var path: [Int] = [] + let stackController = makeStackController(path: $path) + let root = try XCTUnwrap(stackController.viewControllers.first) + // NB: AppKitPlus hands traits down to the view controllers inside on the next turn of the run + // loop. + spinRunLoop(for: 0.1) + + root.traitCollection.push(value: 7) + + XCTAssertEqual(path, [7]) + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 2 }) + } + + @MainActor + func testDismissingAPushedViewControllerPopsIt() { + @UIBinding var path = [1, 2] + let stackController = makeStackController(path: $path) + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 3 }) + + stackController.viewControllers[2].traitCollection.dismiss() + + XCTAssertTrue(waitUntil { path == [1] }) + XCTAssertTrue(waitUntil { stackController.viewControllers.count == 2 }) + } + + @MainActor + func testTheAppsDelegateStillHearsFromTheNavigationController() { + @UIBinding var path: [Int] = [] + let stackController = makeStackController(path: $path) + let delegate = ShowRecordingDelegate() + stackController.delegate = delegate + + withoutAnimation { path = [1] } + + XCTAssertTrue(waitUntil { delegate.shownCount > 0 }) + } + + // MARK: - Support + + @MainActor + private func makeStackController(path: UIBinding<[Int]>) -> NavigationStackController { + let stackController = NavigationStackController(path: path) { [unowned self] in + makeViewController() + } + stackController.navigationDestination(for: Int.self) { number in + NumberViewController(number: number) + } + let window = makeWindow(width: 400, height: 300) + window.contentViewController = stackController + window.orderFront(nil) + return stackController + } + + @MainActor + private func numbers(in stackController: NavigationStackController) -> [Int] { + stackController.viewControllers.compactMap { ($0 as? NumberViewController)?.number } + } + + @MainActor + private func withoutAnimation(_ body: () -> Void) { + var transaction = UITransaction() + transaction.appKit.disablesAnimations = true + withUITransaction(transaction, body) + } + } + + private final class NumberViewController: NSViewController { + let number: Int + + init(number: Int) { + self.number = number + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func loadView() { + view = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)) + } + } + + private final class ShowRecordingDelegate: NSObject, NSNavigationControllerDelegate { + private(set) var shownCount = 0 + + func navigationController( + _ navigationController: NSNavigationController, + didShow viewController: NSViewController + ) { + shownCount += 1 + } + } +#endif From aa20d32f463f4cd1aa5868e2b226d6933e40b15d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:52:25 +0800 Subject: [PATCH 115/141] feat(appkit): push navigation destinations from state, and let shown content dismiss itself --- .../draft-appkit-stack-navigation.md | 6 +- .../Navigation/BindingPresenter.swift | 24 ++ .../AppKitNavigation/Navigation/Dismiss.swift | 24 ++ .../Navigation/NavigationDestination.swift | 271 ++++++++++++++++++ .../AppKitNavigation/Navigation/Popover.swift | 11 + .../DismissActionTests.swift | 120 ++++++++ .../NavigationDestinationTests.swift | 148 ++++++++++ 7 files changed, 602 insertions(+), 2 deletions(-) create mode 100644 Sources/AppKitNavigation/Navigation/NavigationDestination.swift create mode 100644 Tests/AppKitNavigationTests/DismissActionTests.swift create mode 100644 Tests/AppKitNavigationTests/NavigationDestinationTests.swift diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index 85aeabc506..548f2bb847 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -257,8 +257,8 @@ extension NSOutlineView { 1. **trait 与依赖**(已完成):两份清单加 trait 和依赖,6.2 那份抬到 macOS 12。trait 关闭、打开各编译一次 AppKitNavigation,确认关闭时不解析 AppKitPlus。 2. **路径驱动的栈**(已完成):`NavigationStackController`、`navigationDestination(for:destination:)`、`push(value:)`、`traitCollection.push`。先写测试:改路径时推入、弹出;用户返回后路径被截短。 -3. **按状态推入**:推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 -4. **`dismiss()`**:`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 +3. **按状态推入**(已完成):推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 +4. **`dismiss()`**(已完成):`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 5. **AppKitPlus 数据源的选中绑定**:两个 `bind(selection:dataSource:)`,各配双向测试。 6. **示例**:Examples 工程打开 trait,恢复「Stack navigation」一组,补两个案例;CaseStudies 的 macOS 版只编译,不点界面。 7. **文档与验证**:DocC 首页与 skill;判断要不要写打开 trait 的使用指南。Xcode 27.2 跑 AppKit 的全部测试,trait 关闭、打开各一次;Xcode 26.6 在 trait 打开时编译库和 AppKit 测试。 @@ -286,3 +286,5 @@ extension NSOutlineView { | 2026-11-09 | 栈控制器的 `delegate` 读到的是转发代理,不像 UIKit 版那样返回 App 的委托 | AppKitPlus 内部经 `delegate` 属性取委托,getter 若返回 App 的委托,路径代理就被绕过,用户返回时路径不会截短(探针实测)。App 设的委托排在代理后面,所有消息照转 | | 2026-11-09 | 栈控制器重写 `init(nibName:bundle:)` 并标为不可用 | AppKitPlus 的 `init(navigationBarClass:toolbarClass:)` 内部经它初始化,Swift 子类不实现就会在运行时崩溃 | | 2026-11-09 | 视图加载时第一次按路径摆放控制器不带动画 | 那时没有可以过渡的画面;测试里这次动画也收不了尾,后面的推入弹出都排在它后面 | +| 2026-11-09 | 按状态推入的内容,以「到过栈上、又离开了导航控制器、视图也离开了窗口」判定已经下屏 | 推入可能落在任意 `NSNavigationController` 里,不能占用它的委托;AppKitPlus 弹出时不发 `didMove(toParent: nil)`。在 run loop 每次等待前检查这三个条件;推入若因过渡进行中而排队,先等它落到栈上,结束时也先等它落到栈上再弹出 | +| 2026-11-09 | `dismiss` 装在内容的 trait 覆盖里:视图控制器装在自己身上,窗口和存取面板装在窗口上,alert 装在它的窗口上,popover 装在内容视图控制器上 | AppKitPlus 里窗口也是 trait 环境,装在窗口上,窗口里的所有视图都能读到 | diff --git a/Sources/AppKitNavigation/Navigation/BindingPresenter.swift b/Sources/AppKitNavigation/Navigation/BindingPresenter.swift index b9960505ea..932ce0aa5b 100644 --- a/Sources/AppKitNavigation/Navigation/BindingPresenter.swift +++ b/Sources/AppKitNavigation/Navigation/BindingPresenter.swift @@ -160,6 +160,9 @@ } ) phase = .presented(presentation) + #if AppKitPlus + installDismissAction(for: presentation) + #endif let onDismiss = onDismiss style.begin(presentation.content, transaction: transaction) { [weak self] in guard !presentation.hasEnded else { return } @@ -174,6 +177,26 @@ } } + #if AppKitPlus + /// Lets the content close itself with `traitCollection.dismiss()`, as if the user had. + private func installDismissAction(for presentation: Presentation) { + guard let host = presentation.content as? any DismissActionHost else { return } + host.installDismissAction( + AppKitDismissAction { [weak self, weak presentation] transaction in + guard + let self, + let presentation, + case let .presented(current) = phase, + current === presentation + else { return } + // NB: The phase stays as it is, so that the end counts as the user's: the binding is + // cleared, and 'onDismiss' runs once the content has left the screen. + style.end(presentation.content, transaction: transaction) + } + ) + } + #endif + private func end(_ presentation: Presentation, transaction: UITransaction) { phase = .ending(presentation) style.end(presentation.content, transaction: transaction) @@ -214,6 +237,7 @@ case ending(Presentation) } + @MainActor private final class Presentation { let content: Style.Content let identity: AnyHashable? diff --git a/Sources/AppKitNavigation/Navigation/Dismiss.swift b/Sources/AppKitNavigation/Navigation/Dismiss.swift index e48476bd1f..0266597f54 100644 --- a/Sources/AppKitNavigation/Navigation/Dismiss.swift +++ b/Sources/AppKitNavigation/Navigation/Dismiss.swift @@ -77,6 +77,30 @@ static var identifier: String { "AppKitNavigation.DismissAction" } } + /// Content that can hand a dismiss action down to everything it shows. + @MainActor + protocol DismissActionHost: AnyObject { + func installDismissAction(_ action: AppKitDismissAction) + } + + extension NSViewController: DismissActionHost { + func installDismissAction(_ action: AppKitDismissAction) { + traitOverrides.dismiss = action + } + } + + extension NSWindow: DismissActionHost { + func installDismissAction(_ action: AppKitDismissAction) { + traitOverrides.dismiss = action + } + } + + extension NSAlert: DismissActionHost { + func installDismissAction(_ action: AppKitDismissAction) { + window.traitOverrides.dismiss = action + } + } + extension NSMutableTraits { var dismiss: AppKitDismissAction { get { self[DismissActionTrait.self]?.action ?? AppKitDismissAction(run: nil) } diff --git a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift new file mode 100644 index 0000000000..0e7138a890 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift @@ -0,0 +1,271 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + public import AppKit + public import AppKitPlus + public import SwiftNavigation + import AppKitNavigationShim + + extension NSViewController { + /// Pushes a view controller onto the enclosing navigation controller while a binding to a + /// Boolean value you provide is true. + /// + /// Like SwiftUI's `navigationDestination(isPresented:)`, for AppKitPlus's + /// `NSNavigationController`. Setting the binding to `false` pops the view controller, along + /// with anything pushed above it. When the user goes back past it — with the back button, ⌘↑ + /// or a swipe — or it dismisses itself with `traitCollection.dismiss()`, the binding is set to + /// `false`. The view controller is pushed once this view controller's view has appeared. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - isPresented: A binding to a Boolean value that determines whether to push the view + /// controller. + /// - onDismiss: The closure to execute once the view controller has been popped and has left + /// the screen. + /// - content: A closure that returns the view controller to push. + /// - Returns: A token that stops following the binding once cancelled. + #if !Perception + @available(macOS 14, *) + #endif + @discardableResult + public func navigationDestination( + isPresented: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping () -> NSViewController + ) -> ObserveToken { + navigationDestination(item: isPresented.toOptionalUnit, onDismiss: onDismiss) { _ in + content() + } + } + + /// Pushes a view controller onto the enclosing navigation controller while a binding to an + /// optional item holds a value. + /// + /// The view controller is pushed and popped as with + /// ``navigationDestination(isPresented:onDismiss:content:)``. If the item's identity changes, + /// the view controller is popped, and once it has left the screen, one for the new item is + /// pushed. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, the value is passed to `content`. When the user goes back past the view + /// controller, the binding is set to `nil`. + /// - onDismiss: The closure to execute once the view controller has been popped and has left + /// the screen. + /// - content: A closure that returns the view controller to push for the item. + /// - Returns: A token that stops following the binding once cancelled. + #if !Perception + @available(macOS 14, *) + #endif + @discardableResult + public func navigationDestination( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + navigationDestination(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + /// Pushes a view controller onto the enclosing navigation controller while a binding to an + /// optional item holds a value, passing the content a binding to the item. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, a binding to the value is passed to `content`. When the user goes back past the + /// view controller, the binding is set to `nil`. + /// - onDismiss: The closure to execute once the view controller has been popped and has left + /// the screen. + /// - content: A closure that returns the view controller to push for the item. + /// - Returns: A token that stops following the binding once cancelled. + #if !Perception + @available(macOS 14, *) + #endif + @_disfavoredOverload + @discardableResult + public func navigationDestination( + item: UIBinding, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + navigationDestination(item: item, id: \.id, onDismiss: onDismiss, content: content) + } + + /// Pushes a view controller onto the enclosing navigation controller while a binding to an + /// optional item holds a value, telling items apart by the identifier at a key path. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, the value is passed to `content`. When the user goes back past the view + /// controller, the binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the view controller is + /// popped, and once it has left the screen, one for the new item is pushed. + /// - onDismiss: The closure to execute once the view controller has been popped and has left + /// the screen. + /// - content: A closure that returns the view controller to push for the item. + /// - Returns: A token that stops following the binding once cancelled. + #if !Perception + @available(macOS 14, *) + #endif + @discardableResult + public func navigationDestination( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (Item) -> NSViewController + ) -> ObserveToken { + navigationDestination(item: item, id: id, onDismiss: onDismiss) { + content($0.wrappedValue) + } + } + + /// Pushes a view controller onto the enclosing navigation controller while a binding to an + /// optional item holds a value, telling items apart by the identifier at a key path and + /// passing the content a binding to the item. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - item: A binding to an optional source of truth for the view controller. While it holds + /// a value, a binding to the value is passed to `content`. When the user goes back past the + /// view controller, the binding is set to `nil`. + /// - id: The key path to the item's identifier. When it changes, the view controller is + /// popped, and once it has left the screen, one for the new item is pushed. + /// - onDismiss: The closure to execute once the view controller has been popped and has left + /// the screen. + /// - content: A closure that returns the view controller to push for the item. + /// - Returns: A token that stops following the binding once cancelled. + #if !Perception + @available(macOS 14, *) + #endif + @_disfavoredOverload + @discardableResult + public func navigationDestination( + item: UIBinding, + id: KeyPath, + onDismiss: (() -> Void)? = nil, + content: @escaping (UIBinding) -> NSViewController + ) -> ObserveToken { + bindPresentation( + NavigationPushStyle(presenter: self), + item: item, + id: { $0[keyPath: id] }, + onDismiss: onDismiss, + content: content + ) + } + } + + /// Shows content by pushing it onto the navigation controller the presenter is in. + @MainActor + private struct NavigationPushStyle: PresentationStyle { + weak var presenter: NSViewController? + + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + guard let presenter, !presenter._AppKitNavigation_hasViewAppeared else { + body() + return {} + } + let wait = PushWait() + presenter._AppKitNavigation_onViewAppear.append { + MainActor._assumeIsolated { + guard !wait.isCancelled else { return } + body() + } + } + return { + wait.isCancelled = true + } + } + + func begin( + _ child: NSViewController, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + guard + let presenter, + let navigationController = presenter.navigationController + ?? presenter as? NSNavigationController + else { + reportIssue( + """ + Can't push a navigation destination: "navigationController" is "nil". + + 'navigationDestination' must be called on a view controller in an \ + 'NSNavigationController'. + """ + ) + didEnd() + return + } + let record = PushRecord(navigationController: navigationController) + child.appKitNavigationPushRecord = record + navigationController.pushViewController( + child, animated: !transaction.appKit.disablesAnimations + ) + // NB: AppKitPlus never sends 'didMove(toParent: nil)' when it pops a view controller, so a + // pushed one counts as gone once it has been on the stack, has left its navigation + // controller, and its view has left the window. A push that waits for a running + // transition leaves the view controller off the stack for a while. + _ = RunLoopWait.until( + { [weak child] in + guard let child else { return true } + if child.parent != nil { + record.hasBeenPushed = true + } + return record.hasBeenPushed && child.parent == nil + && (!child.isViewLoaded || child.view.window == nil) + }, + then: didEnd + ) + } + + func end(_ child: NSViewController, transaction: UITransaction) { + guard let navigationController = child.appKitNavigationPushRecord?.navigationController + else { return } + let animated = !transaction.appKit.disablesAnimations + // NB: A push that is still waiting for a running transition is popped once it lands. + _ = RunLoopWait.until({ [weak child] in child?.parent != nil || child == nil }) { + [weak child, weak navigationController] in + guard let child, let navigationController else { return } + navigationController.popFromViewController(child, animated: animated) + } + } + } + + /// Where a view controller was pushed, and whether it has reached the stack yet. + @MainActor + private final class PushRecord { + weak var navigationController: NSNavigationController? + var hasBeenPushed = false + + init(navigationController: NSNavigationController) { + self.navigationController = navigationController + } + } + + /// A wait that can be called off after it has been scheduled. + @MainActor + private final class PushWait { + var isCancelled = false + } + + extension NSViewController { + fileprivate var appKitNavigationPushRecord: PushRecord? { + get { + objc_getAssociatedObject(self, pushRecordKey) as? PushRecord + } + set { + objc_setAssociatedObject(self, pushRecordKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) + } + } + } + + @MainActor + private let pushRecordKey = malloc(1)! +#endif diff --git a/Sources/AppKitNavigation/Navigation/Popover.swift b/Sources/AppKitNavigation/Navigation/Popover.swift index d0f73ffc00..54d118bde1 100644 --- a/Sources/AppKitNavigation/Navigation/Popover.swift +++ b/Sources/AppKitNavigation/Navigation/Popover.swift @@ -1,6 +1,9 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit + #if AppKitPlus + import AppKitPlus + #endif extension NSView { /// Shows a view controller in a popover anchored to this view while a binding to a Boolean @@ -464,6 +467,14 @@ } } + #if AppKitPlus + extension PopoverContent: DismissActionHost { + func installDismissAction(_ action: AppKitDismissAction) { + popover.contentViewController?.traitOverrides.dismiss = action + } + } + #endif + /// Shows content in a popover pointing at an anchor. @MainActor private struct PopoverStyle: PresentationStyle { diff --git a/Tests/AppKitNavigationTests/DismissActionTests.swift b/Tests/AppKitNavigationTests/DismissActionTests.swift new file mode 100644 index 0000000000..547244a90d --- /dev/null +++ b/Tests/AppKitNavigationTests/DismissActionTests.swift @@ -0,0 +1,120 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + import AppKit + import AppKitNavigation + import AppKitPlus + import XCTest + + /// Content that a binding showed can close itself with `traitCollection.dismiss()`, which ends + /// it the way the user would: the binding is cleared, and `onDismiss` runs once. + final class DismissActionTests: XCTestCase { + override func setUp() { + super.setUp() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + @MainActor + func testAPresentedViewControllerDismissesItself() { + let host = makeHost() + let child = makeViewController() + @UIBinding var isPresented = false + let dismissCount = Recorded(0) + host.viewController.present( + isPresented: $isPresented, style: .sheet, onDismiss: { dismissCount.value += 1 } + ) { child } + + isPresented = true + XCTAssertTrue(waitUntil { child.view.window?.isVisible == true }, "The sheet never appeared") + spinRunLoop(for: 0.1) + + child.traitCollection.dismiss() + + XCTAssertTrue(waitUntil { !isPresented }, "Dismissing did not write 'false' back") + XCTAssertTrue(waitUntil { dismissCount.value == 1 }) + } + + @MainActor + func testAWindowSheetDismissesItselfFromItsContent() { + let host = makeHost() + let sheetWindow = makeWindow() + let contentView = NSView() + sheetWindow.contentView = contentView + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } + + isPresented = true + XCTAssertTrue(waitUntil { sheetWindow.isVisible }, "The sheet never appeared") + spinRunLoop(for: 0.1) + + contentView.traitCollection.dismiss() + + XCTAssertTrue(waitUntil { !isPresented }, "Dismissing did not write 'false' back") + XCTAssertTrue(waitUntil { !sheetWindow.isVisible }) + } + + @MainActor + func testAPopoverDismissesItself() { + let host = makeHost() + let content = makeViewController() + @UIBinding var isPresented = false + let popovers = recordShownPopovers() + host.view.popover(isPresented: $isPresented, preferredEdge: .maxY) { content } + + isPresented = true + XCTAssertTrue(waitUntil { popovers.shownPopovers.last?.isShown == true }) + spinRunLoop(for: 0.1) + + content.traitCollection.dismiss() + + XCTAssertTrue(waitUntil { !isPresented }, "Dismissing did not write 'false' back") + } + + @MainActor + func testAModalSessionWindowDismissesItself() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + host.modalSession(isPresented: $isPresented) { window } + + isPresented = true + XCTAssertTrue(waitUntil { window.isVisible }, "The window never appeared") + spinRunLoop(for: 0.1) + + window.traitCollection.dismiss() + + XCTAssertTrue(waitUntil { !isPresented }, "Dismissing did not write 'false' back") + } + + @MainActor + func testAModalWindowDismissesItself() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { window } + abortModalLoops(after: 5) + + let start = Date() + perform(after: 0.5) { + window.traitCollection.dismiss() + } + isPresented = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "Dismissing did not write 'false' back") + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + "The modal loop only ended when the safety timer aborted it" + ) + } + + @MainActor + func testContentThatNoBindingShowedReportsAnIssue() { + let viewController = makeViewController() + + XCTExpectFailure { + viewController.traitCollection.dismiss() + } + XCTAssertFalse(viewController.traitCollection.isPresented) + } + } +#endif diff --git a/Tests/AppKitNavigationTests/NavigationDestinationTests.swift b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift new file mode 100644 index 0000000000..cc7232df53 --- /dev/null +++ b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift @@ -0,0 +1,148 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + import AppKit + import AppKitNavigation + import AppKitPlus + import XCTest + + /// A navigation destination is pushed while its binding holds a value, popped when it no longer + /// does, and writes `nil` back when the user goes back past it or it dismisses itself. + final class NavigationDestinationTests: XCTestCase { + @MainActor + func testPushesWhileTheItemHoldsAValueAndPopsWhenItBecomesNil() { + let (navigationController, root) = makeNavigationController() + @UIBinding var detail: Detail? = nil + let dismissCount = Recorded(0) + root.navigationDestination(item: $detail, onDismiss: { dismissCount.value += 1 }) { detail in + DetailViewController(name: detail.name) + } + + withoutAnimation { detail = Detail(name: "Mars") } + XCTAssertTrue(waitUntil { navigationController.viewControllers.count == 2 }) + XCTAssertEqual(topName(of: navigationController), "Mars") + + withoutAnimation { detail = nil } + XCTAssertTrue(waitUntil { navigationController.viewControllers.count == 1 }) + XCTAssertTrue(waitUntil { dismissCount.value == 1 }) + } + + /// The back button, ⌘↑ and the swipe all pop through the navigation controller. + @MainActor + func testGoingBackWritesNilBack() { + let (navigationController, root) = makeNavigationController() + @UIBinding var detail: Detail? = nil + let dismissCount = Recorded(0) + root.navigationDestination(item: $detail, onDismiss: { dismissCount.value += 1 }) { detail in + DetailViewController(name: detail.name) + } + withoutAnimation { detail = Detail(name: "Mars") } + XCTAssertTrue(waitUntil { navigationController.viewControllers.count == 2 }) + + navigationController.popViewController(animated: false) + + XCTAssertTrue(waitUntil { detail == nil }) + XCTAssertTrue(waitUntil { dismissCount.value == 1 }) + } + + @MainActor + func testANewItemReplacesTheDestination() { + let (navigationController, root) = makeNavigationController() + @UIBinding var detail: Detail? = nil + let dismissCount = Recorded(0) + root.navigationDestination(item: $detail, onDismiss: { dismissCount.value += 1 }) { detail in + DetailViewController(name: detail.name) + } + withoutAnimation { detail = Detail(name: "Mars") } + XCTAssertTrue(waitUntil { topName(of: navigationController) == "Mars" }) + + withoutAnimation { detail = Detail(name: "Venus") } + + XCTAssertTrue(waitUntil { topName(of: navigationController) == "Venus" }) + XCTAssertEqual(navigationController.viewControllers.count, 2) + XCTAssertEqual(dismissCount.value, 1) + } + + @MainActor + func testABooleanBindingPushesAndPops() { + let (navigationController, root) = makeNavigationController() + @UIBinding var isShowingSettings = false + root.navigationDestination(isPresented: $isShowingSettings) { + DetailViewController(name: "Settings") + } + + withoutAnimation { isShowingSettings = true } + XCTAssertTrue(waitUntil { topName(of: navigationController) == "Settings" }) + + navigationController.popViewController(animated: false) + XCTAssertTrue(waitUntil { !isShowingSettings }) + } + + @MainActor + func testAPushedDestinationDismissesItself() { + let (navigationController, root) = makeNavigationController() + @UIBinding var detail: Detail? = nil + let dismissCount = Recorded(0) + root.navigationDestination(item: $detail, onDismiss: { dismissCount.value += 1 }) { detail in + DetailViewController(name: detail.name) + } + withoutAnimation { detail = Detail(name: "Mars") } + XCTAssertTrue(waitUntil { navigationController.viewControllers.count == 2 }) + // NB: AppKitPlus hands traits down to the view controllers inside on the next turn of the run + // loop. + spinRunLoop(for: 0.1) + + withoutAnimation { navigationController.viewControllers[1].traitCollection.dismiss() } + + XCTAssertTrue(waitUntil { detail == nil }) + XCTAssertTrue(waitUntil { navigationController.viewControllers.count == 1 }) + XCTAssertTrue(waitUntil { dismissCount.value == 1 }) + } + + // MARK: - Support + + @MainActor + private func makeNavigationController() -> (NSNavigationController, NSViewController) { + let root = makeViewController() + let navigationController = NSNavigationController(rootViewController: root) + let window = makeWindow(width: 400, height: 300) + window.contentViewController = navigationController + window.orderFront(nil) + _ = waitUntil { root.viewIfLoaded?.window != nil } + return (navigationController, root) + } + + @MainActor + private func topName(of navigationController: NSNavigationController) -> String? { + (navigationController.viewControllers.last as? DetailViewController)?.name + } + + @MainActor + private func withoutAnimation(_ body: () -> Void) { + var transaction = UITransaction() + transaction.appKit.disablesAnimations = true + withUITransaction(transaction, body) + } + } + + private struct Detail: Identifiable { + let name: String + var id: String { name } + } + + private final class DetailViewController: NSViewController { + let name: String + + init(name: String) { + self.name = name + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func loadView() { + view = NSView(frame: NSRect(x: 0, y: 0, width: 200, height: 120)) + } + } +#endif From 1a14fdd88df7d993f9e5f44a9862e8be09040be7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:54:13 +0800 Subject: [PATCH 116/141] feat(appkit): bind table and outline selection through AppKitPlus data sources --- .../draft-appkit-stack-navigation.md | 2 +- .../Bindings/AppKitPlusDataSources.swift | 75 +++++++++++++++++ .../AppKitPlusDataSourceBindingTests.swift | 80 +++++++++++++++++++ 3 files changed, 156 insertions(+), 1 deletion(-) create mode 100644 Sources/AppKitNavigation/Bindings/AppKitPlusDataSources.swift create mode 100644 Tests/AppKitNavigationTests/AppKitPlusDataSourceBindingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index 548f2bb847..4f9ee589c2 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -259,7 +259,7 @@ extension NSOutlineView { 2. **路径驱动的栈**(已完成):`NavigationStackController`、`navigationDestination(for:destination:)`、`push(value:)`、`traitCollection.push`。先写测试:改路径时推入、弹出;用户返回后路径被截短。 3. **按状态推入**(已完成):推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 4. **`dismiss()`**(已完成):`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 -5. **AppKitPlus 数据源的选中绑定**:两个 `bind(selection:dataSource:)`,各配双向测试。 +5. **AppKitPlus 数据源的选中绑定**(已完成):两个 `bind(selection:dataSource:)`,各配双向测试。 6. **示例**:Examples 工程打开 trait,恢复「Stack navigation」一组,补两个案例;CaseStudies 的 macOS 版只编译,不点界面。 7. **文档与验证**:DocC 首页与 skill;判断要不要写打开 trait 的使用指南。Xcode 27.2 跑 AppKit 的全部测试,trait 关闭、打开各一次;Xcode 26.6 在 trait 打开时编译库和 AppKit 测试。 diff --git a/Sources/AppKitNavigation/Bindings/AppKitPlusDataSources.swift b/Sources/AppKitNavigation/Bindings/AppKitPlusDataSources.swift new file mode 100644 index 0000000000..c63bf4bb74 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/AppKitPlusDataSources.swift @@ -0,0 +1,75 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + public import AppKit + public import AppKitPlus + public import SwiftNavigation + + extension NSTableView { + /// Establishes a two-way connection between a binding and the table's selected row, through + /// the row lookups of an AppKitPlus reorderable diffable data source. + /// + /// ```swift + /// tableView.bind(selection: $model.selectedTrackID, dataSource: dataSource) + /// ``` + /// + /// Works as ``AppKit/NSTableView/bind(selection:row:itemIdentifier:)``. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected item, and write to when the + /// selection changes. + /// - dataSource: The table's reorderable diffable data source. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + dataSource: NSTableViewDiffableReorderableDataSource + ) -> ObserveToken { + // NB: Held weakly: the table keeps this binding for as long as it lives, and the data source + // may hold on to the table. + bind( + selection: selection, + row: { [weak dataSource] identifier in dataSource?.row(forItemIdentifier: identifier) }, + itemIdentifier: { [weak dataSource] row in dataSource?.itemIdentifier(forRow: row) } + ) + } + } + + extension NSOutlineView { + /// Establishes a two-way connection between a binding and the outline's selected row, through + /// the row lookups of an AppKitPlus outline diffable data source. + /// + /// ```swift + /// outlineView.bind(selection: $model.selectedEntityID, dataSource: dataSource) + /// ``` + /// + /// Works as ``AppKit/NSTableView/bind(selection:row:itemIdentifier:)``. An item inside a + /// collapsed group has no row, so the outline selects nothing for it, and the identifier stays + /// in the binding. + /// + /// Available with the `AppKitPlus` package trait. + /// + /// - Parameters: + /// - selection: The binding to read from for the selected item, and write to when the + /// selection changes. + /// - dataSource: The outline's diffable data source. + /// - Returns: A cancel token. + @discardableResult + public func bind( + selection: UIBinding, + dataSource: NSOutlineViewDiffableDataSource + ) -> ObserveToken { + bind( + selection: selection, + row: { [weak dataSource] identifier in + // NB: AppKitPlus answers -1, not nil, for an item that has no row. + guard let row = dataSource?.row(forItemIdentifier: identifier), row >= 0 else { + return nil + } + return row + }, + itemIdentifier: { [weak dataSource] row in dataSource?.itemIdentifier(forRow: row) } + ) + } + } +#endif diff --git a/Tests/AppKitNavigationTests/AppKitPlusDataSourceBindingTests.swift b/Tests/AppKitNavigationTests/AppKitPlusDataSourceBindingTests.swift new file mode 100644 index 0000000000..59cebebcb3 --- /dev/null +++ b/Tests/AppKitNavigationTests/AppKitPlusDataSourceBindingTests.swift @@ -0,0 +1,80 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + import AppKit + import AppKitNavigation + import AppKitPlus + import Testing + + /// Tables and outlines driven by AppKitPlus's diffable data sources bind their selected row the + /// same way as with AppKit's own. + @MainActor + @Suite struct AppKitPlusDataSourceBindingTests { + @Test("a table with a reorderable data source keeps its selection in step") + func reorderableTableSelectionStaysInStep() async { + let tableView = NSTableView() + tableView.addTableColumn(NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Track"))) + let dataSource = NSTableViewDiffableReorderableDataSource(tableView: tableView) { + _, _, _, track in + NSTextField(labelWithString: track) + } + var snapshot = NSDiffableDataSourceSnapshot() + snapshot.appendSections([0]) + snapshot.appendItems(["Intro", "Verse", "Chorus"]) + dataSource.apply(snapshot, animatingDifferences: false, completion: nil) + @UIBinding var selectedTrack: String? = "Verse" + + tableView.bind(selection: $selectedTrack, dataSource: dataSource) + #expect(tableView.selectedRow == 1) + + selectedTrack = "Chorus" + await Task.yield() + #expect(tableView.selectedRow == 2) + + // NB: What the table does when the user clicks a row. + tableView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) + #expect(selectedTrack == "Intro") + } + + @Test("an outline with an AppKitPlus data source keeps its selection in step") + func outlineSelectionStaysInStep() async { + let (outlineView, dataSource) = makeOutline() + @UIBinding var selectedItem: String? = "Fruit" + + outlineView.bind(selection: $selectedItem, dataSource: dataSource) + #expect(outlineView.selectedRow == 0) + + selectedItem = "Vegetables" + await Task.yield() + #expect(outlineView.selectedRow == 1) + + outlineView.selectRowIndexes(IndexSet(integer: 0), byExtendingSelection: false) + #expect(selectedItem == "Fruit") + } + + @Test("an item inside a collapsed group selects nothing and stays in the binding") + func itemInsideACollapsedGroupStaysInTheBinding() { + let (outlineView, dataSource) = makeOutline() + @UIBinding var selectedItem: String? = "Cherries" + + outlineView.bind(selection: $selectedItem, dataSource: dataSource) + + #expect(outlineView.selectedRow == -1) + #expect(selectedItem == "Cherries") + } + + private func makeOutline() -> (NSOutlineView, NSOutlineViewDiffableDataSource) { + let outlineView = NSOutlineView() + let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier("Item")) + outlineView.addTableColumn(column) + outlineView.outlineTableColumn = column + let dataSource = NSOutlineViewDiffableDataSource(outlineView: outlineView) { + _, _, _, item in + NSTextField(labelWithString: item) + } + var snapshot = NSDiffableDataSourceSectionSnapshot() + snapshot.append(["Fruit", "Vegetables"]) + snapshot.append(["Apples", "Cherries"], to: "Fruit") + dataSource.apply(snapshot, animatingDifferences: false) + return (outlineView, dataSource) + } + } +#endif From c70d2f047a8958175f1fc610d8f751ed6402fdc8 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 21:57:56 +0800 Subject: [PATCH 117/141] docs(examples): turn on the AppKitPlus trait and add the AppKit stack navigation case studies --- .../draft-appkit-stack-navigation.md | 3 +- ...pKit+ErasedNavigationStackController.swift | 100 ++++++++++++++ ...pKit+StaticNavigationStackController.swift | 125 ++++++++++++++++++ .../AppKit/AppKitCaseStudies.swift | 10 +- Examples/Examples.xcodeproj/project.pbxproj | 30 +++++ .../xcshareddata/swiftpm/Package.resolved | 11 +- 6 files changed, 272 insertions(+), 7 deletions(-) create mode 100644 Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift create mode 100644 Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index 4f9ee589c2..1e91bf0f8e 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -260,7 +260,7 @@ extension NSOutlineView { 3. **按状态推入**(已完成):推入用的 `PresentationStyle` 和五种 `navigationDestination` 重载。先用测试确认 AppKitPlus 弹出控制器时的回调顺序,再写实现。 4. **`dismiss()`**(已完成):`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 5. **AppKitPlus 数据源的选中绑定**(已完成):两个 `bind(selection:dataSource:)`,各配双向测试。 -6. **示例**:Examples 工程打开 trait,恢复「Stack navigation」一组,补两个案例;CaseStudies 的 macOS 版只编译,不点界面。 +6. **示例**(已完成):Examples 工程打开 trait,恢复「Stack navigation」一组,补两个案例;CaseStudies 的 macOS 版只编译,不点界面。 7. **文档与验证**:DocC 首页与 skill;判断要不要写打开 trait 的使用指南。Xcode 27.2 跑 AppKit 的全部测试,trait 关闭、打开各一次;Xcode 26.6 在 trait 打开时编译库和 AppKit 测试。 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -288,3 +288,4 @@ extension NSOutlineView { | 2026-11-09 | 视图加载时第一次按路径摆放控制器不带动画 | 那时没有可以过渡的画面;测试里这次动画也收不了尾,后面的推入弹出都排在它后面 | | 2026-11-09 | 按状态推入的内容,以「到过栈上、又离开了导航控制器、视图也离开了窗口」判定已经下屏 | 推入可能落在任意 `NSNavigationController` 里,不能占用它的委托;AppKitPlus 弹出时不发 `didMove(toParent: nil)`。在 run loop 每次等待前检查这三个条件;推入若因过渡进行中而排队,先等它落到栈上,结束时也先等它落到栈上再弹出 | | 2026-11-09 | `dismiss` 装在内容的 trait 覆盖里:视图控制器装在自己身上,窗口和存取面板装在窗口上,alert 装在它的窗口上,popover 装在内容视图控制器上 | AppKitPlus 里窗口也是 trait 环境,装在窗口上,窗口里的所有视图都能读到 | +| 2026-11-09 | Examples 工程加一个指向仓库根目录、带 trait 的本地包引用,fork 的各个产品都改从它取 | Examples 原来经工作区的根包拿到这些产品,而 Xcode 的 trait 设置挂在工程的包引用上。实测 Xcode 27.2 接受这种写法,编译命令里出现 `-DAppKitPlus`;工作区的锁定文件随之多了 AppKitPlus-Release 0.21.0 一条 | diff --git a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift new file mode 100644 index 0000000000..7aea5a1cfa --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift @@ -0,0 +1,100 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation +import AppKitPlus + +final class ErasedNavigationStackController: NavigationStackController, AppKitCaseStudy { + let caseStudyTitle = "Type-erased path" + let readMe = """ + This case study drives a 'NavigationStackController' with the type-erased 'UINavigationPath', \ + so the stack can hold data of different types: here a number, a string and a Boolean, each \ + shown by a destination of its own. + """ + private var model: Model! + + convenience init(model: Model) { + @UIBindable var model = model + self.init(path: $model.path) { + ErasedRootViewController() + } + self.model = model + } + + @Observable + class Model { + var path = UINavigationPath() + } +} + +/// The bottom of the stack, which registers a destination for each type of data on the path. +private final class ErasedRootViewController: XiblessViewController { + override func viewDidLoad() { + super.viewDidLoad() + title = "Type-erased path" + + navigationDestination(for: Int.self) { number in + ErasedFeatureViewController(title: "Number \(number)") + } + navigationDestination(for: String.self) { string in + ErasedFeatureViewController(title: "String \"\(string)\"") + } + navigationDestination(for: Bool.self) { value in + ErasedFeatureViewController(title: "Boolean \(value)") + } + + addColumn( + of: [ + makeButton("Push a number") { [weak self] in + self?.traitCollection.push(value: Int.random(in: 1...1_000)) + }, + makeButton("Push a number → a string → a Boolean") { [weak self] in + self?.traitCollection.push(value: Int.random(in: 1...1_000)) + self?.traitCollection.push(value: "Hello!") + self?.traitCollection.push(value: Bool.random()) + }, + ], + to: view + ) + } +} + +/// A screen on the stack: it can push data of any of the three types, or dismiss itself. +private final class ErasedFeatureViewController: XiblessViewController { + init(title: String) { + super.init(nibName: nil, bundle: nil) + self.title = title + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + + addColumn( + of: [ + makeSectionLabel(title ?? ""), + makeButton("Push a number") { [weak self] in + self?.traitCollection.push(value: Int.random(in: 1...1_000)) + }, + makeButton("Push a string") { [weak self] in + self?.traitCollection.push(value: "Hello!") + }, + makeButton("Push a Boolean") { [weak self] in + self?.traitCollection.push(value: Bool.random()) + }, + makeButton("Dismiss") { [weak self] in + self?.traitCollection.dismiss() + }, + ], + to: view + ) + } +} + +#Preview { + ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift new file mode 100644 index 0000000000..be6dd8ffc1 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift @@ -0,0 +1,125 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation +import AppKitPlus + +final class StaticNavigationStackController: NavigationStackController, AppKitCaseStudy { + let caseStudyTitle = "Statically typed path" + let readMe = """ + This case study demonstrates 'NavigationStackController', an AppKit replacement for SwiftUI's \ + 'NavigationStack'. It is built on AppKitPlus's 'NSNavigationController', so it needs the \ + package's 'AppKitPlus' trait, which this project turns on. + + Each screen pushes a new element onto the path with the 'push' trait, and dismisses itself \ + with the 'dismiss' trait. Going back with the back button, ⌘↑ or a swipe updates the path too. + """ + private var model: Model! + + convenience init(model: Model) { + @UIBindable var model = model + self.init(path: $model.path) { + StaticRootViewController(model: model) + } + navigationDestination(for: Model.Path.self) { feature in + StaticFeatureViewController(feature: feature) + } + self.model = model + } + + @Observable + class Model { + var path: [Path] = [] + + enum Path: Hashable, CaseIterable { + case feature1 + case feature2 + case feature3 + + var title: String { + switch self { + case .feature1: "Feature 1" + case .feature2: "Feature 2" + case .feature3: "Feature 3" + } + } + } + } +} + +/// The bottom of the stack: a button for each feature, and one that pushes all three at once. +private final class StaticRootViewController: XiblessViewController { + let model: StaticNavigationStackController.Model + + init(model: StaticNavigationStackController.Model) { + self.model = model + super.init(nibName: nil, bundle: nil) + title = "Static path" + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + + let pathLabel = NSTextField(wrappingLabelWithString: "") + pathLabel.textColor = .secondaryLabelColor + var views: [NSView] = StaticNavigationStackController.Model.Path.allCases.map { feature in + makeButton("Push \(feature.title.lowercased())") { [weak self] in + self?.traitCollection.push(value: feature) + } + } + views.append( + makeButton("Push feature 1 → 2 → 3") { [weak self] in + self?.model.path.append(contentsOf: [.feature1, .feature2, .feature3]) + } + ) + views.append(pathLabel) + addColumn(of: views, to: view) + + observe { [unowned self] in + pathLabel.stringValue = + "Path: \(model.path.isEmpty ? "empty" : model.path.map(\.title).joined(separator: " → "))" + } + } +} + +/// A screen on the stack: it can push any feature, or dismiss itself. +private final class StaticFeatureViewController: XiblessViewController { + let feature: StaticNavigationStackController.Model.Path + + init(feature: StaticNavigationStackController.Model.Path) { + self.feature = feature + super.init(nibName: nil, bundle: nil) + title = feature.title + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidLoad() { + super.viewDidLoad() + + var views: [NSView] = [makeSectionLabel(feature.title)] + views += StaticNavigationStackController.Model.Path.allCases.map { feature in + makeButton("Push \(feature.title.lowercased())") { [weak self] in + self?.traitCollection.push(value: feature) + } + } + views.append( + makeButton("Dismiss") { [weak self] in + self?.traitCollection.dismiss() + } + ) + addColumn(of: views, to: view) + } +} + +#Preview { + StaticNavigationStackController(model: StaticNavigationStackController.Model()) +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift index 303265b71f..ab806eab10 100644 --- a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -25,11 +25,11 @@ struct AppKitCaseStudiesView: View { NestedModalViewController() DismissalViewController() } -// CaseStudyGroupView("Stack navigation") { -// StaticNavigationStackController() -// ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) -// // TODO: state restoration -// } + CaseStudyGroupView("Stack navigation") { + StaticNavigationStackController(model: StaticNavigationStackController.Model()) + ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) + // TODO: state restoration + } CaseStudyGroupView("Advanced") { // TODO: Deep link WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)) diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index ff4dea3984..df18f59765 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -80,6 +80,8 @@ E9F0050A2EDA000000000015 /* AppKit+OptionBindingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */; }; E9F0050A2EDA000000000016 /* AppKit+TableSelectionViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */; }; E9F0050A2EDA000000000017 /* AppKit+AnimationsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */; }; + E9F0050A2EDA000000000018 /* AppKit+StaticNavigationStackController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000008 /* AppKit+StaticNavigationStackController.swift */; }; + E9F0050A2EDA000000000019 /* AppKit+ErasedNavigationStackController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E9F0050A2EDA000000000009 /* AppKit+ErasedNavigationStackController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -162,6 +164,8 @@ E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+OptionBindingsViewController.swift"; sourceTree = ""; }; E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+TableSelectionViewController.swift"; sourceTree = ""; }; E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+AnimationsViewController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000008 /* AppKit+StaticNavigationStackController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+StaticNavigationStackController.swift"; sourceTree = ""; }; + E9F0050A2EDA000000000009 /* AppKit+ErasedNavigationStackController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "AppKit+ErasedNavigationStackController.swift"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -368,6 +372,8 @@ E9F0050A2EDA000000000005 /* AppKit+OptionBindingsViewController.swift */, E9F0050A2EDA000000000006 /* AppKit+TableSelectionViewController.swift */, E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */, + E9F0050A2EDA000000000008 /* AppKit+StaticNavigationStackController.swift */, + E9F0050A2EDA000000000009 /* AppKit+ErasedNavigationStackController.swift */, ); path = AppKit; sourceTree = ""; @@ -542,6 +548,7 @@ ); mainGroup = CA47378B272F08EF0012CAC3; packageReferences = ( + E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */, CA6453982968A06E00802931 /* XCRemoteSwiftPackageReference "swift-dependencies" */, CA48F3002C49650100BE2C3C /* XCRemoteSwiftPackageReference "swift-identified-collections" */, CA48F3032C49650F00BE2C3C /* XCRemoteSwiftPackageReference "swift-tagged" */, @@ -621,6 +628,8 @@ E9F0050A2EDA000000000015 /* AppKit+OptionBindingsViewController.swift in Sources */, E9F0050A2EDA000000000016 /* AppKit+TableSelectionViewController.swift in Sources */, E9F0050A2EDA000000000017 /* AppKit+AnimationsViewController.swift in Sources */, + E9F0050A2EDA000000000018 /* AppKit+StaticNavigationStackController.swift in Sources */, + E9F0050A2EDA000000000019 /* AppKit+ErasedNavigationStackController.swift in Sources */, DC6A8411291F227400B3F6C9 /* SynchronizedBindings.swift in Sources */, E99B05992C70CE6E003D3AFF /* UIKit+WiFiSettingsViewController.swift in Sources */, E99B05A42C70DC50003D3AFF /* AppKit+ConnectToNetworkViewController.swift in Sources */, @@ -1118,6 +1127,20 @@ }; /* End XCConfigurationList section */ +/* Begin XCLocalSwiftPackageReference section */ + E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */ = { + isa = XCLocalSwiftPackageReference; + relativePath = ..; + traits = ( + AppKitPlus, + CasePaths, + CustomDump, + IssueReporting, + Perception, + ); + }; +/* End XCLocalSwiftPackageReference section */ + /* Begin XCRemoteSwiftPackageReference section */ CA48F3002C49650100BE2C3C /* XCRemoteSwiftPackageReference "swift-identified-collections" */ = { isa = XCRemoteSwiftPackageReference; @@ -1161,14 +1184,17 @@ }; CA4737F3272F09780012CAC3 /* SwiftUINavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = SwiftUINavigation; }; CA48F2F92C49645100BE2C3C /* SwiftUINavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = SwiftUINavigation; }; CA48F2FB2C49645100BE2C3C /* UIKitNavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = UIKitNavigation; }; CA48F3012C49650100BE2C3C /* IdentifiedCollections */ = { @@ -1188,18 +1214,22 @@ }; E9836D932C6CA07300FC6EFD /* AppKitNavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = AppKitNavigation; }; CAAFA9D22C8B422800BB2BA1 /* UIKitNavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = UIKitNavigation; }; CAAFA9D82C8B468000BB2BA1 /* SwiftNavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = SwiftNavigation; }; CAAFA9DA2C8B468000BB2BA1 /* SwiftUINavigation */ = { isa = XCSwiftPackageProductDependency; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; productName = SwiftUINavigation; }; /* End XCSwiftPackageProductDependency section */ diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index 528aa53ec5..cb9b85505d 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,6 +1,15 @@ { - "originHash" : "44d2db2fa3620bdeb8f6f8122273f67ead312b3392d40f1c94c6ce6189f6538e", + "originHash" : "c29f1966f5086e34beae597b464b2409b3c6b0a2c352284799e5706fb0561522", "pins" : [ + { + "identity" : "appkitplus-release", + "kind" : "remoteSourceControl", + "location" : "https://github.com/AppKitSupportProgram/AppKitPlus-Release", + "state" : { + "revision" : "954e6bd30bc452bf54d65793b638e82d3a6a586d", + "version" : "0.21.0" + } + }, { "identity" : "combine-schedulers", "kind" : "remoteSourceControl", From 3a26ccef22bba2d7daf667f9492b416e80a860d7 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Mon, 9 Nov 2026 22:06:03 +0800 Subject: [PATCH 118/141] docs(appkit): document stack navigation with AppKitPlus, and build the trait with Xcode 26 --- .../draft-appkit-stack-navigation.md | 6 +- .../Bindings/NSTableView.swift | 2 +- .../Bindings/TargetActionProxy.swift | 5 + .../Documentation.docc/AppKitNavigation.md | 4 + .../Articles/StackNavigationWithAppKitPlus.md | 108 ++++++++++++++++++ .../Navigation/NavigationDestination.swift | 2 +- 6 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/draft-appkit-stack-navigation.md index 1e91bf0f8e..7e436712f4 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/draft-appkit-stack-navigation.md @@ -7,7 +7,7 @@ - **所属愿景**: 无 - **关联提案**: [0005](0005-appkit-presentation-redesign.md)(弹出的共用生命周期)、[0004](0004-appkit-table-selection-bindings.md)(表格与大纲的选中绑定) - **实现分支 / PR**: `appkit-stack-navigation` -- **配套文档**: 待定 —— 落地时判断要不要写打开 trait 的使用指南 +- **配套文档**: DocC 文章 [Stack navigation with AppKitPlus](../../Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md),对外的使用说明 ## 摘要 @@ -261,7 +261,7 @@ extension NSOutlineView { 4. **`dismiss()`**(已完成):`traitCollection.dismiss` 与 `isPresented`,接进推入和现有五种弹出,各配测试。 5. **AppKitPlus 数据源的选中绑定**(已完成):两个 `bind(selection:dataSource:)`,各配双向测试。 6. **示例**(已完成):Examples 工程打开 trait,恢复「Stack navigation」一组,补两个案例;CaseStudies 的 macOS 版只编译,不点界面。 -7. **文档与验证**:DocC 首页与 skill;判断要不要写打开 trait 的使用指南。Xcode 27.2 跑 AppKit 的全部测试,trait 关闭、打开各一次;Xcode 26.6 在 trait 打开时编译库和 AppKit 测试。 +7. **文档与验证**(已完成):DocC 首页与 skill;判断要不要写打开 trait 的使用指南。Xcode 27.2 跑 AppKit 的全部测试,trait 关闭、打开各一次;Xcode 26.6 在 trait 打开时编译库和 AppKit 测试。 **收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): @@ -289,3 +289,5 @@ extension NSOutlineView { | 2026-11-09 | 按状态推入的内容,以「到过栈上、又离开了导航控制器、视图也离开了窗口」判定已经下屏 | 推入可能落在任意 `NSNavigationController` 里,不能占用它的委托;AppKitPlus 弹出时不发 `didMove(toParent: nil)`。在 run loop 每次等待前检查这三个条件;推入若因过渡进行中而排队,先等它落到栈上,结束时也先等它落到栈上再弹出 | | 2026-11-09 | `dismiss` 装在内容的 trait 覆盖里:视图控制器装在自己身上,窗口和存取面板装在窗口上,alert 装在它的窗口上,popover 装在内容视图控制器上 | AppKitPlus 里窗口也是 trait 环境,装在窗口上,窗口里的所有视图都能读到 | | 2026-11-09 | Examples 工程加一个指向仓库根目录、带 trait 的本地包引用,fork 的各个产品都改从它取 | Examples 原来经工作区的根包拿到这些产品,而 Xcode 的 trait 设置挂在工程的包引用上。实测 Xcode 27.2 接受这种写法,编译命令里出现 `-DAppKitPlus`;工作区的锁定文件随之多了 AppKitPlus-Release 0.21.0 一条 | +| 2026-11-09 | `TargetActionProxy.swift` 在 trait 打开时导入 AppKitPlus | AppKitPlus 也声明了 AppKit 的 `addTarget(_:action:for:)` 与 `NSControlEvents`,和 shim 声明的是同一个 AppKit 方法,运行时只有一份实现。macOS 27 以前的 SDK 里编译器选中 AppKitPlus 那份声明,没导入就报错(Xcode 26.6 打开 trait 时实测) | +| 2026-11-09 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试全部通过:trait 关闭时 XCTest 66 条、Swift Testing 77 条,与改动前相同;trait 打开时 XCTest 83 条、Swift Testing 80 条(各有 2 条故意触发的已知问题)。Xcode 26.6 在 trait 关闭、打开时都编译通过库和 AppKit 测试。生成文档在两种 trait 设置下都只有与上游共用内容里原有的 3 条警告。CaseStudies 的 macOS 版编译通过,没有打开界面去点。文档判断:打开 trait 的契约(连默认 trait 一起写、Swift 6.2 与 macOS 12 起、`delegate` 读到的是代理)在 API 签名里看不出来,写成 DocC 文章 `StackNavigationWithAppKitPlus` 作为使用说明,登记在头部「配套文档」;`swift-navigation-bindings` skill 补了 §4.1;探针得出的 AppKitPlus 行为写在代码注释和本提案里,不另写实现说明;没有新术语 | diff --git a/Sources/AppKitNavigation/Bindings/NSTableView.swift b/Sources/AppKitNavigation/Bindings/NSTableView.swift index 4f00d3107f..37fc63911e 100644 --- a/Sources/AppKitNavigation/Bindings/NSTableView.swift +++ b/Sources/AppKitNavigation/Bindings/NSTableView.swift @@ -109,7 +109,7 @@ extension NSTableView { /// Removes the binding established with /// ``AppKit/NSTableView/bind(selection:row:itemIdentifier:)`` or - /// ``AppKit/NSTableView/bind(selection:dataSource:)``. + /// ``AppKit/NSTableView/bind(selection:dataSource:)-(_,NSTableViewDiffableDataSource)``. public func unbindSelection() { removeBinding(to: \NSTableView.selectedRowIndexes) } diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index dc15deea70..8b88673c84 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -2,6 +2,11 @@ public import AppKit import AppKitNavigationShim +#if AppKitPlus + // NB: AppKitPlus declares the same AppKit control-event methods as the shim. Before the macOS 27 + // SDK, Swift settles on its declarations, which must then be visible here. + import AppKitPlus +#endif @MainActor class TargetActionProxy: NSObject { diff --git a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index ba66c1da52..ffb40b4a4c 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -39,6 +39,10 @@ to something that can outlive the object, capture the object `weak` instead. ## Topics +### Essentials + +- + ### Animations - ``withAppKitAnimation(_:_:completion:)`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md b/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md new file mode 100644 index 0000000000..b0d45bdc18 --- /dev/null +++ b/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md @@ -0,0 +1,108 @@ +# Stack navigation with AppKitPlus + +Drive a stack of view controllers from state, push destinations from optional state, and let +content that a binding showed close itself. + +## Overview + +AppKit has no navigation controller. With the package's `AppKitPlus` trait, AppKitNavigation builds +on the `NSNavigationController` of +[AppKitPlus](https://github.com/AppKitSupportProgram/AppKitPlus-Release) to offer what +UIKitNavigation offers on UIKit: + +- ``NavigationStackController``, whose stack follows a path of data; +- `navigationDestination(isPresented:)` and `navigationDestination(item:)`, which push a view + controller while optional state holds a value; +- `traitCollection.dismiss()`, with which pushed and presented content closes itself; +- selection bindings for tables and outlines driven by AppKitPlus's diffable data sources. + +### Turning the trait on + +The trait is off by default, and with it off the package neither fetches AppKitPlus nor offers +these APIs. Turn it on where you depend on the package, and name the default traits too: naming +any trait replaces them, and AppKitNavigation needs them. + +```swift +.package( + url: "https://github.com/MxIris-Library-Forks/swift-navigation", + from: "…", // a version that has the AppKitPlus trait + traits: [.defaults, "AppKitPlus"] +) +``` + +In an Xcode project, turn the trait on for the package in the project's Package Dependencies +(Xcode 26.4 or later), together with the default traits. + +The trait needs Swift 6.2 or later and macOS 12 or later. It adds AppKitPlus-Release 0.21.0 or +later to your app; AppKitPlus is a dynamic framework that the app embeds. + +### A stack driven by a path + +The path holds data rather than view controllers. Register how each type of data is shown, and +push by appending to the path, or with the `push` trait from inside the stack: + +```swift +let stackController = NavigationStackController(path: $model.path) { + PlanetListViewController(model: model) +} + +// In PlanetListViewController.viewDidLoad(): +navigationDestination(for: Planet.self) { planet in + PlanetViewController(planet: planet) +} + +// Anywhere inside the stack: +traitCollection.push(value: Planet.mars) +``` + +When the user goes back with the back button, ⌘↑ or a swipe, the path loses the elements whose view +controllers were popped. A path of mixed types can use `UINavigationPath`. + +### Pushing from optional state + +A view controller in a navigation controller can push a destination while optional state holds a +value, the way it presents one with `present(item:style:)`: + +```swift +navigationDestination(item: $model.selectedPlanet) { planet in + PlanetViewController(planet: planet) +} +``` + +Setting the state to `nil` pops the destination; going back past it sets the state to `nil`. A new +item, told apart by its identity, replaces the destination once the old one has left the screen. + +### Content that dismisses itself + +Content that a binding pushed or presented — with `navigationDestination`, `present`, `sheet`, +`modal`, `modalSession` or `popover` — can close itself without knowing how it was shown: + +```swift +doneButton.addAction { [weak self] _ in + self?.traitCollection.dismiss() +} +``` + +It ends as if the user had closed it: the binding is set to `nil`, and `onDismiss` runs once the +content has left the screen. + +### Things to know + +- A ``NavigationStackController`` puts a proxy in front of the delegate you set, so that the path + learns of the view controllers the user pops. The proxy passes every message on to your + delegate; reading `delegate` returns the proxy. +- AppKitPlus hands traits down to the view controllers inside on the next turn of the run loop, so + `push` and `dismiss` are there once a view controller is on screen. +- Pushes and pops are animated unless the change happens in a transaction that disables + animations. + +## Topics + +### Stacks + +- ``NavigationStackController`` +- ``AppKitPushAction`` + +### Dismissing + +- ``AppKitDismissAction`` diff --git a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift index 0e7138a890..759d7e8468 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift @@ -1,6 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus public import AppKit - public import AppKitPlus + import AppKitPlus public import SwiftNavigation import AppKitNavigationShim From f0685ad870f803799e78a7448f01db7071dd4f1d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 10 Nov 2026 11:10:40 +0800 Subject: [PATCH 119/141] docs: number proposals 0008 to 0011 and mark them implemented --- ...ve-unowned-self.md => 0008-observe-unowned-self.md} | 9 +++++---- ...indings.md => 0009-appkit-more-control-bindings.md} | 9 +++++---- ...e-study.md => 0010-appkit-animations-case-study.md} | 9 +++++---- ...k-navigation.md => 0011-appkit-stack-navigation.md} | 10 ++++++---- Documentations/Evolutions/README.md | 8 ++++---- Documentations/README.md | 8 ++++---- 6 files changed, 29 insertions(+), 24 deletions(-) rename Documentations/Evolutions/{draft-observe-unowned-self.md => 0008-observe-unowned-self.md} (87%) rename Documentations/Evolutions/{draft-appkit-more-control-bindings.md => 0009-appkit-more-control-bindings.md} (92%) rename Documentations/Evolutions/{draft-appkit-animations-case-study.md => 0010-appkit-animations-case-study.md} (78%) rename Documentations/Evolutions/{draft-appkit-stack-navigation.md => 0011-appkit-stack-navigation.md} (95%) diff --git a/Documentations/Evolutions/draft-observe-unowned-self.md b/Documentations/Evolutions/0008-observe-unowned-self.md similarity index 87% rename from Documentations/Evolutions/draft-observe-unowned-self.md rename to Documentations/Evolutions/0008-observe-unowned-self.md index 77a9b57fbe..12df45601d 100644 --- a/Documentations/Evolutions/draft-observe-unowned-self.md +++ b/Documentations/Evolutions/0008-observe-unowned-self.md @@ -1,9 +1,9 @@ -# Draft - 简化 `observe` 闭包里对 `self` 的捕获 +# 0008 - 简化 `observe` 闭包里对 `self` 的捕获 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-09 -- **最后更新**: 2026-11-09 -- **实现分支**: `appkit-more-control-bindings` +- **最后更新**: 2026-11-10 +- **实现分支**: `appkit-more-control-bindings`,已合进 `main` ## 摘要 @@ -55,3 +55,4 @@ observe { [unowned self] in | 2026-11-09 | 用户选定推荐 `[unowned self]`,不加把对象传进闭包的新重载 | 新重载要在每次访问成员时写 `owner.`,下游多行闭包反而更啰嗦;`[unowned self]` 保留隐式 `self`,闭包体不用改 | | 2026-11-09 | 用户批准,开始实现 | 与另两份提案在同一条分支 `appkit-more-control-bindings` 上实现,做完在本地合进 `main`、不推送 | | 2026-11-09 | 实现完成,待用户看过后收尾 | 两条回归测试通过;DocC 首页加了一节「Observing from a view or view controller」,`swift-navigation-bindings` skill 的示例、说明和常见错误同步改成 `[unowned self]`;AppKit 案例 12 处改完,CaseStudies 的 macOS 版编译通过。文档判断:推荐写法和前提都写进了 DocC 和 skill,不需要另写使用指南或实现说明,没有新术语 | +| 2026-11-10 | Implemented,编号 0008,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:两条回归测试与 AppKit 全部测试通过,CaseStudies 的 macOS 版编译通过;合进 `main` 的代码与测过的功能分支相同。下游 App 改用新写法不在这一批。文档判断同上一行:不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/draft-appkit-more-control-bindings.md b/Documentations/Evolutions/0009-appkit-more-control-bindings.md similarity index 92% rename from Documentations/Evolutions/draft-appkit-more-control-bindings.md rename to Documentations/Evolutions/0009-appkit-more-control-bindings.md index 04cce7011b..613cf760b9 100644 --- a/Documentations/Evolutions/draft-appkit-more-control-bindings.md +++ b/Documentations/Evolutions/0009-appkit-more-control-bindings.md @@ -1,9 +1,9 @@ -# Draft - AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中 +# 0009 - AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-09 -- **最后更新**: 2026-11-09 -- **实现分支**: `appkit-more-control-bindings` +- **最后更新**: 2026-11-10 +- **实现分支**: `appkit-more-control-bindings`,已合进 `main` ## 摘要 @@ -83,3 +83,4 @@ collectionView.bind(selection: $model.focusedSymbolID, dataSource: dataSource) | 2026-11-09 | 数据源更新拿走或重载掉的选中项,标识留在绑定里;项上屏时按绑定重新选上 | 集合视图对这两种变化什么都不报,绑定无从写回;绑定是选中的来源,项回到屏幕上时以它为准 | | 2026-11-09 | 数据源版本的集合视图绑定标 `@available(macOS 10.15.1, *)`;代理类所在文件改为 `public import AppKit`;两份新测试文件在 Swift 6.4 以前的编译器下 `public import Observation` | Xcode 26.6 用 6.2 那份清单,最低系统是 macOS 10.15,而 `NSCollectionViewDiffableDataSource` 从 10.15.1 起才有;Swift 6.2 把这些遵循当成公开的,公开遵循需要公开导入 | | 2026-11-09 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试全部通过:XCTest 66 条,Swift Testing 77 条(其中 2 条是故意触发的已知问题);Xcode 26.6 编译库和 AppKit 测试通过;生成文档只有与上游共用内容里原有的 3 条链接警告;CaseStudies 的 macOS 版经 `SwiftNavigation.xcworkspace` 编译通过,没有点界面。文档判断:用法和契约(集合视图的转发代理、App 自加的菜单项)写在文档注释和 `swift-navigation-bindings` skill 里,DocC 首页登记了 `NSTextView` 和 `NSCollectionView`;探针得出的 AppKit 行为记在代码注释和本提案里,不另写实现说明;没有新术语 | +| 2026-11-10 | Implemented,编号 0009,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:AppKit 测试全部通过,Xcode 26.6 编译通过,CaseStudies 的 macOS 版编译通过,界面没有点过;合进 `main` 的代码与测过的功能分支相同。后续项:表格与大纲的多选,照集合视图的 `Set` 版本补。文档判断同上一行:不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/draft-appkit-animations-case-study.md b/Documentations/Evolutions/0010-appkit-animations-case-study.md similarity index 78% rename from Documentations/Evolutions/draft-appkit-animations-case-study.md rename to Documentations/Evolutions/0010-appkit-animations-case-study.md index c2624a8d41..219b8876fc 100644 --- a/Documentations/Evolutions/draft-appkit-animations-case-study.md +++ b/Documentations/Evolutions/0010-appkit-animations-case-study.md @@ -1,9 +1,9 @@ -# Draft - AppKit 动画案例 +# 0010 - AppKit 动画案例 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-09 -- **最后更新**: 2026-11-09 -- **实现分支**: `appkit-more-control-bindings` +- **最后更新**: 2026-11-10 +- **实现分支**: `appkit-more-control-bindings`,已合进 `main` ## 摘要 @@ -30,3 +30,4 @@ AppKit 案例列表里的「Animations」一项一直是注释掉的:UIKit 有 | 2026-11-09 | Created as Draft | AppKit 案例列表里只有动画一项还注释着,用户选定补上 | | 2026-11-09 | 用户批准,开始实现 | 与另两份提案在同一条分支上实现,做完在本地合进 `main`、不推送 | | 2026-11-09 | 实现完成,待用户看过后收尾 | 新增 `AppKit+AnimationsViewController.swift` 并登记进 `Examples.xcodeproj`,案例列表恢复这一项。CaseStudies 的 macOS 版经 `SwiftNavigation.xcworkspace` 编译通过,新文件没有警告;没有打开界面去点,圆的位移、缩放和换色是否真的有过渡没有实测。文档判断:案例本身就是示例文档,不需要使用指南或实现说明,没有新术语 | +| 2026-11-10 | Implemented,编号 0010,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:CaseStudies 的 macOS 版编译通过;界面没有点过,圆的位移、缩放和换色是否真有过渡仍未实测。文档判断同上一行:案例本身就是示例文档,不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/draft-appkit-stack-navigation.md b/Documentations/Evolutions/0011-appkit-stack-navigation.md similarity index 95% rename from Documentations/Evolutions/draft-appkit-stack-navigation.md rename to Documentations/Evolutions/0011-appkit-stack-navigation.md index 7e436712f4..a57c5e547a 100644 --- a/Documentations/Evolutions/draft-appkit-stack-navigation.md +++ b/Documentations/Evolutions/0011-appkit-stack-navigation.md @@ -1,12 +1,12 @@ -# Draft - 可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit +# 0011 - 可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit -- **状态**: In Progress +- **状态**: Implemented - **作者**: JH - **创建日期**: 2026-11-09 -- **最后更新**: 2026-11-09 +- **最后更新**: 2026-11-10 - **所属愿景**: 无 - **关联提案**: [0005](0005-appkit-presentation-redesign.md)(弹出的共用生命周期)、[0004](0004-appkit-table-selection-bindings.md)(表格与大纲的选中绑定) -- **实现分支 / PR**: `appkit-stack-navigation` +- **实现分支 / PR**: `appkit-stack-navigation`,已合进 `main` - **配套文档**: DocC 文章 [Stack navigation with AppKitPlus](../../Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md),对外的使用说明 ## 摘要 @@ -291,3 +291,5 @@ extension NSOutlineView { | 2026-11-09 | Examples 工程加一个指向仓库根目录、带 trait 的本地包引用,fork 的各个产品都改从它取 | Examples 原来经工作区的根包拿到这些产品,而 Xcode 的 trait 设置挂在工程的包引用上。实测 Xcode 27.2 接受这种写法,编译命令里出现 `-DAppKitPlus`;工作区的锁定文件随之多了 AppKitPlus-Release 0.21.0 一条 | | 2026-11-09 | `TargetActionProxy.swift` 在 trait 打开时导入 AppKitPlus | AppKitPlus 也声明了 AppKit 的 `addTarget(_:action:for:)` 与 `NSControlEvents`,和 shim 声明的是同一个 AppKit 方法,运行时只有一份实现。macOS 27 以前的 SDK 里编译器选中 AppKitPlus 那份声明,没导入就报错(Xcode 26.6 打开 trait 时实测) | | 2026-11-09 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试全部通过:trait 关闭时 XCTest 66 条、Swift Testing 77 条,与改动前相同;trait 打开时 XCTest 83 条、Swift Testing 80 条(各有 2 条故意触发的已知问题)。Xcode 26.6 在 trait 关闭、打开时都编译通过库和 AppKit 测试。生成文档在两种 trait 设置下都只有与上游共用内容里原有的 3 条警告。CaseStudies 的 macOS 版编译通过,没有打开界面去点。文档判断:打开 trait 的契约(连默认 trait 一起写、Swift 6.2 与 macOS 12 起、`delegate` 读到的是代理)在 API 签名里看不出来,写成 DocC 文章 `StackNavigationWithAppKitPlus` 作为使用说明,登记在头部「配套文档」;`swift-navigation-bindings` skill 补了 §4.1;探针得出的 AppKitPlus 行为写在代码注释和本提案里,不另写实现说明;没有新术语 | +| 2026-11-10 | Implemented,编号 0011,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:trait 关闭的两次运行早于最后一处代码改动(`TargetActionProxy.swift` 的条件导入),那处改动只在 trait 打开时参与编译,trait 打开的几次运行都在它之后;合进 `main` 的代码与测过的功能分支相同。界面没有点过。文档判断同上一行:DocC 文章 `StackNavigationWithAppKitPlus` 作为使用说明,不另写实现说明,没有新术语 | +| 2026-11-10 | 后续项:CaseStudies 的 macOS 版补上 `@executable_path/../Frameworks` 这条框架搜索路径 | 收尾时检查构建产物发现:AppKitPlus.framework 已拷进 App 的 `Contents/Frameworks`,但工程的 `LD_RUNPATH_SEARCH_PATHS` 只有 iOS 用的 `@executable_path/Frameworks`,App 离开 Xcode 打开时找不到这个框架。从 Xcode 运行时,Xcode 把构建目录加进 `DYLD_FRAMEWORK_PATH`,按理能找到。两种启动方式都没有实测 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 702adf2793..c0084e0c34 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -13,7 +13,7 @@ | 0005 | [AppKit 弹出 API 重做:生命周期收进一层,重载合并](0005-appkit-presentation-redesign.md) | Implemented | | 0006 | [把 `ModalContent` 改名为 `WindowBackedContent`](0006-appkit-window-backed-content.md) | Implemented | | 0007 | [给 AppKit 案例补上弹出与新控件绑定的演示](0007-appkit-case-studies.md) | Implemented | -| draft | [简化 `observe` 闭包里对 `self` 的捕获](draft-observe-unowned-self.md) | In Progress | -| draft | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](draft-appkit-more-control-bindings.md) | In Progress | -| draft | [AppKit 动画案例](draft-appkit-animations-case-study.md) | In Progress | -| draft | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](draft-appkit-stack-navigation.md) | In Progress | +| 0008 | [简化 `observe` 闭包里对 `self` 的捕获](0008-observe-unowned-self.md) | Implemented | +| 0009 | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](0009-appkit-more-control-bindings.md) | Implemented | +| 0010 | [AppKit 动画案例](0010-appkit-animations-case-study.md) | Implemented | +| 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index 8c80e540da..8f2832739a 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -12,10 +12,10 @@ - [0005-appkit-presentation-redesign.md](Evolutions/0005-appkit-presentation-redesign.md):AppKit 弹出 API 重做——生命周期收进一层,重载合并。 - [0006-appkit-window-backed-content.md](Evolutions/0006-appkit-window-backed-content.md):把公开协议 `ModalContent` 改名为 `WindowBackedContent`。 - [0007-appkit-case-studies.md](Evolutions/0007-appkit-case-studies.md):给 AppKit 案例补上弹出与新控件绑定的演示。 -- [draft-observe-unowned-self.md](Evolutions/draft-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获(In Progress)。 -- [draft-appkit-more-control-bindings.md](Evolutions/draft-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中(In Progress)。 -- [draft-appkit-animations-case-study.md](Evolutions/draft-appkit-animations-case-study.md):AppKit 动画案例(In Progress)。 -- [draft-appkit-stack-navigation.md](Evolutions/draft-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit(In Progress)。 +- [0008-observe-unowned-self.md](Evolutions/0008-observe-unowned-self.md):简化 `observe` 闭包里对 `self` 的捕获。 +- [0009-appkit-more-control-bindings.md](Evolutions/0009-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中。 +- [0010-appkit-animations-case-study.md](Evolutions/0010-appkit-animations-case-study.md):AppKit 动画案例。 +- [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 ## Internal From 935bcc3eacaffc448a5f91e8252ae5e1b7f0792a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Tue, 10 Nov 2026 11:20:31 +0800 Subject: [PATCH 120/141] fix(examples): add the macOS framework search path so the case studies app finds AppKitPlus --- Documentations/Evolutions/0011-appkit-stack-navigation.md | 1 + Examples/Examples.xcodeproj/project.pbxproj | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/Documentations/Evolutions/0011-appkit-stack-navigation.md b/Documentations/Evolutions/0011-appkit-stack-navigation.md index a57c5e547a..430a37ccc7 100644 --- a/Documentations/Evolutions/0011-appkit-stack-navigation.md +++ b/Documentations/Evolutions/0011-appkit-stack-navigation.md @@ -293,3 +293,4 @@ extension NSOutlineView { | 2026-11-09 | 实现完成,待用户看过后收尾 | Xcode 27.2 上 AppKit 测试全部通过:trait 关闭时 XCTest 66 条、Swift Testing 77 条,与改动前相同;trait 打开时 XCTest 83 条、Swift Testing 80 条(各有 2 条故意触发的已知问题)。Xcode 26.6 在 trait 关闭、打开时都编译通过库和 AppKit 测试。生成文档在两种 trait 设置下都只有与上游共用内容里原有的 3 条警告。CaseStudies 的 macOS 版编译通过,没有打开界面去点。文档判断:打开 trait 的契约(连默认 trait 一起写、Swift 6.2 与 macOS 12 起、`delegate` 读到的是代理)在 API 签名里看不出来,写成 DocC 文章 `StackNavigationWithAppKitPlus` 作为使用说明,登记在头部「配套文档」;`swift-navigation-bindings` skill 补了 §4.1;探针得出的 AppKitPlus 行为写在代码注释和本提案里,不另写实现说明;没有新术语 | | 2026-11-10 | Implemented,编号 0011,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:trait 关闭的两次运行早于最后一处代码改动(`TargetActionProxy.swift` 的条件导入),那处改动只在 trait 打开时参与编译,trait 打开的几次运行都在它之后;合进 `main` 的代码与测过的功能分支相同。界面没有点过。文档判断同上一行:DocC 文章 `StackNavigationWithAppKitPlus` 作为使用说明,不另写实现说明,没有新术语 | | 2026-11-10 | 后续项:CaseStudies 的 macOS 版补上 `@executable_path/../Frameworks` 这条框架搜索路径 | 收尾时检查构建产物发现:AppKitPlus.framework 已拷进 App 的 `Contents/Frameworks`,但工程的 `LD_RUNPATH_SEARCH_PATHS` 只有 iOS 用的 `@executable_path/Frameworks`,App 离开 Xcode 打开时找不到这个框架。从 Xcode 运行时,Xcode 把构建目录加进 `DYLD_FRAMEWORK_PATH`,按理能找到。两种启动方式都没有实测 | +| 2026-11-10 | 补上 CaseStudies macOS 版的 `@executable_path/../Frameworks` | 用户选定补上。只加在 macOS 的构建设置里(`LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]`,写法与 Xcode 多平台模板相同),iOS 不变。编译后核对:App 的两份二进制都带这条搜索路径,AppKitPlus.framework 在 `Contents/Frameworks` 里;没有启动 App | diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index df18f59765..6bb2b0256a 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -895,6 +895,10 @@ "$(inherited)", "@executable_path/Frameworks", ); + "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.CaseStudies; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -926,6 +930,10 @@ "$(inherited)", "@executable_path/Frameworks", ); + "LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); MARKETING_VERSION = 1.0; PRODUCT_BUNDLE_IDENTIFIER = co.pointfree.CaseStudies; PRODUCT_NAME = "$(TARGET_NAME)"; From 04be09e8d012b25a6a53c05a4a1c668818dce881 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 11:48:45 +0800 Subject: [PATCH 121/141] fix(appkit): ignore the action a binding's own update sends Setting a color panel's color sends the panel's action, which setting a control's value does not. The binding sets the color itself whenever the bound value changes, and took the action that followed for the user's pick: it wrote the panel's reading of the color back over the bound value. A dynamic color such as labelColor came back fixed, and anything the binding was projected through saw a write it never asked for. The key-value observation was already ignored while the binding sets the value; the action now is too. Every binding built on establishBinding goes through the same path, and the color panel is the only owner that sends its action when set, so nothing else changes. --- .../Bindings/TargetActionProtocol.swift | 7 +++-- .../ColorPanelBindingTests.swift | 30 ++++++++++++++++++- 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift index 86472d600d..ca3fb725af 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -108,8 +108,12 @@ func establishBinding( set: @escaping (_ owner: Owner, _ newValue: Value, _ transaction: UITransaction) -> Void ) -> ObserveToken { owner.removeBinding(to: keyPath) + let isSetting = LockIsolated(false) let actionID = actionProxy?.addBindingAction { [weak owner] _ in - guard let owner else { return } + // NB: Setting a color panel's color sends the panel's action, unlike setting a control's + // value. An action sent while the binding sets the value is its own echo, not the user's + // doing, and writing it back would replace the bound value with the owner's reading of it. + guard let owner, isSetting.withLock({ !$0 }) else { return } if let valueAfterAction { guard let value = valueAfterAction(owner) else { return } binding.wrappedValue = value @@ -118,7 +122,6 @@ func establishBinding( } } - let isSetting = LockIsolated(false) let token = owner.observe { [weak owner] transaction in guard let owner else { return } isSetting.withLock { $0 = true } diff --git a/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift b/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift index b9ea401fb6..519685f48c 100644 --- a/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift +++ b/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift @@ -47,6 +47,26 @@ #expect(swatch.color == Self.green) } + /// Setting the panel's color sends its action, unlike setting a control's value. The binding + /// sets the color itself whenever the bound value changes, so that action is its own echo: taken + /// for the user's pick, it wrote the panel's color back over the bound value, and a dynamic color + /// such as `labelColor` came back as whatever the panel had made of it. + @Test("setting the panel's color from the binding writes nothing back") + func settingTheColorWritesNothingBack() async { + @UIBinding var swatch = Swatch(color: Self.red) + let colorPanel = NSColorPanel.shared + colorPanel.bind(color: $swatch.color) + defer { colorPanel.unbind(\.color) } + #expect(swatch.writeCount == 0) + + swatch.color = NSColor.labelColor + for _ in 0..<5 { await Task.yield() } + + #expect(colorPanel.color == NSColor.labelColor) + #expect(swatch.writeCount == 1) + #expect(swatch.color === NSColor.labelColor) + } + private final class ColorRecipient: NSObject { @objc func takeColor(_ sender: Any?) {} } @@ -54,7 +74,15 @@ /// Holds the color in a value, the way a model would, rather than binding a class instance /// directly. private struct Swatch { - var color: NSColor + var color: NSColor { + didSet { writeCount += 1 } + } + /// How many times the color was written after the swatch was made. + var writeCount = 0 + + init(color: NSColor) { + self.color = color + } } private static let red = NSColor(srgbRed: 1, green: 0, blue: 0, alpha: 1) From 5f37af80347e4d6446f9abc6423d9c5e541b88f0 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:19:57 +0800 Subject: [PATCH 122/141] refactor(appkit): follow view controller presentations without swizzling `present`, `destination` and `navigationDestination` learned when a presenter's view appeared, and when the user dismissed a presented view controller, from implementations the shim exchanged into `NSViewController`'s `viewDidAppear`, `viewDidDisappear` and `dismissViewController:`. That changed the behaviour of every view controller in the app. Both are now watched with `RunLoopWait`, the way sheets, popovers and pushes already were: - A presentation waits until the presenter's view is in a window on screen; a push waits until the navigation stack is, so a presenter that something else covers still pushes onto the top. - A presented view controller ends once AppKit has listed it among the presenter's presented view controllers, has dropped it again, and its window is off screen. `RunLoopWait` now also checks as each run of the main run loop ends, and after Core Animation's commit, so a dismissal is written back before the next event is handled. Draft proposal: Documentations/Evolutions/draft-appkit-remove-shim.md --- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-appkit-remove-shim.md | 45 +++++++ Documentations/README.md | 1 + .../Internal/RunLoopWait.swift | 19 ++- .../Navigation/NavigationDestination.swift | 37 +++--- .../Navigation/Presentation.swift | 118 +++++++++++------ Sources/AppKitNavigationShim/include/shim.h | 8 -- Sources/AppKitNavigationShim/shim.m | 119 ------------------ .../NavigationDestinationTests.swift | 24 ++++ .../ObjectiveCMethodNamingTests.swift | 8 +- .../ViewControllerPresentationTests.swift | 65 +++++++++- 11 files changed, 248 insertions(+), 197 deletions(-) create mode 100644 Documentations/Evolutions/draft-appkit-remove-shim.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index c0084e0c34..aec0964d01 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -17,3 +17,4 @@ | 0009 | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](0009-appkit-more-control-bindings.md) | Implemented | | 0010 | [AppKit 动画案例](0010-appkit-animations-case-study.md) | Implemented | | 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | +| draft | [去掉 AppKitNavigationShim:不再交换系统方法](draft-appkit-remove-shim.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md new file mode 100644 index 0000000000..6bbab1f42b --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -0,0 +1,45 @@ +# Draft - 去掉 AppKitNavigationShim:不再交换系统方法 + +- **状态**: In Progress +- **创建日期**: 2026-11-14 +- **最后更新**: 2026-11-14 +- **实现分支**: `appkit-remove-shim` + +## 摘要 + +`AppKitNavigationShim` 是一个 Objective-C target,在 `+load` 里交换了五个系统方法:`NSViewController` 的 `viewDidAppear`、`viewDidDisappear`、`dismissViewController:`,以及 `NSSavePanel` 的私有方法 `setFinalURL:`、`setFinalURLs:`;另外为 macOS 27 以前的 SDK 重新声明了 `NSControl` 的多 target-action API。交换方法改变的是 App 里每一个视图控制器和存取面板的行为,依赖的私有方法被系统改名时还会静默失效。这一批把它整个删掉:前三个交换改用库里已有的 `RunLoopWait`(主 run loop 每次要休眠前检查一次条件),存取面板的 URL 绑定改由库的 `sheet` / `modal` 在面板以「确定」结束时写回,NSControl 的重复声明直接删除——项目已统一使用 Xcode 27,它的 SDK 自带这组 API。 + +## 方案 + +| shim 做的事 | 用途 | 替代 | +|---|---|---| +| 交换 `viewDidAppear`,记下「视图出现过」并执行排队的闭包 | `present`、`destination` 等到发起者的视图出现后再弹出;`navigationDestination` 等到它出现后再 push | `RunLoopWait` 等条件成立:弹出要等发起者的视图在一个可见窗口里,`NSWindow.sheet` 与 `NSView.popover` 早就这么判断;push 要等发起者所在的导航控制器的视图在可见窗口里 | +| 交换 `dismissViewController:` 与 `viewDidDisappear`,在被关闭的视图控制器消失时回调 | 用户自己关掉弹出的视图控制器(接到 `dismissController:` 的取消按钮、transient popover 收起)时把绑定写回 | 弹出之前就开始用 `RunLoopWait` 盯着:视图控制器出现在发起者的 `presentedViewControllers` 里之后,等它离开这个列表、窗口也不再可见,就算结束。`navigationDestination` 早就用同样的办法判断 pop | +| 交换私有的 `setFinalURL:` / `setFinalURLs:` | `NSSavePanel(url:)`、`NSOpenPanel(urls:)` 把用户确认的 URL 写回绑定 | `WindowBackedContent` 给存取面板的实现里,`beginSheetModal` 回调收到的、或 `runModal` 返回的结果是 `.OK` 时写回 | +| 重新声明 `NSControlEvents` 与 `addTarget(_:action:for:)` | 旧 SDK 下也能编过 `TargetActionProxy` | 删除;`TargetActionProxy` 里为旧 SDK 导入 AppKitPlus 的变通一起删 | + +落地步骤(每步各自构建、测试通过): + +1. **弹出生命周期**(已完成):`Presentation.swift` 与 `NavigationDestination.swift` 改用 `RunLoopWait`,删掉 shim 里 `NSViewController` 的部分。补测试:用户关掉以 popover、模态窗口弹出的视图控制器时绑定写回;被别的页面盖住的发起者照样立刻 push。方法命名测试改用 `-[NSButton appKitNavigationIsOn]` 作扫描锚点。`RunLoopWait` 的检查时机同时调整,见决策日志。 +2. **存取面板绑定**:改走 `sheet` / `modal` 的结果,删掉 shim 里 `NSSavePanel` 的部分和检查私有 setter 的测试。补测试:确认后写回、取消不动、重新绑定只写新绑定。方法命名测试不再有例外。 +3. **NSControl 与 target 本身**:删掉重复声明与 `TargetActionProxy` 的变通;shim 已空,从四份 Package 清单里删掉这个 target,删掉目录。 + +没有询问就采用的假设: + +- 存取面板的绑定只在经库的 `sheet` / `modal` 弹出时写回;App 自己调用 `begin` / `runModal` 时不写回,结果从完成回调里取。取消时绑定保持原值。依赖这个 fork 的 App(PrivateSymbols)与案例都只经 `sheet` / `modal` 使用,读完即清空。 +- 弹出的就绪条件从「发起者的视图出现过」改为「发起者的视图此刻在可见窗口里」:视图出现过又离开窗口时(切到别的标签页、被导航栈里的新页面盖住),绑定再变成有值会等它回到屏幕上再弹,不再立刻弹出一个没有窗口可依附的 sheet。以模态窗口弹出不需要发起者的窗口,也照此等待。 +- push 的就绪条件是「导航栈在屏幕上」而不是「发起者在屏幕上」:被盖住的发起者照旧立刻把新页面压到栈顶,与改动前一致。 +- 盯着用户关闭的检查在整个弹出期间每轮 run loop 做一次,只是一次闭包调用,与 `navigationDestination` 的做法相同。 +- AppKitNavigation 从此只能用 Xcode 27(macOS 27 SDK)编译。`Package@swift-6.0/6.1/6.2.swift` 来自上游,保留,只删 shim target;上游从来没有这个 target,删掉后与上游更接近。 +- `UIKitNavigationShim` 也在交换方法,不在这一批的范围里。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-14 | Created as Draft | 用户不想再让库交换系统方法,并确认项目已统一使用 Xcode 27,要求删掉 AppKitNavigationShim | +| 2026-11-14 | 用户批准,开始实现 | 用户在对话里看过替代方案后批准开工,并选定存取面板的绑定保留 API、由库的 `sheet` / `modal` 写回;提案正文由 agent 起草,用户事前未审阅 | +| 2026-11-14 | push 的就绪条件看导航栈而不是发起者 | 起草时打算统一用「发起者在屏幕上」,实现前发现这会让被盖住的发起者推不出新页面,改变既有行为;弹出 sheet 和 popover 确实需要发起者的窗口,所以只在 push 上区别对待 | +| 2026-11-14 | 弹出之后立刻同步记一次「已列入 `presentedViewControllers`」,不只靠 run loop 检查 | 测试里用户在同一轮 run loop 内就关掉了 sheet,检查还没来得及看到它被弹出,于是永远等不到「离开列表」 | +| 2026-11-14 | `RunLoopWait` 除了 run loop 要休眠时,每次一轮运行结束时也检查,并排在所有同阶段的观察者(含 Core Animation 的提交)之后 | AppKit 每取一个事件都单独跑一轮 run loop,这样用户关闭弹出内容后,下一个事件被处理之前就已写回绑定,用户紧接着再要求弹出不会被这次写回冲掉。这个改动作用于所有用 `RunLoopWait` 的风格,AppKit 测试全部通过 | +| 2026-11-14 | 用户关闭后的写回不再与 AppKit 的关闭同步发生,`testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt` 改为等写回之后再立刻设回 `true` | 交换方法时写回发生在 `viewDidDisappear` 里,不交换就没有同步的时机。原测试在同一段同步代码里关闭 sheet 又设回 `true`,真实使用中两次操作之间总隔着事件循环;改后仍覆盖它要测的情形:中间那次 `false` 没被 `observe` 看到时,内容照样能再弹出 | diff --git a/Documentations/README.md b/Documentations/README.md index 8f2832739a..256da6cc98 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -16,6 +16,7 @@ - [0009-appkit-more-control-bindings.md](Evolutions/0009-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中。 - [0010-appkit-animations-case-study.md](Evolutions/0010-appkit-animations-case-study.md):AppKit 动画案例。 - [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 +- [draft-appkit-remove-shim.md](Evolutions/draft-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 ## Internal diff --git a/Sources/AppKitNavigation/Internal/RunLoopWait.swift b/Sources/AppKitNavigation/Internal/RunLoopWait.swift index d0397f9617..e16ffe499a 100644 --- a/Sources/AppKitNavigation/Internal/RunLoopWait.swift +++ b/Sources/AppKitNavigation/Internal/RunLoopWait.swift @@ -4,13 +4,19 @@ /// Waits for something on screen to change — a window to come on screen, a view to get into a /// window, a sheet to finish leaving the screen — by checking each time the main run loop is - /// about to wait. + /// about to wait, and each time a run of it ends. /// /// Notifications are not reliable for this. A window brought on screen in a process that is not /// the active app — a test runner, for one — posts no occlusion, key or main window notification /// at all, a view has none for getting into a window, and a sheet's completion handler runs /// before the sheet has left the screen. The check costs a closure call per turn of the run /// loop, and only while something is waiting. + /// + /// The check comes after everything else the run loop does at those points, Core Animation's + /// commit included, so that it sees the screen as that turn leaves it. AppKit fetches every + /// event in a run of its own, so a change is seen before the next event is handled: a user who + /// dismisses content and at once asks for it again, for one, does not have the second request + /// undone by the first. @MainActor enum RunLoopWait { /// Calls `body` once `condition` holds — right away when it already does — and returns a @@ -26,7 +32,7 @@ // NB: In the common modes, so that the wait goes on inside modal loops and while the mouse // is tracking. nonisolated(unsafe) let observer = CFRunLoopObserverCreateWithHandler( - nil, CFRunLoopActivity.beforeWaiting.rawValue, true, 0 + nil, CFRunLoopActivity([.beforeWaiting, .exit]).rawValue, true, CFIndex.max ) { observer, _ in MainActor._assumeIsolated { guard condition() else { return } @@ -41,4 +47,13 @@ } } + extension NSViewController { + /// Whether the view controller's view is in a window that is on screen. + /// + /// Never loads the view: one that is not loaded yet is not on screen. + var appKitNavigationIsViewOnScreen: Bool { + isViewLoaded && view.window?.isVisible == true + } + } + #endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift index 759d7e8468..3ed8259779 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift @@ -2,7 +2,6 @@ public import AppKit import AppKitPlus public import SwiftNavigation - import AppKitNavigationShim extension NSViewController { /// Pushes a view controller onto the enclosing navigation controller while a binding to a @@ -12,7 +11,8 @@ /// `NSNavigationController`. Setting the binding to `false` pops the view controller, along /// with anything pushed above it. When the user goes back past it — with the back button, ⌘↑ /// or a swipe — or it dismisses itself with `traitCollection.dismiss()`, the binding is set to - /// `false`. The view controller is pushed once this view controller's view has appeared. + /// `false`. The view controller is pushed once the navigation controller is on screen, onto + /// the top of its stack. /// /// Available with the `AppKitPlus` package trait. /// @@ -166,20 +166,19 @@ weak var presenter: NSViewController? func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { - guard let presenter, !presenter._AppKitNavigation_hasViewAppeared else { - body() - return {} - } - let wait = PushWait() - presenter._AppKitNavigation_onViewAppear.append { - MainActor._assumeIsolated { - guard !wait.isCancelled else { return } - body() - } - } - return { - wait.isCancelled = true - } + // NB: What has to be on screen is the stack the push lands on, not the presenter: one that + // something else has been pushed over still pushes onto the top. A presenter in no + // navigation controller waits for its own view, and 'begin' then reports the misuse. One + // that has gone away counts as ready, so that 'begin' finds out. + RunLoopWait.until( + { [weak presenter] in + guard let presenter else { return true } + let navigationController = + presenter.navigationController ?? presenter as? NSNavigationController + return (navigationController ?? presenter).appKitNavigationIsViewOnScreen + }, + then: body + ) } func begin( @@ -249,12 +248,6 @@ } } - /// A wait that can be called off after it has been scheduled. - @MainActor - private final class PushWait { - var isCancelled = false - } - extension NSViewController { fileprivate var appKitNavigationPushRecord: PushRecord? { get { diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 01f8204c45..77c0a19824 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -1,6 +1,5 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit - import AppKitNavigationShim extension NSViewController { /// How a view controller presents another one. @@ -26,7 +25,7 @@ /// Like SwiftUI's `sheet` and `popover` view modifiers, but for AppKit. Setting the binding to /// `false` dismisses the view controller. When the user dismisses it — a Cancel button wired to /// `dismissController(_:)`, a transient popover closing — the binding is set to `false`. The - /// view controller is presented once this view controller's view has appeared. + /// view controller is presented once this view controller's view is in a window on screen. /// /// - Parameters: /// - isPresented: A binding to a Boolean value that determines whether to present the view @@ -161,10 +160,11 @@ /// provide is true. /// /// This helper powers ``present(isPresented:style:onDismiss:content:)``, and can define custom - /// transitions. A view controller dismissed through `dismiss(_:)` counts as having left the - /// screen once its view has disappeared. One that never went through AppKit's presentation, - /// such as a child added with `addChild(_:)`, counts as having left the screen as soon as - /// `dismiss` returns. + /// transitions. A view controller presented through AppKit counts as having left the screen + /// once AppKit no longer lists it among this view controller's presented view controllers and + /// its window is off screen. One that never went through AppKit's presentation, such as a + /// child added with `addChild(_:)`, counts as having left the screen as soon as `dismiss` + /// returns. /// /// - Parameters: /// - isPresented: A binding to a Boolean value that determines whether to present the view @@ -301,20 +301,13 @@ let transition: Transition func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { - guard let presenter, !presenter._AppKitNavigation_hasViewAppeared else { - body() - return {} - } - let wait = CancellableWait() - presenter._AppKitNavigation_onViewAppear.append { - MainActor._assumeIsolated { - guard !wait.isCancelled else { return } - body() - } - } - return { - wait.isCancelled = true - } + // NB: A sheet or a popover attaches to the presenter's window, so the presenter has to be on + // screen, the way 'NSWindow.sheet' and 'NSView.popover' wait for their anchors. One that + // has gone away counts as ready, so that 'begin' finds out. + RunLoopWait.until( + { [weak presenter] in presenter?.appKitNavigationIsViewOnScreen ?? true }, + then: body + ) } func begin( @@ -326,15 +319,27 @@ didEnd() return } - // NB: The user dismisses a presented view controller without going through the binding — a - // Cancel button wired to 'dismissController:', a transient popover closing — so the shim - // reports the dismissal, once the view controller's view has disappeared. It counts as - // ended once the window that showed it is off screen too. - child._AppKitNavigation_onDismiss = { [weak child] in - MainActor._assumeIsolated { - _ = RunLoopWait.until({ child?.view.window?.isVisible != true }, then: didEnd) - } - } + // NB: AppKit tells no one but the presenter that it dismissed a view controller, and the user + // can dismiss one without going through the binding: with a Cancel button wired to + // 'dismissController:', or by closing a transient popover. So the view controller is + // watched instead. Once AppKit has listed it among the presenter's presented view + // controllers, it counts as ended when it has left that list and its window is off + // screen. The watch starts before presenting, so that it also runs inside any modal loop + // presenting starts. + let record = PresentationRecord(didEnd: didEnd) + child.appKitNavigationPresentationRecord = record + _ = RunLoopWait.until( + { [weak presenter, weak child] in + guard !record.hasEnded, let child else { return true } + let isPresented = presenter?.presentedViewControllers?.contains(child) == true + if isPresented { + record.hasBeenPresented = true + } + return record.hasBeenPresented && !isPresented + && (!child.isViewLoaded || child.view.window?.isVisible != true) + }, + then: { record.end() } + ) switch transition { case let .style(style): presenter.present(child, as: style) @@ -343,6 +348,11 @@ present(child, transaction) } } + // NB: Noted right away as well, since the watch only looks when the run loop is about to + // wait: the user can dismiss the view controller before that. + if presenter.presentedViewControllers?.contains(child) == true { + record.hasBeenPresented = true + } } func end(_ child: NSViewController, transaction: UITransaction) { @@ -362,16 +372,52 @@ return } } - // NB: Not presented through AppKit, or no longer, so no dismissal will be reported. - let reportDismissal = child._AppKitNavigation_onDismiss - child._AppKitNavigation_onDismiss = nil - reportDismissal?() + // NB: One that went through AppKit's presentation ends once the watch sees it off screen. + // Any other one, and one whose presenter has gone away, ends now. + guard let record = child.appKitNavigationPresentationRecord else { return } + if record.hasBeenPresented, presenter != nil { + return + } + record.end() } } - /// A wait that can be called off after it has been scheduled. + /// What a view controller presented by ``ViewControllerPresentationStyle`` reports its end to. @MainActor - private final class CancellableWait { - var isCancelled = false + private final class PresentationRecord { + /// Whether AppKit has listed the view controller among its presenter's presented ones. + var hasBeenPresented = false + private var didEnd: (@MainActor () -> Void)? + + init(didEnd: @escaping @MainActor () -> Void) { + self.didEnd = didEnd + } + + var hasEnded: Bool { + didEnd == nil + } + + /// Reports that the view controller has ended, unless that has been reported already. + func end() { + guard let didEnd else { return } + self.didEnd = nil + didEnd() + } } + + extension NSViewController { + fileprivate var appKitNavigationPresentationRecord: PresentationRecord? { + get { + objc_getAssociatedObject(self, presentationRecordKey) as? PresentationRecord + } + set { + objc_setAssociatedObject( + self, presentationRecordKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + } + } + } + + @MainActor + private let presentationRecordKey = malloc(1)! #endif diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h index afe2026ce5..27589acb2c 100644 --- a/Sources/AppKitNavigationShim/include/shim.h +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -6,14 +6,6 @@ NS_ASSUME_NONNULL_BEGIN -@interface NSViewController (AppKitNavigation) - -@property BOOL _AppKitNavigation_hasViewAppeared; -@property (nullable) void (^ _AppKitNavigation_onDismiss)(); -@property NSArray *_AppKitNavigation_onViewAppear; - -@end - @interface NSSavePanel (AppKitNavigation) @property (nullable) void (^ AppKitNavigation_onFinalURL)(NSURL *_Nullable); @property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index adb0c61c38..f7c5d51f43 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -12,22 +12,7 @@ @interface AppKitNavigationShim : NSObject @implementation AppKitNavigationShim -// NB: We must use Objective-C here to eagerly swizzle view controller code that is responsible -// for state-driven presentation and dismissal of child features. - + (void)load { - method_exchangeImplementations( - class_getInstanceMethod(NSViewController.class, @selector(viewDidAppear)), - class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidAppear)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSViewController.class, @selector(viewDidDisappear)), - class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_viewDidDisappear)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSViewController.class, @selector(dismissViewController:)), - class_getInstanceMethod(NSViewController.class, @selector(AppKitNavigation_dismissViewController:)) - ); method_exchangeImplementations( class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) @@ -40,110 +25,6 @@ + (void)load { @end -static void *hasViewAppearedKey = &hasViewAppearedKey; -static void *isBeingDismissedKey = &isBeingDismissedKey; -static void *onDismissKey = &onDismissKey; -static void *onViewAppearKey = &onViewAppearKey; - -@interface NSViewController (AppKitNavigationDismissal) - -// NB: Set from 'dismissViewController:' on the controller being dismissed and consumed by its -// next 'viewDidDisappear'. Prefixed like everything else this file adds to AppKit's classes, so -// it cannot collide with a method AppKit adds later. -@property (setter=set_AppKitNavigation_isBeingDismissed:) BOOL _AppKitNavigation_isBeingDismissed; - -@end - -@implementation NSViewController (AppKitNavigationDismissal) - -- (BOOL)_AppKitNavigation_isBeingDismissed { - return [objc_getAssociatedObject(self, isBeingDismissedKey) boolValue]; -} - -- (void)set_AppKitNavigation_isBeingDismissed:(BOOL)isBeingDismissed { - objc_setAssociatedObject( - self, isBeingDismissedKey, @(isBeingDismissed), OBJC_ASSOCIATION_COPY_NONATOMIC - ); -} - -@end - -@implementation NSViewController (AppKitNavigation) - -- (void)AppKitNavigation_viewDidAppear { - [self AppKitNavigation_viewDidAppear]; - - if (self._AppKitNavigation_hasViewAppeared) { - return; - } - - self._AppKitNavigation_hasViewAppeared = YES; - - for (void (^work)() in self._AppKitNavigation_onViewAppear) { - work(); - } - - self._AppKitNavigation_onViewAppear = @[]; -} - -- (void)AppKitNavigation_viewDidDisappear { - [self AppKitNavigation_viewDidDisappear]; - - if (!self._AppKitNavigation_isBeingDismissed) { - return; - } - self._AppKitNavigation_isBeingDismissed = NO; - - void (^onDismiss)(void) = self._AppKitNavigation_onDismiss; - self._AppKitNavigation_onDismiss = nil; - if (onDismiss != NULL) { - onDismiss(); - } -} - -- (void)AppKitNavigation_dismissViewController:(NSViewController *)viewController { - // NB: The argument is the controller being dismissed; the receiver is its presenter (or the - // controller itself, when it dismisses itself). The flag belongs on the argument, and it - // has to be set before handing over, because a dismissal without animation reaches - // 'viewDidDisappear' before the original implementation returns. Only a controller that is - // actually presented is marked, so a stray call cannot leave a flag behind for some later, - // unrelated disappearance to act on. - if (viewController.presentingViewController != nil) { - viewController._AppKitNavigation_isBeingDismissed = YES; - } - [self AppKitNavigation_dismissViewController:viewController]; -} - -- (BOOL)_AppKitNavigation_hasViewAppeared { - return [objc_getAssociatedObject(self, hasViewAppearedKey) boolValue]; -} - -- (void)set_AppKitNavigation_hasViewAppeared:(BOOL)_AppKitNavigation_hasViewAppeared { - objc_setAssociatedObject( - self, hasViewAppearedKey, @(_AppKitNavigation_hasViewAppeared), OBJC_ASSOCIATION_COPY_NONATOMIC - ); -} - -- (void (^)())_AppKitNavigation_onDismiss { - return objc_getAssociatedObject(self, onDismissKey); -} - -- (void)set_AppKitNavigation_onDismiss:(void (^)())_AppKitNavigation_onDismiss { - objc_setAssociatedObject(self, onDismissKey, [_AppKitNavigation_onDismiss copy], OBJC_ASSOCIATION_COPY_NONATOMIC); -} - -- (NSMutableArray *)_AppKitNavigation_onViewAppear { - id onViewAppear = objc_getAssociatedObject(self, onViewAppearKey); - - return onViewAppear == nil ? @[] : onViewAppear; -} - -- (void)set_AppKitNavigation_onViewAppear:(NSMutableArray *)onViewAppear { - objc_setAssociatedObject(self, onViewAppearKey, onViewAppear, OBJC_ASSOCIATION_COPY_NONATOMIC); -} - -@end - @implementation NSSavePanel (AppKitNavigation) - (void)setAppKitNavigation_onFinalURLs:(void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { diff --git a/Tests/AppKitNavigationTests/NavigationDestinationTests.swift b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift index cc7232df53..fab11f5310 100644 --- a/Tests/AppKitNavigationTests/NavigationDestinationTests.swift +++ b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift @@ -61,6 +61,30 @@ XCTAssertEqual(dismissCount.value, 1) } + /// A push lands on top of the stack, wherever in it the view controller that asks for it is. + @MainActor + func testAViewControllerThatAnotherDestinationCoversStillPushes() { + let (navigationController, root) = makeNavigationController() + @UIBinding var isShowingSettings = false + @UIBinding var detail: Detail? = nil + root.navigationDestination(isPresented: $isShowingSettings) { + DetailViewController(name: "Settings") + } + root.navigationDestination(item: $detail) { detail in + DetailViewController(name: detail.name) + } + withoutAnimation { isShowingSettings = true } + XCTAssertTrue(waitUntil { topName(of: navigationController) == "Settings" }) + + withoutAnimation { detail = Detail(name: "Mars") } + + XCTAssertTrue( + waitUntil { topName(of: navigationController) == "Mars" }, + "The covered view controller's destination was not pushed" + ) + XCTAssertEqual(navigationController.viewControllers.count, 3) + } + @MainActor func testABooleanBindingPushesAndPops() { let (navigationController, root) = makeNavigationController() diff --git a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift index e6cff2e598..ae2aa4f9ff 100644 --- a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift +++ b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift @@ -24,7 +24,7 @@ // NB: The library is linked into the test binary. Should that change, the scan would find // nothing and pass for the wrong reason. try #require( - addedMethods.contains("-[NSViewController _AppKitNavigation_hasViewAppeared]"), + addedMethods.contains("-[NSButton appKitNavigationIsOn]"), "The scan must find the library's own methods" ) @@ -37,12 +37,8 @@ } /// The methods the library replaces on purpose: the shim exchanges its own implementations in - /// for these, to learn when a view controller appears, disappears or is dismissed, and what - /// the user confirmed in a save panel. + /// for these, to learn what the user confirmed in a save panel. private static let deliberatelyReplacedMethods: Set = [ - "-[NSViewController viewDidAppear]", - "-[NSViewController viewDidDisappear]", - "-[NSViewController dismissViewController:]", "-[NSSavePanel setFinalURL:]", "-[NSSavePanel setFinalURLs:]", ] diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift index 3d7fe55020..94b3b70994 100644 --- a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -90,11 +90,15 @@ isPresented = true XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") host.window.attachedSheet?.contentViewController?.dismiss(nil) - XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet never went away") + XCTAssertTrue( + waitUntil { host.window.attachedSheet == nil && !isPresented }, + "The sheet never went away, or 'false' was never written back" + ) - // NB: No waiting here on purpose. The dismissal writes 'false' back synchronously, but - // 'observe' only re-runs on a later turn of the main queue, so setting 'true' again - // straight away is exactly the case where the 'false' in between is never observed. + // NB: No more waiting here, on purpose. The dismissal writes 'false' back as the run loop + // turn that noticed it ends, but 'observe' only re-runs on a later turn of the main queue, + // so setting 'true' again straight away is exactly the case where the 'false' in between + // is never observed. isPresented = true XCTAssertTrue( @@ -263,6 +267,59 @@ ) } + @MainActor + func testUserDismissingAModalWindowWritesFalseBack() { + let host = makeHost() + let presentedViewController = makeViewController() + @UIBinding var isPresented = false + host.viewController.present(isPresented: $isPresented, style: .modalWindow) { + presentedViewController + } + abortModalLoops(after: 5) + + let start = Date() + perform(after: 0.5) { + // What a Cancel button wired to 'dismissController:' does. + presentedViewController.dismiss(nil) + } + isPresented = true + + XCTAssertTrue( + waitUntil(timeout: 4) { !isPresented }, + "Dismissing the modal window did not write 'false' back" + ) + XCTAssertLessThan( + Date().timeIntervalSince(start), 3, + "The modal window only went away when the safety timer aborted it" + ) + } + + // MARK: - Popover style + + @MainActor + func testUserClosingAPresentedPopoverWritesFalseBack() throws { + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var isPresented = false + host.viewController.present( + isPresented: $isPresented, + style: .popover( + rect: host.view.bounds, view: host.view, preferredEdge: .maxY, behavior: .transient + ) + ) { + self.makeViewController() + } + + isPresented = true + XCTAssertTrue( + waitUntil { recorder.shownPopovers.first?.isShown == true }, "The popover never appeared" + ) + // What a transient popover does once the user clicks elsewhere. + try XCTUnwrap(recorder.shownPopovers.first).close() + + XCTAssertTrue(waitUntil { !isPresented }, "Closing the popover did not write 'false' back") + } + // MARK: - Custom presentation @MainActor From c4af197fa72e7dda2c711b695804c70271e929c5 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:26:34 +0800 Subject: [PATCH 123/141] refactor(appkit): write save and open panel choices without swizzling `NSSavePanel(url:)` and `NSOpenPanel(urls:)` learned what the user confirmed from the private `setFinalURL:` / `setFinalURLs:` setters, which the shim exchanged its own implementations in for. The library's own sheet and modal presentation now writes the panel's `url` / `urls` to the bindings when the panel ends with `.OK`, before the presentation's `onDismiss` runs. Cancelling leaves the bindings as they are, and a panel the app runs itself no longer writes them: its response is the place to read the choice from. The tests confirm a real panel shown as a sheet and modally. The panel runs in another process and its local `ok(_:)` raises, so they end it through the private `completeWithReturnCode:url:urls:` the panel service uses, after checking it is there. Draft proposal: Documentations/Evolutions/draft-appkit-remove-shim.md --- .../Evolutions/draft-appkit-remove-shim.md | 4 +- ...it+PresentationGalleryViewController.swift | 2 + .../Bindings/NSSaveOpenPanel.swift | 106 +++++++++-- .../Navigation/WindowBackedContent.swift | 9 +- Sources/AppKitNavigationShim/include/shim.h | 5 - Sources/AppKitNavigationShim/shim.m | 56 ------ .../ControlBindingLifetimeTests.swift | 40 ---- .../ControlBindingRoundTripTests.swift | 11 -- .../ObjectiveCMethodNamingTests.swift | 11 +- .../PanelBindingTests.swift | 171 ++++++++++++++++++ 10 files changed, 275 insertions(+), 140 deletions(-) create mode 100644 Tests/AppKitNavigationTests/PanelBindingTests.swift diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md index 6bbab1f42b..0fdf0f1d75 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -21,7 +21,7 @@ 落地步骤(每步各自构建、测试通过): 1. **弹出生命周期**(已完成):`Presentation.swift` 与 `NavigationDestination.swift` 改用 `RunLoopWait`,删掉 shim 里 `NSViewController` 的部分。补测试:用户关掉以 popover、模态窗口弹出的视图控制器时绑定写回;被别的页面盖住的发起者照样立刻 push。方法命名测试改用 `-[NSButton appKitNavigationIsOn]` 作扫描锚点。`RunLoopWait` 的检查时机同时调整,见决策日志。 -2. **存取面板绑定**:改走 `sheet` / `modal` 的结果,删掉 shim 里 `NSSavePanel` 的部分和检查私有 setter 的测试。补测试:确认后写回、取消不动、重新绑定只写新绑定。方法命名测试不再有例外。 +2. **存取面板绑定**(已完成):改走 `sheet` / `modal` 的结果,删掉 shim 里 `NSSavePanel` 的部分和检查私有 setter 的测试。补测试:确认后写回、取消不动、重新绑定只写新绑定。方法命名测试不再有例外。案例里的存储面板改为弹出前先清空上次选的 URL。 3. **NSControl 与 target 本身**:删掉重复声明与 `TargetActionProxy` 的变通;shim 已空,从四份 Package 清单里删掉这个 target,删掉目录。 没有询问就采用的假设: @@ -42,4 +42,6 @@ | 2026-11-14 | push 的就绪条件看导航栈而不是发起者 | 起草时打算统一用「发起者在屏幕上」,实现前发现这会让被盖住的发起者推不出新页面,改变既有行为;弹出 sheet 和 popover 确实需要发起者的窗口,所以只在 push 上区别对待 | | 2026-11-14 | 弹出之后立刻同步记一次「已列入 `presentedViewControllers`」,不只靠 run loop 检查 | 测试里用户在同一轮 run loop 内就关掉了 sheet,检查还没来得及看到它被弹出,于是永远等不到「离开列表」 | | 2026-11-14 | `RunLoopWait` 除了 run loop 要休眠时,每次一轮运行结束时也检查,并排在所有同阶段的观察者(含 Core Animation 的提交)之后 | AppKit 每取一个事件都单独跑一轮 run loop,这样用户关闭弹出内容后,下一个事件被处理之前就已写回绑定,用户紧接着再要求弹出不会被这次写回冲掉。这个改动作用于所有用 `RunLoopWait` 的风格,AppKit 测试全部通过 | +| 2026-11-14 | 存取面板测试经私有方法 `completeWithReturnCode:url:urls:` 模拟用户确认,私有方法只出现在测试里 | 面板在另一个进程里运行,本进程里的 `ok(_:)` 直接抛「not implemented」,公开 API 里没有别的办法让面板以「确定」结束;调用前先检查方法还在,不在就让测试失败而不是崩溃。旧测试同样调用私有 setter。临时关掉写回时,四个确认用例都会失败 | +| 2026-11-14 | 案例里的存储面板在弹出前先清空 `savedURL` | 取消不再动绑定,不清空的话,取消后的记录会显示上一次选的文件名 | | 2026-11-14 | 用户关闭后的写回不再与 AppKit 的关闭同步发生,`testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt` 改为等写回之后再立刻设回 `true` | 交换方法时写回发生在 `viewDidDisappear` 里,不交换就没有同步的时机。原测试在同一段同步代码里关闭 sheet 又设回 `true`,真实使用中两次操作之间总隔着事件循环;改后仍覆盖它要测的情形:中间那次 `false` 没被 `observe` 看到时,内容照样能再弹出 | diff --git a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift index d04b79926f..995d32ed74 100644 --- a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift @@ -172,6 +172,8 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa self?.model.alertSheet = .discardChanges }, makeButton("Save panel sheet") { [weak self] in + // NB: Cancelling the panel leaves the URL as it is, so the last choice is cleared first. + self?.model.savedURL = nil self?.model.isSavePanelSheetPresented = true }, ] diff --git a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift index 2e753ee60f..8c08f0fa5b 100755 --- a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift +++ b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift @@ -1,34 +1,48 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit -import AppKitNavigationShim extension NSSavePanel { + /// Creates a save panel that writes the URL the user chooses to a binding. + /// + /// The binding is written when the panel, shown with + /// ``ObjectiveC/NSObject/modal(isPresented:onDismiss:content:)`` or + /// ``AppKit/NSWindow/sheet(isPresented:onDismiss:content:)``, ends with the user confirming + /// their choice, before the presentation's `onDismiss` runs. Cancelling leaves the binding as it + /// is. A panel the app runs itself, with `begin(completionHandler:)` or `runModal()`, does not + /// write it: the app learns what the user chose from the panel's response instead. + /// + /// - Parameter url: A binding to write the chosen URL to. public convenience init(url: UIBinding) { self.init() bind(url: url) } + /// Writes the URL the user chooses in this panel to a binding. + /// + /// The binding is written as described in ``init(url:)``. Binding again replaces the binding + /// given before. + /// + /// - Parameter binding: A binding to write the chosen URL to. + /// - Returns: A token that stops writing to the binding once cancelled. @discardableResult public func bind(url binding: UIBinding) -> ObserveToken { - // NB: The previous binding's token has to be cancelled before the new hook is installed. - // Left to be released when its entry is replaced below, it would clear the hook it no + // NB: The previous binding's token has to be cancelled before the new binding is stored. + // Left to be released when its entry is replaced below, it would clear the binding it no // longer owns. unbindURL() - appKitNavigation_onFinalURL = { url in - binding.wrappedValue = url - } - - let observationToken = ObserveToken { [weak self] in - guard let self else { return } + let confirmedChoiceBindings = appKitNavigationConfirmedChoiceBindings + confirmedChoiceBindings.url = binding + let observationToken = ObserveToken { [weak confirmedChoiceBindings] in MainActor._assumeIsolated { - self.appKitNavigation_onFinalURL = nil + confirmedChoiceBindings?.url = nil } } observationTokens[\NSSavePanel.url] = observationToken return observationToken } + /// Stops writing the URL the user chooses to the binding given to ``bind(url:)``. public func unbindURL() { observationTokens[\NSSavePanel.url]?.cancel() observationTokens[\NSSavePanel.url] = nil @@ -36,33 +50,91 @@ extension NSSavePanel { } extension NSOpenPanel { + /// Creates an open panel that writes the URLs the user chooses to a binding. + /// + /// The binding is written when the panel, shown with + /// ``ObjectiveC/NSObject/modal(isPresented:onDismiss:content:)`` or + /// ``AppKit/NSWindow/sheet(isPresented:onDismiss:content:)``, ends with the user confirming + /// their choice, before the presentation's `onDismiss` runs. Cancelling leaves the binding as it + /// is. A panel the app runs itself, with `begin(completionHandler:)` or `runModal()`, does not + /// write it: the app learns what the user chose from the panel's response instead. + /// + /// - Parameter urls: A binding to write the chosen URLs to. public convenience init(urls: UIBinding<[URL]>) { self.init() bind(urls: urls) } + /// Writes the URLs the user chooses in this panel to a binding. + /// + /// The binding is written as described in ``init(urls:)``. Binding again replaces the binding + /// given before. + /// + /// - Parameter binding: A binding to write the chosen URLs to. + /// - Returns: A token that stops writing to the binding once cancelled. @discardableResult public func bind(urls binding: UIBinding<[URL]>) -> ObserveToken { // NB: See 'NSSavePanel.bind(url:)'. unbindURLs() - appKitNavigation_onFinalURLs = { urls in - binding.wrappedValue = urls - } - - let observationToken = ObserveToken { [weak self] in - guard let self else { return } + let confirmedChoiceBindings = appKitNavigationConfirmedChoiceBindings + confirmedChoiceBindings.urls = binding + let observationToken = ObserveToken { [weak confirmedChoiceBindings] in MainActor._assumeIsolated { - self.appKitNavigation_onFinalURLs = nil + confirmedChoiceBindings?.urls = nil } } observationTokens[\NSOpenPanel.urls] = observationToken return observationToken } + /// Stops writing the URLs the user chooses to the binding given to ``bind(urls:)``. public func unbindURLs() { observationTokens[\NSOpenPanel.urls]?.cancel() observationTokens[\NSOpenPanel.urls] = nil } } +extension NSSavePanel { + /// Writes what the user chose to the bindings given to ``bind(url:)`` and + /// ``NSOpenPanel/bind(urls:)``, once the panel has ended with the user confirming it. + /// + /// AppKit reports the choice only through the panel's response, which only whoever runs the + /// panel sees: the library's sheet and modal presentation call this. + func appKitNavigationWriteConfirmedChoice() { + guard + let confirmedChoiceBindings = objc_getAssociatedObject(self, confirmedChoiceBindingsKey) + as? ConfirmedChoiceBindings + else { return } + confirmedChoiceBindings.url?.wrappedValue = url + if let openPanel = self as? NSOpenPanel { + confirmedChoiceBindings.urls?.wrappedValue = openPanel.urls + } + } + + /// The bindings this panel writes the user's choice to, made on first use. + fileprivate var appKitNavigationConfirmedChoiceBindings: ConfirmedChoiceBindings { + if let confirmedChoiceBindings = objc_getAssociatedObject(self, confirmedChoiceBindingsKey) + as? ConfirmedChoiceBindings + { + return confirmedChoiceBindings + } + let confirmedChoiceBindings = ConfirmedChoiceBindings() + objc_setAssociatedObject( + self, confirmedChoiceBindingsKey, confirmedChoiceBindings, + .OBJC_ASSOCIATION_RETAIN_NONATOMIC + ) + return confirmedChoiceBindings + } +} + +/// The bindings a save or open panel writes the user's choice to. +@MainActor +private final class ConfirmedChoiceBindings { + var url: UIBinding? + var urls: UIBinding<[URL]>? +} + +@MainActor +private let confirmedChoiceBindingsKey = malloc(1)! + #endif diff --git a/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift index 4e33e132b0..9cef52937c 100644 --- a/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift +++ b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift @@ -43,7 +43,10 @@ // NB: A save or open panel has to go through its own method. Attached like a plain window, // its Cancel button cannot end the sheet. if let savePanel = self as? NSSavePanel { - savePanel.beginSheetModal(for: parentWindow) { _ in + savePanel.beginSheetModal(for: parentWindow) { response in + if response == .OK { + savePanel.appKitNavigationWriteConfirmedChoice() + } completionHandler() } } else { @@ -56,7 +59,9 @@ @_documentation(visibility: private) public func _appKitNavigationRunModal() { if let savePanel = self as? NSSavePanel { - _ = savePanel.runModal() + if savePanel.runModal() == .OK { + savePanel.appKitNavigationWriteConfirmedChoice() + } } else { _ = NSApplication.shared.runModal(for: self) } diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h index 27589acb2c..bbc114c17b 100644 --- a/Sources/AppKitNavigationShim/include/shim.h +++ b/Sources/AppKitNavigationShim/include/shim.h @@ -6,11 +6,6 @@ NS_ASSUME_NONNULL_BEGIN -@interface NSSavePanel (AppKitNavigation) -@property (nullable) void (^ AppKitNavigation_onFinalURL)(NSURL *_Nullable); -@property (nullable) void (^ AppKitNavigation_onFinalURLs)(NSArray *); -@end - // MARK: - Multiple target-action pairs // NB: AppKit has stored several target-action pairs per control since macOS 11, but only published diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m index f7c5d51f43..ec6faf8b5e 100644 --- a/Sources/AppKitNavigationShim/shim.m +++ b/Sources/AppKitNavigationShim/shim.m @@ -2,62 +2,6 @@ #include #if __has_include() && !TARGET_OS_MACCATALYST -@import ObjectiveC; -@import AppKit; #import "shim.h" - -@interface AppKitNavigationShim : NSObject - -@end - -@implementation AppKitNavigationShim - -+ (void)load { - method_exchangeImplementations( - class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURL:")), - class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURL:)) - ); - method_exchangeImplementations( - class_getInstanceMethod(NSSavePanel.class, NSSelectorFromString(@"setFinalURLs:")), - class_getInstanceMethod(NSSavePanel.class, @selector(AppKitNavigation_setFinalURLs:)) - ); -} - -@end - -@implementation NSSavePanel (AppKitNavigation) - -- (void)setAppKitNavigation_onFinalURLs:(void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { - objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs), AppKitNavigation_onFinalURLs, OBJC_ASSOCIATION_COPY); -} - -- (void (^)(NSArray * _Nonnull))AppKitNavigation_onFinalURLs { - return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURLs)); -} - -- (void)setAppKitNavigation_onFinalURL:(void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { - objc_setAssociatedObject(self, @selector(AppKitNavigation_onFinalURL), AppKitNavigation_onFinalURL, OBJC_ASSOCIATION_COPY); -} - -- (void (^)(NSURL * _Nullable))AppKitNavigation_onFinalURL { - return objc_getAssociatedObject(self, @selector(AppKitNavigation_onFinalURL)); -} - -- (void)AppKitNavigation_setFinalURL:(nullable NSURL *)url { - [self AppKitNavigation_setFinalURL:url]; - if (self.AppKitNavigation_onFinalURL) { - self.AppKitNavigation_onFinalURL(url); - } -} - -- (void)AppKitNavigation_setFinalURLs:(NSArray *)urls { - [self AppKitNavigation_setFinalURLs:urls]; - if (self.AppKitNavigation_onFinalURLs) { - self.AppKitNavigation_onFinalURLs(urls); - } -} - -@end - #endif /* if __has_include() && !TARGET_OS_MACCATALYST */ #endif /* if __has_include() */ diff --git a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift index 486382eae1..93c9d7182b 100644 --- a/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift +++ b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift @@ -29,46 +29,6 @@ #expect(name == "original") } - /// The panel reports the URL the user confirmed through its private 'setFinalURL:' setter, - /// which is what the binding hooks. - @Test("rebinding a save panel keeps reporting the confirmed URL") - func rebindingASavePanelKeepsReportingTheConfirmedURL() throws { - @UIBinding var firstURL: URL? = nil - @UIBinding var secondURL: URL? = nil - let savePanel = NSSavePanel() - savePanel.bind(url: $firstURL) - savePanel.bind(url: $secondURL) - - let confirmedURL = URL(filePath: "/tmp/confirmed.txt") - try confirm(confirmedURL, in: savePanel, through: "setFinalURL:") - - #expect(secondURL == confirmedURL) - } - - @Test("rebinding an open panel keeps reporting the confirmed URLs") - func rebindingAnOpenPanelKeepsReportingTheConfirmedURLs() throws { - @UIBinding var firstURLs: [URL] = [] - @UIBinding var secondURLs: [URL] = [] - let openPanel = NSOpenPanel() - openPanel.bind(urls: $firstURLs) - openPanel.bind(urls: $secondURLs) - - let confirmedURLs = [URL(filePath: "/tmp/first.txt"), URL(filePath: "/tmp/second.txt")] - try confirm(confirmedURLs, in: openPanel, through: "setFinalURLs:") - - #expect(secondURLs == confirmedURLs) - } - - /// Reports a confirmed choice the way the panel itself does. Checks for the private setter - /// first: messaging a selector the panel no longer has would crash the whole test run. - private func confirm( - _ confirmedChoice: Any, in panel: NSSavePanel, through setterName: String - ) throws { - let setter = NSSelectorFromString(setterName) - try #require(panel.responds(to: setter)) - panel.perform(setter, with: confirmedChoice) - } - /// Types into the field the way the field editor reports it. private func edit(_ textField: NSTextField, to text: String) { textField.stringValue = text diff --git a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift index 533f723c6f..32d02343a5 100644 --- a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift +++ b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift @@ -122,17 +122,6 @@ #expect(segment == .first) } - /// `NSSavePanel.bind(url:)` and `NSOpenPanel.bind(urls:)` hook the private setters through - /// which a panel records what the user confirmed. Should AppKit drop or rename them, the - /// bindings would stop being written without any error; this test is what notices. - @Test( - "the private setters the panel bindings hook still exist", - arguments: ["setFinalURL:", "setFinalURLs:"] - ) - func panelSettersStillExist(_ selectorName: String) { - #expect(NSSavePanel.instancesRespond(to: NSSelectorFromString(selectorName))) - } - private enum Segment: Int { case first case second diff --git a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift index ae2aa4f9ff..8742f67c91 100644 --- a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift +++ b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift @@ -10,6 +10,9 @@ /// app. An unprefixed `textViewDidChangeSelection:` added to `NSTextField` once broke the /// selection handling of every text field that way. Carrying the library's name in every such /// selector keeps the two apart. + /// + /// The same scan keeps the library from replacing a system method on purpose: an implementation + /// exchanged in shows up under the system's own selector, which does not carry the name. // NB: On the main actor because naming an AppKit class from Swift runs its '+initialize' on // the calling thread. Doing that for 'NSView' on a background thread, while other tests run // in parallel, left AppKit tied to the wrong thread: event handling on the main thread then @@ -30,19 +33,11 @@ let unnamedMethods = addedMethods.filter { method in !method.localizedCaseInsensitiveContains("AppKitNavigation") - && !Self.deliberatelyReplacedMethods.contains(method) } #expect(unnamedMethods.isEmpty, "Methods without the library's name: \(unnamedMethods)") } - /// The methods the library replaces on purpose: the shim exchanges its own implementations in - /// for these, to learn what the user confirmed in a save panel. - private static let deliberatelyReplacedMethods: Set = [ - "-[NSSavePanel setFinalURL:]", - "-[NSSavePanel setFinalURLs:]", - ] - /// Every method of the classes defined in the given classes' images whose implementation /// lives in this test binary, formatted the way Objective-C prints a method. private static func methodsImplementedInThisBinary( diff --git a/Tests/AppKitNavigationTests/PanelBindingTests.swift b/Tests/AppKitNavigationTests/PanelBindingTests.swift new file mode 100644 index 0000000000..20d5aadbf2 --- /dev/null +++ b/Tests/AppKitNavigationTests/PanelBindingTests.swift @@ -0,0 +1,171 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// A save or open panel shown with `sheet` or `modal` writes what the user confirms to its + /// binding, and leaves the binding as it is when the user cancels. + final class PanelBindingTests: XCTestCase { + override func setUp() { + super.setUp() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + @MainActor + func testConfirmingASavePanelSheetWritesTheChosenURL() { + let host = makeHost() + let confirmedURL = Self.makeUniqueURL() + @UIBinding var isPresented = false + @UIBinding var chosenURL: URL? + let savePanel = NSSavePanel(url: $chosenURL) + host.window.sheet(isPresented: $isPresented) { savePanel } + + isPresented = true + XCTAssertTrue( + waitUntil(timeout: 8) { host.window.attachedSheet === savePanel }, + "The save panel never appeared as a sheet" + ) + guard confirm(savePanel, choosing: [confirmedURL]) else { return } + + XCTAssertTrue( + waitUntil(timeout: 5) { !isPresented }, "Confirming the panel did not end the sheet" + ) + XCTAssertEqual(chosenURL, confirmedURL) + } + + @MainActor + func testCancellingASavePanelSheetLeavesTheBindingAsItIs() { + let host = makeHost() + let earlierURL = Self.makeUniqueURL() + @UIBinding var isPresented = false + @UIBinding var chosenURL: URL? = earlierURL + let savePanel = NSSavePanel(url: $chosenURL) + host.window.sheet(isPresented: $isPresented) { savePanel } + + isPresented = true + XCTAssertTrue( + waitUntil(timeout: 8) { host.window.attachedSheet === savePanel }, + "The save panel never appeared as a sheet" + ) + // What the panel's Cancel button does. + savePanel.cancel(nil) + + XCTAssertTrue( + waitUntil(timeout: 5) { !isPresented }, "Cancelling the panel did not end the sheet" + ) + XCTAssertEqual(chosenURL, earlierURL) + } + + /// What a reused panel does: the same panel is bound to the next model. + @MainActor + func testRebindingASavePanelWritesOnlyToTheNewBinding() { + let host = makeHost() + let confirmedURL = Self.makeUniqueURL() + @UIBinding var isPresented = false + @UIBinding var firstURL: URL? + @UIBinding var secondURL: URL? + let savePanel = NSSavePanel(url: $firstURL) + savePanel.bind(url: $secondURL) + host.window.sheet(isPresented: $isPresented) { savePanel } + + isPresented = true + XCTAssertTrue( + waitUntil(timeout: 8) { host.window.attachedSheet === savePanel }, + "The save panel never appeared as a sheet" + ) + guard confirm(savePanel, choosing: [confirmedURL]) else { return } + + XCTAssertTrue( + waitUntil(timeout: 5) { !isPresented }, "Confirming the panel did not end the sheet" + ) + XCTAssertNil(firstURL, "The previous binding was written") + XCTAssertEqual(secondURL, confirmedURL) + } + + @MainActor + func testRebindingAnOpenPanelWritesOnlyToTheNewBinding() { + let host = makeHost() + let confirmedURLs = [Self.makeUniqueURL(), Self.makeUniqueURL()] + @UIBinding var isPresented = false + @UIBinding var firstURLs: [URL] = [] + @UIBinding var secondURLs: [URL] = [] + let openPanel = NSOpenPanel(urls: $firstURLs) + openPanel.bind(urls: $secondURLs) + openPanel.allowsMultipleSelection = true + host.window.sheet(isPresented: $isPresented) { openPanel } + + isPresented = true + XCTAssertTrue( + waitUntil(timeout: 8) { host.window.attachedSheet === openPanel }, + "The open panel never appeared as a sheet" + ) + guard confirm(openPanel, choosing: confirmedURLs) else { return } + + XCTAssertTrue( + waitUntil(timeout: 5) { !isPresented }, "Confirming the panel did not end the sheet" + ) + XCTAssertEqual(firstURLs, [], "The previous binding was written") + XCTAssertEqual(secondURLs, confirmedURLs) + } + + @MainActor + func testConfirmingAModalSavePanelWritesTheChosenURL() { + let host = NSObject() + let confirmedURL = Self.makeUniqueURL() + @UIBinding var isPresented = false + @UIBinding var chosenURL: URL? + let savePanel = NSSavePanel(url: $chosenURL) + host.modal(isPresented: $isPresented) { savePanel } + abortModalLoops(after: 8) + + let start = Date() + perform(after: 1) { + self.confirm(savePanel, choosing: [confirmedURL]) + } + isPresented = true + + XCTAssertTrue(waitUntil(timeout: 7) { !isPresented }, "Confirming the panel did not end it") + XCTAssertLessThan( + Date().timeIntervalSince(start), 6, + "The panel only ended when the safety timer aborted it" + ) + XCTAssertEqual(chosenURL, confirmedURL) + } + + /// Ends `panel` the way the panel service does once the user has confirmed `urls`, and returns + /// whether it could. + /// + /// The panel runs in another process, and the copy in this one implements none of its + /// buttons' actions but Cancel's: `ok(_:)` raises "not implemented". The service reports the + /// user's choice through a private method instead, so the tests confirm through it, after + /// checking it is there: messaging a selector the panel no longer has would crash the whole + /// test run. It takes the URLs even from a save panel, and raises when they are missing. + @MainActor + @discardableResult + private func confirm(_ panel: NSSavePanel, choosing urls: [URL]) -> Bool { + guard panel.responds(to: NSSelectorFromString("completeWithReturnCode:url:urls:")) else { + XCTFail("NSSavePanel no longer has 'completeWithReturnCode:url:urls:'") + return false + } + (panel as AnyObject).complete( + returnCode: NSApplication.ModalResponse.OK.rawValue, url: urls.first, urls: urls + ) + return true + } + + /// A file URL nothing else uses. Nothing is created at it. + private static func makeUniqueURL() -> URL { + FileManager.default.temporaryDirectory.appending( + path: "AppKitNavigationTests-\(UUID().uuidString).txt" + ) + } + } + + /// The private method through which the panel service reports the user's choice to a panel. + @objc private protocol PanelCompletion { + @objc(completeWithReturnCode:url:urls:) + func complete(returnCode: Int, url: URL?, urls: [URL]?) + } +#endif From 8be9c70f2271596ce959082be3f6a5dc2b79a233 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:30:40 +0800 Subject: [PATCH 124/141] build(appkit): drop AppKitNavigationShim The shim's last part redeclared `NSControl`'s multiple target-action API for SDKs older than macOS 27. The macOS 27 SDK declares it, and Xcode 27 is the only toolchain this fork is built with now, so the target goes away from every manifest, along with the AppKitPlus import that `TargetActionProxy` needed to pick a declaration before that SDK. AppKitNavigation no longer builds with an older SDK. Draft proposal: Documentations/Evolutions/draft-appkit-remove-shim.md --- .../Evolutions/draft-appkit-remove-shim.md | 2 +- Package.swift | 4 - Package@swift-6.0.swift | 4 - Package@swift-6.1.swift | 4 - Package@swift-6.2.swift | 4 - .../Bindings/TargetActionProxy.swift | 10 --- Sources/AppKitNavigationShim/include/shim.h | 74 ------------------- Sources/AppKitNavigationShim/shim.m | 7 -- 8 files changed, 1 insertion(+), 108 deletions(-) delete mode 100644 Sources/AppKitNavigationShim/include/shim.h delete mode 100644 Sources/AppKitNavigationShim/shim.m diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md index 0fdf0f1d75..acfd6124a2 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -22,7 +22,7 @@ 1. **弹出生命周期**(已完成):`Presentation.swift` 与 `NavigationDestination.swift` 改用 `RunLoopWait`,删掉 shim 里 `NSViewController` 的部分。补测试:用户关掉以 popover、模态窗口弹出的视图控制器时绑定写回;被别的页面盖住的发起者照样立刻 push。方法命名测试改用 `-[NSButton appKitNavigationIsOn]` 作扫描锚点。`RunLoopWait` 的检查时机同时调整,见决策日志。 2. **存取面板绑定**(已完成):改走 `sheet` / `modal` 的结果,删掉 shim 里 `NSSavePanel` 的部分和检查私有 setter 的测试。补测试:确认后写回、取消不动、重新绑定只写新绑定。方法命名测试不再有例外。案例里的存储面板改为弹出前先清空上次选的 URL。 -3. **NSControl 与 target 本身**:删掉重复声明与 `TargetActionProxy` 的变通;shim 已空,从四份 Package 清单里删掉这个 target,删掉目录。 +3. **NSControl 与 target 本身**(已完成):删掉重复声明与 `TargetActionProxy` 的变通;shim 已空,从四份 Package 清单里删掉这个 target,删掉目录。 没有询问就采用的假设: diff --git a/Package.swift b/Package.swift index b9f2e28866..ac04b3b337 100644 --- a/Package.swift +++ b/Package.swift @@ -193,7 +193,6 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "AppKitNavigationShim", .product( name: "AppKitPlus", package: "AppKitPlus-Release", @@ -201,9 +200,6 @@ let package = Package( ), ] ), - .target( - name: "AppKitNavigationShim" - ), .testTarget( name: "UIKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.0.swift b/Package@swift-6.0.swift index 7114d91e40..1d8da72bb1 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -115,12 +115,8 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "AppKitNavigationShim", ] ), - .target( - name: "AppKitNavigationShim" - ), .testTarget( name: "AppKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.1.swift b/Package@swift-6.1.swift index 4b5af868b4..6fad7c0d64 100644 --- a/Package@swift-6.1.swift +++ b/Package@swift-6.1.swift @@ -193,12 +193,8 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "AppKitNavigationShim", ] ), - .target( - name: "AppKitNavigationShim" - ), .testTarget( name: "AppKitNavigationTests", dependencies: [ diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift index 9e0611e2de..b946c9a760 100644 --- a/Package@swift-6.2.swift +++ b/Package@swift-6.2.swift @@ -200,7 +200,6 @@ let package = Package( name: "AppKitNavigation", dependencies: [ "SwiftNavigation", - "AppKitNavigationShim", .product( name: "AppKitPlus", package: "AppKitPlus-Release", @@ -208,9 +207,6 @@ let package = Package( ), ] ), - .target( - name: "AppKitNavigationShim" - ), .testTarget( name: "AppKitNavigationTests", dependencies: [ diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift index 8b88673c84..fa3e5d06a3 100755 --- a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -1,12 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) public import AppKit -import AppKitNavigationShim -#if AppKitPlus - // NB: AppKitPlus declares the same AppKit control-event methods as the shim. Before the macOS 27 - // SDK, Swift settles on its declarations, which must then be visible here. - import AppKitPlus -#endif @MainActor class TargetActionProxy: NSObject { @@ -60,10 +54,6 @@ class TargetActionProxy: NSObject { // // A text field's per-keystroke changes arrive through the notification below on every // OS version, so text fields need nothing more. - // - // The event set is spelled as a literal on purpose: the option set is named - // 'NSControlEvents' when it comes from the shim and 'NSControl.Events' when it comes - // from the macOS 27 SDK, and inference makes both spellings compile. control.addTarget(self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered]) } else { self.originTarget = owner.target diff --git a/Sources/AppKitNavigationShim/include/shim.h b/Sources/AppKitNavigationShim/include/shim.h deleted file mode 100644 index bbc114c17b..0000000000 --- a/Sources/AppKitNavigationShim/include/shim.h +++ /dev/null @@ -1,74 +0,0 @@ -#if __has_include() -#include - -#if __has_include() && !TARGET_OS_MACCATALYST -@import AppKit; - -NS_ASSUME_NONNULL_BEGIN - -// MARK: - Multiple target-action pairs - -// NB: AppKit has stored several target-action pairs per control since macOS 11, but only published -// the API in the macOS 27 SDK. Redeclaring it here lets the binding layer register additional -// actions without taking over a control's single 'target' / 'action' pair, while still building -// against an older SDK. The whole block compiles away once the SDK in use declares it, so -// nothing has to be deleted by hand — but the redeclaration should be dropped altogether once -// the macOS 27 SDK is the minimum supported one. -// -// Note that the events themselves are not all as old as the API: on macOS 26 a button click -// only delivers NSControlEventTrackingBegan and NSControlEventTrackingEndedInside, and -// NSControlEventValueChanged / NSControlEventPrimaryActionTriggered are never sent. Anything -// relying on those has to stay behind an availability check. -// -// The SDK spells the type 'NS_SWIFT_NAME(NSControl.Events)'. That must NOT be repeated here: -// nesting a type inside a class that belongs to a *different* module makes the Swift importer -// drop the whole declaration, taking the two methods with it, and Swift then sees neither -// 'NSControlEvents' nor 'NSControl.Events'. Without the attribute Swift imports the type under -// its Objective-C name and the methods as 'addTarget(_:action:for:)'. -#if !defined(MAC_OS_VERSION_27_0) || __MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_VERSION_27_0 - -typedef NS_OPTIONS(NSUInteger, NSControlEvents) { - NSControlEventTrackingBegan = 1 << 0, - NSControlEventTrackingRepeated API_AVAILABLE(macos(27.0)) = 1 << 1, - NSControlEventTrackingInside = 1 << 2, - NSControlEventTrackingOutside = 1 << 3, - NSControlEventTrackingEntered = 1 << 4, - NSControlEventTrackingExited = 1 << 5, - NSControlEventTrackingEndedInside = 1 << 6, - NSControlEventTrackingEndedOutside = 1 << 7, - NSControlEventTrackingCancelled = 1 << 8, - - NSControlEventValueChanged API_AVAILABLE(macos(27.0)) = 1 << 12, - NSControlEventPrimaryActionTriggered API_AVAILABLE(macos(27.0)) = 1 << 13, - NSControlEventMenuActionTriggered API_AVAILABLE(macos(27.0)) = 1 << 14, - - NSControlEventAllTrackingEvents = 0x00000FFF, - NSControlEventApplicationReserved API_AVAILABLE(macos(27.0)) = 0x0F000000, - NSControlEventSystemReserved = 0xF0000000, - NSControlEventAllEvents = 0xFFFFFFFF -} API_AVAILABLE(macos(11.0)); - -@interface NSControl (AppKitNavigationControlEvents) - -/// Associates a target object and action method with one or more control events. -/// -/// Unlike the 'target' and 'action' properties, this may be called several times to register -/// several pairs. The control does not retain the target. -- (void)addTarget:(nullable id)target - action:(SEL)action - forControlEvents:(NSControlEvents)controlEvents API_AVAILABLE(macos(11.0)); - -/// Stops the delivery of the specified events to the given target object. -/// -/// Pass 'nil' as the action to remove all actions for the target. -- (void)removeTarget:(nullable id)target - action:(nullable SEL)action - forControlEvents:(NSControlEvents)controlEvents API_AVAILABLE(macos(11.0)); - -@end - -#endif /* macOS 27 SDK redeclaration */ - -NS_ASSUME_NONNULL_END -#endif -#endif /* if __has_include() */ diff --git a/Sources/AppKitNavigationShim/shim.m b/Sources/AppKitNavigationShim/shim.m deleted file mode 100644 index ec6faf8b5e..0000000000 --- a/Sources/AppKitNavigationShim/shim.m +++ /dev/null @@ -1,7 +0,0 @@ -#if __has_include() -#include - -#if __has_include() && !TARGET_OS_MACCATALYST -#import "shim.h" -#endif /* if __has_include() && !TARGET_OS_MACCATALYST */ -#endif /* if __has_include() */ From ce88ec845bfe45783bdab8587da8677a62017f77 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:41:20 +0800 Subject: [PATCH 125/141] fix(appkit): present modal windows and push while the window is minimized Waiting for the presenter's window to be on screen is what a sheet or a popover needs, since it attaches to that window. A modal window, a transition of the caller's own and a push do not: before the shim went away they went ahead as soon as the presenter had appeared once. They now go ahead while the window that holds the presenter, or the navigation stack, is minimized too. The two new tests present a modal window and push from a minimized window; both failed before. The review's other findings are recorded in Documentations/Internal/ReviewDecisions.md. --- .../Evolutions/draft-appkit-remove-shim.md | 7 ++- Documentations/Internal/ReviewDecisions.md | 53 ++++++++++++++++++- .../Internal/RunLoopWait.swift | 9 ++++ .../Navigation/NavigationDestination.swift | 15 +++--- .../Navigation/Presentation.swift | 21 ++++++-- .../NavigationDestinationTests.swift | 22 ++++++++ .../ViewControllerPresentationTests.swift | 34 ++++++++++++ 7 files changed, 146 insertions(+), 15 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md index acfd6124a2..472fc4237f 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -27,8 +27,8 @@ 没有询问就采用的假设: - 存取面板的绑定只在经库的 `sheet` / `modal` 弹出时写回;App 自己调用 `begin` / `runModal` 时不写回,结果从完成回调里取。取消时绑定保持原值。依赖这个 fork 的 App(PrivateSymbols)与案例都只经 `sheet` / `modal` 使用,读完即清空。 -- 弹出的就绪条件从「发起者的视图出现过」改为「发起者的视图此刻在可见窗口里」:视图出现过又离开窗口时(切到别的标签页、被导航栈里的新页面盖住),绑定再变成有值会等它回到屏幕上再弹,不再立刻弹出一个没有窗口可依附的 sheet。以模态窗口弹出不需要发起者的窗口,也照此等待。 -- push 的就绪条件是「导航栈在屏幕上」而不是「发起者在屏幕上」:被盖住的发起者照旧立刻把新页面压到栈顶,与改动前一致。 +- 弹出的就绪条件从「发起者的视图出现过」改为看它此刻所在的窗口:sheet 与 popover 要求窗口在屏幕上,视图出现过又离开窗口时(切到别的标签页、被导航栈里的新页面盖住),绑定再变成有值会等它回到屏幕上再弹,不再立刻弹出一个没有窗口可依附的 sheet;模态窗口与自定义转场不需要发起者的窗口,窗口最小化时也照常弹出。 +- push 的就绪条件看导航栈所在的窗口而不是发起者:被盖住的发起者照旧立刻把新页面压到栈顶,窗口最小化时也照常 push,与改动前一致;栈的视图不在任何窗口里时(未选中的标签页)推迟到它出现。 - 盯着用户关闭的检查在整个弹出期间每轮 run loop 做一次,只是一次闭包调用,与 `navigationDestination` 的做法相同。 - AppKitNavigation 从此只能用 Xcode 27(macOS 27 SDK)编译。`Package@swift-6.0/6.1/6.2.swift` 来自上游,保留,只删 shim target;上游从来没有这个 target,删掉后与上游更接近。 - `UIKitNavigationShim` 也在交换方法,不在这一批的范围里。 @@ -44,4 +44,7 @@ | 2026-11-14 | `RunLoopWait` 除了 run loop 要休眠时,每次一轮运行结束时也检查,并排在所有同阶段的观察者(含 Core Animation 的提交)之后 | AppKit 每取一个事件都单独跑一轮 run loop,这样用户关闭弹出内容后,下一个事件被处理之前就已写回绑定,用户紧接着再要求弹出不会被这次写回冲掉。这个改动作用于所有用 `RunLoopWait` 的风格,AppKit 测试全部通过 | | 2026-11-14 | 存取面板测试经私有方法 `completeWithReturnCode:url:urls:` 模拟用户确认,私有方法只出现在测试里 | 面板在另一个进程里运行,本进程里的 `ok(_:)` 直接抛「not implemented」,公开 API 里没有别的办法让面板以「确定」结束;调用前先检查方法还在,不在就让测试失败而不是崩溃。旧测试同样调用私有 setter。临时关掉写回时,四个确认用例都会失败 | | 2026-11-14 | 案例里的存储面板在弹出前先清空 `savedURL` | 取消不再动绑定,不清空的话,取消后的记录会显示上一次选的文件名 | +| 2026-11-14 | 自审:模态窗口、自定义转场与 push 在窗口最小化时也就绪 | 自审指出它们本不需要发起者的窗口在屏幕上,改动后却会一直等到窗口还原,而改动前是立刻弹出。先写了两条在最小化窗口上弹出与 push 的测试,修前失败、修后通过 | +| 2026-11-14 | 自审其余发现登记进 `Internal/ReviewDecisions.md` | 共 10 条:1 条已修(上一行);2 条误报;1 条暂缓;5 条是方案有意接受的代价;存储面板取消时的写法留给用户定,见下一行 | +| 2026-11-14 | 存储面板取消时不动绑定,待用户确认 | 在 `main` 上实测,交换方法的旧实现在用户取消时会把绑定写成 `nil`。用户开工前选的方案写的是「取消时绑定不变」,当时没有说明旧行为,所以交付时请用户再确认一次 | | 2026-11-14 | 用户关闭后的写回不再与 AppKit 的关闭同步发生,`testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt` 改为等写回之后再立刻设回 `true` | 交换方法时写回发生在 `viewDidDisappear` 里,不交换就没有同步的时机。原测试在同一段同步代码里关闭 sheet 又设回 `true`,真实使用中两次操作之间总隔着事件循环;改后仍覆盖它要测的情形:中间那次 `false` 没被 `observe` 看到时,内容照样能再弹出 | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index 65f280bdab..3bd4ea965c 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -30,6 +30,17 @@ - **理由**:在 macOS 27.2 上实测,`NSFontManager()` 返回的就是 `NSFontManager.shared`。 - **复查条件**:将来某个系统版本上它不再返回共享实例时。 +### 同一个视图控制器实例再次弹出时,覆盖上一次弹出的结束记录 + +- **裁决**:误报。(2026-11-14) +- **理由**:结束记录挂在被弹出的视图控制器上,只有一个槽位。可同一个 `BindingPresenter` 在上一次内容结束之前不会再弹出(`.ending` 阶段什么都不做),两个绑定同时弹出同一个实例又是 AppKit 本身不支持的,构造不出覆盖的场景。`main` 上交换方法时的 `_AppKitNavigation_onDismiss` 同样只有一个槽位。 + +### 自定义 presentation animator 不把视图移出窗口时,内容永远不算结束 + +- **裁决**:与改动前相同,不按问题处理。(2026-11-14) +- **理由**:判断结束要等被弹出的视图控制器的窗口不再可见。只有动画器在关闭时既不移除视图、也不关窗口才会卡住,而这样的动画器本身就把被关闭的视图留在了界面上。`main` 上交换方法时,报告关闭之后也是等同一个条件,提案 [0005-appkit-presentation-redesign](../Evolutions/0005-appkit-presentation-redesign.md) 有意这样定,好让有动画时 `onDismiss` 也在内容下屏之后才运行。 +- **复查条件**:出现合理的动画器需要把视图留在窗口里时。 + ## 暂缓处理 ### 上游 `UIKitNavigation` 的 `UITextField` 选区绑定同样把 UTF-16 偏移当成字符数 @@ -38,6 +49,46 @@ - **理由**:AppKit 那份已按 UTF-16 换算修好。UIKit 那份是上游拥有的代码,fork 保持与上游一致,在 fork 里改会让以后的合并持续冲突。 - **复查条件**:上游自己修了,或者 fork 的 UIKit 用户撞上这个问题时。 +### 视图控制器弹出与 push 的结束检测,和 `navigationDestination` 的记录写了两套 + +- **裁决**:不是缺陷,暂缓合并。(2026-11-14) +- **理由**:去掉 AppKitNavigationShim 时,弹出改用「先出现在列表里、再离开列表且下屏」的检测,形状和 push 的 `PushRecord` 相近,但判断条件不同(`presentedViewControllers` 对父视图控制器)。push 那套来自另一份提案,合成一个共用 helper 属于单独的重构。 +- **复查条件**:其中一套要改检测条件时,一并合并。 + +## 有意的取舍 + +这些发现确实存在,是方案主动接受的代价,理由仍成立就不再重审。 + +### 去掉 NSControl 的重复声明后,旧 SDK 编不过 AppKitNavigation + +- **裁决**:按用户决定,不修。(2026-11-14) +- **理由**:macOS 27 以前的 SDK 没有公开 `addTarget(_:action:for:)`,`Package@swift-6.0/6.1/6.2.swift` 选中的 Xcode 26 及更早版本编到 `TargetActionProxy` 时报错。shim 里的这段声明当初就写明「macOS 27 SDK 成为最低要求时整段删掉」;用户确认项目已统一使用 Xcode 27。fork 的 CI 仍用 Xcode 16.4,在 `main` 上本来就是红的(examples 任务失败)。其余几个库在旧 Xcode 上不受影响。 +- **复查条件**:需要重新支持 Xcode 26 时。 + +### `destination` 的 present 闭包从别的视图控制器弹出时,察觉不到用户关闭 + +- **裁决**:不修。(2026-11-14) +- **理由**:察觉用户关闭只看调用 `destination` 的那个视图控制器的 `presentedViewControllers`,文档已写明。改动前交换 `dismissViewController:` 不分发起者,所以这是这次引入的差别。但从别的视图控制器弹 sheet 没有实际用处(sheet 挂在同一个窗口上),要支持就得读被弹出者的 `presentingViewController`,它不是弱引用,发起者释放时读取会崩。 +- **复查条件**:有调用方确实需要从别处弹出时。 + +### 存取面板的 URL 绑定只在经库的 `sheet` / `modal` 弹出时写回 + +- **裁决**:按用户决定,不修。(2026-11-14) +- **理由**:不交换私有方法,就只有面板的结果(`beginSheetModal` 的回调、`runModal` 的返回值)能告诉库用户选了什么,而只有运行面板的一方看得到。App 自己 `begin` / `runModal` 时从结果里取即可。依赖这个 fork 的 App 与案例都经 `sheet` / `modal` 使用。 +- **复查条件**:有 App 需要自己运行面板又想用绑定时。 + +### 弹出期间每轮 run loop 都检查一次 + +- **裁决**:不修。(2026-11-14) +- **理由**:察觉用户关闭弹出的视图控制器,靠的是弹出期间每轮 run loop(休眠前和每次运行结束)调用一次检查闭包,取一次 `presentedViewControllers`。改动前视图控制器的弹出没有这项开销,sheet、popover、push 的等待早就这样做。一次闭包调用加一个小数组,与处理事件本身相比可以忽略,这是不交换方法的代价。 +- **复查条件**:出现可测的性能问题时(用 `sample` 采样)。 + +### 栈不在任何窗口里时,push 推迟到它出现 + +- **裁决**:剩下的这部分不修。(2026-11-14) +- **理由**:改动前只要发起者出现过一次就立刻 push;现在要等栈所在的窗口在屏幕上或已最小化。最小化的情形已修好,有回归测试。还剩未选中的标签页:栈的视图不在任何窗口里,push 推迟到标签页被选中时补上,不会丢。不交换 `viewDidAppear` 就无从知道视图是否出现过。 +- **复查条件**:有 App 依赖往隐藏标签页里的栈 push 时。 + ## 系统限制 ### Xcode 26.6 上 `observe(_:)` 的两条 `@isolated(any)` 转换警告 @@ -56,4 +107,4 @@ ### transient popover 被点外部关闭时的回写 -- `present(style: .popover(...))` 在用户关闭时把 binding 写回 `nil`,依靠的是 AppKit 调用 `dismissViewController:`。用 `dismiss(nil)` 关闭的情形有测试覆盖;点击 popover 外部触发的 transient 关闭,在单元测试里没法模拟,所以 AppKit 在这条路径上是否也调用 `dismissViewController:`,还没有验证。 +- `present(style: .popover(...))` 在用户关闭时把 binding 写回 `nil`。2026-11-14 起不再依靠 AppKit 调用 `dismissViewController:`:只要 popover 关闭后 AppKit 把视图控制器移出发起者的 `presentedViewControllers`、它的窗口也不再可见,就会写回。`ViewControllerPresentationTests` 用 `NSPopover.close()` 关闭的情形有测试覆盖;点击 popover 外部触发的关闭在单元测试里没法模拟,那条路径是否也走 `close()`,还没有验证。 diff --git a/Sources/AppKitNavigation/Internal/RunLoopWait.swift b/Sources/AppKitNavigation/Internal/RunLoopWait.swift index e16ffe499a..63290f3f88 100644 --- a/Sources/AppKitNavigation/Internal/RunLoopWait.swift +++ b/Sources/AppKitNavigation/Internal/RunLoopWait.swift @@ -54,6 +54,15 @@ var appKitNavigationIsViewOnScreen: Bool { isViewLoaded && view.window?.isVisible == true } + + /// Whether the view controller's view is in a window that is on screen or minimized to the + /// Dock. + /// + /// Never loads the view. + var appKitNavigationIsViewOnScreenOrMinimized: Bool { + guard isViewLoaded, let window = view.window else { return false } + return window.isVisible || window.isMiniaturized + } } #endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift index 3ed8259779..18bb5cfa44 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift @@ -11,8 +11,8 @@ /// `NSNavigationController`. Setting the binding to `false` pops the view controller, along /// with anything pushed above it. When the user goes back past it — with the back button, ⌘↑ /// or a swipe — or it dismisses itself with `traitCollection.dismiss()`, the binding is set to - /// `false`. The view controller is pushed once the navigation controller is on screen, onto - /// the top of its stack. + /// `false`. The view controller is pushed onto the top of the stack once the navigation + /// controller is in a window that is on screen or minimized. /// /// Available with the `AppKitPlus` package trait. /// @@ -166,16 +166,17 @@ weak var presenter: NSViewController? func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { - // NB: What has to be on screen is the stack the push lands on, not the presenter: one that - // something else has been pushed over still pushes onto the top. A presenter in no - // navigation controller waits for its own view, and 'begin' then reports the misuse. One - // that has gone away counts as ready, so that 'begin' finds out. + // NB: What has to have come on screen is the stack the push lands on, not the presenter: one + // that something else has been pushed over still pushes onto the top, and so does a + // stack whose window is in the Dock. A presenter in no navigation controller waits for + // its own view, and 'begin' then reports the misuse. One that has gone away counts as + // ready, so that 'begin' finds out. RunLoopWait.until( { [weak presenter] in guard let presenter else { return true } let navigationController = presenter.navigationController ?? presenter as? NSNavigationController - return (navigationController ?? presenter).appKitNavigationIsViewOnScreen + return (navigationController ?? presenter).appKitNavigationIsViewOnScreenOrMinimized }, then: body ) diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 77c0a19824..fdc34fab6a 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -25,7 +25,8 @@ /// Like SwiftUI's `sheet` and `popover` view modifiers, but for AppKit. Setting the binding to /// `false` dismisses the view controller. When the user dismisses it — a Cancel button wired to /// `dismissController(_:)`, a transient popover closing — the binding is set to `false`. The - /// view controller is presented once this view controller's view is in a window on screen. + /// view controller is presented once this view controller's view is in a window on screen; a + /// modal window also goes up while that window is minimized. /// /// - Parameters: /// - isPresented: A binding to a Boolean value that determines whether to present the view @@ -302,10 +303,20 @@ func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { // NB: A sheet or a popover attaches to the presenter's window, so the presenter has to be on - // screen, the way 'NSWindow.sheet' and 'NSView.popover' wait for their anchors. One that - // has gone away counts as ready, so that 'begin' finds out. - RunLoopWait.until( - { [weak presenter] in presenter?.appKitNavigationIsViewOnScreen ?? true }, + // screen, the way 'NSWindow.sheet' and 'NSView.popover' wait for their anchors. A modal + // window has a window of its own, and a transition of the caller's own is up to the + // caller, so those only need the presenter's window to have come on screen: one in the + // Dock will do. A presenter that has gone away counts as ready, so that 'begin' finds + // out. + let isReady: @MainActor (NSViewController) -> Bool + switch transition { + case .style(.sheet), .style(.popover): + isReady = { $0.appKitNavigationIsViewOnScreen } + case .style(.modalWindow), .style(.custom), .custom: + isReady = { $0.appKitNavigationIsViewOnScreenOrMinimized } + } + return RunLoopWait.until( + { [weak presenter] in presenter.map(isReady) ?? true }, then: body ) } diff --git a/Tests/AppKitNavigationTests/NavigationDestinationTests.swift b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift index fab11f5310..9aabd713cd 100644 --- a/Tests/AppKitNavigationTests/NavigationDestinationTests.swift +++ b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift @@ -61,6 +61,28 @@ XCTAssertEqual(dismissCount.value, 1) } + /// A push needs a navigation stack in a window, not one on screen: one asked for while the + /// window is in the Dock lands at once. + @MainActor + func testPushesWhileTheWindowIsMinimized() throws { + let (navigationController, root) = makeNavigationController() + let window = try XCTUnwrap(navigationController.view.window) + window.styleMask.insert(.miniaturizable) + window.miniaturize(nil) + try XCTSkipUnless(waitUntil { window.isMiniaturized }, "This runner cannot minimize windows") + @UIBinding var detail: Detail? = nil + root.navigationDestination(item: $detail) { detail in + DetailViewController(name: detail.name) + } + + withoutAnimation { detail = Detail(name: "Mars") } + + XCTAssertTrue( + waitUntil { topName(of: navigationController) == "Mars" }, + "The destination waited for the window to come back" + ) + } + /// A push lands on top of the stack, wherever in it the view controller that asks for it is. @MainActor func testAViewControllerThatAnotherDestinationCoversStillPushes() { diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift index 94b3b70994..9e3d169ce0 100644 --- a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -238,6 +238,40 @@ // MARK: - Modal window style + /// A modal window has a window of its own, so it does not wait for the presenter's window to + /// come back from the Dock. + @MainActor + func testAModalWindowIsPresentedWhileThePresentersWindowIsMinimized() throws { + let viewController = makeViewController(width: 480, height: 320) + let window = NSWindow(contentViewController: viewController) + window.styleMask.insert(.miniaturizable) + window.isReleasedWhenClosed = false + window.orderFront(nil) + addTeardownBlock { @MainActor in + window.close() + } + window.miniaturize(nil) + try XCTSkipUnless(waitUntil { window.isMiniaturized }, "This runner cannot minimize windows") + let presentedViewController = makeViewController() + @UIBinding var isPresented = false + viewController.present(isPresented: $isPresented, style: .modalWindow) { + presentedViewController + } + abortModalLoops(after: 5) + + let wasOnScreen = Recorded(false) + perform(after: 0.5) { + wasOnScreen.value = presentedViewController.view.window?.isVisible == true + isPresented = false + } + isPresented = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "The binding was never reset") + XCTAssertTrue( + wasOnScreen.value, "The modal window waited for the presenter's window to come back" + ) + } + @MainActor func testSettingTheBindingToFalseDismissesAModalWindow() { let host = makeHost() From 7cea303fc527cdc0cd362fd79b07193be413bd64 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:41:51 +0800 Subject: [PATCH 126/141] docs(appkit): say what the presentation readiness checks actually look at --- .../Navigation/NavigationDestination.swift | 9 ++++----- Sources/AppKitNavigation/Navigation/Presentation.swift | 5 ++--- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift index 18bb5cfa44..45674e52d5 100644 --- a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift +++ b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift @@ -166,11 +166,10 @@ weak var presenter: NSViewController? func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { - // NB: What has to have come on screen is the stack the push lands on, not the presenter: one - // that something else has been pushed over still pushes onto the top, and so does a - // stack whose window is in the Dock. A presenter in no navigation controller waits for - // its own view, and 'begin' then reports the misuse. One that has gone away counts as - // ready, so that 'begin' finds out. + // NB: What has to be in a window on screen, or in the Dock, is the stack the push lands on, + // not the presenter: one that something else has been pushed over still pushes onto the + // top. A presenter in no navigation controller waits for its own view, and 'begin' then + // reports the misuse. One that has gone away counts as ready, so that 'begin' finds out. RunLoopWait.until( { [weak presenter] in guard let presenter else { return true } diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index fdc34fab6a..0519771661 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -305,9 +305,8 @@ // NB: A sheet or a popover attaches to the presenter's window, so the presenter has to be on // screen, the way 'NSWindow.sheet' and 'NSView.popover' wait for their anchors. A modal // window has a window of its own, and a transition of the caller's own is up to the - // caller, so those only need the presenter's window to have come on screen: one in the - // Dock will do. A presenter that has gone away counts as ready, so that 'begin' finds - // out. + // caller, so for those the presenter's window may be on screen or in the Dock. A + // presenter that has gone away counts as ready, so that 'begin' finds out. let isReady: @MainActor (NSViewController) -> Bool switch transition { case .style(.sheet), .style(.popover): From d095d4773851fce08687d31a93a56227c47edf3e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:42:54 +0800 Subject: [PATCH 127/141] docs: note the shim removal as implemented and awaiting review --- Documentations/Evolutions/draft-appkit-remove-shim.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md index 472fc4237f..dfef693de4 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -33,6 +33,11 @@ - AppKitNavigation 从此只能用 Xcode 27(macOS 27 SDK)编译。`Package@swift-6.0/6.1/6.2.swift` 来自上游,保留,只删 shim target;上游从来没有这个 target,删掉后与上游更接近。 - `UIKitNavigationShim` 也在交换方法,不在这一批的范围里。 +后续项: + +- 把弹出与 push 两套「先出现、再离开且下屏」的结束检测合成一个共用 helper(见 `Internal/ReviewDecisions.md`)。 +- fork 的 CI 仍用 Xcode 16.4,编不过 AppKitNavigation 了;要么换成 Xcode 27,要么不再编它。CI 在这次改动之前就已经是红的。 + ## 决策日志 | 日期 | 决定 | 理由 | @@ -42,9 +47,10 @@ | 2026-11-14 | push 的就绪条件看导航栈而不是发起者 | 起草时打算统一用「发起者在屏幕上」,实现前发现这会让被盖住的发起者推不出新页面,改变既有行为;弹出 sheet 和 popover 确实需要发起者的窗口,所以只在 push 上区别对待 | | 2026-11-14 | 弹出之后立刻同步记一次「已列入 `presentedViewControllers`」,不只靠 run loop 检查 | 测试里用户在同一轮 run loop 内就关掉了 sheet,检查还没来得及看到它被弹出,于是永远等不到「离开列表」 | | 2026-11-14 | `RunLoopWait` 除了 run loop 要休眠时,每次一轮运行结束时也检查,并排在所有同阶段的观察者(含 Core Animation 的提交)之后 | AppKit 每取一个事件都单独跑一轮 run loop,这样用户关闭弹出内容后,下一个事件被处理之前就已写回绑定,用户紧接着再要求弹出不会被这次写回冲掉。这个改动作用于所有用 `RunLoopWait` 的风格,AppKit 测试全部通过 | +| 2026-11-14 | 用户关闭后的写回不再与 AppKit 的关闭同步发生,`testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt` 改为等写回之后再立刻设回 `true` | 交换方法时写回发生在 `viewDidDisappear` 里,不交换就没有同步的时机。原测试在同一段同步代码里关闭 sheet 又设回 `true`,真实使用中两次操作之间总隔着事件循环;改后仍覆盖它要测的情形:中间那次 `false` 没被 `observe` 看到时,内容照样能再弹出 | | 2026-11-14 | 存取面板测试经私有方法 `completeWithReturnCode:url:urls:` 模拟用户确认,私有方法只出现在测试里 | 面板在另一个进程里运行,本进程里的 `ok(_:)` 直接抛「not implemented」,公开 API 里没有别的办法让面板以「确定」结束;调用前先检查方法还在,不在就让测试失败而不是崩溃。旧测试同样调用私有 setter。临时关掉写回时,四个确认用例都会失败 | | 2026-11-14 | 案例里的存储面板在弹出前先清空 `savedURL` | 取消不再动绑定,不清空的话,取消后的记录会显示上一次选的文件名 | | 2026-11-14 | 自审:模态窗口、自定义转场与 push 在窗口最小化时也就绪 | 自审指出它们本不需要发起者的窗口在屏幕上,改动后却会一直等到窗口还原,而改动前是立刻弹出。先写了两条在最小化窗口上弹出与 push 的测试,修前失败、修后通过 | | 2026-11-14 | 自审其余发现登记进 `Internal/ReviewDecisions.md` | 共 10 条:1 条已修(上一行);2 条误报;1 条暂缓;5 条是方案有意接受的代价;存储面板取消时的写法留给用户定,见下一行 | | 2026-11-14 | 存储面板取消时不动绑定,待用户确认 | 在 `main` 上实测,交换方法的旧实现在用户取消时会把绑定写成 `nil`。用户开工前选的方案写的是「取消时绑定不变」,当时没有说明旧行为,所以交付时请用户再确认一次 | -| 2026-11-14 | 用户关闭后的写回不再与 AppKit 的关闭同步发生,`testPresentedSheetCanBePresentedAgainAfterTheUserDismissedIt` 改为等写回之后再立刻设回 `true` | 交换方法时写回发生在 `viewDidDisappear` 里,不交换就没有同步的时机。原测试在同一段同步代码里关闭 sheet 又设回 `true`,真实使用中两次操作之间总隔着事件循环;改后仍覆盖它要测的情形:中间那次 `false` 没被 `observe` 看到时,内容照样能再弹出 | +| 2026-11-14 | 实现完成,待用户看过后收尾 | 文档已同步:本提案、`present` / `destination` / `navigationDestination` 与存取面板绑定的文档注释、`Internal/ReviewDecisions.md`。改动只涉及内部机制与既有 API 的语义,不需要另写使用指南或实现说明,也没有新术语 | From 62d70f420a999f4333df84e1d67fbaefee8927da Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 14:48:07 +0800 Subject: [PATCH 128/141] docs: record that cancelling a save panel keeps its binding as it is --- Documentations/Evolutions/draft-appkit-remove-shim.md | 3 ++- Documentations/Internal/ReviewDecisions.md | 6 ++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md index dfef693de4..2ac581ff4b 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -26,7 +26,7 @@ 没有询问就采用的假设: -- 存取面板的绑定只在经库的 `sheet` / `modal` 弹出时写回;App 自己调用 `begin` / `runModal` 时不写回,结果从完成回调里取。取消时绑定保持原值。依赖这个 fork 的 App(PrivateSymbols)与案例都只经 `sheet` / `modal` 使用,读完即清空。 +- 存取面板的绑定只在经库的 `sheet` / `modal` 弹出时写回;App 自己调用 `begin` / `runModal` 时不写回,结果从完成回调里取。取消时绑定保持原值——交换方法的旧实现会写成 `nil`,用户确认改用新语义。依赖这个 fork 的 App(PrivateSymbols)与案例都只经 `sheet` / `modal` 使用,读完即清空。 - 弹出的就绪条件从「发起者的视图出现过」改为看它此刻所在的窗口:sheet 与 popover 要求窗口在屏幕上,视图出现过又离开窗口时(切到别的标签页、被导航栈里的新页面盖住),绑定再变成有值会等它回到屏幕上再弹,不再立刻弹出一个没有窗口可依附的 sheet;模态窗口与自定义转场不需要发起者的窗口,窗口最小化时也照常弹出。 - push 的就绪条件看导航栈所在的窗口而不是发起者:被盖住的发起者照旧立刻把新页面压到栈顶,窗口最小化时也照常 push,与改动前一致;栈的视图不在任何窗口里时(未选中的标签页)推迟到它出现。 - 盯着用户关闭的检查在整个弹出期间每轮 run loop 做一次,只是一次闭包调用,与 `navigationDestination` 的做法相同。 @@ -54,3 +54,4 @@ | 2026-11-14 | 自审其余发现登记进 `Internal/ReviewDecisions.md` | 共 10 条:1 条已修(上一行);2 条误报;1 条暂缓;5 条是方案有意接受的代价;存储面板取消时的写法留给用户定,见下一行 | | 2026-11-14 | 存储面板取消时不动绑定,待用户确认 | 在 `main` 上实测,交换方法的旧实现在用户取消时会把绑定写成 `nil`。用户开工前选的方案写的是「取消时绑定不变」,当时没有说明旧行为,所以交付时请用户再确认一次 | | 2026-11-14 | 实现完成,待用户看过后收尾 | 文档已同步:本提案、`present` / `destination` / `navigationDestination` 与存取面板绑定的文档注释、`Internal/ReviewDecisions.md`。改动只涉及内部机制与既有 API 的语义,不需要另写使用指南或实现说明,也没有新术语 | +| 2026-11-14 | 用户确认:存储面板取消时绑定保持原值 | 用户看过旧实现「取消即写成 `nil`」的实测结果后,仍选择取消时不动绑定;案例在弹出前清空 `savedURL` 的那一行保留 | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md index 3bd4ea965c..8d290f141d 100644 --- a/Documentations/Internal/ReviewDecisions.md +++ b/Documentations/Internal/ReviewDecisions.md @@ -77,6 +77,12 @@ - **理由**:不交换私有方法,就只有面板的结果(`beginSheetModal` 的回调、`runModal` 的返回值)能告诉库用户选了什么,而只有运行面板的一方看得到。App 自己 `begin` / `runModal` 时从结果里取即可。依赖这个 fork 的 App 与案例都经 `sheet` / `modal` 使用。 - **复查条件**:有 App 需要自己运行面板又想用绑定时。 +### 存储面板取消时不再把绑定清空 + +- **裁决**:按用户决定,不修。(2026-11-14) +- **理由**:交换私有 setter 的旧实现在用户取消时也会被 AppKit 调用,把绑定写成 `nil`(在 `main` 上实测)。现在只在面板以「确定」结束时写回,取消保持原值;用户看过旧行为后确认保留新语义。想在取消后看到空值的调用方,在弹出前自己清空,案例就是这样做的。 +- **复查条件**:调用方普遍需要「取消即清空」时,再考虑加一个选项。 + ### 弹出期间每轮 run loop 都检查一次 - **裁决**:不修。(2026-11-14) From 0efd8aa46d9e9ac81bffb502ae468616a3eaf8a6 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 15:08:41 +0800 Subject: [PATCH 129/141] fix(appkit): report a binding's own dismissal as soon as AppKit returns AppKit has taken a presented view controller off screen by the time `dismiss(_:)` returns. While the shim reported dismissals from `viewDidDisappear`, a dismissal the binding asked for therefore ended while the binding's change was still being applied; since the shim went away it waited for the run loop turn to end. `end` now checks right after dismissing and ends the presentation there and then. A dismissal still on its way out, through an animator of the caller's own, is left to the watch, and one the user starts is still noticed as the run loop turn ends. The new test reads `onDismiss` from a custom transaction key, whose `perform` runs once the binding's change has been applied. It failed before. --- .../Evolutions/draft-appkit-remove-shim.md | 2 + .../Navigation/Presentation.swift | 83 +++++++++++-------- .../ViewControllerPresentationTests.swift | 50 +++++++++++ 3 files changed, 101 insertions(+), 34 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/draft-appkit-remove-shim.md index 2ac581ff4b..5130b3535e 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/draft-appkit-remove-shim.md @@ -37,6 +37,7 @@ - 把弹出与 push 两套「先出现、再离开且下屏」的结束检测合成一个共用 helper(见 `Internal/ReviewDecisions.md`)。 - fork 的 CI 仍用 Xcode 16.4,编不过 AppKitNavigation 了;要么换成 Xcode 27,要么不再编它。CI 在这次改动之前就已经是红的。 +- 窗口 sheet(`NSWindow.sheet`)与模态会话(`modalSession`)由绑定关闭时,同样等到这一轮 run loop 结束才写回,`main` 上就是这样。可以照视图控制器的做法,在关闭调用返回后立刻检查一次。 ## 决策日志 @@ -54,4 +55,5 @@ | 2026-11-14 | 自审其余发现登记进 `Internal/ReviewDecisions.md` | 共 10 条:1 条已修(上一行);2 条误报;1 条暂缓;5 条是方案有意接受的代价;存储面板取消时的写法留给用户定,见下一行 | | 2026-11-14 | 存储面板取消时不动绑定,待用户确认 | 在 `main` 上实测,交换方法的旧实现在用户取消时会把绑定写成 `nil`。用户开工前选的方案写的是「取消时绑定不变」,当时没有说明旧行为,所以交付时请用户再确认一次 | | 2026-11-14 | 实现完成,待用户看过后收尾 | 文档已同步:本提案、`present` / `destination` / `navigationDestination` 与存取面板绑定的文档注释、`Internal/ReviewDecisions.md`。改动只涉及内部机制与既有 API 的语义,不需要另写使用指南或实现说明,也没有新术语 | +| 2026-11-14 | 由绑定触发的视图控制器关闭,在 `dismiss(_:)` 返回后立刻检查、当场写回 | 用户指出 AppKit 的 `dismiss(_:)` 返回时内容已经离屏,与 UIKit 不同。交换方法时这条路是同步写回的,去掉之后却要等这一轮 run loop 结束;用户选择只恢复这一条,用户自己关掉的仍在这一轮结束时写回。新测试借自定义事务键在绑定变化应用完的那一刻检查 `onDismiss` 是否已运行,修前失败、修后通过 | | 2026-11-14 | 用户确认:存储面板取消时绑定保持原值 | 用户看过旧实现「取消即写成 `nil`」的实测结果后,仍选择取消时不动绑定;案例在弹出前清空 `savedURL` 的那一行保留 | diff --git a/Sources/AppKitNavigation/Navigation/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift index 0519771661..b64fc5fb3b 100644 --- a/Sources/AppKitNavigation/Navigation/Presentation.swift +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -332,24 +332,11 @@ // NB: AppKit tells no one but the presenter that it dismissed a view controller, and the user // can dismiss one without going through the binding: with a Cancel button wired to // 'dismissController:', or by closing a transient popover. So the view controller is - // watched instead. Once AppKit has listed it among the presenter's presented view - // controllers, it counts as ended when it has left that list and its window is off - // screen. The watch starts before presenting, so that it also runs inside any modal loop - // presenting starts. - let record = PresentationRecord(didEnd: didEnd) + // watched instead, as the record describes. The watch starts before presenting, so that + // it also runs inside any modal loop presenting starts. + let record = PresentationRecord(presenter: presenter, child: child, didEnd: didEnd) child.appKitNavigationPresentationRecord = record - _ = RunLoopWait.until( - { [weak presenter, weak child] in - guard !record.hasEnded, let child else { return true } - let isPresented = presenter?.presentedViewControllers?.contains(child) == true - if isPresented { - record.hasBeenPresented = true - } - return record.hasBeenPresented && !isPresented - && (!child.isViewLoaded || child.view.window?.isVisible != true) - }, - then: { record.end() } - ) + _ = RunLoopWait.until({ record.hasEnded || record.isOver() }, then: { record.end() }) switch transition { case let .style(style): presenter.present(child, as: style) @@ -358,11 +345,9 @@ present(child, transaction) } } - // NB: Noted right away as well, since the watch only looks when the run loop is about to - // wait: the user can dismiss the view controller before that. - if presenter.presentedViewControllers?.contains(child) == true { - record.hasBeenPresented = true - } + // NB: Noted right away as well, since the watch only looks as a run loop turn ends: the + // user can dismiss the view controller before that. + record.noteWhetherPresented() } func end(_ child: NSViewController, transaction: UITransaction) { @@ -372,34 +357,44 @@ // safe to read while the presenter is being deallocated. if let presenter, presenter.presentedViewControllers?.contains(child) == true { presenter.dismiss(child) - return } case let .custom(_, dismiss): withUITransaction(transaction) { dismiss(child, transaction) } - if presenter?.presentedViewControllers?.contains(child) == true { - return - } } - // NB: One that went through AppKit's presentation ends once the watch sees it off screen. - // Any other one, and one whose presenter has gone away, ends now. + // NB: AppKit has taken a view controller off screen by the time 'dismiss(_:)' returns, so + // the end is reported now rather than as the run loop turn ends, the way it was while + // the shim reported it from 'viewDidDisappear'. One still on its way out, through an + // animator of the caller's own, is left to the watch. One that never went through + // AppKit's presentation, or whose presenter has gone away, has ended as far as anyone + // can tell. guard let record = child.appKitNavigationPresentationRecord else { return } - if record.hasBeenPresented, presenter != nil { - return + let isOver = record.isOver() + if isOver || !record.hasBeenPresented || presenter == nil { + record.end() } - record.end() } } - /// What a view controller presented by ``ViewControllerPresentationStyle`` reports its end to. + /// What a view controller presented by ``ViewControllerPresentationStyle`` reports its end to, + /// and how to tell that it has ended: once AppKit has listed it among its presenter's presented + /// view controllers, it has ended when it has left that list and its window is off screen. @MainActor private final class PresentationRecord { + private weak var presenter: NSViewController? + private weak var child: NSViewController? /// Whether AppKit has listed the view controller among its presenter's presented ones. - var hasBeenPresented = false + private(set) var hasBeenPresented = false private var didEnd: (@MainActor () -> Void)? - init(didEnd: @escaping @MainActor () -> Void) { + init( + presenter: NSViewController, + child: NSViewController, + didEnd: @escaping @MainActor () -> Void + ) { + self.presenter = presenter + self.child = child self.didEnd = didEnd } @@ -407,6 +402,26 @@ didEnd == nil } + /// Notes whether AppKit lists the view controller among its presenter's presented ones now, + /// and returns whether it does. + @discardableResult + func noteWhetherPresented() -> Bool { + guard let child, presenter?.presentedViewControllers?.contains(child) == true else { + return false + } + hasBeenPresented = true + return true + } + + /// Whether the view controller, having been presented, has since been dismissed and has left + /// the screen, or has gone away altogether. + func isOver() -> Bool { + guard let child else { return true } + let isPresented = noteWhetherPresented() + return hasBeenPresented && !isPresented + && (!child.isViewLoaded || child.view.window?.isVisible != true) + } + /// Reports that the view controller has ended, unless that has been reported already. func end() { guard let didEnd else { return } diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift index 9e3d169ce0..9b33d5e437 100644 --- a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -123,6 +123,39 @@ XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not dismissed") } + /// AppKit takes a view controller off screen before `dismiss(_:)` returns, so the binding's + /// own dismissal ends while its change is being applied, with nothing left for a later turn + /// of the run loop. + @MainActor + func testSettingTheBindingToFalseEndsTheSheetWhileTheChangeIsApplied() { + let host = makeHost() + @UIBinding var isPresented = false + let dismissCount = Recorded(0) + host.viewController.present( + isPresented: $isPresented, style: .sheet, onDismiss: { dismissCount.value += 1 } + ) { + self.makeViewController() + } + isPresented = true + XCTAssertTrue(waitUntil { host.window.attachedSheet != nil }, "The sheet never appeared") + + let dismissCountOnceApplied = Recorded(nil) + var transaction = UITransaction() + transaction[ChangeAppliedKey.self] = { + dismissCountOnceApplied.value = dismissCount.value + } + withUITransaction(transaction) { + isPresented = false + } + + XCTAssertTrue( + waitUntil { dismissCountOnceApplied.value != nil }, "The change was never applied" + ) + XCTAssertEqual( + dismissCountOnceApplied.value, 1, "'onDismiss' waited for a later turn of the run loop" + ) + } + // NB: 'sheet(isSheeted:)' once dismissed a view controller sheet the moment it appeared, while // its own implementation of sheets still existed next to this one. @MainActor @@ -388,4 +421,21 @@ ) } } + + /// Runs its value once a change made in its transaction has been applied: `observe` wraps the + /// re-run a change causes in the `perform` of every custom key the change's transaction carries. + private enum ChangeAppliedKey: _UICustomTransactionKey { + static let defaultValue: (@MainActor @Sendable () -> Void)? = nil + + static func perform( + value: (@MainActor @Sendable () -> Void)?, + operation: @Sendable () -> Void + ) { + operation() + guard let value else { return } + MainActor.assumeIsolated { + value() + } + } + } #endif From 65f6c0c7f2c732cd480e309067a5127e0934402c Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 19:19:11 +0800 Subject: [PATCH 130/141] docs(examples): lay the AppKit case studies out as grouped forms and make every sheet closable The Basics case study's Boolean sheet showed one line of text and no button, so once it came up nothing could close it; the Wi-Fi network detail sheet had the same dead end after cancelling "Forget". Half of the AppKit pages were also line-for-line ports of the UIKit ones: a pile of buttons in the middle of the window, with the state written into their titles as emoji. Every AppKit page now lays its controls out the way System Settings does: titled groups of rows in rounded boxes, each row's title on its leading side and its state and controls on its trailing side, in a column that scrolls. The layout lives in the shared support file, so no file is added to the project. Every presented sheet has a Done button that Return triggers. The presented view controllers also implement cancel(_:): a sheet asks its delegate, which is the view controller AppKit presented, for it when nothing else handles Escape. --- Documentations/Evolutions/README.md | 1 + .../draft-appkit-examples-redesign.md | 47 ++ Documentations/README.md | 1 + .../AppKit+AnimationsViewController.swift | 108 ++--- ...ppKit+BasicsNavigationViewController.swift | 127 +++--- .../AppKit/AppKit+CaseStudySupport.swift | 415 +++++++++++++++--- ...+ConciseEnumNavigationViewController.swift | 99 +++-- .../AppKit+DismissalViewController.swift | 34 +- .../AppKit+EnumControlsViewController.swift | 81 ++-- ...pKit+ErasedNavigationStackController.swift | 94 ++-- .../AppKit/AppKit+FocusViewController.swift | 145 +++--- ...Kit+MinimalObservationViewController.swift | 60 +-- ...pKit+NSControlBindingsViewController.swift | 80 ++-- .../AppKit+NestedModalViewController.swift | 39 +- .../AppKit+OptionBindingsViewController.swift | 98 +++-- ...it+PresentationGalleryViewController.swift | 111 +++-- ...pKit+StaticNavigationStackController.swift | 82 +++- .../AppKit+TableSelectionViewController.swift | 144 +++--- ...ppKit+ConnectToNetworkViewController.swift | 2 + .../AppKit+NetworkDetailViewController.swift | 45 +- .../AppKit+WiFiSettingsViewController.swift | 29 +- 21 files changed, 1198 insertions(+), 644 deletions(-) create mode 100644 Documentations/Evolutions/draft-appkit-examples-redesign.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index aec0964d01..662a58b924 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -18,3 +18,4 @@ | 0010 | [AppKit 动画案例](0010-appkit-animations-case-study.md) | Implemented | | 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | | draft | [去掉 AppKitNavigationShim:不再交换系统方法](draft-appkit-remove-shim.md) | In Progress | +| draft | [AppKit 案例改用系统设置式的分组排版](draft-appkit-examples-redesign.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-examples-redesign.md b/Documentations/Evolutions/draft-appkit-examples-redesign.md new file mode 100644 index 0000000000..fb10ab26e5 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-examples-redesign.md @@ -0,0 +1,47 @@ +# Draft - AppKit 案例改用系统设置式的分组排版 + +- **状态**: In Progress +- **创建日期**: 2026-11-14 +- **最后更新**: 2026-11-14 +- **实现分支**: `appkit-examples-redesign` + +## 摘要 + +AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按钮堆在窗口正中,状态用 ✅/❌ 写进按钮标题;较新的页面从左上角往下排,每节一个粗体标题,能用但简陋。Basics 页里由布尔值弹出的 sheet 只有一行「Hello!」,没有任何按钮,弹出来就关不掉;Wi-Fi 案例的网络详情 sheet 也一样,在「忘记网络」的确认框里取消之后就没有出口。这一批把全部 AppKit 案例(15 个案例页,加上 Wi-Fi 案例的 3 个页面)改成「系统设置」那样的分组排版,并让每个弹出的 sheet 都能关掉。 + +## 方案 + +- **共享排版**放进已有的 `AppKit+CaseStudySupport.swift`,不新建源文件,也就不用改 `Examples.xcodeproj`: + - 页面:一列分组,放在可以滚动的区域里,靠上、水平居中,有最大宽度。 + - 分组:上方一行粗体标题,中间一个圆角框装着若干行,行与行之间画分隔线,下方可以有一段说明。 + - 行:左边是名称,右边是状态文字和控件;表格、画布、日志这类内容占满整行。 +- **每页只换排版**,演示的 API 和行为不变。状态改成行里的文字,不再写进按钮标题。 +- **sheet 都能关掉**:弹出的内容都有 Done 按钮,回车可以触发;按 Esc 也能关,做法见决策日志。 + +落地步骤(每步各自编译通过): + +1. 共享排版;Basics 与 Wi-Fi 网络详情的 sheet 加上关闭的办法。(已完成) +2. 其余页面逐页换成分组排版。(已完成) +3. 编译 CaseStudies 的 macOS 版,启动 App 逐页截图检查,修排版问题。(已完成) + +没有询问就采用的假设: + +- 分组标题照「系统设置」用粗体,不用选样式时预览里的全大写。 +- 共享排版只用 AppKit,不用 AppKitPlus:多数案例只依赖 AppKitNavigation,读者在页面代码里看到的应当只有这个库的用法。 +- 工具栏上的「About」按钮和各案例的说明文字保持原样。 +- NSControl bindings 页原先把模型里的颜色涂满整页背景,改为只由颜色井显示:整页背景会盖掉分组框的层次。默认颜色从窗口背景色改成系统蓝,否则颜色井看起来是空的。 +- Focus 页原先把有焦点的文本框涂成浅灰,深色模式下很刺眼,改成把那一行的名称染成强调色。 +- Basics 页的 sheet 内容从 SwiftUI 改用案例共用的 AppKit 视图控制器,与其他页面的 sheet 一致;它的 Done 按钮清空状态,演示由状态关闭。Basics 模型里装打开面板提示语的属性从 `alert` 改名为 `openPanelMessage`,那里弹的早就不是 alert。 +- Animations 页的圆默认改用系统蓝,颜色循环最后也回到系统蓝:原来的黑色在深色模式下几乎看不见。 +- Wi-Fi 设置页本来就是分组列表,只把分组框、宽度和边距对齐到其他页面;连接网络的面板给 Join 配上回车、给 Cancel 配上 Esc。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-14 | Created as Draft | Basics 页由布尔值弹出的 sheet 关不掉,AppKit 案例的界面也太简陋 | +| 2026-11-14 | 用户批准,开始实现 | 用户选定改全部 AppKit 页面、用系统设置式分组,并同意做完后由 agent 启动 App 逐页截图检查 | +| 2026-11-14 | sheet 关不掉不是去掉 AppKitNavigationShim 引入的 | 这个 sheet 的内容从 2024 年起就只有一行文字,它所在的文件也没被那次改动碰过;`main` 上同样关不掉 | +| 2026-11-14 | 分组、行和整页改用约束排列,不用 `NSStackView` 的 `.width` 对齐 | 第一次截图时整列都靠右、行内名称被挤到右边:`NSStackView` 的 `.width` 对齐并不会把子视图撑满宽度。改成自己用约束一个接一个地排,隐藏的行不占位置,分隔线跟着重画 | +| 2026-11-14 | Esc 关 sheet 由被弹出的视图控制器实现 `cancel(_:)` | 逆向 macOS 27.2 的 AppKit 得知:视图控制器弹出的 sheet 按 Esc 默认只会响一声;弹出时被呈现的视图控制器成为 sheet 窗口的 delegate,窗口处理 Esc 时先问 delegate 有没有 `cancel:`。这条路走的仍是正常的关闭流程。截图检查时示例 App 不在前台,后台发送的 Esc 送不到,还没在运行中验证 | +| 2026-11-14 | 实现完成,待用户看过后收尾 | `CaseStudies` 的 macOS 版编译通过,改动的文件没有警告。启动 App 逐页截图检查了 15 个案例页和 Wi-Fi 设置页,并点开 Basics 与 Dismissal 的 sheet、用 Done 关掉;Wi-Fi 网络详情的 sheet 要靠鼠标悬停才出现的按钮打开,没截到。文档判断:案例本身就是示例文档,不需要另写使用指南或实现说明,没有新术语 | diff --git a/Documentations/README.md b/Documentations/README.md index 256da6cc98..416b487af9 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -17,6 +17,7 @@ - [0010-appkit-animations-case-study.md](Evolutions/0010-appkit-animations-case-study.md):AppKit 动画案例。 - [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 - [draft-appkit-remove-shim.md](Evolutions/draft-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 +- [draft-appkit-examples-redesign.md](Evolutions/draft-appkit-examples-redesign.md):AppKit 案例改用系统设置式的分组排版,弹出的 sheet 都能关掉。 ## Internal diff --git a/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift index 4b5e422b50..4c449354a5 100644 --- a/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift @@ -14,45 +14,50 @@ class AnimationsViewController: XiblessViewController, AppKitCaseStudy { and cycle through its colors with the button. """ @UIBindable var model = Model() - private let canvasView = NSView() override func viewDidLoad() { super.viewDidLoad() - canvasView.wantsLayer = true - canvasView.layer?.backgroundColor = NSColor.quaternaryLabelColor.cgColor - canvasView.layer?.cornerRadius = 8 - canvasView.translatesAutoresizingMaskIntoConstraints = false + let canvasView = CanvasView() + canvasView.clipsToBounds = true + canvasView.heightAnchor.constraint(equalToConstant: 320).isActive = true + canvasView.onPointer = { [weak self] location in + withAppKitAnimation(Self.springAnimation) { + self?.model.position = location + } + } let circleView = NSView() circleView.wantsLayer = true canvasView.addSubview(circleView) - let isScaledLabel = NSTextField(labelWithString: "Is scaled?") - let isScaledSwitch = NSSwitch(isOn: $model.isScaled.animation(Self.springAnimation)) - let scaleRow = NSStackView(views: [isScaledLabel, isScaledSwitch]) - scaleRow.orientation = .horizontal - scaleRow.spacing = 12 - let cycleColorsButton = makeButton("Cycle colors") { [weak self] in - guard let self else { return } - Task { await self.model.cycleColors() } - } - let controls = NSStackView(views: [scaleRow, cycleColorsButton]) - controls.orientation = .vertical - controls.alignment = .centerX - controls.spacing = 12 - controls.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(controls) - view.addSubview(canvasView) - NSLayoutConstraint.activate([ - controls.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), - controls.centerXAnchor.constraint(equalTo: view.centerXAnchor), - canvasView.topAnchor.constraint(equalTo: controls.bottomAnchor, constant: 20), - canvasView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), - canvasView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20), - canvasView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20), - canvasView.heightAnchor.constraint(greaterThanOrEqualToConstant: 360), - ]) + addForm( + [ + FormSection( + "Circle", + rows: [ + FormRow( + "Scaled up", + accessories: [NSSwitch(isOn: $model.isScaled.animation(Self.springAnimation))] + ), + FormRow( + "Color", + accessories: [ + makeButton("Cycle colors") { [weak self] in + guard let self else { return } + Task { await self.model.cycleColors() } + }, + ] + ), + ] + ), + FormSection( + "Canvas", + footer: "Click or drag in the canvas to move the circle with a spring.", + rows: [FormRow(content: canvasView, insets: NSEdgeInsets())] + ), + ], + to: view + ) observe { [unowned self] in // NB: 'NSView' has no 'transform' to scale with, so the circle grows by its frame instead. @@ -68,22 +73,6 @@ class AnimationsViewController: XiblessViewController, AppKitCaseStudy { } } - override func mouseDown(with event: NSEvent) { - moveCircle(to: event) - } - - override func mouseDragged(with event: NSEvent) { - moveCircle(to: event) - } - - private func moveCircle(to event: NSEvent) { - let location = canvasView.convert(event.locationInWindow, from: nil) - guard canvasView.bounds.contains(location) else { return } - withAppKitAnimation(Self.springAnimation) { - model.position = location - } - } - /// A spring where the system has one, which is macOS 15 and later. private static var springAnimation: AppKitAnimation { if #available(macOS 15, *) { @@ -96,12 +85,12 @@ class AnimationsViewController: XiblessViewController, AppKitCaseStudy { @MainActor @Observable class Model { - var position = CGPoint(x: 150, y: 180) + var position = CGPoint(x: 150, y: 160) var isScaled = false - var color = NSColor.black + var color = NSColor.systemBlue func cycleColors() async { - let colors: [NSColor] = [.systemRed, .systemBlue, .systemTeal, .systemGreen, .systemPink, .systemPurple, .black] + let colors: [NSColor] = [.systemRed, .systemOrange, .systemYellow, .systemGreen, .systemTeal, .systemPurple, .systemBlue] for color in colors { withAppKitAnimation { self.color = color } try? await Task.sleep(for: .seconds(1)) @@ -110,6 +99,25 @@ class AnimationsViewController: XiblessViewController, AppKitCaseStudy { } } +/// The area the circle moves in. It reports where it is clicked and dragged. +private final class CanvasView: NSView { + var onPointer: (@MainActor (CGPoint) -> Void)? + + override func mouseDown(with event: NSEvent) { + report(event) + } + + override func mouseDragged(with event: NSEvent) { + report(event) + } + + private func report(_ event: NSEvent) { + let location = convert(event.locationInWindow, from: nil) + guard bounds.contains(location) else { return } + onPointer?(location) + } +} + #Preview { AnimationsViewController() } diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index cbff0e26d6..e1cd2ee5b1 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -1,5 +1,4 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import SwiftUI import AppKit import AppKitNavigation @@ -14,77 +13,95 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS override func viewDidLoad() { super.viewDidLoad() - let showAlertButton = NSButton() - showAlertButton.addAction { [weak self] _ in - self?.model.alert = "Hello!" - } - - let showSheetButton = NSButton() - showSheetButton.addAction { [weak self] _ in - self?.model.sheet = .random(in: 1 ... 1_000) - DispatchQueue.main.asyncAfter(deadline: .now() + 3) { - self?.model.sheet = nil - } - } - - let showSheetFromBooleanButton = NSButton() - showSheetFromBooleanButton.addAction { [weak self] _ in - self?.model.isSheetPresented = true - } - - let stack = NSStackView(views: [ - showAlertButton, - showSheetButton, - showSheetFromBooleanButton, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false + let openPanelStatusLabel = makeValueLabel() + let chosenFileLabel = makeValueLabel() + let numberSheetStatusLabel = makeValueLabel() + let sheetStatusLabel = makeValueLabel() - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) + addForm( + [ + FormSection( + "Optional state", + footer: "Setting an optional presents content for its value, and clearing it dismisses the content.", + rows: [ + FormRow( + "Open panel", + accessories: [ + openPanelStatusLabel, + makeButton("Show") { [weak self] in + self?.model.openPanelMessage = "Choose a file to show its name." + }, + ] + ), + FormRow("Chosen file", accessories: [chosenFileLabel]), + FormRow( + "Sheet with a number", + subtitle: "Closes itself after 3 seconds", + accessories: [ + numberSheetStatusLabel, + makeButton("Show") { [weak self] in + let number = Int.random(in: 1 ... 1_000) + self?.model.sheet = number + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { + // NB: Only the sheet this click presented: it may have been closed, and + // another one presented, in the meantime. + if self?.model.sheet == number { + self?.model.sheet = nil + } + } + }, + ] + ), + ] + ), + FormSection( + "Boolean state", + footer: "The sheet's Done button sets the Boolean back to false.", + rows: [ + FormRow( + "Sheet", + accessories: [ + sheetStatusLabel, + makeButton("Show") { [weak self] in + self?.model.isSheetPresented = true + }, + ] + ), + ] + ), + ], + to: view + ) observe { [unowned self] in - if let url = model.url { - showAlertButton.title = "URL is: \(url)" - } else { - showAlertButton.title = "Alert is presented: \(model.alert != nil ? "✅" : "❌")" - } - showSheetButton.title = "Sheet is presented: \(model.sheet != nil ? "✅" : "❌")" - showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.isSheetPresented ? "✅" : "❌")" + openPanelStatusLabel.stringValue = model.openPanelMessage != nil ? "Shown" : "Not shown" + chosenFileLabel.stringValue = model.url?.lastPathComponent ?? "None" + numberSheetStatusLabel.stringValue = model.sheet.map { "Showing \($0)" } ?? "Not shown" + sheetStatusLabel.stringValue = model.isSheetPresented ? "Shown" : "Not shown" } - modal(item: $model.alert, id: \.self) { [unowned self] message in -// let alert = NSAlert() -// alert.messageText = "This is an alert" -// alert.informativeText = message -// alert.addButton(withTitle: "OK") -// return alert + modal(item: $model.openPanelMessage, id: \.self) { [unowned self] message in let openPanel = NSOpenPanel(url: $model.url) openPanel.message = message return openPanel } - present(item: $model.sheet, id: \.self, style: .sheet) { count in - NSHostingController( - rootView: Form { Text(count.description) }.frame(width: 100, height: 100, alignment: .center) - ) + present(item: $model.sheet, id: \.self, style: .sheet) { [unowned self] number in + MessageViewController(message: "The number is \(number).") { [weak self] in + self?.model.sheet = nil + } } - present(isPresented: $model.isSheetPresented, style: .sheet) { - NSHostingController( - rootView: Form { Text("Hello!") }.frame(width: 100, height: 100, alignment: .center) - ) + present(isPresented: $model.isSheetPresented, style: .sheet) { [unowned self] in + MessageViewController(message: "Hello!") { [weak self] in + self?.model.isSheetPresented = false + } } } @Observable class Model { - var alert: String? + var openPanelMessage: String? var isSheetPresented = false var sheet: Int? var url: URL? diff --git a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift index e523e6734a..5cecb7d3fd 100644 --- a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift +++ b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift @@ -2,7 +2,28 @@ import AppKit import AppKitNavigation -// Small pieces the presentation and binding case studies share. +// Pieces the AppKit case studies share: the view controller they start from, a form laid out the +// way System Settings lays out its forms, and the windows and view controllers they present. + +/// A view controller whose view is a `View` made in code rather than loaded from a nib. +class XiblessViewController: NSViewController { + lazy var contentView = View() + + override func loadView() { + view = contentView + } + + override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { + super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +// MARK: - Controls /// A push button that runs `action` when clicked. @MainActor @@ -12,32 +33,285 @@ func makeButton(_ title: String, action: @escaping () -> Void) -> NSButton { return button } -/// A bold label that heads a group of controls. +/// A label for a value that a case study reads from its model, shown on the trailing side of a +/// row. @MainActor -func makeSectionLabel(_ title: String) -> NSTextField { - let label = NSTextField(labelWithString: title) - label.font = .boldSystemFont(ofSize: NSFont.systemFontSize) +func makeValueLabel(_ text: String = "") -> NSTextField { + let label = NSTextField(labelWithString: text) + label.textColor = .secondaryLabelColor + label.alignment = .right + label.lineBreakMode = .byTruncatingTail + // NB: A long value gives way before the row's title and controls do. + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) return label } -/// Lays `views` out in a column pinned to the top of `view`, and returns the column. +// MARK: - Forms + +/// Lays `sections` out the way System Settings lays out a form: one under another, in a column that +/// scrolls and grows no wider than reads well. @MainActor -@discardableResult -func addColumn(of views: [NSView], to view: NSView) -> NSStackView { - let column = NSStackView(views: views) - column.orientation = .vertical - column.alignment = .leading - column.spacing = 10 +func addForm(_ sections: [FormSection], to view: NSView) { + let column = FormColumnView(sections, spacing: 24) column.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(column) + + let documentView = FlippedView() + documentView.translatesAutoresizingMaskIntoConstraints = false + documentView.addSubview(column) + + let scrollView = NSScrollView() + scrollView.drawsBackground = false + scrollView.hasVerticalScroller = true + scrollView.autohidesScrollers = true + scrollView.documentView = documentView + scrollView.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(scrollView) + + let clipView = scrollView.contentView + let fillsTheWidth = column.widthAnchor.constraint(equalTo: documentView.widthAnchor, constant: -48) + fillsTheWidth.priority = .defaultHigh NSLayoutConstraint.activate([ - column.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20), - column.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), - column.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20), + scrollView.topAnchor.constraint(equalTo: view.topAnchor), + scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), + scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor), + scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor), + documentView.topAnchor.constraint(equalTo: clipView.topAnchor), + documentView.leadingAnchor.constraint(equalTo: clipView.leadingAnchor), + documentView.trailingAnchor.constraint(equalTo: clipView.trailingAnchor), + column.topAnchor.constraint(equalTo: documentView.topAnchor, constant: 20), + column.bottomAnchor.constraint(equalTo: documentView.bottomAnchor, constant: -24), + column.centerXAnchor.constraint(equalTo: documentView.centerXAnchor), + column.widthAnchor.constraint(lessThanOrEqualToConstant: 640), + fillsTheWidth, ]) - return column } +/// A label whose text wraps to the width it is laid out at: a note, a log or a dump of a model. +@MainActor +func makeWrappingLabel(_ text: String = "") -> NSTextField { + WrappingLabel(wrappingLabelWithString: text) +} + +/// A group of rows in a rounded box, with a title above the box and a note below it. +/// +/// Hide a section, or a row in it, to take it out of the form; what is left closes up. +final class FormSection: FormColumnView { + init(_ title: String? = nil, footer: String? = nil, rows: [FormRow]) { + var arrangedViews: [NSView] = [] + if let title { + let titleLabel = NSTextField(labelWithString: title) + titleLabel.font = .systemFont(ofSize: NSFont.systemFontSize, weight: .semibold) + arrangedViews.append(insetHorizontally(titleLabel)) + } + arrangedViews.append(FormBox(rows: rows)) + if let footer { + let footerLabel = makeWrappingLabel(footer) + footerLabel.font = .systemFont(ofSize: NSFont.smallSystemFontSize) + footerLabel.textColor = .secondaryLabelColor + arrangedViews.append(insetHorizontally(footerLabel)) + } + super.init(arrangedViews, spacing: 6) + } +} + +/// A row of a form section: a title on its leading side and controls on its trailing side, or +/// content of its own that spans the row. +final class FormRow: NSView { + /// The row's title. Empty for a row of content. + let titleLabel = NSTextField(labelWithString: "") + + /// A row with a title, and an optional line under it, on its leading side, and `accessories` + /// on its trailing side. + init(_ title: String, subtitle: String? = nil, accessories: [NSView] = []) { + super.init(frame: .zero) + titleLabel.stringValue = title + titleLabel.lineBreakMode = .byTruncatingTail + + let titleColumn = NSStackView(views: [titleLabel]) + titleColumn.orientation = .vertical + titleColumn.alignment = .leading + titleColumn.spacing = 2 + if let subtitle { + let subtitleLabel = NSTextField(labelWithString: subtitle) + subtitleLabel.font = .systemFont(ofSize: NSFont.smallSystemFontSize) + subtitleLabel.textColor = .secondaryLabelColor + subtitleLabel.lineBreakMode = .byTruncatingTail + titleColumn.addArrangedSubview(subtitleLabel) + } + titleColumn.translatesAutoresizingMaskIntoConstraints = false + addSubview(titleColumn) + + let accessoryRow = NSStackView(views: accessories) + accessoryRow.orientation = .horizontal + accessoryRow.alignment = .centerY + accessoryRow.spacing = 8 + accessoryRow.translatesAutoresizingMaskIntoConstraints = false + addSubview(accessoryRow) + + // NB: As short as its content allows, but never shorter than a row of buttons. + let compactHeight = heightAnchor.constraint(equalToConstant: 40) + compactHeight.priority = .defaultLow + NSLayoutConstraint.activate([ + titleColumn.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 12), + titleColumn.centerYAnchor.constraint(equalTo: centerYAnchor), + titleColumn.topAnchor.constraint(greaterThanOrEqualTo: topAnchor, constant: 8), + accessoryRow.leadingAnchor.constraint(greaterThanOrEqualTo: titleColumn.trailingAnchor, constant: 16), + accessoryRow.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -12), + accessoryRow.centerYAnchor.constraint(equalTo: centerYAnchor), + accessoryRow.topAnchor.constraint(greaterThanOrEqualTo: topAnchor, constant: 8), + heightAnchor.constraint(greaterThanOrEqualToConstant: 40), + compactHeight, + ]) + } + + /// A row that is all `content`, such as a table, a canvas or a log. + init(content: NSView, insets: NSEdgeInsets = NSEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)) { + super.init(frame: .zero) + pin(content, insets: insets) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +/// A column of views, one under another and each as wide as the column. A hidden view leaves no +/// gap. +/// +/// Unlike a vertical `NSStackView`, which only aligns its views, this stretches them to its width. +class FormColumnView: NSView { + private let arrangedViews: [NSView] + private let spacing: CGFloat + private var arrangementConstraints: [NSLayoutConstraint] = [] + private var hiddenObservations: [NSKeyValueObservation] = [] + + init(_ arrangedViews: [NSView], spacing: CGFloat) { + self.arrangedViews = arrangedViews + self.spacing = spacing + super.init(frame: .zero) + for arrangedView in arrangedViews { + arrangedView.translatesAutoresizingMaskIntoConstraints = false + addSubview(arrangedView) + } + hiddenObservations = arrangedViews.map { arrangedView in + arrangedView.observe(\.isHidden) { [weak self] _, _ in + MainActor.assumeIsolated { + self?.arrange() + } + } + } + arrange() + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + /// The arranged views that are not hidden, from the top. + var visibleArrangedViews: [NSView] { + arrangedViews.filter { !$0.isHidden } + } + + private func arrange() { + NSLayoutConstraint.deactivate(arrangementConstraints) + arrangementConstraints = [] + var previousBottom: NSLayoutYAxisAnchor? + for arrangedView in arrangedViews { + arrangementConstraints += [ + arrangedView.leadingAnchor.constraint(equalTo: leadingAnchor), + arrangedView.trailingAnchor.constraint(equalTo: trailingAnchor), + ] + guard !arrangedView.isHidden else { + // NB: Still placed, so that its layout is not ambiguous, but outside the column's height. + arrangementConstraints.append(arrangedView.topAnchor.constraint(equalTo: topAnchor)) + continue + } + arrangementConstraints.append( + previousBottom.map { arrangedView.topAnchor.constraint(equalTo: $0, constant: spacing) } + ?? arrangedView.topAnchor.constraint(equalTo: topAnchor) + ) + previousBottom = arrangedView.bottomAnchor + } + arrangementConstraints.append((previousBottom ?? topAnchor).constraint(equalTo: bottomAnchor)) + NSLayoutConstraint.activate(arrangementConstraints) + needsDisplay = true + } +} + +/// The rounded box of a form section. It draws the box, and a separator above every visible row +/// but the first. +private final class FormBox: FormColumnView { + init(rows: [FormRow]) { + super.init(rows, spacing: 0) + } + + override func draw(_ dirtyRect: NSRect) { + let hairline = 1 / (window?.backingScaleFactor ?? 2) + let box = NSBezierPath( + roundedRect: bounds.insetBy(dx: hairline / 2, dy: hairline / 2), xRadius: 10, yRadius: 10 + ) + NSColor.quaternarySystemFill.setFill() + box.fill() + box.lineWidth = hairline + NSColor.separatorColor.setStroke() + box.stroke() + + NSColor.separatorColor.setFill() + for row in visibleArrangedViews.dropFirst() { + let rowFrame = convert(row.bounds, from: row) + let lineY = isFlipped ? rowFrame.minY : rowFrame.maxY - hairline + NSBezierPath.fill(NSRect(x: bounds.minX + 12, y: lineY, width: bounds.width - 24, height: hairline)) + } + } + + override func layout() { + super.layout() + needsDisplay = true + } +} + +/// A label whose text wraps to the width it is laid out at. +private final class WrappingLabel: NSTextField { + override func layout() { + super.layout() + // NB: The label works its height out from this width, which only layout knows. + if preferredMaxLayoutWidth != bounds.width { + preferredMaxLayoutWidth = bounds.width + } + } +} + +/// A view whose origin is its top-left corner, so that a scroll view shows it from the top. +private final class FlippedView: NSView { + override var isFlipped: Bool { true } +} + +extension NSView { + /// Adds `subview` and pins its edges to this view's, `insets` in from them. + fileprivate func pin(_ subview: NSView, insets: NSEdgeInsets) { + subview.translatesAutoresizingMaskIntoConstraints = false + addSubview(subview) + NSLayoutConstraint.activate([ + subview.topAnchor.constraint(equalTo: topAnchor, constant: insets.top), + subview.leadingAnchor.constraint(equalTo: leadingAnchor, constant: insets.left), + subview.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -insets.right), + subview.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -insets.bottom), + ]) + } +} + +/// `view` in a container that insets it as far as a row insets its title. +@MainActor +private func insetHorizontally(_ view: NSView) -> NSView { + let container = NSView() + container.pin(view, insets: NSEdgeInsets(top: 0, left: 12, bottom: 0, right: 12)) + return container +} + +// MARK: - Presented content + /// A titled, closable window showing a message above a row of buttons. @MainActor func makeWindow(title: String, message: String, buttons: [NSButton]) -> NSWindow { @@ -49,42 +323,25 @@ func makeWindow(title: String, message: String, buttons: [NSButton]) -> NSWindow ) window.title = title window.isReleasedWhenClosed = false - - let messageLabel = NSTextField(wrappingLabelWithString: message) - let buttonRow = NSStackView(views: buttons) - buttonRow.orientation = .horizontal - buttonRow.spacing = 8 - let column = NSStackView(views: [messageLabel, buttonRow]) - column.orientation = .vertical - column.alignment = .leading - column.spacing = 16 - column.translatesAutoresizingMaskIntoConstraints = false - - let contentView = NSView() - contentView.addSubview(column) - NSLayoutConstraint.activate([ - column.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20), - column.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20), - column.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20), - column.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20), - messageLabel.widthAnchor.constraint(equalToConstant: 340), - ]) - window.contentView = contentView + window.contentView = makeMessageView(message: message, buttons: buttons) window.center() return window } -/// A view controller to present: a message above a row of buttons. +/// A view controller to present: a message above a row of buttons that ends with Done. /// -/// Its Done button dismisses it the way a user would, through `dismiss(_:)`, so the presentation -/// learns about it from the dismissal and clears its state. +/// Done and Return, and Escape in a sheet, run `done` when one is given. Otherwise they dismiss the +/// view controller the way a user would, through `dismiss(_:)`, so the presentation learns about +/// it from the dismissal and clears its state. class MessageViewController: XiblessViewController { private let message: String private let extraButtons: [NSButton] + private let done: (() -> Void)? - init(message: String, extraButtons: [NSButton] = []) { + init(message: String, extraButtons: [NSButton] = [], done: (() -> Void)? = nil) { self.message = message self.extraButtons = extraButtons + self.done = done super.init(nibName: nil, bundle: nil) } @@ -96,28 +353,64 @@ class MessageViewController: XiblessViewController { override func viewDidLoad() { super.viewDidLoad() - let messageLabel = NSTextField(wrappingLabelWithString: message) let doneButton = makeButton("Done") { [weak self] in - self?.dismiss(nil) + self?.finish() } doneButton.keyEquivalent = "\r" - let buttonRow = NSStackView(views: extraButtons + [doneButton]) - buttonRow.orientation = .horizontal - buttonRow.spacing = 8 - let column = NSStackView(views: [messageLabel, buttonRow]) - column.orientation = .vertical - column.alignment = .leading - column.spacing = 16 - column.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(column) - NSLayoutConstraint.activate([ - column.topAnchor.constraint(equalTo: view.topAnchor, constant: 20), - column.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20), - column.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20), - column.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -20), - messageLabel.widthAnchor.constraint(equalToConstant: 300), - ]) + view.pin(makeMessageView(message: message, buttons: extraButtons + [doneButton]), insets: NSEdgeInsets()) } + + /// Escape in a sheet. + /// + /// AppKit makes a view controller it presents as a sheet the sheet's delegate, and a window asks + /// its delegate for `cancel(_:)` when nothing else handles Escape. + @objc func cancel(_ sender: Any?) { + finish() + } + + private func finish() { + if let done { + done() + } else { + dismiss(nil) + } + } +} + +/// A message, under an optional bold title, above a row of buttons on the trailing side, the way +/// a dialog lays them out. +@MainActor +func makeMessageView(title: String? = nil, message: String, buttons: [NSButton]) -> NSView { + let messageLabel = NSTextField(wrappingLabelWithString: message) + messageLabel.preferredMaxLayoutWidth = 320 + let textColumn = NSStackView(views: [messageLabel]) + textColumn.orientation = .vertical + textColumn.alignment = .leading + textColumn.spacing = 6 + if let title { + let titleLabel = NSTextField(labelWithString: title) + titleLabel.font = .systemFont(ofSize: NSFont.systemFontSize, weight: .semibold) + textColumn.insertArrangedSubview(titleLabel, at: 0) + } + textColumn.translatesAutoresizingMaskIntoConstraints = false + let buttonRow = NSStackView(views: buttons) + buttonRow.orientation = .horizontal + buttonRow.spacing = 8 + buttonRow.translatesAutoresizingMaskIntoConstraints = false + + let container = NSView() + container.addSubview(textColumn) + container.addSubview(buttonRow) + NSLayoutConstraint.activate([ + messageLabel.widthAnchor.constraint(equalToConstant: 320), + textColumn.topAnchor.constraint(equalTo: container.topAnchor, constant: 20), + textColumn.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 20), + textColumn.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -20), + buttonRow.topAnchor.constraint(equalTo: textColumn.bottomAnchor, constant: 20), + buttonRow.leadingAnchor.constraint(greaterThanOrEqualTo: container.leadingAnchor, constant: 20), + buttonRow.trailingAnchor.constraint(equalTo: container.trailingAnchor, constant: -20), + buttonRow.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -20), + ]) + return container } #endif diff --git a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift index 90f340ccc2..6777acd5fb 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -1,5 +1,4 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import SwiftUI import AppKit import AppKitNavigation @@ -24,39 +23,53 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit override func viewDidLoad() { super.viewDidLoad() - let showAlertButton = NSButton() - showAlertButton.addAction { [weak self] _ in - self?.model.destination = .alert("Hello!") - } - let showSheetButton = NSButton() - showSheetButton.addAction { [weak self] _ in - self?.model.destination = .sheet(.random(in: 1 ... 1_000)) - } - let showSheetFromBooleanButton = NSButton() - showSheetFromBooleanButton.addAction { [weak self] _ in - self?.model.destination = .sheetWithoutPayload - } - - let stack = NSStackView(views: [ - showAlertButton, - showSheetButton, - showSheetFromBooleanButton, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false + let alertStatusLabel = makeValueLabel() + let numberSheetStatusLabel = makeValueLabel() + let sheetStatusLabel = makeValueLabel() - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) + addForm( + [ + FormSection( + "Destination", + footer: "One optional enum holds whichever of these is up, so at most one can be presented at a time.", + rows: [ + FormRow( + "Alert", + accessories: [ + alertStatusLabel, + makeButton("Show") { [weak self] in + self?.model.destination = .alert("Hello!") + }, + ] + ), + FormRow( + "Sheet with a number", + accessories: [ + numberSheetStatusLabel, + makeButton("Show") { [weak self] in + self?.model.destination = .sheet(.random(in: 1 ... 1_000)) + }, + ] + ), + FormRow( + "Sheet without a payload", + accessories: [ + sheetStatusLabel, + makeButton("Show") { [weak self] in + self?.model.destination = .sheetWithoutPayload + }, + ] + ), + ] + ), + ], + to: view + ) observe { [unowned self] in - showAlertButton.title = "Alert is presented: \(model.destination?.alert != nil ? "✅" : "❌")" - showSheetButton.title = "Sheet is presented: \(model.destination?.sheet != nil ? "✅" : "❌")" - showSheetFromBooleanButton.title = "Sheet is presented from boolean: \(model.destination?.sheetWithoutPayload != nil ? "✅" : "❌")" + alertStatusLabel.stringValue = model.destination?.alert != nil ? "Shown" : "Not shown" + numberSheetStatusLabel.stringValue = model.destination?.sheet.map { "Showing \($0)" } ?? "Not shown" + sheetStatusLabel.stringValue = model.destination?.sheetWithoutPayload != nil ? "Shown" : "Not shown" } modal(item: $model.destination.alert, id: \.self) { message in @@ -66,25 +79,15 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit alert.addButton(withTitle: "OK") return alert } - present(item: $model.destination.sheet, id: \.self, style: .sheet) { [unowned self] count in - NSHostingController( - rootView: Form { - Text(count.description) - Button("Close") { - self.model.destination = nil - } - }.frame(width: 200, height: 200, alignment: .center) - ) + present(item: $model.destination.sheet, id: \.self, style: .sheet) { [unowned self] number in + MessageViewController(message: "The number is \(number).") { [weak self] in + self?.model.destination = nil + } } present(isPresented: UIBinding($model.destination.sheetWithoutPayload), style: .sheet) { [unowned self] in - NSHostingController( - rootView: Form { - Text("Hello!") - Button("Close") { - self.model.destination = nil - } - }.frame(width: 200, height: 200, alignment: .center) - ) + MessageViewController(message: "Hello!") { [weak self] in + self?.model.destination = nil + } } } diff --git a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift index a222b29f64..ecec204434 100644 --- a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift @@ -18,14 +18,34 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { override func viewDidLoad() { super.viewDidLoad() - let presentButton = makeButton("Present the first fruit") { [weak self] in - self?.model.fruit = .apple - } - let logLabel = NSTextField(wrappingLabelWithString: "") + let fruitLabel = makeValueLabel() + let logLabel = makeWrappingLabel() logLabel.textColor = .secondaryLabelColor - addColumn(of: [presentButton, makeSectionLabel("onDismiss log"), logLabel], to: view) + + addForm( + [ + FormSection( + "Sheet", + footer: "Done dismisses the sheet the way a user would; its other buttons change the state instead.", + rows: [ + FormRow( + "Fruit", + accessories: [ + fruitLabel, + makeButton("Present") { [weak self] in + self?.model.fruit = .apple + }, + ] + ), + ] + ), + FormSection("onDismiss log", rows: [FormRow(content: logLabel)]), + ], + to: view + ) observe { [unowned self] in + fruitLabel.stringValue = model.fruit.map { $0.name.prefix(1).uppercased() + $0.name.dropFirst() } ?? "None" logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") } @@ -35,8 +55,8 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { }) { [unowned self] fruit in MessageViewController( message: """ - This sheet shows \(fruit.name). Done dismisses it yourself; the other buttons change \ - its state instead. + This sheet shows \(fruit.name). Done dismisses it the way a user would; the other \ + buttons change its state instead. """, extraButtons: [ makeButton("Clear the state") { [weak self] in diff --git a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift index 34031efb38..adbd36ce44 100644 --- a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift @@ -29,66 +29,47 @@ class EnumControlsViewController: XiblessViewController, AppKitCaseStudy override func viewDidLoad() { super.viewDidLoad() - let quantityLabel = NSTextField(labelWithString: "") - let quantityStepper = NSStepper() - quantityStepper.maxValue = .infinity - let quantityStack = NSStackView(views: [ - quantityLabel, - quantityStepper, - ]) - let outOfStockButton = NSButton() - outOfStockButton.addAction { [weak self] _ in + let statusLabel = makeValueLabel() + let outOfStockButton = makeButton("Out of stock") { [weak self] in self?.status = .outOfStock(isOnBackOrder: false) } - outOfStockButton.title = "Out of stock" - let inStockStack = NSStackView(views: [ - quantityStack, - outOfStockButton, - ]) - inStockStack.orientation = .vertical - - let isOnBackOrderLabel = NSTextField(labelWithString: "Is on back order?") - let isOnBackOrderSwitch = NSSwitch() - let isOnBackOrderStack = NSStackView(views: [ - isOnBackOrderLabel, - isOnBackOrderSwitch, - ]) - let backInStockButton = NSButton() - backInStockButton.addAction { [weak self] _ in + let backInStockButton = makeButton("Back in stock!") { [weak self] in self?.status = .inStock(quantity: 100) } - - backInStockButton.title = "Back in stock!" - let outOfStockStack = NSStackView(views: [ - isOnBackOrderStack, - backInStockButton, - ]) - outOfStockStack.orientation = .vertical - - let stack = NSStackView(views: [ - inStockStack, - outOfStockStack, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(stack) - - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) + let quantityLabel = makeValueLabel() + let quantityStepper = NSStepper() + quantityStepper.maxValue = .infinity + let quantityRow = FormRow("Quantity", accessories: [quantityLabel, quantityStepper]) + let isOnBackOrderSwitch = NSSwitch() + let isOnBackOrderRow = FormRow("On back order", accessories: [isOnBackOrderSwitch]) + + addForm( + [ + FormSection( + "Item", + footer: "The stepper and the switch bind into the cases of a single status enum.", + rows: [ + FormRow("Status", accessories: [statusLabel, outOfStockButton, backInStockButton]), + quantityRow, + isOnBackOrderRow, + ] + ), + ], + to: view + ) observe { [unowned self] in - inStockStack.isHidden = !status.is(\.inStock) - outOfStockStack.isHidden = !status.is(\.outOfStock) + let isInStock = status.is(\.inStock) + statusLabel.stringValue = isInStock ? "In stock" : "Out of stock" + outOfStockButton.isHidden = !isInStock + backInStockButton.isHidden = isInStock + quantityRow.isHidden = !isInStock + isOnBackOrderRow.isHidden = isInStock switch status { case .inStock: if let quantity = $status.inStock { - quantityLabel.stringValue = "Quantity: \(quantity.wrappedValue)" + quantityLabel.stringValue = quantity.wrappedValue.description quantityStepper.bind(value: quantity.asDouble) } diff --git a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift index 7aea5a1cfa..442161347e 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift @@ -42,16 +42,32 @@ private final class ErasedRootViewController: XiblessViewController { ErasedFeatureViewController(title: "Boolean \(value)") } - addColumn( - of: [ - makeButton("Push a number") { [weak self] in - self?.traitCollection.push(value: Int.random(in: 1...1_000)) - }, - makeButton("Push a number → a string → a Boolean") { [weak self] in - self?.traitCollection.push(value: Int.random(in: 1...1_000)) - self?.traitCollection.push(value: "Hello!") - self?.traitCollection.push(value: Bool.random()) - }, + addForm( + [ + FormSection( + "Push", + footer: "Each type of data on the path has a destination of its own.", + rows: [ + FormRow( + "A number", + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: Int.random(in: 1...1_000)) + }, + ] + ), + FormRow( + "A number, a string and a Boolean", + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: Int.random(in: 1...1_000)) + self?.traitCollection.push(value: "Hello!") + self?.traitCollection.push(value: Bool.random()) + }, + ] + ), + ] + ), ], to: view ) @@ -73,21 +89,49 @@ private final class ErasedFeatureViewController: XiblessViewController { override func viewDidLoad() { super.viewDidLoad() - addColumn( - of: [ - makeSectionLabel(title ?? ""), - makeButton("Push a number") { [weak self] in - self?.traitCollection.push(value: Int.random(in: 1...1_000)) - }, - makeButton("Push a string") { [weak self] in - self?.traitCollection.push(value: "Hello!") - }, - makeButton("Push a Boolean") { [weak self] in - self?.traitCollection.push(value: Bool.random()) - }, - makeButton("Dismiss") { [weak self] in - self?.traitCollection.dismiss() - }, + addForm( + [ + FormSection( + "Push", + rows: [ + FormRow( + "A number", + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: Int.random(in: 1...1_000)) + }, + ] + ), + FormRow( + "A string", + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: "Hello!") + }, + ] + ), + FormRow( + "A Boolean", + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: Bool.random()) + }, + ] + ), + ] + ), + FormSection( + rows: [ + FormRow( + "This screen", + accessories: [ + makeButton("Dismiss") { [weak self] in + self?.traitCollection.dismiss() + }, + ] + ), + ] + ), ], to: view ) diff --git a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift index a0b779a7fb..716c6a3032 100644 --- a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift @@ -15,98 +15,73 @@ class FocusViewController: XiblessViewController, AppKitCaseStudy { override func viewDidLoad() { super.viewDidLoad() - let bioTextField = NSTextField(text: $model.bio) - bioTextField.bind(focus: $model.focus, equals: .bio) - bioTextField.bezelStyle = .roundedBezel - bioTextField.placeholderString = "Bio" + let usernameTextField = NSTextField(text: $model.username) + usernameTextField.bind(focus: $model.focus, equals: .username) let emailTextField = NSTextField(text: $model.email) emailTextField.bind(focus: $model.focus, equals: .email) - emailTextField.bezelStyle = .roundedBezel - emailTextField.placeholderString = "Email" let passwordTextField = NSSecureTextField(text: $model.password) passwordTextField.bind(focus: $model.focus, equals: .password) - passwordTextField.bezelStyle = .roundedBezel - passwordTextField.placeholderString = "Password" - let usernameTextField = NSTextField(text: $model.username) - usernameTextField.bind(focus: $model.focus, equals: .username) - usernameTextField.bezelStyle = .roundedBezel - usernameTextField.placeholderString = "Username" - - let currentFocusLabel = NSTextField(labelWithString: "") - - let focusBioButton = NSButton() - focusBioButton.addAction { [weak self] _ in - self?.model.focus = .bio - } - - focusBioButton.title = "Focus bio" - let focusEmailButton = NSButton() - focusEmailButton.addAction { [weak self] _ in - self?.model.focus = .email - } - - focusEmailButton.title = "Focus email" - let focusPasswordButton = NSButton() - focusPasswordButton.addAction { [weak self] _ in - self?.model.focus = .password - } - - focusPasswordButton.title = "Focus password" - let focusUsernameButton = NSButton() - focusUsernameButton.addAction { [weak self] _ in - self?.model.focus = .username - } - - focusUsernameButton.title = "Focus username" - let resignFirstResponder = NSButton() - resignFirstResponder.addAction { [weak self] _ in - self?.view.window?.makeFirstResponder(nil) + let bioTextField = NSTextField(text: $model.bio) + bioTextField.bind(focus: $model.focus, equals: .bio) + for textField in [usernameTextField, emailTextField, passwordTextField, bioTextField] { + textField.bezelStyle = .roundedBezel + textField.widthAnchor.constraint(equalToConstant: 240).isActive = true } - - resignFirstResponder.title = "Resign first responder" - - let stack = NSStackView(views: [ - usernameTextField, - emailTextField, - passwordTextField, - bioTextField, - currentFocusLabel, - focusUsernameButton, - focusEmailButton, - focusPasswordButton, - focusBioButton, - resignFirstResponder, - ]) - stack.orientation = .vertical - stack.translatesAutoresizingMaskIntoConstraints = false - - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.topAnchor - .constraint(equalTo: view.safeAreaLayoutGuide.topAnchor), - stack.leadingAnchor - .constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 24), - stack.trailingAnchor - .constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor, constant: -24), - ]) + let fieldRows: [(FormRow, Model.Focus)] = [ + (FormRow("Username", accessories: [usernameTextField]), .username), + (FormRow("Email", accessories: [emailTextField]), .email), + (FormRow("Password", accessories: [passwordTextField]), .password), + (FormRow("Bio", accessories: [bioTextField]), .bio), + ] + let currentFocusLabel = makeValueLabel() + + addForm( + [ + FormSection( + "Account", + footer: "The title of the field that the model says has focus is tinted.", + rows: fieldRows.map(\.0) + ), + FormSection( + "Focus", + footer: "The model and the window keep the focus in step: click into a field, or move the focus from here.", + rows: [ + FormRow("Current focus", accessories: [currentFocusLabel]), + FormRow( + "Move the focus to", + accessories: [ + makeButton("Username") { [weak self] in + self?.model.focus = .username + }, + makeButton("Email") { [weak self] in + self?.model.focus = .email + }, + makeButton("Password") { [weak self] in + self?.model.focus = .password + }, + makeButton("Bio") { [weak self] in + self?.model.focus = .bio + }, + ] + ), + FormRow( + "Resign first responder", + accessories: [ + makeButton("Resign") { [weak self] in + self?.view.window?.makeFirstResponder(nil) + }, + ] + ), + ] + ), + ], + to: view + ) observe { [unowned self] in - currentFocusLabel.stringValue = "Current focus: \(model.focus?.rawValue ?? "none")" - bioTextField.backgroundColor = nil - emailTextField.backgroundColor = nil - passwordTextField.backgroundColor = nil - usernameTextField.backgroundColor = nil - switch model.focus { - case .bio: - bioTextField.backgroundColor = .lightGray - case .email: - emailTextField.backgroundColor = .lightGray - case .password: - passwordTextField.backgroundColor = .lightGray - case .username: - usernameTextField.backgroundColor = .lightGray - case .none: - break + currentFocusLabel.stringValue = model.focus?.rawValue.capitalized ?? "None" + for (row, focus) in fieldRows { + row.titleLabel.textColor = model.focus == focus ? .controlAccentColor : .labelColor } } } diff --git a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift index 0af34c6c56..ad48b4788d 100644 --- a/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift @@ -19,28 +19,38 @@ class MinimalObservationViewController: XiblessViewController, AppKitCas override func viewDidLoad() { super.viewDidLoad() - let countLabel = NSTextField(labelWithString: "") - let incrementButton = NSButton(title: "Increment", target: self, action: #selector(incrementButtonAction(_:))) - let isCountHiddenSwitch = NSSwitch(isOn: $model.isCountHidden) - let isCountHiddenLabel = NSTextField(labelWithString: "Is count hidden?") - let viewRenderLabel = NSTextField(labelWithString: "") - let stack = NSStackView(views: [ - countLabel, - incrementButton, - isCountHiddenLabel, - isCountHiddenSwitch, - viewRenderLabel, - ]) - stack.orientation = .vertical - stack.alignment = .centerX - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(stack) - NSLayoutConstraint.activate([ - stack.centerYAnchor.constraint(equalTo: view.safeAreaLayoutGuide.centerYAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - ]) + let countLabel = makeValueLabel() + let viewRenderLabel = makeValueLabel() + + addForm( + [ + FormSection( + "Counter", + footer: """ + Hide the count and increment again: the count keeps changing, but the view no \ + longer re-renders, because the 'observe' closure stops reading it. + """, + rows: [ + FormRow( + "Count", + accessories: [ + countLabel, + makeButton("Increment") { [weak self] in + self?.model.count += 1 + }, + ] + ), + FormRow("Hide the count", accessories: [NSSwitch(isOn: $model.isCountHidden)]), + ] + ), + FormSection( + "Rendering", + rows: [FormRow("Times the view rendered", accessories: [viewRenderLabel])] + ), + ], + to: view + ) + let viewRenderCount = LockIsolated(0) observe { [unowned self] in viewRenderCount.withValue { $0 += 1 } @@ -51,14 +61,10 @@ class MinimalObservationViewController: XiblessViewController, AppKitCas countLabel.stringValue = model.count.description } countLabel.isHidden = model.isCountHidden - viewRenderLabel.stringValue = "# of view renders: \(viewRenderCount.value)" + viewRenderLabel.stringValue = viewRenderCount.value.description } } - @objc func incrementButtonAction(_ sender: NSButton) { - model.count += 1 - } - @Observable class Model { var count = 0 diff --git a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift index 8eaa142251..d638404783 100644 --- a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift @@ -2,24 +2,7 @@ import AppKit import AppKitNavigation -class XiblessViewController: NSViewController { - lazy var contentView = View() - - override func loadView() { - view = contentView - } - - override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { - super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("") - } -} - -class NSControlBindingsViewController: XiblessViewController, AppKitCaseStudy { +class NSControlBindingsViewController: XiblessViewController, AppKitCaseStudy { let caseStudyTitle = "NSControl bindings" let readMe = """ This demonstrates how to use the library's `@UIBinding` and `@UIBindable` property wrappers \ @@ -31,51 +14,56 @@ class NSControlBindingsViewController: XiblessViewController, AppKitCaseS override func viewDidLoad() { super.viewDidLoad() - contentView.boxType = .custom - contentView.borderWidth = 0 + let colorWell = NSColorWell(color: $model.color) let datePicker = NSDatePicker(date: $model.date) let segmentControl = NSSegmentedControl(labels: Model.Segment.allCases.map { "\($0)" }, trackingMode: .selectOne, target: nil, action: nil) segmentControl.bind(selectedSegment: $model.segment) let slider = NSSlider(value: $model.sliderValue) + slider.widthAnchor.constraint(equalToConstant: 180).isActive = true + let stepperValueLabel = makeValueLabel() let stepper = NSStepper(value: $model.stepperValue) let `switch` = NSSwitch(isOn: $model.isOn) let textField = NSTextField(text: $model.text) textField.bind(focus: $model.focus, equals: .text) textField.bind(selection: $model.textSelection) textField.bezelStyle = .roundedBezel - let label = NSTextField(labelWithString: "") - label.maximumNumberOfLines = 0 - let stack = NSStackView(views: [ - colorWell, - datePicker, - segmentControl, - slider, - stepper, - `switch`, - textField, - label, - ]) - stack.orientation = .vertical - stack.spacing = 12 - stack.translatesAutoresizingMaskIntoConstraints = false - contentView.contentView?.addSubview(stack) - NSLayoutConstraint.activate([ - stack.topAnchor.constraint(equalTo: view.topAnchor), - stack.leadingAnchor.constraint(equalTo: view.leadingAnchor), - stack.trailingAnchor.constraint(equalTo: view.trailingAnchor), - stack.bottomAnchor.constraint(equalTo: view.bottomAnchor), - colorWell.heightAnchor.constraint(equalToConstant: 50), - ]) + textField.widthAnchor.constraint(equalToConstant: 200).isActive = true + let modelLabel = makeWrappingLabel() + modelLabel.font = .monospacedSystemFont(ofSize: NSFont.smallSystemFontSize, weight: .regular) + modelLabel.textColor = .secondaryLabelColor + + addForm( + [ + FormSection( + "Controls", + rows: [ + FormRow("Color well", accessories: [colorWell]), + FormRow("Date picker", accessories: [datePicker]), + FormRow("Segmented control", accessories: [segmentControl]), + FormRow("Slider", accessories: [slider]), + FormRow("Stepper", accessories: [stepperValueLabel, stepper]), + FormRow("Switch", accessories: [`switch`]), + FormRow("Text field", accessories: [textField]), + ] + ), + FormSection( + "Model", + footer: "Each control writes to the model through its binding, and the model writes back to the control.", + rows: [FormRow(content: modelLabel)] + ), + ], + to: view + ) observe { [unowned self] in - contentView.fillColor = model.color + stepperValueLabel.stringValue = model.stepperValue.formatted() let textSelection = model.textSelection.map { self.model.text.range(for: $0.range) } - label.stringValue = """ + modelLabel.stringValue = """ MyModel( color: \(model.color.description), date: \(model.date), @@ -94,7 +82,7 @@ class NSControlBindingsViewController: XiblessViewController, AppKitCaseS @MainActor @Observable final class Model: HashableObject { - var color: NSColor = .windowBackgroundColor + var color: NSColor = .systemBlue var date = Date() var focus: Focus? var isOn = false diff --git a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift index b67f112171..32369eb6e7 100644 --- a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift @@ -18,18 +18,37 @@ class NestedModalViewController: XiblessViewController, AppKitCaseStudy override func viewDidLoad() { super.viewDidLoad() - let openButton = makeButton("Open the settings") { [weak self] in - self?.model.isSettingsPresented = true - } - let statusLabel = NSTextField(wrappingLabelWithString: "") - addColumn(of: [openButton, statusLabel], to: view) + let settingsWindowLabel = makeValueLabel() + let confirmationAlertLabel = makeValueLabel() + let resetCountLabel = makeValueLabel() + + addForm( + [ + FormSection( + "Modals", + footer: "Try “Close in 3 seconds” and then “Reset…”: the window waits for the alert to end before it closes.", + rows: [ + FormRow( + "Settings window", + accessories: [ + settingsWindowLabel, + makeButton("Open") { [weak self] in + self?.model.isSettingsPresented = true + }, + ] + ), + FormRow("Confirmation alert", accessories: [confirmationAlertLabel]), + FormRow("Resets", accessories: [resetCountLabel]), + ] + ), + ], + to: view + ) observe { [unowned self] in - statusLabel.stringValue = """ - Settings window: \(model.isSettingsPresented ? "open" : "closed") - Confirmation alert: \(model.resetConfirmation != nil ? "open" : "closed") - Resets: \(model.resetCount) - """ + settingsWindowLabel.stringValue = model.isSettingsPresented ? "Open" : "Closed" + confirmationAlertLabel.stringValue = model.resetConfirmation != nil ? "Open" : "Closed" + resetCountLabel.stringValue = model.resetCount.description } modal(isPresented: $model.isSettingsPresented) { [unowned self] in diff --git a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift index f978f50a93..1d964eec2a 100644 --- a/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift @@ -37,11 +37,7 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu tabViewController.bind(selection: $model.fruit, options: Fruit.allCases) addChild(tabViewController) let tabView = tabViewController.view - tabView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - tabView.widthAnchor.constraint(equalToConstant: 320), - tabView.heightAnchor.constraint(equalToConstant: 110), - ]) + tabView.heightAnchor.constraint(equalToConstant: 110).isActive = true let styleControl = NSSegmentedControl( labels: ["Bold", "Italic", "Underline"], trackingMode: .selectAny, target: nil, action: nil @@ -66,52 +62,76 @@ class OptionBindingsViewController: XiblessViewController, AppKitCaseStu tagPopUpButton.menu?.addItem(newTagItem) let noteScrollView = NSTextView.scrollableTextView() - noteScrollView.borderType = .bezelBorder - noteScrollView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - noteScrollView.widthAnchor.constraint(equalToConstant: 320), - noteScrollView.heightAnchor.constraint(equalToConstant: 60), - ]) + noteScrollView.borderType = .noBorder + noteScrollView.wantsLayer = true + noteScrollView.layer?.cornerRadius = 6 + noteScrollView.layer?.masksToBounds = true + noteScrollView.heightAnchor.constraint(equalToConstant: 80).isActive = true if let noteTextView = noteScrollView.documentView as? NSTextView { noteTextView.isRichText = false + noteTextView.textContainerInset = NSSize(width: 4, height: 6) noteTextView.bind(text: $model.note) } - let statusLabel = NSTextField(wrappingLabelWithString: "") - statusLabel.textColor = .secondaryLabelColor - - addColumn( - of: [ - makeSectionLabel("One of several options"), - popUpButton, - segmentedControl, - tabView, - makeSectionLabel("A Bool for each segment"), - styleControl, - makeSectionLabel("A menu item's checkmark"), - viewOptionsButton, - makeSectionLabel("Options that change"), - tagPopUpButton, - makeSectionLabel("A text view's text"), - noteScrollView, - statusLabel, + let fruitLabel = makeValueLabel() + let styleLabel = makeValueLabel() + let gridLabel = makeValueLabel() + let tagLabel = makeValueLabel() + let noteLabel = makeValueLabel() + + addForm( + [ + FormSection( + "One of several options", + footer: "The pop-up button, the segmented control and the tabs follow the same fruit.", + rows: [ + FormRow("Pop-up button", accessories: [popUpButton]), + FormRow("Segmented control", accessories: [segmentedControl]), + FormRow(content: tabView), + ] + ), + FormSection( + "A Bool for each segment", + rows: [FormRow("Style", accessories: [styleControl])] + ), + FormSection( + "A menu item's checkmark", + rows: [FormRow("Grid", accessories: [viewOptionsButton])] + ), + FormSection( + "Options that change", + footer: "New Tag… adds a tag to the model, and the pop-up grows an item for it.", + rows: [FormRow("Tag", accessories: [tagPopUpButton])] + ), + FormSection( + "A text view's text", + rows: [FormRow(content: noteScrollView)] + ), + FormSection( + "Model", + rows: [ + FormRow("Fruit", accessories: [fruitLabel]), + FormRow("Style", accessories: [styleLabel]), + FormRow("Grid", accessories: [gridLabel]), + FormRow("Tag", accessories: [tagLabel]), + FormRow("Note", accessories: [noteLabel]), + ] + ), ], to: view ) observe { [unowned self] in let styles = [ - model.isBold ? "bold" : nil, - model.isItalic ? "italic" : nil, - model.isUnderlined ? "underlined" : nil, + model.isBold ? "Bold" : nil, + model.isItalic ? "Italic" : nil, + model.isUnderlined ? "Underlined" : nil, ].compactMap(\.self) - statusLabel.stringValue = """ - Fruit: \(model.fruit.title) - Style: \(styles.isEmpty ? "plain" : styles.joined(separator: ", ")) - Grid: \(model.showsGrid ? "shown" : "hidden") - Tag: \(model.tag ?? "none") - Note: \(model.note.count) characters - """ + fruitLabel.stringValue = model.fruit.title + styleLabel.stringValue = styles.isEmpty ? "Plain" : styles.joined(separator: ", ") + gridLabel.stringValue = model.showsGrid ? "Shown" : "Hidden" + tagLabel.stringValue = model.tag ?? "None" + noteLabel.stringValue = "\(model.note.count) characters" } } diff --git a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift index 995d32ed74..a62058ce0f 100644 --- a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift @@ -22,48 +22,87 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa override func viewDidLoad() { super.viewDidLoad() - let modalWindowButton = makeButton("Run a window modally") { [weak self] in - self?.model.isModalWindowPresented = true - } - let modalAlertButton = makeButton("Run an alert modally") { [weak self] in - self?.model.modalAlert = .discardChanges - } - let modalSessionButton = makeButton("Show a window in a modal session") { [weak self] in - self?.model.isModalSessionPresented = true - } - let popoverButton = makeButton("Show a popover from this button") { [weak self] in + let popoverButton = makeButton("Show") { [weak self] in self?.model.isPopoverPresented = true } - let viewControllerSheetButton = makeButton("Present as a sheet") { [weak self] in - self?.model.isViewControllerSheetPresented = true - } - let viewControllerWindowButton = makeButton("Present in a modal window") { [weak self] in - self?.model.isViewControllerWindowPresented = true - } - let viewControllerPopoverButton = makeButton("Present in a popover") { [weak self] in + let viewControllerPopoverButton = makeButton("Present") { [weak self] in self?.model.isViewControllerPopoverPresented = true } - let documentWindowButton = makeButton("Open a document window") { [weak self] in - self?.openDocumentWindow() - } - let logLabel = NSTextField(wrappingLabelWithString: "") + let logLabel = makeWrappingLabel() logLabel.textColor = .secondaryLabelColor - addColumn( - of: [ - makeSectionLabel("Windows, alerts and panels"), - modalWindowButton, - modalAlertButton, - modalSessionButton, - documentWindowButton, - makeSectionLabel("Popovers"), - popoverButton, - makeSectionLabel("View controllers"), - viewControllerSheetButton, - viewControllerWindowButton, - viewControllerPopoverButton, - makeSectionLabel("onDismiss log"), - logLabel, + addForm( + [ + FormSection( + "Windows, alerts and panels", + rows: [ + FormRow( + "Modal window", + accessories: [ + makeButton("Run") { [weak self] in + self?.model.isModalWindowPresented = true + }, + ] + ), + FormRow( + "Modal alert", + accessories: [ + makeButton("Run") { [weak self] in + self?.model.modalAlert = .discardChanges + }, + ] + ), + FormRow( + "Modal session", + subtitle: "Takes the app's input without blocking", + accessories: [ + makeButton("Show") { [weak self] in + self?.model.isModalSessionPresented = true + }, + ] + ), + FormRow( + "Document window", + subtitle: "Sheets and a toolbar popover attach to it", + accessories: [ + makeButton("Open") { [weak self] in + self?.openDocumentWindow() + }, + ] + ), + ] + ), + FormSection( + "Popovers", + rows: [FormRow("From a button", accessories: [popoverButton])] + ), + FormSection( + "View controllers", + rows: [ + FormRow( + "As a sheet", + accessories: [ + makeButton("Present") { [weak self] in + self?.model.isViewControllerSheetPresented = true + }, + ] + ), + FormRow( + "In a modal window", + accessories: [ + makeButton("Present") { [weak self] in + self?.model.isViewControllerWindowPresented = true + }, + ] + ), + FormRow("In a popover", accessories: [viewControllerPopoverButton]), + ] + ), + FormSection( + "onDismiss log", + footer: "'onDismiss' runs once the content has left the screen, however it was dismissed.", + rows: [FormRow(content: logLabel)] + ), ], to: view ) diff --git a/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift index be6dd8ffc1..ad5b97deb6 100644 --- a/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift @@ -64,24 +64,41 @@ private final class StaticRootViewController: XiblessViewController { override func viewDidLoad() { super.viewDidLoad() - let pathLabel = NSTextField(wrappingLabelWithString: "") - pathLabel.textColor = .secondaryLabelColor - var views: [NSView] = StaticNavigationStackController.Model.Path.allCases.map { feature in - makeButton("Push \(feature.title.lowercased())") { [weak self] in - self?.traitCollection.push(value: feature) - } + let pathLabel = makeValueLabel() + let featureRows = StaticNavigationStackController.Model.Path.allCases.map { feature in + FormRow( + feature.title, + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: feature) + }, + ] + ) } - views.append( - makeButton("Push feature 1 → 2 → 3") { [weak self] in - self?.model.path.append(contentsOf: [.feature1, .feature2, .feature3]) - } + let allFeaturesRow = FormRow( + "All three", + subtitle: "Feature 1 → 2 → 3", + accessories: [ + makeButton("Push") { [weak self] in + self?.model.path.append(contentsOf: [.feature1, .feature2, .feature3]) + }, + ] + ) + + addForm( + [ + FormSection("Push", rows: featureRows + [allFeaturesRow]), + FormSection( + "Model", + footer: "Going back with the back button, ⌘↑ or a swipe shortens the path too.", + rows: [FormRow("Path", accessories: [pathLabel])] + ), + ], + to: view ) - views.append(pathLabel) - addColumn(of: views, to: view) observe { [unowned self] in - pathLabel.stringValue = - "Path: \(model.path.isEmpty ? "empty" : model.path.map(\.title).joined(separator: " → "))" + pathLabel.stringValue = model.path.isEmpty ? "Empty" : model.path.map(\.title).joined(separator: " → ") } } } @@ -104,18 +121,35 @@ private final class StaticFeatureViewController: XiblessViewController { override func viewDidLoad() { super.viewDidLoad() - var views: [NSView] = [makeSectionLabel(feature.title)] - views += StaticNavigationStackController.Model.Path.allCases.map { feature in - makeButton("Push \(feature.title.lowercased())") { [weak self] in - self?.traitCollection.push(value: feature) - } + let featureRows = StaticNavigationStackController.Model.Path.allCases.map { feature in + FormRow( + feature.title, + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: feature) + }, + ] + ) } - views.append( - makeButton("Dismiss") { [weak self] in - self?.traitCollection.dismiss() - } + + addForm( + [ + FormSection("Push", rows: featureRows), + FormSection( + rows: [ + FormRow( + "This screen", + accessories: [ + makeButton("Dismiss") { [weak self] in + self?.traitCollection.dismiss() + }, + ] + ), + ] + ), + ], + to: view ) - addColumn(of: views, to: view) } } diff --git a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift index 3814f1aa1c..be02308fc6 100644 --- a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift @@ -95,75 +95,113 @@ class TableSelectionViewController: XiblessViewController, AppKitCaseStu collectionDataSource.apply(colorSnapshot, animatingDifferences: false) self.collectionDataSource = collectionDataSource collectionView.bind(selection: $model.selectedColors, dataSource: collectionDataSource) + collectionView.backgroundColors = [.clear] let collectionScrollView = NSScrollView() collectionScrollView.documentView = collectionView - collectionScrollView.borderType = .bezelBorder - collectionScrollView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - collectionScrollView.widthAnchor.constraint(equalToConstant: 260), - collectionScrollView.heightAnchor.constraint(equalToConstant: 80), - ]) + collectionScrollView.drawsBackground = false + collectionScrollView.heightAnchor.constraint(equalToConstant: 64).isActive = true - let statusLabel = NSTextField(wrappingLabelWithString: "") - statusLabel.textColor = .secondaryLabelColor + let planetLabel = makeValueLabel() + let pantryItemLabel = makeValueLabel() + let expandedGroupsLabel = makeValueLabel() + let colorsLabel = makeValueLabel() - addColumn( - of: [ - makeSectionLabel("Table"), - Self.scrollView(containing: tableView), - makeButton("Select Mars") { [weak self] in - self?.model.selectedPlanet = "Mars" - }, - makeButton("Clear the table's selection") { [weak self] in - self?.model.selectedPlanet = nil - }, - makeSectionLabel("Outline"), - Self.scrollView(containing: outlineView), - makeButton("Select Cherries") { [weak self] in - // NB: Expanded too, since a row only exists while its group is expanded. - self?.model.expandedPantryGroups.insert("Fruit") - self?.model.selectedPantryItem = "Cherries" - }, - makeButton("Expand everything") { [weak self] in - self?.model.expandedPantryGroups = Set(PantryOutlineDataSource.groupNames) - }, - makeButton("Collapse everything") { [weak self] in - self?.model.expandedPantryGroups = [] - }, - makeSectionLabel("Collection"), - collectionScrollView, - makeButton("Select the warm colors") { [weak self] in - self?.model.selectedColors = ["Red", "Orange", "Yellow"] - }, - makeButton("Clear the colors' selection") { [weak self] in - self?.model.selectedColors = [] - }, - statusLabel, + addForm( + [ + FormSection( + "Table", + footer: "The table binds its selected row to the name of the planet in it.", + rows: [ + FormRow(content: Self.scrollView(containing: tableView, height: 150), insets: NSEdgeInsets(top: 6, left: 0, bottom: 6, right: 0)), + FormRow( + "Selection", + accessories: [ + planetLabel, + makeButton("Select Mars") { [weak self] in + self?.model.selectedPlanet = "Mars" + }, + makeButton("Clear") { [weak self] in + self?.model.selectedPlanet = nil + }, + ] + ), + ] + ), + FormSection( + "Outline", + footer: "The outline binds its selected row to the name of the item in it, and the groups it has expanded to a set of names.", + rows: [ + FormRow(content: Self.scrollView(containing: outlineView, height: 170), insets: NSEdgeInsets(top: 6, left: 0, bottom: 6, right: 0)), + FormRow( + "Selection", + accessories: [ + pantryItemLabel, + makeButton("Select Cherries") { [weak self] in + // NB: Expanded too, since a row only exists while its group is expanded. + self?.model.expandedPantryGroups.insert("Fruit") + self?.model.selectedPantryItem = "Cherries" + }, + ] + ), + FormRow( + "Expanded groups", + accessories: [ + expandedGroupsLabel, + makeButton("Expand All") { [weak self] in + self?.model.expandedPantryGroups = Set(PantryOutlineDataSource.groupNames) + }, + makeButton("Collapse All") { [weak self] in + self?.model.expandedPantryGroups = [] + }, + ] + ), + ] + ), + FormSection( + "Collection", + footer: "Click, ⌘-click, drag across the colors or choose Select All, and the model follows.", + rows: [ + FormRow(content: collectionScrollView), + FormRow( + "Selection", + accessories: [ + colorsLabel, + makeButton("Select the warm colors") { [weak self] in + self?.model.selectedColors = ["Red", "Orange", "Yellow"] + }, + makeButton("Clear") { [weak self] in + self?.model.selectedColors = [] + }, + ] + ), + ] + ), ], to: view ) observe { [unowned self] in - statusLabel.stringValue = """ - Table selection: \(model.selectedPlanet ?? "none") - Outline selection: \(model.selectedPantryItem ?? "none") - Expanded groups: \(model.expandedPantryGroups.isEmpty ? "none" : model.expandedPantryGroups.sorted().joined(separator: ", ")) - Selected colors: \(model.selectedColors.isEmpty ? "none" : ColorItem.colorNames.filter(model.selectedColors.contains).joined(separator: ", ")) - """ + planetLabel.stringValue = model.selectedPlanet ?? "None" + pantryItemLabel.stringValue = model.selectedPantryItem ?? "None" + expandedGroupsLabel.stringValue = + model.expandedPantryGroups.isEmpty ? "None" : model.expandedPantryGroups.sorted().joined(separator: ", ") + colorsLabel.stringValue = + model.selectedColors.isEmpty + ? "None" : ColorItem.colorNames.filter(model.selectedColors.contains).joined(separator: ", ") } } - private static func scrollView(containing tableView: NSTableView) -> NSScrollView { + /// A scroll view, as tall as `height`, showing `tableView` without a header. + private static func scrollView(containing tableView: NSTableView, height: CGFloat) -> NSScrollView { tableView.headerView = nil + tableView.style = .inset + tableView.backgroundColor = .clear let scrollView = NSScrollView() scrollView.documentView = tableView scrollView.hasVerticalScroller = true - scrollView.borderType = .bezelBorder - scrollView.translatesAutoresizingMaskIntoConstraints = false - NSLayoutConstraint.activate([ - scrollView.widthAnchor.constraint(equalToConstant: 260), - scrollView.heightAnchor.constraint(equalToConstant: 120), - ]) + scrollView.autohidesScrollers = true + scrollView.drawsBackground = false + scrollView.heightAnchor.constraint(equalToConstant: height).isActive = true return scrollView } diff --git a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift index 376df845f2..545bdb5df0 100644 --- a/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/AppKit+ConnectToNetworkViewController.swift @@ -65,6 +65,7 @@ final class ConnectToNetworkViewController: XiblessViewController { model.cancelButtonTapped() } cancelButton.title = "Cancel" + cancelButton.keyEquivalent = "\u{1b}" let joinButton = NSButton() joinButton.addAction { [weak self] _ in @@ -74,6 +75,7 @@ final class ConnectToNetworkViewController: XiblessViewController { } } joinButton.title = "Join" + joinButton.keyEquivalent = "\r" let progress = NSProgressIndicator() progress.isIndeterminate = true diff --git a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift index 1e6ca6e18a..a36c95b0b5 100644 --- a/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift @@ -14,29 +14,31 @@ final class NetworkDetailViewController: XiblessViewController { override func viewDidLoad() { super.viewDidLoad() -// navigationItem.title = model.network.name - - let forgetButton = NSButton() - forgetButton.addAction { [weak self] _ in - guard let self else { return } - model.forgetNetworkButtonTapped() + let forgetButton = makeButton("Forget This Network…") { [weak self] in + self?.model.forgetNetworkButtonTapped() } - - forgetButton.title = "Forget network" -// forgetButton.hasDestructiveAction = true - forgetButton.translatesAutoresizingMaskIntoConstraints = false - view.addSubview(forgetButton) + let doneButton = makeButton("Done") { [weak self] in + self?.dismiss(nil) + } + doneButton.keyEquivalent = "\r" + let isConnected = model.network.id == model.selectedNetworkID + let content = makeMessageView( + title: model.network.name, + message: """ + \(isConnected ? "Your Mac is connected to this network." : "Your Mac is not connected to this network.") \ + \(model.network.isSecured ? "It is secured with a password." : "It is an open network.") + """, + buttons: [forgetButton, doneButton] + ) + content.translatesAutoresizingMaskIntoConstraints = false + view.addSubview(content) NSLayoutConstraint.activate([ - forgetButton.centerXAnchor.constraint(equalTo: view.centerXAnchor), - forgetButton.centerYAnchor.constraint(equalTo: view.centerYAnchor), + content.topAnchor.constraint(equalTo: view.topAnchor), + content.leadingAnchor.constraint(equalTo: view.leadingAnchor), + content.trailingAnchor.constraint(equalTo: view.trailingAnchor), + content.bottomAnchor.constraint(equalTo: view.bottomAnchor), ]) - observe { [weak self] in - guard let self else { return } - -// forgetButton.isHidden = model.network.id != model.selectedNetworkID - } - modal(isPresented: $model.forgetAlertIsPresented) { [unowned self] in let alert = NSAlert() alert.messageText = "Forget Wi-Fi Network “\(model.network.name)”?" @@ -53,6 +55,11 @@ final class NetworkDetailViewController: XiblessViewController { return alert } } + + /// Escape in the sheet, which AppKit asks the sheet's delegate for: this view controller. + @objc func cancel(_ sender: Any?) { + dismiss(nil) + } } #Preview { diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift index 6539d5deff..cac403b1ed 100644 --- a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -27,21 +27,28 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas override func viewDidLoad() { super.viewDidLoad() collectionView.autoresizingMask = [.width, .height] + collectionView.backgroundColors = [.clear] + contentView.drawsBackground = false contentView.documentView = collectionView let collectionViewLayout = NSCollectionViewCompositionalLayout { sectionIndex, layoutEnvironment -> NSCollectionLayoutSection? in // Item - let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(sectionIndex == 0 ? 60 : 44)) + let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(sectionIndex == 0 ? 52 : 44)) let item = NSCollectionLayoutItem(layoutSize: itemSize) - item.contentInsets = .init(top: 0, leading: sectionIndex == 0 ? 10 : 30, bottom: 0, trailing: 10) + item.contentInsets = .init(top: 0, leading: 12, bottom: 0, trailing: 12) // Group - let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(sectionIndex == 0 ? 60 : 44)) + let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(sectionIndex == 0 ? 52 : 44)) let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item]) // Section + // NB: Inset to the same centered column, no wider than 640 points, that the other case + // studies' forms use. + let containerWidth = layoutEnvironment.container.effectiveContentSize.width + let sideInset = max(24, (containerWidth - 640) / 2) + let topInset: CGFloat = sectionIndex == 0 ? 20 : 0 let section = NSCollectionLayoutSection(group: group) - section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 10, bottom: 0, trailing: 10) + section.contentInsets = NSDirectionalEdgeInsets(top: topInset, leading: sideInset, bottom: 0, trailing: sideInset) let decorationItem = NSCollectionLayoutDecorationItem.background(elementKind: NSCollectionView.DecorationElementKind.background) - decorationItem.contentInsets = .init(top: 0, leading: 10, bottom: 0, trailing: 10) + decorationItem.contentInsets = .init(top: topInset, leading: sideInset, bottom: 0, trailing: sideInset) section.decorationItems = [decorationItem] return section } @@ -104,9 +111,7 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas } present(item: $model.destination.detail, style: .sheet) { model in - let vc = NetworkDetailViewController(model: model) - vc.preferredContentSize = .init(width: 300, height: 200) - return vc + NetworkDetailViewController(model: model) } } } @@ -156,6 +161,12 @@ class WiFiSettingsSectionBackgroundView: NSBox, NSCollectionViewElement { func commonInit() { titlePosition = .noTitle + // NB: The same rounded box as the sections of the other case studies' forms. + boxType = .custom + fillColor = .quaternarySystemFill + borderColor = .separatorColor + borderWidth = 0.5 + cornerRadius = 10 } } @@ -216,7 +227,7 @@ class WiFiSettingsConnectedNetworkViewItem: XiblessCollectionViewItem { let statusButton = NSButton() let securedIconImageView = NSImageView(systemSymbolName: "lock.fill") let wifiIconImageView = NSImageView(systemSymbolName: "wifi") - let detailButton = NSButton(title: "Detail...", target: nil, action: nil) + let detailButton = NSButton(title: "Details…", target: nil, action: nil) override init(nibName nibNameOrNil: NSNib.Name?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) let stackView = NSStackView() From 6644bd5dfc866c1b9ad8086ff5243ca7afe2da3f Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 22:00:44 +0800 Subject: [PATCH 131/141] docs(examples): give the macOS case studies a sidebar and show every presentation's state On the Mac the case studies still lived in the drill-down list the iOS app uses: Case studies, then AppKit, then the page, with a back button in between. The AppKit pages had also lost the presentation state the old ones wrote into their button titles; only a few rows showed it, as grey text. The Mac app now opens a split view. Its sidebar lists every SwiftUI and AppKit case study, grouped as before and each with a symbol, and the chosen one shows beside it. The read-me moves from an About sheet to a popover behind the toolbar's info button, and the SwiftUI forms use the grouped style the AppKit pages use. iOS keeps the existing list. Every AppKit row that presents something now shows whether it is presented, and what, with a green check or a grey cross. The type-erased stack shows how many values its path holds, and the Wi-Fi settings show where they navigate to above the list. --- Documentations/Evolutions/README.md | 2 +- .../draft-appkit-examples-redesign.md | 35 +++- Documentations/README.md | 2 +- ...ppKit+BasicsNavigationViewController.swift | 18 +- .../AppKit/AppKit+CaseStudySupport.swift | 44 +++++ ...+ConciseEnumNavigationViewController.swift | 21 ++- .../AppKit+DismissalViewController.swift | 14 +- ...pKit+ErasedNavigationStackController.swift | 28 ++- .../AppKit+NestedModalViewController.swift | 12 +- ...it+PresentationGalleryViewController.swift | 47 ++++- .../AppKit/AppKitCaseStudies.swift | 107 +++++++----- Examples/CaseStudies/CaseStudiesApp.swift | 7 + Examples/CaseStudies/Internal/CaseStudy.swift | 37 ---- Examples/CaseStudies/RootView.swift | 5 - Examples/CaseStudies/SidebarRootView.swift | 162 ++++++++++++++++++ .../AppKit+WiFiSettingsViewController.swift | 74 ++++++++ Examples/Examples.xcodeproj/project.pbxproj | 4 + 17 files changed, 494 insertions(+), 125 deletions(-) create mode 100644 Examples/CaseStudies/SidebarRootView.swift diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 662a58b924..5a107e07d4 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -18,4 +18,4 @@ | 0010 | [AppKit 动画案例](0010-appkit-animations-case-study.md) | Implemented | | 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | | draft | [去掉 AppKitNavigationShim:不再交换系统方法](draft-appkit-remove-shim.md) | In Progress | -| draft | [AppKit 案例改用系统设置式的分组排版](draft-appkit-examples-redesign.md) | In Progress | +| draft | [macOS 示例改用侧边栏外壳与系统设置式排版](draft-appkit-examples-redesign.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-examples-redesign.md b/Documentations/Evolutions/draft-appkit-examples-redesign.md index fb10ab26e5..f10d977dc3 100644 --- a/Documentations/Evolutions/draft-appkit-examples-redesign.md +++ b/Documentations/Evolutions/draft-appkit-examples-redesign.md @@ -1,4 +1,4 @@ -# Draft - AppKit 案例改用系统设置式的分组排版 +# Draft - macOS 示例改用侧边栏外壳与系统设置式排版 - **状态**: In Progress - **创建日期**: 2026-11-14 @@ -7,15 +7,23 @@ ## 摘要 -AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按钮堆在窗口正中,状态用 ✅/❌ 写进按钮标题;较新的页面从左上角往下排,每节一个粗体标题,能用但简陋。Basics 页里由布尔值弹出的 sheet 只有一行「Hello!」,没有任何按钮,弹出来就关不掉;Wi-Fi 案例的网络详情 sheet 也一样,在「忘记网络」的确认框里取消之后就没有出口。这一批把全部 AppKit 案例(15 个案例页,加上 Wi-Fi 案例的 3 个页面)改成「系统设置」那样的分组排版,并让每个弹出的 sheet 都能关掉。 +AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按钮堆在窗口正中,状态用 ✅/❌ 写进按钮标题;较新的页面从左上角往下排,每节一个粗体标题,能用但简陋。Basics 页里由布尔值弹出的 sheet 只有一行「Hello!」,没有任何按钮,弹出来就关不掉;Wi-Fi 案例的网络详情 sheet 也一样,在「忘记网络」的确认框里取消之后就没有出口。 + +第一轮把全部 AppKit 案例(15 个案例页,加上 Wi-Fi 案例的 3 个页面)改成「系统设置」那样的分组排版,并让每个弹出的 sheet 都能关掉。看过之后,整个示例的外壳仍是从 iOS 沿用的逐层进入的列表(Case studies → AppKit → 页面,换页要先返回),不像现代的 Mac App;旧版写在按钮标题里的弹出状态,也只剩部分行有一段灰色文字。第二轮把 macOS 上的外壳换成侧边栏加详情,并在每个会弹出或跳转的行上标出当前的导航状态。 ## 方案 -- **共享排版**放进已有的 `AppKit+CaseStudySupport.swift`,不新建源文件,也就不用改 `Examples.xcodeproj`: +- **外壳**(只改 macOS,iOS 保持上游原样): + - 新文件 `SidebarRootView.swift`:`NavigationSplitView` 的侧边栏按「框架 · 主题」分组列出全部 SwiftUI 与 AppKit 案例,每个带一个 SF Symbol 图标;详情区显示选中的案例,标题下用副标题注明是 SwiftUI 还是 AppKit。 + - 案例说明从「About 按钮 + 带 Close 的 sheet」改成工具栏 ⓘ 按钮弹出的 popover。 + - 详情区包一层 `NavigationStack`,SwiftUI 案例里的下钻照常推入。 + - SwiftUI 案例在 macOS 上的表单用分组样式,与 AppKit 案例一致。 +- **共享排版**放在已有的 `AppKit+CaseStudySupport.swift`: - 页面:一列分组,放在可以滚动的区域里,靠上、水平居中,有最大宽度。 - 分组:上方一行粗体标题,中间一个圆角框装着若干行,行与行之间画分隔线,下方可以有一段说明。 - - 行:左边是名称,右边是状态文字和控件;表格、画布、日志这类内容占满整行。 -- **每页只换排版**,演示的 API 和行为不变。状态改成行里的文字,不再写进按钮标题。 + - 行:左边是名称,右边是状态和控件;表格、画布、日志这类内容占满整行。 + - 导航状态标记 `PresentationStateView`:绿色对勾加「Presented」,有值时带上值(「Presented: 42」);没弹出时是灰色叉号加「Not presented」。 +- **每页只换排版和状态显示**,演示的 API 和行为不变。所有会弹出内容的行都带状态标记;栈导航的状态是路径,显示在「Path」一行。 - **sheet 都能关掉**:弹出的内容都有 Done 按钮,回车可以触发;按 Esc 也能关,做法见决策日志。 落地步骤(每步各自编译通过): @@ -23,12 +31,23 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 1. 共享排版;Basics 与 Wi-Fi 网络详情的 sheet 加上关闭的办法。(已完成) 2. 其余页面逐页换成分组排版。(已完成) 3. 编译 CaseStudies 的 macOS 版,启动 App 逐页截图检查,修排版问题。(已完成) +4. macOS 外壳换成侧边栏加详情,说明改到工具栏 ⓘ,SwiftUI 案例用分组样式。(已完成) +5. 全部 AppKit 案例的弹出行加上状态标记,类型擦除路径页加上「Path」一行,Wi-Fi 页加上「Destination」一行。(已完成) +6. 重新编译,启动 App 截图检查外壳和各页的状态标记。(已完成) 没有询问就采用的假设: - 分组标题照「系统设置」用粗体,不用选样式时预览里的全大写。 - 共享排版只用 AppKit,不用 AppKitPlus:多数案例只依赖 AppKitNavigation,读者在页面代码里看到的应当只有这个库的用法。 -- 工具栏上的「About」按钮和各案例的说明文字保持原样。 +- 各案例的说明文字保持原样,只是改由 ⓘ 弹出。 +- 侧边栏的分组沿用原来两个列表的分组和顺序,SwiftUI 在前、AppKit 在后,分组名前加框架名区分;启动时不预先选中任何案例,详情区提示先在侧边栏里选,每个窗口记住自己上次选的案例。 +- 每个窗口为每个 AppKit 案例只创建一次视图控制器,切到别的案例再切回来,页面保留原来的状态;SwiftUI 案例切回来是新的一页。 +- macOS 侧边栏里的 SwiftUI 案例清单与 `SwiftUICaseStudiesView` 的清单各写一份:iOS 上仍用后者。以后合并上游新增的 SwiftUI 案例,两处都要加。 +- `RootView` 去掉 AppKit 入口,`CaseStudy.swift` 里只给旧 AppKit 列表用的按钮和 result builder 分支一并删掉;iOS 的外壳与 UIKit 案例不动。 +- 状态标记的文字与界面其余部分一样用英文。 +- Presentation styles 页的文档窗口里那几个 sheet 和工具栏 popover,按钮在文档窗口里,主页面单列一组只显示它们的状态。 +- 类型擦除路径 `UINavigationPath` 只公开元素个数,所以那一页的「Path」只显示有几个值。 +- Wi-Fi 设置页的行是网络列表,不适合逐行加标记,改在列表顶部加一行「Destination」,显示正在连接或查看详情的是哪个网络。 - NSControl bindings 页原先把模型里的颜色涂满整页背景,改为只由颜色井显示:整页背景会盖掉分组框的层次。默认颜色从窗口背景色改成系统蓝,否则颜色井看起来是空的。 - Focus 页原先把有焦点的文本框涂成浅灰,深色模式下很刺眼,改成把那一行的名称染成强调色。 - Basics 页的 sheet 内容从 SwiftUI 改用案例共用的 AppKit 视图控制器,与其他页面的 sheet 一致;它的 Done 按钮清空状态,演示由状态关闭。Basics 模型里装打开面板提示语的属性从 `alert` 改名为 `openPanelMessage`,那里弹的早就不是 alert。 @@ -45,3 +64,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 | 2026-11-14 | 分组、行和整页改用约束排列,不用 `NSStackView` 的 `.width` 对齐 | 第一次截图时整列都靠右、行内名称被挤到右边:`NSStackView` 的 `.width` 对齐并不会把子视图撑满宽度。改成自己用约束一个接一个地排,隐藏的行不占位置,分隔线跟着重画 | | 2026-11-14 | Esc 关 sheet 由被弹出的视图控制器实现 `cancel(_:)` | 逆向 macOS 27.2 的 AppKit 得知:视图控制器弹出的 sheet 按 Esc 默认只会响一声;弹出时被呈现的视图控制器成为 sheet 窗口的 delegate,窗口处理 Esc 时先问 delegate 有没有 `cancel:`。这条路走的仍是正常的关闭流程。截图检查时示例 App 不在前台,后台发送的 Esc 送不到,还没在运行中验证 | | 2026-11-14 | 实现完成,待用户看过后收尾 | `CaseStudies` 的 macOS 版编译通过,改动的文件没有警告。启动 App 逐页截图检查了 15 个案例页和 Wi-Fi 设置页,并点开 Basics 与 Dismissal 的 sheet、用 Done 关掉;Wi-Fi 网络详情的 sheet 要靠鼠标悬停才出现的按钮打开,没截到。文档判断:案例本身就是示例文档,不需要另写使用指南或实现说明,没有新术语 | +| 2026-11-14 | 范围扩大到整个 macOS 示例:外壳换成侧边栏加详情,导航状态逐行标出 | 用户看过第一轮后,认为整个示例的外观仍不够现代,并要求找回旧版那样的弹出状态显示。用户选定侧边栏加详情、每行标状态、只改 macOS,并同意再次截图自查 | +| 2026-11-14 | 外壳放进新文件 `SidebarRootView.swift`,手动登记进 `Examples.xcodeproj` | 外壳同时涉及 SwiftUI 与 AppKit 两边,放进任何一个已有文件都名不副实;新文件也不会在合并上游时冲突。这个工程没有用文件夹同步,新文件要在工程里登记四处 | +| 2026-11-14 | AppKit 案例的视图控制器每个窗口只建一次,切回时复用 | `NSViewControllerRepresenting` 只在第一次创建时取用传入的视图控制器,之后每次重新求值都白建一个再丢掉;复用还让切走再切回的页面保留状态。截图检查时切回 Basics,sheet 照常弹出、照常用 Done 关掉 | +| 2026-11-14 | 实现完成(第二轮),待用户看过后收尾 | 编译通过,唯一的警告来自没改过的 `Text+Template.swift`。截图检查了侧边栏、全部导航相关的 AppKit 页、几个绑定页、两个 SwiftUI 页、SwiftUI 下钻与返回、ⓘ 弹出的说明,并点开 Basics 的两个 sheet 看状态标记变化。没在运行中验证:Wi-Fi 页的 Destination 切换(打开它的按钮要靠鼠标悬停才出现)、Esc 关 sheet。文档判断:仍不需要另写使用指南或实现说明,没有新术语 | diff --git a/Documentations/README.md b/Documentations/README.md index 416b487af9..0c666e3681 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -17,7 +17,7 @@ - [0010-appkit-animations-case-study.md](Evolutions/0010-appkit-animations-case-study.md):AppKit 动画案例。 - [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 - [draft-appkit-remove-shim.md](Evolutions/draft-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 -- [draft-appkit-examples-redesign.md](Evolutions/draft-appkit-examples-redesign.md):AppKit 案例改用系统设置式的分组排版,弹出的 sheet 都能关掉。 +- [draft-appkit-examples-redesign.md](Evolutions/draft-appkit-examples-redesign.md):macOS 示例改用侧边栏外壳与系统设置式排版,每个弹出行标出导航状态,弹出的 sheet 都能关掉。 ## Internal diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift index e1cd2ee5b1..b44308e319 100644 --- a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -13,10 +13,10 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS override func viewDidLoad() { super.viewDidLoad() - let openPanelStatusLabel = makeValueLabel() + let openPanelState = PresentationStateView() let chosenFileLabel = makeValueLabel() - let numberSheetStatusLabel = makeValueLabel() - let sheetStatusLabel = makeValueLabel() + let numberSheetState = PresentationStateView() + let sheetState = PresentationStateView() addForm( [ @@ -27,7 +27,7 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS FormRow( "Open panel", accessories: [ - openPanelStatusLabel, + openPanelState, makeButton("Show") { [weak self] in self?.model.openPanelMessage = "Choose a file to show its name." }, @@ -38,7 +38,7 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS "Sheet with a number", subtitle: "Closes itself after 3 seconds", accessories: [ - numberSheetStatusLabel, + numberSheetState, makeButton("Show") { [weak self] in let number = Int.random(in: 1 ... 1_000) self?.model.sheet = number @@ -61,7 +61,7 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS FormRow( "Sheet", accessories: [ - sheetStatusLabel, + sheetState, makeButton("Show") { [weak self] in self?.model.isSheetPresented = true }, @@ -74,10 +74,10 @@ class BasicsNavigationViewController: XiblessViewController, AppKitCaseS ) observe { [unowned self] in - openPanelStatusLabel.stringValue = model.openPanelMessage != nil ? "Shown" : "Not shown" + openPanelState.update(isPresented: model.openPanelMessage != nil) chosenFileLabel.stringValue = model.url?.lastPathComponent ?? "None" - numberSheetStatusLabel.stringValue = model.sheet.map { "Showing \($0)" } ?? "Not shown" - sheetStatusLabel.stringValue = model.isSheetPresented ? "Shown" : "Not shown" + numberSheetState.update(isPresented: model.sheet != nil, detail: model.sheet?.description) + sheetState.update(isPresented: model.isSheetPresented) } modal(item: $model.openPanelMessage, id: \.self) { [unowned self] message in diff --git a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift index 5cecb7d3fd..f40c71a45b 100644 --- a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift +++ b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift @@ -46,6 +46,50 @@ func makeValueLabel(_ text: String = "") -> NSTextField { return label } +/// Whether a piece of navigation state presents its content, shown on the trailing side of a row: +/// a green check and "Presented", followed by what is presented when there is something to tell, +/// or a grey cross and "Not presented". +final class PresentationStateView: NSView { + private let symbolView = NSImageView() + private let label = NSTextField(labelWithString: "") + + init() { + super.init(frame: .zero) + symbolView.symbolConfiguration = NSImage.SymbolConfiguration( + pointSize: NSFont.systemFontSize, weight: .medium + ) + label.lineBreakMode = .byTruncatingTail + // NB: A long description gives way before the row's title and controls do. + label.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + let stack = NSStackView(views: [symbolView, label]) + stack.orientation = .horizontal + stack.alignment = .centerY + stack.spacing = 4 + pin(stack, insets: NSEdgeInsets()) + update(isPresented: false) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + /// Shows whether the state presents its content, and `detail` about what it presents. + func update(isPresented: Bool, detail: String? = nil) { + if isPresented { + symbolView.image = NSImage(systemSymbolName: "checkmark.circle.fill", accessibilityDescription: nil) + symbolView.contentTintColor = .systemGreen + label.stringValue = detail.map { "Presented: \($0)" } ?? "Presented" + label.textColor = .labelColor + } else { + symbolView.image = NSImage(systemSymbolName: "xmark.circle.fill", accessibilityDescription: nil) + symbolView.contentTintColor = .tertiaryLabelColor + label.stringValue = "Not presented" + label.textColor = .secondaryLabelColor + } + } +} + // MARK: - Forms /// Lays `sections` out the way System Settings lays out a form: one under another, in a column that diff --git a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift index 6777acd5fb..1030afa4b3 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -23,9 +23,9 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit override func viewDidLoad() { super.viewDidLoad() - let alertStatusLabel = makeValueLabel() - let numberSheetStatusLabel = makeValueLabel() - let sheetStatusLabel = makeValueLabel() + let alertState = PresentationStateView() + let numberSheetState = PresentationStateView() + let sheetState = PresentationStateView() addForm( [ @@ -36,7 +36,7 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit FormRow( "Alert", accessories: [ - alertStatusLabel, + alertState, makeButton("Show") { [weak self] in self?.model.destination = .alert("Hello!") }, @@ -45,7 +45,7 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit FormRow( "Sheet with a number", accessories: [ - numberSheetStatusLabel, + numberSheetState, makeButton("Show") { [weak self] in self?.model.destination = .sheet(.random(in: 1 ... 1_000)) }, @@ -54,7 +54,7 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit FormRow( "Sheet without a payload", accessories: [ - sheetStatusLabel, + sheetState, makeButton("Show") { [weak self] in self?.model.destination = .sheetWithoutPayload }, @@ -67,9 +67,12 @@ class ConciseEnumNavigationViewController: XiblessViewController, AppKit ) observe { [unowned self] in - alertStatusLabel.stringValue = model.destination?.alert != nil ? "Shown" : "Not shown" - numberSheetStatusLabel.stringValue = model.destination?.sheet.map { "Showing \($0)" } ?? "Not shown" - sheetStatusLabel.stringValue = model.destination?.sheetWithoutPayload != nil ? "Shown" : "Not shown" + alertState.update(isPresented: model.destination?.alert != nil) + numberSheetState.update( + isPresented: model.destination?.sheet != nil, + detail: model.destination?.sheet?.description + ) + sheetState.update(isPresented: model.destination?.sheetWithoutPayload != nil) } modal(item: $model.destination.alert, id: \.self) { message in diff --git a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift index ecec204434..56911ef212 100644 --- a/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift @@ -18,7 +18,7 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { override func viewDidLoad() { super.viewDidLoad() - let fruitLabel = makeValueLabel() + let fruitSheetState = PresentationStateView() let logLabel = makeWrappingLabel() logLabel.textColor = .secondaryLabelColor @@ -31,7 +31,7 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { FormRow( "Fruit", accessories: [ - fruitLabel, + fruitSheetState, makeButton("Present") { [weak self] in self?.model.fruit = .apple }, @@ -45,7 +45,7 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { ) observe { [unowned self] in - fruitLabel.stringValue = model.fruit.map { $0.name.prefix(1).uppercased() + $0.name.dropFirst() } ?? "None" + fruitSheetState.update(isPresented: model.fruit != nil, detail: model.fruit?.title) logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") } @@ -97,6 +97,14 @@ class DismissalViewController: XiblessViewController, AppKitCaseStudy { } } + var title: String { + switch self { + case .apple: "Apple" + case .banana: "Banana" + case .cherry: "Cherry" + } + } + var next: Self { Self(rawValue: rawValue + 1) ?? .apple } diff --git a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift index 442161347e..6699b43ba2 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift @@ -15,7 +15,7 @@ final class ErasedNavigationStackController: NavigationStackController, AppKitCa convenience init(model: Model) { @UIBindable var model = model self.init(path: $model.path) { - ErasedRootViewController() + ErasedRootViewController(model: model) } self.model = model } @@ -28,9 +28,22 @@ final class ErasedNavigationStackController: NavigationStackController, AppKitCa /// The bottom of the stack, which registers a destination for each type of data on the path. private final class ErasedRootViewController: XiblessViewController { + let model: ErasedNavigationStackController.Model + + init(model: ErasedNavigationStackController.Model) { + self.model = model + super.init(nibName: nil, bundle: nil) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + override func viewDidLoad() { super.viewDidLoad() title = "Type-erased path" + let pathLabel = makeValueLabel() navigationDestination(for: Int.self) { number in ErasedFeatureViewController(title: "Number \(number)") @@ -68,9 +81,22 @@ private final class ErasedRootViewController: XiblessViewController { ), ] ), + FormSection( + "Model", + footer: "A type-erased path tells how many values it holds, not what they are.", + rows: [FormRow("Path", accessories: [pathLabel])] + ), ], to: view ) + + observe { [unowned self] in + pathLabel.stringValue = switch model.path.count { + case 0: "Empty" + case 1: "1 value" + case let count: "\(count) values" + } + } } } diff --git a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift index 32369eb6e7..94fb699c2c 100644 --- a/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift @@ -18,8 +18,8 @@ class NestedModalViewController: XiblessViewController, AppKitCaseStudy override func viewDidLoad() { super.viewDidLoad() - let settingsWindowLabel = makeValueLabel() - let confirmationAlertLabel = makeValueLabel() + let settingsWindowState = PresentationStateView() + let confirmationAlertState = PresentationStateView() let resetCountLabel = makeValueLabel() addForm( @@ -31,13 +31,13 @@ class NestedModalViewController: XiblessViewController, AppKitCaseStudy FormRow( "Settings window", accessories: [ - settingsWindowLabel, + settingsWindowState, makeButton("Open") { [weak self] in self?.model.isSettingsPresented = true }, ] ), - FormRow("Confirmation alert", accessories: [confirmationAlertLabel]), + FormRow("Confirmation alert", accessories: [confirmationAlertState]), FormRow("Resets", accessories: [resetCountLabel]), ] ), @@ -46,8 +46,8 @@ class NestedModalViewController: XiblessViewController, AppKitCaseStudy ) observe { [unowned self] in - settingsWindowLabel.stringValue = model.isSettingsPresented ? "Open" : "Closed" - confirmationAlertLabel.stringValue = model.resetConfirmation != nil ? "Open" : "Closed" + settingsWindowState.update(isPresented: model.isSettingsPresented) + confirmationAlertState.update(isPresented: model.resetConfirmation != nil) resetCountLabel.stringValue = model.resetCount.description } diff --git a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift index a62058ce0f..cfb1daa12b 100644 --- a/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift @@ -22,6 +22,17 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa override func viewDidLoad() { super.viewDidLoad() + let modalWindowState = PresentationStateView() + let modalAlertState = PresentationStateView() + let modalSessionState = PresentationStateView() + let windowSheetState = PresentationStateView() + let alertSheetState = PresentationStateView() + let savePanelSheetState = PresentationStateView() + let toolbarPopoverState = PresentationStateView() + let popoverState = PresentationStateView() + let viewControllerSheetState = PresentationStateView() + let viewControllerWindowState = PresentationStateView() + let viewControllerPopoverState = PresentationStateView() let popoverButton = makeButton("Show") { [weak self] in self?.model.isPopoverPresented = true } @@ -39,6 +50,7 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa FormRow( "Modal window", accessories: [ + modalWindowState, makeButton("Run") { [weak self] in self?.model.isModalWindowPresented = true }, @@ -47,6 +59,7 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa FormRow( "Modal alert", accessories: [ + modalAlertState, makeButton("Run") { [weak self] in self?.model.modalAlert = .discardChanges }, @@ -56,25 +69,35 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa "Modal session", subtitle: "Takes the app's input without blocking", accessories: [ + modalSessionState, makeButton("Show") { [weak self] in self?.model.isModalSessionPresented = true }, ] ), + ] + ), + FormSection( + "Document window", + footer: "The window's own buttons attach these sheets to it, and its toolbar item shows the popover.", + rows: [ FormRow( - "Document window", - subtitle: "Sheets and a toolbar popover attach to it", + "Window", accessories: [ makeButton("Open") { [weak self] in self?.openDocumentWindow() }, ] ), + FormRow("Window sheet", accessories: [windowSheetState]), + FormRow("Alert sheet", accessories: [alertSheetState]), + FormRow("Save panel sheet", accessories: [savePanelSheetState]), + FormRow("Toolbar popover", accessories: [toolbarPopoverState]), ] ), FormSection( "Popovers", - rows: [FormRow("From a button", accessories: [popoverButton])] + rows: [FormRow("From a button", accessories: [popoverState, popoverButton])] ), FormSection( "View controllers", @@ -82,6 +105,7 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa FormRow( "As a sheet", accessories: [ + viewControllerSheetState, makeButton("Present") { [weak self] in self?.model.isViewControllerSheetPresented = true }, @@ -90,12 +114,16 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa FormRow( "In a modal window", accessories: [ + viewControllerWindowState, makeButton("Present") { [weak self] in self?.model.isViewControllerWindowPresented = true }, ] ), - FormRow("In a popover", accessories: [viewControllerPopoverButton]), + FormRow( + "In a popover", + accessories: [viewControllerPopoverState, viewControllerPopoverButton] + ), ] ), FormSection( @@ -108,6 +136,17 @@ class PresentationGalleryViewController: XiblessViewController, AppKitCa ) observe { [unowned self] in + modalWindowState.update(isPresented: model.isModalWindowPresented) + modalAlertState.update(isPresented: model.modalAlert != nil) + modalSessionState.update(isPresented: model.isModalSessionPresented) + windowSheetState.update(isPresented: model.isWindowSheetPresented) + alertSheetState.update(isPresented: model.alertSheet != nil) + savePanelSheetState.update(isPresented: model.isSavePanelSheetPresented) + toolbarPopoverState.update(isPresented: model.isToolbarPopoverPresented) + popoverState.update(isPresented: model.isPopoverPresented) + viewControllerSheetState.update(isPresented: model.isViewControllerSheetPresented) + viewControllerWindowState.update(isPresented: model.isViewControllerWindowPresented) + viewControllerPopoverState.update(isPresented: model.isViewControllerPopoverPresented) logLabel.stringValue = model.log.isEmpty ? "Nothing dismissed yet." : model.log.joined(separator: "\n") } diff --git a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift index ab806eab10..93f64eb91c 100644 --- a/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -1,47 +1,68 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) -import SwiftUI -import SwiftUINavigation +import AppKitNavigation -struct AppKitCaseStudiesView: View { - var body: some View { - List { - CaseStudyGroupView("Observation") { - MinimalObservationViewController() - AnimationsViewController() - } - CaseStudyGroupView("Bindings") { - NSControlBindingsViewController() - EnumControlsViewController() - FocusViewController() - OptionBindingsViewController() - TableSelectionViewController() - } - CaseStudyGroupView("Optional navigation") { - BasicsNavigationViewController() - ConciseEnumNavigationViewController() - } - CaseStudyGroupView("Presentation") { - PresentationGalleryViewController() - NestedModalViewController() - DismissalViewController() - } - CaseStudyGroupView("Stack navigation") { - StaticNavigationStackController(model: StaticNavigationStackController.Model()) - ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) - // TODO: state restoration - } - CaseStudyGroupView("Advanced") { - // TODO: Deep link - WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)) - } - } - .navigationTitle("AppKit") - } -} - -#Preview { - NavigationStack { - AppKitCaseStudiesView() - } +extension CaseStudySection { + /// The AppKit case studies, grouped by what they show. + @MainActor + static func appKitSections() -> [Self] { + [ + Self( + title: "AppKit · Observation", + pages: [ + CaseStudyPage(MinimalObservationViewController(), systemImage: "eye"), + CaseStudyPage(AnimationsViewController(), systemImage: "sparkles"), + ] + ), + Self( + title: "AppKit · Bindings", + pages: [ + CaseStudyPage(NSControlBindingsViewController(), systemImage: "slider.horizontal.3"), + CaseStudyPage(EnumControlsViewController(), systemImage: "switch.2"), + CaseStudyPage(FocusViewController(), systemImage: "scope"), + CaseStudyPage(OptionBindingsViewController(), systemImage: "checklist"), + CaseStudyPage(TableSelectionViewController(), systemImage: "tablecells"), + ] + ), + Self( + title: "AppKit · Optional navigation", + pages: [ + CaseStudyPage(BasicsNavigationViewController(), systemImage: "rectangle.on.rectangle"), + CaseStudyPage(ConciseEnumNavigationViewController(), systemImage: "list.bullet.rectangle"), + ] + ), + Self( + title: "AppKit · Presentation", + pages: [ + CaseStudyPage(PresentationGalleryViewController(), systemImage: "macwindow.on.rectangle"), + CaseStudyPage(NestedModalViewController(), systemImage: "square.stack.3d.up"), + CaseStudyPage(DismissalViewController(), systemImage: "xmark.rectangle"), + ] + ), + Self( + title: "AppKit · Stack navigation", + pages: [ + CaseStudyPage( + StaticNavigationStackController(model: StaticNavigationStackController.Model()), + systemImage: "rectangle.stack" + ), + CaseStudyPage( + ErasedNavigationStackController(model: ErasedNavigationStackController.Model()), + systemImage: "square.stack" + ), + // TODO: state restoration + ] + ), + Self( + title: "AppKit · Advanced", + pages: [ + // TODO: Deep link + CaseStudyPage( + WiFiSettingsViewController(model: WiFiSettingsModel(foundNetworks: .mocks)), + systemImage: "wifi" + ), + ] + ), + ] + } } #endif diff --git a/Examples/CaseStudies/CaseStudiesApp.swift b/Examples/CaseStudies/CaseStudiesApp.swift index f8e5d18028..9a1b534768 100644 --- a/Examples/CaseStudies/CaseStudiesApp.swift +++ b/Examples/CaseStudies/CaseStudiesApp.swift @@ -4,7 +4,14 @@ import SwiftUI struct CaseStudiesApp: App { var body: some Scene { WindowGroup { + #if canImport(AppKit) && !targetEnvironment(macCatalyst) + SidebarRootView() + #else RootView() + #endif } + #if canImport(AppKit) && !targetEnvironment(macCatalyst) + .defaultSize(width: 1100, height: 760) + #endif } } diff --git a/Examples/CaseStudies/Internal/CaseStudy.swift b/Examples/CaseStudies/Internal/CaseStudy.swift index cdbfe41ff8..385e22194f 100644 --- a/Examples/CaseStudies/Internal/CaseStudy.swift +++ b/Examples/CaseStudies/Internal/CaseStudy.swift @@ -54,12 +54,6 @@ enum CaseStudyViewBuilder { UIKitCaseStudyButton(caseStudy: caseStudy) } #endif - #if canImport(AppKit) && !targetEnvironment(macCatalyst) - @ViewBuilder - static func buildExpression(_ caseStudy: some AppKitCaseStudy) -> some View { - AppKitCaseStudyButton(caseStudy: caseStudy) - } - #endif static func buildPartialBlock(first: some View) -> some View { first } @@ -96,37 +90,6 @@ struct SwiftUICaseStudyButton: View { } } -#if canImport(AppKit) && !targetEnvironment(macCatalyst) - -struct AppKitCaseStudyButton: View { - let caseStudy: C - @State var isPresented = false - var body: some View { -// if caseStudy.isPresentedInSheet { -// Button(caseStudy.caseStudyTitle) { -// isPresented = true -// } -// .sheet(isPresented: $isPresented) { -// NSViewControllerRepresenting { -// ((caseStudy as? UINavigationController) -// ?? UINavigationController(rootViewController: caseStudy)) -// .setUp(caseStudy: caseStudy) -// } -// .modifier(CaseStudyModifier(caseStudy: caseStudy)) -// } -// } else { - NavigationLink(caseStudy.caseStudyTitle) { - NSViewControllerRepresenting { - caseStudy - } - .modifier(CaseStudyModifier(caseStudy: caseStudy)) - } -// } - } -} - -#endif - #if canImport(UIKit) && !os(watchOS) struct UIKitCaseStudyButton: View { let caseStudy: C diff --git a/Examples/CaseStudies/RootView.swift b/Examples/CaseStudies/RootView.swift index cb466a2879..5f4707a272 100644 --- a/Examples/CaseStudies/RootView.swift +++ b/Examples/CaseStudies/RootView.swift @@ -13,11 +13,6 @@ struct RootView: View { UIKitCaseStudiesView() } #endif - #if canImport(AppKit) && !targetEnvironment(macCatalyst) - NavigationLink("AppKit") { - AppKitCaseStudiesView() - } - #endif } .navigationTitle("Case studies") } diff --git a/Examples/CaseStudies/SidebarRootView.swift b/Examples/CaseStudies/SidebarRootView.swift new file mode 100644 index 0000000000..9dd8f30c21 --- /dev/null +++ b/Examples/CaseStudies/SidebarRootView.swift @@ -0,0 +1,162 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKitNavigation +import SwiftUI + +/// The case studies app on the Mac: a sidebar that lists every case study, beside the one that is +/// chosen. +struct SidebarRootView: View { + @State private var catalog = CaseStudyCatalog() + @SceneStorage("SidebarRootView.selection") private var selection: CaseStudyPage.ID? + + var body: some View { + NavigationSplitView { + List(selection: $selection) { + ForEach(catalog.sections) { section in + Section(section.title) { + ForEach(section.pages) { page in + Label(page.title, systemImage: page.systemImage) + } + } + } + } + .navigationSplitViewColumnWidth(min: 220, ideal: 260, max: 340) + } detail: { + if let page = selection.flatMap(catalog.page(id:)) { + CaseStudyPageView(page: page) + // NB: Each case study gets a page of its own, rather than one page whose content changes. + .id(page.id) + } else { + ContentUnavailableView( + "No Case Study Selected", + systemImage: "sidebar.left", + description: Text("Choose one in the sidebar to try it.") + ) + } + } + } +} + +/// A case study beside the sidebar, with its read-me behind the toolbar's info button. +private struct CaseStudyPageView: View { + let page: CaseStudyPage + @State private var isAboutPresented = false + + var body: some View { + NavigationStack { + page.content + .navigationTitle(page.navigationTitle) + .navigationSubtitle(page.framework) + .toolbar { + ToolbarItem(placement: .primaryAction) { + Button { + isAboutPresented.toggle() + } label: { + Label("About", systemImage: "info.circle") + } + .help("About this case study") + .popover(isPresented: $isAboutPresented, arrowEdge: .bottom) { + Text(template: page.readMe) + .frame(width: 360, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .padding(20) + } + } + } + } + } +} + +/// Every case study the sidebar lists, made once for each window. +/// +/// The AppKit case studies keep their state while another one is shown, since the same view +/// controller comes back when its case study is chosen again. +@MainActor +final class CaseStudyCatalog { + let sections = CaseStudySection.swiftUISections() + CaseStudySection.appKitSections() + + func page(id: CaseStudyPage.ID) -> CaseStudyPage? { + for section in sections { + if let page = section.pages.first(where: { $0.id == id }) { + return page + } + } + return nil + } +} + +/// A group of case studies in the sidebar. +struct CaseStudySection: Identifiable { + let title: String + let pages: [CaseStudyPage] + + var id: String { title } +} + +/// A case study in the sidebar, and what shows beside it once it is chosen. +struct CaseStudyPage: Identifiable { + let id: String + let title: String + let navigationTitle: String + let framework: String + let readMe: String + let systemImage: String + let content: AnyView +} + +extension CaseStudyPage { + @MainActor + init(_ caseStudy: some SwiftUICaseStudy, systemImage: String) { + self.init( + id: String(describing: type(of: caseStudy)), + title: caseStudy.caseStudyTitle, + navigationTitle: caseStudy.caseStudyNavigationTitle, + framework: "SwiftUI", + readMe: caseStudy.readMe, + systemImage: systemImage, + // NB: Grouped, like System Settings and the AppKit case studies, rather than in columns. + content: AnyView(CaseStudyView { caseStudy }.formStyle(.grouped)) + ) + } + + @MainActor + init(_ caseStudy: some AppKitCaseStudy, systemImage: String) { + self.init( + id: String(describing: type(of: caseStudy)), + title: caseStudy.caseStudyTitle, + navigationTitle: caseStudy.caseStudyNavigationTitle, + framework: "AppKit", + readMe: caseStudy.readMe, + systemImage: systemImage, + content: AnyView(NSViewControllerRepresenting { caseStudy }) + ) + } +} + +extension CaseStudySection { + /// The SwiftUI case studies, in the groups `SwiftUICaseStudiesView` lists them in. + @MainActor + static func swiftUISections() -> [Self] { + [ + Self( + title: "SwiftUI · Navigation", + pages: [ + CaseStudyPage(OptionalNavigation(), systemImage: "rectangle.on.rectangle.angled"), + CaseStudyPage(EnumNavigation(), systemImage: "list.bullet.rectangle"), + CaseStudyPage(AlertDialogState(), systemImage: "exclamationmark.bubble"), + ] + ), + Self( + title: "SwiftUI · Binding helpers", + pages: [ + CaseStudyPage(SynchronizedBindings(), systemImage: "arrow.triangle.2.circlepath"), + CaseStudyPage(EnumControls(), systemImage: "switch.2"), + ] + ), + ] + } +} + +#Preview { + SidebarRootView() +} +#endif diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift index cac403b1ed..0c472a9f85 100644 --- a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -19,6 +19,9 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas let collectionView = NSCollectionView() + /// The header above the sections, which shows where the settings navigate to. + private weak var destinationHeader: WiFiSettingsDestinationHeaderView? + init(model: WiFiSettingsModel) { self.model = model super.init(nibName: nil, bundle: nil) @@ -55,8 +58,20 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas collectionViewLayout.register(WiFiSettingsSectionBackgroundView.self, forDecorationViewOfKind: .background) let configuration = NSCollectionViewCompositionalLayoutConfiguration() configuration.interSectionSpacing = 20 + configuration.boundarySupplementaryItems = [ + NSCollectionLayoutBoundarySupplementaryItem( + layoutSize: NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(60)), + elementKind: WiFiSettingsDestinationHeaderView.elementKind, + alignment: .top + ), + ] collectionViewLayout.configuration = configuration collectionView.collectionViewLayout = collectionViewLayout + collectionView.register( + WiFiSettingsDestinationHeaderView.self, + forSupplementaryViewOfKind: WiFiSettingsDestinationHeaderView.elementKind, + withIdentifier: .init(WiFiSettingsDestinationHeaderView.self) + ) collectionView.register(WiFiSettingsSwitchViewItem.self, forItemWithIdentifier: .init(WiFiSettingsSwitchViewItem.self)) collectionView.register(WiFiSettingsConnectedNetworkViewItem.self, forItemWithIdentifier: .init(WiFiSettingsConnectedNetworkViewItem.self)) collectionView.register(WiFiSettingsFoundedNetworkViewItem.self, forItemWithIdentifier: .init(WiFiSettingsFoundedNetworkViewItem.self)) @@ -95,6 +110,21 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas } } + dataSource.supplementaryViewProvider = { [weak self] collectionView, elementKind, indexPath in + guard elementKind == WiFiSettingsDestinationHeaderView.elementKind else { return nil } + let header = collectionView.makeSupplementaryView( + ofKind: elementKind, + withIdentifier: .init(WiFiSettingsDestinationHeaderView.self), + for: indexPath + ) as! WiFiSettingsDestinationHeaderView + if let self { + destinationHeader = header + let destination = destinationDescription + header.stateView.update(isPresented: destination != nil, detail: destination) + } + return header + } + observe { [unowned self] in dataSource.apply( NSDiffableDataSourceSnapshot(model: model), @@ -102,6 +132,13 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas ) } + observe { [unowned self] in + // NB: Reads the destination even before the header is made, so that its changes are + // observed from the start. + let destination = destinationDescription + destinationHeader?.stateView.update(isPresented: destination != nil, detail: destination) + } + modalSession(item: $model.destination.connect) { model in let panel = NSPanel(contentViewController: ConnectToNetworkViewController(model: model)) panel.styleMask = [.titled] @@ -114,6 +151,43 @@ class WiFiSettingsViewController: XiblessViewController, AppKitCas NetworkDetailViewController(model: model) } } + + /// What the settings navigate to, if anything. + private var destinationDescription: String? { + switch model.destination { + case let .connect(connectModel): "Connect to “\(connectModel.network.name)”" + case let .detail(detailModel): "Details of “\(detailModel.network.name)”" + case nil: nil + } + } +} + +/// The top of the settings: one row that shows where the settings navigate to. +class WiFiSettingsDestinationHeaderView: NSView, NSCollectionViewElement { + static let elementKind = "DestinationHeader" + + let stateView = PresentationStateView() + + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + let section = FormSection(rows: [FormRow("Destination", accessories: [stateView])]) + section.translatesAutoresizingMaskIntoConstraints = false + addSubview(section) + // NB: The same centered column, no wider than 640 points, that the sections below use. + let fillsTheWidth = section.widthAnchor.constraint(equalTo: widthAnchor, constant: -48) + fillsTheWidth.priority = .defaultHigh + NSLayoutConstraint.activate([ + section.topAnchor.constraint(equalTo: topAnchor, constant: 20), + section.centerXAnchor.constraint(equalTo: centerXAnchor), + section.widthAnchor.constraint(lessThanOrEqualToConstant: 640), + fillsTheWidth, + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } } #Preview { diff --git a/Examples/Examples.xcodeproj/project.pbxproj b/Examples/Examples.xcodeproj/project.pbxproj index 6bb2b0256a..55022cd6de 100644 --- a/Examples/Examples.xcodeproj/project.pbxproj +++ b/Examples/Examples.xcodeproj/project.pbxproj @@ -21,6 +21,7 @@ CA4737FC272F09D00012CAC3 /* Inventory.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA4737F8272F09D00012CAC3 /* Inventory.swift */; }; CA47380B272F0D340012CAC3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = CA47380A272F0D340012CAC3 /* Assets.xcassets */; }; CA473834272F0D860012CAC3 /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA47382E272F0D860012CAC3 /* RootView.swift */; }; + F1A0B0C12EB6D10000A1B2C3 /* SidebarRootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F1A0B0C02EB6D10000A1B2C3 /* SidebarRootView.swift */; }; CA473836272F0D860012CAC3 /* CaseStudiesApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA473830272F0D860012CAC3 /* CaseStudiesApp.swift */; }; CA473837272F0D860012CAC3 /* FactClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA473831272F0D860012CAC3 /* FactClient.swift */; }; CA473838272F0D860012CAC3 /* OptionalNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA473832272F0D860012CAC3 /* OptionalNavigation.swift */; }; @@ -105,6 +106,7 @@ CA473804272F0D330012CAC3 /* CaseStudies.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = CaseStudies.app; sourceTree = BUILT_PRODUCTS_DIR; }; CA47380A272F0D340012CAC3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; CA47382E272F0D860012CAC3 /* RootView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = ""; }; + F1A0B0C02EB6D10000A1B2C3 /* SidebarRootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SidebarRootView.swift; sourceTree = ""; }; CA473830272F0D860012CAC3 /* CaseStudiesApp.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = CaseStudiesApp.swift; sourceTree = ""; }; CA473831272F0D860012CAC3 /* FactClient.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FactClient.swift; sourceTree = ""; }; CA473832272F0D860012CAC3 /* OptionalNavigation.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OptionalNavigation.swift; sourceTree = ""; }; @@ -261,6 +263,7 @@ CA47383C272F0F0D0012CAC3 /* Info.plist */, CA473830272F0D860012CAC3 /* CaseStudiesApp.swift */, CA47382E272F0D860012CAC3 /* RootView.swift */, + F1A0B0C02EB6D10000A1B2C3 /* SidebarRootView.swift */, CA47380A272F0D340012CAC3 /* Assets.xcassets */, CA9D70492C1F642A003B672A /* Internal */, CADCA3642C1CE80B00DE645F /* SwiftUI */, @@ -641,6 +644,7 @@ CA9D70562C2087DC003B672A /* EnumControls.swift in Sources */, CA473836272F0D860012CAC3 /* CaseStudiesApp.swift in Sources */, CA473834272F0D860012CAC3 /* RootView.swift in Sources */, + F1A0B0C12EB6D10000A1B2C3 /* SidebarRootView.swift in Sources */, CA3D0E322C20B27B00CCF7CD /* UIKit+ConnectToNetworkViewController.swift in Sources */, E9836D962C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift in Sources */, CA3D0E332C20B27B00CCF7CD /* UIKit+NetworkDetailViewController.swift in Sources */, From 4e19dd7126cd9266971909e3327ae3c959901c32 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sat, 14 Nov 2026 22:46:15 +0800 Subject: [PATCH 132/141] fix(examples): give the stack screens a background and let the AppKit pages fill the window Pushing onto an AppKit navigation stack showed both screens at once: the screens drew no background, so the old one showed through the new one as it slid in. Each screen now has the window's background material behind it. windowBackgroundColor would be a shade darker than the window, whose background takes on the desktop picture's tint. Every AppKit page was also laid out 688 points wide and centered. The form column's wish to fill the page minus its margins was stronger (750) than the width SwiftUI holds a hosted view controller at (500), so it narrowed the whole page to the column. The column now prefers 640 points at 490 and is required to stay within the page, so the pages fill the space beside the sidebar again. --- .../draft-appkit-examples-redesign.md | 12 +++++- .../AppKit/AppKit+CaseStudySupport.swift | 38 +++++++++++++++++-- ...pKit+ErasedNavigationStackController.swift | 4 +- ...pKit+StaticNavigationStackController.swift | 4 +- .../AppKit+WiFiSettingsViewController.swift | 7 ++-- 5 files changed, 54 insertions(+), 11 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-examples-redesign.md b/Documentations/Evolutions/draft-appkit-examples-redesign.md index f10d977dc3..aa160c5cff 100644 --- a/Documentations/Evolutions/draft-appkit-examples-redesign.md +++ b/Documentations/Evolutions/draft-appkit-examples-redesign.md @@ -19,7 +19,8 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 - 详情区包一层 `NavigationStack`,SwiftUI 案例里的下钻照常推入。 - SwiftUI 案例在 macOS 上的表单用分组样式,与 AppKit 案例一致。 - **共享排版**放在已有的 `AppKit+CaseStudySupport.swift`: - - 页面:一列分组,放在可以滚动的区域里,靠上、水平居中,有最大宽度。 + - 页面:一列分组,放在可以滚动的区域里,靠上、水平居中,有最大宽度。滚动区域铺满整个详情区,列宽只以弱于 SwiftUI 宿主尺寸的优先级偏向 640 点,不会反过来把整页拉窄。 + - 栈导航的每一页(`WindowBackgroundView`)铺一层与窗口相同的背景材质:推入的新页从右侧滑进来压在旧页上,没有背景就会透出旧页。 - 分组:上方一行粗体标题,中间一个圆角框装着若干行,行与行之间画分隔线,下方可以有一段说明。 - 行:左边是名称,右边是状态和控件;表格、画布、日志这类内容占满整行。 - 导航状态标记 `PresentationStateView`:绿色对勾加「Presented」,有值时带上值(「Presented: 42」);没弹出时是灰色叉号加「Not presented」。 @@ -34,6 +35,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 4. macOS 外壳换成侧边栏加详情,说明改到工具栏 ⓘ,SwiftUI 案例用分组样式。(已完成) 5. 全部 AppKit 案例的弹出行加上状态标记,类型擦除路径页加上「Path」一行,Wi-Fi 页加上「Destination」一行。(已完成) 6. 重新编译,启动 App 截图检查外壳和各页的状态标记。(已完成) +7. 栈导航的页面铺上窗口背景,表单的列宽改成不会拉窄页面的弱偏好;连续截帧检查推入转场。(已完成) 没有询问就采用的假设: @@ -54,6 +56,10 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 - Animations 页的圆默认改用系统蓝,颜色循环最后也回到系统蓝:原来的黑色在深色模式下几乎看不见。 - Wi-Fi 设置页本来就是分组列表,只把分组框、宽度和边距对齐到其他页面;连接网络的面板给 Join 配上回车、给 Cancel 配上 Esc。 +## 后续项 + +- 栈导航返回时,滑出去的那一页只画出背景、内容不显示:页面的子视图都还在、图层内容也在,换透明、纯色、窗口材质三种背景结果相同,去掉滚动视图也一样,推入时则正常。问题在 AppKitPlus 返回转场的实现里,示例这边绕不开;页面透明时被掩盖了,看起来只是根页滑回来。要在 AppKitPlus 里查,修好后需要发新版 AppKitPlus-Release。 + ## 决策日志 | 日期 | 决定 | 理由 | @@ -68,3 +74,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 | 2026-11-14 | 外壳放进新文件 `SidebarRootView.swift`,手动登记进 `Examples.xcodeproj` | 外壳同时涉及 SwiftUI 与 AppKit 两边,放进任何一个已有文件都名不副实;新文件也不会在合并上游时冲突。这个工程没有用文件夹同步,新文件要在工程里登记四处 | | 2026-11-14 | AppKit 案例的视图控制器每个窗口只建一次,切回时复用 | `NSViewControllerRepresenting` 只在第一次创建时取用传入的视图控制器,之后每次重新求值都白建一个再丢掉;复用还让切走再切回的页面保留状态。截图检查时切回 Basics,sheet 照常弹出、照常用 Done 关掉 | | 2026-11-14 | 实现完成(第二轮),待用户看过后收尾 | 编译通过,唯一的警告来自没改过的 `Text+Template.swift`。截图检查了侧边栏、全部导航相关的 AppKit 页、几个绑定页、两个 SwiftUI 页、SwiftUI 下钻与返回、ⓘ 弹出的说明,并点开 Basics 的两个 sheet 看状态标记变化。没在运行中验证:Wi-Fi 页的 Destination 切换(打开它的按钮要靠鼠标悬停才出现)、Esc 关 sheet。文档判断:仍不需要另写使用指南或实现说明,没有新术语 | +| 2026-11-14 | 栈导航的页面铺上窗口背景材质,不用 `windowBackgroundColor` | 用户看过第二轮后指出栈导航转场有残影。连续截帧确认:页面没有背景,推入时新页透明地压在旧页上,两页的分组框和按钮叠在一起。纯色的 `windowBackgroundColor` 量出来是 (30, 30, 30),而窗口实际的底色随桌面着色,是 (34, 34, 35),铺上去会显出一块更深的矩形;改用 `.windowBackground` 材质后与周围逐像素一致 | +| 2026-11-14 | 表单列宽改成优先级 490 的「偏向 640 点」,加上「不宽过页面减 48」的必需约束 | 用 lldb 看视图树发现:SwiftUI 宿主用约束钉住页面,自身宽度约束只有 500 优先级;原来那条 750 优先级的「列宽 = 文档宽 − 48」压过了它,把每个 AppKit 页都拉成 688 点宽、居中摆放。页面透明时看不出来,只有滚动条停在 1024 点处;栈页铺上背景后就显出一块窄矩形。改后页面铺满详情区,滚动条回到窗口右缘。Wi-Fi 页顶部那一行用的是同一种写法,一并改掉 | +| 2026-11-14 | 返回转场里旧页内容不显示,记为后续项,不在示例里绕 | 断点和截帧都指向 AppKitPlus 的返回动画:动画开始和结束时旧页的视图树、图层内容都完好,动画过程中却只合成出它的背景。示例这边换背景、去滚动视图都没有用 | +| 2026-11-14 | 实现完成(第三轮),待用户看过后收尾 | 编译通过,警告仍只有 `Text+Template.swift` 那一条。连续截帧检查了两个栈页的推入:新页完全挡住旧页;栈页、Presentation styles、Wi-Fi 页都铺满详情区,底色与窗口一致。文档判断:不需要另写使用指南或实现说明,没有新术语 | diff --git a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift index f40c71a45b..039af951c5 100644 --- a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift +++ b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift @@ -23,6 +23,29 @@ class XiblessViewController: NSViewController { } } +/// A view with the window's own background behind its subviews: the view of a screen on a +/// navigation stack. +/// +/// A pushed screen slides in over the one under it, so a screen that draws no background of its own +/// lets the other one show through while the transition runs. +final class WindowBackgroundView: NSView { + override init(frame frameRect: NSRect) { + super.init(frame: frameRect) + // NB: The window background material rather than `windowBackgroundColor`, which is a shade + // darker than a window whose background takes on the desktop picture's tint. + let background = NSVisualEffectView() + background.material = .windowBackground + background.blendingMode = .behindWindow + background.state = .followsWindowActiveState + pin(background, insets: NSEdgeInsets()) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + // MARK: - Controls /// A push button that runs `action` when clicked. @@ -112,8 +135,8 @@ func addForm(_ sections: [FormSection], to view: NSView) { view.addSubview(scrollView) let clipView = scrollView.contentView - let fillsTheWidth = column.widthAnchor.constraint(equalTo: documentView.widthAnchor, constant: -48) - fillsTheWidth.priority = .defaultHigh + let preferredWidth = column.widthAnchor.constraint(equalToConstant: 640) + preferredWidth.priority = .preferredFormWidth NSLayoutConstraint.activate([ scrollView.topAnchor.constraint(equalTo: view.topAnchor), scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor), @@ -126,10 +149,19 @@ func addForm(_ sections: [FormSection], to view: NSView) { column.bottomAnchor.constraint(equalTo: documentView.bottomAnchor, constant: -24), column.centerXAnchor.constraint(equalTo: documentView.centerXAnchor), column.widthAnchor.constraint(lessThanOrEqualToConstant: 640), - fillsTheWidth, + column.widthAnchor.constraint(lessThanOrEqualTo: documentView.widthAnchor, constant: -48), + preferredWidth, ]) } +extension NSLayoutConstraint.Priority { + /// How strongly a form prefers its column 640 points wide. + /// + /// Weaker than the 500 that SwiftUI holds the size of a view controller it hosts with: a stronger + /// preference wins over that size and narrows the whole page to the column's width instead. + static let preferredFormWidth = Self(490) +} + /// A label whose text wraps to the width it is laid out at: a note, a log or a dump of a model. @MainActor func makeWrappingLabel(_ text: String = "") -> NSTextField { diff --git a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift index 6699b43ba2..57bc832430 100644 --- a/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift @@ -27,7 +27,7 @@ final class ErasedNavigationStackController: NavigationStackController, AppKitCa } /// The bottom of the stack, which registers a destination for each type of data on the path. -private final class ErasedRootViewController: XiblessViewController { +private final class ErasedRootViewController: XiblessViewController { let model: ErasedNavigationStackController.Model init(model: ErasedNavigationStackController.Model) { @@ -101,7 +101,7 @@ private final class ErasedRootViewController: XiblessViewController { } /// A screen on the stack: it can push data of any of the three types, or dismiss itself. -private final class ErasedFeatureViewController: XiblessViewController { +private final class ErasedFeatureViewController: XiblessViewController { init(title: String) { super.init(nibName: nil, bundle: nil) self.title = title diff --git a/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift index ad5b97deb6..ec37c92fee 100644 --- a/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift +++ b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift @@ -47,7 +47,7 @@ final class StaticNavigationStackController: NavigationStackController, AppKitCa } /// The bottom of the stack: a button for each feature, and one that pushes all three at once. -private final class StaticRootViewController: XiblessViewController { +private final class StaticRootViewController: XiblessViewController { let model: StaticNavigationStackController.Model init(model: StaticNavigationStackController.Model) { @@ -104,7 +104,7 @@ private final class StaticRootViewController: XiblessViewController { } /// A screen on the stack: it can push any feature, or dismiss itself. -private final class StaticFeatureViewController: XiblessViewController { +private final class StaticFeatureViewController: XiblessViewController { let feature: StaticNavigationStackController.Model.Path init(feature: StaticNavigationStackController.Model.Path) { diff --git a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift index 0c472a9f85..ce260c2a06 100644 --- a/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -174,13 +174,14 @@ class WiFiSettingsDestinationHeaderView: NSView, NSCollectionViewElement { section.translatesAutoresizingMaskIntoConstraints = false addSubview(section) // NB: The same centered column, no wider than 640 points, that the sections below use. - let fillsTheWidth = section.widthAnchor.constraint(equalTo: widthAnchor, constant: -48) - fillsTheWidth.priority = .defaultHigh + let preferredWidth = section.widthAnchor.constraint(equalToConstant: 640) + preferredWidth.priority = .preferredFormWidth NSLayoutConstraint.activate([ section.topAnchor.constraint(equalTo: topAnchor, constant: 20), section.centerXAnchor.constraint(equalTo: centerXAnchor), section.widthAnchor.constraint(lessThanOrEqualToConstant: 640), - fillsTheWidth, + section.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -48), + preferredWidth, ]) } From 3cb333362b8a5b130e49f121bb2bea6ffd910393 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 00:19:06 +0800 Subject: [PATCH 133/141] docs(examples): record why a popped stack screen slides out blank, and where it is fixed The screen a pop takes away slid out as its bare background. AppKitPlus, like the UXKit it ports, sets that screen's frame wholly outside the container as the animation starts, and AppKit only redraws the part of a view inside the window. The fix is in AppKitPlus and reaches the case studies with its next release; nothing changes here. --- Documentations/Evolutions/draft-appkit-examples-redesign.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Documentations/Evolutions/draft-appkit-examples-redesign.md b/Documentations/Evolutions/draft-appkit-examples-redesign.md index aa160c5cff..db36569541 100644 --- a/Documentations/Evolutions/draft-appkit-examples-redesign.md +++ b/Documentations/Evolutions/draft-appkit-examples-redesign.md @@ -2,7 +2,7 @@ - **状态**: In Progress - **创建日期**: 2026-11-14 -- **最后更新**: 2026-11-14 +- **最后更新**: 2026-11-15 - **实现分支**: `appkit-examples-redesign` ## 摘要 @@ -58,7 +58,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 ## 后续项 -- 栈导航返回时,滑出去的那一页只画出背景、内容不显示:页面的子视图都还在、图层内容也在,换透明、纯色、窗口材质三种背景结果相同,去掉滚动视图也一样,推入时则正常。问题在 AppKitPlus 返回转场的实现里,示例这边绕不开;页面透明时被掩盖了,看起来只是根页滑回来。要在 AppKitPlus 里查,修好后需要发新版 AppKitPlus-Release。 +- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。已在 AppKitPlus 的 `fix/transition-leaving-page-content` 修好(AppKitPlus 提案 transition-leaving-page-content),合进了它本地的 `main`,还没发版。AppKitPlus-Release 发出新版后,把本仓库的依赖升上去即可,示例这边不用改。 ## 决策日志 @@ -78,3 +78,4 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 | 2026-11-14 | 表单列宽改成优先级 490 的「偏向 640 点」,加上「不宽过页面减 48」的必需约束 | 用 lldb 看视图树发现:SwiftUI 宿主用约束钉住页面,自身宽度约束只有 500 优先级;原来那条 750 优先级的「列宽 = 文档宽 − 48」压过了它,把每个 AppKit 页都拉成 688 点宽、居中摆放。页面透明时看不出来,只有滚动条停在 1024 点处;栈页铺上背景后就显出一块窄矩形。改后页面铺满详情区,滚动条回到窗口右缘。Wi-Fi 页顶部那一行用的是同一种写法,一并改掉 | | 2026-11-14 | 返回转场里旧页内容不显示,记为后续项,不在示例里绕 | 断点和截帧都指向 AppKitPlus 的返回动画:动画开始和结束时旧页的视图树、图层内容都完好,动画过程中却只合成出它的背景。示例这边换背景、去滚动视图都没有用 | | 2026-11-14 | 实现完成(第三轮),待用户看过后收尾 | 编译通过,警告仍只有 `Text+Template.swift` 那一条。连续截帧检查了两个栈页的推入:新页完全挡住旧页;栈页、Presentation styles、Wi-Fi 页都铺满详情区,底色与窗口一致。文档判断:不需要另写使用指南或实现说明,没有新术语 | +| 2026-11-15 | 返回转场的空白在 AppKitPlus 里修,示例不绕 | 用户同意按「离场页留在原位、只用图层动画移走、结束时再落位」在 AppKitPlus 修。核对 UXKit 27.2 汇编后确认它本身就这样移离场页,AppKitPlus 有意偏离。修复在它的功能分支上做完、本地合进它的 `main`,待发版后升级依赖 | From 19c0468db08459b3d1a11604b854c9156cbf2243 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 11:53:21 +0800 Subject: [PATCH 134/141] docs(examples): point the stack-transition follow-up at AppKitPlus 0116 The fix for the blank screen a pop slides away has landed in AppKitPlus as proposal 0116 and is pushed, but no AppKitPlus-Release carries it yet: the case studies pin 0.21.0, and 0.22.0 predates it. Bumping that pin after the next release is all that is left here. --- Documentations/Evolutions/draft-appkit-examples-redesign.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-appkit-examples-redesign.md b/Documentations/Evolutions/draft-appkit-examples-redesign.md index db36569541..5ac4ed9f9f 100644 --- a/Documentations/Evolutions/draft-appkit-examples-redesign.md +++ b/Documentations/Evolutions/draft-appkit-examples-redesign.md @@ -58,7 +58,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 ## 后续项 -- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。已在 AppKitPlus 的 `fix/transition-leaving-page-content` 修好(AppKitPlus 提案 transition-leaving-page-content),合进了它本地的 `main`,还没发版。AppKitPlus-Release 发出新版后,把本仓库的依赖升上去即可,示例这边不用改。 +- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。修复已作为 AppKitPlus 提案 0116(transition-leaving-page-content)合进它的 `main` 并推送,还没发版:示例锁定的 AppKitPlus-Release 0.21.0 和最新的 0.22.0 都不含它。含这项修复的版本发出后,把示例锁定的版本升上去即可,`Package.swift` 与示例代码都不用改。 ## 决策日志 @@ -79,3 +79,4 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 | 2026-11-14 | 返回转场里旧页内容不显示,记为后续项,不在示例里绕 | 断点和截帧都指向 AppKitPlus 的返回动画:动画开始和结束时旧页的视图树、图层内容都完好,动画过程中却只合成出它的背景。示例这边换背景、去滚动视图都没有用 | | 2026-11-14 | 实现完成(第三轮),待用户看过后收尾 | 编译通过,警告仍只有 `Text+Template.swift` 那一条。连续截帧检查了两个栈页的推入:新页完全挡住旧页;栈页、Presentation styles、Wi-Fi 页都铺满详情区,底色与窗口一致。文档判断:不需要另写使用指南或实现说明,没有新术语 | | 2026-11-15 | 返回转场的空白在 AppKitPlus 里修,示例不绕 | 用户同意按「离场页留在原位、只用图层动画移走、结束时再落位」在 AppKitPlus 修。核对 UXKit 27.2 汇编后确认它本身就这样移离场页,AppKitPlus 有意偏离。修复在它的功能分支上做完、本地合进它的 `main`,待发版后升级依赖 | +| 2026-11-15 | 后续项改指 AppKitPlus 提案 0116 | AppKitPlus 的修复已以 0116 合进它的 `main` 并推送,原来的功能分支已删除;仍要等 AppKitPlus-Release 发出含它的版本 | From 2578ffa326d97c76c1c6e698a7231994797f81db Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 12:04:05 +0800 Subject: [PATCH 135/141] docs: number proposals 0012 and 0013 and mark them implemented The shim removal and the macOS case study redesign land together: the redesign was built on top of the shim removal. The case studies still pin AppKitPlus-Release 0.21.0; 0.23.0 carries the fix for the blank screen a pop slides away, and moving the pin is left as a follow-up. --- ...ft-appkit-remove-shim.md => 0012-appkit-remove-shim.md} | 7 ++++--- ...amples-redesign.md => 0013-appkit-examples-redesign.md} | 7 ++++--- Documentations/Evolutions/README.md | 4 ++-- Documentations/README.md | 4 ++-- 4 files changed, 12 insertions(+), 10 deletions(-) rename Documentations/Evolutions/{draft-appkit-remove-shim.md => 0012-appkit-remove-shim.md} (93%) rename Documentations/Evolutions/{draft-appkit-examples-redesign.md => 0013-appkit-examples-redesign.md} (95%) diff --git a/Documentations/Evolutions/draft-appkit-remove-shim.md b/Documentations/Evolutions/0012-appkit-remove-shim.md similarity index 93% rename from Documentations/Evolutions/draft-appkit-remove-shim.md rename to Documentations/Evolutions/0012-appkit-remove-shim.md index 5130b3535e..3c45365530 100644 --- a/Documentations/Evolutions/draft-appkit-remove-shim.md +++ b/Documentations/Evolutions/0012-appkit-remove-shim.md @@ -1,8 +1,8 @@ -# Draft - 去掉 AppKitNavigationShim:不再交换系统方法 +# 0012 - 去掉 AppKitNavigationShim:不再交换系统方法 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-14 -- **最后更新**: 2026-11-14 +- **最后更新**: 2026-11-15 - **实现分支**: `appkit-remove-shim` ## 摘要 @@ -57,3 +57,4 @@ | 2026-11-14 | 实现完成,待用户看过后收尾 | 文档已同步:本提案、`present` / `destination` / `navigationDestination` 与存取面板绑定的文档注释、`Internal/ReviewDecisions.md`。改动只涉及内部机制与既有 API 的语义,不需要另写使用指南或实现说明,也没有新术语 | | 2026-11-14 | 由绑定触发的视图控制器关闭,在 `dismiss(_:)` 返回后立刻检查、当场写回 | 用户指出 AppKit 的 `dismiss(_:)` 返回时内容已经离屏,与 UIKit 不同。交换方法时这条路是同步写回的,去掉之后却要等这一轮 run loop 结束;用户选择只恢复这一条,用户自己关掉的仍在这一轮结束时写回。新测试借自定义事务键在绑定变化应用完的那一刻检查 `onDismiss` 是否已运行,修前失败、修后通过 | | 2026-11-14 | 用户确认:存储面板取消时绑定保持原值 | 用户看过旧实现「取消即写成 `nil`」的实测结果后,仍选择取消时不动绑定;案例在弹出前清空 `savedURL` 的那一行保留 | +| 2026-11-15 | 落地:合进 `main` 并推送,编号 0012 | 用户要求收尾,与在它之上做的示例改版(0013)一同落地。在合并后的最终代码上验证:全量 `swift test` 只有 `ButtonStateTests.testAsyncAnimationWarning` 失败,这是 macOS 27.2 上早就存在的上游问题,两次改动都没有碰它所在的模块;打开 AppKitPlus trait 的 AppKit 测试全部通过(XCTest 94 个,Swift Testing 78 个);`CaseStudies` 的 macOS 版编译通过。文档判断不变:不需要另写使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/draft-appkit-examples-redesign.md b/Documentations/Evolutions/0013-appkit-examples-redesign.md similarity index 95% rename from Documentations/Evolutions/draft-appkit-examples-redesign.md rename to Documentations/Evolutions/0013-appkit-examples-redesign.md index 5ac4ed9f9f..e9b03c9f16 100644 --- a/Documentations/Evolutions/draft-appkit-examples-redesign.md +++ b/Documentations/Evolutions/0013-appkit-examples-redesign.md @@ -1,6 +1,6 @@ -# Draft - macOS 示例改用侧边栏外壳与系统设置式排版 +# 0013 - macOS 示例改用侧边栏外壳与系统设置式排版 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-14 - **最后更新**: 2026-11-15 - **实现分支**: `appkit-examples-redesign` @@ -58,7 +58,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 ## 后续项 -- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。修复已作为 AppKitPlus 提案 0116(transition-leaving-page-content)合进它的 `main` 并推送,还没发版:示例锁定的 AppKitPlus-Release 0.21.0 和最新的 0.22.0 都不含它。含这项修复的版本发出后,把示例锁定的版本升上去即可,`Package.swift` 与示例代码都不用改。 +- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。修复已作为 AppKitPlus 提案 0116(transition-leaving-page-content)随 AppKitPlus-Release 0.23.0 发布;示例还锁在 0.21.0,把锁定的版本升到 0.23.0 即可,示例代码不用改。 ## 决策日志 @@ -80,3 +80,4 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 | 2026-11-14 | 实现完成(第三轮),待用户看过后收尾 | 编译通过,警告仍只有 `Text+Template.swift` 那一条。连续截帧检查了两个栈页的推入:新页完全挡住旧页;栈页、Presentation styles、Wi-Fi 页都铺满详情区,底色与窗口一致。文档判断:不需要另写使用指南或实现说明,没有新术语 | | 2026-11-15 | 返回转场的空白在 AppKitPlus 里修,示例不绕 | 用户同意按「离场页留在原位、只用图层动画移走、结束时再落位」在 AppKitPlus 修。核对 UXKit 27.2 汇编后确认它本身就这样移离场页,AppKitPlus 有意偏离。修复在它的功能分支上做完、本地合进它的 `main`,待发版后升级依赖 | | 2026-11-15 | 后续项改指 AppKitPlus 提案 0116 | AppKitPlus 的修复已以 0116 合进它的 `main` 并推送,原来的功能分支已删除;仍要等 AppKitPlus-Release 发出含它的版本 | +| 2026-11-15 | 落地:合进 `main` 并推送,编号 0013 | 用户要求收尾。验证与 0012 是同一次:`CaseStudies` 的 macOS 版编译通过,全量测试只有那条早就存在的上游失败。返回转场的空白留作后续项:AppKitPlus-Release 0.23.0 已带上修复,示例仍锁在 0.21.0,升级另行决定。文档判断:不需要另写使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 5a107e07d4..e6595228a2 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -17,5 +17,5 @@ | 0009 | [AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中](0009-appkit-more-control-bindings.md) | Implemented | | 0010 | [AppKit 动画案例](0010-appkit-animations-case-study.md) | Implemented | | 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | -| draft | [去掉 AppKitNavigationShim:不再交换系统方法](draft-appkit-remove-shim.md) | In Progress | -| draft | [macOS 示例改用侧边栏外壳与系统设置式排版](draft-appkit-examples-redesign.md) | In Progress | +| 0012 | [去掉 AppKitNavigationShim:不再交换系统方法](0012-appkit-remove-shim.md) | Implemented | +| 0013 | [macOS 示例改用侧边栏外壳与系统设置式排版](0013-appkit-examples-redesign.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index 0c666e3681..f78b86c1cc 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -16,8 +16,8 @@ - [0009-appkit-more-control-bindings.md](Evolutions/0009-appkit-more-control-bindings.md):AppKit 控件绑定第二批——随模型变化的选项、文本视图、集合视图的选中。 - [0010-appkit-animations-case-study.md](Evolutions/0010-appkit-animations-case-study.md):AppKit 动画案例。 - [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 -- [draft-appkit-remove-shim.md](Evolutions/draft-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 -- [draft-appkit-examples-redesign.md](Evolutions/draft-appkit-examples-redesign.md):macOS 示例改用侧边栏外壳与系统设置式排版,每个弹出行标出导航状态,弹出的 sheet 都能关掉。 +- [0012-appkit-remove-shim.md](Evolutions/0012-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 +- [0013-appkit-examples-redesign.md](Evolutions/0013-appkit-examples-redesign.md):macOS 示例改用侧边栏外壳与系统设置式排版,每个弹出行标出导航状态,弹出的 sheet 都能关掉。 ## Internal From ba88dbb7ef2e79c93dd5c11ef2b2d3493c47970d Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 12:10:47 +0800 Subject: [PATCH 136/141] build(examples): pin AppKitPlus-Release 0.23.0 0.23.0 fixes the blank screen a pop slides away in stack navigation. Only the case studies' lockfile moves; Package.swift still asks for 0.21.0 or later, which already allows 0.23.0. --- Documentations/Evolutions/0013-appkit-examples-redesign.md | 3 ++- .../xcshareddata/swiftpm/Package.resolved | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/Documentations/Evolutions/0013-appkit-examples-redesign.md b/Documentations/Evolutions/0013-appkit-examples-redesign.md index e9b03c9f16..de3008aa21 100644 --- a/Documentations/Evolutions/0013-appkit-examples-redesign.md +++ b/Documentations/Evolutions/0013-appkit-examples-redesign.md @@ -58,7 +58,7 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 ## 后续项 -- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。修复已作为 AppKitPlus 提案 0116(transition-leaving-page-content)随 AppKitPlus-Release 0.23.0 发布;示例还锁在 0.21.0,把锁定的版本升到 0.23.0 即可,示例代码不用改。 +- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。修复已作为 AppKitPlus 提案 0116(transition-leaving-page-content)随 AppKitPlus-Release 0.23.0 发布。已完成(2026-11-15):示例锁定的版本升到 0.23.0,示例代码没有改动。 ## 决策日志 @@ -81,3 +81,4 @@ AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按 | 2026-11-15 | 返回转场的空白在 AppKitPlus 里修,示例不绕 | 用户同意按「离场页留在原位、只用图层动画移走、结束时再落位」在 AppKitPlus 修。核对 UXKit 27.2 汇编后确认它本身就这样移离场页,AppKitPlus 有意偏离。修复在它的功能分支上做完、本地合进它的 `main`,待发版后升级依赖 | | 2026-11-15 | 后续项改指 AppKitPlus 提案 0116 | AppKitPlus 的修复已以 0116 合进它的 `main` 并推送,原来的功能分支已删除;仍要等 AppKitPlus-Release 发出含它的版本 | | 2026-11-15 | 落地:合进 `main` 并推送,编号 0013 | 用户要求收尾。验证与 0012 是同一次:`CaseStudies` 的 macOS 版编译通过,全量测试只有那条早就存在的上游失败。返回转场的空白留作后续项:AppKitPlus-Release 0.23.0 已带上修复,示例仍锁在 0.21.0,升级另行决定。文档判断:不需要另写使用指南或实现说明,没有新术语 | +| 2026-11-15 | 示例锁定的 AppKitPlus-Release 升到 0.23.0,`Package.swift` 的下限保持 0.21.0 | 0.23.0 带上了返回转场的修复。用户选定只改示例用的锁定文件、不强制其他使用方升级;`from: "0.21.0"` 本来就允许 0.23.0 | diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index cb9b85505d..ee8c8a8e97 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -6,8 +6,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/AppKitSupportProgram/AppKitPlus-Release", "state" : { - "revision" : "954e6bd30bc452bf54d65793b638e82d3a6a586d", - "version" : "0.21.0" + "revision" : "63039aa889273976aa95087dd0c0c3e109caca9d", + "version" : "0.23.0" } }, { From d32047932a6d02cf87f260e52c3b4245a42e0b78 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 13:20:17 +0800 Subject: [PATCH 137/141] build: require macOS 14 AppKitPlus's next release requires macOS 14, and with the AppKitPlus trait on, SwiftPM rejects this package while it declares less, whatever the app's deployment target. Below macOS 13.3 Swift also loses conformances to protocols with a changed runtime name (swiftlang/swift#94329), and the stack controller's delegate adopts one. Only the two manifests that carry the trait change; the Swift 6.0 and 6.1 manifests keep macOS 10.15. --- Documentations/Evolutions/README.md | 1 + .../Evolutions/draft-raise-macos-minimum.md | 39 +++++++++++++++++++ Documentations/README.md | 1 + Package.swift | 2 +- Package@swift-6.2.swift | 2 +- .../Articles/StackNavigationWithAppKitPlus.md | 2 +- 6 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 Documentations/Evolutions/draft-raise-macos-minimum.md diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index e6595228a2..262daf6488 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -19,3 +19,4 @@ | 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | | 0012 | [去掉 AppKitNavigationShim:不再交换系统方法](0012-appkit-remove-shim.md) | Implemented | | 0013 | [macOS 示例改用侧边栏外壳与系统设置式排版](0013-appkit-examples-redesign.md) | Implemented | +| draft | [把 macOS 下限提到 14](draft-raise-macos-minimum.md) | In Progress | diff --git a/Documentations/Evolutions/draft-raise-macos-minimum.md b/Documentations/Evolutions/draft-raise-macos-minimum.md new file mode 100644 index 0000000000..551591eb28 --- /dev/null +++ b/Documentations/Evolutions/draft-raise-macos-minimum.md @@ -0,0 +1,39 @@ +# Draft - 把 macOS 下限提到 14 + +- **状态**: In Progress +- **创建日期**: 2026-11-15 +- **最后更新**: 2026-11-15 +- **实现分支**: `raise-macos-minimum` + +## 摘要 + +AppKitPlus 的 `main` 已把最低系统提到 macOS 14(AppKitPlus 提案 0117),下一个 AppKitPlus-Release 会在清单里声明 `.macOS(.v14)`。这个 fork 带 AppKitPlus trait 的两份清单仍声明 macOS 12:到那时打开 trait,即使 App 的部署目标更高,SwiftPM 也会因为 fork 自己声明的下限直接报错。另外,部署目标低于 13.3 时,Swift 对改过运行时名的协议做 `as?` 或声明采纳都会悄悄失效(swiftlang/swift#94329)。栈导航内部采纳 `NSNavigationControllerDelegate` 的 `PathDelegate` 正受此影响,只是 AppKitPlus 调用 delegate 前只看它实现了哪些方法、不检查协议,所以还没出问题。这一批不等 AppKitPlus 发版,先把这两份清单的 macOS 下限提到 14。 + +## 方案 + +- `Package.swift`(Xcode 27 用)与 `Package@swift-6.2.swift`(Xcode 26.x 用)的 `.macOS(.v12)` 改成 `.macOS(.v14)`;iOS、tvOS、watchOS 的下限不变。 +- 使用指南 `StackNavigationWithAppKitPlus.md` 里 trait 的系统要求随之改成 macOS 14。 +- 对使用方是破坏性变更:部署目标低于 macOS 14 的 App,以及声明的 macOS 下限低于 14、又依赖这个 fork 的包,升级后都编不过。2026-11-15 核对过依赖这个 fork 的几个 App(XCOrganizer、PrivateSymbols、SymbolViewer、MacKedUpdater、ReverseEngineeringToolbox),部署目标最低是 14.3,都不受影响。 + +没有询问就采用的假设: + +- `Package@swift-6.0.swift` 与 `Package@swift-6.1.swift` 不动,仍是 macOS 10.15:它们没有 AppKitPlus trait,只给 Xcode 16 用;自 0012 起 AppKitNavigation 只能用 Xcode 27 编,这两份只影响其余几个库。 +- 代码里因此变得多余的 macOS 版本判断(`@available(macOS 14, *)`、`#available(…macOS 12…)` 之类)不删:多数在与上游共用的文件里,改了会增加合并上游时的冲突。 +- 下限到 14 后,为 macOS 编译时多出 5 条弃用警告,这一批不改:SwiftUI 的 `onChange(of:perform:)` 4 处(`Bind.swift` 两处、`Alert.swift`、`ConfirmationDialog.swift`,都与上游一字不差),Perception 的 `withPerceptionTracking` 1 处(`Observe.swift`)。前者换成新 API 要按平台分开写,因为 iOS 的下限仍是 15;改了会让这些文件与上游分叉。 +- 不为 `PathDelegate` 的协议采纳单写测试:目前没有哪项可观察的行为受它影响,单测协议采纳等于测编译器本身;下限不低于 13.3,问题的前提就不存在了。 + +## 后续项 + +- AppKitPlus-Release 发出要求 macOS 14 的版本后,再把示例锁定的版本升上去;`Package.swift` 里 AppKitPlus-Release 的版本下限要不要跟着提,到时再定。 +- 上面那 5 条弃用警告要不要改,待用户定。 +- fork 发版时,版本号要体现最低系统提高这一破坏性变更。 +- AppKitNavigation 自己的几处 `@available(macOS 14, *)` 可以删掉;`Perception` trait 在 macOS 上可能不再必需,可以评估。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-15 | Created as Draft | AppKitPlus 下一版要求 macOS 14,fork 两份带 trait 的清单仍是 12,届时打开 trait 会报错;部署目标低于 13.3 还会让栈导航 delegate 的协议采纳在运行时失效 | +| 2026-11-15 | 用户批准,开始实现 | 用户知道这对所有使用方都是破坏性变更,决定现在就提,不等 AppKitPlus 发版 | +| 2026-11-15 | 多出的 5 条弃用警告先不改,交给用户定 | 改前改后各从零编一次对比:多出的只有这 5 条,都在与上游共用的文件里;改不改是在「编译干净」与「少和上游分叉」之间取舍 | +| 2026-11-15 | 实现完成,待用户看过后收尾 | 全量 `swift test` 只有 `ButtonStateTests.testAsyncAnimationWarning` 失败,与改前相同,是 macOS 27.2 上早就存在的上游问题;打开 AppKitPlus trait 的 AppKit 测试全部通过(XCTest 94 个,Swift Testing 78 个);`CaseStudies` 的 macOS 版编译通过。文档判断:使用指南里的系统要求已同步,不需要另写实现说明,没有新术语 | diff --git a/Documentations/README.md b/Documentations/README.md index f78b86c1cc..fb84ed9bab 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -18,6 +18,7 @@ - [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 - [0012-appkit-remove-shim.md](Evolutions/0012-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 - [0013-appkit-examples-redesign.md](Evolutions/0013-appkit-examples-redesign.md):macOS 示例改用侧边栏外壳与系统设置式排版,每个弹出行标出导航状态,弹出的 sheet 都能关掉。 +- [draft-raise-macos-minimum.md](Evolutions/draft-raise-macos-minimum.md):把两份带 AppKitPlus trait 的清单的 macOS 下限从 12 提到 14。 ## Internal diff --git a/Package.swift b/Package.swift index ac04b3b337..6d7436a4f1 100644 --- a/Package.swift +++ b/Package.swift @@ -13,7 +13,7 @@ let package = Package( name: "swift-navigation", platforms: [ .iOS(.v15), - .macOS(.v12), + .macOS(.v14), .tvOS(.v15), .watchOS(.v9), ], diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift index b946c9a760..47faefb807 100644 --- a/Package@swift-6.2.swift +++ b/Package@swift-6.2.swift @@ -13,7 +13,7 @@ let package = Package( name: "swift-navigation", platforms: [ .iOS(.v13), - .macOS(.v12), + .macOS(.v14), .tvOS(.v13), .watchOS(.v6), ], diff --git a/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md b/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md index b0d45bdc18..3f10499fe9 100644 --- a/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md +++ b/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md @@ -33,7 +33,7 @@ any trait replaces them, and AppKitNavigation needs them. In an Xcode project, turn the trait on for the package in the project's Package Dependencies (Xcode 26.4 or later), together with the default traits. -The trait needs Swift 6.2 or later and macOS 12 or later. It adds AppKitPlus-Release 0.21.0 or +The trait needs Swift 6.2 or later and macOS 14 or later. It adds AppKitPlus-Release 0.21.0 or later to your app; AppKitPlus is a dynamic framework that the app embeds. ### A stack driven by a path From a9d9ba22708445a452defccfcaebe8cf614cfbcd Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 14:10:15 +0800 Subject: [PATCH 138/141] docs: record that the macOS 14 deprecation warnings stay for now Raising the floor surfaces five deprecation warnings in files this fork shares with upstream; leaving them keeps upstream merges clean. --- Documentations/Evolutions/draft-raise-macos-minimum.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Documentations/Evolutions/draft-raise-macos-minimum.md b/Documentations/Evolutions/draft-raise-macos-minimum.md index 551591eb28..57c4d9de02 100644 --- a/Documentations/Evolutions/draft-raise-macos-minimum.md +++ b/Documentations/Evolutions/draft-raise-macos-minimum.md @@ -25,7 +25,7 @@ AppKitPlus 的 `main` 已把最低系统提到 macOS 14(AppKitPlus 提案 0117 ## 后续项 - AppKitPlus-Release 发出要求 macOS 14 的版本后,再把示例锁定的版本升上去;`Package.swift` 里 AppKitPlus-Release 的版本下限要不要跟着提,到时再定。 -- 上面那 5 条弃用警告要不要改,待用户定。 +- 那 5 条弃用警告先留着,等上游改用新 API 或提高下限时再跟进。 - fork 发版时,版本号要体现最低系统提高这一破坏性变更。 - AppKitNavigation 自己的几处 `@available(macOS 14, *)` 可以删掉;`Perception` trait 在 macOS 上可能不再必需,可以评估。 @@ -37,3 +37,4 @@ AppKitPlus 的 `main` 已把最低系统提到 macOS 14(AppKitPlus 提案 0117 | 2026-11-15 | 用户批准,开始实现 | 用户知道这对所有使用方都是破坏性变更,决定现在就提,不等 AppKitPlus 发版 | | 2026-11-15 | 多出的 5 条弃用警告先不改,交给用户定 | 改前改后各从零编一次对比:多出的只有这 5 条,都在与上游共用的文件里;改不改是在「编译干净」与「少和上游分叉」之间取舍 | | 2026-11-15 | 实现完成,待用户看过后收尾 | 全量 `swift test` 只有 `ButtonStateTests.testAsyncAnimationWarning` 失败,与改前相同,是 macOS 27.2 上早就存在的上游问题;打开 AppKitPlus trait 的 AppKit 测试全部通过(XCTest 94 个,Swift Testing 78 个);`CaseStudies` 的 macOS 版编译通过。文档判断:使用指南里的系统要求已同步,不需要另写实现说明,没有新术语 | +| 2026-11-15 | 5 条弃用警告先留着 | 用户选定:不改与上游共用的文件,合并上游时不增加冲突 | From 23bc265d8b3b207a24ef54961f63e3882c32809e Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Sun, 15 Nov 2026 15:14:47 +0800 Subject: [PATCH 139/141] docs: number proposal 0014 and mark it implemented The macOS 14 floor lands together with the case studies' move to AppKitPlus-Release 0.23.0, which it was built on. --- ...ft-raise-macos-minimum.md => 0014-raise-macos-minimum.md} | 5 +++-- Documentations/Evolutions/README.md | 2 +- Documentations/README.md | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) rename Documentations/Evolutions/{draft-raise-macos-minimum.md => 0014-raise-macos-minimum.md} (91%) diff --git a/Documentations/Evolutions/draft-raise-macos-minimum.md b/Documentations/Evolutions/0014-raise-macos-minimum.md similarity index 91% rename from Documentations/Evolutions/draft-raise-macos-minimum.md rename to Documentations/Evolutions/0014-raise-macos-minimum.md index 57c4d9de02..72a7188cba 100644 --- a/Documentations/Evolutions/draft-raise-macos-minimum.md +++ b/Documentations/Evolutions/0014-raise-macos-minimum.md @@ -1,6 +1,6 @@ -# Draft - 把 macOS 下限提到 14 +# 0014 - 把 macOS 下限提到 14 -- **状态**: In Progress +- **状态**: Implemented - **创建日期**: 2026-11-15 - **最后更新**: 2026-11-15 - **实现分支**: `raise-macos-minimum` @@ -38,3 +38,4 @@ AppKitPlus 的 `main` 已把最低系统提到 macOS 14(AppKitPlus 提案 0117 | 2026-11-15 | 多出的 5 条弃用警告先不改,交给用户定 | 改前改后各从零编一次对比:多出的只有这 5 条,都在与上游共用的文件里;改不改是在「编译干净」与「少和上游分叉」之间取舍 | | 2026-11-15 | 实现完成,待用户看过后收尾 | 全量 `swift test` 只有 `ButtonStateTests.testAsyncAnimationWarning` 失败,与改前相同,是 macOS 27.2 上早就存在的上游问题;打开 AppKitPlus trait 的 AppKit 测试全部通过(XCTest 94 个,Swift Testing 78 个);`CaseStudies` 的 macOS 版编译通过。文档判断:使用指南里的系统要求已同步,不需要另写实现说明,没有新术语 | | 2026-11-15 | 5 条弃用警告先留着 | 用户选定:不改与上游共用的文件,合并上游时不增加冲突 | +| 2026-11-15 | 落地:推送到 `main`,编号 0014 | 用户看过后要求收尾,与示例锁定 AppKitPlus-Release 0.23.0 的改动一同推送(这一批就叠在那次改动之上)。验证沿用实现完成时那一次:那之后只改过文档。文档判断不变:使用指南已同步,不需要另写实现说明,没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 262daf6488..0b532929ce 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -19,4 +19,4 @@ | 0011 | [可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit](0011-appkit-stack-navigation.md) | Implemented | | 0012 | [去掉 AppKitNavigationShim:不再交换系统方法](0012-appkit-remove-shim.md) | Implemented | | 0013 | [macOS 示例改用侧边栏外壳与系统设置式排版](0013-appkit-examples-redesign.md) | Implemented | -| draft | [把 macOS 下限提到 14](draft-raise-macos-minimum.md) | In Progress | +| 0014 | [把 macOS 下限提到 14](0014-raise-macos-minimum.md) | Implemented | diff --git a/Documentations/README.md b/Documentations/README.md index fb84ed9bab..3947aff547 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -18,7 +18,7 @@ - [0011-appkit-stack-navigation.md](Evolutions/0011-appkit-stack-navigation.md):可选集成 AppKitPlus,把 UIKit 的栈式导航搬到 AppKit。 - [0012-appkit-remove-shim.md](Evolutions/0012-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 - [0013-appkit-examples-redesign.md](Evolutions/0013-appkit-examples-redesign.md):macOS 示例改用侧边栏外壳与系统设置式排版,每个弹出行标出导航状态,弹出的 sheet 都能关掉。 -- [draft-raise-macos-minimum.md](Evolutions/draft-raise-macos-minimum.md):把两份带 AppKitPlus trait 的清单的 macOS 下限从 12 提到 14。 +- [0014-raise-macos-minimum.md](Evolutions/0014-raise-macos-minimum.md):把两份带 AppKitPlus trait 的清单的 macOS 下限从 12 提到 14。 ## Internal From 66acb59a2a976065e6b232d67d6ecb5bf82fda9a Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 27 Nov 2026 16:35:30 +0800 Subject: [PATCH 140/141] refactor(appkit): drop the requirements of WindowBackedContent The protocol has to stay public because it constrains the content of the public sheet and modal methods, but its three underscored requirements were implementation details that came along with it: they hung as public members on every NSWindow and NSAlert, and a type outside the library could conform by implementing them. WindowBackedContent is now a marker protocol with no requirements. The implementation moves, unchanged apart from losing the underscore, into the internal PresentableWindowBackedContent, which only NSWindow and NSAlert conform to. The sheet and modal-loop styles cast the content to it when they begin. Content of a type conformed from outside the library reports an issue and ends right away, as if the user had dismissed it, instead of showing. Nothing downstream conforms to the protocol or calls the removed members. Add the proposal and point to it from 0005. --- .../0005-appkit-presentation-redesign.md | 1 + Documentations/Evolutions/README.md | 1 + ...t-appkit-window-backed-content-marker.html | 423 ++++++++++++++++++ ...aft-appkit-window-backed-content-marker.md | 210 +++++++++ Documentations/README.md | 1 + .../AppKitNavigation/Navigation/Modal.swift | 14 +- .../AppKitNavigation/Navigation/Sheet.swift | 10 +- .../Navigation/WindowBackedContent.swift | 68 ++- .../ModalPresentationTests.swift | 20 + .../PresentationTestSupport.swift | 19 + .../SheetPresentationTests.swift | 21 + 11 files changed, 757 insertions(+), 31 deletions(-) create mode 100644 Documentations/Evolutions/draft-appkit-window-backed-content-marker.html create mode 100644 Documentations/Evolutions/draft-appkit-window-backed-content-marker.md diff --git a/Documentations/Evolutions/0005-appkit-presentation-redesign.md b/Documentations/Evolutions/0005-appkit-presentation-redesign.md index 2a9a89e690..fb578c739b 100644 --- a/Documentations/Evolutions/0005-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/0005-appkit-presentation-redesign.md @@ -414,3 +414,4 @@ final class BindingPresenter { | 2026-11-06 | 实现完成,待用户看过后收尾 | 八步都已提交并推送功能分支,验证结果见第 8 步。文档判断:不需要使用指南,调用方要遵守的契约(`onDismiss` 的时机、等锚点显示、宿主释放与取消 token、`destination` 的 `dismiss` 约定)都写在文档注释和 `swift-navigation-bindings` skill 里;暂不需要实现说明,难懂的决定(模态循环从 run loop 块启动、等被停下的循环返回、用 run loop 检查代替通知、内容强持有)写在代码的 NB 注释和本提案里,收尾时再判断一次;没有要登记的新术语 | | 2026-11-06 | Implemented,编号 0005,落地到 `main` | 用户看过效果后要求收尾。八步全部完成,没做的两项留在后续项(独立的 `TestingSupport` 库;sheet、popover、视图控制器的「宿主释放时收起」没有测试)。验证沿用第 8 步那一轮的结果:合进 `main` 时 `main` 没有别的新提交,合并后的代码与测过的功能分支完全相同。文档判断:不需要使用指南,契约都在文档注释和 `swift-navigation-bindings` skill 里;不需要实现说明,难懂的决定都写在代码的 NB 注释和本提案里,下一任维护者读代码就能看到;没有要登记的新术语 | | 2026-11-08 | 落地后,协议 `ModalContent` 改名为 `WindowBackedContent` | 这个名字读起来像只给 `modal` 用,而 `NSWindow.sheet` 也用它;改名的理由与做法见 [0006](0006-appkit-window-backed-content.md)。本提案正文保持落地时的原样 | +| 2026-11-27 | 落地后,`WindowBackedContent` 去掉全部要求 | 三个带下划线的要求跟着协议公开挂在每个窗口和 alert 上;改成没有要求的标记协议,实现挪进内部协议,弹出时在运行时转换。理由与做法见 [去掉 `WindowBackedContent` 的全部要求](draft-appkit-window-backed-content-marker.md)。本提案正文保持落地时的原样 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 0b532929ce..c6d01889fb 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -20,3 +20,4 @@ | 0012 | [去掉 AppKitNavigationShim:不再交换系统方法](0012-appkit-remove-shim.md) | Implemented | | 0013 | [macOS 示例改用侧边栏外壳与系统设置式排版](0013-appkit-examples-redesign.md) | Implemented | | 0014 | [把 macOS 下限提到 14](0014-raise-macos-minimum.md) | Implemented | +| draft | [去掉 `WindowBackedContent` 的全部要求](draft-appkit-window-backed-content-marker.md) | In Progress | diff --git a/Documentations/Evolutions/draft-appkit-window-backed-content-marker.html b/Documentations/Evolutions/draft-appkit-window-backed-content-marker.html new file mode 100644 index 0000000000..58ab146196 --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-window-backed-content-marker.html @@ -0,0 +1,423 @@ + + + + + + +Draft - 去掉 WindowBackedContent 的全部要求 + + + + +
+ +
+

swift-navigationEvolutionsDraft

+

Draft 去掉 WindowBackedContent 的全部要求

+
+
状态
In Progress
+
最后更新
2026-11-27
+
项目类型
库
+
实现分支
appkit-window-backed-content-marker
+
原文
draft-appkit-window-backed-content-marker.md
+
+
+ + + +
+ +
+

摘要

+

公开协议 WindowBackedContent 去掉三个带下划线的要求(_appKitNavigationWindow、_appKitNavigationBeginSheet(attachedTo:completionHandler:)、_appKitNavigationRunModal()),变成一个没有任何要求的标记协议,NSWindow(连同所有面板)与 NSAlert 照旧遵循。怎么把内容挂成 sheet、怎么跑模态循环,挪进模块内部的协议 PresentableWindowBackedContent,只有 NSWindow 与 NSAlert 在库内遵循它;两个弹出方式在开始弹出时把内容转换成它。

+

库外的类型就算遵循了 WindowBackedContent,弹出时也只会报告一条 issue、当作内容立即结束(binding 复位,onDismiss 调用一次),不会显示任何东西。调用 sheet(...) 与 modal(...) 的代码不受影响。

+
+

为什么协议本身仍是 public

+

NSWindow.sheet(...) 与 NSObject.modal(...) 的 10 个公开重载都用 Content: WindowBackedContent 作泛型约束,Swift 要求公开签名里的约束至少同样公开;@_spi 与 package 都不行。

+
+
+ +
+

架构图

+
    +
  • 新增
  • +
  • 修改
  • +
  • 删除
  • +
  • 不变
  • +
+

改了什么

+
+ + + Public surface + protocol WindowBackedContent {}marker, no requirements + _appKitNavigationWindow + _appKitNavigationBeginSheet(...) + _appKitNavigationRunModal() + NSWindow, NSAlert: WindowBackedContent (empty extension) + + + AppKitNavigation (internal) + protocol PresentableWindowBackedContentappKitNavigationWindow / BeginSheet / RunModal + WindowBackedContent.presentableContent()cast, or reportIssue and nil + SheetStyle, ModalLoopStylebegin: didEnd() when the cast fails + + + refines + + conforms internally + + + +
+

公开面只剩空协议和空遵循;三个要求去掉下划线后搬进内部协议,实现代码不变。

+ +

弹出时的流程

+
+ + sheet(isPresented:) / modal(isPresented:) + BindingPresenter.show + SheetStyle.begin / ModalLoopStyle.begin + presentableContent() + appKitNavigationBeginSheetor RunModal; NSWindow, NSAlert + reportIssue, then didEnd()binding reset, onDismiss once + + + + + + supported + any other type + +
+
+ +
+

改动地图

+
+ + + + + + + + + + + + + + + +
文件 / 类型动作改什么为什么步骤
Navigation/WindowBackedContent.swift · WindowBackedContent修改去掉三个要求,变成空协议;改写文档注释公开面不再暴露实现细节1
同上 · PresentableWindowBackedContent新增internal 协议,承载三个去掉下划线的要求弹出逻辑仍按类型分派,但只在库内可见1
同上 · presentableContent()新增转换成内部协议,失败时 reportIssue 并返回 nil一处集中处理库外遵循的类型1
同上 · NSWindow、NSAlert 的扩展修改公开遵循改成空扩展;实现挪到内部协议的遵循里,从 public 降为 internal同上1
Navigation/Sheet.swift · SheetStyle修改begin 经 presentableContent() 取内容,取不到就 didEnd();end 转换失败直接返回不再读公开要求1
Navigation/Modal.swift · ModalLoopStyle修改同上同上1
Tests/…/PresentationTestSupport.swift修改新增 UnsupportedWindowBackedContent 与 expectUnsupportedContentIssue(_:);补 import AppKitNavigation两个弹出方式的测试共用2
Tests/…/SheetPresentationTests.swift修改新增「不支持的内容」测试覆盖 sheet 的新分支2
Tests/…/ModalPresentationTests.swift修改新增「不支持的内容」测试覆盖 modal 的新分支2
Evolutions/0005-appkit-presentation-redesign.md修改决策日志加一行指向本提案0005 设计了那三个要求3
Evolutions/README.md、Documentations/README.md修改登记本提案索引3
+
+
+ +
+

详细设计

+
+ 协议与转换 +
+
@MainActor
+public protocol WindowBackedContent: AnyObject {}
+
+extension NSWindow: WindowBackedContent {}
+extension NSAlert: WindowBackedContent {}
+
+@MainActor
+protocol PresentableWindowBackedContent: WindowBackedContent {
+  var appKitNavigationWindow: NSWindow { get }
+  func appKitNavigationBeginSheet(
+    attachedTo parentWindow: NSWindow,
+    completionHandler: @escaping @MainActor () -> Void
+  )
+  func appKitNavigationRunModal()
+}
+
+extension WindowBackedContent {
+  func presentableContent() -> (any PresentableWindowBackedContent)? {
+    if let presentableContent = self as? any PresentableWindowBackedContent {
+      return presentableContent
+    }
+    reportIssue("Content of type '\(Self.self)' could not be shown. …")
+    return nil
+  }
+}
+
+
+
+ 两个 style 怎么用它 +
+
// SheetStyle.begin
+guard let parentWindow, let presentableContent = content.presentableContent() else {
+  didEnd()
+  return
+}
+

ModalLoopStyle.begin 同理,在进入 ModalStack.startLoop 之前取内容;原来闭包里用 nonisolated(unsafe) 捕获 content,现在改为捕获转换后的内容。两个 end 转换失败直接返回,因为这样的内容在 begin 里已经结束了。

+

NSWindow 的子类(App 自己的窗口子类、NSSavePanel、NSOpenPanel)继承 NSWindow 的遵循,转换照样成功。

+
+
+
+ issue 的文字 +
+
Content of type '<Type>' could not be shown.
+
+Only 'NSWindow', its subclasses such as the save and open panels, and 'NSAlert' can be
+attached as a sheet or run as a modal. Conforming other types to 'WindowBackedContent' is
+not supported.
+
+
+
+ +
+

调研

+
+ 查证过的事实 +
+
    +
  • 只有两个私有的弹出方式读这三个要求:SheetStyle(Sheet.swift:157)与 ModalLoopStyle(Modal.swift:280)。modalSession(...) 只收 NSWindow,不经过这个协议。
  • +
  • 公开方法的泛型约束用 internal 协议会报 method cannot be declared public because its generic parameter uses an internal type;@_spi 协议也不能出现在不带 SPI 的公开签名里。
  • +
  • 库里已有同样的手法:BindingPresenter.swift:182 用 as? any DismissActionHost 判断内部能力。
  • +
  • 本库对误用一律 reportIssue 后继续运行(Dismiss.swift:49、Push.swift:53 等);SheetStyle.begin 在父窗口已释放时直接 didEnd(),通用层把它当作用户关掉:复位 binding、调用一次 onDismiss。
  • +
  • 下游:/Volumes/Repositories/Private 下除本库外没有代码遵循这个协议或调用 _appKitNavigation…。
  • +
  • Apple 的先例(SwiftUI 的 View._makeView、ShapeStyle._apply)正是现在「公开带下划线」的做法;这次有意偏离它。
  • +
  • Swift 没有「只能用、不能遵循」的协议,「遵循了也用不了」只能从编译期挪到运行期。
  • +
+
+
+
+ +
+

替代方案

+
+ 5 条,都已否决 +
+
    +
  • 保留带下划线的要求(现状):与 SwiftUI 一致、有编译期检查,但成员仍公开挂在每个窗口和 alert 上。用户要求公开面上不留任何要求,否。
  • +
  • 每种内容各一套重载:重载从 10 个变成 20 个,0005 为砍掉这种重复才引入协议,否。
  • +
  • 在 style 里直接 switch 到具体类型:三处各一个 switch,加类型要改三处,否。
  • +
  • 转换失败时 preconditionFailure:本库对误用统一 reportIssue 不崩溃,照项目惯例,否。
  • +
  • 协议改成 @_spi 或 package:公开签名里用不了,编译不过,否。
  • +
+
+
+
+ +
+

影响

+

源码兼容性

+

调用 sheet(...)、modal(...) 的代码不受影响。破坏的只有两种文档早已写明不支持的写法:

+
    +
  • 直接调用 window._appKitNavigationRunModal() 这类下划线成员:改后编译不过,改用 modal(isPresented:) 或 AppKit 自己的 API。
  • +
  • 在库外让自己的类型遵循 WindowBackedContent:改后编译得过,但弹出时报告 issue、什么也不显示,改为返回 NSWindow 或 NSAlert。
  • +
+

下游没有这两种代码,不提供废弃期过渡。

+

ABI 兼容性

+

不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。

+

文档与示例

+

协议的文档注释改写;DocC 首页只列符号名、swift-navigation-bindings skill 不提要求、示例 App 只返回窗口和 alert,都不用改;0005 的决策日志加一行指向本提案。

+

API 演进与废弃策略

+

三个下划线成员直接删除,不保留废弃期,也不需要单独的 major 版本跃迁:它们从来不是受支持的 API。

+
+ +
+

落地步骤

+
    +
  1. 协议改成标记协议,实现挪进内部协议,两个 style 改用转换(改动地图第 1–6 行) +
    • 行为:已有的 sheet 与 modal 测试(窗口、alert、存取面板)全部照旧通过。
    +
  2. +
  3. 不支持的内容报告 issue 并立即结束,补测试(第 7–9 行) +
      +
    • 行为:SheetPresentationTests.testContentOfAnUnsupportedTypeReportsAnIssueAndWritesFalseBack
    • +
    • 行为:ModalPresentationTests.testContentOfAnUnsupportedTypeReportsAnIssueAndWritesFalseBack
    • +
    +
  4. +
  5. 文档(第 10–11 行)
  6. +
+
+ +
+

决策日志

+
+ 4 条,最近一条:内部协议的要求保留 appKitNavigation 前缀 +
+
+ + + + + + + + +
日期变更说明
2026-11-27Created as Draft协议因为是公开方法的泛型约束而必须公开,但它的三个要求只是实现细节,却跟着公开挂在每个窗口和 alert 上
2026-11-27Accepted用户批准去掉全部要求、改在运行时分派,接受失去编译期检查
2026-11-27库外遵循的类型报告 issue 并当作立即结束,不崩溃与本库其他误用的处理方式一致;begin 里直接 didEnd() 是通用层已支持的路径
2026-11-27内部协议的要求保留 appKitNavigation 前缀去掉前缀会与 NSSavePanel.runModal()、NSAlert.window 等 AppKit 成员撞名
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/draft-appkit-window-backed-content-marker.md b/Documentations/Evolutions/draft-appkit-window-backed-content-marker.md new file mode 100644 index 0000000000..b38b8914ff --- /dev/null +++ b/Documentations/Evolutions/draft-appkit-window-backed-content-marker.md @@ -0,0 +1,210 @@ +# Draft - 去掉 `WindowBackedContent` 的全部要求 + +- **状态**: In Progress +- **作者**: JH +- **创建日期**: 2026-11-27 +- **最后更新**: 2026-11-27 +- **所属愿景**: 无 +- **关联提案**: [0005](0005-appkit-presentation-redesign.md)(设计了这个协议和它的三个要求)、[0006](0006-appkit-window-backed-content.md)(把它从 `ModalContent` 改名为现在的名字) +- **实现分支 / PR**: `appkit-window-backed-content-marker` +- **配套文档**: 不需要——见决策日志 +- **网页版**: 同目录同名的 `.html` + +## 摘要 + +公开协议 `WindowBackedContent` 去掉三个带下划线的要求(`_appKitNavigationWindow`、`_appKitNavigationBeginSheet(attachedTo:completionHandler:)`、`_appKitNavigationRunModal()`),变成一个没有任何要求的标记协议,`NSWindow`(连同所有面板)与 `NSAlert` 照旧遵循。怎么把内容挂成 sheet、怎么跑模态循环,挪进模块内部的协议 `PresentableWindowBackedContent`,只有 `NSWindow` 与 `NSAlert` 在库内遵循它;两个弹出方式在开始弹出时把内容转换成它。库外的类型就算遵循了 `WindowBackedContent`,弹出时也只会报告一条 issue、当作内容立即结束(binding 复位,`onDismiss` 调用一次),不会显示任何东西。调用 `sheet(...)` 与 `modal(...)` 的代码不受影响。 + +## 动机 + +这个协议必须是 `public`:`NSWindow.sheet(...)` 的 5 个重载和 `NSObject.modal(...)` 的 5 个重载都用 `Content: WindowBackedContent` 作泛型约束(`Sources/AppKitNavigation/Navigation/Sheet.swift:26`、`Modal.swift:24` 等),Swift 要求公开签名里的约束至少同样公开。但它的三个要求只是库的实现细节,却跟着协议一起公开了: + +- 它们以 `public` 成员的身份挂在每一个 `NSWindow`、`NSAlert` 上,出现在模块的公开接口里。`@_documentation(visibility: private)` 只让 DocC 不生成它们的页面,App 照样能写 `window._appKitNavigationRunModal()`,绕开库对弹出生命周期的管理。 +- 库外的类型实现这三个要求就能遵循协议,于是它们事实上成了一份要长期维护的契约,尽管文档注释写着「不支持」。0005 否掉「把它开放成扩展点」时,理由正是不想多一份契约。 + +去掉要求以后,公开面只剩协议名本身,库内怎么改弹出逻辑都不再牵动公开接口。 + +## 前期调研 + +- **协议怎么用**:只有两个私有的弹出方式读它的要求——`SheetStyle`(`Sheet.swift:157`,`begin` 取窗口并挂 sheet,`end` 取窗口并 `endSheet`)和 `ModalLoopStyle`(`Modal.swift:280`,`begin` 取窗口并跑模态循环,`end` 取窗口并停循环)。`modalSession(...)` 只收 `NSWindow`,不经过这个协议。 +- **为什么不能不公开**:公开方法的泛型约束用了 internal 协议,编译器报 `method cannot be declared public because its generic parameter uses an internal type`;`@_spi` 的协议同样不能出现在不带 SPI 的公开签名里,`package` 只对同一个包可见,外部 App 都调不到这些方法。 +- **库里已有同样的手法**:`BindingPresenter.swift:182` 用 `presentation.content as? any DismissActionHost` 在运行时判断内容能不能装上 dismiss 动作,`DismissActionHost` 是内部协议。 +- **误用怎么报**:本库对调用方的误用一律 `reportIssue` 后照常往下走、不崩溃,例如 `Navigation/Dismiss.swift:49`、`Navigation/Push.swift:53`、`Navigation/NavigationStackController.swift` 的几处。`SheetStyle.begin` 在父窗口已被释放时直接调用 `didEnd()`(`Sheet.swift:172-175`),通用层(`BindingPresenter.show`,`BindingPresenter.swift:150-178`)把这种「刚开始就结束」当作用户关掉:复位 binding、调用一次 `onDismiss`。不支持的内容可以走同一条路。 +- **下游**:搜过 `/Volumes/Repositories/Private` 下除本库以外的全部 Swift 源码,没有代码遵循 `WindowBackedContent`、也没有调用 `_appKitNavigation…`(唯一的命中是 OpenUXKit 示例里名字恰好含 `ModalContent` 的 `ModalContentViewController`,与本库无关)。 +- **Apple 的先例**:SwiftUI 的 `View._makeView`、`ShapeStyle._apply` 这类「公开但带下划线」的要求,正是现在的做法。这次有意偏离它:目标是公开面上一个要求都不留。 +- **Swift 没有「只能用、不能遵循」的协议**:公开协议总能被库外类型遵循,所以只能把「遵循了也用不了」的后果从编译期挪到运行期。 + +## 提议方案 + +- `public protocol WindowBackedContent: AnyObject {}`:保留 `@MainActor` 与 `AnyObject`,去掉全部要求;`NSWindow`、`NSAlert` 用空扩展遵循。文档注释改成「没有要求;只有这几种类型能弹出,遵循别的类型会报告 issue、什么也不显示」。 +- 新增 internal 的 `PresentableWindowBackedContent: WindowBackedContent`,三个要求原样搬进来,去掉下划线;名字保留 `appKitNavigation` 前缀,避免与 AppKit 自己的 `NSSavePanel.runModal()`、`NSAlert.window`、`NSAlert.beginSheetModal(for:completionHandler:)` 撞名。`NSWindow` 与 `NSAlert` 在库内遵循它,实现代码不变。 +- `WindowBackedContent` 上加一个 internal 的 `presentableContent()`:能转换成 `PresentableWindowBackedContent` 就返回它,否则 `reportIssue` 并返回 `nil`。 +- `SheetStyle.begin` 与 `ModalLoopStyle.begin` 先取 `presentableContent()`,取不到就直接 `didEnd()`;两个 `end` 转换失败直接返回(这样的内容在 `begin` 里已经结束了)。 + +### 非目标 + +- 不改任何公开方法的签名,也不改 `modalSession(...)`。 +- 不把协议开放成扩展点,不支持库外类型弹出。 +- 不为删掉的三个下划线成员保留废弃期。 + +## 改动地图 + +| 文件 / 类型 | 动作 | 改什么 | 为什么 | 步骤 | +|---|---|---|---|---| +| `Sources/AppKitNavigation/Navigation/WindowBackedContent.swift` · `WindowBackedContent` | 修改 | 去掉三个要求,变成空协议;改写文档注释 | 公开面不再暴露实现细节 | 1 | +| 同上 · `PresentableWindowBackedContent` | 新增 | internal 协议,承载三个去掉下划线的要求 | 弹出逻辑仍按类型分派,但只在库内可见 | 1 | +| 同上 · `WindowBackedContent.presentableContent()` | 新增 | 转换成内部协议,失败时 `reportIssue` 并返回 `nil` | 一处集中处理库外遵循的类型 | 1 | +| 同上 · `NSWindow`、`NSAlert` 的扩展 | 修改 | 对 `WindowBackedContent` 的遵循改成空扩展;实现挪到对 `PresentableWindowBackedContent` 的遵循里,从 `public` 降为 internal | 同上 | 1 | +| `Sources/AppKitNavigation/Navigation/Sheet.swift` · `SheetStyle` | 修改 | `begin` 经 `presentableContent()` 取内容,取不到就 `didEnd()`;`end` 转换失败直接返回 | 不再读公开要求 | 1 | +| `Sources/AppKitNavigation/Navigation/Modal.swift` · `ModalLoopStyle` | 修改 | 同上 | 同上 | 1 | +| `Tests/AppKitNavigationTests/PresentationTestSupport.swift` | 修改 | 新增库外遵循的 `UnsupportedWindowBackedContent` 与 `expectUnsupportedContentIssue(_:)`;补 `import AppKitNavigation` | 两个弹出方式的测试共用 | 2 | +| `Tests/AppKitNavigationTests/SheetPresentationTests.swift` | 修改 | 新增「不支持的内容」测试 | 覆盖 sheet 的新分支 | 2 | +| `Tests/AppKitNavigationTests/ModalPresentationTests.swift` | 修改 | 新增「不支持的内容」测试 | 覆盖 modal 的新分支 | 2 | +| `Documentations/Evolutions/0005-appkit-presentation-redesign.md` | 修改 | 决策日志加一行指向本提案 | 0005 设计了那三个要求 | 3 | +| `Documentations/Evolutions/README.md`、`Documentations/README.md` | 修改 | 登记本提案 | 索引 | 3 | + +## 架构图 + +改了什么: + +```text + public protocol WindowBackedContent: AnyObject +- var _appKitNavigationWindow: NSWindow +- func _appKitNavigationBeginSheet(attachedTo:completionHandler:) +- func _appKitNavigationRunModal() + ++internal protocol PresentableWindowBackedContent: WindowBackedContent ++ var appKitNavigationWindow: NSWindow ++ func appKitNavigationBeginSheet(attachedTo:completionHandler:) ++ func appKitNavigationRunModal() + + NSWindow (and every panel) + : WindowBackedContent // public, empty ++ : PresentableWindowBackedContent // internal, the old implementation + NSAlert + : WindowBackedContent // public, empty ++ : PresentableWindowBackedContent // internal, the old implementation +``` + +弹出时的流程: + +```text +NSWindow.sheet(isPresented:) / NSObject.modal(isPresented:) +└─ BindingPresenter.show + └─ SheetStyle.begin / ModalLoopStyle.begin ++ ├─ content.presentableContent() ++ │ ├─ NSWindow / NSAlert → any PresentableWindowBackedContent ++ │ └─ any other type → reportIssue(...) → nil → didEnd() ++ │ (binding reset, onDismiss once, nothing shown) + └─ appKitNavigationBeginSheet(...) / appKitNavigationRunModal() +``` + +## 详细设计 + +```swift +@MainActor +public protocol WindowBackedContent: AnyObject {} + +extension NSWindow: WindowBackedContent {} +extension NSAlert: WindowBackedContent {} + +@MainActor +protocol PresentableWindowBackedContent: WindowBackedContent { + var appKitNavigationWindow: NSWindow { get } + func appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) + func appKitNavigationRunModal() +} + +extension WindowBackedContent { + func presentableContent() -> (any PresentableWindowBackedContent)? { + if let presentableContent = self as? any PresentableWindowBackedContent { + return presentableContent + } + reportIssue("Content of type '\(Self.self)' could not be shown. …") + return nil + } +} +``` + +`SheetStyle.begin`: + +```swift +guard let parentWindow, let presentableContent = content.presentableContent() else { + didEnd() + return +} +``` + +`ModalLoopStyle.begin` 同理,在进入 `ModalStack.startLoop` 之前取内容;原来闭包里用 `nonisolated(unsafe)` 捕获 `content`,现在改为捕获 `presentableContent`。 + +issue 的文字: + +```text +Content of type '' could not be shown. + +Only 'NSWindow', its subclasses such as the save and open panels, and 'NSAlert' can be attached as a sheet or run as a modal. Conforming other types to 'WindowBackedContent' is not supported. +``` + +`NSWindow` 的子类(App 自己的窗口子类、`NSSavePanel`、`NSOpenPanel`)继承 `NSWindow` 的遵循,转换照样成功。 + +## 替代方案考量 + +- **保留带下划线的要求(现状)**:与 SwiftUI 的做法一致,也有编译期检查;但三个成员仍然公开挂在每个窗口和 alert 上,库外类型也能照着实现。用户要求公开面上不留任何要求,否。 +- **每种内容各一套重载、去掉协议**:`sheet` 与 `modal` 的重载从 10 个变成 20 个。0005 为了砍掉这种重复才引入协议,否。 +- **在两个 style 里直接 `switch` 到 `NSWindow` / `NSAlert`**:取窗口、挂 sheet、跑模态三处各写一个 `switch`,每加一种内容要改三处;内部协议只需一次转换,加类型只加一个遵循,否。 +- **转换失败时 `preconditionFailure`**:Apple 的规则是程序员的错误用 precondition;但本库对误用统一 `reportIssue` 后继续运行(Dismiss、Push、NavigationStackController),照项目惯例,否。 +- **把协议改成 `@_spi` 或 `package`**:公开方法签名里用不了,编译不过,否。 + +## 影响 + +### 源码兼容性(source compatibility) + +调用 `sheet(...)`、`modal(...)` 的代码不受影响,返回 `NSWindow`、`NSAlert` 或面板的闭包照旧编译、照旧弹出。 + +破坏的只有两种写法,都是文档早已写明不支持的: + +- **直接调用三个下划线成员**,例如 `window._appKitNavigationRunModal()`:改后编译不过。改法是改用 `modal(isPresented:)` 或 AppKit 自己的 `NSApplication.runModal(for:)`。 +- **在库外让自己的类型遵循 `WindowBackedContent`**:改前要实现三个要求,能弹出;改后编译得过,但弹出时报告 issue、什么也不显示。改法是返回一个 `NSWindow` 或 `NSAlert`。 + +下游没有这两种代码(见「前期调研」)。删掉的成员本来就带下划线、不在文档里,不提供 `@available(*, deprecated)` 过渡。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +本仓库只有 `AppKitNavigation` 及其测试受影响。下游仓库里没有遵循这个协议、也没有调用那三个成员的代码。 + +### 文档与示例 + +- 协议的文档注释改写,说明它没有要求、遵循别的类型会怎样。 +- DocC 首页(`Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md:88`)只列符号名,不用改;三个要求原本就不出现在文档里。 +- `swift-navigation-bindings` skill 只说「任意 `WindowBackedContent`:`NSWindow`(及所有面板)、`NSAlert`」,不提要求,不用改。 +- 示例 App 只返回窗口和 alert,不用改。 +- 0005 的正文保持原样,只在它的决策日志里加一行指向本提案。 + +## API 演进与废弃策略 + +- 三个下划线成员直接删除,不保留废弃期:它们从来不是受支持的 API。 +- 不需要单独的 major 版本跃迁。 + +## 落地步骤 + +1. **协议改成标记协议,实现挪进内部协议,两个 style 改用转换** —— 改动地图第 1–6 行 + - 行为:已有的 sheet 与 modal 测试(窗口、alert、存取面板)全部照旧通过。 +2. **不支持的内容报告 issue 并立即结束,补测试** —— 改动地图第 7–9 行 + - 行为:`SheetPresentationTests.testContentOfAnUnsupportedTypeReportsAnIssueAndWritesFalseBack`——报告 issue、binding 复位、`onDismiss` 调用一次、没有挂上 sheet。 + - 行为:`ModalPresentationTests.testContentOfAnUnsupportedTypeReportsAnIssueAndWritesFalseBack`——报告 issue、binding 复位、`onDismiss` 调用一次、没有跑模态循环。 +3. **文档** —— 改动地图第 10–11 行 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-11-27 | Created as Draft | 协议因为是公开方法的泛型约束而必须公开,但它的三个要求只是实现细节,却跟着公开挂在每个窗口和 alert 上 | +| 2026-11-27 | Accepted | 用户批准去掉全部要求、改在运行时分派,接受失去编译期检查 | +| 2026-11-27 | 库外遵循的类型报告 issue 并当作立即结束,不崩溃 | 与本库其他误用的处理方式一致;`begin` 里直接 `didEnd()` 是通用层已支持的路径 | +| 2026-11-27 | 内部协议的要求保留 `appKitNavigation` 前缀 | 去掉前缀会与 `NSSavePanel.runModal()`、`NSAlert.window` 等 AppKit 成员撞名 | diff --git a/Documentations/README.md b/Documentations/README.md index 3947aff547..c8ffee4b7b 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -19,6 +19,7 @@ - [0012-appkit-remove-shim.md](Evolutions/0012-appkit-remove-shim.md):去掉 AppKitNavigationShim,不再交换系统方法。 - [0013-appkit-examples-redesign.md](Evolutions/0013-appkit-examples-redesign.md):macOS 示例改用侧边栏外壳与系统设置式排版,每个弹出行标出导航状态,弹出的 sheet 都能关掉。 - [0014-raise-macos-minimum.md](Evolutions/0014-raise-macos-minimum.md):把两份带 AppKitPlus trait 的清单的 macOS 下限从 12 提到 14。 +- [draft-appkit-window-backed-content-marker.md](Evolutions/draft-appkit-window-backed-content-marker.md):`WindowBackedContent` 去掉全部要求,变成标记协议,弹出逻辑挪进内部协议。 ## Internal diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift index 56fe0893a1..9128895df6 100644 --- a/Sources/AppKitNavigation/Navigation/Modal.swift +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -283,8 +283,12 @@ transaction: UITransaction, didEnd: @escaping @MainActor () -> Void ) { - let window = content._appKitNavigationWindow - nonisolated(unsafe) let content = content + guard let presentableContent = content.presentableContent() else { + didEnd() + return + } + let window = presentableContent.appKitNavigationWindow + nonisolated(unsafe) let modalContent = presentableContent ModalStack.startLoop { guard !ModalStack.takeEndRequest(for: window) else { // NB: Ended before it got to run. @@ -301,7 +305,7 @@ } } } - content._appKitNavigationRunModal() + modalContent.appKitNavigationRunModal() closeObserver.invalidate() ModalStack.modalDidEnd(window) // NB: Ending a modal loop does not take its window off screen. Alerts and panels order @@ -314,7 +318,9 @@ } func end(_ content: Content, transaction: UITransaction) { - ModalStack.end(content._appKitNavigationWindow) { + // NB: Content that could not be shown has already ended. + guard let presentableContent = content as? any PresentableWindowBackedContent else { return } + ModalStack.end(presentableContent.appKitNavigationWindow) { NSApplication.shared.stopModal() } } diff --git a/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift index 7040828588..af4d86af73 100644 --- a/Sources/AppKitNavigation/Navigation/Sheet.swift +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -169,12 +169,12 @@ transaction: UITransaction, didEnd: @escaping @MainActor () -> Void ) { - guard let parentWindow else { + guard let parentWindow, let presentableContent = content.presentableContent() else { didEnd() return } - let sheetWindow = content._appKitNavigationWindow - content._appKitNavigationBeginSheet(attachedTo: parentWindow) { + let sheetWindow = presentableContent.appKitNavigationWindow + presentableContent.appKitNavigationBeginSheet(attachedTo: parentWindow) { // NB: The completion handler runs as the sheet starts to leave, while it is still on // screen. _ = RunLoopWait.until({ !sheetWindow.isVisible }, then: didEnd) @@ -182,7 +182,9 @@ } func end(_ content: Content, transaction: UITransaction) { - let sheetWindow = content._appKitNavigationWindow + // NB: Content that could not be shown has already ended. + guard let presentableContent = content as? any PresentableWindowBackedContent else { return } + let sheetWindow = presentableContent.appKitNavigationWindow // NB: A sheet still queued behind another one has no sheet parent yet. (sheetWindow.sheetParent ?? parentWindow)?.endSheet(sheetWindow) } diff --git a/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift index 9cef52937c..5b8ea0f033 100644 --- a/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift +++ b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift @@ -10,33 +10,59 @@ /// ``ObjectiveC/NSObject/modal(isPresented:onDismiss:content:)`` to run it as a modal. /// `NSWindow`, and through it every panel, conforms, as does `NSAlert`. /// - /// The requirements are implementation details of AppKitNavigation. Conforming other types is not - /// supported. + /// The protocol has no requirements: AppKitNavigation knows how to show each of these types. + /// Conforming other types is not supported; presenting one reports an issue and shows nothing. @MainActor - public protocol WindowBackedContent: AnyObject { + public protocol WindowBackedContent: AnyObject {} + + extension NSWindow: WindowBackedContent {} + + extension NSAlert: WindowBackedContent {} + + /// Content that AppKitNavigation knows how to attach as a sheet and run as a modal. + /// + /// Only the types that conform to ``WindowBackedContent`` inside AppKitNavigation conform to + /// this protocol. + @MainActor + protocol PresentableWindowBackedContent: WindowBackedContent { /// The window that shows the content. - @_documentation(visibility: private) - var _appKitNavigationWindow: NSWindow { get } + var appKitNavigationWindow: NSWindow { get } /// Attaches the content to `parentWindow` as a sheet, and calls `completionHandler` once the /// sheet has ended. - @_documentation(visibility: private) - func _appKitNavigationBeginSheet( + func appKitNavigationBeginSheet( attachedTo parentWindow: NSWindow, completionHandler: @escaping @MainActor () -> Void ) /// Runs the content in an application-modal loop, and returns once the loop has ended. - @_documentation(visibility: private) - func _appKitNavigationRunModal() + func appKitNavigationRunModal() + } + + extension WindowBackedContent { + /// The content as AppKitNavigation shows it, or `nil`, after reporting an issue, when the + /// content is of a type conformed to ``WindowBackedContent`` outside AppKitNavigation. + func presentableContent() -> (any PresentableWindowBackedContent)? { + if let presentableContent = self as? any PresentableWindowBackedContent { + return presentableContent + } + reportIssue( + """ + Content of type '\(Self.self)' could not be shown. + + Only 'NSWindow', its subclasses such as the save and open panels, and 'NSAlert' can be \ + attached as a sheet or run as a modal. Conforming other types to 'WindowBackedContent' is \ + not supported. + """ + ) + return nil + } } - extension NSWindow: WindowBackedContent { - @_documentation(visibility: private) - public var _appKitNavigationWindow: NSWindow { self } + extension NSWindow: PresentableWindowBackedContent { + var appKitNavigationWindow: NSWindow { self } - @_documentation(visibility: private) - public func _appKitNavigationBeginSheet( + func appKitNavigationBeginSheet( attachedTo parentWindow: NSWindow, completionHandler: @escaping @MainActor () -> Void ) { @@ -56,8 +82,7 @@ } } - @_documentation(visibility: private) - public func _appKitNavigationRunModal() { + func appKitNavigationRunModal() { if let savePanel = self as? NSSavePanel { if savePanel.runModal() == .OK { savePanel.appKitNavigationWriteConfirmedChoice() @@ -68,12 +93,10 @@ } } - extension NSAlert: WindowBackedContent { - @_documentation(visibility: private) - public var _appKitNavigationWindow: NSWindow { window } + extension NSAlert: PresentableWindowBackedContent { + var appKitNavigationWindow: NSWindow { window } - @_documentation(visibility: private) - public func _appKitNavigationBeginSheet( + func appKitNavigationBeginSheet( attachedTo parentWindow: NSWindow, completionHandler: @escaping @MainActor () -> Void ) { @@ -82,8 +105,7 @@ } } - @_documentation(visibility: private) - public func _appKitNavigationRunModal() { + func appKitNavigationRunModal() { _ = runModal() } } diff --git a/Tests/AppKitNavigationTests/ModalPresentationTests.swift b/Tests/AppKitNavigationTests/ModalPresentationTests.swift index 6325ba1c26..bb59272488 100644 --- a/Tests/AppKitNavigationTests/ModalPresentationTests.swift +++ b/Tests/AppKitNavigationTests/ModalPresentationTests.swift @@ -448,6 +448,26 @@ XCTAssertNil(presentedWindow, "The window is still held after its modal ended") } + @MainActor + func testContentOfAnUnsupportedTypeReportsAnIssueAndWritesFalseBack() { + let host = NSObject() + @UIBinding var isPresented = false + var dismissCount = 0 + host.modal(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { + UnsupportedWindowBackedContent() + } + abortModalLoops(after: 5) + + expectUnsupportedContentIssue { + isPresented = true + _ = waitUntil { !isPresented } + } + + XCTAssertFalse(isPresented, "Content that could not be shown did not write 'false' back") + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run exactly once") + XCTAssertNil(NSApplication.shared.modalWindow, "A modal loop ran for unsupported content") + } + // MARK: - Owner and token @MainActor diff --git a/Tests/AppKitNavigationTests/PresentationTestSupport.swift b/Tests/AppKitNavigationTests/PresentationTestSupport.swift index 8589f72285..ce6b234111 100644 --- a/Tests/AppKitNavigationTests/PresentationTestSupport.swift +++ b/Tests/AppKitNavigationTests/PresentationTestSupport.swift @@ -1,5 +1,6 @@ #if canImport(AppKit) && !targetEnvironment(macCatalyst) import AppKit + import AppKitNavigation import XCTest // NB: The presentation tests are synchronous XCTest methods on purpose. They wait by spinning @@ -171,4 +172,22 @@ final class WeakReference { weak var object: Object? } + + /// Content of a type conformed to `WindowBackedContent` outside AppKitNavigation, which the + /// library does not know how to show. + @MainActor + final class UnsupportedWindowBackedContent: WindowBackedContent {} + + extension XCTestCase { + /// Expects `body` to report that content of type `UnsupportedWindowBackedContent` could not be + /// shown, and fails if it does not. + @MainActor + func expectUnsupportedContentIssue(_ body: () -> Void) { + let options = XCTExpectedFailure.Options() + options.issueMatcher = { issue in + issue.compactDescription.contains("'UnsupportedWindowBackedContent' could not be shown") + } + XCTExpectFailure("Unsupported content reports an issue", options: options, failingBlock: body) + } + } #endif diff --git a/Tests/AppKitNavigationTests/SheetPresentationTests.swift b/Tests/AppKitNavigationTests/SheetPresentationTests.swift index ec0b828755..b1e62e2301 100644 --- a/Tests/AppKitNavigationTests/SheetPresentationTests.swift +++ b/Tests/AppKitNavigationTests/SheetPresentationTests.swift @@ -294,5 +294,26 @@ "Cancelling the panel did not end the sheet" ) } + + // MARK: - Unsupported content + + @MainActor + func testContentOfAnUnsupportedTypeReportsAnIssueAndWritesFalseBack() { + let host = makeHost() + @UIBinding var isPresented = false + var dismissCount = 0 + host.window.sheet(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { + UnsupportedWindowBackedContent() + } + + expectUnsupportedContentIssue { + isPresented = true + _ = waitUntil { !isPresented } + } + + XCTAssertFalse(isPresented, "Content that could not be shown did not write 'false' back") + XCTAssertEqual(dismissCount, 1, "'onDismiss' did not run exactly once") + XCTAssertNil(host.window.attachedSheet, "A sheet was attached for unsupported content") + } } #endif From 2842089d4c096af7ed261ecd7657821ffdeb6166 Mon Sep 17 00:00:00 2001 From: Mx-Iris Date: Fri, 27 Nov 2026 16:38:37 +0800 Subject: [PATCH 141/141] docs: number proposal 0015 and mark it implemented --- .../0005-appkit-presentation-redesign.md | 2 +- ...015-appkit-window-backed-content-marker.html} | 16 +++++++++------- ... 0015-appkit-window-backed-content-marker.md} | 10 ++++++---- Documentations/Evolutions/README.md | 2 +- Documentations/README.md | 2 +- 5 files changed, 18 insertions(+), 14 deletions(-) rename Documentations/Evolutions/{draft-appkit-window-backed-content-marker.html => 0015-appkit-window-backed-content-marker.html} (94%) rename Documentations/Evolutions/{draft-appkit-window-backed-content-marker.md => 0015-appkit-window-backed-content-marker.md} (93%) diff --git a/Documentations/Evolutions/0005-appkit-presentation-redesign.md b/Documentations/Evolutions/0005-appkit-presentation-redesign.md index fb578c739b..06f7eecbb3 100644 --- a/Documentations/Evolutions/0005-appkit-presentation-redesign.md +++ b/Documentations/Evolutions/0005-appkit-presentation-redesign.md @@ -414,4 +414,4 @@ final class BindingPresenter { | 2026-11-06 | 实现完成,待用户看过后收尾 | 八步都已提交并推送功能分支,验证结果见第 8 步。文档判断:不需要使用指南,调用方要遵守的契约(`onDismiss` 的时机、等锚点显示、宿主释放与取消 token、`destination` 的 `dismiss` 约定)都写在文档注释和 `swift-navigation-bindings` skill 里;暂不需要实现说明,难懂的决定(模态循环从 run loop 块启动、等被停下的循环返回、用 run loop 检查代替通知、内容强持有)写在代码的 NB 注释和本提案里,收尾时再判断一次;没有要登记的新术语 | | 2026-11-06 | Implemented,编号 0005,落地到 `main` | 用户看过效果后要求收尾。八步全部完成,没做的两项留在后续项(独立的 `TestingSupport` 库;sheet、popover、视图控制器的「宿主释放时收起」没有测试)。验证沿用第 8 步那一轮的结果:合进 `main` 时 `main` 没有别的新提交,合并后的代码与测过的功能分支完全相同。文档判断:不需要使用指南,契约都在文档注释和 `swift-navigation-bindings` skill 里;不需要实现说明,难懂的决定都写在代码的 NB 注释和本提案里,下一任维护者读代码就能看到;没有要登记的新术语 | | 2026-11-08 | 落地后,协议 `ModalContent` 改名为 `WindowBackedContent` | 这个名字读起来像只给 `modal` 用,而 `NSWindow.sheet` 也用它;改名的理由与做法见 [0006](0006-appkit-window-backed-content.md)。本提案正文保持落地时的原样 | -| 2026-11-27 | 落地后,`WindowBackedContent` 去掉全部要求 | 三个带下划线的要求跟着协议公开挂在每个窗口和 alert 上;改成没有要求的标记协议,实现挪进内部协议,弹出时在运行时转换。理由与做法见 [去掉 `WindowBackedContent` 的全部要求](draft-appkit-window-backed-content-marker.md)。本提案正文保持落地时的原样 | +| 2026-11-27 | 落地后,`WindowBackedContent` 去掉全部要求 | 三个带下划线的要求跟着协议公开挂在每个窗口和 alert 上;改成没有要求的标记协议,实现挪进内部协议,弹出时在运行时转换。理由与做法见 [0015](0015-appkit-window-backed-content-marker.md)。本提案正文保持落地时的原样 | diff --git a/Documentations/Evolutions/draft-appkit-window-backed-content-marker.html b/Documentations/Evolutions/0015-appkit-window-backed-content-marker.html similarity index 94% rename from Documentations/Evolutions/draft-appkit-window-backed-content-marker.html rename to Documentations/Evolutions/0015-appkit-window-backed-content-marker.html index 58ab146196..ad9e6ad5f3 100644 --- a/Documentations/Evolutions/draft-appkit-window-backed-content-marker.html +++ b/Documentations/Evolutions/0015-appkit-window-backed-content-marker.html @@ -4,7 +4,7 @@ -Draft - 去掉 WindowBackedContent 的全部要求 +0015 - 去掉 WindowBackedContent 的全部要求