File viewer
It would be cool to be able to see the file contents. You can imagine having viewers for images, text documents, PDFs, audio and video files, and so on.
What we probably don’t want to do is load all those preview components when we only need one at a time. We can solve this with a neat Vite feature.
First, create a lib/components/viewers folder with image.svelte and fallback.svelte:
<script lang="ts">
import type { file } from '$lib/server/db/schema';
interface Props {
data: typeof file.$inferSelect;
}
let { data }: Props = $props();
</script>
<img alt={data.name} src="TODO" /> <p>No preview available</p> Then, create lib/components/FileViewer.svelte:
<script lang="ts">
import type { file } from '$lib/server/db/schema';
interface Props {
data: typeof file.$inferSelect;
}
let { data }: Props = $props();
const types = new Set(['image']);
const type = $derived(data.type.split('/')[0]);
const module = $derived(
types.has(type)
? await import(`./viewers/${type}.svelte`)
: await import('./viewers/fallback.svelte')
);
</script>
<module.default {data} /> Lo and behold, we can see a file preview. It’s broken though because we have no way to get the image data. We’ll fix that in the next exercise.