Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion Sources/CodexBar/MenuBarLayoutRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ final class MenuBarLayoutTitleCache {
@MainActor
final class MenuBarLayoutRenderer {
private static let missingValue = "–"
private static let stackedBaselineOffset: CGFloat = -3 // Center multi-line NSStatusBarButton titles.

private struct TokenStyle {
let font: NSFont
Expand Down Expand Up @@ -138,11 +139,14 @@ final class MenuBarLayoutRenderer {
paragraphStyle.maximumLineHeight = 9.5
paragraphStyle.lineSpacing = -1
}
let attributes: [NSAttributedString.Key: Any] = [
var attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: foregroundColor,
.paragraphStyle: paragraphStyle,
]
if isStacked {
attributes[.baselineOffset] = Self.stackedBaselineOffset
}
let result = NSMutableAttributedString()
var accessibilityLines: [String] = []

Expand Down
34 changes: 34 additions & 0 deletions Tests/CodexBarTests/MenuBarLayoutRendererTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,29 @@ struct MenuBarLayoutRendererTests {
#expect(bounds.height <= 22)
}

@Test
func `stacked titles apply a vertical centering offset`() throws {
let renderer = MenuBarLayoutRenderer()
let stacked = renderer.render(
layout: MenuBarLayout(lines: [
[.percent(window: .automatic)],
[.resetCountdown],
]),
data: self.data(),
icon: nil,
options: self.options())
let resetIndex = (stacked.attributedTitle.string as NSString).range(of: "in 2h").location
let singleLine = renderer.render(
layout: MenuBarLayout(lines: [[.percent(window: .automatic), .resetCountdown]]),
data: self.data(),
icon: nil,
options: self.options())

#expect(try #require(self.baselineOffset(in: stacked.attributedTitle, at: 0)) == -3)
#expect(try #require(self.baselineOffset(in: stacked.attributedTitle, at: resetIndex)) == -3)
#expect(self.baselineOffset(in: singleLine.attributedTitle, at: 0) == nil)
}

@Test
func `two line icon uses compact paragraph metrics`() {
let renderer = MenuBarLayoutRenderer()
Expand Down Expand Up @@ -303,4 +326,15 @@ struct MenuBarLayoutRendererTests {
}
return try totalBrightness / CGFloat(#require(visiblePixelCount > 0 ? visiblePixelCount : nil))
}

private func baselineOffset(in title: NSAttributedString, at index: Int) -> CGFloat? {
let value = title.attribute(.baselineOffset, at: index, effectiveRange: nil)
if let value = value as? CGFloat {
return value
}
if let value = value as? NSNumber {
return CGFloat(truncating: value)
}
return nil
}
}