SettingsRootView.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import HealthKit
  2. import LoopKit
  3. import LoopKitUI
  4. import SwiftUI
  5. import Swinject
  6. import UIKit
  7. extension Settings {
  8. struct VersionInfo: Equatable {
  9. var latestVersion: String?
  10. var isUpdateAvailable: Bool
  11. var isBlacklisted: Bool
  12. var latestDevVersion: String?
  13. var isDevUpdateAvailable: Bool
  14. }
  15. struct RootView: BaseView {
  16. let resolver: Resolver
  17. @StateObject var state = StateModel()
  18. @State private var showShareSheet = false
  19. @State private var searchText: String = ""
  20. @State private var shouldDisplayHint: Bool = false
  21. @State var hintDetent = PresentationDetent.large
  22. @State var selectedVerboseHint: AnyView?
  23. @State var hintLabel: String?
  24. @State private var decimalPlaceholder: Decimal = 0.0
  25. @State private var booleanPlaceholder: Bool = false
  26. @State private var versionInfo = VersionInfo(
  27. latestVersion: nil,
  28. isUpdateAvailable: false,
  29. isBlacklisted: false,
  30. latestDevVersion: nil,
  31. isDevUpdateAvailable: false
  32. )
  33. @State private var closedLoopDisabled = true
  34. @State private var showCopiedToast = false
  35. @Environment(\.colorScheme) var colorScheme
  36. @EnvironmentObject var appIcons: Icons
  37. @Environment(AppState.self) var appState
  38. @Environment(SettingsSearchHighlight.self) var searchHighlight
  39. private var filteredItems: [FilteredSettingItem] {
  40. SettingItems.filteredItems(searchText: searchText)
  41. }
  42. @ViewBuilder var versionInfoView: some View {
  43. VStack(alignment: .leading, spacing: 4) {
  44. // Main version info
  45. if let version = versionInfo.latestVersion {
  46. let updateColor: Color = versionInfo.isUpdateAvailable ? .orange : .green
  47. let versionIconName = versionInfo
  48. .isUpdateAvailable ? "exclamationmark.triangle.fill" : "checkmark.circle.fill"
  49. HStack {
  50. Text("Latest version: \(version)")
  51. .font(.footnote)
  52. .foregroundColor(updateColor)
  53. Image(systemName: versionIconName)
  54. .foregroundColor(updateColor)
  55. }
  56. if versionInfo.isBlacklisted {
  57. HStack {
  58. Text("Warning: Known issues. Update now.")
  59. .font(.footnote)
  60. .foregroundColor(.red)
  61. Image(systemName: "exclamationmark.octagon.fill")
  62. .foregroundColor(.red)
  63. }
  64. }
  65. } else {
  66. Text("Latest version: Fetching...")
  67. .font(.footnote)
  68. .foregroundColor(.secondary)
  69. }
  70. // Show latest dev version on any branch except main
  71. let buildDetails = BuildDetails.shared
  72. if buildDetails.trioBranch != "main" {
  73. if let devVersion = versionInfo.latestDevVersion {
  74. let devUpdateColor: Color = versionInfo.isDevUpdateAvailable ? .orange : .secondary
  75. let devVersionIconName = versionInfo.isDevUpdateAvailable ? "arrow.up.circle.fill" : "hammer.fill"
  76. HStack {
  77. Text("Latest dev: \(devVersion)")
  78. .font(.footnote)
  79. .foregroundColor(devUpdateColor)
  80. Image(systemName: devVersionIconName)
  81. .font(.footnote)
  82. .foregroundColor(devUpdateColor)
  83. }
  84. } else {
  85. Text("Latest dev: Fetching...")
  86. .font(.footnote)
  87. .foregroundColor(.secondary)
  88. }
  89. }
  90. }
  91. }
  92. var body: some View {
  93. List {
  94. if searchText.isEmpty {
  95. let buildDetails = BuildDetails.shared
  96. Section(
  97. header: Text("BRANCH: \(buildDetails.branchAndSha)").textCase(nil),
  98. content: {
  99. /// The current development version of the app.
  100. ///
  101. /// Follows a semantic pattern where release versions are like `0.5.0`, and
  102. /// development versions increment with a fourth component (e.g., `0.5.0.1`, `0.5.0.2`)
  103. /// after the base release. For example:
  104. /// - After release `0.5.0` → `0.5.0`
  105. /// - First dev push → `0.5.0.1`
  106. /// - Next dev push → `0.5.0.2`
  107. /// - Next release `0.6.0` → `0.6.0`
  108. /// - Next dev push → `0.6.0.1`
  109. ///
  110. /// If the dev version is unavailable, `"unknown"` is returned.
  111. let devVersion = Bundle.main.appDevVersion ?? "unknown"
  112. let buildNumber = Bundle.main.buildVersionNumber ?? String(localized: "Unknown")
  113. NavigationLink(destination: SubmodulesView(buildDetails: buildDetails)) {
  114. HStack {
  115. Image(appIcons.appIcon.rawValue)
  116. .resizable()
  117. .aspectRatio(contentMode: .fit)
  118. .frame(width: 50, height: 50)
  119. .cornerRadius(10)
  120. .padding(.trailing, 10)
  121. VStack(alignment: .leading, spacing: 4) {
  122. Text("Trio v\(devVersion) (\(buildNumber))")
  123. .font(.headline)
  124. if let expirationDate = buildDetails.calculateExpirationDate() {
  125. let formattedDate = DateFormatter.localizedString(
  126. from: expirationDate,
  127. dateStyle: .medium,
  128. timeStyle: .none
  129. )
  130. Text("\(buildDetails.expirationHeaderString): \(formattedDate)")
  131. .font(.footnote)
  132. .foregroundColor(.secondary)
  133. } else {
  134. Text("Simulator Build has no expiry")
  135. .font(.footnote)
  136. .foregroundColor(.secondary)
  137. }
  138. versionInfoView
  139. }
  140. }
  141. .contentShape(Rectangle())
  142. .onLongPressGesture {
  143. UIPasteboard.general.string =
  144. "Trio v\(devVersion) (\(buildNumber)) \(buildDetails.branchAndSha)"
  145. UINotificationFeedbackGenerator().notificationOccurred(.success)
  146. withAnimation { showCopiedToast = true }
  147. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  148. withAnimation { showCopiedToast = false }
  149. }
  150. }
  151. }
  152. }
  153. ).listRowBackground(Color.chart)
  154. let miniHintText = closedLoopDisabled ?
  155. String(localized: "Add a CGM and pump to enable automated insulin delivery") :
  156. String(localized: "Enable automated insulin delivery.")
  157. let miniHintTextColorForDisabled: Color = colorScheme == .dark ? .orange : .accentColor
  158. let miniHintTextColor: Color = closedLoopDisabled ? miniHintTextColorForDisabled : .secondary
  159. SettingInputSection(
  160. decimalValue: $decimalPlaceholder,
  161. booleanValue: $state.closedLoop,
  162. shouldDisplayHint: $shouldDisplayHint,
  163. selectedVerboseHint: Binding(
  164. get: { selectedVerboseHint },
  165. set: {
  166. selectedVerboseHint = $0.map { AnyView($0) }
  167. hintLabel = String(localized: "Closed Loop")
  168. }
  169. ),
  170. units: state.units,
  171. type: .boolean,
  172. label: String(localized: "Closed Loop"),
  173. miniHint: miniHintText,
  174. verboseHint: VStack(alignment: .leading, spacing: 10) {
  175. Text(
  176. "Running Trio in closed loop mode requires an active CGM sensor session and a connected pump. This enables automated insulin delivery."
  177. )
  178. Text(
  179. "Before enabling, dial in your settings (basal / insulin sensitivity / carb ratio), and familiarize yourself with the app."
  180. )
  181. },
  182. headerText: String(localized: "Automated Insulin Delivery"),
  183. isToggleDisabled: closedLoopDisabled,
  184. miniHintColor: miniHintTextColor
  185. )
  186. .onAppear {
  187. closedLoopDisabled = !state.hasCgmAndPump()
  188. }
  189. Section(
  190. header: Text("Trio Configuration"),
  191. content: {
  192. ForEach(SettingItems.trioConfig) { item in
  193. Text(LocalizedStringKey(item.title)).navigationLink(to: item.view, from: self)
  194. }
  195. }
  196. )
  197. .listRowBackground(Color.chart)
  198. Section(
  199. header: Text("Support & Community"),
  200. content: {
  201. Button {
  202. showShareSheet.toggle()
  203. } label: {
  204. HStack {
  205. Text("Share Logs")
  206. .foregroundColor(.primary)
  207. Spacer()
  208. Image(systemName: "chevron.right")
  209. .foregroundColor(.secondary)
  210. .font(.footnote)
  211. }
  212. }
  213. .frame(maxWidth: .infinity, alignment: .leading)
  214. Button {
  215. if let url = URL(string: "https://github.com/nightscout/Trio/issues/new/choose") {
  216. UIApplication.shared.open(url)
  217. }
  218. } label: {
  219. HStack {
  220. Text("Submit Ticket on GitHub")
  221. .foregroundColor(.primary)
  222. Spacer()
  223. Image(systemName: "chevron.right")
  224. .foregroundColor(.secondary)
  225. .font(.footnote)
  226. }
  227. }
  228. .frame(maxWidth: .infinity, alignment: .leading)
  229. Button {
  230. if let url = URL(string: "https://discord.triodocs.org") {
  231. UIApplication.shared.open(url)
  232. }
  233. } label: {
  234. HStack {
  235. Text("Trio Discord")
  236. .foregroundColor(.primary)
  237. Spacer()
  238. Image(systemName: "chevron.right")
  239. .foregroundColor(.secondary)
  240. .font(.footnote)
  241. }
  242. }
  243. .frame(maxWidth: .infinity, alignment: .leading)
  244. Button {
  245. if let url = URL(string: "https://facebook.triodocs.org") {
  246. UIApplication.shared.open(url)
  247. }
  248. } label: {
  249. HStack {
  250. Text("Trio Facebook")
  251. .foregroundColor(.primary)
  252. Spacer()
  253. Image(systemName: "chevron.right")
  254. .foregroundColor(.secondary)
  255. .font(.footnote)
  256. }
  257. }
  258. .frame(maxWidth: .infinity, alignment: .leading)
  259. }
  260. ).listRowBackground(Color.chart)
  261. Section(
  262. header: Text("Trio Backup"),
  263. content: {
  264. Text(String(
  265. localized: "Export Settings",
  266. comment: "Export Settings menu item in Trio Settings Root View"
  267. ))
  268. .navigationLink(to: .settingsExport, from: self)
  269. }
  270. ).listRowBackground(Color.chart)
  271. } else {
  272. Section(
  273. header: Text("Search Results"),
  274. content: {
  275. if filteredItems.isNotEmpty {
  276. ForEach(filteredItems) { filteredItem in
  277. NavigationLink(value: SearchResultTarget(
  278. screen: filteredItem.settingItem.view,
  279. scrollLabel: filteredItem.scrollLabel.localized
  280. )) {
  281. VStack(alignment: .leading) {
  282. Text(filteredItem.matchedContent.localized).bold()
  283. if let path = filteredItem.settingItem.path {
  284. Text(path.map(\.localized).joined(separator: " > "))
  285. .font(.caption)
  286. .foregroundColor(.secondary)
  287. }
  288. }
  289. }
  290. }
  291. } else {
  292. Text("No settings matching your search query")
  293. +
  294. Text(" »\(searchText)« ").bold()
  295. +
  296. Text("found.")
  297. }
  298. }
  299. ).listRowBackground(Color.chart)
  300. }
  301. }
  302. .overlay(alignment: .bottom) {
  303. if showCopiedToast {
  304. Label("Copied", systemImage: "checkmark.circle.fill")
  305. .font(.footnote.weight(.semibold))
  306. .foregroundColor(.white)
  307. .padding(.horizontal, 16)
  308. .padding(.vertical, 10)
  309. .background(.ultraThinMaterial, in: Capsule())
  310. .padding(.bottom, 32)
  311. .transition(.move(edge: .bottom).combined(with: .opacity))
  312. }
  313. }
  314. .scrollContentBackground(.hidden).background(appState.trioBackgroundColor(for: colorScheme))
  315. .sheet(isPresented: $shouldDisplayHint) {
  316. SettingInputHintView(
  317. hintDetent: $hintDetent,
  318. shouldDisplayHint: $shouldDisplayHint,
  319. hintLabel: hintLabel ?? "",
  320. hintText: selectedVerboseHint ?? AnyView(EmptyView()),
  321. sheetTitle: String(localized: "Help", comment: "Help sheet title")
  322. )
  323. }
  324. .sheet(isPresented: $showShareSheet) {
  325. ShareSheet(activityItems: state.logItems())
  326. }
  327. .onAppear(perform: configureView)
  328. .navigationTitle("Settings")
  329. .navigationBarTitleDisplayMode(.automatic)
  330. .toolbar {
  331. ToolbarItem(placement: .topBarTrailing) {
  332. Button(
  333. action: {
  334. if let url = URL(string: "https://triodocs.org/") {
  335. UIApplication.shared.open(url)
  336. }
  337. },
  338. label: {
  339. HStack {
  340. Text("Trio Docs")
  341. Image(systemName: "questionmark.circle")
  342. }
  343. }
  344. )
  345. }
  346. }
  347. .searchable(text: $searchText, placement: .navigationBarDrawer(displayMode: .always))
  348. .navigationDestination(for: SearchResultTarget.self) { target in
  349. state.view(for: target.screen)
  350. .onAppear {
  351. searchHighlight.highlightedSetting = target.scrollLabel
  352. }
  353. }
  354. .screenNavigation(self)
  355. .onAppear {
  356. Task { @MainActor in
  357. let (_, latestVersion, isNewer, isBlacklisted) = await AppVersionChecker.shared.refreshVersionInfo()
  358. versionInfo.latestVersion = latestVersion
  359. versionInfo.isUpdateAvailable = isNewer
  360. versionInfo.isBlacklisted = isBlacklisted
  361. // Fetch dev version if not on main branch
  362. let buildDetails = BuildDetails.shared
  363. if buildDetails.trioBranch != "main" {
  364. let (devVersion, isDevNewer) = await AppVersionChecker.shared.checkForNewDevVersion()
  365. versionInfo.latestDevVersion = devVersion
  366. versionInfo.isDevUpdateAvailable = isDevNewer
  367. }
  368. }
  369. }
  370. }
  371. }
  372. }