| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- //
- // 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", systemImage: "arrow.3.trianglepath") {
- tryAutosave()
- }
- .keyboardShortcut("R", modifiers: [.command, .shift])
- // .disabled(!shouldAutosave)
- .onAppear(perform: tryAutosave)
- .help("Will save as \(ymd(weekStart)) after \(ymd(nextSunday(weekStart)))")
- }
- 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, onDate: 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)
- }
|