Prevent possible endless loop with image fallback (#444)
This commit is contained in:
parent
62051f951c
commit
d025251572
|
@ -1,6 +1,7 @@
|
||||||
import type { StorybookConfig } from "@storybook/angular";
|
import type { StorybookConfig } from "@storybook/angular";
|
||||||
const config: StorybookConfig = {
|
const config: StorybookConfig = {
|
||||||
stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
|
stories: ["../src/**/*.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
|
||||||
|
staticDirs: [{ from: '../src/assets', to: '/assets' }],
|
||||||
addons: [
|
addons: [
|
||||||
"@storybook/addon-links",
|
"@storybook/addon-links",
|
||||||
"@storybook/addon-essentials",
|
"@storybook/addon-essentials",
|
||||||
|
|
|
@ -1,5 +1,7 @@
|
||||||
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
|
import {Directive, ElementRef, HostListener, Input} from '@angular/core';
|
||||||
|
|
||||||
|
const DEFAULT_IMAGE_FALLBACK_PATH: string = '/assets/images/no-image.svg';
|
||||||
|
|
||||||
@Directive({
|
@Directive({
|
||||||
selector: 'img[imageFallback]'
|
selector: 'img[imageFallback]'
|
||||||
})
|
})
|
||||||
|
@ -10,7 +12,22 @@ export class ImageFallbackDirective {
|
||||||
|
|
||||||
@HostListener('error')
|
@HostListener('error')
|
||||||
loadFallbackOnError() {
|
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?:\/\/[^\/]*/, '');
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue