diff --git a/src/hosts/main.py b/src/hosts/main.py index c12a678..ca7ba8a 100644 --- a/src/hosts/main.py +++ b/src/hosts/main.py @@ -176,6 +176,20 @@ class HostsManagerApp(App): return visible_entries + def get_first_visible_entry_index(self) -> int: + """Get the index of the first visible entry in the hosts file.""" + show_defaults = self.config.should_show_default_entries() + + for i, entry in enumerate(self.hosts_file.entries): + canonical_hostname = entry.hostnames[0] if entry.hostnames else "" + # Skip default entries if configured to hide them + if not show_defaults and self.config.is_default_entry(entry.ip_address, canonical_hostname): + continue + return i + + # If no visible entries found, return 0 + return 0 + def display_index_to_actual_index(self, display_index: int) -> int: """Convert a display table index to the actual hosts file entry index.""" visible_entries = self.get_visible_entries() @@ -270,8 +284,8 @@ class HostsManagerApp(App): return if previous_entry is None: - # No previous selection, start at first entry - self.selected_entry_index = 0 + # No previous selection, start at first visible entry + self.selected_entry_index = self.get_first_visible_entry_index() else: # Try to find the same entry in the reloaded file for i, entry in enumerate(self.hosts_file.entries): @@ -281,8 +295,8 @@ class HostsManagerApp(App): self.selected_entry_index = i break else: - # Entry not found, default to first entry - self.selected_entry_index = 0 + # Entry not found, default to first visible entry + self.selected_entry_index = self.get_first_visible_entry_index() # Update the DataTable cursor position using display index table = self.query_one("#entries-table", DataTable) @@ -302,6 +316,27 @@ class HostsManagerApp(App): details_widget.update("No entries loaded") return + # Get visible entries to check if we need to adjust selection + visible_entries = self.get_visible_entries() + if not visible_entries: + details_widget.update("No visible entries") + return + + # If default entries are hidden and selected_entry_index points to a hidden entry, + # we need to find the corresponding visible entry + show_defaults = self.config.should_show_default_entries() + if not show_defaults: + # Check if the currently selected entry is a default entry (hidden) + if (self.selected_entry_index < len(self.hosts_file.entries) and + self.hosts_file.entries[self.selected_entry_index].is_default_entry()): + # The selected entry is hidden, so we should show the first visible entry instead + if visible_entries: + # Find the first visible entry in the hosts file + for i, entry in enumerate(self.hosts_file.entries): + if not entry.is_default_entry(): + self.selected_entry_index = i + break + if self.selected_entry_index >= len(self.hosts_file.entries): self.selected_entry_index = 0