From 0acc57302f3e79d19499c1ccdf97e88d7f999a00 Mon Sep 17 00:00:00 2001 From: Ross Date: Mon, 10 Nov 2025 12:17:53 +0000 Subject: [PATCH] Enhance initAnatomyFragment to prevent double initialization and improve HTMX swap handling --- anatomy/static/js/anatomy.js | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/anatomy/static/js/anatomy.js b/anatomy/static/js/anatomy.js index af991c2c..056cb021 100644 --- a/anatomy/static/js/anatomy.js +++ b/anatomy/static/js/anatomy.js @@ -343,14 +343,17 @@ function loadJsonToolStateOnCurrentImage(element, json) { // Called by HTMX after a fragment swap; initializes any dicom-image-legacy viewers window.initAnatomyFragment = function(fragmentRoot) { + console.log("initAnatomyFragment", fragmentRoot); try { - // If a fragment root is an element (hx-on passes `this`), search within it. - const root = fragmentRoot || document; - const imgs = (root.querySelectorAll) ? root.querySelectorAll('.dicom-image-legacy') : []; + const root = fragmentRoot && fragmentRoot.nodeType ? fragmentRoot : (fragmentRoot && fragmentRoot.detail && fragmentRoot.detail.target) ? fragmentRoot.detail.target : document; + const imgs = (root && root.querySelectorAll) ? root.querySelectorAll('.dicom-image-legacy') : []; imgs.forEach((el) => { try { + // Avoid double initialization + if (el.dataset && (el.dataset.dicomInitialised === '1' || el.dataset.dicomInitialised === 'true')) return; if (typeof window.setUpDicomLegacy === 'function') { window.setUpDicomLegacy(el); + if (el.dataset) el.dataset.dicomInitialised = '1'; } } catch (err) { console.warn('initAnatomyFragment: setUpDicomLegacy failed for element', el, err); @@ -361,6 +364,16 @@ window.initAnatomyFragment = function(fragmentRoot) { } } +// Global fallback: listen for HTMX swaps and initialise any viewers inside +document.addEventListener('htmx:afterSwap', function (e) { + try { + const root = e && e.target ? e.target : (e && e.detail && e.detail.target ? e.detail.target : document); + if (window.initAnatomyFragment) window.initAnatomyFragment(root); + } catch (err) { + console.warn('htmx afterSwap listener error', err); + } +}); + async function setUpDicomLegacy(element) { console.log("setUpDicom (original)", element);