From d6998fe5ce41b9454a13d599e2e5bcca8aa44021 Mon Sep 17 00:00:00 2001 From: yogeshprasad098 Date: Thu, 26 Nov 2026 22:43:52 -0800 Subject: [PATCH] fix(app): leave a gap in History where nothing was recorded The charts joined the last sample before a stretch with no recording, such as Chargectl being quit, to the first one after, so a straight line ran across hours with no data, and hovering snapped between the two ends. Draw each unbroken run of samples as its own line, let the hover line follow the pointer with its dot on the line, and say "Not recorded" in a gap. The charger strip stops at a gap too. --- App/Dashboard/HistoryPage.swift | 63 +++++++++++++++++--------------- App/Dashboard/OverviewPage.swift | 49 +++++++++++++++---------- App/Debug/DesignRender.swift | 12 +++++- CHANGELOG.md | 9 +++++ Shared/XPC/DaemonModels.swift | 51 ++++++++++++++++++++++++++ Tests/SharedModelTests.swift | 41 +++++++++++++++++++++ 6 files changed, 175 insertions(+), 50 deletions(-) diff --git a/App/Dashboard/HistoryPage.swift b/App/Dashboard/HistoryPage.swift index 1195cf4..a927564 100644 --- a/App/Dashboard/HistoryPage.swift +++ b/App/Dashboard/HistoryPage.swift @@ -69,10 +69,9 @@ struct HistoryPage: View { } private func content(_ samples: [HistorySample], domain: ClosedRange) -> some View { - let shown = hovered.flatMap { date in - samples.min { abs($0.date.timeIntervalSince(date)) < abs($1.date.timeIntervalSince(date)) } - } - let reading = shown ?? samples.last + // The sample recorded nearest the pointer; nil while hovering a time nothing was recorded. + let shown = hovered.flatMap { samples.sample(near: $0) } + let reading = hovered == nil ? samples.last : shown let since = model.history.first.map(\.date).flatMap { $0 > domain.lowerBound ? $0 : nil } return VStack(spacing: 14) { SpanRow(spans: [1, 1, 1, 1]) { @@ -83,7 +82,7 @@ struct HistoryPage: View { VStack(alignment: .leading, spacing: 14) { PanelHeader(title: "Charge", symbol: "chart.xyaxis.line") { HStack(alignment: .firstTextBaseline, spacing: 8) { - if let since, shown == nil { + if let since, hovered == nil { Label( "Recorded since \(since.formatted(.dateTime.hour().minute()))", systemImage: "circle.fill" @@ -91,9 +90,9 @@ struct HistoryPage: View { .labelStyle(DotLabelStyle()) .padding(.trailing, 6) } - Text(shown.map { $0.date.formatted(.dateTime.hour().minute()) } ?? "Now") + Text(hovered.map { $0.formatted(.dateTime.hour().minute()) } ?? "Now") Text( - "\(Text("\(reading?.percent ?? 0)").font(.system(size: 24, weight: .semibold)))\(Text("%").font(.system(size: 13, weight: .medium)))" + "\(Text(reading.map { "\($0.percent)" } ?? "–").font(.system(size: 24, weight: .semibold)))\(Text("%").font(.system(size: 13, weight: .medium)))" ) .foregroundStyle(.primary) .monospacedDigit() @@ -221,29 +220,34 @@ struct HistoryPage: View { private func temperatureCard( _ samples: [HistorySample], domain: ClosedRange, shown: HistorySample?, reading: HistorySample? ) -> some View { - let points = samples.compactMap { s in s.temperature.map { (s.date, unit.value($0)) } } + let points = zip(samples, samples.runs).compactMap { s, run in + s.temperature.map { (s.date, unit.value($0), run) } + } let values = points.map(\.1) let low = (values.min() ?? 0) - max(((values.max() ?? 0) - (values.min() ?? 0)) * 0.2, 0.6) let high = (values.max() ?? 1) + max(((values.max() ?? 0) - (values.min() ?? 0)) * 0.2, 0.6) return Panel { VStack(alignment: .leading, spacing: 12) { PanelHeader(title: "Temperature", symbol: "thermometer.medium") { - readout(shown, unit.format(reading?.temperature)) + readout(unit.format(reading?.temperature)) } Chart { - ForEach(points, id: \.0) { date, value in + ForEach(points, id: \.0) { date, value, run in AreaMark( - x: .value("Time", date), yStart: .value("Base", low), yEnd: .value("Temperature", value) + x: .value("Time", date), yStart: .value("Base", low), yEnd: .value("Temperature", value), + series: .value("Run", run) ) .interpolationMethod(.monotone) .foregroundStyle( LinearGradient( colors: [Theme.warn.opacity(0.2), Theme.warn.opacity(0)], startPoint: .top, endPoint: .bottom)) - LineMark(x: .value("Time", date), y: .value("Temperature", value)) - .interpolationMethod(.monotone) - .foregroundStyle(Theme.warn) - .lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round)) + LineMark( + x: .value("Time", date), y: .value("Temperature", value), series: .value("Run", run) + ) + .interpolationMethod(.monotone) + .foregroundStyle(Theme.warn) + .lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round)) } if let threshold = model.settings.flatMap({ $0.heatProtection ? $0.heatThreshold : nil }), unit.value(threshold) < high + 5 @@ -252,9 +256,9 @@ struct HistoryPage: View { .lineStyle(StrokeStyle(lineWidth: 1, dash: [3, 4])) .foregroundStyle(Theme.warn.opacity(0.7)) } - crosshair(shown) - if let shown, let value = shown.temperature { - PointMark(x: .value("Time", shown.date), y: .value("Temperature", unit.value(value))) + crosshair(recorded: shown != nil) + if let hovered, let value = samples.value(at: hovered, { $0.temperature }) { + PointMark(x: .value("Time", hovered), y: .value("Temperature", unit.value(value))) .foregroundStyle(Theme.warn).symbolSize(40) } } @@ -287,18 +291,18 @@ struct HistoryPage: View { return Panel { VStack(alignment: .leading, spacing: 12) { PanelHeader(title: "Power", symbol: "bolt") { - Text(shown.map { $0.date.formatted(.dateTime.hour().minute()) } ?? "Now") + Text(hovered.map { $0.formatted(.dateTime.hour().minute()) } ?? "Now") } Chart { RuleMark(y: .value("Zero", 0)) .lineStyle(StrokeStyle(lineWidth: 1, dash: [2, 3])) .foregroundStyle(Theme.lineStrong) ForEach(series.filter { !hiddenPower.contains($0.key) }, id: \.key) { item in - ForEach(samples, id: \.date) { sample in + ForEach(Array(zip(samples, samples.runs)), id: \.0.date) { sample, run in if let value = item.value(sample) { LineMark( x: .value("Time", sample.date), y: .value(item.title, value), - series: .value("Series", item.title) + series: .value("Series", "\(item.title) \(run)") ) .interpolationMethod(.monotone) .foregroundStyle(item.tint) @@ -306,7 +310,7 @@ struct HistoryPage: View { } } } - crosshair(shown) + crosshair(recorded: shown != nil) } .modifier(SharedChartStyle(domain: domain, hovered: $hovered, format: { "\(Int($0)) W" })) .chartYScale(domain: low...high) @@ -347,18 +351,19 @@ struct HistoryPage: View { return Format.watts(value) } - private func readout(_ shown: HistorySample?, _ value: String) -> some View { + private func readout(_ value: String) -> some View { HStack(alignment: .firstTextBaseline, spacing: 8) { - Text(shown.map { $0.date.formatted(.dateTime.hour().minute()) } ?? "Now") + Text(hovered.map { $0.formatted(.dateTime.hour().minute()) } ?? "Now") Text(value).font(.system(size: 15, weight: .semibold)).foregroundStyle(.primary).monospacedDigit() } } - @ChartContentBuilder private func crosshair(_ shown: HistorySample?) -> some ChartContent { - if let shown { - RuleMark(x: .value("Time", shown.date)) - .lineStyle(StrokeStyle(lineWidth: 1)) - .foregroundStyle(Color.secondary) + /// Follows the pointer; dashed where nothing was recorded. + @ChartContentBuilder private func crosshair(recorded: Bool) -> some ChartContent { + if let hovered { + RuleMark(x: .value("Time", hovered)) + .lineStyle(StrokeStyle(lineWidth: 1, dash: recorded ? [] : [3, 3])) + .foregroundStyle(Color.secondary.opacity(recorded ? 1 : 0.7)) } } } diff --git a/App/Dashboard/OverviewPage.swift b/App/Dashboard/OverviewPage.swift index eca1de4..cf1aaff 100644 --- a/App/Dashboard/OverviewPage.swift +++ b/App/Dashboard/OverviewPage.swift @@ -885,9 +885,9 @@ struct ChargeChart: View { private var selection: Binding { usesLocalHover ? $localHover : $hovered } var body: some View { - let shown = selection.wrappedValue.flatMap { date in - samples.min { abs($0.date.timeIntervalSince(date)) < abs($1.date.timeIntervalSince(date)) } - } + let hovered = selection.wrappedValue + let shown = hovered.flatMap { samples.sample(near: $0) } + let runs = samples.runs VStack(spacing: 10) { Chart { if let limit, let lowerBound, lowerBound < limit { @@ -897,21 +897,24 @@ struct ChargeChart: View { ) .foregroundStyle(Theme.accentSoft) } - ForEach(samples, id: \.date) { sample in + ForEach(Array(zip(samples, runs)), id: \.0.date) { sample, run in AreaMark( x: .value("Time", sample.date), yStart: .value("Base", 0), - yEnd: .value("Charge", sample.percent) + yEnd: .value("Charge", sample.percent), series: .value("Run", run) ) .interpolationMethod(.monotone) .foregroundStyle( LinearGradient( colors: [Theme.accent.opacity(0.22), Theme.accent.opacity(0)], startPoint: .top, endPoint: .bottom)) - LineMark(x: .value("Time", sample.date), y: .value("Charge", sample.percent)) - .interpolationMethod(.monotone) - .foregroundStyle(Theme.accent) - .lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round)) - .shadow(color: Theme.glow.opacity(0.6), radius: 4) + LineMark( + x: .value("Time", sample.date), y: .value("Charge", sample.percent), + series: .value("Run", run) + ) + .interpolationMethod(.monotone) + .foregroundStyle(Theme.accent) + .lineStyle(StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round)) + .shadow(color: Theme.glow.opacity(0.6), radius: 4) } if let limit { RuleMark(y: .value("Limit", limit)) @@ -923,17 +926,21 @@ struct ChargeChart: View { .symbolSize(40) .foregroundStyle(Theme.accent) } - if let shown { - RuleMark(x: .value("Time", shown.date)) - .lineStyle(StrokeStyle(lineWidth: 1)) - .foregroundStyle(Color.secondary) - PointMark(x: .value("Time", shown.date), y: .value("Charge", shown.percent)) - .symbolSize(50) + if let hovered { + // The line and the time follow the pointer; the dot slides along the charge line. Where + // nothing was recorded, the line is dashed and says so. + let y = samples.value(at: hovered) { Double($0.percent) } + RuleMark(x: .value("Time", hovered)) + .lineStyle(StrokeStyle(lineWidth: 1, dash: y == nil ? [3, 3] : [])) + .foregroundStyle(Color.secondary.opacity(y == nil ? 0.7 : 1)) + PointMark(x: .value("Time", hovered), y: .value("Charge", y ?? 100)) + .symbolSize(y == nil ? 0 : 50) .foregroundStyle(Theme.accent) .annotation(position: .top, spacing: 8, overflowResolution: .init(x: .fit, y: .disabled)) { VStack(alignment: .leading, spacing: 1) { - Text("\(shown.percent)%").font(.system(size: 13, weight: .semibold)) - Text(shown.date, format: .dateTime.hour().minute()) + Text(shown.map { "\($0.percent)%" } ?? "Not recorded") + .font(.system(size: 13, weight: .semibold)) + Text(hovered, format: .dateTime.hour().minute()) .font(.system(size: 11)).foregroundStyle(.secondary) } .padding(.horizontal, 10) @@ -981,7 +988,11 @@ struct ChargerStrip: View { context.fill( Path(roundedRect: CGRect(origin: .zero, size: size), cornerRadius: 3), with: .color(Theme.track)) for (index, sample) in samples.enumerated() where (sample.wallPower ?? 0) > 0.5 { - let end = index + 1 < samples.count ? samples[index + 1].date : sample.date.addingTimeInterval(60) + // Up to the next sample, unless nothing was recorded in between. + let next = index + 1 < samples.count ? samples[index + 1].date : nil + let end = + next.flatMap { $0.timeIntervalSince(sample.date) <= HistorySample.maximumSpacing ? $0 : nil } + ?? sample.date.addingTimeInterval(60) let x0 = size.width * sample.date.timeIntervalSince(domain.lowerBound) / span let x1 = size.width * end.timeIntervalSince(domain.lowerBound) / span let charging = (sample.batteryPower ?? 0) > 0.5 diff --git a/App/Debug/DesignRender.swift b/App/Debug/DesignRender.swift index 5008859..526c235 100644 --- a/App/Debug/DesignRender.swift +++ b/App/Debug/DesignRender.swift @@ -124,6 +124,10 @@ return AnyView(DashboardView(model: Sample.model(), initialPage: page)) }) } + shots.append( + Shot(name: "history-gap", size: dashboard) { + AnyView(DashboardView(model: Sample.model(historyGap: true), initialPage: .history)) + }) shots.append( Shot(name: "logs-warning", size: dashboard) { AnyView(DashboardView(model: Sample.model(warning: true), initialPage: .logs)) @@ -424,7 +428,7 @@ static func model( percent: Int = 61, service: ServiceState = .running, heat: Bool = false, enabled: Bool = true, tiles: Bool = false, warning: Bool = false, mode: ChargeMode = .automatic, manyLogs: Bool = false, - limit: Int = 80, calibrateEveryMonths: Int? = nil, smartLimit: Bool = false + limit: Int = 80, calibrateEveryMonths: Int? = nil, smartLimit: Bool = false, historyGap: Bool = false ) -> AppModel { let charging = mode == .automatic && percent < 80 let draining = mode != .automatic @@ -458,7 +462,11 @@ smartLimit: SmartLimit.Status(target: 55, usual: 34, sessions: 23)) : nil return AppModel( - preview: battery, status: status, service: service, history: history(), + preview: battery, status: status, service: service, + // Chargectl quit for three hours, so the helper recorded nothing. + history: history().filter { + !historyGap || !(-240 ... -60).contains($0.date.timeIntervalSinceNow / 60) + }, logs: manyLogs ? Self.manyLogs() : logs(warning: warning), macOSLimit: 80, daily: daily()) } diff --git a/CHANGELOG.md b/CHANGELOG.md index cf01fc2..dab5683 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,15 @@ sees, with its pull request link. Credit outside contributors with ## [Unreleased] +### Fixed + +- **History no longer draws a line across time nothing was recorded.** While + Chargectl was quit, which stops the helper, or the Mac slept, the charts + joined the last reading before to the first one after, and the hover marker + jumped between them. The charts now leave a gap there, and the marker + follows the pointer smoothly, saying "Not recorded" inside a gap. + ([#117](https://github.com/tyldra/chargectl/pull/117)) + ### Changed - **Chargectl moved to github.com/tyldra.** The app checks for updates there, diff --git a/Shared/XPC/DaemonModels.swift b/Shared/XPC/DaemonModels.swift index 438aedd..a1d2488 100644 --- a/Shared/XPC/DaemonModels.swift +++ b/Shared/XPC/DaemonModels.swift @@ -33,6 +33,57 @@ nonisolated struct HistorySample: Codable, Equatable, Sendable { var batteryPower: Double? /// The charger is connected, also while wall power is cut. Helpers before 0.3.0 leave it out. var pluggedIn: Bool? = nil + + /// Samples further apart than this have nothing recorded between them: Chargectl was quit, which + /// stops the helper, or the Mac slept without waking. The helper records once a minute while the + /// Mac is awake, and a sleeping Mac wakes to record about every 15 minutes. + static let maximumSpacing: TimeInterval = 20 * 60 +} + +extension [HistorySample] { + /// For each sample, in date order, the number of the unbroken run it belongs to. Charts draw each + /// run as its own line, so a gap in the recording shows as a gap, not a straight line across it. + nonisolated var runs: [Int] { + var run = 0 + return indices.map { index in + if index > 0, self[index].date.timeIntervalSince(self[index - 1].date) > HistorySample.maximumSpacing { + run += 1 + } + return run + } + } + + /// A value at `date`, read along the line between the samples around it, so a marker can follow the + /// pointer smoothly. Nil when nothing was recorded then. Samples must be in date order. + nonisolated func value(at date: Date, _ read: (HistorySample) -> Double?) -> Double? { + guard let nearest = sample(near: date) else { return nil } + let after = firstIndex { $0.date >= date } + guard let after, after > 0 else { return read(nearest) } + let (a, b) = (self[after - 1], self[after]) + let span = b.date.timeIntervalSince(a.date) + guard span > 0, span <= HistorySample.maximumSpacing, let va = read(a), let vb = read(b) else { + return read(nearest) + } + return va + (vb - va) * date.timeIntervalSince(a.date) / span + } + + /// The sample recorded closest to `date`, or nil when nothing was recorded near it. Samples must be + /// in date order. + nonisolated func sample(near date: Date) -> HistorySample? { + var low = 0 + var high = count + while low < high { + let middle = (low + high) / 2 + if self[middle].date < date { low = middle + 1 } else { high = middle } + } + let nearest = [low - 1, low].filter { indices.contains($0) }.min { + abs(self[$0].date.timeIntervalSince(date)) < abs(self[$1].date.timeIntervalSince(date)) + } + guard let nearest, abs(self[nearest].date.timeIntervalSince(date)) <= HistorySample.maximumSpacing / 2 else { + return nil + } + return self[nearest] + } } nonisolated struct LogEntry: Codable, Equatable, Identifiable, Sendable { diff --git a/Tests/SharedModelTests.swift b/Tests/SharedModelTests.swift index 444057f..c0cd6b2 100644 --- a/Tests/SharedModelTests.swift +++ b/Tests/SharedModelTests.swift @@ -117,4 +117,45 @@ import Testing new.autoDischarge = true #expect(new.changes(from: ChargeSettings()) == ["limit 80% → 75%", "automatic discharge off → on"]) } + + /// Recorded once a minute, then nothing for five hours (Chargectl was quit), then again. + private static func historyWithGap() -> [HistorySample] { + let start = Date(timeIntervalSince1970: 1_800_000_000) + let minutes = [0, 1, 2, 3] + [300, 301, 302] + return minutes.map { HistorySample(date: start.addingTimeInterval(Double($0) * 60), percent: 80) } + } + + @Test func historyRunsBreakWhereNothingWasRecorded() { + #expect(Self.historyWithGap().runs == [0, 0, 0, 0, 1, 1, 1]) + // A sleeping Mac wakes to record about every 15 minutes; that is still one run. + let start = Date(timeIntervalSince1970: 1_800_000_000) + let asleep = [0, 15, 30, 45].map { HistorySample(date: start.addingTimeInterval(Double($0) * 60), percent: 80) } + #expect(asleep.runs == [0, 0, 0, 0]) + #expect([HistorySample]().runs.isEmpty) + } + + @Test func historyFindsTheSampleNearAMomentButNotInAGap() { + let history = Self.historyWithGap() + let start = history[0].date + #expect(history.sample(near: start.addingTimeInterval(80))?.date == history[1].date) + #expect(history.sample(near: start.addingTimeInterval(-30))?.date == history[0].date) + // Two hours into the five-hour gap: nothing was recorded then. + #expect(history.sample(near: start.addingTimeInterval(2 * 60 * 60)) == nil) + // Five minutes past the last sample before the gap still reads it. + #expect(history.sample(near: start.addingTimeInterval(8 * 60))?.date == history[3].date) + #expect(history.sample(near: start.addingTimeInterval(301.4 * 60))?.date == history[5].date) + #expect([HistorySample]().sample(near: start) == nil) + } + + /// A marker follows the pointer: between two samples it sits on the line joining them. + @Test func historyValueFollowsTheLineBetweenSamples() { + let start = Date(timeIntervalSince1970: 1_800_000_000) + let history = [ + HistorySample(date: start, percent: 70), HistorySample(date: start.addingTimeInterval(60), percent: 80), + ] + let percent = { (sample: HistorySample) in Double(sample.percent) } + #expect(history.value(at: start.addingTimeInterval(15), percent) == 72.5) + #expect(history.value(at: start.addingTimeInterval(120), percent) == 80) + #expect(Self.historyWithGap().value(at: start.addingTimeInterval(2 * 60 * 60), percent) == nil) + } }