Optimize autocomplete with debouncing

- Add 150ms debounce to text field onChange handler
- Prevents excessive autocomplete calculations during rapid typing
- Add timer cleanup in onDisappear
- Works for both main chat and private chat inputs
This commit is contained in:
jack
2025-07-24 13:40:34 +02:00
parent bb6552f4a6
commit 7120b11692
2 changed files with 70 additions and 26 deletions
+16 -4
View File
@@ -28,6 +28,7 @@ struct ContentView: View {
@FocusState private var isNicknameFieldFocused: Bool
@State private var lastScrollTime: Date = .distantPast
@State private var scrollThrottleTimer: Timer?
@State private var autocompleteDebounceTimer: Timer?
private var backgroundColor: Color {
colorScheme == .dark ? Color.black : Color.white
@@ -159,6 +160,11 @@ struct ContentView: View {
Button("cancel", role: .cancel) {}
}
.onDisappear {
// Clean up timers
scrollThrottleTimer?.invalidate()
autocompleteDebounceTimer?.invalidate()
}
}
private func messagesView(privatePeer: String?) -> some View {
@@ -399,11 +405,17 @@ struct ContentView: View {
.focused($isTextFieldFocused)
.padding(.leading, 12)
.onChange(of: messageText) { newValue in
// Get cursor position (approximate - end of text for now)
let cursorPosition = newValue.count
viewModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition)
// Cancel previous debounce timer
autocompleteDebounceTimer?.invalidate()
// Check for command autocomplete
// Debounce autocomplete updates to reduce calls during rapid typing
autocompleteDebounceTimer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: false) { _ in
// Get cursor position (approximate - end of text for now)
let cursorPosition = newValue.count
viewModel.updateAutocomplete(for: newValue, cursorPosition: cursorPosition)
}
// Check for command autocomplete (instant, no debounce needed)
if newValue.hasPrefix("/") && newValue.count >= 1 {
// Build context-aware command list
let commandDescriptions = [