Skip to content

Commit 0891709

Browse files
committed
feat: image re-usable component with fallback
1 parent 6231f2d commit 0891709

File tree

2 files changed

+62
-7
lines changed

2 files changed

+62
-7
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
<script lang="ts">
2+
import { cn } from '$lib/functions/classnames';
3+
4+
type Props = {
5+
src?: string | null;
6+
class?: string;
7+
};
8+
9+
let { src, class: klass }: Props = $props();
10+
11+
let valid_src = $state(false);
12+
13+
const object_classes: string[] = [];
14+
let _klass = klass
15+
?.split(/\s+/)
16+
.filter((cls) => {
17+
if (cls.startsWith('object-')) {
18+
object_classes.push(cls);
19+
return false;
20+
}
21+
return true;
22+
})
23+
.join(' ');
24+
25+
$effect.pre(() => {
26+
if (!src) {
27+
valid_src = false;
28+
return;
29+
}
30+
// create img instance
31+
const img = new Image();
32+
img.onload = () => (valid_src = true);
33+
img.onerror = () => (valid_src = false);
34+
img.src = src;
35+
});
36+
</script>
37+
38+
<div class={cn(_klass, 'grid place-items-center overflow-hidden bg-neutral')}>
39+
{#if valid_src}
40+
<img {src} alt="" class={cn('h-full w-full', ...object_classes)} />
41+
{:else}
42+
<svg
43+
class="w-10 text-neutral-content"
44+
viewBox="0 0 157 86"
45+
fill="none"
46+
xmlns="http://www.w3.org/2000/svg"
47+
>
48+
<path
49+
d="M143.6 13L113.366 43L143.6 73M13 13L43.2344 43L13 73"
50+
stroke="currentColor"
51+
stroke-width="25"
52+
stroke-linecap="round"
53+
stroke-linejoin="round"
54+
/>
55+
</svg>
56+
{/if}
57+
</div>

frontend/src/routes/(app)/q/[name]/+page.svelte

+5-7
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import { createAuthStore } from '$lib/stores/auth.svelte';
99
import { onMount } from 'svelte';
1010
import { createSidebarStore } from '$lib/stores/sidebar.svelte';
11+
import Image from '$lib/components/ui/image.svelte';
1112
1213
const { data }: { data: PageData } = $props();
1314
const { quiblet, quibs, highlighted_quibs } = data;
@@ -40,13 +41,10 @@
4041
</svelte:head>
4142

4243
<div class="relative">
43-
<div
44-
class={cn(
45-
!quiblet?.banner ? 'h-24 bg-neutral' : 'h-40 bg-cover bg-center',
46-
'w-full rounded-2xl'
47-
)}
48-
style="background-image: url({quiblet?.banner});"
49-
></div>
44+
<Image
45+
src={quiblet?.banner}
46+
class={cn(quiblet?.banner ? 'h-40 object-cover object-center' : 'h-24', 'rounded-2xl')}
47+
/>
5048
<div class="absolute inset-x-0 -bottom-12 flex items-end justify-between px-4">
5149
<div class="flex items-end gap-2">
5250
<Avatar class="!size-20 outline outline-8 outline-base-300" src={quiblet?.avatar} />

0 commit comments

Comments
 (0)