PreferencesEditorDataFlow.swift 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import Foundation
  2. import LoopKit
  3. protocol SettableValue {}
  4. extension Bool: SettableValue {}
  5. extension Decimal: SettableValue {}
  6. extension InsulinCurve: SettableValue {}
  7. enum PreferencesEditor {
  8. enum Config {}
  9. enum FieldType {
  10. case boolean(keypath: WritableKeyPath<Preferences, Bool>)
  11. case decimal(keypath: WritableKeyPath<Preferences, Decimal>)
  12. case insulinCurve(keypath: WritableKeyPath<Preferences, InsulinCurve>)
  13. }
  14. class Field: Identifiable {
  15. var displayName: String
  16. var type: FieldType
  17. var infoText: String
  18. var boolValue: Bool {
  19. get {
  20. switch type {
  21. case let .boolean(keypath):
  22. return settable?.get(keypath) ?? false
  23. default: return false
  24. }
  25. }
  26. set { set(value: newValue) }
  27. }
  28. var decimalValue: Decimal {
  29. get {
  30. switch type {
  31. case let .decimal(keypath):
  32. return settable?.get(keypath) ?? 0
  33. default: return 0
  34. }
  35. }
  36. set { set(value: newValue) }
  37. }
  38. var insulinCurveValue: InsulinCurve {
  39. get {
  40. switch type {
  41. case let .insulinCurve(keypath):
  42. return settable?.get(keypath) ?? .rapidActing
  43. default: return .rapidActing
  44. }
  45. }
  46. set { set(value: newValue) }
  47. }
  48. private func set<T: SettableValue>(value: T) {
  49. switch (type, value) {
  50. case let (.boolean(keypath), value as Bool):
  51. settable?.set(keypath, value: value)
  52. case let (.decimal(keypath), value as Decimal):
  53. settable?.set(keypath, value: value)
  54. case let (.insulinCurve(keypath), value as InsulinCurve):
  55. settable?.set(keypath, value: value)
  56. default: break
  57. }
  58. }
  59. weak var settable: PreferencesSettable?
  60. init(
  61. displayName: String,
  62. type: FieldType,
  63. infoText: String,
  64. settable: PreferencesSettable? = nil
  65. ) {
  66. self.displayName = displayName
  67. self.type = type
  68. self.infoText = infoText
  69. self.settable = settable
  70. }
  71. let id = UUID()
  72. }
  73. struct FieldSection: Identifiable {
  74. let displayName: String
  75. var fields: [Field]
  76. let id = UUID()
  77. }
  78. }
  79. protocol PreferencesEditorProvider: Provider {
  80. var preferences: Preferences { get }
  81. func savePreferences(_ preferences: Preferences)
  82. func migrateUnits()
  83. }
  84. protocol PreferencesSettable: AnyObject {
  85. func set<T>(_ keypath: WritableKeyPath<Preferences, T>, value: T)
  86. func get<T>(_ keypath: WritableKeyPath<Preferences, T>) -> T
  87. }