import AppKit import SwiftUI /// The same time ranges drive drawing and hover. A gap only acquires a sleep /// marker when it overlaps an observed system sleep/wake pair. struct BatteryHistoryLayout { struct Bar { let index: Int let x: CGFloat let range: ClosedRange let charge: Double? let joinsPrevious: Bool let state: BatteryPowerFlow.State } struct SleepBand { let interval: DateInterval let chargeBeforeSleep: Double? let range: ClosedRange } enum Hit: Equatable { case sample(Int) case sleep(DateInterval) } private(set) var bars: [Bar] = [] private(set) var sleeps: [SleepBand] = [] let width: CGFloat let pitch: CGFloat let newest: Date? private(set) var previousContinuousDate: Date? init(samples: [TrendSample], sleeps: [DateInterval], width: CGFloat) { self.width = width // Keep one outgoing sample available beyond the viewport at capacity. pitch = max(4, width / CGFloat(MetricHistory.capacity - 1)) newest = samples.last?.date guard width > 0 else { return } var right = width for i in samples.indices.reversed() { let sample = samples[i] let left = right - pitch let previous = i > 0 ? samples[i - 1] : nil let elapsed = previous.map { sample.date.timeIntervalSince($0.date) } ?? 0 let continuous = elapsed > 0 && !sample.breakBefore && elapsed <= max(5, 2 * (previous?.expectedInterval ?? 0)) if i == samples.count - 1 && continuous { previousContinuousDate = previous?.date } let charge = sample.battery.flatMap { (0...1).contains($0) ? $0 : nil } if charge != nil || sample.powerFlow != nil { bars.append(Bar(index: i, x: (left + right) / 2, range: left...right, charge: charge, joinsPrevious: continuous, state: sample.powerFlow?.state ?? .unknown)) } guard let previous, elapsed > 0, left > -pitch else { break } right = left if !continuous { // Reserve a separate gap without spreading the surrounding samples. let gap = max(20, 5 * pitch) right -= gap for interval in sleeps { let begin = max(previous.date, interval.start) let end = min(sample.date, interval.end) guard end > begin else { continue } let x1 = right + gap * begin.timeIntervalSince(previous.date) / elapsed let x2 = right + gap * end.timeIntervalSince(previous.date) / elapsed self.sleeps.append(SleepBand(interval: interval, chargeBeforeSleep: previous.battery, range: x1...x2)) } } } bars.reverse() } func hit(at x: CGFloat) -> Hit? { if let band = sleeps.first(where: { $0.range.lowerBound <= x && x < $0.range.upperBound }) { return .sleep(band.interval) } return bars.last(where: { $0.range.contains(x) }).map { .sample($0.index) } } } struct BatteryHistoryChart: View { let samples: [TrendSample] let sleeps: [DateInterval] @ViewBuilder let detail: (TrendSample) -> Detail @Environment(\.panelMotionActive) private var active @Environment(\.accessibilityReduceMotion) private var reduceMotion @State private var pointer: CGPoint? var body: some View { GeometryReader { proxy in let layout = BatteryHistoryLayout(samples: samples, sleeps: sleeps, width: proxy.size.width) BatteryHistoryDrawing(layout: layout, hit: pointer.flatMap { layout.hit(at: $0.x) }, animates: active && !reduceMotion && pointer == nil) .contentShape(Rectangle()) .onContinuousHover { phase in switch phase { case .active(let point): pointer = point case .ended: pointer = nil } } .anchorPreference(key: ChartTooltipPreference.self, value: .bounds) { anchor in guard let pointer, let hit = layout.hit(at: pointer.x) else { return nil } return ChartTooltipPresentation(plot: anchor, point: pointer, content: AnyView(tooltip(hit))) } } .padding(.horizontal, 8) .padding(.bottom, 4) .accessibilityElement(children: .ignore) .accessibilityLabel(Text("metric.battery")) .accessibilityValue(Text(verbatim: MetricFormat.percent(samples.last?.battery))) } private func tooltip(_ hit: BatteryHistoryLayout.Hit) -> some View { VStack(alignment: .leading, spacing: 2) { switch hit { case .sleep(let interval): Label("power.sleep", systemImage: "moon.fill").bold() Text(interval.start.. BatteryHistoryViewport { BatteryHistoryViewport() } func updateNSView(_ viewport: BatteryHistoryViewport, context: Context) { viewport.update(layout, hit: hit, animates: animates) } } final class BatteryHistoryViewport: NSView { let plot = BatteryHistoryPlot() static let slideKey = "battery.slide" init() { super.init(frame: .zero) wantsLayer = true layer?.masksToBounds = true plot.wantsLayer = true addSubview(plot) } required init?(coder: NSCoder) { nil } override func layout() { super.layout() let pitch = plot.layoutData.pitch plot.frame = CGRect(x: -pitch, y: 0, width: bounds.width + pitch, height: bounds.height) plot.setBoundsOrigin(CGPoint(x: -pitch, y: 0)) } func update(_ value: BatteryHistoryLayout, hit: BatteryHistoryLayout.Hit?, animates: Bool) { let old = plot.layoutData let appended = value.newest != old.newest let resized = value.width != old.width plot.layoutData = value plot.hit = hit plot.needsDisplay = true if resized { needsLayout = true } if appended || resized || !animates { plot.layer?.removeAnimation(forKey: Self.slideKey) } guard appended, !resized, animates, window?.isVisible == true, let previous = value.previousContinuousDate, previous == old.newest else { return } let slide = CABasicAnimation(keyPath: "transform.translation.x") slide.fromValue = value.pitch slide.toValue = 0 slide.duration = 0.35 slide.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut) plot.layer?.add(slide, forKey: Self.slideKey) } } final class BatteryHistoryPlot: NSView { var layoutData = BatteryHistoryLayout(samples: [], sleeps: [], width: 0) var hit: BatteryHistoryLayout.Hit? override var isFlipped: Bool { true } override func draw(_ dirtyRect: NSRect) { let baseline = bounds.height - 11 guard baseline > 0 else { return } let bars = layoutData.bars let columnWidth = min(5, layoutData.pitch * 0.72) var start = 0 while start < bars.count { let bar = bars[start] var end = start while end + 1 < bars.count, bars[end + 1].state == bar.state, bars[end + 1].index == bars[end].index + 1, bars[end + 1].joinsPrevious { end += 1 } let range = bar.range.lowerBound...bars[end].range.upperBound let style = bar.state.style drawSymbol(style.symbol, color: style.color, in: range) for item in bars[start...end] { column(at: item.x, width: columnWidth, height: item.charge.map { $0 * baseline }, baseline: baseline, color: style.color) } start = end + 1 } for sleep in layoutData.sleeps { let color = NSColor(named: "MetricDisk") ?? .systemOrange drawSymbol("moon.fill", color: color, in: sleep.range) let span = sleep.range.upperBound - sleep.range.lowerBound let pitch = layoutData.pitch let count = max(1, Int((span / pitch).rounded())) let margin = (span - CGFloat(count - 1) * pitch) / 2 let height = sleep.chargeBeforeSleep.flatMap { (0...1).contains($0) ? $0 * baseline : nil } ?? 4 for i in 0.. 0 else { return } let fill = CGRect(x: track.minX, y: baseline - height, width: width, height: height) let fillRadius = min(radius, height / 2) color.setFill() NSBezierPath(roundedRect: fill, xRadius: fillRadius, yRadius: fillRadius).fill() } private func drawSymbol(_ symbol: String, color: NSColor, in range: ClosedRange) { let visibleLeft = max(0, range.lowerBound) let visibleWidth = min(layoutData.width, range.upperBound) - visibleLeft guard visibleWidth >= 13, let image = NSImage(systemSymbolName: symbol, accessibilityDescription: nil)? .withSymbolConfiguration(.init(paletteColors: [color])) else { return } let scale = min(11 / image.size.width, 9 / image.size.height) let size = CGSize(width: image.size.width * scale, height: image.size.height * scale) let icon = CGRect(x: visibleLeft + (visibleWidth - size.width) / 2, y: bounds.maxY - 5.5 - size.height / 2, width: size.width, height: size.height) image.draw(in: icon, from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil) } }