Prevent possible endless loop with image fallback (#444)

This commit is contained in:
Jean Fernandez 2024-03-06 13:52:40 -05:00 committed by GitHub
parent 62051f951c
commit d025251572
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 1 deletions

View File

@ -1,6 +1,7 @@
import type { StorybookConfig } from "@storybook/angular";
const config: StorybookConfig = {
stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
staticDirs: [{ from: '../src/assets', to: '/assets' }],
addons: [
"@storybook/addon-links",
"@storybook/addon-essentials",

View File

@ -1,5 +1,7 @@
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
const DEFAULT_IMAGE_FALLBACK_PATH: string = '/assets/images/no-image.svg';
@Directive({
selector: 'img[imageFallback]'
})
@ -10,7 +12,22 @@ export class ImageFallbackDirective {
@HostListener('error')
loadFallbackOnError() {
this.elementRef.nativeElement.src = this.imageFallback || 'assets/images/no-image.svg';
// Check to see if we have already tried to load the fallback image.
// Avoids endless loop if for some reason fallback image is missing. Just accept the broken image.
if (this.path(this.elementRef.nativeElement.src) == this.path(this.fallbackSrc())) {
return;
}
this.elementRef.nativeElement.src = this.fallbackSrc();
}
private fallbackSrc(): string {
return this.imageFallback || DEFAULT_IMAGE_FALLBACK_PATH;
}
private path(urlString: string): string {
// remove http(s) and domain
return urlString.replace(/^https?:\/\/[^\/]*/, '');
}
}