sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.97k stars 117 forks source link

MenuBarExtra does not work with Defaults #106

Closed Wouter01 closed 1 year ago

Wouter01 commented 2 years ago

macOS 13.0 introduced a new SwiftUI Scene for showing a menubar icon: MenuBarExtra.

When using the initializer with isInserted, the settings window will just hang and show a beachball if isInserted has a value from Defaults. If AppStorage is used, everything works as expected.

Broken code:

Note that showPreferencesWindow has been replaced by showSettingsWindow in macOS 13.0

struct TestApp: App {
    @Default(.showMenuBarIcon) private var showMenubarIcon
    var menuBar: some Scene {
        MenuBarExtra("test", systemImage: "plus", isInserted: $showMenubarIcon) {
            Button {
                NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
            } label: {
                Text("Preferences")
            }
            .keyboardShortcut(.init(",", modifiers: .command))
            Divider()
            Button {
                NSApp.terminate(nil)
            } label: {
                Text("Quit")
            }
            .keyboardShortcut(.init("q", modifiers: .command))
        }
    }

    var body: some Scene {
        menuBar

        Settings {
            PreferencesView()
        }
    }
}

Working code:

struct TestApp: App {
    @AppStorage("showMenuBarIcon") private var showMenubarIcon = true
    var menuBar: some Scene {
        MenuBarExtra("test", systemImage: "plus", isInserted: $showMenubarIcon) {
            Button {
                NSApp.sendAction(Selector(("showSettingsWindow:")), to: nil, from: nil)
            } label: {
                Text("Preferences")
            }
            .keyboardShortcut(.init(",", modifiers: .command))
            Divider()
            Button {
                NSApp.terminate(nil)
            } label: {
                Text("Quit")
            }
            .keyboardShortcut(.init("q", modifiers: .command))
        }
    }

    var body: some Scene {
        menuBar

        Settings {
            PreferencesView()
        }
    }
}
sindresorhus commented 2 years ago

Thanks for reporting. I'll look into it if it's still an issue in beta 2. Beta 1 is usually super buggy and many things are generally fixed in beta 2.

sindresorhus commented 1 year ago

I'm going to assume this was resolved in the final macOS 13 version.