scrolling within modals using keys/buttons/swipe (needs help with infinite scrolling)

This commit is contained in:
zach
2026-03-06 13:53:15 -05:00
parent 7fd8a21d1c
commit ce56d08efe
4 changed files with 398 additions and 8 deletions

View File

@@ -531,3 +531,72 @@ $tiers: (
stroke: var(--bs-success-border-subtle); stroke: var(--bs-success-border-subtle);
color: var(--bs-success-border-subtle); color: var(--bs-success-border-subtle);
} }
/* Card Modal Navigation Styles */
.card-nav-prev,
.card-nav-next {
transition: all 0.2s ease-in-out;
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 36px;
padding: 0.375rem 0.5rem;
}
.card-nav-prev:hover:not(:disabled),
.card-nav-next:hover:not(:disabled) {
background-color: var(--bs-secondary);
border-color: var(--bs-secondary);
color: white;
transform: translateY(-1px);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.card-nav-prev:active:not(:disabled),
.card-nav-next:active:not(:disabled) {
transform: translateY(0);
}
.card-nav-prev:disabled,
.card-nav-next:disabled {
cursor: not-allowed;
}
/* Optional: Add keyboard indicator hint */
.modal-header {
position: relative;
}
/* Smooth fade in/out for disabled state */
.card-nav-prev,
.card-nav-next {
will-change: opacity;
}
/* Touch-friendly sizing on mobile */
@media (max-width: 768px) {
.card-nav-prev,
.card-nav-next {
min-width: 40px;
padding: 0.5rem;
}
}
/* Optional: Add a subtle animation when swiping */
@keyframes swipe-feedback {
0% {
transform: scale(1);
}
50% {
transform: scale(0.95);
}
100% {
transform: scale(1);
}
}
.card-nav-prev.swiping,
.card-nav-next.swiping {
animation: swipe-feedback 0.3s ease-out;
}

View File

@@ -17,6 +17,7 @@ import '/src/assets/css/main.scss';
<!-- End Google Tag Manager --> <!-- End Google Tag Manager -->
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="htmx-config" content='{"historyCacheSize": 50}'></meta>
<link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
<title>Rigid's App Thing</title> <title>Rigid's App Thing</title>
@@ -40,5 +41,6 @@ import '/src/assets/css/main.scss';
<script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/htmx.org@2.0.8/dist/htmx.min.js"></script>
<script src="../assets/js/main.js"></script> <script src="../assets/js/main.js"></script>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
</body> </body>
</html> </html>

View File

@@ -12,7 +12,6 @@ export const prerender = false;
const searchParams = Astro.url.searchParams; const searchParams = Astro.url.searchParams;
const cardId = Number(searchParams.get('cardId')) || 0; const cardId = Number(searchParams.get('cardId')) || 0;
// query the database for the card with the given productId and return the card data as json // query the database for the card with the given productId and return the card data as json
const card = await db.query.cards.findFirst({ const card = await db.query.cards.findFirst({
where: { cardId: Number(cardId) }, where: { cardId: Number(cardId) },
@@ -22,6 +21,16 @@ const card = await db.query.cards.findFirst({
} }
}); });
// Get the current card's position in the grid and find previous/next cards
// This assumes cards are displayed in a specific order in the DOM
const cardElements = typeof document !== 'undefined' ? document.querySelectorAll('[data-card-id]') : [];
let prevCardId = null;
let nextCardId = null;
// Since this is server-side, we can't access the DOM directly
// Instead, we'll pass the current cardId and let JavaScript handle navigation
// The JS will look for the next/prev cards in the grid based on the visible cards
function timeAgo(date: Date | null) { function timeAgo(date: Date | null) {
if (!date) return "Not applicable"; if (!date) return "Not applicable";
@@ -100,16 +109,27 @@ const ebaySearchUrl = (card: any) => {
}; };
--- ---
<div class="modal-dialog modal-dialog-centered modal-fullscreen-md-down modal-xl">
<div class="modal-dialog modal-dialog-centered modal-fullscreen-md-down modal-xl"> <div class="modal-dialog modal-dialog-centered modal-fullscreen-md-down modal-xl">
<div class="modal-content"> <div class="modal-content" data-card-id={card?.cardId}>
<div class="modal-header border-0"> <div class="modal-header border-0">
<div class="container-fluid row align-items-center"> <div class="container-fluid row align-items-center">
<div class="h4 card-title pe-2 col-sm-12 col-md-auto mb-sm-1">{card?.productName}</div> <div class="h4 card-title pe-2 col-sm-12 col-md-auto mb-sm-1">{card?.productName}</div>
<div class="text-secondary col-auto">{card?.number}</div> <div class="text-secondary col-auto">{card?.number}</div>
<div class="text-secondary col-auto">{card?.variant}</div> <div class="text-secondary col-auto">{card?.variant}</div>
</div> </div>
<button type="button" class="btn-close" aria-label="Close" data-bs-dismiss="modal"></button> <div class="d-flex gap-2 align-items-center">
<button type="button" class="btn btn-sm btn-outline-secondary card-nav-prev" title="Previous card (← or swipe right)" aria-label="Previous card">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="15 18 9 12 15 6"></polyline>
</svg>
</button>
<button type="button" class="btn btn-sm btn-outline-secondary card-nav-next" title="Next card (→ or swipe left)" aria-label="Next card">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<polyline points="9 18 15 12 9 6"></polyline>
</svg>
</button>
<button type="button" class="btn-close" aria-label="Close" data-bs-dismiss="modal"></button>
</div>
</div> </div>
<div class="modal-body pt-0"> <div class="modal-body pt-0">
<div class="container-fluid"> <div class="container-fluid">
@@ -197,8 +217,6 @@ const ebaySearchUrl = (card: any) => {
</div> </div>
</div> </div>
</div> </div>
</div>
</div>
<script is:inline> <script is:inline>
async function copyImage(img) { async function copyImage(img) {
@@ -219,4 +237,306 @@ const ebaySearchUrl = (card: any) => {
console.log("Copied image via canvas."); console.log("Copied image via canvas.");
}); });
} }
// ===== Card Navigation System =====
// Only declare class if it hasn't been declared yet (prevents HTMX reload errors)
if (typeof window.CardNavigator === 'undefined') {
window.CardNavigator = class CardNavigator {
constructor() {
this.touchStartX = 0;
this.touchEndX = 0;
this.swipeThreshold = 50; // minimum distance in pixels for a swipe
this.loadingMoreCards = false;
this.init();
}
init() {
this.setupEventListeners();
this.updateNavigationButtons();
this.setupScrollObserver();
}
setupScrollObserver() {
// Listen for when new cards are added to the grid
const observer = new MutationObserver(() => {
this.loadingMoreCards = false;
});
const cardGrid = document.getElementById('cardGrid');
if (cardGrid) {
observer.observe(cardGrid, {
childList: true,
subtree: false
});
}
}
setupEventListeners() {
const modal = document.getElementById('cardModal');
if (!modal) return;
// Keyboard navigation
document.addEventListener('keydown', (e) => this.handleKeydown(e));
// Touch/Swipe navigation
modal.addEventListener('touchstart', (e) => this.handleTouchStart(e), false);
modal.addEventListener('touchend', (e) => this.handleTouchEnd(e), false);
// Button navigation
const prevBtn = document.querySelector('.card-nav-prev');
const nextBtn = document.querySelector('.card-nav-next');
if (prevBtn) prevBtn.addEventListener('click', () => this.navigatePrev());
if (nextBtn) nextBtn.addEventListener('click', () => this.navigateNext());
}
handleKeydown(e) {
// Only navigate if the modal is visible
const modal = document.getElementById('cardModal');
if (!modal || !modal.classList.contains('show')) return;
if (e.key === 'ArrowLeft') {
e.preventDefault();
this.navigatePrev();
} else if (e.key === 'ArrowRight') {
e.preventDefault();
this.navigateNext();
}
}
handleTouchStart(e) {
this.touchStartX = e.changedTouches[0].screenX;
}
handleTouchEnd(e) {
this.touchEndX = e.changedTouches[0].screenX;
this.handleSwipe();
}
handleSwipe() {
const diff = this.touchStartX - this.touchEndX;
// Swipe left = show next card
if (diff > this.swipeThreshold) {
this.navigateNext();
}
// Swipe right = show previous card
else if (diff < -this.swipeThreshold) {
this.navigatePrev();
}
}
getVisibleCards() {
// Get all card triggers from the current grid
return Array.from(document.querySelectorAll('[data-card-id]'));
}
getCurrentCardElement() {
const modal = document.getElementById('cardModal');
if (!modal) return null;
const currentCardId = modal.querySelector('.modal-content')?.getAttribute('data-card-id');
return currentCardId ? document.querySelector(`[data-card-id="${currentCardId}"]`) : null;
}
navigatePrev() {
const cards = this.getVisibleCards();
const currentCard = this.getCurrentCardElement();
if (!cards.length || !currentCard) return;
const currentIndex = cards.indexOf(currentCard);
if (currentIndex <= 0) return; // Already at the first card
const prevCard = cards[currentIndex - 1];
this.loadCard(prevCard);
}
navigateNext() {
const cards = this.getVisibleCards();
const currentCard = this.getCurrentCardElement();
if (!cards.length || !currentCard) return;
const currentIndex = cards.indexOf(currentCard);
if (currentIndex >= cards.length - 1) {
// At the last card, try to load more cards via infinite scroll
this.triggerInfiniteScroll();
return;
}
const nextCard = cards[currentIndex + 1];
this.loadCard(nextCard);
}
triggerInfiniteScroll() {
if (this.loadingMoreCards) return; // Already loading
this.loadingMoreCards = true;
// Find the infinite scroll trigger element (the "Loading..." div with hx-trigger="revealed")
const scrollTrigger = document.querySelector('[hx-trigger="revealed"]');
if (scrollTrigger) {
// Trigger HTMX to load more cards
if (typeof htmx !== 'undefined') {
htmx.trigger(scrollTrigger, 'revealed');
} else {
// Fallback: manually call the endpoint
const endpoint = scrollTrigger.getAttribute('hx-post') || scrollTrigger.getAttribute('hx-get');
if (endpoint) {
const formData = new FormData(document.getElementById('searchform'));
const currentCards = this.getVisibleCards();
const start = (currentCards.length - 1) * 20; // Approximate
formData.append('start', start.toString());
fetch(endpoint, {
method: 'POST',
body: formData
})
.then(r => r.text())
.then(html => {
const grid = document.getElementById('cardGrid');
if (grid) {
grid.insertAdjacentHTML('beforeend', html);
this.waitForNewCards();
}
});
}
}
// Wait for new cards to be added and then navigate
this.waitForNewCards();
} else {
this.loadingMoreCards = false;
}
}
waitForNewCards() {
// Wait up to 3 seconds for new cards to load
let attempts = 0;
const checkInterval = setInterval(() => {
attempts++;
const cards = this.getVisibleCards();
const currentCardId = document.querySelector('#cardModal .modal-content')?.getAttribute('data-card-id');
const currentIndex = cards.findIndex(c => c.getAttribute('data-card-id') === currentCardId);
// If we have more cards than before, navigate to the next one
if (currentIndex >= 0 && currentIndex < cards.length - 1) {
clearInterval(checkInterval);
const nextCard = cards[currentIndex + 1];
this.loadingMoreCards = false;
this.loadCard(nextCard);
} else if (attempts > 30) { // 30 * 100ms = 3 seconds
clearInterval(checkInterval);
this.loadingMoreCards = false;
this.updateNavigationButtons();
}
}, 100);
}
loadCard(cardElement) {
const hxGet = cardElement.getAttribute('hx-get');
if (!hxGet) return;
// Check if HTMX is available, if not use fetch
if (typeof htmx !== 'undefined') {
// Use HTMX to load the card
htmx.ajax('GET', hxGet, {
target: '#cardModal',
swap: 'innerHTML',
onLoad: () => {
this.updateNavigationButtons();
// Trigger any analytics event if needed
const cardTitle = cardElement.querySelector('#cardImage')?.getAttribute('alt') || 'Unknown Card';
if (typeof dataLayer !== 'undefined') {
dataLayer.push({
'event': 'virtualPageview',
'pageUrl': hxGet,
'pageTitle': cardTitle,
'previousUrl': '/pokemon'
});
}
}
});
} else {
// Fallback to native fetch if HTMX not available
fetch(hxGet)
.then(response => response.text())
.then(html => {
const modalContent = document.querySelector('#cardModal .modal-dialog');
if (modalContent) {
modalContent.innerHTML = html;
this.updateNavigationButtons();
// Trigger any analytics event if needed
const cardTitle = cardElement.querySelector('#cardImage')?.getAttribute('alt') || 'Unknown Card';
if (typeof dataLayer !== 'undefined') {
dataLayer.push({
'event': 'virtualPageview',
'pageUrl': hxGet,
'pageTitle': cardTitle,
'previousUrl': '/pokemon'
});
}
}
})
.catch(error => console.error('Error loading card:', error));
}
}
updateNavigationButtons() {
const cards = this.getVisibleCards();
const currentCard = this.getCurrentCardElement();
const currentIndex = cards.indexOf(currentCard);
const prevBtn = document.querySelector('.card-nav-prev');
const nextBtn = document.querySelector('.card-nav-next');
if (prevBtn) {
prevBtn.disabled = currentIndex <= 0;
prevBtn.style.opacity = currentIndex <= 0 ? '0.5' : '1';
}
if (nextBtn) {
nextBtn.disabled = currentIndex >= cards.length - 1;
nextBtn.style.opacity = currentIndex >= cards.length - 1 ? '0.5' : '1';
}
}
}
} // End of: if (typeof window.CardNavigator === 'undefined')
// Initialize the card navigator when the modal is shown (only setup once)
if (!window.cardNavigatorInitialized) {
window.cardNavigatorInitialized = true;
const modalElement = document.getElementById('cardModal');
if (modalElement) {
modalElement.addEventListener('shown.bs.modal', () => {
if (!window.cardNavigator) {
window.cardNavigator = new window.CardNavigator();
} else {
window.cardNavigator.updateNavigationButtons();
}
});
}
// Also initialize on first load in case the modal is already visible
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
// Wait a bit for HTMX to load
setTimeout(() => {
if (!window.cardNavigator) {
window.cardNavigator = new window.CardNavigator();
}
}, 100);
});
} else {
// Wait a bit for HTMX to load if already loaded
setTimeout(() => {
if (!window.cardNavigator) {
window.cardNavigator = new window.CardNavigator();
}
}, 100);
}
}
</script> </script>

View File

@@ -1,7 +1,6 @@
--- ---
import { client } from '../../db/typesense'; import { client } from '../../db/typesense';
import RarityIcon from '../../components/RarityIcon.astro'; import RarityIcon from '../../components/RarityIcon.astro';
export const prerender = false; export const prerender = false;
import * as util from 'util'; import * as util from 'util';