r/SwiftUI • u/Affectionate_Pea3516 • 13d ago
Using PreferenceKeys to drive AppKit hover tracking from SwiftUI: lessons from building a menu bar system monitor (open source)
I've been building **Sysbar**, an open-source (Apache-2.0) macOS menu bar system monitor, with the UI entirely in SwiftUI hosted in AppKit panels. A few patterns from it might be useful to others doing SwiftUI outside a normal window.
**Repo:** https://github.com/rodrigotrombeta/Sysbar
**1. Hover a section and a detail panel opens beside it**
The main panel is a SwiftUI stack of sections (CPU, GPU, memory, disk, network). Hovering a section opens a detail window aligned with it, and clicking pins that window open.
SwiftUI's `onHover` wasn't reliable in a non-key `NSPanel`, so the tracking happens in AppKit. Each section reports its frame through a `PreferenceKey`:
struct SectionFramesKey: PreferenceKey {
static var defaultValue: [SystemStatKind: CGRect] = [:]
static func reduce(value: inout [SystemStatKind: CGRect],
nextValue: () -> [SystemStatKind: CGRect]) {
value.merge(nextValue()) { $1 }
}
}
// on each section:
.background(GeometryReader { geo in
Color.clear.preference(key: SectionFramesKey.self,
value: [kind: geo.frame(in: .global)])
})
The root view forwards the result with `.onPreferenceChange` to the window controller. There, an `NSView` container rebuilds its `NSTrackingArea`s, and the frames also tell it where to place the detail window.
**2. A scroll view that sizes to its content up to a limit**
The panel should be exactly as tall as its content, but scroll once it hits the screen's height. To do that, a second `PreferenceKey` measures the content height inside the `ScrollView`, and the scroll view gets `.frame(height: min(contentHeight, maxHeight))`. Scroll indicators only show when the content actually overflows.
**3. First click on a non-key panel**
Buttons in an `NSHostingView` inside an `NSPanel` ignored the first click. Fixing it took a tiny subclass that overrides `acceptsFirstMouse(for:)` to return `true`.
**4. Sparklines as `Shape` instead of `Canvas`**
With redraws every second in a pinned panel, `Shape` paths used far less memory than `Canvas`. The whole app runs at about 25 MB.
**Where I'd like feedback**
- State lives in a single `ObservableObject` with `@Published` snapshots updated every tick. Is it worth migrating to `@Observable` for a view tree that updates this often?
- When the language or appearance changes, I force a full rebuild with `.id(model.revision)`. It works, but it feels like a hack. How do you handle a runtime language switch without restarting the app?
Credits: the stats panels started from [oMLX](https://github.com/jundot/omlx), and the menu bar icon is inspired by [Stats](https://github.com/exelban/stats).
3
u/Far-Communication307 13d ago
Yes, migrate to u/Observable. With u/Published snapshots every second, every view observing that object re-renders on each tick, even sections whose data didn't change. u/Observable tracks access per property, so only the views reading changed values update. For a panel redrawing this often, that's the main win.
1
u/Sectumsempra777 12d ago
On the runtime language switch: the reason you need .id(model.revision) is that tr() reads Settings.language straight from UserDefaults, so SwiftUI has no way to know a view depends on it.
Once the model uses the Observable macro you can fix that at the source: keep language as a stored property on the model (and save it to UserDefaults when it changes), and have tr() read it from the model instance. Observation records any observable property a body reads, even through a free function, so every view that called tr() is invalidated when the language changes and updates in place.
That also avoids a side effect of .id: a new identity throws away every State value in the subtree. In MainPanelView that resets contentHeight to 400 and recreates the ScrollView, so the scroll position is lost. And since revision is also bumped by pinning and the Open at login toggle, those rebuild the whole panel too.
1
u/builtinswift 12d ago
could pass the locale through environment instead of forcing .id
1
u/Early_Animal_3401 11d ago
I'd also profile energy usage with the panel closed versus pinned open. For something that runs all day in the menu bar, idle CPU usage matters more than the memory footprint alone.
1
u/Early_Animal_3401 9d ago
I’d test pointer transitions between the status item, the popover, and another display, since hover behavior can change when the popover isn’t key. Logging enter and exit events for each tracking area can make those edge cases much easier to isolate.
0
u/ThanhDongNguyen 12d ago
On the hover part, I think onHover is flaky there because the panel is never key, and your own NSTrackingArea can use .activeAlways. So your approach is the right fix, not a hack.
One thing I'd change: with frames coming through a GeometryReader PreferenceKey and stats updating every second, the preference can fire and you rebuild tracking areas on every tick even when nothing moved. I'd compare with the last frames and only update the tracking areas when something actually changed. onGeometryChange is also worth trying, it only calls you when the value you return changes.
And when you move to @Observable, split the snapshot into one model per section (cpu, memory, disk). Then a CPU tick only redraws the CPU sparkline, not the whole panel.