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/ diff --git a/Documentations/Evolutions/0001-appkit-navigation-cleanup.md b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md new file mode 100644 index 0000000000..c91e40392e --- /dev/null +++ b/Documentations/Evolutions/0001-appkit-navigation-cleanup.md @@ -0,0 +1,69 @@ +# 0001 - AppKitNavigation 清理:警告、重复代理和多余依赖 + +- **状态**: Implemented +- **创建日期**: 2026-11-04 +- **最后更新**: 2026-11-04 +- **实现分支**: `appkit-navigation-cleanup` + +## 摘要 + +不改用法,把 AppKitNavigation 收拾干净:清掉 fork 自己代码里的 14 条编译警告(其中 3 条在以后的 Swift 语言模式里会变成错误),把 `NSFontManager` 复制出来的那一整套动作代理并回通用实现,去掉只为两个私有数组引入的 `IdentifiedCollections` 依赖,给加在 AppKit 类上的 `@objc` 成员加库前缀,收回一个没必要公开的遵循,删掉文档目录里从 UIKit 抄来的页面。起因是上一批修 bug 时,同样的两个问题要在两份代理里各修一遍;fork 的依赖和 lockfile 也比上游多出两个包。实现中发现 `NSColorPanel.bind(color:)` 一调用就崩溃,用户决定在这一批一起修掉;用户看过后,又要求修掉与上游共用代码里的警告和 Examples 的编译错误(第 9 步)。 + +## 方案 + +先补测试,再动代码: + +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`,所以只共享内部实现,公开签名不变。实际做法:`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`,库里已有同样的写法。 +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 实际解析出的版本一致。 + +没有询问就采用的假设: + +- 公开 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)),属于大型重构,另起完整档提案;新功能各自另起提案。(已由 [0005](0005-appkit-presentation-redesign.md) 完成。) + +## 后续项 + +- 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) 在同一分支上提交。) + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 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 | 现有的两条面板测试在调用私有方法前先确认它存在 | 方法不在时直接调用会让整个测试进程崩溃,金丝雀测试的结果也就看不到了 | +| 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 不用改(公开用法没变) | +| 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 的库和测试,只剩上游那一条警告 | +| 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 编得过 | +| 2026-11-04 | Implemented,编号 0001,落地到 `main` | 用户看过效果后要求收尾。九步全部完成;没做的两项留在后续项(测试进程中途以 0 退出、`NSPathControl` 构造器标签)。文档判断:不需要使用指南或实现说明,没有新的调用契约,难懂的决定都写在代码注释和本提案里;没有新术语;README 和 `swift-navigation-bindings` skill 不用改,公开用法没变 | diff --git a/Documentations/Evolutions/0002-appkit-test-run-loop-exit.md b/Documentations/Evolutions/0002-appkit-test-run-loop-exit.md new file mode 100644 index 0000000000..03a3aa41e2 --- /dev/null +++ b/Documentations/Evolutions/0002-appkit-test-run-loop-exit.md @@ -0,0 +1,44 @@ +# 0002 - AppKit 测试在 `swift test` 下不再中途以 0 退出 + +- **状态**: Implemented +- **创建日期**: 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` 测试计划里没有 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 上用 `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` 的两条链接器警告)。 + +没有询问就采用的假设: + +- trait 放在 `AppKitNavigationTests` 里,不新建 `TestingSupport` target:只有这一个 target 需要它,新建 target 又要改四份与上游共用的包清单。 +- 不改 `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` 上同样如此(这个测试和它测的代码在本分支上没有改动)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 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` 上同样存在 | +| 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/0003-appkit-common-control-bindings.md b/Documentations/Evolutions/0003-appkit-common-control-bindings.md new file mode 100644 index 0000000000..3ec463bfd2 --- /dev/null +++ b/Documentations/Evolutions/0003-appkit-common-control-bindings.md @@ -0,0 +1,67 @@ +# 0003 - AppKit 常用控件的类型化绑定 + +- **状态**: Implemented +- **创建日期**: 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。改成三部分都可选——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:)`。 +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 首页「绑定」一组登记了 `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 全新构建,本包代码零警告。 + +没有询问就采用的假设: + +- 参数标签用 `selection:`、`options:`,照 SwiftUI 的 `Picker(selection:)` 和 Cocoa 绑定的 `content` / `selectedObject`;现有的 `bind(selectedSegment:)` 保留不动。 +- 模型里的值不在 `options` 里时,用 `reportIssue` 报出来:弹出按钮和分段控件取消选中,标签页保持原样。用户选中了 `options` 之外的项(例如菜单里另加的项)时,同样报出来,不写回。 +- 勾选框不支持混合状态:`.on` 对应 `true`,其余都是 `false`。 +- 选项列表在绑定时一次给定;菜单内容随模型变化的情况这次不做。 +- 分栏折叠只在改模型时带了动画(`withAppKitAnimation`,或绑定自带的事务)才带动画,与库里其他绑定的做法一致。 +- 分栏和标签页不加便捷构造器:它们随视图控制器创建,构造器没有可省的步骤。 +- 只改 fork 独有的 AppKitNavigation,不碰与上游共用的 SwiftNavigation 核心。各项目改用新绑定不在这一批。 + +## 后续项 + +- 各项目要用新绑定,得先给 fork 打一个包含它们的新版本(目前最新是 2.11.100),再把约 50 处手写代码换掉。 +- 菜单内容随模型变化(比如 XCOrganizer 在 `observe {}` 里重建标签菜单)还得手写:`options` 只在绑定时给一次。 +- 勾选框的混合状态没有对应的绑定。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-05 | 先做常用控件的类型化绑定,表格选中绑定、状态驱动的独立窗口、简化 `observe` 写法留到以后 | 用户选定。调查中这一块手写代码的处数最多,写法与现有绑定一致,没有设计上的未知数 | +| 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 | 菜单项的新扩展同样标 `@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/0004-appkit-table-selection-bindings.md b/Documentations/Evolutions/0004-appkit-table-selection-bindings.md new file mode 100644 index 0000000000..2ca444eb64 --- /dev/null +++ b/Documentations/Evolutions/0004-appkit-table-selection-bindings.md @@ -0,0 +1,68 @@ +# 0004 - 表格与大纲的选中绑定、大纲的展开状态绑定 + +- **状态**: Implemented +- **创建日期**: 2026-11-05 +- **最后更新**: 2026-11-06 +- **实现分支**: `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`;生成文档没有新的 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 全新构建,本包代码零警告。 + +没有询问就采用的假设: + +- 只做单选;多选以后另做。 +- 标识要求 `Hashable`,与 diffable 数据源和展开状态用的 `Set` 一致。 +- 通过表格、大纲发出的通知得知用户的改动,不占用、也不替换 app 自己的 delegate。 +- 绑定不负责滚动到选中的行。 +- 数据重新加载后,绑定在两种情况下重新对一次选中和展开:绑定的值变了,或者 `row`、`itemIdentifier` 闭包里读到的可观察状态变了。diffable 数据源应用快照时,表格自己会让选中跟着条目走;新条目的展开状态应该放进快照里。 +- 只改 fork 独有的 AppKitNavigation;各项目改用新绑定不在这一批。 + +## 后续项 + +- 多选(绑定一个 `Set`)和 `NSCollectionView` 的选中这次没做。 +- 各项目要用,得先给 fork 打一个包含它们的新版本,再把约 20 处手写的选中同步换掉。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-11-05 | 行和标识用两个查找函数对应,另给 AppKit 自带的 diffable 数据源一个简写 | 用户选定。diffable 数据源直接传它自己的两个方法,普通数组和对象树写两个闭包,任何数据源都能用 | +| 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 不用改;没有新术语 | +| 2026-11-06 | Implemented,编号 0004,落地到 `main` | 用户看过后要求收尾。四步全部完成;多选、`NSCollectionView` 的选中和给 fork 打新版本留在后续项。文档判断同上一行,没有新术语 | diff --git a/Documentations/Evolutions/0005-appkit-presentation-redesign.md b/Documentations/Evolutions/0005-appkit-presentation-redesign.md new file mode 100644 index 0000000000..06f7eecbb3 --- /dev/null +++ b/Documentations/Evolutions/0005-appkit-presentation-redesign.md @@ -0,0 +1,417 @@ +# 0005 - AppKit 弹出 API 重做:生命周期收进一层,重载合并 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-06 +- **最后更新**: 2026-11-06 +- **所属愿景**: 无 +- **关联提案**: [0001 - AppKitNavigation 清理](0001-appkit-navigation-cleanup.md)(把这次重构留给了单独的完整档提案) +- **实现分支 / PR**: `appkit-presentation-redesign`,已合进 `main` +- **配套文档**: 无(调用方契约写在文档注释里,难懂的实现决定写在代码注释和本提案里) + +## 摘要 + +把 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 步的测试在 macOS 27.2 上复现了 1–5 和 8,第 8 条里对 alert 的猜测被测试否定(见该行)。本机依赖这个 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 | 存取面板作为 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`)永远走不到 | 没修过;起草本提案时发现 | + +### 结构上的问题 + +- **重复**:四个文件共 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(_:)` | + +- **怎么等**:所有「等」——等窗口显示、等视图进窗口、等工具栏显示、等 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 会丢掉那次停止请求,旧循环再也不返回。所以本库请某个循环停下后,新的模态循环先排队,等它返回再启动;窗口关闭按钮触发的停止也走同一条路。 + +### 存放与清理 + +- 每个 `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`、监听窗口的遮挡与 key、main 通知**:起草时的方案。前者要替换每个视图的一个系统方法;后者在测试进程里一个都不发(见「怎么等」)。实现时改用 run loop 观察者检查条件,两者都不需要了。 +- **保留全局单例、只修泄漏**:每次弹出各自观察以后,全局状态就没有存在的理由了。 +- **存取面板沿用 `@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`、`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`。 + +### 文档与示例 + +- 公开 API 全部补上文档注释,包括 `ModalContent`。 +- 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,不用改。 + +## API 演进与废弃策略 + +- 被替代的旧 API 直接删除,不标 `deprecated`、不设废弃期。理由:这些 API 是 fork 独有的,上游没有;本机依赖这个 fork 的项目没有调用点受影响;保留旧名会让重载数量翻倍,和这次收敛重载的目标相反。这偏离了 API 设计规范「改名时保留旧名并标 `renamed:`」的默认做法,偏离的理由就是上面这几条。 +- 不跃迁 semver major:fork 的版本号跟随上游的 2.11,自己的改动用 100 以上的补丁号(最近一次是 2.11.101)。下一个版本号在发版时再定。 + +## 落地步骤 + +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 的关动画;删除 `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. **文档**(已完成):文档注释已随第 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。结果: + - 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 步才删除。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 有「从 API 签名看不出来的调用方契约」就写使用指南;有「下次维护会踩、代码本身看不出来的决策」就写实现说明。写了就登记到头部的「配套文档」。候选的实现说明内容:模态循环为什么要在两种 run loop 模式里启动、为什么要等上层模态先结束、内容为什么要强持有。 +- **有没有引入新术语** —— 有就同批次登记进术语表(项目级 `Documentations/Glossary.md`,跨项目通用的登记到全局术语表)。 + +## 后续项 + +- AppKit 测试的共享辅助(`PresentationTestSupport.swift` 里的等待、建窗口、记录 popover)将来可以移进一个独立的 `TestingSupport` 测试库;这要改四份 `Package*.swift`,不在这一批。 +- 「宿主释放时收起内容」只在 modal 上有测试。sheet、popover 和视图控制器的情形没有测:AppKit 在内容显示期间多半还持有宿主(sheet 的父窗口、popover 的锚点视图、弹出它的控制器),宿主能不能在那时释放,还没有验证。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 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 | 用户批准,开始实现 | +| 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` 一致 | +| 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 | +| 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 能正常关掉它 | +| 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` 也用它;改名的理由与做法见 [0006](0006-appkit-window-backed-content.md)。本提案正文保持落地时的原样 | +| 2026-11-27 | 落地后,`WindowBackedContent` 去掉全部要求 | 三个带下划线的要求跟着协议公开挂在每个窗口和 alert 上;改成没有要求的标记协议,实现挪进内部协议,弹出时在运行时转换。理由与做法见 [0015](0015-appkit-window-backed-content-marker.md)。本提案正文保持落地时的原样 | diff --git a/Documentations/Evolutions/0006-appkit-window-backed-content.md b/Documentations/Evolutions/0006-appkit-window-backed-content.md new file mode 100644 index 0000000000..d5e9c0b64a --- /dev/null +++ b/Documentations/Evolutions/0006-appkit-window-backed-content.md @@ -0,0 +1,30 @@ +# 0006 - 把 `ModalContent` 改名为 `WindowBackedContent` + +- **状态**: Implemented +- **创建日期**: 2026-11-08 +- **最后更新**: 2026-11-08 +- **实现分支**: `appkit-window-backed-content`,已合进 `main` + +## 摘要 + +[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 只加了一行指向本提案;不需要使用指南或实现说明,没有新术语 | +| 2026-11-08 | Implemented,编号 0006,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:AppKit 测试全部通过,文档生成没有新警告;合并后的代码与测过的功能分支相同。文档判断同上一行:不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/0007-appkit-case-studies.md b/Documentations/Evolutions/0007-appkit-case-studies.md new file mode 100644 index 0000000000..bbeba2cf86 --- /dev/null +++ b/Documentations/Evolutions/0007-appkit-case-studies.md @@ -0,0 +1,39 @@ +# 0007 - 给 AppKit 案例补上弹出与新控件绑定的演示 + +- **状态**: Implemented +- **创建日期**: 2026-11-08 +- **最后更新**: 2026-11-08 +- **实现分支**: `appkit-window-backed-content`,已合进 `main` + +## 摘要 + +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 案例此前就有,不用改;不需要使用指南或实现说明,没有新术语 | +| 2026-11-08 | Implemented,编号 0007,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:`CaseStudies` 的 macOS 版编译通过;界面没有点过。文档判断同上一行:案例本身就是示例文档,不需要另写使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/0008-observe-unowned-self.md b/Documentations/Evolutions/0008-observe-unowned-self.md new file mode 100644 index 0000000000..12df45601d --- /dev/null +++ b/Documentations/Evolutions/0008-observe-unowned-self.md @@ -0,0 +1,58 @@ +# 0008 - 简化 `observe` 闭包里对 `self` 的捕获 + +- **状态**: Implemented +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-10 +- **实现分支**: `appkit-more-control-bindings`,已合进 `main` + +## 摘要 + +依赖这个 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`、不推送 | +| 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/0009-appkit-more-control-bindings.md b/Documentations/Evolutions/0009-appkit-more-control-bindings.md new file mode 100644 index 0000000000..613cf760b9 --- /dev/null +++ b/Documentations/Evolutions/0009-appkit-more-control-bindings.md @@ -0,0 +1,86 @@ +# 0009 - AppKit 控件绑定第二批:随模型变化的选项、文本视图、集合视图的选中 + +- **状态**: Implemented +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-10 +- **实现分支**: `appkit-more-control-bindings`,已合进 `main` + +## 摘要 + +[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:)` 对应。 + - 用户的点选、⌘ 或 ⇧ 点选、拖选、方向键、全选,以及 App 直接设置 `selectionIndexPaths`,都写回;模型改变选中时,库自己防止回写。 + - 集合视图只把用户的选中变化告诉 delegate,所以绑定在 App 的 delegate 前面放一个转发代理:所有消息原样转给 App 的 delegate,只顺带听选中变化;App 之后另设 delegate 时重新放到前面,解除绑定时把 App 的 delegate 放回去。读 `delegate` 拿到的是代理。 + - 数据源更新删掉选中项、重新加载清掉被重载项的选中时,集合视图什么都不报,这些标识留在绑定里;项出现在屏幕上时,绑定里还有它的标识就重新选上,并补上选中外观(PrivateSymbols 现在手工修的就是这个)。 +4. **示例**(已完成):在现有的「选项绑定」和「表格选中」案例里各加上新绑定的演示:标签弹出按钮的选项随模型增加,带一个 App 自己的「New Tag…」项;一个绑定到字符串的文本视图;一个多选的集合视图。 +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`、不推送 | +| 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(_:)` | +| 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 行为记在代码注释和本提案里,不另写实现说明;没有新术语 | +| 2026-11-10 | Implemented,编号 0009,落地到 `main` | 用户看过后要求收尾。验证沿用实现完成时那一轮:AppKit 测试全部通过,Xcode 26.6 编译通过,CaseStudies 的 macOS 版编译通过,界面没有点过;合进 `main` 的代码与测过的功能分支相同。后续项:表格与大纲的多选,照集合视图的 `Set` 版本补。文档判断同上一行:不需要使用指南或实现说明,没有新术语 | diff --git a/Documentations/Evolutions/0010-appkit-animations-case-study.md b/Documentations/Evolutions/0010-appkit-animations-case-study.md new file mode 100644 index 0000000000..219b8876fc --- /dev/null +++ b/Documentations/Evolutions/0010-appkit-animations-case-study.md @@ -0,0 +1,33 @@ +# 0010 - AppKit 动画案例 + +- **状态**: Implemented +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-10 +- **实现分支**: `appkit-more-control-bindings`,已合进 `main` + +## 摘要 + +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`、不推送 | +| 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/0011-appkit-stack-navigation.md b/Documentations/Evolutions/0011-appkit-stack-navigation.md new file mode 100644 index 0000000000..430a37ccc7 --- /dev/null +++ b/Documentations/Evolutions/0011-appkit-stack-navigation.md @@ -0,0 +1,296 @@ +# 0011 - 可选集成 AppKitPlus:把 UIKit 的栈式导航搬到 AppKit + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-11-09 +- **最后更新**: 2026-11-10 +- **所属愿景**: 无 +- **关联提案**: [0005](0005-appkit-presentation-redesign.md)(弹出的共用生命周期)、[0004](0004-appkit-table-selection-bindings.md)(表格与大纲的选中绑定) +- **实现分支 / PR**: `appkit-stack-navigation`,已合进 `main` +- **配套文档**: DocC 文章 [Stack navigation with AppKitPlus](../../Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md),对外的使用说明 + +## 摘要 + +给 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`;推入动画跟随事务;选中绑定覆盖大纲与可重排表格两种数据源 | 提问时补上的默认做法,用户确认 | +| 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 | 视图加载时第一次按路径摆放控制器不带动画 | 那时没有可以过渡的画面;测试里这次动画也收不了尾,后面的推入弹出都排在它后面 | +| 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 行为写在代码注释和本提案里,不另写实现说明;没有新术语 | +| 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/Documentations/Evolutions/0012-appkit-remove-shim.md b/Documentations/Evolutions/0012-appkit-remove-shim.md new file mode 100644 index 0000000000..3c45365530 --- /dev/null +++ b/Documentations/Evolutions/0012-appkit-remove-shim.md @@ -0,0 +1,60 @@ +# 0012 - 去掉 AppKitNavigationShim:不再交换系统方法 + +- **状态**: Implemented +- **创建日期**: 2026-11-14 +- **最后更新**: 2026-11-15 +- **实现分支**: `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 的测试。补测试:确认后写回、取消不动、重新绑定只写新绑定。方法命名测试不再有例外。案例里的存储面板改为弹出前先清空上次选的 URL。 +3. **NSControl 与 target 本身**(已完成):删掉重复声明与 `TargetActionProxy` 的变通;shim 已空,从四份 Package 清单里删掉这个 target,删掉目录。 + +没有询问就采用的假设: + +- 存取面板的绑定只在经库的 `sheet` / `modal` 弹出时写回;App 自己调用 `begin` / `runModal` 时不写回,结果从完成回调里取。取消时绑定保持原值——交换方法的旧实现会写成 `nil`,用户确认改用新语义。依赖这个 fork 的 App(PrivateSymbols)与案例都只经 `sheet` / `modal` 使用,读完即清空。 +- 弹出的就绪条件从「发起者的视图出现过」改为看它此刻所在的窗口: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` 也在交换方法,不在这一批的范围里。 + +后续项: + +- 把弹出与 push 两套「先出现、再离开且下屏」的结束检测合成一个共用 helper(见 `Internal/ReviewDecisions.md`)。 +- fork 的 CI 仍用 Xcode 16.4,编不过 AppKitNavigation 了;要么换成 Xcode 27,要么不再编它。CI 在这次改动之前就已经是红的。 +- 窗口 sheet(`NSWindow.sheet`)与模态会话(`modalSession`)由绑定关闭时,同样等到这一轮 run loop 结束才写回,`main` 上就是这样。可以照视图控制器的做法,在关闭调用返回后立刻检查一次。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 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` 看到时,内容照样能再弹出 | +| 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 | 实现完成,待用户看过后收尾 | 文档已同步:本提案、`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/0013-appkit-examples-redesign.md b/Documentations/Evolutions/0013-appkit-examples-redesign.md new file mode 100644 index 0000000000..de3008aa21 --- /dev/null +++ b/Documentations/Evolutions/0013-appkit-examples-redesign.md @@ -0,0 +1,84 @@ +# 0013 - macOS 示例改用侧边栏外壳与系统设置式排版 + +- **状态**: Implemented +- **创建日期**: 2026-11-14 +- **最后更新**: 2026-11-15 +- **实现分支**: `appkit-examples-redesign` + +## 摘要 + +AppKit 案例里有一半页面是照着 UIKit 案例逐行移植的:几个按钮堆在窗口正中,状态用 ✅/❌ 写进按钮标题;较新的页面从左上角往下排,每节一个粗体标题,能用但简陋。Basics 页里由布尔值弹出的 sheet 只有一行「Hello!」,没有任何按钮,弹出来就关不掉;Wi-Fi 案例的网络详情 sheet 也一样,在「忘记网络」的确认框里取消之后就没有出口。 + +第一轮把全部 AppKit 案例(15 个案例页,加上 Wi-Fi 案例的 3 个页面)改成「系统设置」那样的分组排版,并让每个弹出的 sheet 都能关掉。看过之后,整个示例的外壳仍是从 iOS 沿用的逐层进入的列表(Case studies → AppKit → 页面,换页要先返回),不像现代的 Mac App;旧版写在按钮标题里的弹出状态,也只剩部分行有一段灰色文字。第二轮把 macOS 上的外壳换成侧边栏加详情,并在每个会弹出或跳转的行上标出当前的导航状态。 + +## 方案 + +- **外壳**(只改 macOS,iOS 保持上游原样): + - 新文件 `SidebarRootView.swift`:`NavigationSplitView` 的侧边栏按「框架 · 主题」分组列出全部 SwiftUI 与 AppKit 案例,每个带一个 SF Symbol 图标;详情区显示选中的案例,标题下用副标题注明是 SwiftUI 还是 AppKit。 + - 案例说明从「About 按钮 + 带 Close 的 sheet」改成工具栏 ⓘ 按钮弹出的 popover。 + - 详情区包一层 `NavigationStack`,SwiftUI 案例里的下钻照常推入。 + - SwiftUI 案例在 macOS 上的表单用分组样式,与 AppKit 案例一致。 +- **共享排版**放在已有的 `AppKit+CaseStudySupport.swift`: + - 页面:一列分组,放在可以滚动的区域里,靠上、水平居中,有最大宽度。滚动区域铺满整个详情区,列宽只以弱于 SwiftUI 宿主尺寸的优先级偏向 640 点,不会反过来把整页拉窄。 + - 栈导航的每一页(`WindowBackgroundView`)铺一层与窗口相同的背景材质:推入的新页从右侧滑进来压在旧页上,没有背景就会透出旧页。 + - 分组:上方一行粗体标题,中间一个圆角框装着若干行,行与行之间画分隔线,下方可以有一段说明。 + - 行:左边是名称,右边是状态和控件;表格、画布、日志这类内容占满整行。 + - 导航状态标记 `PresentationStateView`:绿色对勾加「Presented」,有值时带上值(「Presented: 42」);没弹出时是灰色叉号加「Not presented」。 +- **每页只换排版和状态显示**,演示的 API 和行为不变。所有会弹出内容的行都带状态标记;栈导航的状态是路径,显示在「Path」一行。 +- **sheet 都能关掉**:弹出的内容都有 Done 按钮,回车可以触发;按 Esc 也能关,做法见决策日志。 + +落地步骤(每步各自编译通过): + +1. 共享排版;Basics 与 Wi-Fi 网络详情的 sheet 加上关闭的办法。(已完成) +2. 其余页面逐页换成分组排版。(已完成) +3. 编译 CaseStudies 的 macOS 版,启动 App 逐页截图检查,修排版问题。(已完成) +4. macOS 外壳换成侧边栏加详情,说明改到工具栏 ⓘ,SwiftUI 案例用分组样式。(已完成) +5. 全部 AppKit 案例的弹出行加上状态标记,类型擦除路径页加上「Path」一行,Wi-Fi 页加上「Destination」一行。(已完成) +6. 重新编译,启动 App 截图检查外壳和各页的状态标记。(已完成) +7. 栈导航的页面铺上窗口背景,表单的列宽改成不会拉窄页面的弱偏好;连续截帧检查推入转场。(已完成) + +没有询问就采用的假设: + +- 分组标题照「系统设置」用粗体,不用选样式时预览里的全大写。 +- 共享排版只用 AppKit,不用 AppKitPlus:多数案例只依赖 AppKitNavigation,读者在页面代码里看到的应当只有这个库的用法。 +- 各案例的说明文字保持原样,只是改由 ⓘ 弹出。 +- 侧边栏的分组沿用原来两个列表的分组和顺序,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。 +- Animations 页的圆默认改用系统蓝,颜色循环最后也回到系统蓝:原来的黑色在深色模式下几乎看不见。 +- Wi-Fi 设置页本来就是分组列表,只把分组框、宽度和边距对齐到其他页面;连接网络的面板给 Join 配上回车、给 Cancel 配上 Esc。 + +## 后续项 + +- 栈导航返回时,滑出去的那一页只画出背景、内容不显示。原因已查明:AppKitPlus 的视差与滑动转场(照它移植的 UXKit)在动画一开始就把离场页的 frame 设到容器外,而 AppKit 只重画视图在窗口里的部分,途中被标脏的内容全成了空白。页面透明时被掩盖了,看起来只是根页滑回来。修复已作为 AppKitPlus 提案 0116(transition-leaving-page-content)随 AppKitPlus-Release 0.23.0 发布。已完成(2026-11-15):示例锁定的版本升到 0.23.0,示例代码没有改动。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 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 要靠鼠标悬停才出现的按钮打开,没截到。文档判断:案例本身就是示例文档,不需要另写使用指南或实现说明,没有新术语 | +| 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。文档判断:仍不需要另写使用指南或实现说明,没有新术语 | +| 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 页都铺满详情区,底色与窗口一致。文档判断:不需要另写使用指南或实现说明,没有新术语 | +| 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/Documentations/Evolutions/0014-raise-macos-minimum.md b/Documentations/Evolutions/0014-raise-macos-minimum.md new file mode 100644 index 0000000000..72a7188cba --- /dev/null +++ b/Documentations/Evolutions/0014-raise-macos-minimum.md @@ -0,0 +1,41 @@ +# 0014 - 把 macOS 下限提到 14 + +- **状态**: Implemented +- **创建日期**: 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 条弃用警告先留着,等上游改用新 API 或提高下限时再跟进。 +- 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 版编译通过。文档判断:使用指南里的系统要求已同步,不需要另写实现说明,没有新术语 | +| 2026-11-15 | 5 条弃用警告先留着 | 用户选定:不改与上游共用的文件,合并上游时不增加冲突 | +| 2026-11-15 | 落地:推送到 `main`,编号 0014 | 用户看过后要求收尾,与示例锁定 AppKitPlus-Release 0.23.0 的改动一同推送(这一批就叠在那次改动之上)。验证沿用实现完成时那一次:那之后只改过文档。文档判断不变:使用指南已同步,不需要另写实现说明,没有新术语 | diff --git a/Documentations/Evolutions/0015-appkit-window-backed-content-marker.html b/Documentations/Evolutions/0015-appkit-window-backed-content-marker.html new file mode 100644 index 0000000000..ad9e6ad5f3 --- /dev/null +++ b/Documentations/Evolutions/0015-appkit-window-backed-content-marker.html @@ -0,0 +1,425 @@ + + + + + + +0015 - 去掉 WindowBackedContent 的全部要求 + + + + +
+ +
+

