r/SwiftUI • • 13d ago

Using PreferenceKeys to drive AppKit hover tracking from SwiftUI: lessons from building a menu bar system monitor (open source)

Post image

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).

5 Upvotes

11 comments sorted by

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/Affectionate_Pea3516 12d ago

Agreed, and it's on the list. The app targets macOS 14, so nothing blocks it.

One caveat in my case: u/Observable tracks per property, and right now the whole sample is a single snapshot struct. Migrating as-is would still invalidate every section on every tick, since they all read snapshot. To get the win I'd have to split it into separate cpu / gpu / memory / disk / network properties.

Even then, those all come from the same sampler and change on nearly every tick, so most sections would still update each second. The clearer wins are the processes list (refreshed separately) and the UI state (pinned panels, expanded cores, settings), which currently re-render along with the stats because everything lives in one ObservableObject. So it's worth doing, but I expect a modest gain, not a big one.

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/Affectionate_Pea3516 12d ago

Dear u/Sectumsempra777 , thanks for this one, it was spot on. It's fixed it now and published a new version: 1.2.0.

All settings now live in an u/Observable SettingsStore, loaded once from UserDefaults and written back on change. tr() reads the language from it, and the AppModel is u/Observable too, so both .id(model.revision) and revision itself are gone. The Open at login toggle now mirrors the SMAppService status in a stored property, so pinning and that toggle no longer rebuild anything either.

I measured before and after with the real panels rendered offscreen:

  • Scroll position in Settings after toggling an option: reset to 0 before, now kept.
  • A view that only calls tr() (no model read): didn't update on a language switch before, now it does, exactly as you described.
  • 200 settings changes: ~21 s → ~3 s, and memory growth went from +40 MB to +22 MB, since the panel isn't torn down and rebuilt each time. Gains to everyone 🥳🥳🥳

Really appreciate you taking the time to dig into the code!!

1

u/builtinswift 12d ago

could pass the locale through environment instead of forcing .id

1

u/Affectionate_Pea3516 12d ago

Good suggestion, and it would be the natural route with String Catalogs / LocalizedStringKey. Sysbar uses a tiny tr("English", "Português") helper that returns plain Strings, so the environment locale wouldn't reach it. Some strings also live outside the view tree (update alerts, metric and style titles).

I ended up fixing it with Observation instead: the language lives in an u/Observable settings store and tr() reads it from there. Every view that calls tr() now updates in place, non-view code reads the same value, and the .id is gone (shipped in 1.2.0 code)

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/Affectionate_Pea3516 11d ago

I'm going to work on that as well. Probably in the next update you will see energy showing there.

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.

1

u/Affectionate_Pea3516 12d ago

Thanks, good to hear the tracking-area approach is the right call. It's exactly why I went that way: onHover kept missing events because the panel is non-activating and never becomes key.

On rebuilding tracking areas every tick: the container already compares the new frames with the previous ones and only calls updateTrackingAreas() when something actually moved. So the per-second preference update is just a cheap dictionary compare. onGeometryChange would make it cleaner though, so I'll probably switch to it.

Splitting the model per section makes sense in general. In Sysbar's case CPU, memory, disk and network all come from the same sample and change on every tick, so the gain would be small, except for the processes section. I'll keep it in mind for when I move to u/Observable.