Enhance initAnatomyFragment to prevent double initialization and improve HTMX swap handling

This commit is contained in:
Ross
2025-11-10 12:17:53 +00:00
parent ed88f794f8
commit 0acc57302f
+16 -3
View File
@@ -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);