mirror of
https://github.com/pacnpal/thrillwiki_django_no_react.git
synced 2025-12-23 23:51:07 -05:00
Add search suggestions feature with improved filtering and UI
This commit is contained in:
101
templates/rides/partials/ride_list_results.html
Normal file
101
templates/rides/partials/ride_list_results.html
Normal file
@@ -0,0 +1,101 @@
|
||||
{% load ride_tags %}
|
||||
|
||||
<!-- Rides Grid -->
|
||||
<div id="rides-grid" class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-3">
|
||||
{% for ride in rides %}
|
||||
<div class="overflow-hidden transition-transform transform bg-white rounded-lg shadow-lg dark:bg-gray-800 hover:-translate-y-1">
|
||||
<div class="aspect-w-16 aspect-h-9">
|
||||
<a href="{% url 'parks:rides:ride_detail' ride.park.slug ride.slug %}"
|
||||
class="text-gray-900 hover:text-blue-600 dark:text-white dark:hover:text-blue-400">
|
||||
{{ ride.name }}
|
||||
{% if ride.photos.exists %}
|
||||
<img src="{{ ride.photos.first.image.url }}"
|
||||
alt="{{ ride.name }}"
|
||||
class="object-cover w-full">
|
||||
{% else %}
|
||||
<img src="{% get_ride_placeholder_image ride.category %}"
|
||||
alt="{{ ride.name }}"
|
||||
class="object-cover w-full">
|
||||
{% endif %}
|
||||
</a>
|
||||
</div>
|
||||
<div class="p-4">
|
||||
<h2 class="mb-2 text-xl font-bold">
|
||||
<a href="{% url 'parks:rides:ride_detail' ride.park.slug ride.slug %}"
|
||||
class="text-gray-900 hover:text-blue-600 dark:text-white dark:hover:text-blue-400">
|
||||
{{ ride.name }}
|
||||
</a>
|
||||
</h2>
|
||||
{% if not park %}
|
||||
<p class="mb-3 text-gray-600 dark:text-gray-400">
|
||||
at <a href="{% url 'parks:park_detail' ride.park.slug %}"
|
||||
class="text-blue-600 hover:text-blue-700 dark:text-blue-400 dark:hover:text-blue-300">
|
||||
{{ ride.park.name }}
|
||||
</a>
|
||||
</p>
|
||||
{% endif %}
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<span class="text-blue-800 bg-blue-100 status-badge dark:bg-blue-400/30 dark:text-blue-200 dark:ring-1 dark:ring-blue-400/30">
|
||||
{{ ride.get_category_display }}
|
||||
</span>
|
||||
<span class="status-badge {% if ride.status == 'OPERATING' %}status-operating
|
||||
{% elif ride.status == 'CLOSED_TEMP' or ride.status == 'CLOSED_PERM' %}status-closed
|
||||
{% elif ride.status == 'UNDER_CONSTRUCTION' %}status-construction
|
||||
{% elif ride.status == 'DEMOLISHED' %}status-demolished
|
||||
{% elif ride.status == 'RELOCATED' %}status-relocated{% endif %}">
|
||||
{{ ride.get_status_display }}
|
||||
</span>
|
||||
{% if ride.average_rating %}
|
||||
<span class="text-yellow-800 bg-yellow-100 status-badge dark:bg-yellow-400/30 dark:text-yellow-200 dark:ring-1 dark:ring-yellow-400/30">
|
||||
<i class="mr-1 text-yellow-500 fas fa-star dark:text-yellow-300"></i>
|
||||
{{ ride.average_rating|floatformat:1 }}/10
|
||||
</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if ride.coaster_stats %}
|
||||
<div class="grid grid-cols-2 gap-2 mt-4">
|
||||
{% if ride.coaster_stats.height_ft %}
|
||||
<div class="text-sm text-gray-600 dark:text-gray-400">
|
||||
Height: {{ ride.coaster_stats.height_ft }}ft
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if ride.coaster_stats.speed_mph %}
|
||||
<div class="text-sm text-gray-600 dark:text-gray-400">
|
||||
Speed: {{ ride.coaster_stats.speed_mph }}mph
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% empty %}
|
||||
<div class="col-span-3 py-8 text-center">
|
||||
<p class="text-gray-500 dark:text-gray-400">No rides found matching your criteria.</p>
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
<!-- Pagination -->
|
||||
{% if is_paginated %}
|
||||
<div class="flex justify-center mt-6" hx-target="#rides-grid" hx-push-url="true">
|
||||
<div class="inline-flex rounded-md shadow-sm" hx-indicator=".loading-indicator">
|
||||
{% if page_obj.has_previous %}
|
||||
<a hx-get="?page=1{{ request.GET.urlencode }}"
|
||||
class="px-3 py-2 text-gray-700 bg-white border border-gray-300 rounded-l-lg hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700">« First</a>
|
||||
<a hx-get="?page={{ page_obj.previous_page_number }}{{ request.GET.urlencode }}"
|
||||
class="px-3 py-2 text-gray-700 bg-white border-t border-b border-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700">Previous</a>
|
||||
{% endif %}
|
||||
|
||||
<span class="px-3 py-2 text-gray-700 bg-white border border-gray-300 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300">
|
||||
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}
|
||||
</span>
|
||||
|
||||
{% if page_obj.has_next %}
|
||||
<a hx-get="?page={{ page_obj.next_page_number }}{{ request.GET.urlencode }}"
|
||||
class="px-3 py-2 text-gray-700 bg-white border-t border-b border-gray-300 hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700">Next</a>
|
||||
<a hx-get="?page={{ page_obj.paginator.num_pages }}{{ request.GET.urlencode }}"
|
||||
class="px-3 py-2 text-gray-700 bg-white border border-gray-300 rounded-r-lg hover:bg-gray-50 dark:bg-gray-800 dark:border-gray-600 dark:text-gray-300 dark:hover:bg-gray-700">Last »</a>
|
||||
{% endif %}
|
||||
</div>
|
||||
</div>
|
||||
{% endif %}
|
||||
327
templates/rides/partials/search_script.html
Normal file
327
templates/rides/partials/search_script.html
Normal file
@@ -0,0 +1,327 @@
|
||||
<script>
|
||||
document.addEventListener('alpine:init', () => {
|
||||
Alpine.data('rideSearch', () => ({
|
||||
init() {
|
||||
// Initialize from URL params
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
this.searchQuery = urlParams.get('search') || '';
|
||||
|
||||
// Bind to form reset
|
||||
document.querySelector('form').addEventListener('reset', () => {
|
||||
this.searchQuery = '';
|
||||
this.showSuggestions = false;
|
||||
this.selectedIndex = -1;
|
||||
this.cleanup();
|
||||
});
|
||||
|
||||
// Handle clicks outside suggestions
|
||||
document.addEventListener('click', (e) => {
|
||||
if (!e.target.closest('#search-suggestions') && !e.target.closest('#search')) {
|
||||
this.showSuggestions = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Handle HTMX errors
|
||||
document.body.addEventListener('htmx:error', (evt) => {
|
||||
console.error('HTMX Error:', evt.detail.error);
|
||||
this.showError('An error occurred while searching. Please try again.');
|
||||
});
|
||||
|
||||
// Bind to popstate for browser navigation
|
||||
window.addEventListener('popstate', () => {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
this.searchQuery = urlParams.get('search') || '';
|
||||
this.syncFormWithUrl();
|
||||
});
|
||||
|
||||
// Restore filters from localStorage if no URL params exist
|
||||
const savedFilters = localStorage.getItem('rideFilters');
|
||||
if (savedFilters) {
|
||||
const filters = JSON.parse(savedFilters);
|
||||
Object.entries(filters).forEach(([key, value]) => {
|
||||
const input = document.querySelector(`[name="${key}"]`);
|
||||
if (input) input.value = value;
|
||||
});
|
||||
// Trigger search with restored filters
|
||||
document.querySelector('form').dispatchEvent(new Event('change'));
|
||||
}
|
||||
|
||||
// Set up filter persistence
|
||||
document.querySelector('form').addEventListener('change', (e) => {
|
||||
this.saveFilters();
|
||||
});
|
||||
},
|
||||
|
||||
showSuggestions: false,
|
||||
loading: false,
|
||||
searchQuery: '',
|
||||
suggestionTimeout: null,
|
||||
|
||||
// Save current filters to localStorage
|
||||
saveFilters() {
|
||||
const form = document.querySelector('form');
|
||||
const formData = new FormData(form);
|
||||
const filters = {};
|
||||
for (let [key, value] of formData.entries()) {
|
||||
if (value) filters[key] = value;
|
||||
}
|
||||
localStorage.setItem('rideFilters', JSON.stringify(filters));
|
||||
},
|
||||
|
||||
// Clear all filters
|
||||
clearFilters() {
|
||||
document.querySelectorAll('form select, form input').forEach(el => {
|
||||
el.value = '';
|
||||
});
|
||||
localStorage.removeItem('rideFilters');
|
||||
document.querySelector('form').dispatchEvent(new Event('change'));
|
||||
},
|
||||
|
||||
// Get search suggestions
|
||||
async getSearchSuggestions() {
|
||||
if (this.searchQuery.length < 2) {
|
||||
this.showSuggestions = false;
|
||||
return;
|
||||
}
|
||||
|
||||
const controller = new AbortController();
|
||||
const timeoutId = setTimeout(() => controller.abort(), 5000); // 5s timeout
|
||||
|
||||
try {
|
||||
const parkSlug = document.querySelector('input[name="park_slug"]')?.value;
|
||||
const url = `/rides/search-suggestions/?q=${encodeURIComponent(this.searchQuery)}${parkSlug ? '&park_slug=' + parkSlug : ''}`;
|
||||
|
||||
const response = await fetch(url, { signal: controller.signal });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
const html = await response.text();
|
||||
|
||||
// Ensure the response is for the current query
|
||||
if (this.searchQuery === document.getElementById('search').value) {
|
||||
document.getElementById('search-suggestions').innerHTML = html;
|
||||
this.showSuggestions = html.trim() ? true : false;
|
||||
}
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
console.warn('Search suggestion request timed out');
|
||||
} else {
|
||||
console.error('Error fetching suggestions:', error);
|
||||
// Show error state in UI
|
||||
document.getElementById('search-suggestions').innerHTML = `
|
||||
<div class="p-2 text-sm text-red-600 dark:text-red-400">
|
||||
Failed to load suggestions. Please try again.
|
||||
</div>`;
|
||||
this.showSuggestions = true;
|
||||
}
|
||||
} finally {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
},
|
||||
|
||||
// Handle input changes with debounce
|
||||
async handleInput() {
|
||||
clearTimeout(this.suggestionTimeout);
|
||||
this.suggestionTimeout = setTimeout(() => {
|
||||
this.getSearchSuggestions();
|
||||
}, 200);
|
||||
},
|
||||
|
||||
// Handle suggestion selection
|
||||
// Sync form with URL parameters
|
||||
syncFormWithUrl() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const form = document.querySelector('form');
|
||||
|
||||
// Clear existing values
|
||||
form.querySelectorAll('input, select').forEach(el => {
|
||||
if (el.type !== 'hidden') el.value = '';
|
||||
});
|
||||
|
||||
// Set values from URL
|
||||
urlParams.forEach((value, key) => {
|
||||
const input = form.querySelector(`[name="${key}"]`);
|
||||
if (input) input.value = value;
|
||||
});
|
||||
|
||||
// Trigger form update
|
||||
form.dispatchEvent(new Event('change'));
|
||||
},
|
||||
|
||||
// Cleanup resources
|
||||
cleanup() {
|
||||
clearTimeout(this.suggestionTimeout);
|
||||
this.showSuggestions = false;
|
||||
localStorage.removeItem('rideFilters');
|
||||
},
|
||||
|
||||
selectSuggestion(text) {
|
||||
this.searchQuery = text;
|
||||
this.showSuggestions = false;
|
||||
document.getElementById('search').value = text;
|
||||
|
||||
// Update URL with search parameter
|
||||
const url = new URL(window.location);
|
||||
url.searchParams.set('search', text);
|
||||
window.history.pushState({}, '', url);
|
||||
|
||||
document.querySelector('form').dispatchEvent(new Event('change'));
|
||||
},
|
||||
|
||||
// Handle keyboard navigation
|
||||
// Show error message
|
||||
showError(message) {
|
||||
const searchInput = document.getElementById('search');
|
||||
const errorDiv = document.createElement('div');
|
||||
errorDiv.className = 'text-red-600 text-sm mt-1';
|
||||
errorDiv.textContent = message;
|
||||
searchInput.parentNode.appendChild(errorDiv);
|
||||
setTimeout(() => errorDiv.remove(), 3000);
|
||||
},
|
||||
|
||||
// Handle keyboard navigation
|
||||
handleKeydown(e) {
|
||||
const suggestions = document.querySelectorAll('#search-suggestions button');
|
||||
if (!suggestions.length) return;
|
||||
|
||||
const currentIndex = Array.from(suggestions).findIndex(el => el === document.activeElement);
|
||||
|
||||
switch(e.key) {
|
||||
case 'ArrowDown':
|
||||
e.preventDefault();
|
||||
if (currentIndex < 0) {
|
||||
suggestions[0].focus();
|
||||
this.selectedIndex = 0;
|
||||
} else if (currentIndex < suggestions.length - 1) {
|
||||
suggestions[currentIndex + 1].focus();
|
||||
this.selectedIndex = currentIndex + 1;
|
||||
}
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
e.preventDefault();
|
||||
if (currentIndex > 0) {
|
||||
suggestions[currentIndex - 1].focus();
|
||||
this.selectedIndex = currentIndex - 1;
|
||||
} else {
|
||||
document.getElementById('search').focus();
|
||||
this.selectedIndex = -1;
|
||||
}
|
||||
break;
|
||||
case 'Escape':
|
||||
this.showSuggestions = false;
|
||||
this.selectedIndex = -1;
|
||||
document.getElementById('search').blur();
|
||||
break;
|
||||
case 'Enter':
|
||||
if (document.activeElement.tagName === 'BUTTON') {
|
||||
e.preventDefault();
|
||||
this.selectSuggestion(document.activeElement.dataset.text);
|
||||
}
|
||||
break;
|
||||
case 'Tab':
|
||||
this.showSuggestions = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}));
|
||||
});
|
||||
</script>
|
||||
|
||||
<!-- HTMX Loading Indicator Styles -->
|
||||
<style>
|
||||
.htmx-indicator {
|
||||
opacity: 0;
|
||||
transition: opacity 200ms ease-in;
|
||||
}
|
||||
.htmx-request .htmx-indicator {
|
||||
opacity: 1
|
||||
}
|
||||
|
||||
/* Enhanced Loading Indicator */
|
||||
.loading-indicator {
|
||||
position: fixed;
|
||||
bottom: 1rem;
|
||||
right: 1rem;
|
||||
z-index: 50;
|
||||
padding: 0.5rem 1rem;
|
||||
background: rgba(37, 99, 235, 0.95);
|
||||
border-radius: 0.5rem;
|
||||
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
color: white;
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.loading-indicator svg {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
animation: spin 1s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
from { transform: rotate(0deg); }
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
</style>
|
||||
|
||||
<script>
|
||||
// Initialize request timeout management
|
||||
const timeouts = new Map();
|
||||
|
||||
// Handle request start
|
||||
document.addEventListener('htmx:beforeRequest', function(evt) {
|
||||
const timestamp = document.querySelector('.loading-timestamp');
|
||||
if (timestamp) {
|
||||
timestamp.textContent = new Date().toLocaleTimeString();
|
||||
}
|
||||
|
||||
// Set timeout for request
|
||||
const timeoutId = setTimeout(() => {
|
||||
evt.detail.xhr.abort();
|
||||
showError('Request timed out. Please try again.');
|
||||
}, 10000); // 10s timeout
|
||||
|
||||
timeouts.set(evt.detail.xhr, timeoutId);
|
||||
});
|
||||
|
||||
// Handle request completion
|
||||
document.addEventListener('htmx:afterRequest', function(evt) {
|
||||
const timeoutId = timeouts.get(evt.detail.xhr);
|
||||
if (timeoutId) {
|
||||
clearTimeout(timeoutId);
|
||||
timeouts.delete(evt.detail.xhr);
|
||||
}
|
||||
|
||||
if (!evt.detail.successful) {
|
||||
showError('Failed to update results. Please try again.');
|
||||
}
|
||||
});
|
||||
|
||||
// Handle errors
|
||||
function showError(message) {
|
||||
const indicator = document.querySelector('.loading-indicator');
|
||||
if (indicator) {
|
||||
indicator.innerHTML = `
|
||||
<div class="flex items-center text-red-100">
|
||||
<i class="mr-2 fas fa-exclamation-circle"></i>
|
||||
<span>${message}</span>
|
||||
</div>`;
|
||||
setTimeout(() => {
|
||||
indicator.innerHTML = originalIndicatorContent;
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// Store original indicator content
|
||||
const originalIndicatorContent = document.querySelector('.loading-indicator')?.innerHTML;
|
||||
|
||||
// Reset loading state when navigating away
|
||||
window.addEventListener('beforeunload', () => {
|
||||
timeouts.forEach(timeoutId => clearTimeout(timeoutId));
|
||||
timeouts.clear();
|
||||
});
|
||||
</script>
|
||||
26
templates/rides/partials/search_suggestions.html
Normal file
26
templates/rides/partials/search_suggestions.html
Normal file
@@ -0,0 +1,26 @@
|
||||
{% if suggestions %}
|
||||
<div class="py-2">
|
||||
{% for suggestion in suggestions %}
|
||||
<button class="block w-full px-4 py-2 text-left text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-700"
|
||||
@click="selectSuggestion('{{ suggestion.text }}')"
|
||||
@keydown.enter="selectSuggestion('{{ suggestion.text }}')"
|
||||
@keydown.esc="showSuggestions = false"
|
||||
data-text="{{ suggestion.text }}"
|
||||
tabindex="0">
|
||||
<div class="flex items-center">
|
||||
{% if suggestion.type == 'park' %}
|
||||
<i class="w-6 mr-2 text-gray-400 fa fa-map-marker-alt"></i>
|
||||
{% elif suggestion.type == 'category' %}
|
||||
<i class="w-6 mr-2 text-gray-400 fa fa-ticket-alt"></i>
|
||||
{% else %}
|
||||
<i class="w-6 mr-2 text-gray-400 fa fa-search"></i>
|
||||
{% endif %}
|
||||
<span>{{ suggestion.text }}</span>
|
||||
{% if suggestion.subtext %}
|
||||
<span class="ml-2 text-sm text-gray-500 dark:text-gray-400">{{ suggestion.subtext }}</span>
|
||||
{% endif %}
|
||||
</div>
|
||||
</button>
|
||||
{% endfor %}
|
||||
</div>
|
||||
{% endif %}
|
||||
Reference in New Issue
Block a user