From 823efaf142c99fd4af39bae745842db444994aa4 Mon Sep 17 00:00:00 2001 From: David Hein <44842054+MasterZydra@users.noreply.github.com> Date: Wed, 12 Jun 2024 10:49:14 +0200 Subject: [PATCH] Add attribute `component:navigate` --- js/wire-extender.js | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) diff --git a/js/wire-extender.js b/js/wire-extender.js index 2526489..3f4f3f6 100644 --- a/js/wire-extender.js +++ b/js/wire-extender.js @@ -111,3 +111,49 @@ document.addEventListener('DOMContentLoaded', function() { renderComponents(components); }); + +// Attribute "component:navigate" +document.addEventListener('livewire:initialized', (e) => { + // If a "component:navigate" anker is clicked, load the given component + const componentNavigateClick = (event) => { + event.preventDefault(); + + let component = event.target.getAttribute('data-component'); + let params = event.target.getAttribute('data-params'); + + let livewireElem = event.target.closest("livewire"); + livewireElem.setAttribute('data-component', component); + livewireElem.setAttribute('data-params', params ?? ''); + + renderComponents([{name: component, params: params}]); + }; + + // Register click event for all elements with attribute "component:navigate" + const componentNavigateElementUpdated = ({el}) => { + if (el == undefined) { + document.querySelectorAll('[component\\:navigate]').forEach( + (elem) => elem.addEventListener('click', componentNavigateClick) + ); + return; + } + + if (el.hasAttribute('component:navigate')) { + el.addEventListener('click', componentNavigateClick); + return; + } + }; + + // Trigger event for every livewire update cycle + window.Livewire.hook('morph.updated', componentNavigateElementUpdated); + + // Use observer to detect if the component has been replaced + const componentNavigateObserver = new MutationObserver( () => { + componentNavigateElementUpdated({ undefined }); + }); + document.querySelectorAll('livewire').forEach((elem) => { + componentNavigateObserver.observe(elem, {attributes: false, childList: true, subtree: true}); + }); + + // Initial call to register click events + componentNavigateElementUpdated({ undefined }); +});