swift-navigationEvolutions0015

+

0015 去掉 WindowBackedContent 的全部要求

+
+
状态
Implemented
+
最后更新
2026-11-27
+
项目类型
库
+
实现分支
appkit-window-backed-content-marker,已合进 main
+
原文
0015-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. +
+
+ +
+

决策日志

+
+ 6 条,最近一条:Implemented,编号 0015,落地到 main +
+
+ + + + + + + + + + +
日期变更说明
2026-11-27Created as Draft协议因为是公开方法的泛型约束而必须公开,但它的三个要求只是实现细节,却跟着公开挂在每个窗口和 alert 上
2026-11-27Accepted用户批准去掉全部要求、改在运行时分派,接受失去编译期检查
2026-11-27库外遵循的类型报告 issue 并当作立即结束,不崩溃与本库其他误用的处理方式一致;begin 里直接 didEnd() 是通用层已支持的路径
2026-11-27内部协议的要求保留 appKitNavigation 前缀去掉前缀会与 NSSavePanel.runModal()、NSAlert.window 等 AppKit 成员撞名
2026-11-27实现完成,没有偏离方案Xcode 27.2、macOS 27.2 上跑 swift test --filter AppKitNavigationTests,退出码 0:XCTest 77 条、Swift Testing 75 条全部通过(2 条 known issue 是 CommonControlBindingTests 原有的 withKnownIssue),两条新测试确认报告的正是这条 issue。没有另跑带 AppKitPlus trait 的构建,改动的三个文件不在 trait 条件里;没有生成 DocC,文档注释里的符号链接没变
2026-11-27Implemented,编号 0015,落地到 main用户看过后要求收尾;合并后的代码与测过的功能分支相同。文档判断:不需要使用指南,调用方要知道的只有「只支持窗口、面板和 alert」,已写在协议的文档注释里;不需要实现说明,内部协议与转换的理由写在本提案和代码注释里;没有新术语
+
+
+
+
+ +
+
+ + diff --git a/Documentations/Evolutions/0015-appkit-window-backed-content-marker.md b/Documentations/Evolutions/0015-appkit-window-backed-content-marker.md new file mode 100644 index 0000000000..46e6244f4b --- /dev/null +++ b/Documentations/Evolutions/0015-appkit-window-backed-content-marker.md @@ -0,0 +1,212 @@ +# 0015 - 去掉 `WindowBackedContent` 的全部要求 + +- **状态**: Implemented +- **作者**: 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`,已合进 `main` +- **配套文档**: 无——见决策日志 +- **网页版**: 同目录同名的 `.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 成员撞名 | +| 2026-11-27 | 实现完成,没有偏离方案 | Xcode 27.2、macOS 27.2 上跑 `swift test --filter AppKitNavigationTests`,退出码 0:XCTest 77 条、Swift Testing 75 条全部通过(2 条 known issue 是 `CommonControlBindingTests` 原有的 `withKnownIssue`),两条新测试确认报告的正是这条 issue。没有另跑带 AppKitPlus trait 的构建,改动的三个文件不在 trait 条件里;没有生成 DocC,文档注释里的符号链接没变 | +| 2026-11-27 | Implemented,编号 0015,落地到 `main` | 用户看过后要求收尾;合并后的代码与测过的功能分支相同。文档判断:不需要使用指南,调用方要知道的只有「只支持窗口、面板和 alert」,已写在协议的文档注释里;不需要实现说明,内部协议与转换的理由写在本提案和代码注释里;没有新术语 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md new file mode 100644 index 0000000000..8dbcc304f9 --- /dev/null +++ b/Documentations/Evolutions/README.md @@ -0,0 +1,23 @@ +# Evolutions + +- **项目类型**: library + +这个 fork 的改动提案。编号在实现合进 `main` 时才分配,进行中的提案叫 `draft-.md`。 + +| # | 标题 | 状态 | +|---|------|------| +| 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 | +| 0004 | [表格与大纲的选中绑定、大纲的展开状态绑定](0004-appkit-table-selection-bindings.md) | Implemented | +| 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 | +| 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 | +| 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 | +| 0015 | [去掉 `WindowBackedContent` 的全部要求](0015-appkit-window-backed-content-marker.md) | Implemented | diff --git a/Documentations/Internal/ReviewDecisions.md b/Documentations/Internal/ReviewDecisions.md new file mode 100644 index 0000000000..8d290f141d --- /dev/null +++ b/Documentations/Internal/ReviewDecisions.md @@ -0,0 +1,116 @@ +# 审查裁决清单 + +记录审查中判为误报、不值得修或暂缓处理的发现,以及没能在运行时验证的部分。每次审查之前先对照这份清单:已裁决、且理由仍然成立的条目直接跳过;新证据推翻了当初理由的,更新条目并重新裁决。 + +已修复的问题不在这里,它们的原因与验证写在各自的 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(_:)`,行为不变。 + +### alert 作为 sheet 时没走 `beginSheetModal(for:)`,会不排版、按钮关不掉 + +- **裁决**:误报。(2026-11-06) +- **理由**:`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:)` 会建出一个和字体面板无关的新实例 + +- **裁决**:误报。(2026-11-03) +- **理由**:在 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 偏移当成字符数 + +- **裁决**:确认是同类问题,fork 内不修,暂不向上游报告。(2026-11-03,暂不报告由用户决定) +- **理由**: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 需要自己运行面板又想用绑定时。 + +### 存储面板取消时不再把绑定清空 + +- **裁决**:按用户决定,不修。(2026-11-14) +- **理由**:交换私有 setter 的旧实现在用户取消时也会被 AppKit 调用,把绑定写成 `nil`(在 `main` 上实测)。现在只在面板以「确定」结束时写回,取消保持原值;用户看过旧行为后确认保留新语义。想在取消后看到空值的调用方,在弹出前自己清空,案例就是这样做的。 +- **复查条件**:调用方普遍需要「取消即清空」时,再考虑加一个选项。 + +### 弹出期间每轮 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)` 转换警告 + +- **裁决**:旧编译器的限制,不修。(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(_:)` 时生效 + +- **裁决**:AppKit 自身的行为,库里无法绕开。(2026-11-03) +- **理由**:实测发现,响应链上没有实现 `changeFont(_:)` 的对象时,`NSFontManager.sendAction()` 返回 `false`,`addFontTrait(_:)` 也什么都不做,字体面板的改动根本不会发出来。 +- **现状**:已写进 `NSFontManager.bind(font:)` 的文档注释。 + +## 未在运行时验证 + +### transient popover 被点外部关闭时的回写 + +- `present(style: .popover(...))` 在用户关闭时把 binding 写回 `nil`。2026-11-14 起不再依靠 AppKit 调用 `dismissViewController:`:只要 popover 关闭后 AppKit 把视图控制器移出发起者的 `presentedViewControllers`、它的窗口也不再可见,就会写回。`ViewControllerPresentationTests` 用 `NSPopover.close()` 关闭的情形有测试覆盖;点击 popover 外部触发的关闭在单元测试里没法模拟,那条路径是否也走 `close()`,还没有验证。 diff --git a/Documentations/README.md b/Documentations/README.md new file mode 100644 index 0000000000..53cfd6c410 --- /dev/null +++ b/Documentations/README.md @@ -0,0 +1,26 @@ +# 文档索引 + +这个 fork 自己的文档。库的公开 API 文档在各 target 的 `Documentation.docc` 里,与上游共用。 + +## Evolutions + +- [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 退出。 +- [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 重做——生命周期收进一层,重载合并。 +- [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 案例补上弹出与新控件绑定的演示。 +- [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。 +- [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。 +- [0015-appkit-window-backed-content-marker.md](Evolutions/0015-appkit-window-backed-content-marker.md):`WindowBackedContent` 去掉全部要求,变成标记协议,弹出逻辑挪进内部协议。 + +## Internal + +- [ReviewDecisions.md](Internal/ReviewDecisions.md):审查中判为误报、不修或暂缓的发现及理由,以及没能在运行时验证的部分;每次审查前先对照。 diff --git a/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift new file mode 100644 index 0000000000..4c449354a5 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+AnimationsViewController.swift @@ -0,0 +1,124 @@ +#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() + + override func viewDidLoad() { + super.viewDidLoad() + + 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) + + 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. + 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 + } + } + + /// 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: 160) + var isScaled = false + var color = NSColor.systemBlue + + func cycleColors() async { + 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)) + } + } + } +} + +/// 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() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift new file mode 100644 index 0000000000..b44308e319 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+BasicsNavigationViewController.swift @@ -0,0 +1,114 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +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 AppKit (modal \ + panels, sheets) by driving navigation off of optional and boolean state. + """ + @UIBindable var model = Model() + + override func viewDidLoad() { + super.viewDidLoad() + + let openPanelState = PresentationStateView() + let chosenFileLabel = makeValueLabel() + let numberSheetState = PresentationStateView() + let sheetState = PresentationStateView() + + addForm( + [ + FormSection( + "Optional state", + footer: "Setting an optional presents content for its value, and clearing it dismisses the content.", + rows: [ + FormRow( + "Open panel", + accessories: [ + openPanelState, + 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: [ + numberSheetState, + 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: [ + sheetState, + makeButton("Show") { [weak self] in + self?.model.isSheetPresented = true + }, + ] + ), + ] + ), + ], + to: view + ) + + observe { [unowned self] in + openPanelState.update(isPresented: model.openPanelMessage != nil) + chosenFileLabel.stringValue = model.url?.lastPathComponent ?? "None" + 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 + let openPanel = NSOpenPanel(url: $model.url) + openPanel.message = message + return openPanel + } + + 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) { [unowned self] in + MessageViewController(message: "Hello!") { [weak self] in + self?.model.isSheetPresented = false + } + } + } + + @Observable + class Model { + var openPanelMessage: String? + var isSheetPresented = false + var sheet: Int? + var url: URL? + } +} + +#Preview { + BasicsNavigationViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift new file mode 100644 index 0000000000..039af951c5 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+CaseStudySupport.swift @@ -0,0 +1,492 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +// 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") + } +} + +/// 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. +@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 label for a value that a case study reads from its model, shown on the trailing side of a +/// row. +@MainActor +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 +} + +/// 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 +/// scrolls and grows no wider than reads well. +@MainActor +func addForm(_ sections: [FormSection], to view: NSView) { + let column = FormColumnView(sections, spacing: 24) + column.translatesAutoresizingMaskIntoConstraints = false + + 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 preferredWidth = column.widthAnchor.constraint(equalToConstant: 640) + preferredWidth.priority = .preferredFormWidth + NSLayoutConstraint.activate([ + 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), + 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 { + 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 { + 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 + window.contentView = makeMessageView(message: message, buttons: buttons) + window.center() + return window +} + +/// A view controller to present: a message above a row of buttons that ends with Done. +/// +/// 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] = [], done: (() -> Void)? = nil) { + self.message = message + self.extraButtons = extraButtons + self.done = done + 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 doneButton = makeButton("Done") { [weak self] in + self?.finish() + } + doneButton.keyEquivalent = "\r" + 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 new file mode 100644 index 0000000000..1030afa4b3 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+ConciseEnumNavigationViewController.swift @@ -0,0 +1,114 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +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 alertState = PresentationStateView() + let numberSheetState = PresentationStateView() + let sheetState = PresentationStateView() + + 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: [ + alertState, + makeButton("Show") { [weak self] in + self?.model.destination = .alert("Hello!") + }, + ] + ), + FormRow( + "Sheet with a number", + accessories: [ + numberSheetState, + makeButton("Show") { [weak self] in + self?.model.destination = .sheet(.random(in: 1 ... 1_000)) + }, + ] + ), + FormRow( + "Sheet without a payload", + accessories: [ + sheetState, + makeButton("Show") { [weak self] in + self?.model.destination = .sheetWithoutPayload + }, + ] + ), + ] + ), + ], + to: view + ) + + observe { [unowned self] in + 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 + 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] 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 + MessageViewController(message: "Hello!") { [weak self] in + self?.model.destination = nil + } + } + } + + @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/AppKit+DismissalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift new file mode 100644 index 0000000000..56911ef212 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+DismissalViewController.swift @@ -0,0 +1,117 @@ +#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 fruitSheetState = PresentationStateView() + let logLabel = makeWrappingLabel() + logLabel.textColor = .secondaryLabelColor + + addForm( + [ + FormSection( + "Sheet", + footer: "Done dismisses the sheet the way a user would; its other buttons change the state instead.", + rows: [ + FormRow( + "Fruit", + accessories: [ + fruitSheetState, + makeButton("Present") { [weak self] in + self?.model.fruit = .apple + }, + ] + ), + ] + ), + FormSection("onDismiss log", rows: [FormRow(content: logLabel)]), + ], + to: view + ) + + observe { [unowned self] in + fruitSheetState.update(isPresented: model.fruit != nil, detail: model.fruit?.title) + 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 the way a user would; 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 title: String { + switch self { + case .apple: "Apple" + case .banana: "Banana" + case .cherry: "Cherry" + } + } + + var next: Self { + Self(rawValue: rawValue + 1) ?? .apple + } + } +} + +#Preview { + DismissalViewController() +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift new file mode 100644 index 0000000000..adbd36ce44 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+EnumControlsViewController.swift @@ -0,0 +1,97 @@ +#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 statusLabel = makeValueLabel() + let outOfStockButton = makeButton("Out of stock") { [weak self] in + self?.status = .outOfStock(isOnBackOrder: false) + } + let backInStockButton = makeButton("Back in stock!") { [weak self] in + self?.status = .inStock(quantity: 100) + } + 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 + 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.wrappedValue.description + 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+ErasedNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift new file mode 100644 index 0000000000..57bc832430 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+ErasedNavigationStackController.swift @@ -0,0 +1,170 @@ +#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(model: model) + } + 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 { + 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)") + } + navigationDestination(for: String.self) { string in + ErasedFeatureViewController(title: "String \"\(string)\"") + } + navigationDestination(for: Bool.self) { value in + ErasedFeatureViewController(title: "Boolean \(value)") + } + + 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()) + }, + ] + ), + ] + ), + 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" + } + } + } +} + +/// 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() + + 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 + ) + } +} + +#Preview { + ErasedNavigationStackController(model: ErasedNavigationStackController.Model()) +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift new file mode 100644 index 0000000000..716c6a3032 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+FocusViewController.swift @@ -0,0 +1,109 @@ +#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 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) + let passwordTextField = NSSecureTextField(text: $model.password) + passwordTextField.bind(focus: $model.focus, equals: .password) + 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 + } + 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 = model.focus?.rawValue.capitalized ?? "None" + for (row, focus) in fieldRows { + row.titleLabel.textColor = model.focus == focus ? .controlAccentColor : .labelColor + } + } + } + + @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 new file mode 100644 index 0000000000..ad48b4788d --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+MinimalObservationViewController.swift @@ -0,0 +1,79 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation +import ConcurrencyExtras + +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 \ + 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 viewDidLoad() { + super.viewDidLoad() + + 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 } + + 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 = viewRenderCount.value.description + } + } + + @Observable + class Model { + var count = 0 + var isCountHidden = false + } +} + +#Preview { + MinimalObservationViewController() +} + +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift new file mode 100644 index 0000000000..d638404783 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+NSControlBindingsViewController.swift @@ -0,0 +1,119 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +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() + + 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 + 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 + stepperValueLabel.stringValue = model.stepperValue.formatted() + + let textSelection = model.textSelection.map { + self.model.text.range(for: $0.range) + } + + modelLabel.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 = .systemBlue + 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/AppKit/AppKit+NestedModalViewController.swift b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift new file mode 100644 index 0000000000..94fb699c2c --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+NestedModalViewController.swift @@ -0,0 +1,115 @@ +#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 settingsWindowState = PresentationStateView() + let confirmationAlertState = PresentationStateView() + 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: [ + settingsWindowState, + makeButton("Open") { [weak self] in + self?.model.isSettingsPresented = true + }, + ] + ), + FormRow("Confirmation alert", accessories: [confirmationAlertState]), + FormRow("Resets", accessories: [resetCountLabel]), + ] + ), + ], + to: view + ) + + observe { [unowned self] in + settingsWindowState.update(isPresented: model.isSettingsPresented) + confirmationAlertState.update(isPresented: model.resetConfirmation != nil) + resetCountLabel.stringValue = model.resetCount.description + } + + 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..1d964eec2a --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+OptionBindingsViewController.swift @@ -0,0 +1,200 @@ +#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. + + 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() + + 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.heightAnchor.constraint(equalToConstant: 110).isActive = true + + 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 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 = .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 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, + ].compactMap(\.self) + 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" + } + } + + @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 + var isBold = true + 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 { + 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..cfb1daa12b --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+PresentationGalleryViewController.swift @@ -0,0 +1,377 @@ +#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 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 + } + let viewControllerPopoverButton = makeButton("Present") { [weak self] in + self?.model.isViewControllerPopoverPresented = true + } + let logLabel = makeWrappingLabel() + logLabel.textColor = .secondaryLabelColor + + addForm( + [ + FormSection( + "Windows, alerts and panels", + rows: [ + FormRow( + "Modal window", + accessories: [ + modalWindowState, + makeButton("Run") { [weak self] in + self?.model.isModalWindowPresented = true + }, + ] + ), + FormRow( + "Modal alert", + accessories: [ + modalAlertState, + makeButton("Run") { [weak self] in + self?.model.modalAlert = .discardChanges + }, + ] + ), + FormRow( + "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( + "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: [popoverState, popoverButton])] + ), + FormSection( + "View controllers", + rows: [ + FormRow( + "As a sheet", + accessories: [ + viewControllerSheetState, + makeButton("Present") { [weak self] in + self?.model.isViewControllerSheetPresented = true + }, + ] + ), + FormRow( + "In a modal window", + accessories: [ + viewControllerWindowState, + makeButton("Present") { [weak self] in + self?.model.isViewControllerWindowPresented = true + }, + ] + ), + FormRow( + "In a popover", + accessories: [viewControllerPopoverState, viewControllerPopoverButton] + ), + ] + ), + FormSection( + "onDismiss log", + footer: "'onDismiss' runs once the content has left the screen, however it was dismissed.", + rows: [FormRow(content: logLabel)] + ), + ], + to: view + ) + + 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") + } + + // 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 + // 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 + }, + ] + ) + 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+StaticNavigationStackController.swift b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift new file mode 100644 index 0000000000..ec37c92fee --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+StaticNavigationStackController.swift @@ -0,0 +1,159 @@ +#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 = makeValueLabel() + let featureRows = StaticNavigationStackController.Model.Path.allCases.map { feature in + FormRow( + feature.title, + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: feature) + }, + ] + ) + } + 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 + ) + + observe { [unowned self] in + pathLabel.stringValue = 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() + + let featureRows = StaticNavigationStackController.Model.Path.allCases.map { feature in + FormRow( + feature.title, + accessories: [ + makeButton("Push") { [weak self] in + self?.traitCollection.push(value: feature) + }, + ] + ) + } + + addForm( + [ + FormSection("Push", rows: featureRows), + FormSection( + rows: [ + FormRow( + "This screen", + accessories: [ + makeButton("Dismiss") { [weak self] in + self?.traitCollection.dismiss() + }, + ] + ), + ] + ), + ], + to: view + ) + } +} + +#Preview { + StaticNavigationStackController(model: StaticNavigationStackController.Model()) +} +#endif diff --git a/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift new file mode 100644 index 0000000000..be02308fc6 --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKit+TableSelectionViewController.swift @@ -0,0 +1,303 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKit +import AppKitNavigation + +class TableSelectionViewController: XiblessViewController, AppKitCaseStudy { + 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 \ + 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. + + 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() + + // 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 + } + ) + + // 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) + collectionView.backgroundColors = [.clear] + let collectionScrollView = NSScrollView() + collectionScrollView.documentView = collectionView + collectionScrollView.drawsBackground = false + collectionScrollView.heightAnchor.constraint(equalToConstant: 64).isActive = true + + let planetLabel = makeValueLabel() + let pantryItemLabel = makeValueLabel() + let expandedGroupsLabel = makeValueLabel() + let colorsLabel = makeValueLabel() + + 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 + 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: ", ") + } + } + + /// 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.autohidesScrollers = true + scrollView.drawsBackground = false + scrollView.heightAnchor.constraint(equalToConstant: height).isActive = true + return scrollView + } + + @Observable + class Model { + 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 + } +} + +/// 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 new file mode 100644 index 0000000000..93f64eb91c --- /dev/null +++ b/Examples/CaseStudies/AppKit/AppKitCaseStudies.swift @@ -0,0 +1,68 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +import AppKitNavigation + +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 ef9c063e7f..385e22194f 100644 --- a/Examples/CaseStudies/Internal/CaseStudy.swift +++ b/Examples/CaseStudies/Internal/CaseStudy.swift @@ -1,221 +1,249 @@ import SwiftUI -import UIKitNavigation @MainActor 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) +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 } +} +#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 } -} -extension UIKitCaseStudy { - var usesOwnLayout: Bool { true } + 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) - } - @ViewBuilder - static func buildExpression(_ caseStudy: some UIKitCaseStudy) -> some View { - UIKitCaseStudyButton(caseStudy: caseStudy) - } - static func buildPartialBlock(first: some View) -> some View { - first - } - @ViewBuilder - static func buildPartialBlock(accumulated: some View, next: some View) -> some View { - accumulated - next - } + @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 + 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 - } - .modifier(CaseStudyModifier(caseStudy: caseStudy)) - } - } else { - NavigationLink(caseStudy.caseStudyTitle) { - 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)) - } } - } } +#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) + #if os(macOS) + Button("Close") { + isAboutPresented = false + } + #endif + } + .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 - - var body: some View { - Section { - content - } header: { - title + @CaseStudyViewBuilder let content: Content + @ViewBuilder let title: 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! """ } +#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..5f4707a272 100644 --- a/Examples/CaseStudies/RootView.swift +++ b/Examples/CaseStudies/RootView.swift @@ -2,23 +2,25 @@ 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 + } + .navigationTitle("Case studies") } - NavigationLink("UIKit") { - UIKitCaseStudiesView() - } - } - .navigationTitle("Case studies") } - } } struct RootView_Previews: PreviewProvider { - static var previews: some View { - RootView() - } + static var previews: some View { + RootView() + } } 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/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 ab3e14aa4c..7a1c36cda8 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 @@ -157,3 +158,4 @@ class ConciseEnumNavigationViewController: UIViewController, UIKitCaseStudy { rootViewController: BasicsNavigationViewController() ) } +#endif diff --git a/Examples/CaseStudies/UIKit/EnumControlsViewController.swift b/Examples/CaseStudies/UIKit/EnumControlsViewController.swift index 2e3b6b7885..b427c3d538 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 @@ -107,3 +108,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 531f38a4b4..aa3b2ed62e 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 @@ -171,3 +172,4 @@ private class FeatureViewController: UIViewController { #Preview { StaticNavigationStackController(model: StaticNavigationStackController.Model()) } +#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 e6e86b697a..bbf55f7762 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 deleted file mode 100644 index fee0ef6472..0000000000 --- a/Examples/CaseStudies/UIKit/WiFiFeature/ConnectToNetworkFeature.swift +++ /dev/null @@ -1,111 +0,0 @@ -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") - ) - ) - ) - } -} diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift deleted file mode 100644 index 3255e01d04..0000000000 --- a/Examples/CaseStudies/UIKit/WiFiFeature/NetworkDetailFeature.swift +++ /dev/null @@ -1,99 +0,0 @@ -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() - ) - ) - ) - } -} diff --git a/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift b/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift deleted file mode 100644 index d489bed343..0000000000 --- a/Examples/CaseStudies/UIKit/WiFiFeature/WiFiSettingsFeature.swift +++ /dev/null @@ -1,311 +0,0 @@ -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 .selectedNetwork(let networkID): - guard let network = model.foundNetworks.first(where: { $0.id == networkID }) - else { return } - configureNetwork(cell: cell, network: network, indexPath: indexPath, item: item) - - case .foundNetwork(let 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() + cancelButton.addAction { [weak self] _ in + guard let self else { return } + model.cancelButtonTapped() + } + cancelButton.title = "Cancel" + cancelButton.keyEquivalent = "\u{1b}" + + let joinButton = NSButton() + joinButton.addAction { [weak self] _ in + guard let self else { return } + Task { + await self.model.joinButtonTapped() + } + } + joinButton.title = "Join" + joinButton.keyEquivalent = "\r" + + 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(isPresented: $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..954cbc2e29 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/ConnectToNetworkFeature/ConnectToNetworkModel.swift @@ -0,0 +1,36 @@ +import Foundation +import IssueReporting + +@Observable +@MainActor +class ConnectToNetworkModel: Identifiable { + var incorrectPasswordAlertIsPresented = false + var isConnecting = false + var onCancel: () -> Void = { + reportIssue("ConnectToNetworkModel.onCancel unimplemented.") + } + var onConnect: (Network) -> Void = { _ in + reportIssue("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..a36c95b0b5 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/AppKit+NetworkDetailViewController.swift @@ -0,0 +1,73 @@ +#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() + + let forgetButton = makeButton("Forget This Network…") { [weak self] in + self?.model.forgetNetworkButtonTapped() + } + 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([ + content.topAnchor.constraint(equalTo: view.topAnchor), + content.leadingAnchor.constraint(equalTo: view.leadingAnchor), + content.trailingAnchor.constraint(equalTo: view.trailingAnchor), + content.bottomAnchor.constraint(equalTo: view.bottomAnchor), + ]) + + modal(isPresented: $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 + } + } + + /// Escape in the sheet, which AppKit asks the sheet's delegate for: this view controller. + @objc func cancel(_ sender: Any?) { + dismiss(nil) + } +} + +#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..a37d722187 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/NetworkDetailFeature/NetworkDetailModel.swift @@ -0,0 +1,32 @@ +import Foundation +import IssueReporting + +@MainActor +@Observable +class NetworkDetailModel: Identifiable { + var forgetAlertIsPresented = false + var onConfirmForget: () -> Void = { + reportIssue("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..ce260c2a06 --- /dev/null +++ b/Examples/CaseStudies/WiFiFeature/WiFiSettingsFeature/AppKit+WiFiSettingsViewController.swift @@ -0,0 +1,440 @@ +#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() + + /// 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) + } + + 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 ? 52 : 44)) + let item = NSCollectionLayoutItem(layoutSize: itemSize) + item.contentInsets = .init(top: 0, leading: 12, bottom: 0, trailing: 12) + // Group + 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: topInset, leading: sideInset, bottom: 0, trailing: sideInset) + let decorationItem = NSCollectionLayoutDecorationItem.background(elementKind: NSCollectionView.DecorationElementKind.background) + decorationItem.contentInsets = .init(top: topInset, leading: sideInset, bottom: 0, trailing: sideInset) + section.decorationItems = [decorationItem] + return section + } + 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)) + + dataSource = NSCollectionViewDiffableDataSource( + collectionView: collectionView + ) { [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 + 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 { [weak self] _ in + guard let self else { return } + 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 { [weak self] _ in + guard let self else { return } + self.model.networkTapped(network) + } + return foundedViewItem + } + } + + 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), + animatingDifferences: true + ) + } + + 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] + panel.title = "" + panel.animationBehavior = .none + return panel + } + + present(item: $model.destination.detail, style: .sheet) { model in + 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 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), + section.widthAnchor.constraint(lessThanOrEqualTo: widthAnchor, constant: -48), + preferredWidth, + ]) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } +} + +#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 + // 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 + } +} + +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: "Details…", 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/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 93bc679c91..eebfbd5a4f 100644 --- a/Examples/CaseStudiesTests/NavigationPathTests.swift +++ b/Examples/CaseStudiesTests/NavigationPathTests.swift @@ -645,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 e533c10c0b..4fde934316 100644 --- a/Examples/CaseStudiesTests/NavigationStackTests.swift +++ b/Examples/CaseStudiesTests/NavigationStackTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKitNavigation import UIKitNavigationShim import XCTest @@ -317,3 +318,4 @@ private final class ChildViewController: UIViewController { } } } +#endif diff --git a/Examples/CaseStudiesTests/PresentationTests.swift b/Examples/CaseStudiesTests/PresentationTests.swift index da1483175f..ae22eefef6 100644 --- a/Examples/CaseStudiesTests/PresentationTests.swift +++ b/Examples/CaseStudiesTests/PresentationTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKitNavigation import XCTest @@ -707,3 +708,4 @@ private class BasicViewController: UIViewController { } } } +#endif diff --git a/Examples/CaseStudiesTests/RuntimeWarningTests.swift b/Examples/CaseStudiesTests/RuntimeWarningTests.swift index 7df5f19ed2..26bd168ee0 100644 --- a/Examples/CaseStudiesTests/RuntimeWarningTests.swift +++ b/Examples/CaseStudiesTests/RuntimeWarningTests.swift @@ -1,3 +1,4 @@ +#if canImport(UIKit) && !os(watchOS) import UIKitNavigation import XCTest @@ -158,3 +159,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 ac05f0d99b..55022cd6de 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 */; }; CA456DA82CB810BA00F04E02 /* IdentifiedCollections in Frameworks */ = {isa = PBXBuildFile; productRef = CA456DA72CB810BA00F04E02 /* IdentifiedCollections */; }; CA4737CF272F09600012CAC3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = CA4737CE272F09600012CAC3 /* Assets.xcassets */; }; CA4737F4272F09780012CAC3 /* SwiftUINavigation in Frameworks */ = {isa = PBXBuildFile; productRef = CA4737F3272F09780012CAC3 /* SwiftUINavigation */; }; @@ -21,11 +21,12 @@ 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 */; }; 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 */; }; @@ -58,6 +59,30 @@ 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; 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 */; }; + 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 */; }; + 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 */ @@ -81,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 = ""; }; @@ -108,10 +134,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 = ""; }; @@ -119,6 +145,29 @@ 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 /* 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 = ""; }; + 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 = ""; }; + 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 */ @@ -140,6 +189,7 @@ CA48F2FA2C49645100BE2C3C /* SwiftUINavigation in Frameworks */, CA48F3052C49650F00BE2C3C /* Tagged in Frameworks */, CA48F2FC2C49645100BE2C3C /* UIKitNavigation in Frameworks */, + E9836D942C6CA07300FC6EFD /* AppKitNavigation in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -213,10 +263,13 @@ CA47383C272F0F0D0012CAC3 /* Info.plist */, CA473830272F0D860012CAC3 /* CaseStudiesApp.swift */, CA47382E272F0D860012CAC3 /* RootView.swift */, + F1A0B0C02EB6D10000A1B2C3 /* SidebarRootView.swift */, CA47380A272F0D340012CAC3 /* Assets.xcassets */, CA9D70492C1F642A003B672A /* Internal */, CADCA3642C1CE80B00DE645F /* SwiftUI */, CA9D704A2C1F6431003B672A /* UIKit */, + E9836D902C6C9E3000FC6EFD /* AppKit */, + DC5EB9BC2C0525980034B757 /* WiFiFeature */, ); path = CaseStudies; sourceTree = ""; @@ -258,7 +311,6 @@ CA9D704F2C1FB431003B672A /* StaticNavigationStackController.swift */, CA9D70592C208977003B672A /* UIControlBindingsViewController.swift */, CA9D70442C1F6001003B672A /* UIKitCaseStudies.swift */, - DC5EB9BC2C0525980034B757 /* WiFiFeature */, ); path = UIKit; sourceTree = ""; @@ -288,10 +340,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 = ""; @@ -306,6 +358,60 @@ path = Internal; sourceTree = ""; }; + E9836D902C6C9E3000FC6EFD /* AppKit */ = { + isa = PBXGroup; + children = ( + E9CD5B7D2C6D14DC00CE7947 /* AppKitCaseStudies.swift */, + E9836D912C6CA03E00FC6EFD /* AppKit+MinimalObservationViewController.swift */, + E9836D952C6CADBB00FC6EFD /* AppKit+NSControlBindingsViewController.swift */, + E9CD5B752C6CD7A200CE7947 /* AppKit+EnumControlsViewController.swift */, + 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 */, + E9F0050A2EDA000000000007 /* AppKit+AnimationsViewController.swift */, + E9F0050A2EDA000000000008 /* AppKit+StaticNavigationStackController.swift */, + E9F0050A2EDA000000000009 /* AppKit+ErasedNavigationStackController.swift */, + ); + 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 PBXHeadersBuildPhase section */ @@ -359,6 +465,7 @@ CA48F3012C49650100BE2C3C /* IdentifiedCollections */, CA48F3042C49650F00BE2C3C /* Tagged */, CA48F3072C49651700BE2C3C /* ConcurrencyExtras */, + E9836D932C6CA07300FC6EFD /* AppKitNavigation */, ); productName = CaseStudies; productReference = CA473804272F0D330012CAC3 /* CaseStudies.app */; @@ -444,6 +551,7 @@ ); mainGroup = CA47378B272F08EF0012CAC3; packageReferences = ( + E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */, CA6453982968A06E00802931 /* XCRemoteSwiftPackageReference "swift-dependencies" */, CA48F3002C49650100BE2C3C /* XCRemoteSwiftPackageReference "swift-identified-collections" */, CA48F3032C49650F00BE2C3C /* XCRemoteSwiftPackageReference "swift-tagged" */, @@ -511,30 +619,54 @@ buildActionMask = 2147483647; files = ( 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 */, + 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 */, + 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 */, 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 */, - CA3D0E332C20B27B00CCF7CD /* NetworkDetailFeature.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 */, 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 */, + 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; @@ -767,9 +899,15 @@ "$(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)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SUPPORTS_MACCATALYST = NO; SWIFT_EMIT_LOC_STRINGS = YES; SWIFT_OPTIMIZATION_LEVEL = "-Onone"; TARGETED_DEVICE_FAMILY = "1,2"; @@ -796,9 +934,15 @@ "$(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)"; + SUPPORTED_PLATFORMS = "iphoneos iphonesimulator macosx"; + SUPPORTS_MACCATALYST = NO; SWIFT_EMIT_LOC_STRINGS = YES; TARGETED_DEVICE_FAMILY = "1,2"; }; @@ -810,6 +954,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; @@ -819,6 +964,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; TARGETED_DEVICE_FAMILY = "1,2"; @@ -832,6 +979,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; @@ -841,6 +989,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; TARGETED_DEVICE_FAMILY = "1,2"; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/CaseStudies.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/CaseStudies"; @@ -989,6 +1139,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; @@ -1032,14 +1196,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 */ = { @@ -1057,20 +1224,24 @@ package = CA48F3062C49651700BE2C3C /* XCRemoteSwiftPackageReference "swift-concurrency-extras" */; productName = ConcurrencyExtras; }; - CAAFA9D22C8B422800BB2BA1 /* UIKitNavigation */ = { + E9836D932C6CA07300FC6EFD /* AppKitNavigation */ = { isa = XCSwiftPackageProductDependency; - productName = UIKitNavigation; + package = E9F0050A2EDA000000000021 /* XCLocalSwiftPackageReference ".." */; + productName = AppKitNavigation; }; - CAAFA9D62C8B468000BB2BA1 /* AppKitNavigation */ = { + CAAFA9D22C8B422800BB2BA1 /* UIKitNavigation */ = { isa = XCSwiftPackageProductDependency; - productName = AppKitNavigation; + 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/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/Package.resolved b/Package.resolved index be678cf5af..b1255becc1 100644 --- a/Package.resolved +++ b/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "ec9e997bed87527379922584201be46e70c2efdf78de999abb9cb1425fcee9a0", + "originHash" : "696fb0ef1c5b1570c6d08c3cd197a39c299326aa7f71e9fa5fc3bea7474942de", "pins" : [ { "identity" : "swift-case-paths", diff --git a/Package.swift b/Package.swift index 73bdffa3a3..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), ], @@ -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"), @@ -183,6 +189,17 @@ let package = Package( .target( name: "UIKitNavigationShim" ), + .target( + name: "AppKitNavigation", + dependencies: [ + "SwiftNavigation", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), + ] + ), .testTarget( name: "UIKitNavigationTests", dependencies: [ @@ -190,10 +207,16 @@ let package = Package( .product(name: "IssueReportingTestSupport", package: "swift-issue-reporting"), ] ), - .target( - name: "AppKitNavigation", + .testTarget( + name: "AppKitNavigationTests", dependencies: [ - "SwiftNavigation" + "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.0.swift b/Package@swift-6.0.swift index e8bc9c1cb9..1d8da72bb1 100644 --- a/Package@swift-6.0.swift +++ b/Package@swift-6.0.swift @@ -114,7 +114,14 @@ let package = Package( .target( name: "AppKitNavigation", dependencies: [ - "SwiftNavigation" + "SwiftNavigation", + ] + ), + .testTarget( + name: "AppKitNavigationTests", + dependencies: [ + "AppKitNavigation", + .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), ] ), ], diff --git a/Package@swift-6.1.swift b/Package@swift-6.1.swift index 6c58c81ebb..6fad7c0d64 100644 --- a/Package@swift-6.1.swift +++ b/Package@swift-6.1.swift @@ -192,7 +192,14 @@ let package = Package( .target( name: "AppKitNavigation", dependencies: [ - "SwiftNavigation" + "SwiftNavigation", + ] + ), + .testTarget( + name: "AppKitNavigationTests", + dependencies: [ + "AppKitNavigation", + .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), ] ), ], diff --git a/Package@swift-6.2.swift b/Package@swift-6.2.swift index e604d590c4..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(.v10_15), + .macOS(.v14), .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"), @@ -193,7 +199,24 @@ let package = Package( .target( name: "AppKitNavigation", dependencies: [ - "SwiftNavigation" + "SwiftNavigation", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), + ] + ), + .testTarget( + name: "AppKitNavigationTests", + dependencies: [ + "AppKitNavigation", + .product( + name: "AppKitPlus", + package: "AppKitPlus-Release", + condition: .when(platforms: [.macOS], traits: ["AppKitPlus"]) + ), + .product(name: "IssueReportingTestSupport", package: "xctest-dynamic-overlay"), ] ), ], diff --git a/Sources/AppKitNavigation/AppKitAnimation.swift b/Sources/AppKitNavigation/AppKitAnimation.swift index 771e02acd7..b5655aaeb7 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 .appKit(let animation): 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/Sources/AppKitNavigation/Bindings/NSAlert.swift b/Sources/AppKitNavigation/Bindings/NSAlert.swift new file mode 100644 index 0000000000..24cc2c2b01 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSAlert.swift @@ -0,0 +1,54 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public 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 + ) { + addButton(buttonState) { _ in } + } + + public func addButton( + _ buttonState: ButtonState, + action handler: @escaping (_ action: Action?) -> Void + ) { + 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/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/Bindings/NSCollectionView.swift b/Sources/AppKitNavigation/Bindings/NSCollectionView.swift new file mode 100644 index 0000000000..18702d4435 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSCollectionView.swift @@ -0,0 +1,251 @@ +#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 + @available(macOS 10.15.1, *) + 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 + @available(macOS 10.15.1, *) + 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/Bindings/NSColorPanel.swift b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift new file mode 100755 index 0000000000..97ba500fa4 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSColorPanel.swift @@ -0,0 +1,50 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +public import AppKit + +extension NSColorPanel: @unchecked @retroactive Sendable {} +extension NSColorPanel: TargetActionProtocol { + public var target: AnyObject? { + set { setTarget(newValue) } + get { value(forKeyPath: "target") as? AnyObject } + } + + public var action: Selector? { + set { setAction(newValue) } + 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) + } + } +} + +extension NSColorPanel { + /// Creates a new color panel and registers the binding against the + /// selected color. + /// + /// - 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) + } + + /// 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..b2c99fc415 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSColorWell.swift @@ -0,0 +1,27 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public 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..aabd124ba7 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSControl.swift @@ -0,0 +1,10 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSControl: @unchecked @retroactive Sendable {} +extension NSControl: TargetActionProtocol {} + +extension NSControl {} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSDatePicker.swift b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift new file mode 100755 index 0000000000..cbb8b46881 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSDatePicker.swift @@ -0,0 +1,27 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public 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 100644 index 0000000000..5b53b65a1b --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSFontManager.swift @@ -0,0 +1,102 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +@_spi(Internals) public import SwiftNavigation +public import AppKit + +extension NSFontManager: @unchecked @retroactive Sendable {} + +@MainActor +extension NSFontManager { + /// Returns the shared font manager, with the binding registered against its selected font. + /// + /// `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 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 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 { + bind(font, to: \.appKitNavigationSelectedFont) + } + + // 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 + // anything else keeps only the change and loses the bound font's family and size. + get { convert(selectedFont ?? .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. + /// - 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. + /// - 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 { + establishBinding(binding, to: keyPath, of: self, through: createActionProxyIfNeeded(), set: set) + } + + public func unbind(_ keyPath: KeyPath) { + removeBinding(to: keyPath) + } + + private func createActionProxyIfNeeded() -> TargetActionProxy { + if let actionProxy { + return actionProxy + } else { + let actionProxy = TargetActionProxy(fontManager: self) + self.actionProxy = actionProxy + return actionProxy + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSMenuItem.swift b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift new file mode 100755 index 0000000000..5e64c2c1e0 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSMenuItem.swift @@ -0,0 +1,57 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +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/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/Sources/AppKitNavigation/Bindings/NSPathControl.swift b/Sources/AppKitNavigation/Bindings/NSPathControl.swift new file mode 100755 index 0000000000..e705e16d45 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSPathControl.swift @@ -0,0 +1,29 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +public 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. + /// - url: The binding to read from for the selected url, and write to when the selected + /// url changes. + public convenience init(frame: CGRect = .zero, url: UIBinding) { + self.init(frame: frame) + bind(url: url) + } + + /// 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/NSPopUpButton.swift b/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift new file mode 100644 index 0000000000..1478e5493f --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSPopUpButton.swift @@ -0,0 +1,321 @@ +#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 + /// ) + /// ``` + /// + /// 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. + /// - column: The source `#column` associated with the binding. + public convenience init( + frame: CGRect = .zero, + selection: UIBinding, + options: [Value], + 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) + bind( + selection: selection, + options: options, + title: title, + image: image, + 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. 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 + /// 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 + } + } + + /// 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/NSProgressIndicator.swift b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift new file mode 100644 index 0000000000..b0655848bc --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSProgressIndicator.swift @@ -0,0 +1,58 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +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 } + if isAnimated.wrappedValue { + startAnimation(nil) + } else { + stopAnimation(nil) + } + } + // 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 + ) + } + } + + private static let isAnimatedTokenKey = malloc(1)! +} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift new file mode 100755 index 0000000000..8c08f0fa5b --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSaveOpenPanel.swift @@ -0,0 +1,140 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +public import AppKit + +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 binding is stored. + // Left to be released when its entry is replaced below, it would clear the binding it no + // longer owns. + unbindURL() + let confirmedChoiceBindings = appKitNavigationConfirmedChoiceBindings + confirmedChoiceBindings.url = binding + let observationToken = ObserveToken { [weak confirmedChoiceBindings] in + MainActor._assumeIsolated { + 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 + } +} + +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() + let confirmedChoiceBindings = appKitNavigationConfirmedChoiceBindings + confirmedChoiceBindings.urls = binding + let observationToken = ObserveToken { [weak confirmedChoiceBindings] in + MainActor._assumeIsolated { + 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/Bindings/NSSegmentedControl.swift b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift new file mode 100755 index 0000000000..ff7d0ca039 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSegmentedControl.swift @@ -0,0 +1,323 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit + +extension NSSegmentedControl { + /// 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 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, + 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 segmented control's selected + /// segment. + /// + /// - 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( + 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 + ) + } + + /// 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. + /// - 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. + public convenience init( + frame: CGRect = .zero, + selection: UIBinding, + options: [Value], + title: @escaping (Value) -> String, + image: ((Value) -> NSImage?)? = nil, + fileID: StaticString = #fileID, + filePath: StaticString = #filePath, + line: UInt = #line, + column: UInt = #column + ) { + self.init(frame: frame) + 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, + column: column + ) + } + + /// 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: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. + /// + /// - 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 + } + } + + /// 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 { + 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..1e091af00b --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSlider.swift @@ -0,0 +1,26 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public 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/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/NSStepper.swift b/Sources/AppKitNavigation/Bindings/NSStepper.swift new file mode 100755 index 0000000000..75eaa1e52f --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSStepper.swift @@ -0,0 +1,26 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public 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..fcba9fe359 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSSwitch.swift @@ -0,0 +1,36 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public 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: \.appKitNavigationIsOn) { control, isOn, transaction in + control.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/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/Sources/AppKitNavigation/Bindings/NSTableView.swift b/Sources/AppKitNavigation/Bindings/NSTableView.swift new file mode 100644 index 0000000000..37fc63911e --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTableView.swift @@ -0,0 +1,117 @@ +#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. + // 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, + 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:)-(_,NSTableViewDiffableDataSource)``. + public func unbindSelection() { + removeBinding(to: \NSTableView.selectedRowIndexes) + } +} +#endif diff --git a/Sources/AppKitNavigation/Bindings/NSTextField.swift b/Sources/AppKitNavigation/Bindings/NSTextField.swift new file mode 100755 index 0000000000..1137407250 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSTextField.swift @@ -0,0 +1,348 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +public import AppKit +import Combine +public import SwiftNavigation + +extension NSTextField { + /// 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 { + // 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 + } + } + // 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 } + MainActor._assumeIsolated { reportSelection(self) } + } + // 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. + nonisolated(unsafe) 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) } + } + nonisolated(unsafe) 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 = ObserveToken { + editingChangedAction.cancel() + selectionChangedAction.cancel() + editingDidEndAction.cancel() + token.cancel() + } + observationTokens[\NSTextField.selectedRange] = observationToken + return observationToken + } + + fileprivate var selectedRange: NSRange? { + set { + currentEditor()?.selectedRange = newValue ?? .init(location: 0, length: 0) + } + + get { + currentEditor()?.selectedRange + } + } + + // 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 } + let text = stringValue + 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 { + guard let selection = newValue?.range else { + selectedRange = nil + return + } + let text = stringValue + 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) + ) + } + } + + /// 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 `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: NSViewController { + /// 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 = NSTextField(text: $username) + /// usernameTextField.bind(focus: $focusedField, equals: .usernameField) + /// + /// let passwordTextField = NSSecureTextField(text: $password) + /// passwordTextField.bind(focus: $focusedField, equals: .passwordField) + /// + /// 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) + /// } + /// } + /// + /// // ... + /// } + /// } + /// ``` + /// + /// 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`, the text field loses 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() + // 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. + // + // 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 { + 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. + nonisolated(unsafe) 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): + // 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: + break + } + } + let outerToken = ObserveToken { + focusGainedAction.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 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 SignUpViewController: NSViewController { + /// @UIBinding private var username = "" + /// @UIBinding private var usernameFieldIsFocused = false + /// + /// // ... + /// + /// override func viewDidLoad() { + /// super.viewDidLoad() + /// + /// let textField = NSTextField(text: $username) + /// textField.bind(focus: $usernameFieldIsFocused) + /// + /// 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 + /// } + /// } + /// + /// // ... + /// } + /// } + /// ``` + /// + /// 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` + /// 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`, the text + /// field loses 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 AppKit. +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 + } +} + +#endif 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/NSToolbarItem.swift b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift new file mode 100644 index 0000000000..cbc57bcde0 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/NSToolbarItem.swift @@ -0,0 +1,8 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +import AppKit + +extension NSToolbarItem: @unchecked @retroactive Sendable {} +extension NSToolbarItem: TargetActionProtocol {} + +#endif diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift new file mode 100755 index 0000000000..ca3fb725af --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/TargetActionProtocol.swift @@ -0,0 +1,202 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) +@_spi(Internals) public import SwiftNavigation +public 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 } +} + +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. + /// - 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 + } + } + + 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. + /// - 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 { + establishBinding(binding, to: keyPath, of: self, through: createActionProxyIfNeeded(), set: set) + } + + public func unbind(_ keyPath: KeyPath) { + removeBinding(to: keyPath) + } + + @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() + } +} + +/// 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. +/// +/// 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, 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( + _ binding: UIBinding, + to keyPath: KeyPath, + of owner: Owner, + 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 isSetting = LockIsolated(false) + let actionID = actionProxy?.addBindingAction { [weak owner] _ in + // 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 + } else { + binding.wrappedValue = owner[keyPath: keyPath] + } + } + + 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: NSKeyValueObservation? + 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] + } + } + } else { + observation = nil + } + let observationToken = ObserveToken { [weak actionProxy] in + if let actionID { + MainActor._assumeIsolated { + actionProxy?.removeBindingAction(for: actionID) + } + } + token.cancel() + observation?.invalidate() + } + owner.observationTokens[keyPath] = observationToken + return observationToken +} + +@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 + ) + } + } + + /// 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 +private let observationTokensKey = malloc(1)! +@MainActor +private let actionProxyKey = malloc(1)! + +#endif diff --git a/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift new file mode 100755 index 0000000000..fa3e5d06a3 --- /dev/null +++ b/Sources/AppKitNavigation/Bindings/TargetActionProxy.swift @@ -0,0 +1,178 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + +public import AppKit + +@MainActor +class TargetActionProxy: 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: [Action] = [] + + private var actions: [Action] = [] + + private var originTarget: AnyObject? + + 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 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 + + init(owner: any TargetActionProtocol) { + if #available(macOS 27, *) { + registersAsAdditionalTarget = owner is NSControl + } else { + registersAsAdditionalTarget = false + } + super.init() + + if #available(macOS 27, *), registersAsAdditionalTarget, let control = owner as? NSControl { + // 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. + control.addTarget(self, action: #selector(invokeAction(_:)), for: [.primaryActionTriggered]) + } 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 + ) + } + } + + /// 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) } + } + + @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. + // + // A 'nil' original target is forwarded as 'nil': it means "up the responder chain", which + // 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) + } + 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.removeAll { $0.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.removeAll { $0.id == id } + } + + func removeAllBindingActions() { + bindingActions.removeAll() + } +} + +/// 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/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md index 691e284b43..ffb40b4a4c 100644 --- a/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md +++ b/Sources/AppKitNavigation/Documentation.docc/AppKitNavigation.md @@ -2,6 +2,35 @@ 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. 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) @@ -10,6 +39,10 @@ Tools for making AppKit navigation simpler, more ergonomic and more precise. ## Topics +### Essentials + +- + ### Animations - ``withAppKitAnimation(_:_:completion:)`` @@ -21,3 +54,41 @@ Tools for making AppKit navigation simpler, more ergonomic and more precise. - ``NSViewRepresenting`` - ``NSViewControllerRepresenting`` + +### Binding controls to state + +- ``TargetActionProtocol`` +- ``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/NSTextView`` +- ``AppKit/NSTableView`` +- ``AppKit/NSOutlineView`` +- ``AppKit/NSCollectionView`` +- ``AppKit/NSMenuItem`` +- ``AppKit/NSSplitViewItem`` +- ``AppKit/NSTabViewController`` +- ``AppKit/NSColorPanel`` +- ``AppKit/NSFontManager`` +- ``AppKit/NSSavePanel`` +- ``AppKit/NSOpenPanel`` + +### Presenting content from state + +- ``WindowBackedContent`` +- ``AppKit/NSViewController`` +- ``AppKit/NSWindow`` +- ``AppKit/NSView`` +- ``AppKit/NSToolbarItem`` +- ``ObjectiveC/NSObject`` +- ``AppKit/NSAlert`` diff --git a/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md b/Sources/AppKitNavigation/Documentation.docc/Articles/StackNavigationWithAppKitPlus.md new file mode 100644 index 0000000000..3f10499fe9 --- /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 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 + +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/Internal/CollectionViewDelegateProxy.swift b/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift new file mode 100644 index 0000000000..de2bf68e61 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/CollectionViewDelegateProxy.swift @@ -0,0 +1,59 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + 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 + /// 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/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/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/Sources/AppKitNavigation/Internal/OptionIndex.swift b/Sources/AppKitNavigation/Internal/OptionIndex.swift new file mode 100644 index 0000000000..7cece32f24 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/OptionIndex.swift @@ -0,0 +1,70 @@ +#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 { + 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), + 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 { + let currentOptions = options.value() + guard currentOptions.indices.contains(newValue) + else { + reportIssue( + """ + A selection binding was given position \(newValue), which matches none of its \ + \(currentOptions.count) options. + """, + fileID: fileID.rawValue, + filePath: filePath.rawValue, + line: line, + column: column + ) + return + } + self = currentOptions[newValue] + } + } +} + +#endif diff --git a/Sources/AppKitNavigation/Internal/RunLoopWait.swift b/Sources/AppKitNavigation/Internal/RunLoopWait.swift new file mode 100644 index 0000000000..63290f3f88 --- /dev/null +++ b/Sources/AppKitNavigation/Internal/RunLoopWait.swift @@ -0,0 +1,68 @@ +#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, 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 + /// 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, .exit]).rawValue, true, CFIndex.max + ) { observer, _ in + MainActor._assumeIsolated { + guard condition() else { return } + CFRunLoopObserverInvalidate(observer) + body() + } + } + CFRunLoopAddObserver(CFRunLoopGetMain(), observer, .commonModes) + return { + CFRunLoopObserverInvalidate(observer) + } + } + } + + 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 + } + + /// 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/BindingPresenter.swift b/Sources/AppKitNavigation/Navigation/BindingPresenter.swift new file mode 100644 index 0000000000..932ce0aa5b --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/BindingPresenter.swift @@ -0,0 +1,290 @@ +#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) + #if AppKitPlus + installDismissAction(for: presentation) + #endif + 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?() + } + } + } + + #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) + } + + 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) + } + + @MainActor + 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/Dismiss.swift b/Sources/AppKitNavigation/Navigation/Dismiss.swift new file mode 100644 index 0000000000..0266597f54 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Dismiss.swift @@ -0,0 +1,110 @@ +#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" } + } + + /// 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) } + set { self[DismissActionTrait.self] = newValue.run == nil ? nil : DismissActionBox(newValue) } + } + } +#endif diff --git a/Sources/AppKitNavigation/Navigation/Modal.swift b/Sources/AppKitNavigation/Navigation/Modal.swift new file mode 100644 index 0000000000..9128895df6 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Modal.swift @@ -0,0 +1,482 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + + 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() + } + } + + /// 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) + } + } + + /// 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 + ) + } + + /// 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) + } + } + + /// 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 + ) + } + } + + // 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() + } + } + + /// 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) + } + } + + /// 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 + ) + } + + /// 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) + } + } + + /// 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 + ) + } + } + + // 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 + ) { + 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. + 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() + } + } + } + modalContent.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() + } + } + + func end(_ content: Content, transaction: UITransaction) { + // 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() + } + } + } + + /// 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) + // NB: The window is still on screen while it is about to close. + _ = RunLoopWait.until({ !window.isVisible }, then: didEnd) + } + } + + func end(_ window: NSWindow, transaction: UITransaction) { + ModalStack.end(window) { + window.close() + } + } + } + + /// Keeps a notification observer alive until it has fired once. + @MainActor + private final class OneTimeObserver { + var observer: NotificationObserver? + + func invalidate() { + observer?.invalidate() + observer = nil + } + } + + /// 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 { + if endingWindows.isEmpty { + run() + } else { + loopsToStart.append(run) + } + } + } + } + + /// 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() + } + + /// 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 + } + + /// 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) + } + } + + 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 + } + + private static func stopObserving() { + guard let runLoopObserver else { return } + CFRunLoopObserverInvalidate(runLoopObserver) + self.runLoopObserver = nil + } + + 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 { + MainActor._assumeIsolated { + end() + } + } + } + } + +#endif diff --git a/Sources/AppKitNavigation/Navigation/NavigationDestination.swift b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift new file mode 100644 index 0000000000..45674e52d5 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/NavigationDestination.swift @@ -0,0 +1,264 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) && AppKitPlus + public import AppKit + import AppKitPlus + public import SwiftNavigation + + 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 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. + /// + /// - 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 { + // 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 } + let navigationController = + presenter.navigationController ?? presenter as? NSNavigationController + return (navigationController ?? presenter).appKitNavigationIsViewOnScreenOrMinimized + }, + then: body + ) + } + + 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 + } + } + + 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/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/Popover.swift b/Sources/AppKitNavigation/Navigation/Popover.swift new file mode 100644 index 0000000000..54d118bde1 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Popover.swift @@ -0,0 +1,518 @@ +#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 + /// 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()) + } + } + + /// 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)) + } + } + + /// 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)) + } + } + + /// 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)) + } + } + + /// 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)) + } + } + + 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 + ) + } + } + + @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()) + } + } + + /// 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)) + } + } + + /// 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)) + } + } + + /// 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)) + } + } + + /// 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)) + } + } + + private func popoverStyle( + behavior: NSPopover.Behavior, + animates: Bool + ) -> PopoverStyle { + PopoverStyle( + anchor: ToolbarItemAnchor(toolbarItem: self), + behavior: behavior, + animates: animates + ) + } + } + + // MARK: - Style + + /// 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 } + + func show(_ popover: NSPopover) + } + + @MainActor + private struct ViewAnchor: PopoverAnchor { + weak var view: NSView? + let rect: NSRect + let preferredEdge: NSRectEdge + + var isOnScreen: Bool { + view?.window?.isVisible == true + } + + func show(_ popover: NSPopover) { + guard let view else { return } + popover.show(relativeTo: rect, of: view, preferredEdge: preferredEdge) + } + } + + @available(macOS 14.0, *) + @MainActor + private struct ToolbarItemAnchor: PopoverAnchor { + weak var toolbarItem: NSToolbarItem? + + var isOnScreen: Bool { + guard let toolbar = toolbarItem?.toolbar, toolbar.isVisible else { return false } + return NSApplication.shared.windows.contains { $0.toolbar === toolbar && $0.isVisible } + } + + func show(_ popover: NSPopover) { + guard let toolbarItem else { return } + popover.show(relativeTo: toolbarItem) + } + } + + /// 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)? + + init(viewController: NSViewController) { + popover.contentViewController = viewController + } + + /// Reports that the popover has closed, once. + func finish() { + closeObserver?.invalidate() + closeObserver = nil + let didEnd = didEnd + self.didEnd = nil + didEnd?() + } + } + + #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 { + let anchor: Anchor + let behavior: NSPopover.Behavior + let animates: Bool + + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + RunLoopWait.until({ [anchor] in anchor.isOnScreen }, then: body) + } + + 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) + } + + 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/Presentation.swift b/Sources/AppKitNavigation/Navigation/Presentation.swift new file mode 100644 index 0000000000..b64fc5fb3b --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Presentation.swift @@ -0,0 +1,448 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + public import AppKit + + 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) + } + + /// 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 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 + /// 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() + } + } + + /// 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) + } + + /// 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) + } + + /// 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) + } + } + + /// 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 + ) + } + + /// 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 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 + /// 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 + ) + } + + /// 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 + ) + } + + 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) + } + } + } + + /// 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 { + // 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 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): + isReady = { $0.appKitNavigationIsViewOnScreen } + case .style(.modalWindow), .style(.custom), .custom: + isReady = { $0.appKitNavigationIsViewOnScreenOrMinimized } + } + return RunLoopWait.until( + { [weak presenter] in presenter.map(isReady) ?? true }, + then: body + ) + } + + func begin( + _ child: NSViewController, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + guard let presenter else { + didEnd() + return + } + // 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, 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({ record.hasEnded || record.isOver() }, then: { record.end() }) + switch transition { + case let .style(style): + presenter.present(child, as: style) + case let .custom(present, _): + withUITransaction(transaction) { + present(child, transaction) + } + } + // 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) { + 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) + } + case let .custom(_, dismiss): + withUITransaction(transaction) { + dismiss(child, transaction) + } + } + // 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 } + let isOver = record.isOver() + if isOver || !record.hasBeenPresented || presenter == nil { + record.end() + } + } + } + + /// 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. + private(set) var hasBeenPresented = false + private var didEnd: (@MainActor () -> Void)? + + init( + presenter: NSViewController, + child: NSViewController, + didEnd: @escaping @MainActor () -> Void + ) { + self.presenter = presenter + self.child = child + self.didEnd = didEnd + } + + var hasEnded: Bool { + 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 } + 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/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/Sources/AppKitNavigation/Navigation/Sheet.swift b/Sources/AppKitNavigation/Navigation/Sheet.swift new file mode 100644 index 0000000000..af4d86af73 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/Sheet.swift @@ -0,0 +1,193 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + + 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() + } + } + + /// 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) + } + } + + /// 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 + ) + } + + /// 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) + } + } + + /// 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 + ) + } + } + + /// Attaches content to a window as a sheet. + @MainActor + private struct SheetStyle: PresentationStyle { + weak var parentWindow: NSWindow? + + func whenReady(_ body: @escaping @MainActor () -> Void) -> @MainActor () -> Void { + RunLoopWait.until( + { [weak parentWindow] in parentWindow?.isVisible == true }, + then: body + ) + } + + func begin( + _ content: Content, + transaction: UITransaction, + didEnd: @escaping @MainActor () -> Void + ) { + guard let parentWindow, let presentableContent = content.presentableContent() else { + didEnd() + return + } + 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) + } + } + + func end(_ content: Content, transaction: UITransaction) { + // 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) + } + } + +#endif diff --git a/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift new file mode 100644 index 0000000000..5b8ea0f033 --- /dev/null +++ b/Sources/AppKitNavigation/Navigation/WindowBackedContent.swift @@ -0,0 +1,113 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + + public import AppKit + + /// 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 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 {} + + 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. + var appKitNavigationWindow: NSWindow { get } + + /// Attaches the content to `parentWindow` as a sheet, and calls `completionHandler` once the + /// sheet has ended. + func appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) + + /// Runs the content in an application-modal loop, and returns once the loop has ended. + 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: PresentableWindowBackedContent { + var appKitNavigationWindow: NSWindow { self } + + 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) { response in + if response == .OK { + savePanel.appKitNavigationWriteConfirmedChoice() + } + completionHandler() + } + } else { + parentWindow.beginSheet(self) { _ in + completionHandler() + } + } + } + + func appKitNavigationRunModal() { + if let savePanel = self as? NSSavePanel { + if savePanel.runModal() == .OK { + savePanel.appKitNavigationWriteConfirmedChoice() + } + } else { + _ = NSApplication.shared.runModal(for: self) + } + } + } + + extension NSAlert: PresentableWindowBackedContent { + var appKitNavigationWindow: NSWindow { window } + + func appKitNavigationBeginSheet( + attachedTo parentWindow: NSWindow, + completionHandler: @escaping @MainActor () -> Void + ) { + beginSheetModal(for: parentWindow) { _ in + completionHandler() + } + } + + func appKitNavigationRunModal() { + _ = runModal() + } + } + +#endif 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 diff --git a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved index e8e2a2bd30..ee8c8a8e97 100644 --- a/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/SwiftNavigation.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,13 +1,22 @@ { - "originHash" : "556faf476a22c66a001c9e0e2869bdf97eab5490bd68796c4d4263a81098fdc2", + "originHash" : "c29f1966f5086e34beae597b464b2409b3c6b0a2c352284799e5706fb0561522", "pins" : [ + { + "identity" : "appkitplus-release", + "kind" : "remoteSourceControl", + "location" : "https://github.com/AppKitSupportProgram/AppKitPlus-Release", + "state" : { + "revision" : "63039aa889273976aa95087dd0c0c3e109caca9d", + "version" : "0.23.0" + } + }, { "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 +24,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 +33,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 +42,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 +51,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 +60,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 +69,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 +105,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 +123,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 +132,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 +141,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 +153,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 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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + 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 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 diff --git a/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift b/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift new file mode 100644 index 0000000000..519685f48c --- /dev/null +++ b/Tests/AppKitNavigationTests/ColorPanelBindingTests.swift @@ -0,0 +1,92 @@ +#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) + } + + /// 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?) {} + } + + /// Holds the color in a value, the way a model would, rather than binding a class instance + /// directly. + private struct Swatch { + 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) + 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 diff --git a/Tests/AppKitNavigationTests/CommonControlBindingTests.swift b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift new file mode 100644 index 0000000000..d40534a258 --- /dev/null +++ b/Tests/AppKitNavigationTests/CommonControlBindingTests.swift @@ -0,0 +1,336 @@ +#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: - 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) + } + + /// 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(frame: .zero, pullsDown: false) + popUpButton.addItems(withTitles: ["Light", "Regular", "Bold", "Custom…"]) + popUpButton.bind(selection: $weight, options: Weight.allCases) + + popUpButton.selectItem(at: 3) + withKnownIssue { + sendAction(of: popUpButton) + } + #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: - 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: - 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: - 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.. 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/ControlBindingLifetimeTests.swift b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift new file mode 100644 index 0000000000..93c9d7182b --- /dev/null +++ b/Tests/AppKitNavigationTests/ControlBindingLifetimeTests.swift @@ -0,0 +1,38 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import Testing + + @MainActor + @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() { + @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") + } + + /// 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 diff --git a/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift new file mode 100644 index 0000000000..32d02343a5 --- /dev/null +++ b/Tests/AppKitNavigationTests/ControlBindingRoundTripTests.swift @@ -0,0 +1,146 @@ +#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(.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. + _ = 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(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) + } + + 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/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/FontManagerBindingTests.swift b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift new file mode 100644 index 0000000000..0e7dea5e20 --- /dev/null +++ b/Tests/AppKitNavigationTests/FontManagerBindingTests.swift @@ -0,0 +1,76 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + // 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 { + /// 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 { + try withChangeFontResponder { + @UIBinding var textStyle = TextStyle(font: try Self.helvetica()) + let fontManager = NSFontManager.shared + fontManager.bind(font: $textStyle.font) + + fontManager.addFontTrait(Self.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) + + 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 + /// directly. + 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 diff --git a/Tests/AppKitNavigationTests/ItemValidationTests.swift b/Tests/AppKitNavigationTests/ItemValidationTests.swift new file mode 100644 index 0000000000..c8aef48f42 --- /dev/null +++ b/Tests/AppKitNavigationTests/ItemValidationTests.swift @@ -0,0 +1,82 @@ +#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. + /// 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 validateMenuItem(_ menuItem: NSMenuItem) -> 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) + 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 diff --git a/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift b/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift new file mode 100644 index 0000000000..645d841099 --- /dev/null +++ b/Tests/AppKitNavigationTests/MainRunLoopKeeper.swift @@ -0,0 +1,108 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import Foundation + #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. + /// + /// `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 diff --git a/Tests/AppKitNavigationTests/ModalPresentationTests.swift b/Tests/AppKitNavigationTests/ModalPresentationTests.swift new file mode 100644 index 0000000000..bb59272488 --- /dev/null +++ b/Tests/AppKitNavigationTests/ModalPresentationTests.swift @@ -0,0 +1,560 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// 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() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + // MARK: - Modal session + + @MainActor + func testUserClosingAModalSessionWindowWritesFalseBack() { + 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") + + // What the window's close button does once 'windowShouldClose' agrees. + window.close() + + XCTAssertTrue(waitUntil { !isPresented }, "Closing the window did not write 'false' back") + } + + @MainActor + func testSettingTheBindingToFalseEndsTheModalSession() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + host.modalSession(isPresented: $isPresented) { window } + + isPresented = true + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow === window }, "The modal session never began" + ) + + isPresented = false + + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow == nil && !window.isVisible }, + "The modal session did not end, or its window stayed on screen" + ) + } + + @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() + let firstWindow = makeWindow() + let secondWindow = makeWindow() + @UIBinding var isFirstPresented = false + @UIBinding var isSecondPresented = false + var secondDismissCount = 0 + host.modalSession(isPresented: $isFirstPresented) { firstWindow } + host.modalSession(isPresented: $isSecondPresented, onDismiss: { secondDismissCount += 1 }) { + secondWindow + } + + isFirstPresented = true + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow === firstWindow }, + "The first modal session never began" + ) + isSecondPresented = true + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow === secondWindow }, + "The second modal session never began" + ) + spinRunLoop(for: 0.3) + + 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" + ) + + isSecondPresented = false + isFirstPresented = false + XCTAssertTrue( + waitUntil { NSApplication.shared.modalWindow == nil }, "The modal sessions never ended" + ) + } + + // MARK: - Modal loop + + @MainActor + func testSettingTheBindingToFalseTakesTheModalWindowOffScreen() { + 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) { + isPresented = false + } + isPresented = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "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" + ) + } + + @MainActor + func testUserClosingAModalWindowWritesFalseBack() { + 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) { + // What the window's close button does once 'windowShouldClose' agrees. + window.close() + } + isPresented = true + + 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" + ) + } + + @MainActor + func testSettingTheBindingToFalseCallsOnDismissOnce() { + let host = NSObject() + let window = makeWindow() + @UIBinding var isPresented = false + var dismissCount = 0 + host.modal(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { window } + abortModalLoops(after: 5) + + perform(after: 0.5) { + isPresented = false + } + isPresented = true + + 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 isPresented = false + host.modal(isPresented: $isPresented) { alert } + abortModalLoops(after: 5) + + let start = Date() + perform(after: 0.5) { + isPresented = false + } + isPresented = true + + 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" + ) + XCTAssertTrue(waitUntil { !alert.window.isVisible }, "The alert stayed on screen") + } + + @MainActor + func testSettingTheBindingToFalseStopsAModalSavePanel() { + let host = NSObject() + let savePanel = NSSavePanel() + @UIBinding var isPresented = false + host.modal(isPresented: $isPresented) { savePanel } + abortModalLoops(after: 8) + + let start = Date() + perform(after: 1) { + isPresented = false + } + isPresented = true + + 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() + 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 windowStayedPresented = Recorded(false) + let windowStayedVisible = Recorded(false) + let alertWasOnTop = Recorded(false) + perform(after: 0.4) { + isAlertPresented = true + } + perform(after: 1.2) { + windowStayedPresented.value = isWindowPresented + windowStayedVisible.value = window.isVisible + alertWasOnTop.value = NSApplication.shared.modalWindow === alert.window + isAlertPresented = false + } + perform(after: 1.8) { + isWindowPresented = false + } + isWindowPresented = true + + XCTAssertTrue( + waitUntil(timeout: 5) { + !isWindowPresented && !isAlertPresented && NSApplication.shared.modalWindow == nil + }, + "The modals never all ended" + ) + 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 isPresented = false + host.modal(isPresented: $isPresented) { + 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) { + isPresented = false + } + isPresented = true + + XCTAssertTrue(waitUntil(timeout: 4) { !isPresented }, "The binding was never reset") + spinRunLoop(for: 0.3) + 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 + 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/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 diff --git a/Tests/AppKitNavigationTests/NavigationDestinationTests.swift b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift new file mode 100644 index 0000000000..9aabd713cd --- /dev/null +++ b/Tests/AppKitNavigationTests/NavigationDestinationTests.swift @@ -0,0 +1,194 @@ +#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) + } + + /// 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() { + 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() + @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 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 diff --git a/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift new file mode 100644 index 0000000000..8742f67c91 --- /dev/null +++ b/Tests/AppKitNavigationTests/ObjectiveCMethodNamingTests.swift @@ -0,0 +1,100 @@ +#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. + /// + /// 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 + // 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("-[NSButton appKitNavigationIsOn]"), + "The scan must find the library's own methods" + ) + + let unnamedMethods = addedMethods.filter { method in + !method.localizedCaseInsensitiveContains("AppKitNavigation") + } + + #expect(unnamedMethods.isEmpty, "Methods without the library's name: \(unnamedMethods)") + } + + /// 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 = 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: getsegmentdata(header, "__TEXT", &codeSize)) + return codeStart..<(codeStart + codeSize) + } + } +#endif diff --git a/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift b/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift new file mode 100644 index 0000000000..71822920aa --- /dev/null +++ b/Tests/AppKitNavigationTests/ObserveLifetimeTests.swift @@ -0,0 +1,80 @@ +#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 + /// 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 let 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 diff --git a/Tests/AppKitNavigationTests/OptionItemBindingTests.swift b/Tests/AppKitNavigationTests/OptionItemBindingTests.swift new file mode 100644 index 0000000000..da1a65a927 --- /dev/null +++ b/Tests/AppKitNavigationTests/OptionItemBindingTests.swift @@ -0,0 +1,274 @@ +#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, + /// 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/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 diff --git a/Tests/AppKitNavigationTests/PopoverPresentationTests.swift b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift new file mode 100644 index 0000000000..e304e2ec30 --- /dev/null +++ b/Tests/AppKitNavigationTests/PopoverPresentationTests.swift @@ -0,0 +1,324 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + #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 + + /// 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() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + // MARK: - View anchor + + @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) + + 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 } + ) { + 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 + func testChangingTheItemClosesThePreviousPopover() throws { + struct Item: Identifiable { + let id: Int + } + let host = makeHost() + let recorder = recordShownPopovers() + @UIBinding var item: Item? + var dismissCount = 0 + host.view.popover( + item: $item, behavior: .applicationDefined, onDismiss: { dismissCount += 1 } + ) { _ 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" + ) + + 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 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 diff --git a/Tests/AppKitNavigationTests/PresentationTestSupport.swift b/Tests/AppKitNavigationTests/PresentationTestSupport.swift new file mode 100644 index 0000000000..ce6b234111 --- /dev/null +++ b/Tests/AppKitNavigationTests/PresentationTestSupport.swift @@ -0,0 +1,193 @@ +#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 + // 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 + } + } + + /// An object that work scheduled with `perform(after:_:)` can reach without keeping it alive. + @MainActor + 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/ResponderChainForwardingTests.swift b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift new file mode 100644 index 0000000000..45d9a0bd70 --- /dev/null +++ b/Tests/AppKitNavigationTests/ResponderChainForwardingTests.swift @@ -0,0 +1,79 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + // 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 + + /// 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. + 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 + } + } + + @MainActor + @Suite struct ResponderChainForwardingTests { + 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 textStyle = TextStyle(font: NSFont.systemFont(ofSize: 12)) + let fontManager = NSFontManager.shared + 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 diff --git a/Tests/AppKitNavigationTests/SheetPresentationTests.swift b/Tests/AppKitNavigationTests/SheetPresentationTests.swift new file mode 100644 index 0000000000..b1e62e2301 --- /dev/null +++ b/Tests/AppKitNavigationTests/SheetPresentationTests.swift @@ -0,0 +1,319 @@ +#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 isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } + + isPresented = true + + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + } + + @MainActor + func testSettingTheBindingToFalseEndsTheSheet() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } + + isPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + + isPresented = false + + XCTAssertTrue(waitUntil { host.window.attachedSheet == nil }, "The sheet was not ended") + } + + @MainActor + func testUserEndingTheSheetWritesFalseBack() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { sheetWindow } + + isPresented = 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 { !isPresented }, "Ending the sheet did not write 'false' back") + } + + @MainActor + func testSettingTheBindingToFalseCallsOnDismissOnce() { + let host = makeHost() + let sheetWindow = makeWindow() + @UIBinding var isPresented = false + var dismissCount = 0 + host.window.sheet(isPresented: $isPresented, onDismiss: { dismissCount += 1 }) { + sheetWindow + } + + isPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === sheetWindow }, "The sheet never appeared" + ) + 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 isFirstPresented = false + @UIBinding var isSecondPresented = false + var secondDismissCount = 0 + host.window.sheet(isPresented: $isFirstPresented) { firstSheet } + host.window.sheet(isPresented: $isSecondPresented, onDismiss: { secondDismissCount += 1 }) { + secondSheet + } + + isFirstPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet === firstSheet }, "The first sheet never appeared" + ) + isSecondPresented = true + spinRunLoop(for: 0.5) + + 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" + ) + + 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 + func testClickingAButtonOfAnAlertSheetEndsTheSheetAndWritesFalseBack() throws { + let host = makeHost() + let alert = NSAlert() + alert.messageText = "Delete the item?" + alert.addButton(withTitle: "Delete") + @UIBinding var isPresented = false + host.window.sheet(isPresented: $isPresented) { alert } + + isPresented = 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 && !isPresented }, + "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 isPresented = false + host.window.sheet(isPresented: $isPresented) { alert } + + isPresented = 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 isPresented = false + 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) { host.window.attachedSheet == nil && !isPresented }, + "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 diff --git a/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift new file mode 100644 index 0000000000..35ffaf2fee --- /dev/null +++ b/Tests/AppKitNavigationTests/TableSelectionBindingTests.swift @@ -0,0 +1,306 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + #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 + + /// 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: - 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 + ) { + 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")]), + ]) + } + + /// 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() { + 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 diff --git a/Tests/AppKitNavigationTests/TargetActionTests.swift b/Tests/AppKitNavigationTests/TargetActionTests.swift new file mode 100644 index 0000000000..e54418b612 --- /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` 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; the + /// control events only cover the action it sends on Return. + @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 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 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 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 diff --git a/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift new file mode 100644 index 0000000000..9b33d5e437 --- /dev/null +++ b/Tests/AppKitNavigationTests/ViewControllerPresentationTests.swift @@ -0,0 +1,441 @@ +#if canImport(AppKit) && !targetEnvironment(macCatalyst) + import AppKit + import AppKitNavigation + import XCTest + + /// 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() + MainActor.assumeIsolated { + _ = NSApplication.shared + } + } + + // MARK: - Sheet style + + @MainActor + func testUserDismissingAPresentedSheetWritesFalseBack() { + let host = makeHost() + @UIBinding var isPresented = false + let sheetViewController = makeViewController() + 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 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() + @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") + host.window.attachedSheet?.contentViewController?.dismiss(nil) + XCTAssertTrue( + waitUntil { host.window.attachedSheet == nil && !isPresented }, + "The sheet never went away, or 'false' was never written back" + ) + + // 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( + 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.makeViewController() + } + + 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") + } + + /// 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 + 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) + // 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 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 + host.viewController.present(isPresented: $isFirstPresented, style: .sheet) { + firstViewController + } + host.viewController.present( + isPresented: $isSecondPresented, style: .sheet, onDismiss: { secondDismissCount += 1 } + ) { + secondViewController + } + + isFirstPresented = true + XCTAssertTrue( + waitUntil { host.window.attachedSheet?.contentViewController === firstViewController }, + "The first sheet never appeared" + ) + isSecondPresented = true + spinRunLoop(for: 0.5) + + 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") + } + + // 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() + let presentedViewController = makeViewController() + @UIBinding var isPresented = false + 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" + ) + } + + @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 + 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 { 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) + + isPresented = true + + XCTAssertTrue( + waitUntil { presentedChildren.count == 2 }, + "Setting the binding to 'true' again did not present the child again" + ) + } + } + + /// 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