Skip to content

Commit

Permalink
fix(shadow-wrapper): do not call success callback on the second `css-…
Browse files Browse the repository at this point in the history
…src` attribute change (#583)
  • Loading branch information
nd0ut authored Dec 29, 2023
1 parent 8e0a4de commit eb9618a
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 13 deletions.
30 changes: 17 additions & 13 deletions utils/waitForAttribute.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,27 @@
* }} options
*/
export const waitForAttribute = ({ element, attribute, onSuccess, onTimeout, timeout = 300 }) => {
const currentAttrValue = element.getAttribute(attribute);
if (currentAttrValue !== null) {
onSuccess(currentAttrValue);
return;
}

const observer = new MutationObserver((mutations) => {
const mutation = mutations[mutations.length - 1];
handleMutation(mutation);
});

observer.observe(element, {
attributes: true,
attributeFilter: [attribute],
});

const timeoutId = setTimeout(() => {
observer.disconnect();
onTimeout();
}, timeout);

/** @param {MutationRecord} mutation */
const handleMutation = (mutation) => {
const attrValue = element.getAttribute(attribute);
Expand All @@ -23,17 +40,4 @@ export const waitForAttribute = ({ element, attribute, onSuccess, onTimeout, tim
onSuccess(attrValue);
}
};
const currentAttrValue = element.getAttribute(attribute);
if (currentAttrValue !== null) {
clearTimeout(timeoutId);
onSuccess(currentAttrValue);
}
const observer = new MutationObserver((mutations) => {
const mutation = mutations[mutations.length - 1];
handleMutation(mutation);
});
observer.observe(element, {
attributes: true,
attributeFilter: [attribute],
});
};
20 changes: 20 additions & 0 deletions utils/waitForAttribute.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -55,4 +55,24 @@ describe('waitForAttribute', () => {
expect(onSuccess.getCall(0).args[0]).to.equal('test');
expect(onTimeout.called).to.be.false;
});

it('should not call onSuccess on the second attribute change', async () => {
const element = document.createElement('div');
element.setAttribute(TEST_ATTRIBUTE, 'test');
const onSuccess = spy();
const onTimeout = spy();
waitForAttribute({
element,
attribute: TEST_ATTRIBUTE,
onSuccess,
onTimeout,
timeout: 10,
});
await delay(100);
element.setAttribute(TEST_ATTRIBUTE, 'tes2');
await delay(100);
expect(onSuccess.calledOnce).to.be.true;
expect(onSuccess.getCall(0).args[0]).to.equal('test');
expect(onTimeout.called).to.be.false;
});
});

0 comments on commit eb9618a

Please sign in to comment.