Do not use jQuery for TabRemember Helper.

This commit is contained in:
Jan Böhmer 2022-07-29 23:26:30 +02:00
parent 47130846a2
commit 9519150fb9

View file

@ -1,5 +1,7 @@
"use strict"; "use strict";
import {Tab} from "bootstrap";
/** /**
* This listener keeps track of which tab is currently selected (using hash and localstorage) and will try to open * This listener keeps track of which tab is currently selected (using hash and localstorage) and will try to open
* that tab on reload. That means that if the user changes something, he does not have to switch back to the tab * that tab on reload. That means that if the user changes something, he does not have to switch back to the tab
@ -7,42 +9,48 @@
*/ */
class TabRememberHelper { class TabRememberHelper {
constructor() { constructor() {
document.addEventListener("turbo:load", this.onLoad); document.addEventListener("turbo:load", this.onLoad.bind(this));
} }
onLoad(event) { onLoad(event) {
//Determine which tab should be shown (use hash if specified, otherwise use localstorage) //Determine which tab should be shown (use hash if specified, otherwise use localstorage)
let $activeTab = null; let activeTab = null;
if (location.hash) { if (location.hash) {
$activeTab = $('a[href=\'' + location.hash + '\']'); activeTab = document.querySelector('[href=\'' + location.hash + '\']');
} else if (localStorage.getItem('activeTab')) { } else if (localStorage.getItem('activeTab')) {
$activeTab = $('a[href="' + localStorage.getItem('activeTab') + '"]'); activeTab = document.querySelector('[href="' + localStorage.getItem('activeTab') + '"]');
} }
if ($activeTab) { if (activeTab) {
//Findout if the tab has any parent tab we have to show before
var parents = $($activeTab).parents('.tab-pane');
parents.each(function (n) {
$('a[href="#' + $(this).attr('id') + '"]').tab('show');
});
//Finally show the active tab itself
$activeTab.tab('show');
}
$('body').on('click', 'a[data-bs-toggle=\'tab\']', function (e) { let parent = activeTab.parentElement.closest('.tab-pane');
e.preventDefault()
var tab_name = this.getAttribute('href') //Iterate over each parent tab and show it
if (history.replaceState) { while(parent) {
history.replaceState(null, null, tab_name) Tab.getOrCreateInstance(parent).show();
} else {
location.hash = tab_name parent = parent.parentElement.closest('.tab-pane');
} }
localStorage.setItem('activeTab', tab_name)
$(this).tab('show'); //Finally show the active tab itself
return false; Tab.getOrCreateInstance(activeTab).show();
}); }
//Register listener for tab change
document.addEventListener('shown.bs.tab', this.onTabChange.bind(this));
}
onTabChange(event) {
const tab = event.target;
let tab_name = tab.getAttribute('href')
if (history.replaceState) {
history.replaceState(null, null, tab_name)
} else {
location.hash = tab_name
}
localStorage.setItem('activeTab', tab_name)
} }
} }