LoopView.swift 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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: 38, height: 38)
  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. Spacer()
  32. if isLooping {
  33. Text("looping").font(.caption2)
  34. } else if actualSuggestion?.timestamp != nil {
  35. Text("\(Int((timerDate.timeIntervalSince(lastLoopDate) - Config.lag) / 60) + 1) min ago").font(.caption)
  36. } else {
  37. Text("--").font(.caption)
  38. }
  39. }
  40. }
  41. private var color: Color {
  42. guard actualSuggestion?.timestamp != nil else {
  43. return Color(UIColor(named: "LoopGray")!)
  44. }
  45. let delta = timerDate.timeIntervalSince(lastLoopDate) - Config.lag
  46. if delta <= 5.minutes.timeInterval {
  47. return Color(UIColor(named: "LoopGreen")!)
  48. } else if delta <= 10.minutes.timeInterval {
  49. return Color(UIColor(named: "LoopYellow")!)
  50. } else {
  51. return Color(UIColor(named: "LoopRed")!)
  52. }
  53. }
  54. func mask(in rect: CGRect) -> Path {
  55. var path = Rectangle().path(in: rect)
  56. if !closedLoop {
  57. path.addPath(Rectangle().path(in: CGRect(x: rect.minX, y: rect.midY - 5, width: rect.width, height: 10)))
  58. }
  59. return path
  60. }
  61. private var actualSuggestion: Suggestion? {
  62. if closedLoop, suggestion?.rate != nil || suggestion?.units != nil {
  63. return enactedSuggestion
  64. } else {
  65. return suggestion
  66. }
  67. }
  68. }
  69. extension View {
  70. func animateForever(
  71. using animation: Animation = Animation.easeInOut(duration: 1),
  72. autoreverses: Bool = false,
  73. _ action: @escaping () -> Void
  74. ) -> some View {
  75. let repeated = animation.repeatForever(autoreverses: autoreverses)
  76. return onAppear {
  77. withAnimation(repeated) {
  78. action()
  79. }
  80. }
  81. }
  82. }