2024-12-09 17:47:03 +01:00

95 lines
2.6 KiB
Swift

import SwiftUI
struct AddPageView: View {
@Environment(\.dismiss)
private var dismiss: DismissAction
@Environment(\.language)
private var language: ContentLanguage
@EnvironmentObject
private var content: Content
@Binding
var selectedPage: Page?
@State
private var newPageId = ""
private let allowedCharactersInPageId = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-")).inverted
init(selected: Binding<Page?>) {
self._selectedPage = selected
}
private var idExists: Bool {
content.pages.contains { $0.id == newPageId }
}
private var containsInvalidCharacters: Bool {
newPageId.rangeOfCharacter(from: allowedCharactersInPageId) != nil
}
var body: some View {
VStack {
Text("New page")
.font(.headline)
TextField("", text: $newPageId)
.textFieldStyle(.roundedBorder)
.frame(maxWidth: 350)
if newPageId.isEmpty {
Text("Enter the id of the new page to create")
.foregroundStyle(.secondary)
} else if idExists {
Text("A page 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 page with the id")
.foregroundStyle(.secondary)
}
HStack {
Button(role: .cancel, action: dismissSheet) {
Text("Cancel")
}
Button(action: addNewPage) {
Text("Create")
}
.disabled(newPageId.isEmpty || containsInvalidCharacters || idExists)
}
}
.padding()
}
private func addNewPage() {
let page = Page(
content: content,
id: newPageId,
isDraft: true,
createdDate: .now,
startDate: .now,
endDate: nil,
german: .init(urlString: "seite",
title: "Ein Titel"),
english: .init(urlString: "page",
title: "A Title"),
tags: [])
content.pages.insert(page, at: 0)
selectedPage = page
dismissSheet()
}
private func dismissSheet() {
dismiss()
}
}
#Preview {
AddPageView(selected: .constant(nil))
.environmentObject(Content.mock)
}