| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- //
- // SaveAndRefreshMenu.swift
- // Todos
- //
- // Created by Sam Jaffe on 3/9/26.
- //
- import SwiftUI
- import SwiftData
- internal import Combine
- struct AutosaveMenu: 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: [Project]
- @Binding var hasAutosave: Bool
- var body: some View {
- Button("Save and Cleanup") {
- tryAutosave()
- }
- .keyboardShortcut("R", modifiers: [.command, .shift])
- // .disabled(!shouldAutosave)
- Text(" Next Autosave: after \(ymd(nextSunday(weekStart)))")
- .onAppear(perform: tryAutosave)
- }
- func tryAutosave() {
- if shouldAutosave && !inPreview {
- saveAndCleanup(weekStart)
- weekStart = Date()
- hasAutosave = true
- }
- }
- func nextSunday(_ date: Date) -> Date {
- Calendar.current.nextDate(after: date,
- matching: DateComponents(weekday: 1),
- matchingPolicy: .nextTime)!
- }
- func ymd(_ date: Date) -> String {
- date.formatted(.iso8601.year().month().day())
- }
- var shouldAutosave: Bool {
- ymd(Date()) > ymd(nextSunday(weekStart))
- }
- func saveAndCleanup(_ date: Date) {
- SaveController.save(items, toUrl: SaveController.filename(date: ymd(date)))
- for item in items {
- item.tasks.removeAll(where: { $0.status == .complete })
- for task in item.tasks {
- if task.status == .inProgress {
- task.status = .todo
- }
- task.subtasks.removeAll(where: { $0.status == .complete })
- for subtask in task.subtasks where subtask.status == .inProgress {
- subtask.status = .todo
- }
- }
- }
- }
- }
- #Preview {
- @Previewable @State var hasAutosave = true
- AutosaveMenu(hasAutosave: $hasAutosave)
- }
|