Skip to content

Commit 4183dac

Browse files
committed
Implement waitForElementToBeRemoved method
1 parent bf8d7dd commit 4183dac

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

src/wait-for-element-to-be-removed.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import {getDocument, getSetImmediate, newMutationObserver} from './helpers'
2+
3+
function waitForElementToBeRemoved(
4+
callback,
5+
{
6+
container = getDocument(),
7+
timeout = 4500,
8+
mutationObserverOptions = {
9+
subtree: true,
10+
childList: true,
11+
attributes: true,
12+
characterData: true,
13+
},
14+
} = {},
15+
) {
16+
return new Promise((resolve, reject) => {
17+
if (typeof callback !== 'function') {
18+
reject(
19+
'waitForElementToBeRemoved requires a callback as the first parameter',
20+
)
21+
}
22+
const timer = setTimeout(onTimeout, timeout)
23+
const observer = newMutationObserver(onMutation)
24+
observer.observe(container, mutationObserverOptions)
25+
function onDone(error, result) {
26+
const setImmediate = getSetImmediate()
27+
clearTimeout(timer)
28+
setImmediate(() => observer.disconnect())
29+
if (error) {
30+
reject(error)
31+
} else {
32+
resolve(result)
33+
}
34+
}
35+
function onMutation() {
36+
try {
37+
const result = callback()
38+
if (!result) {
39+
onDone(null, true)
40+
}
41+
// If `callback` returns truthy value, wait for the next mutation or timeout.
42+
} catch (error) {
43+
onDone(null, true)
44+
}
45+
}
46+
function onTimeout() {
47+
onDone(new Error('Timed out in waitForElementToBeRemoved.'), null)
48+
}
49+
onMutation()
50+
})
51+
}
52+
53+
export {waitForElementToBeRemoved}

0 commit comments

Comments
 (0)