Code cleanup

This commit is contained in:
VincentMeilinger
2024-01-25 22:51:08 +01:00
parent f6f9ca553a
commit 10cb851a5a
18 changed files with 131 additions and 107 deletions

View File

@@ -1,135 +0,0 @@
//
// AlertHandler.swift
// Nextcloud Cookbook iOS Client
//
// Created by Vincent Meilinger on 18.10.23.
//
import Foundation
import SwiftUI
protocol UserAlert: Error {
var localizedTitle: LocalizedStringKey { get }
var localizedDescription: LocalizedStringKey { get }
var alertButtons: [AlertButton] { get }
}
enum AlertButton: LocalizedStringKey, Identifiable {
var id: Self {
return self
}
case OK = "Ok", DELETE = "Delete", CANCEL = "Cancel"
}
enum RecipeAlert: UserAlert {
case NO_TITLE,
DUPLICATE,
UPLOAD_ERROR,
CONFIRM_DELETE,
LOGIN_FAILED,
GENERIC,
CUSTOM(title: LocalizedStringKey, description: LocalizedStringKey)
var localizedDescription: LocalizedStringKey {
switch self {
case .NO_TITLE:
return "Please enter a recipe name."
case .DUPLICATE:
return "A recipe with that name already exists."
case .UPLOAD_ERROR:
return "Unable to upload your recipe. Please check your internet connection."
case .CONFIRM_DELETE:
return "This action is not reversible!"
case .LOGIN_FAILED:
return "Please check your credentials and internet connection."
case .CUSTOM(title: _, description: let description):
return description
default:
return "An unknown error occured."
}
}
var localizedTitle: LocalizedStringKey {
switch self {
case .NO_TITLE:
return "Missing recipe name."
case .DUPLICATE:
return "Duplicate recipe."
case .UPLOAD_ERROR:
return "Network error."
case .CONFIRM_DELETE:
return "Delete recipe?"
case .LOGIN_FAILED:
return "Login failed."
case .CUSTOM(title: let title, description: _):
return title
default:
return "Error."
}
}
var alertButtons: [AlertButton] {
switch self {
case .CONFIRM_DELETE:
return [.CANCEL, .DELETE]
default:
return [.OK]
}
}
}
enum RecipeImportAlert: UserAlert {
case BAD_URL,
CHECK_CONNECTION,
WEBSITE_NOT_SUPPORTED
var localizedDescription: LocalizedStringKey {
switch self {
case .BAD_URL: return "Please check the entered URL."
case .CHECK_CONNECTION: return "Unable to load website content. Please check your internet connection."
case .WEBSITE_NOT_SUPPORTED: return "This website might not be currently supported. If this appears incorrect, you can use the support options in the app settings to raise awareness about this issue."
}
}
var localizedTitle: LocalizedStringKey {
switch self {
case .BAD_URL: return "Bad URL"
case .CHECK_CONNECTION: return "Connection error"
case .WEBSITE_NOT_SUPPORTED: return "Parsing error"
}
}
var alertButtons: [AlertButton] {
return [.OK]
}
}
enum RequestAlert: UserAlert {
case REQUEST_DELAYED,
REQUEST_DROPPED
var localizedDescription: LocalizedStringKey {
switch self {
case .REQUEST_DELAYED: return "Could not establish a connection to the server. The action will be retried upon reconnection."
case .REQUEST_DROPPED: return "Unable to complete action."
}
}
var localizedTitle: LocalizedStringKey {
switch self {
case .REQUEST_DELAYED: return "Action delayed"
case .REQUEST_DROPPED: return "Error"
}
}
var alertButtons: [AlertButton] {
return [.OK]
}
}

View File

