-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNoteCreationView.swift
More file actions
75 lines (66 loc) · 2.55 KB
/
NoteCreationView.swift
File metadata and controls
75 lines (66 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import SwiftUI
import SwiftData
struct NoteCreationView: View {
@Environment(\.modelContext) private var modelContext
@Environment(\.dismiss) private var dismiss
@Query(sort: \Folder.name) private var folders: [Folder]
let parentNote: Note?
@State private var title = ""
@State private var selectedFolderID: PersistentIdentifier?
init(parentNote: Note? = nil) {
self.parentNote = parentNote
}
var body: some View {
NavigationStack {
Form {
Section(header: Text("Note Details")) {
TextField("Note name", text: $title)
.font(.body)
if let parent = parentNote {
HStack {
Text("Sub-note of:")
.foregroundStyle(.secondary)
Text(parent.title)
.fontWeight(.bold)
}
.font(.caption)
} else {
Picker("Folder", selection: $selectedFolderID) {
Text("None (Root)").tag(nil as PersistentIdentifier?)
ForEach(folders) { folder in
Text(folder.name).tag(folder.id as PersistentIdentifier?)
}
}
}
}
}
.formStyle(.grouped)
.navigationTitle(parentNote == nil ? "New Note" : "New Sub-note")
.frame(width: 400, height: 280)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Cancel") { dismiss() }
}
ToolbarItem(placement: .confirmationAction) {
Button("Create") {
createNewNote()
}
.disabled(title.trimmingCharacters(in: .whitespaces).isEmpty)
}
}
}
}
private func createNewNote() {
let newNote = Note(title: title.isEmpty ? "New note" : title)
if let parent = parentNote {
newNote.parentNote = parent
newNote.folder = parent.folder
} else if let folderID = selectedFolderID,
let folder = folders.first(where: { $0.id == folderID }) {
newNote.folder = folder
}
modelContext.insert(newNote)
try? modelContext.save()
dismiss()
}
}