From 08c0300120467ab1539a0431b7157e57ded9c050 Mon Sep 17 00:00:00 2001 From: Sean Doyle Date: Mon, 21 Nov 2022 15:52:08 -0500 Subject: [PATCH] [BACKPORT]: Promote lazily-loaded Turbo Frame navigation The changed merged into `@hotwired/turbo` as part of [hotwired/turbo#790][] resolve an important issue around how `` elements treat `[data-turbo-action]` attributes. With #790 merged into `main`, it is not yet part of an official `@hotwired/turbo` or `@hotwired/turbo-rails` release, and is only available through a manual backport. Once `@hotwired/turbo@7.2.5` is released, this commit can be reverted or deleted from the history. [hotwired/turbo#790]: https://github.com/hotwired/turbo/pull/790 --- app/javascript/application.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/app/javascript/application.js b/app/javascript/application.js index a31a955..1a9af51 100644 --- a/app/javascript/application.js +++ b/app/javascript/application.js @@ -3,3 +3,31 @@ import "@hotwired/turbo-rails" import "controllers" import "trix" import "@rails/actiontext" + +// Delete me when https://github.com/hotwired/turbo/pull/790 is released +// and we've upgraded to Turbo 7.2.5 +// +// START BACKPORT +for (const { delegate } of document.querySelectorAll("turbo-frame")) { + backportLazyLoadedFramePromotion(delegate) +} + +new MutationObserver((mutationRecords) => { + for (const { addedNodes } of mutationRecords) { + for (const addedNode of addedNodes) { + if (addedNode.localName == "turbo-frame") { + backportLazyLoadedFramePromotion(addedNode.delegate) + } + } + } +}).observe(document.documentElement, { subtree: true, childList: true }) + +function backportLazyLoadedFramePromotion(frameController) { + function elementAppearedInViewport(element) { + this.proposeVisitIfNavigatedWithAction(element, element) + this.loadSourceURL() + } + + frameController.elementAppearedInViewport = elementAppearedInViewport.bind(frameController) +} +// END BACKPORT