@@ -8,19 +8,19 @@
import SwiftUI
struct MainView: View {
@StateObject var viewModel = MainViewModel()
@StateObject var viewModel = AppState()
@StateObject var groceryList = GroceryList()
@State var selectedCategory: Category? = nil
@State var showLoadingIndicator: Bool = false
@StateObject var recipeViewModel = RecipeTabView.ViewModel()
@StateObject var searchViewModel = SearchTabView.ViewModel()
enum Tab {
case recipes, search, groceryList, settings
case recipes, search, groceryList
}
var body: some View {
TabView {
RecipeTabView(selectedCategory: $selectedCategory, showLoadingIndicator: $showLoadingIndicator)
RecipeTabView()
.environmentObject(recipeViewModel)
.environmentObject(viewModel)
.environmentObject(groceryList)
.tabItem {
@@ -29,6 +29,7 @@ struct MainView: View {
.tag(Tab.recipes)
SearchTabView()
.environmentObject(searchViewModel)
.environmentObject(viewModel)
.environmentObject(groceryList)
.tabItem {
@@ -42,16 +43,9 @@ struct MainView: View {
Label("Grocery List", systemImage: "storefront")
}
.tag(Tab.groceryList)
SettingsView()
.environmentObject(viewModel)
.tabItem {
Label("Settings", systemImage: "gearshape")
}
.tag(Tab.settings)
}
.task {
showLoadingIndicator = true
recipeViewModel.presentLoadingIndicator = true
await viewModel.getCategories()
await viewModel.updateAllRecipeDetails()
@@ -63,11 +57,11 @@ struct MainView: View {
}
return false
}) {
self.selectedCategory = cat
recipeViewModel.selectedCategory = cat
}
}
showLoadingIndicator = false
await groceryList.load()
recipeViewModel.presentLoadingIndicator = false
}
}
}

View File

