93 lines
2.5 KiB
Swift
93 lines
2.5 KiB
Swift
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(
|
|
content: content,
|
|
id: newPostId,
|
|
isDraft: true,
|
|
createdDate: .now,
|
|
startDate: .now,
|
|
endDate: nil,
|
|
tags: [],
|
|
german: .init(content: content, title: "Titel", text: "Text"),
|
|
english: .init(content: content, title: "Title", text: "Text"))
|
|
content.posts.insert(post, at: 0)
|
|
selectedPost = post
|
|
dismissSheet()
|
|
}
|
|
|
|
private func dismissSheet() {
|
|
dismiss()
|
|
}
|
|
}
|
|
|
|
#Preview {
|
|
AddPostView(selected: .constant(nil))
|
|
.environmentObject(Content.mock)
|
|
}
|