forked from LoopKit/LoopKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDailyValueScheduleTableViewController.swift
More file actions
285 lines (214 loc) · 10 KB
/
DailyValueScheduleTableViewController.swift
File metadata and controls
285 lines (214 loc) · 10 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
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
//
// DailyValueScheduleTableViewController.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/6/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import UIKit
import LoopKit
public protocol DailyValueScheduleTableViewControllerDelegate: AnyObject {
func dailyValueScheduleTableViewControllerWillFinishUpdating(_ controller: DailyValueScheduleTableViewController)
}
func insertableIndices<T>(for scheduleItems: [RepeatingScheduleValue<T>], removing row: Int, with interval: TimeInterval) -> [Bool] {
let insertableIndices = scheduleItems.enumerated().map { (enumeration) -> Bool in
let (index, item) = enumeration
if row == index {
return true
} else if index == 0 {
return false
} else if index == scheduleItems.endIndex - 1 {
return item.startTime < TimeInterval(hours: 24) - interval
} else if index > row {
return scheduleItems[index + 1].startTime - item.startTime > interval
} else {
return item.startTime - scheduleItems[index - 1].startTime > interval
}
}
return insertableIndices
}
open class DailyValueScheduleTableViewController: UITableViewController, DatePickerTableViewCellDelegate {
private var keyboardWillShowNotificationObserver: Any?
public convenience init() {
self.init(style: .plain)
}
open override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 44
if !isReadOnly {
navigationItem.rightBarButtonItems = [insertButtonItem, editButtonItem]
}
tableView.keyboardDismissMode = .onDrag
keyboardWillShowNotificationObserver = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: OperationQueue.main, using: { [weak self] (note) -> Void in
guard let strongSelf = self else {
return
}
guard note.userInfo?[UIResponder.keyboardIsLocalUserInfoKey] as? Bool == true else {
return
}
let animated = note.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double ?? 0 > 0
if let indexPath = strongSelf.tableView.indexPathForSelectedRow {
strongSelf.tableView.beginUpdates()
strongSelf.tableView.deselectRow(at: indexPath, animated: animated)
strongSelf.tableView.endUpdates()
}
})
}
open override func setEditing(_ editing: Bool, animated: Bool) {
if let indexPath = tableView.indexPathForSelectedRow {
tableView.beginUpdates()
tableView.deselectRow(at: indexPath, animated: animated)
tableView.endUpdates()
}
tableView.endEditing(false)
navigationItem.rightBarButtonItems?[0].isEnabled = !editing
super.setEditing(editing, animated: animated)
}
deinit {
if let observer = keyboardWillShowNotificationObserver {
NotificationCenter.default.removeObserver(observer)
}
}
open override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tableView.endEditing(true)
}
public weak var delegate: DailyValueScheduleTableViewControllerDelegate?
public private(set) lazy var insertButtonItem: UIBarButtonItem = {
return UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addScheduleItem(_:)))
}()
// MARK: - State
public var timeZone = TimeZone.currentFixed {
didSet {
calendar.timeZone = timeZone
let localTimeZone = TimeZone.current
let timeZoneDiff = TimeInterval(timeZone.secondsFromGMT() - localTimeZone.secondsFromGMT())
if timeZoneDiff != 0 {
let localTimeZoneName = localTimeZone.abbreviation() ?? localTimeZone.identifier
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
let diffString = formatter.string(from: abs(timeZoneDiff)) ?? String(abs(timeZoneDiff))
navigationItem.prompt = String(
format: LocalizedString("Times in %1$@%2$@%3$@", comment: "The schedule table view header describing the configured time zone difference from the default time zone. The substitution parameters are: (1: time zone name)(2: +/-)(3: time interval)"),
localTimeZoneName, timeZoneDiff < 0 ? "-" : "+", diffString
)
}
}
}
public var unitDisplayString: String = "U/hour"
public var isReadOnly: Bool = false {
didSet {
if isReadOnly {
isEditing = false
}
if isViewLoaded {
navigationItem.setRightBarButtonItems(isReadOnly ? [] : [insertButtonItem, editButtonItem], animated: true)
}
}
}
private var calendar = Calendar.current
var midnight: Date {
return calendar.startOfDay(for: Date())
}
@objc func addScheduleItem(_ sender: Any?) {
guard !isReadOnly else {
return
}
// Updates the table view state. Subclasses should update their data model before calling super
tableView.insertRows(at: [IndexPath(row: tableView.numberOfRows(inSection: 0), section: 0)], with: .automatic)
}
func insertableIndiciesByRemovingRow(_ row: Int, withInterval timeInterval: TimeInterval) -> [Bool] {
fatalError("Subclasses must override \(#function)")
}
// MARK: - UITableViewDataSource
open override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
open override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
fatalError("Subclasses must override \(#function)")
}
open override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return !isReadOnly && indexPath.section == 0 && indexPath.row > 0
}
open override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return self.tableView(tableView, canEditRowAt: indexPath)
}
open override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
fatalError("Subclasses must override \(#function)")
}
open override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Updates the table view state. Subclasses should update their data model before calling super
tableView.deleteRows(at: [indexPath], with: .automatic)
}
}
// MARK: - UITableViewDelegate
open override func tableView(_ tableView: UITableView, shouldHighlightRowAt indexPath: IndexPath) -> Bool {
guard indexPath.section == 0 else {
return true
}
return !isReadOnly && indexPath.row > 0
}
open override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
guard self.tableView(tableView, shouldHighlightRowAt: indexPath) else {
return nil
}
tableView.endEditing(false)
tableView.beginUpdates()
hideDatePickerCells(excluding: indexPath)
return indexPath
}
open override func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
tableView.beginUpdates()
tableView.endUpdates()
}
open override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.endEditing(false)
tableView.endUpdates()
tableView.deselectRow(at: indexPath, animated: true)
}
open override func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
guard sourceIndexPath.section == proposedDestinationIndexPath.section else {
return sourceIndexPath
}
guard sourceIndexPath != proposedDestinationIndexPath, let cell = tableView.cellForRow(at: sourceIndexPath) as? RepeatingScheduleValueTableViewCell else {
return proposedDestinationIndexPath
}
let interval = cell.datePickerInterval
let indices = insertableIndiciesByRemovingRow(sourceIndexPath.row, withInterval: interval)
let closestDestinationRow = indices.insertableIndex(closestTo: proposedDestinationIndexPath.row, from: sourceIndexPath.row)
return IndexPath(row: closestDestinationRow, section: proposedDestinationIndexPath.section)
}
// MARK: - DatePickerTableViewCellDelegate
public func datePickerTableViewCellDidUpdateDate(_ cell: DatePickerTableViewCell) {
// Updates the TableView state. Subclasses should update their data model
if let indexPath = tableView.indexPath(for: cell) {
var indexPaths: [IndexPath] = []
if indexPath.row > 0 {
indexPaths.append(IndexPath(row: indexPath.row - 1, section: indexPath.section))
}
if indexPath.row < tableView.numberOfRows(inSection: 0) - 1 {
indexPaths.append(IndexPath(row: indexPath.row + 1, section: indexPath.section))
}
DispatchQueue.main.async {
self.tableView.reloadRows(at: indexPaths, with: .none)
}
}
}
}
extension Array where Element == Bool {
func insertableIndex(closestTo destination: Int, from source: Int) -> Int {
if self[destination] {
return destination
} else {
var closestRow = source
for (index, valid) in self.enumerated() where valid {
if abs(destination - index) < abs(destination - closestRow) {
closestRow = index
}
}
return closestRow
}
}
}