Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Give the sidebar's list the focus only once it is in the window

Țugui Dragoș071dee43dc98
diff --git a/Peel/Navigation/SidebarFocus.swift b/Peel/Navigation/SidebarFocus.swift
index fe336735..58e0b41b 100644
--- a/Peel/Navigation/SidebarFocus.swift
+++ b/Peel/Navigation/SidebarFocus.swift
@@ -46,8 +46,10 @@ private struct ListFocus: NSViewRepresentable {
}
private func takeFocusIfNothingHasIt() {
+ // As a tree of views comes into a window this view can get there before the list, and AppKit refuses a
+ // first responder from outside the window.
guard let window, window.firstResponder === window,
- let list = list(in: enclosingSplitViewItem?.viewController.view)
+ let list = list(in: enclosingSplitViewItem?.viewController.view), list.window === window
else { return }
window.makeFirstResponder(list)
}
diff --git a/PeelTests/SidebarFocusTests.swift b/PeelTests/SidebarFocusTests.swift
new file mode 100644
index 00000000..48ef45f2
--- /dev/null
+++ b/PeelTests/SidebarFocusTests.swift
@@ -0,0 +1,49 @@
+import AppKit
+@testable import Peel
+import SwiftUI
+import Testing
+
+@MainActor
+struct SidebarFocusTests {
+ private final class WatchedWindow: NSWindow {
+ var windowsOfTheViewsGivenFocus: [NSWindow?] = []
+
+ override func makeFirstResponder(_ responder: NSResponder?) -> Bool {
+ if let view = responder as? NSOutlineView { windowsOfTheViewsGivenFocus.append(view.window) }
+ return super.makeFirstResponder(responder)
+ }
+ }
+
+ private struct Sidebar: View {
+ var body: some View {
+ List {
+ Text("A row")
+ Text("Another row")
+ }
+ .takesFocusWhenNothingHasIt()
+ }
+ }
+
+ @Test func aListIsGivenTheFocusOnlyOnceItIsInTheWindow() throws {
+ let sidebar = NSHostingController(rootView: Sidebar())
+ sidebar.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300)
+ sidebar.view.layoutSubtreeIfNeeded()
+ let controller = NSSplitViewController()
+ controller.addSplitViewItem(NSSplitViewItem(sidebarWithViewController: sidebar))
+ controller.addSplitViewItem(NSSplitViewItem(viewController: NSHostingController(rootView: Color.clear)))
+ controller.view.frame = NSRect(x: 0, y: 0, width: 800, height: 300)
+ controller.view.layoutSubtreeIfNeeded()
+ let window = WatchedWindow(
+ contentRect: NSRect(x: 0, y: 0, width: 800, height: 300),
+ styleMask: [.titled], backing: .buffered, defer: true
+ )
+
+ window.contentViewController = controller
+ window.setContentSize(NSSize(width: 900, height: 400))
+ window.layoutIfNeeded()
+
+ #expect(!window.windowsOfTheViewsGivenFocus.isEmpty)
+ #expect(window.windowsOfTheViewsGivenFocus.allSatisfy { $0 === window })
+ #expect(window.firstResponder is NSOutlineView)
+ }
+}