Skip to content

Commit

Permalink
refactor: general solution
Browse files Browse the repository at this point in the history
  • Loading branch information
jeripeierSBB committed Aug 28, 2024
1 parent 22b2c23 commit 9dbd910
Showing 1 changed file with 21 additions and 10 deletions.
31 changes: 21 additions & 10 deletions src/elements/core/testing/wait-for-image-ready.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,37 @@ export async function waitForImageReady(
element: HTMLImageElement | SbbImageElement,
timeoutInMilliseconds = 2 * 1000,
): Promise<void> {
const imgElement =
element.localName === 'sbb-image'
? (element.shadowRoot?.querySelector<HTMLImageElement>('.sbb-image__img') ?? null)
: (element as HTMLImageElement);

if (!imgElement) {
return Promise.reject('img tag not found');
}

if (!element.complete) {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(() => reject('image loading timeout'), timeoutInMilliseconds);
element.addEventListener('load', () => {
clearTimeout(timeout);
if (element instanceof HTMLImageElement) {
element.decode().then(resolve);
} else if (isSafari && element.localName === 'sbb-image') {
// On a test this is only happening once (first time an image is loaded). Therefore, the impact is very small.
setTimeout(resolve, 200);
} else {
resolve();
}

imgElement.decode().then(() => {
if (isSafari && element.localName === 'sbb-image') {
// On a test page this is only happening once (first time an image is loaded). Therefore, the impact is very small.
setTimeout(resolve, 100);
} else {
resolve();
}
});
});

element.addEventListener('error', () => {
clearTimeout(timeout);
reject('image error');
});
});
} else if (element instanceof HTMLImageElement) {
await element.decode();
} else {
await imgElement.decode();
}
}

0 comments on commit 9dbd910

Please sign in to comment.