diff --git a/assets/controllers/elements/tree_controller.js b/assets/controllers/elements/tree_controller.js index d2f21a8e..c9d8b213 100644 --- a/assets/controllers/elements/tree_controller.js +++ b/assets/controllers/elements/tree_controller.js @@ -98,6 +98,7 @@ export default class extends Controller { const node = event.detail.node; if (node.href) { window.Turbo.visit(node.href, {action: "advance"}); + this._registerURLWatcher(node); } }, //onNodeContextmenu: contextmenu_handler, @@ -108,12 +109,40 @@ export default class extends Controller { const treeView = event.detail.treeView; treeView.revealNode(treeView.getSelected()); + //Add the url watcher to all selected nodes + for (const node of treeView.getSelected()) { + this._registerURLWatcher(node); + } + //Add contextmenu event listener to the tree, which allows us to open the links in a new tab with a right click treeView.getTreeElement().addEventListener("contextmenu", this._onContextMenu.bind(this)); }); } + _registerURLWatcher(node) + { + //Register a watcher for a location change, which will unselect the node, if the location changes + const desired_url = node.href; + + //Ensure that the node is unselected, if the location changes + const unselectNode = () => { + //Parse url so we can properly compare them + const desired = new URL(node.href, window.location.origin); + + //We only compare the pathname, because the hash and parameters should not matter + if(window.location.pathname !== desired.pathname) { + node.setSelected(false); + + //Unregister the watcher + document.removeEventListener('turbo:visit', unselectNode); + } + }; + + //Register the watcher via hotwire turbo + document.addEventListener('turbo:visit', unselectNode); + } + _onContextMenu(event) { //Find the node that was clicked and open link in new tab