-
Notifications
You must be signed in to change notification settings - Fork 128
/
ScreenTime.swift
316 lines (277 loc) · 11.1 KB
/
ScreenTime.swift
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
//
// Copyright © 2022 Swift Charts Examples.
// Open Source - MIT License
import SwiftUI
import Charts
struct ScreenTime: View {
var isOverview: Bool
@State private var weekData = ScreenTimeValue.week.makeDayValues()
@State private var selectedDate: Date = date(year: 2022, month: 06, day: 20)
var body: some View {
ZStack {
if isOverview {
VStack {
weekChart
dayChart
}
.frame(height: 300)
} else {
List {
Section {
VStack {
weekChart
dayChart
}
.frame(height: 300)
}
}
.navigationTitle(ChartType.screenTime.title)
#if canImport(UIKit)
.navigationBarTitleDisplayMode(.inline)
#endif
}
}
.chartForegroundStyleScale([
ScreenTimeCategory.social: Color.blue,
ScreenTimeCategory.entertainment: Color.teal,
ScreenTimeCategory.productivityFinance: Color.orange,
ScreenTimeCategory.other: Color.gray
])
}
private var weekChart: some View {
Chart {
ForEach(weekData) { category in
let isSelected = Calendar.current.isDate(category.valueDate, inSameDayAs: selectedDate)
BarMark(
x: .value("date", category.valueDate, unit: .day),
y: .value("duration", category.duration)
)
.foregroundStyle(by: .value("category", isSelected ? category.category : ScreenTimeCategory.other))
}
RuleMark(
y: .value("Average", weekAverageDuration)
)
.foregroundStyle(.green)
.lineStyle(StrokeStyle(lineWidth: 1.5, dash: [3, 5]))
.annotation(position: .trailing, alignment: .leading) {
Text("avg")
.font(.caption2)
.foregroundStyle(.green)
}
}
.accessibilityRepresentation {
Chart {
ForEach(accessibilityGroupedWeekData, id: \.date) { dataPoint in
Plot {
BarMark(
x: .value("date", dataPoint.date, unit: .day),
y: .value("duration", dataPoint.totalDuration)
)
}
.accessibilityLabel("\(dataPoint.date.formatted(Date.FormatStyle().month(.wide).day(.defaultDigits).weekday(.wide)))")
.accessibilityValue(dataPoint.description)
.accessibilityHidden(isOverview)
}
}
}
.accessibilityChartDescriptor(ScreenTimeChartDescriptor(summaries: accessibilityGroupedWeekData,
type: .week))
.chartYAxis {
AxisMarks(values: .automatic(desiredCount: 3)) { value in
AxisGridLine()
let formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.hour]
return formatter
}()
if let timeInterval = value.as(TimeInterval.self), let formatted = formatter.string(from: timeInterval) {
AxisValueLabel(formatted)
}
}
}
.chartXAxis {
AxisMarks(values: .stride(by: .day)) { _ in
AxisGridLine()
AxisTick()
AxisValueLabel(format: .dateTime.weekday(.narrow))
}
}
.chartLegend(.hidden)
.chartOverlay { proxy in
GeometryReader { geo in
Rectangle().fill(.clear).contentShape(Rectangle())
.gesture(
DragGesture(minimumDistance: 0)
.onChanged { value in
let x = value.location.x - geo[proxy.plotAreaFrame].origin.x
if let date: Date = proxy.value(atX: x) {
selectedDate = Calendar.current.startOfDay(for: date)
}
}
)
}
}
}
private var dayChart: some View {
Chart {
ForEach(getDayValue()) { value in
BarMark(
x: .value("date", value.valueDate, unit: .hour),
y: .value("duration", value.duration)
)
.foregroundStyle(by: .value("category", value.category))
// .relative(presentation: .numeric, unitsStyle: .wide)
}
}
.accessibilityRepresentation {
Chart {
ForEach(accessibilityGroupedDayData, id: \.date) { dataPoint in
Plot {
BarMark(
x: .value("date", dataPoint.date, unit: .hour),
y: .value("duration", dataPoint.totalDuration)
)
}
.accessibilityLabel("\(dataPoint.date.formatted(Date.FormatStyle().hour(.conversationalDefaultDigits(amPM: .wide)).minute(.twoDigits)))")
.accessibilityValue(dataPoint.description)
.accessibilityHidden(isOverview)
}
}
}
.accessibilityChartDescriptor(ScreenTimeChartDescriptor(summaries: accessibilityGroupedDayData,
type: .day))
.chartXScale(domain: Calendar.current.startOfDay(for: selectedDate)...Calendar.current.startOfDay(for: selectedDate).addingTimeInterval(60*60*24))
.chartYAxis {
AxisMarks(values: [TimeInterval(0), TimeInterval(30*60), TimeInterval(60*60)]) { value in
AxisGridLine()
let formatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .abbreviated
formatter.allowedUnits = [.minute]
return formatter
}()
if let timeInterval = value.as(TimeInterval.self), let formatted = formatter.string(from: timeInterval) {
AxisValueLabel(formatted)
}
}
}
}
private func getDayValue() -> [ScreenTimeValue] {
ScreenTimeValue.week.filter({ Calendar.current.isDate($0.valueDate, inSameDayAs: selectedDate) })
}
private var weekAverageDuration: TimeInterval {
let totalDuration = weekData.reduce(0) { $0 + $1.duration }
return totalDuration/7.0
}
}
// MARK: - Accessibility
// Reduces clutter when re-used and in type annotations
fileprivate typealias AccessibilitySummary = (date: Date, totalDuration: TimeInterval, description: String)
fileprivate extension ScreenTime {
/// A grouping of the startOfDay Date, the total hours of screen time on the date
/// and a descriptive breakdown of usage categories
/// for use with accessibilityChartDescriptor and label/value of WeekChart data
var accessibilityGroupedWeekData: [AccessibilitySummary] {
// NOTE: weekData's valueDate are the start of date for each day based on makeDayValues()
let grouped = Dictionary(grouping: weekData) { $0.valueDate }
let summaries: [AccessibilitySummary] = grouped.map { k, v in
let totalDuration: TimeInterval = v.reduce(0.0) { $0 + $1.duration }
let summaries = v.map { "\($0.category.rawValue): \($0.duration.durationDescription)"}
return (date: k,
totalDuration: totalDuration,
description: summaries.formatted(.list(type: .and)))
}
return summaries.sorted { $0.date < $1.date }
}
/// A grouping by the hour of the day, of the total hours of screen time
/// and a descriptive breakdown of usage categories
/// for use with accessibilityChartDescriptor and label/value of DayChart data
var accessibilityGroupedDayData: [AccessibilitySummary] {
let grouped = Dictionary(grouping: getDayValue()) {
// Since the sample data only uses hours, we group by the date
$0.valueDate
// If, the schema changes to include minute data, use the following to get the startOfHour
// let hour = Calendar.current.component(.hour, from: $0.valueDate)
// return Calendar.current.date(from: .init(hour: hour)) ?? $0.valueDate
}
let summaries: [AccessibilitySummary] = grouped.map { k, v in
let totalDuration: TimeInterval = v.reduce(0.0) { $0 + $1.duration }
let summaries = v.map { "\($0.category.rawValue): \($0.duration.durationDescription)"}
return (date: k,
totalDuration: totalDuration,
description: summaries.formatted(.list(type: .and)))
}
return summaries.sorted { $0.date < $1.date }
}
}
struct ScreenTimeChartDescriptor: AXChartDescriptorRepresentable {
/// A list of options to change the axis labels
/// depending on whether the audio graph is for week or day data
fileprivate enum ChartDescriptorType {
case week
case day
}
fileprivate let summaries: [AccessibilitySummary]
fileprivate let type: ChartDescriptorType
func makeChartDescriptor() -> AXChartDescriptor {
let min = 0
let max = summaries.map(\.totalDuration).max() ?? 0
// A closure that takes a date and converts it to a label for axes
// To re-phrase/frame, the return value here is how we group data points on the axis
// So for week data, group by the date, but for day, use the hour
let dateStringConverter: ((AccessibilitySummary) -> (String)) = { dataPoint in
switch type {
case .week:
return dataPoint.date
.formatted(
Date.FormatStyle()
.month(.wide)
.day(.defaultDigits)
.weekday(.wide)
)
case .day:
return dataPoint.date
.formatted(
Date.FormatStyle()
.hour(.conversationalDefaultDigits(amPM: .wide))
.minute(.twoDigits)
)
}
}
// The axes and descriptions here mirror Apple's implementation of the Screen time graph
// So we simply describe the total usage time instead of detailing the usage breakdown
let xAxis = AXCategoricalDataAxisDescriptor(title: "Time",
categoryOrder: summaries.map { dateStringConverter($0) } )
let yAxis = AXNumericDataAxisDescriptor(
title: "Usage",
range: Double(min)...Double(max),
gridlinePositions: []
) { value in "Total usage: \(value.durationDescription)" }
// If, however you want to put the usage categories in the audio graph,
// add label: point.description to the dataPoints init here
let series = AXDataSeriesDescriptor(
name: "Device Usage",
isContinuous: false,
dataPoints: summaries.map { point in
.init(x: dateStringConverter(point),
y: Double(point.totalDuration))
}
)
return AXChartDescriptor(
title: "Screen Time Data",
summary: nil,
xAxis: xAxis,
yAxis: yAxis,
additionalAxes: [],
series: [series]
)
}
}
// MARK: - Preview
struct ScreenTime_Previews: PreviewProvider {
static var previews: some View {
ScreenTime(isOverview: true)
ScreenTime(isOverview: false)
}
}