Implementation: fix checking the username so it won't generate undefined behavior during ui rendering
This commit is contained in:
@@ -12,22 +12,24 @@ extension EnvironmentValues {
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
@AppStorage("peered_username") private var username: String = "fallback_user"
|
||||
@State private var notes = [Note]()
|
||||
@AppStorage("peered_username") private var username: String = "fallback_user"
|
||||
@State private var notes = [Note]()
|
||||
@State private var notesClient: NoteEditingSessionClient?
|
||||
@State private var ownPeer: OwnPeer?
|
||||
|
||||
var body: some View {
|
||||
var isUsernameValid: Bool {
|
||||
username != "fallback_user" && !username.isEmpty
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
List {
|
||||
Section("Your notes") {
|
||||
ForEach(notes) { note in
|
||||
NavigationLink(note.name) {
|
||||
let peer = ownPeer ?? .init(peer: .init(displayName: username))
|
||||
if ownPeer == nil {
|
||||
ownPeer = peer
|
||||
if let ownPeer {
|
||||
NoteEditorScreen(note: note, peer: ownPeer)
|
||||
}
|
||||
return NoteEditorScreen(note: note, peer: peer)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,25 +47,36 @@ struct ContentView: View {
|
||||
.environment(\.ownPeer, ownPeer ?? .fallback)
|
||||
.navigationTitle("Peered")
|
||||
.toolbar {
|
||||
Button("Create note") {
|
||||
NotesStorage().createNote(name: "New Note")
|
||||
notes = NotesStorage().loadNotes()
|
||||
}
|
||||
Button("Create note") {
|
||||
NotesStorage().createNote(name: "New Note")
|
||||
notes = NotesStorage().loadNotes()
|
||||
}
|
||||
}
|
||||
}
|
||||
.onAppear {
|
||||
notes = NotesStorage().loadNotes()
|
||||
if notesClient == nil {
|
||||
notesClient = .init(peer: .init(displayName: username))
|
||||
if isUsernameValid {
|
||||
setupSession()
|
||||
}
|
||||
notesClient?.startBrowsingForNotes()
|
||||
}
|
||||
.sheet(isPresented: .constant(username == "fallback_user" || username.isEmpty)) {
|
||||
SetUserNameBottomSheetView(username: $username)
|
||||
}
|
||||
}
|
||||
.onChange(of: username) { _, newUsername in
|
||||
guard isUsernameValid else { return }
|
||||
setupSession()
|
||||
}
|
||||
.sheet(isPresented: .constant(!isUsernameValid)) {
|
||||
SetUserNameBottomSheetView(username: $username)
|
||||
}
|
||||
}
|
||||
|
||||
private func setupSession() {
|
||||
notesClient?.stopBrowsingForNotes()
|
||||
let peer = OwnPeer(peer: .init(displayName: username))
|
||||
ownPeer = peer
|
||||
notesClient = .init(peer: peer.peer)
|
||||
notesClient?.startBrowsingForNotes()
|
||||
}
|
||||
}
|
||||
|
||||
#Preview {
|
||||
ContentView()
|
||||
ContentView()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user