aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Image/FallbackImage.svelte
blob: 1eafdd4cca67b9b85238b8313f08f561e25ae05c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<script lang="ts">
  interface Props {
    source: string | undefined | null;
    alternative: string | undefined | null;
    fallback: string | undefined | null;
    maxReplaceCount?: number;
    replaceDelay?: number;
    error?: string;
    hideOnError?: boolean;
    style?: string;
  }

  let {
    source,
    alternative,
    fallback,
    maxReplaceCount = 1,
    replaceDelay = 1000,
    error = 'https://i2.kym-cdn.com/photos/images/newsfeed/000/290/992/0aa.jpg',
    hideOnError = false,
    style = ''
  }: Props = $props();

  let replaceCount = $state(0);

  const delayedReplace = (event: Event, image: string | undefined | null) => {
    if (replaceCount >= maxReplaceCount) return;

    setTimeout(() => {
      (event.target as HTMLImageElement).src = image || '';

      replaceCount += 1;
    }, replaceDelay);
  };
</script>

{#if replaceCount < maxReplaceCount}
  <img
    src={source}
    alt={alternative}
    loading="lazy"
    class="badge"
    onerror={(e) => delayedReplace(e, fallback)}
    {style}
  />
{:else if !hideOnError}
  <img src={error} alt="Not found" loading="lazy" class="badge" />
{/if}

<style>
  .badge {
    border-radius: 8px;
  }
</style>