Consolidate images and files
This commit is contained in:
91
CHDataManagement/Views/Posts/AddPostView.swift
Normal file
91
CHDataManagement/Views/Posts/AddPostView.swift
Normal file
@ -0,0 +1,91 @@
|
||||
import SwiftUI
|
||||
|
||||
struct AddPostView: View {
|
||||
|
||||
@Environment(\.dismiss)
|
||||
private var dismiss: DismissAction
|
||||
|
||||
@Environment(\.language)
|
||||
private var language: ContentLanguage
|
||||
|
||||
@EnvironmentObject
|
||||
private var content: Content
|
||||
|
||||
@Binding
|
||||
var selectedPost: Post?
|
||||
|
||||
@State
|
||||
private var newPostId = ""
|
||||
|
||||
private let allowedCharactersInPostId = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-")).inverted
|
||||
|
||||
init(selected: Binding<Post?>) {
|
||||
self._selectedPost = selected
|
||||
}
|
||||
|
||||
private var idExists: Bool {
|
||||
content.posts.contains { $0.id == newPostId }
|
||||
}
|
||||
|
||||
private var containsInvalidCharacters: Bool {
|
||||
newPostId.rangeOfCharacter(from: allowedCharactersInPostId) != nil
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
VStack {
|
||||
Text("New post")
|
||||
.font(.headline)
|
||||
|
||||
TextField("", text: $newPostId)
|
||||
.textFieldStyle(.roundedBorder)
|
||||
.frame(maxWidth: 350)
|
||||
if newPostId.isEmpty {
|
||||
Text("Enter the id of the new post to create")
|
||||
.foregroundStyle(.secondary)
|
||||
} else if idExists {
|
||||
Text("A post with the same id already exists")
|
||||
.foregroundStyle(Color.red)
|
||||
} else if containsInvalidCharacters {
|
||||
Text("The id contains invalid characters")
|
||||
.foregroundStyle(Color.red)
|
||||
} else {
|
||||
Text("Create a new post with the id")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
HStack {
|
||||
Button(role: .cancel, action: dismissSheet) {
|
||||
Text("Cancel")
|
||||
}
|
||||
Button(action: addNewPost) {
|
||||
Text("Create")
|
||||
}
|
||||
.disabled(newPostId.isEmpty || containsInvalidCharacters || idExists)
|
||||
}
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
|
||||
private func addNewPost() {
|
||||
let post = Post(
|
||||
id: newPostId,
|
||||
isDraft: true,
|
||||
createdDate: .now,
|
||||
startDate: .now,
|
||||
endDate: nil,
|
||||
tags: [],
|
||||
german: .init(title: "Titel", content: "Text"),
|
||||
english: .init(title: "Title", content: "Text"))
|
||||
content.posts.insert(post, at: 0)
|
||||
selectedPost = post
|
||||
dismissSheet()
|
||||
}
|
||||
|
||||
private func dismissSheet() {
|
||||
dismiss()
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
AddPostView(selected: .constant(nil))
|
||||
.environmentObject(Content.mock)
|
||||
}
|
Reference in New Issue
Block a user