Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle popup right after first popup detected (#326) #327

Merged
merged 15 commits into from
Jan 25, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 25 additions & 23 deletions lib/web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -233,30 +233,32 @@ export default class AutoConsent {
return cmp
}

detectPopups(cmps: AutoCMP[], onFirstPopupAppears: (cmp: AutoCMP) => unknown): Promise<AutoCMP[]> {
return new Promise(resolve => {
const foundCmps: AutoCMP[] = []
let completed = 0

for (let i = 0, l = cmps.length; i < l; i++) {
this.detectPopup(cmps[i])
.then(cmp => {
foundCmps.push(cmp)
if (foundCmps.length === 1) {
onFirstPopupAppears(cmp)
}
})
.catch(error => {
enableLogs && console.warn(`error waiting for a popup for ${cmps[i].name}`, error)
})
.finally(() => {
if (++completed === l) {
resolve(foundCmps)
}
})
async detectPopups(cmps: AutoCMP[], onFirstPopupAppears: (cmp: AutoCMP) => unknown) {
const tasks = cmps.map(
cmp => this.detectPopup(cmp)
// Handle errors immediately and propagate the error to next handler: Promise.allSettled
// If we gracefully return errors, Promise.race needs another evaluation
.catch(error => {
enableLogs && console.warn(`error waiting for a popup for ${cmp.name}`, error)

throw error
})
)

const firstCmpWithPopup = await Promise.race(tasks)
seia-soto marked this conversation as resolved.
Show resolved Hide resolved

onFirstPopupAppears(firstCmpWithPopup)

const results = await Promise.allSettled(tasks)
const popups: AutoCMP[] = []

for (const result of results) {
if (result.status === 'fulfilled') {
popups.push(result.value)
}
})
}

return popups
}

async handlePopup(cmp: AutoCMP): Promise<boolean> {
Expand Down