forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChartsManager.swift
More file actions
240 lines (192 loc) · 7.09 KB
/
ChartsManager.swift
File metadata and controls
240 lines (192 loc) · 7.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
//
// Chart.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/19/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import HealthKit
import LoopKit
import SwiftCharts
import UIKit
open class ChartsManager {
private lazy var timeFormatter: DateFormatter = {
let formatter = DateFormatter()
let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)!
let isAmPmTimeFormat = dateFormat.firstIndex(of: "a") != nil
formatter.dateFormat = isAmPmTimeFormat
? "h a"
: "H:mm"
return formatter
}()
public init(
colors: ChartColorPalette,
settings: ChartSettings,
axisLabelFont: UIFont = .systemFont(ofSize: 14), // caption1, but hard-coded until axis can scale with type preference
charts: [ChartProviding],
traitCollection: UITraitCollection
) {
self.colors = colors
self.chartSettings = settings
self.charts = charts
self.traitCollection = traitCollection
self.chartsCache = Array(repeating: nil, count: charts.count)
axisLabelSettings = ChartLabelSettings(font: axisLabelFont, fontColor: colors.axisLabel)
guideLinesLayerSettings = ChartGuideLinesLayerSettings(linesColor: colors.grid)
}
// MARK: - Configuration
private let colors: ChartColorPalette
private let chartSettings: ChartSettings
private let labelsWidthY: CGFloat = 30
public let charts: [ChartProviding]
/// The amount of horizontal space reserved for fixed margins
public var fixedHorizontalMargin: CGFloat {
return chartSettings.leading + chartSettings.trailing + labelsWidthY + chartSettings.labelsToAxisSpacingY
}
private let axisLabelSettings: ChartLabelSettings
private let guideLinesLayerSettings: ChartGuideLinesLayerSettings
public var gestureRecognizer: UIGestureRecognizer?
// MARK: - UITraitEnvironment
public var traitCollection: UITraitCollection
public func didReceiveMemoryWarning() {
for chart in charts {
chart.didReceiveMemoryWarning()
}
xAxisValues = nil
}
// MARK: - Data
/// The earliest date on the X-axis
public var startDate = Date() {
didSet {
if startDate != oldValue {
xAxisValues = nil
// Set a new minimum end date
endDate = startDate.addingTimeInterval(.hours(3))
}
}
}
/// The latest date on the X-axis
private var endDate = Date() {
didSet {
if endDate != oldValue {
xAxisValues = nil
}
}
}
/// The latest allowed date on the X-axis
public var maxEndDate = Date.distantFuture {
didSet {
endDate = min(endDate, maxEndDate)
}
}
/// Updates the endDate using a new candidate date
///
/// Dates are rounded up to the next hour.
///
/// - Parameter date: The new candidate date
public func updateEndDate(_ date: Date) {
if date > endDate {
let components = DateComponents(minute: 0)
endDate = min(
maxEndDate,
Calendar.current.nextDate(
after: date,
matching: components,
matchingPolicy: .strict,
direction: .forward
) ?? date
)
}
}
// MARK: - State
private var xAxisValues: [ChartAxisValue]? {
didSet {
if let xAxisValues = xAxisValues, xAxisValues.count > 1 {
xAxisModel = ChartAxisModel(axisValues: xAxisValues, lineColor: colors.axisLine, labelSpaceReservationMode: .fixed(20))
} else {
xAxisModel = nil
}
chartsCache.replaceAllElements(with: nil)
}
}
private var xAxisModel: ChartAxisModel?
private var chartsCache: [Chart?]
// MARK: - Generators
public func chart(atIndex index: Int, frame: CGRect) -> Chart? {
if let chart = chartsCache[index], chart.frame != frame {
chartsCache[index] = nil
}
if chartsCache[index] == nil, let xAxisModel = xAxisModel, let xAxisValues = xAxisValues {
chartsCache[index] = charts[index].generate(withFrame: frame, xAxisModel: xAxisModel, xAxisValues: xAxisValues, axisLabelSettings: axisLabelSettings, guideLinesLayerSettings: guideLinesLayerSettings, colors: colors, chartSettings: chartSettings, labelsWidthY: labelsWidthY, gestureRecognizer: gestureRecognizer, traitCollection: traitCollection)
}
return chartsCache[index]
}
public func invalidateChart(atIndex index: Int) {
chartsCache[index] = nil
}
// MARK: - Shared Axis
private func generateXAxisValues() {
if let endDate = charts.compactMap({ $0.endDate }).max() {
updateEndDate(endDate)
}
let points = [
ChartPoint(
x: ChartAxisValueDate(date: startDate, formatter: timeFormatter),
y: ChartAxisValue(scalar: 0)
),
ChartPoint(
x: ChartAxisValueDate(date: endDate, formatter: timeFormatter),
y: ChartAxisValue(scalar: 0)
)
]
let segments = ceil(endDate.timeIntervalSince(startDate).hours)
let xAxisValues = ChartAxisValuesStaticGenerator.generateXAxisValuesWithChartPoints(points,
minSegmentCount: segments - 1,
maxSegmentCount: segments + 1,
multiple: TimeInterval(hours: 1),
axisValueGenerator: {
ChartAxisValueDate(
date: ChartAxisValueDate.dateFromScalar($0),
formatter: timeFormatter,
labelSettings: self.axisLabelSettings
)
},
addPaddingSegmentIfEdge: false
)
xAxisValues.first?.hidden = true
xAxisValues.last?.hidden = true
self.xAxisValues = xAxisValues
}
/// Runs any necessary steps before rendering charts
public func prerender() {
if xAxisValues == nil {
generateXAxisValues()
}
}
}
fileprivate extension Array {
mutating func replaceAllElements(with element: Element) {
self = Array(repeating: element, count: count)
}
}
public protocol ChartProviding {
/// Instructs the chart to clear its non-critical resources like caches
func didReceiveMemoryWarning()
/// The last date represented in the chart data
var endDate: Date? { get }
/// Creates a chart from the current data
///
/// - Returns: A new chart object
func generate(withFrame frame: CGRect,
xAxisModel: ChartAxisModel,
xAxisValues: [ChartAxisValue],
axisLabelSettings: ChartLabelSettings,
guideLinesLayerSettings: ChartGuideLinesLayerSettings,
colors: ChartColorPalette,
chartSettings: ChartSettings,
labelsWidthY: CGFloat,
gestureRecognizer: UIGestureRecognizer?,
traitCollection: UITraitCollection
) -> Chart
}