Skip to content

Commit f35d4ca

Browse files
Eagerly update tab UI
This moves the manipulation of the tabs to the click action (via a standalone function) rather than in the turbo:frame-render action.
1 parent 2001287 commit f35d4ca

File tree

1 file changed

+22
-12
lines changed

1 file changed

+22
-12
lines changed

app/javascript/loading_spinner.js

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,19 @@
1+
// Update the tab UI to reflect the newly-requested state. This function is called
2+
// by a click event handler in the tab UI. It follows a two-step process:
3+
function swapTabs(new_target) {
4+
// 1. Reset all tabs to base condition
5+
document.querySelectorAll('.tab-link').forEach((tab) => {
6+
tab.classList.remove('active');
7+
tab.removeAttribute('aria-current');
8+
});
9+
// 2. Add "active" class and aria-current attribute to the newly-active tab link
10+
const currentTabLink = document.querySelector(`.tab-link[href*="tab=${new_target}"]`);
11+
if (currentTabLink) {
12+
currentTabLink.classList.add('active');
13+
currentTabLink.setAttribute('aria-current', 'page');
14+
}
15+
}
16+
117
// Loading spinner behavior for pagination (Turbo Frame updates)
218
document.addEventListener('turbo:frame-render', function(event) {
319
if (window.pendingFocusAction === 'pagination') {
@@ -23,18 +39,6 @@ document.addEventListener('turbo:frame-render', function(event) {
2339
// console.log(`Updated tab input value to: ${queryParam}`);
2440
}
2541

26-
// update tab links to reflect new state. This is a two-step process:
27-
// 1. Reset all tabs to base condition
28-
document.querySelectorAll('.tab-link').forEach((tab) => {
29-
tab.classList.remove('active');
30-
tab.removeAttribute('aria-current');
31-
});
32-
// 2. Add "active" class and aria-current attribute to the newly-active tab link
33-
const currentTabLink = document.querySelector(`.tab-link[href*="tab=${queryParam}"]`);
34-
if (currentTabLink) {
35-
currentTabLink.classList.add('active');
36-
currentTabLink.setAttribute('aria-current', 'page');
37-
}
3842
// Remove the spinner now that things are ready
3943
document.getElementById('search-results').classList.remove('spinner');
4044

@@ -55,11 +59,17 @@ document.addEventListener('click', function(event) {
5559

5660
// Handle tab clicks
5761
if (clickedElement.closest('.tab-navigation')) {
62+
const clickedParams = new URLSearchParams(clickedElement.search);
63+
const newTab = clickedParams.get('tab');
64+
5865
// Throw the spinner on the search results immediately
5966
document.getElementById('search-results').classList.add('spinner');
6067

6168
// Position the window at the top of the results
6269
window.scrollTo({ top: 0, behavior: 'smooth' });
70+
71+
swapTabs(newTab);
72+
6373
window.pendingFocusAction = 'tab';
6474
}
6575
});

0 commit comments

Comments
 (0)