@@ -13,7 +13,7 @@ import SwiftUI
struct CategoryDetailView: View {
@State var categoryName: String
@State var searchText: String = ""
@ObservedObject var viewModel: MainViewModel
@ObservedObject var viewModel: AppState
@Binding var showEditView: Bool
var body: some View {

View File

@@ -9,7 +9,7 @@ import Foundation
import SwiftUI
struct RecipeCardView: View {
@State var viewModel: MainViewModel
@State var viewModel: AppState
@State var recipe: Recipe
@State var recipeThumb: UIImage?
@State var isDownloaded: Bool? = nil

View File

@@ -10,7 +10,7 @@ import SwiftUI
struct RecipeDetailView: View {
@ObservedObject var viewModel: MainViewModel
@ObservedObject var viewModel: AppState
@State var recipe: Recipe
@State var recipeDetail: RecipeDetail?
@State var recipeImage: UIImage?
@@ -214,7 +214,7 @@ fileprivate struct ShareView: View {
fileprivate struct RecipeDurationSection: View {
@ObservedObject var viewModel: MainViewModel
@ObservedObject var viewModel: AppState
@State var recipeDetail: RecipeDetail
var body: some View {

View File

@@ -11,7 +11,7 @@ import SwiftUI
struct SettingsView: View {
@EnvironmentObject var viewModel: MainViewModel
@EnvironmentObject var viewModel: AppState
@ObservedObject var userSettings = UserSettings.shared
@State fileprivate var alertType: SettingsAlert = .NONE

View File

@@ -10,25 +10,18 @@ import SwiftUI
struct RecipeTabView: View {
@Binding var selectedCategory: Category?
@Binding var showLoadingIndicator: Bool
@EnvironmentObject var viewModel: MainViewModel
@StateObject var userSettings: UserSettings = UserSettings.shared
@State private var showEditView: Bool = false
@State private var serverConnection: Bool = false
@EnvironmentObject var viewModel: RecipeTabView.ViewModel
@EnvironmentObject var mainViewModel: AppState
var body: some View {
NavigationSplitView {
List(selection: $selectedCategory) {
List(selection: $viewModel.selectedCategory) {
// Categories
ForEach(viewModel.categories) { category in
ForEach(mainViewModel.categories) { category in
if category.recipe_count != 0 {
NavigationLink(value: category) {
HStack(alignment: .center) {
if selectedCategory != nil && category.name == selectedCategory!.name {
if viewModel.selectedCategory != nil && category.name == viewModel.selectedCategory!.name {
Image(systemName: "book")
} else {
Image(systemName: "book.closed.fill")
@@ -52,53 +45,59 @@ struct RecipeTabView: View {
}
.navigationTitle("Cookbooks")
.toolbar {
RecipeTabViewToolBar(
viewModel: viewModel,
showEditView: $showEditView,
serverConnection: $serverConnection,
showLoadingIndicator: $showLoadingIndicator
)
RecipeTabViewToolBar()
}
.navigationDestination(isPresented: $viewModel.presentSettingsView) {
SettingsView()
}
} detail: {
NavigationStack {
if let category = selectedCategory {
if let category = viewModel.selectedCategory {
CategoryDetailView(
categoryName: category.name,
viewModel: viewModel,
showEditView: $showEditView
viewModel: mainViewModel,
showEditView: $viewModel.presentEditView
)
.id(category.id) // Workaround: This is needed to update the detail view when the selection changes
}
}
}
.tint(.nextcloudBlue)
.sheet(isPresented: $showEditView) {
.sheet(isPresented: $viewModel.presentEditView) {
RecipeEditView(
viewModel:
RecipeEditViewModel(
mainViewModel: viewModel,
mainViewModel: mainViewModel,
uploadNew: true
),
isPresented: $showEditView
isPresented: $viewModel.presentEditView
)
}
.task {
self.serverConnection = await viewModel.checkServerConnection()
viewModel.serverConnection = await mainViewModel.checkServerConnection()
}
.refreshable {
self.serverConnection = await viewModel.checkServerConnection()
await viewModel.getCategories()
viewModel.serverConnection = await mainViewModel.checkServerConnection()
await mainViewModel.getCategories()
}
}
class ViewModel: ObservableObject {
@Published var presentEditView: Bool = false
@Published var presentSettingsView: Bool = false
@Published var presentLoadingIndicator: Bool = false
@Published var presentConnectionPopover: Bool = false
@Published var serverConnection: Bool = false
@Published var selectedCategory: Category? = nil
}
}
fileprivate struct RecipeTabViewToolBar: ToolbarContent {
@ObservedObject var viewModel: MainViewModel
@Binding var showEditView: Bool
@Binding var serverConnection: Bool
@Binding var showLoadingIndicator: Bool
@State private var presentPopover: Bool = false
@EnvironmentObject var mainViewModel: AppState
@EnvironmentObject var viewModel: RecipeTabView.ViewModel
var body: some ToolbarContent {
// Top left menu toolbar item
@@ -106,20 +105,26 @@ fileprivate struct RecipeTabViewToolBar: ToolbarContent {
Menu {
Button {
Task {
showLoadingIndicator = true
viewModel.presentLoadingIndicator = true
UserSettings.shared.lastUpdate = Date.distantPast
await viewModel.getCategories()
for category in viewModel.categories {
await viewModel.getCategory(named: category.name, fetchMode: .preferServer)
await mainViewModel.getCategories()
for category in mainViewModel.categories {
await mainViewModel.getCategory(named: category.name, fetchMode: .preferServer)
}
await viewModel.updateAllRecipeDetails()
showLoadingIndicator = false
await mainViewModel.updateAllRecipeDetails()
viewModel.presentLoadingIndicator = false
}
} label: {
Text("Refresh all")
Image(systemName: "icloud.and.arrow.down")
}
Button {
viewModel.presentSettingsView = true
} label: {
Text("Settings")
Image(systemName: "gearshape")
}
} label: {
Image(systemName: "ellipsis.circle")
}
@@ -129,18 +134,18 @@ fileprivate struct RecipeTabViewToolBar: ToolbarContent {
ToolbarItem(placement: .topBarTrailing) {
Button {
print("Check server connection")
presentPopover = true
viewModel.presentConnectionPopover = true
} label: {
if showLoadingIndicator {
if viewModel.presentLoadingIndicator {
ProgressView()
} else if serverConnection {
} else if viewModel.serverConnection {
Image(systemName: "checkmark.icloud")
} else {
Image(systemName: "xmark.icloud")
}
}.popover(isPresented: $presentPopover) {
}.popover(isPresented: $viewModel.presentConnectionPopover) {
VStack(alignment: .leading) {
Text(serverConnection ? LocalizedStringKey("Connected to server.") : LocalizedStringKey("Unable to connect to server."))
Text(viewModel.serverConnection ? LocalizedStringKey("Connected to server.") : LocalizedStringKey("Unable to connect to server."))
.bold()
Text("Last updated: \(DateFormatter.utcToString(date: UserSettings.shared.lastUpdate))")
@@ -156,7 +161,7 @@ fileprivate struct RecipeTabViewToolBar: ToolbarContent {
ToolbarItem(placement: .topBarTrailing) {
Button {
print("Add new recipe")
showEditView = true
viewModel.presentEditView = true
} label: {
Image(systemName: "plus.circle.fill")
}

View File

@@ -10,26 +10,17 @@ import SwiftUI
struct SearchTabView: View {
@EnvironmentObject var viewModel: MainViewModel
var body: some View {
RecipeSearchView(viewModel: viewModel)
}
}
struct RecipeSearchView: View {
@ObservedObject var viewModel: MainViewModel
@State var searchText: String = ""
@State var allRecipes: [Recipe] = []
@EnvironmentObject var viewModel: SearchTabView.ViewModel
@EnvironmentObject var mainViewModel: AppState
var body: some View {
NavigationStack {
VStack {
ScrollView(showsIndicators: false) {
LazyVStack {
ForEach(recipesFiltered(), id: \.recipe_id) { recipe in
ForEach(viewModel.recipesFiltered(), id: \.recipe_id) { recipe in
NavigationLink(value: recipe) {
RecipeCardView(viewModel: viewModel, recipe: recipe)
RecipeCardView(viewModel: mainViewModel, recipe: recipe)
.shadow(radius: 2)
}
.buttonStyle(.plain)
@@ -37,22 +28,32 @@ struct RecipeSearchView: View {
}
}
.navigationDestination(for: Recipe.self) { recipe in
RecipeDetailView(viewModel: viewModel, recipe: recipe)
RecipeDetailView(viewModel: mainViewModel, recipe: recipe)
}
.searchable(text: $searchText, prompt: "Search recipes/keywords")
.searchable(text: $viewModel.searchText, prompt: "Search recipes/keywords")
}
.navigationTitle("Search recipe")
}
.task {
allRecipes = await viewModel.getRecipes()
if viewModel.allRecipes.isEmpty {
viewModel.allRecipes = await mainViewModel.getRecipes()
}
}
.refreshable {
viewModel.allRecipes = await mainViewModel.getRecipes()
}
}
func recipesFiltered() -> [Recipe] {
guard searchText != "" else { return allRecipes }
return allRecipes.filter { recipe in
recipe.name.lowercased().contains(searchText.lowercased()) || // check name for occurence of search term
(recipe.keywords != nil && recipe.keywords!.lowercased().contains(searchText.lowercased())) // check keywords for search term
class ViewModel: ObservableObject {
@Published var allRecipes: [Recipe] = []
@Published var searchText: String = ""
func recipesFiltered() -> [Recipe] {
guard searchText != "" else { return allRecipes }
return allRecipes.filter { recipe in
recipe.name.lowercased().contains(searchText.lowercased()) || // check name for occurence of search term
(recipe.keywords != nil && recipe.keywords!.lowercased().contains(searchText.lowercased())) // check keywords for search term
}
}
}
}