LoopView.swift 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. import SwiftDate
  2. import SwiftUI
  3. import UIKit
  4. struct LoopView: View {
  5. private enum Config {
  6. static let lag: TimeInterval = 30
  7. }
  8. @Binding var suggestion: Suggestion?
  9. @Binding var enactedSuggestion: Suggestion?
  10. @Binding var closedLoop: Bool
  11. @Binding var timerDate: Date
  12. @Binding var isLooping: Bool
  13. @Binding var lastLoopDate: Date
  14. private var dateFormatter: DateFormatter {
  15. let formatter = DateFormatter()
  16. formatter.timeStyle = .short
  17. return formatter
  18. }
  19. private let rect = CGRect(x: 0, y: 0, width: 32, height: 32)
  20. var body: some View {
  21. VStack(alignment: .center) {
  22. ZStack {
  23. Circle()
  24. .strokeBorder(color, lineWidth: 6)
  25. .frame(width: rect.width, height: rect.height)
  26. .mask(mask(in: rect).fill(style: FillStyle(eoFill: true)))
  27. if isLooping {
  28. ProgressView()
  29. }
  30. }
  31. if isLooping {
  32. Text("looping").font(.caption2)
  33. } else if actualSuggestion?.timestamp != nil {
  34. Text("\(Int((timerDate.timeIntervalSince(lastLoopDate) - Config.lag) / 60) + 1) min ago").font(.caption2)
  35. .foregroundColor(.secondary)
  36. } else {
  37. Text("--").font(.caption2).foregroundColor(.secondary)
  38. }
  39. }
  40. }
  41. private var color: Color {
  42. guard actualSuggestion?.timestamp != nil else {
  43. return .loopGray
  44. }
  45. let delta = timerDate.timeIntervalSince(lastLoopDate) - Config.lag
  46. if delta <= 5.minutes.timeInterval {
  47. guard actualSuggestion?.deliverAt != nil else {
  48. return .loopYellow
  49. }
  50. return .loopGreen
  51. } else if delta <= 10.minutes.timeInterval {
  52. return .loopYellow
  53. } else {
  54. return .loopRed
  55. }
  56. }
  57. func mask(in rect: CGRect) -> Path {
  58. var path = Rectangle().path(in: rect)
  59. if !closedLoop {
  60. path.addPath(Rectangle().path(in: CGRect(x: rect.minX, y: rect.midY - 5, width: rect.width, height: 10)))
  61. }
  62. return path
  63. }
  64. private var actualSuggestion: Suggestion? {
  65. if closedLoop, suggestion?.rate != nil || suggestion?.units != nil {
  66. return enactedSuggestion ?? suggestion
  67. } else {
  68. return suggestion
  69. }
  70. }
  71. }
  72. extension View {
  73. func animateForever(
  74. using animation: Animation = Animation.easeInOut(duration: 1),
  75. autoreverses: Bool = false,
  76. _ action: @escaping () -> Void
  77. ) -> some View {
  78. let repeated = animation.repeatForever(autoreverses: autoreverses)
  79. return onAppear {
  80. withAnimation(repeated) {
  81. action()
  82. }
  83. }
  84. }
  85. }