Преглед изворни кода

feat: implement an autosave function that is run on app startup

Sam Jaffe пре 3 недеља
родитељ
комит
882782143c
2 измењених фајлова са 38 додато и 0 уклоњено
  1. 1 0
      Todos/TodosApp.swift
  2. 37 0
      Todos/View/ContentView.swift

+ 1 - 0
Todos/TodosApp.swift

@@ -11,6 +11,7 @@ import SwiftData
 struct UserDefaultsKeys {
   private static let root = "leumasjaffe.Todos"
   static let UrlHints = root + ".URLHints"
+  static let WeekStart = root + ".WeekStart"
 }
 
 @main

+ 37 - 0
Todos/View/ContentView.swift

@@ -10,6 +10,8 @@ import SwiftData
 
 struct ContentView: View {
   @Environment(\.modelContext) private var modelContext
+  @AppStorage(UserDefaultsKeys.WeekStart) private var weekStart = Date()
+  let inPreview = ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
   
   @Query private var items: [Category]
   
@@ -39,10 +41,16 @@ struct ContentView: View {
             Label("New Category", systemImage: "plus")
           }
         }
+        ToolbarItem {
+          Button(action: autosave) {
+            Label("Save Historical", systemImage: "document")
+          }
+        }
       }
     } detail: {
       Text("Select an item")
     }
+    .onAppear(perform: autosave)
   }
 
   private func addItem() {
@@ -56,6 +64,35 @@ struct ContentView: View {
     }
   }
   
+  private func autosave() {
+    if inPreview {
+      // This isn't great, but we shouldn't be running this in a preview
+      // environment in the first place, so w/e.
+      return
+    }
+    
+    let now = Date()
+    let sunday = Calendar.current.nextDate(after: weekStart,
+                                           matching: DateComponents(weekday: 1),
+                                           matchingPolicy: .nextTime)
+
+    if now <= sunday! {
+      return
+    }
+    
+    let ymd = weekStart.formatted(.iso8601.year().month().day())
+    let data = Data(items.map({ $0.yaml() }).joined().utf8)
+    let url = URL.documentsDirectory.appending(path: "Todo \(ymd).yaml")
+    do {
+      try data.write(to: url, options: [.atomic, .completeFileProtection])
+      let input = try String(contentsOf: url, encoding: .utf8)
+      print(input)
+    } catch {
+      print(error.localizedDescription)
+    }
+    weekStart = now
+  }
+  
   private func deleteItem(item: Category) {
     withAnimation {
       modelContext.delete(item)