| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486 |
- import CoreData
- import SwiftUI
- import Swinject
- extension DataTable {
- struct RootView: BaseView {
- let resolver: Resolver
- @StateObject var state = StateModel()
- @State private var isRemoveHistoryItemAlertPresented: Bool = false
- @State private var alertTitle: String = ""
- @State private var alertMessage: String = ""
- @State private var alertTreatmentToDelete: Treatment?
- @State private var alertGlucoseToDelete: Glucose?
- @State private var showExternalInsulin: Bool = false
- @State private var showFutureEntries: Bool = false // default to hide future entries
- @State private var showManualGlucose: Bool = false
- @State private var isAmountUnconfirmed: Bool = true
- @Environment(\.colorScheme) var colorScheme
- private var insulinFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- formatter.maximumFractionDigits = 2
- return formatter
- }
- private var glucoseFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- if state.units == .mmolL {
- formatter.maximumFractionDigits = 1
- formatter.roundingMode = .halfUp
- } else {
- formatter.maximumFractionDigits = 0
- }
- return formatter
- }
- private var manualGlucoseFormatter: NumberFormatter {
- let formatter = NumberFormatter()
- formatter.numberStyle = .decimal
- if state.units == .mmolL {
- formatter.maximumFractionDigits = 1
- formatter.roundingMode = .ceiling
- } else {
- formatter.maximumFractionDigits = 0
- }
- return formatter
- }
- private var dateFormatter: DateFormatter {
- let formatter = DateFormatter()
- formatter.timeStyle = .short
- return formatter
- }
- private var color: LinearGradient {
- colorScheme == .dark ? LinearGradient(
- gradient: Gradient(colors: [
- // RGB(10, 34, 55)
- Color(red: 0.03921568627, green: 0.1333333333, blue: 0.2156862745),
- // RGB(3, 15, 28)
- Color(red: 0.011, green: 0.058, blue: 0.109),
- // RGB(10, 34, 55)
- Color(red: 0.03921568627, green: 0.1333333333, blue: 0.2156862745)
- ]),
- startPoint: .top,
- endPoint: .bottom
- )
- :
- LinearGradient(gradient: Gradient(colors: [Color.gray.opacity(0.1)]), startPoint: .top, endPoint: .bottom)
- }
-
- var body: some View {
- VStack {
- Picker("Mode", selection: $state.mode) {
- ForEach(
- Mode.allCases.filter({ state.historyLayout == .twoTabs ? $0 != .meals : true }).indexed(),
- id: \.1
- ) { index, item in
- if state.historyLayout == .threeTabs && item == .treatments {
- Text("Insulin")
- .tag(index)
- } else {
- Text(item.name)
- .tag(index)
- }
- }
- }
- .pickerStyle(SegmentedPickerStyle())
- .padding(.horizontal)
- Form {
- switch state.mode {
- case .treatments: treatmentsList
- case .glucose: glucoseList
- case .meals: state.historyLayout == .threeTabs ? AnyView(mealsList) : AnyView(EmptyView())
- }
- }.scrollContentBackground(.hidden)
- .background(color)
- }.background(color)
- .onAppear(perform: configureView)
- .navigationTitle("History")
- .navigationBarTitleDisplayMode(.inline)
- .navigationBarItems(trailing: Button("Close", action: state.hideModal))
- .sheet(isPresented: $showManualGlucose) {
- addGlucoseView
- }
- .sheet(isPresented: $showExternalInsulin, onDismiss: { if isAmountUnconfirmed { state.externalInsulinAmount = 0
- state.externalInsulinDate = Date() } }) {
- addExternalInsulinView
- }
- }
- private var treatmentsList: some View {
- List {
- HStack {
- Button(action: { showExternalInsulin = true
- state.externalInsulinDate = Date() }, label: {
- HStack {
- Image(systemName: "syringe")
- Text("Add")
- .foregroundColor(Color.secondary)
- .font(.caption)
- }.frame(maxWidth: .infinity, alignment: .leading)
- }).buttonStyle(.borderless)
- if state.historyLayout == .twoTabs {
- Spacer()
- filterEntriesButton
- }
- }
- if !state.treatments.isEmpty {
- ForEach(state.treatments.filter({ !showFutureEntries ? $0.date <= Date() : true })) { item in
- treatmentView(item)
- }
- } else {
- HStack {
- Text("No data.")
- }
- }
- }
- }
- private var mealsList: some View {
- List {
- HStack {
- Text("Type").foregroundStyle(.secondary)
- Spacer()
- filterEntriesButton
- }
- if !state.meals.isEmpty {
- ForEach(state.meals.filter({ !showFutureEntries ? $0.date <= Date() : true })) { item in
- mealView(item)
- }
- } else {
- HStack {
- Text("No data.")
- }
- }
- }
- }
- private var glucoseList: some View {
- List {
- HStack {
- Button(
- action: { showManualGlucose = true
- state.manualGlucose = 0 },
- label: { Image(systemName: "plus.circle.fill").foregroundStyle(.secondary)
- }
- ).buttonStyle(.borderless)
- Text(state.units.rawValue).foregroundStyle(.secondary)
- Spacer()
- Text("Time").foregroundStyle(.secondary)
- }
- if !state.glucose.isEmpty {
- ForEach(state.glucose) { item in
- glucoseView(item, isManual: item.glucose)
- }
- } else {
- HStack {
- Text("No data.")
- }
- }
- }
- }
- var addGlucoseView: some View {
- NavigationView {
- VStack {
- Form {
- Section {
- HStack {
- Text("New Glucose")
- DecimalTextField(
- " ... ",
- value: $state.manualGlucose,
- formatter: manualGlucoseFormatter,
- autofocus: true,
- cleanInput: true
- )
- Text(state.units.rawValue).foregroundStyle(.secondary)
- }
- }
- Section {
- HStack {
- let limitLow: Decimal = state.units == .mmolL ? 0.8 : 14
- let limitHigh: Decimal = state.units == .mmolL ? 40 : 720
- Button {
- state.addManualGlucose()
- isAmountUnconfirmed = false
- showManualGlucose = false
- }
- label: { Text("Save") }
- .frame(maxWidth: .infinity, alignment: .center)
- .disabled(state.manualGlucose < limitLow || state.manualGlucose > limitHigh)
- }
- }
- }
- }
- .onAppear(perform: configureView)
- .navigationTitle("Add Glucose")
- .navigationBarTitleDisplayMode(.automatic)
- .navigationBarItems(trailing: Button("Close", action: { showManualGlucose = false }))
- }
- }
- private var filterEntriesButton: some View {
- Button(action: { showFutureEntries.toggle() }, label: {
- HStack {
- Text(showFutureEntries ? "Hide Future" : "Show Future")
- .foregroundColor(Color.secondary)
- .font(.caption)
- Image(systemName: showFutureEntries ? "calendar.badge.minus" : "calendar.badge.plus")
- }.frame(maxWidth: .infinity, alignment: .trailing)
- }).buttonStyle(.borderless)
- }
- @ViewBuilder private func treatmentView(_ item: Treatment) -> some View {
- HStack {
- Image(systemName: "circle.fill").foregroundColor(item.color)
- Text((item.isSMB ?? false) ? "SMB" : item.type.name)
- Text(item.amountText).foregroundColor(.secondary)
- if let duration = item.durationText {
- Text(duration).foregroundColor(.secondary)
- }
- Spacer()
- Text(dateFormatter.string(from: item.date))
- .moveDisabled(true)
- }
- .swipeActions {
- Button(
- "Delete",
- systemImage: "trash.fill",
- role: .none,
- action: {
- alertTreatmentToDelete = item
- if item.type == .carbs {
- alertTitle = "Delete Carbs?"
- alertMessage = dateFormatter.string(from: item.date) + ", " + item.amountText
- } else if item.type == .fpus {
- alertTitle = "Delete Carb Equivalents?"
- alertMessage = "All FPUs of the meal will be deleted."
- } else {
- // item is insulin treatment; item.type == .bolus
- alertTitle = "Delete Insulin?"
- alertMessage = dateFormatter.string(from: item.date) + ", " + item.amountText
- if item.isSMB ?? false {
- // Add text snippet, so that alert message is more descriptive for SMBs
- alertMessage += "SMB"
- }
- }
- isRemoveHistoryItemAlertPresented = true
- }
- ).tint(.red)
- }
- .disabled(item.type == .tempBasal || item.type == .tempTarget || item.type == .resume || item.type == .suspend)
- .alert(
- Text(NSLocalizedString(alertTitle, comment: "")),
- isPresented: $isRemoveHistoryItemAlertPresented
- ) {
- Button("Cancel", role: .cancel) {}
- Button("Delete", role: .destructive) {
- guard let treatmentToDelete = alertTreatmentToDelete else {
- debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
- return
- }
- if state.historyLayout == .twoTabs, treatmentToDelete.type == .carbs || treatmentToDelete.type == .fpus {
- state.deleteCarbs(treatmentToDelete)
- } else {
- state.deleteInsulin(treatmentToDelete)
- }
- }
- } message: {
- Text("\n" + NSLocalizedString(alertMessage, comment: ""))
- }
- }
- @ViewBuilder private func mealView(_ meal: Treatment) -> some View {
- HStack {
- Image(systemName: "circle.fill").foregroundColor(meal.color)
- Text(meal.type.name)
- Text(meal.amountText).foregroundColor(.secondary)
- if let duration = meal.durationText {
- Text(duration).foregroundColor(.secondary)
- }
- Spacer()
- Text(dateFormatter.string(from: meal.date))
- .moveDisabled(true)
- }.swipeActions {
- Button(
- "Delete",
- systemImage: "trash.fill",
- role: .none,
- action: {
- alertTreatmentToDelete = meal
- if meal.type == .carbs {
- alertTitle = "Delete Carbs?"
- alertMessage = dateFormatter.string(from: meal.date) + ", " + meal.amountText
- } else if meal.type == .fpus {
- alertTitle = "Delete Carb Equivalents?"
- alertMessage = "All FPUs of the meal will be deleted."
- } else {
- // item is insulin treatment; item.type == .bolus
- alertTitle = "Delete Insulin?"
- alertMessage = dateFormatter.string(from: meal.date) + ", " + meal.amountText
- }
- isRemoveHistoryItemAlertPresented = true
- }
- ).tint(.red)
- }
- .alert(
- Text(NSLocalizedString(alertTitle, comment: "")),
- isPresented: $isRemoveHistoryItemAlertPresented
- ) {
- Button("Cancel", role: .cancel) {}
- Button("Delete", role: .destructive) {
- guard let treatmentToDelete = alertTreatmentToDelete else {
- debug(.default, "Cannot gracefully unwrap alertTreatmentToDelete!")
- return
- }
- state.deleteCarbs(treatmentToDelete)
- }
- } message: {
- Text("\n" + NSLocalizedString(alertMessage, comment: ""))
- }
- }
- var addExternalInsulinView: some View {
- NavigationView {
- VStack {
- Form {
- Section {
- HStack {
- Text("Amount")
- Spacer()
- DecimalTextField(
- "0",
- value: $state.externalInsulinAmount,
- formatter: insulinFormatter,
- autofocus: true,
- cleanInput: true
- )
- Text("U").foregroundColor(.secondary)
- }
- }
- Section {
- DatePicker("Date", selection: $state.externalInsulinDate, in: ...Date())
- }
- let amountWarningCondition = (state.externalInsulinAmount > state.maxBolus)
- Section {
- HStack {
- Button {
- state.addExternalInsulin()
- isAmountUnconfirmed = false
- showExternalInsulin = false
- }
- label: {
- Text("Log external insulin")
- }
- .foregroundColor(amountWarningCondition ? Color.white : Color.accentColor)
- .frame(maxWidth: .infinity, alignment: .center)
- .disabled(
- state.externalInsulinAmount <= 0 || state.externalInsulinAmount > state.maxBolus * 3
- )
- }
- }
- header: {
- if amountWarningCondition
- {
- Text("⚠️ Warning! The entered insulin amount is greater than your Max Bolus setting!")
- }
- }
- .listRowBackground(
- amountWarningCondition ? Color
- .red : colorScheme == .dark ? Color(UIColor.secondarySystemBackground) : Color.white
- )
- }
- }
- .onAppear(perform: configureView)
- .navigationTitle("External Insulin")
- .navigationBarTitleDisplayMode(.inline)
- .navigationBarItems(trailing: Button("Close", action: { showExternalInsulin = false
- state.externalInsulinAmount = 0 }))
- }
- }
- @ViewBuilder private func glucoseView(_ item: Glucose, isManual: BloodGlucose) -> some View {
- HStack {
- Text(item.glucose.glucose.map {
- (
- isManual.type == GlucoseType.manual.rawValue ?
- manualGlucoseFormatter :
- glucoseFormatter
- )
- .string(from: Double(
- state.units == .mmolL ? $0.asMmolL : Decimal($0)
- ) as NSNumber)!
- } ?? "--")
- if isManual.type == GlucoseType.manual.rawValue {
- Image(systemName: "drop.fill").symbolRenderingMode(.monochrome).foregroundStyle(.red)
- } else {
- Text(item.glucose.direction?.symbol ?? "--")
- }
- Spacer()
- Text(dateFormatter.string(from: item.glucose.dateString))
- }
- .swipeActions {
- Button(
- "Delete",
- systemImage: "trash.fill",
- role: .none,
- action: {
- alertGlucoseToDelete = item
- let valueText = (
- isManual.type == GlucoseType.manual.rawValue ?
- manualGlucoseFormatter :
- glucoseFormatter
- ).string(from: Double(
- state.units == .mmolL ? Double(item.glucose.value.asMmolL) : item.glucose.value
- ) as NSNumber)! + " " + state.units.rawValue
- alertTitle = "Delete Glucose?"
- alertMessage = dateFormatter.string(from: item.glucose.dateString) + ", " + valueText
- isRemoveHistoryItemAlertPresented = true
- }
- ).tint(.red)
- }
- .alert(
- Text(NSLocalizedString(alertTitle, comment: "")),
- isPresented: $isRemoveHistoryItemAlertPresented
- ) {
- Button("Cancel", role: .cancel) {}
- Button("Delete", role: .destructive) {
- guard let glucoseToDelete = alertGlucoseToDelete else {
- print("Cannot unwrap alertTreatmentToDelete!")
- return
- }
- state.deleteGlucose(glucoseToDelete)
- }
- } message: {
- Text("\n" + NSLocalizedString(alertMessage, comment: ""))
- }
- }
- }
- }
|