From 111fd4cda856471fea0b41d90fc7ab161810a6db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Simon=20Andr=C3=A9?= Date: Sat, 22 Feb 2025 01:18:37 +0100 Subject: [PATCH] fix: lazy load Stimulus controllers with Turbo --- src/StimulusBundle/assets/dist/loader.js | 21 +++++++---------- src/StimulusBundle/assets/src/loader.ts | 29 +++++++++++------------- 2 files changed, 21 insertions(+), 29 deletions(-) diff --git a/src/StimulusBundle/assets/dist/loader.js b/src/StimulusBundle/assets/dist/loader.js index 3f70fed3f99..b2c49cfa2b7 100644 --- a/src/StimulusBundle/assets/dist/loader.js +++ b/src/StimulusBundle/assets/dist/loader.js @@ -53,22 +53,17 @@ class StimulusLazyControllerHandler { return; } new MutationObserver((mutationsList) => { - for (const mutation of mutationsList) { - switch (mutation.type) { - case 'childList': { - for (const node of mutation.addedNodes) { - if (node instanceof Element) { - extractControllerNamesFrom(node).forEach((controllerName) => { - this.loadLazyController(controllerName); - }); - } + for (const { attributeName, target, type } of mutationsList) { + switch (type) { + case 'attributes': { + if (attributeName === controllerAttribute && + target.getAttribute(controllerAttribute)) { + extractControllerNamesFrom(target).forEach((controllerName) => this.loadLazyController(controllerName)); } break; } - case 'attributes': { - if (mutation.attributeName === controllerAttribute) { - extractControllerNamesFrom(mutation.target).forEach((controllerName) => this.loadLazyController(controllerName)); - } + case 'childList': { + this.lazyLoadExistingControllers(target); } } } diff --git a/src/StimulusBundle/assets/src/loader.ts b/src/StimulusBundle/assets/src/loader.ts index 393ded69f19..178214a6aad 100644 --- a/src/StimulusBundle/assets/src/loader.ts +++ b/src/StimulusBundle/assets/src/loader.ts @@ -99,26 +99,23 @@ class StimulusLazyControllerHandler { return; } new MutationObserver((mutationsList) => { - for (const mutation of mutationsList) { - switch (mutation.type) { - case 'childList': { - // @ts-ignore - for (const node of mutation.addedNodes) { - if (node instanceof Element) { - extractControllerNamesFrom(node).forEach((controllerName) => { - this.loadLazyController(controllerName); - }); - } - } - break; - } - + for (const { attributeName, target, type } of mutationsList) { + switch (type) { case 'attributes': { - if (mutation.attributeName === controllerAttribute) { - extractControllerNamesFrom(mutation.target as Element).forEach((controllerName) => + if ( + attributeName === controllerAttribute && + (target as Element).getAttribute(controllerAttribute) + ) { + extractControllerNamesFrom(target as Element).forEach((controllerName) => this.loadLazyController(controllerName) ); } + + break; + } + + case 'childList': { + this.lazyLoadExistingControllers(target as Element); } } }