I’m using data-turbo-action = "advance" in an app with a sidebar → detail layout, so that the URL updates to something real as users traverse objects. In my sidebar, I’m doing various things that I’d like to persist—like adding a class to selected rows and writing data attributes.
I’ve marked the parent sidebar element as data-turbo-permanent, but the entire page gets torn down and repainted with every click. New data loads into the detail frame (which is good), but the ‘dirty’ state of the sidebar is lost. What am I missing? Am I misunderstanding what data-turbo-permanent is for?
FYI, to persist the element for future loads, you could do something like:
// data-turbo-persist
// copy elements from current document to new before rendering
function persistElements(newDocument) {
const isPreview = document.documentElement.hasAttribute('data-turbo-permanent');
if (isPreview) return;
const persistElements = document.querySelectorAll('[id][data-turbo-permanent]');
persistElements.forEach((persistElement) => {
const { id } = persistElement;
const newPersistElement = newDocument.querySelector(`#${id}[data-turbo-permanent]`);
if (newPersistElement) {
newPersistElement.outerHTML = persistElement.outerHTML;
}
});
}
or use a different attribute (e.g. data-turbo-persist):
// data-turbo-persist
// copy elements from current document to new before rendering
function persistElements(newDocument) {
const isPreview = document.documentElement.hasAttribute('data-turbo-preview');
if (isPreview) return;
const persistElements = document.querySelectorAll('[id][data-turbo-persist]');
persistElements.forEach((persistElement) => {
const { id } = persistElement;
const newPersistElement = newDocument.querySelector(`#${id}[data-turbo-persist]`);
if (newPersistElement) {
newPersistElement.outerHTML = persistElement.outerHTML;
}
});
}
It might be worth mentioning that data-turbo-permanentnow works with both application and restoration visits (ie, both Back/Forward button and clicking links/submitting forms).