| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109 |
- //
- // ContentView.swift
- // Todos
- //
- // Created by Sam Jaffe on 2/28/26.
- //
- import SwiftUI
- 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]
-
- @State private var showingPopup = false
- @State private var currentHint: URLHint = URLHint()
-
- var body: some View {
- NavigationSplitView {
- List {
- ForEach(items) { item in
- NavigationLink {
- CategoryPanelView(item: item)
- } label: {
- CategorySidebarView(name: Bindable(item).name)
- } .contextMenu {
- Button(action: { deleteItem(item: item) }) {
- Label("Delete", systemImage: "trash")
- }
- }
- }
- .onDelete(perform: deleteItems)
- }
- .navigationSplitViewColumnWidth(min: 180, ideal: 200)
- .toolbar {
- ToolbarItem {
- Button(action: addItem) {
- Label("New Category", systemImage: "plus")
- }
- }
- }
- } detail: {
- Text("Select an item")
- }
- .onAppear(perform: autosave)
- }
- private func addItem() {
- withAnimation {
- let newItem = Category(timestamp: Date())
- let count = items.count(where: { $0.name.starts(with: "New Category") })
- if (count > 0) {
- newItem.name += " (\(count))"
- }
- modelContext.insert(newItem)
- }
- }
-
- 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)
- }
- }
- private func deleteItems(offsets: IndexSet) {
- withAnimation {
- for index in offsets {
- modelContext.delete(items[index])
- }
- }
- }
- }
- #Preview {
- ContentView()
- .modelContainer(for: Category.self, inMemory: true)
- }
|