Skip to content

Commit

Permalink
fix: replace DOMSubtreeModified with MutationObserver & add delay to …
Browse files Browse the repository at this point in the history
…dynamic url widget mutation test
  • Loading branch information
ChinHairSaintClair committed Sep 6, 2024
1 parent bbe5ded commit 46488f8
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
15 changes: 14 additions & 1 deletion webapp/src/js/enketo/widgets/dynamic-url.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,20 @@ class DynamicUrlWidget extends Widget {
const urlElement = currentElement.find('.url');
const setHref = () => currentElement.attr('href', urlElement.text());
setHref();
urlElement.on('DOMSubtreeModified', setHref);

const observer = new MutationObserver(mutationList => {
mutationList.forEach(mutation => {
if (mutation.type === 'childList' || mutation.type === 'characterData') {
setHref();
}
});
});

observer.observe(urlElement[0], {
childList: true, // Monitor direct child nodes
characterData: true, // Monitor text content changes
subtree: true // Monitor all descendants
});
}
}

Expand Down
7 changes: 5 additions & 2 deletions webapp/tests/karma/js/enketo/widgets/dynamic-url.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,17 @@ describe('Enketo: Dynamic URL Widget', () => {
expect($(DynamicUrlWidget.selector).attr('href')).to.equal('http://google.com?q=');
});

it('should update the href for the dynamically generated URL when the dynamic value changes', () => {
it('should update the href for the dynamically generated URL when the dynamic value changes', (done) => {
buildHtml('helloWorld');

new DynamicUrlWidget($(DynamicUrlWidget.selector)[0]);
const dynamic = 'worldHello';
$('.url span').text(dynamic);

expect($(DynamicUrlWidget.selector).attr('href')).to.equal(`http://google.com?q=${dynamic}`);
setTimeout(() => {
expect($(DynamicUrlWidget.selector).attr('href')).to.equal(`http://google.com?q=${dynamic}`);
done();
}, 0);
});

it('should not modify elements besides dynamic-url links', () => {
Expand Down

0 comments on commit 46488f8

Please sign in to comment.