// // BudgetsListView.swift // ydnab // // Created by Andrea Franceschini on 23/09/2020. // import SwiftUI class BudgetsListViewModel: ObservableObject { @Published var items: BudgetsList init() { let applicationSupportURL = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] guard !applicationSupportURL.path.isEmpty else { print("Couldn't find Application Support path.") items = [] return } let budgetsListURL = URL(fileURLWithPath: "Budgets.json", relativeTo: applicationSupportURL) guard FileManager.default.fileExists(atPath: budgetsListURL.path) else { print("Couldn't find the budgets list in Application Support.") print(budgetsListURL.path) items = [] return } do { items = try JSONDecoder().decode(BudgetsList.self, from: Data.init(contentsOf: budgetsListURL)) } catch { print("Couldn't open the budgets list.") print("Error: \(error)") items = [] return } } } struct BudgetsListView: View { @State var currentBudgetId: UUID? @ObservedObject var budgetsList = BudgetsListViewModel() init(currentBudgetId: UUID?, budgetsList: BudgetsListViewModel = BudgetsListViewModel()) { self.currentBudgetId = currentBudgetId self.budgetsList = budgetsList } func createBudget() { print("Creating new budget...") print("... done creating new budget.") } var body: some View { VStack { List { ForEach(budgetsList.items) { budget in NavigationLink(destination: BudgetView(budget: budget, currentBudgetId: $currentBudgetId), tag: budget.id, selection: $currentBudgetId) { Text(budget.name) } } .onDelete(perform: { indexSet in print(indexSet) }) .onMove(perform: { indices, newOffset in print("\(indices) :: \(newOffset)") }) } Text(currentBudgetId?.uuidString ?? "--") } .listStyle(PlainListStyle()) .navigationTitle("Budgets") .toolbar { #if os(iOS) ToolbarItem(placement: .primaryAction) { EditButton() } #endif ToolbarItem(placement: .navigationBarLeading) { Button("Add") { print(self) } } } } } struct BudgetsListView_Previews: PreviewProvider { static var previews: some View { NavigationView { BudgetsListView(currentBudgetId: UUID()) } } }