Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"eslint-config-prettier": "9.1.2",
"eslint-plugin-svelte": "2.46.1",
"husky": "^9.1.7",
"image-size": "^2.0.2",
"jsdom": "^29.1.1",
"lint-staged": "^17.0.8",
"postcss": "^8.4.38",
Expand Down
46 changes: 46 additions & 0 deletions src/lib/components/ImageLoader.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<script lang="ts">
// Props
export let src: string;
export let alt: string = '';
export let dimensions: { width: number; height: number } | undefined = undefined;
export let className: string = '';
export let imageClassName: string = '';

// Whether the image has finished loading — used only to hide the skeleton.
// The image itself is never gated on this, so it can't get stuck hidden.
let loaded = false;

// Normalize path so nested routes (e.g., /publications/paper-name) don't break relative paths
$: normalizedSrc = src.startsWith('/') || src.startsWith('http') ? src : `/${src}`;

// Reserve the exact aspect ratio so the box holds its height before the image
// loads, eliminating layout shift.
$: aspectRatio = dimensions ? `${dimensions.width} / ${dimensions.height}` : 'auto';

function markLoaded() {
loaded = true;
}

// Cached or server-rendered images can finish loading before the `load` listener
// is attached, so reconcile the state on mount by inspecting the element directly.
function trackLoad(node: HTMLImageElement) {
if (node.complete) markLoaded();
}
</script>

<div class="relative w-full overflow-hidden {className}" style="aspect-ratio: {aspectRatio};">
<!-- Skeleton placeholder, shown behind the image until it has loaded -->
{#if !loaded}
<div class="absolute inset-0 animate-pulse bg-primary/10" aria-hidden="true"></div>
{/if}

<!-- Actual image: always visible, covers the skeleton once it paints -->
<img
src={normalizedSrc}
{alt}
use:trackLoad
on:load={markLoaded}
on:error={markLoaded}
class="absolute inset-0 h-full w-full object-contain {imageClassName}"
/>
</div>
7 changes: 7 additions & 0 deletions src/lib/helpers/projectsProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import Pen from 'svelte-material-icons/Pen.svelte';
import Web from 'svelte-material-icons/Web.svelte';
import Youtube from 'svelte-material-icons/Youtube.svelte';
import { FunProject, LinkWithIcon, ResearchProject } from '../types';
import imageDimensions from 'virtual:image-dimensions';

let cachedResearchProjects: ResearchProject[] | null = null;

Expand Down Expand Up @@ -400,6 +401,9 @@ export function getResearchProjects(): ResearchProject[] {
)
];
projects.sort((a, b) => parseInt(b.year) - parseInt(a.year));
projects.forEach((p) => {
if (imageDimensions[p.imageSrc]) p.imageDimensions = imageDimensions[p.imageSrc];
});
cachedResearchProjects = projects;
return projects;
}
Expand Down Expand Up @@ -505,6 +509,9 @@ export function getFunProjects(): FunProject[] {
]
)
];
projects.forEach((p) => {
if (imageDimensions[p.imageSrc]) p.imageDimensions = imageDimensions[p.imageSrc];
});
cachedFunProjects = projects;
return projects;
}
Expand Down
28 changes: 23 additions & 5 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export class Project {
title: string;
abstract: string;
imageSrc: string;
imageDimensions?: { width: number; height: number };
links: LinkWithIcon[];
/**
* Creates a project
Expand All @@ -32,11 +33,19 @@ export class Project {
* @param {String} abstract the abstract of the project/paper
* @param {String} imageSrc the image source for the project
* @param {[LinkWithIcon]} links links from the project to more information
* @param {{ width: number; height: number }} imageDimensions dimensions of the image
*/
constructor(title: string, abstract: string, imageSrc: string, links: LinkWithIcon[] = []) {
constructor(
title: string,
abstract: string,
imageSrc: string,
links: LinkWithIcon[] = [],
imageDimensions?: { width: number; height: number }
) {
this.title = title;
this.abstract = abstract;
this.imageSrc = imageSrc;
this.imageDimensions = imageDimensions;
this.links = links;
}
}
Expand All @@ -59,6 +68,7 @@ export class ResearchProject extends Project {
* @param {String} venue the venue of the publication
* @param {String} imageSRC the image source for the project
* @param {[LinkWithIcon]} links links from the project to more information
* @param {{ width: number; height: number }} imageDimensions dimensions of the image
*/
constructor(
title: string,
Expand All @@ -67,9 +77,10 @@ export class ResearchProject extends Project {
year: string,
venue: string,
imageSRC: string,
links: LinkWithIcon[] = []
links: LinkWithIcon[] = [],
imageDimensions?: { width: number; height: number }
) {
super(title, abstract, imageSRC, links);
super(title, abstract, imageSRC, links, imageDimensions);
this.authors = authors;
this.year = year;
this.venue = venue;
Expand All @@ -87,9 +98,16 @@ export class FunProject extends Project {
* @param {String} abstract the abstract of the project/paper
* @param {String} imageSRC the image source for the project
* @param {[LinkWithIcon]} links links from the project to more information
* @param {{ width: number; height: number }} imageDimensions dimensions of the image
*/
constructor(title: string, abstract: string, imageSRC: string, links: LinkWithIcon[] = []) {
super(title, abstract, imageSRC, links);
constructor(
title: string,
abstract: string,
imageSRC: string,
links: LinkWithIcon[] = [],
imageDimensions?: { width: number; height: number }
) {
super(title, abstract, imageSRC, links, imageDimensions);
}
}

Expand Down
7 changes: 5 additions & 2 deletions src/routes/publications/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<script lang="ts">
import Icon from '$lib/components/Icon.svelte';
import ImageLoader from '$lib/components/ImageLoader.svelte';
import { getResearchProjects, slugify } from '$lib/helpers/projectsProvider';
import { reveal } from '$lib/actions/reveal';

Expand Down Expand Up @@ -57,10 +58,12 @@

<!-- Thumbnail -->
<div class="shrink-0 overflow-hidden rounded-lg">
<img
<ImageLoader
src={pub.imageSrc}
alt={pub.title}
class="h-auto w-full object-contain transition-transform duration-500 group-hover:scale-[1.03] sm:w-48"
dimensions={pub.imageDimensions}
className="w-full sm:w-48"
imageClassName="transition-transform duration-500 group-hover:scale-[1.03]"
/>
</div>

Expand Down
11 changes: 6 additions & 5 deletions src/routes/publications/[paper]/+page.svelte
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script lang="ts">
import { page } from '$app/stores';
import Icon from '$lib/components/Icon.svelte';
import ImageLoader from '$lib/components/ImageLoader.svelte';
import { getResearchProjects, slugify } from '$lib/helpers/projectsProvider';
import { reveal } from '$lib/actions/reveal';

Expand Down Expand Up @@ -80,12 +81,12 @@
<div
class="order-1 overflow-hidden rounded-2xl border border-primary/10 bg-background-card/50 p-2 shadow-sm backdrop-blur-sm md:order-2 md:col-span-2 md:col-start-4 md:row-start-1"
>
<img
src={paper.imageSrc.startsWith('/') || paper.imageSrc.startsWith('http')
? paper.imageSrc
: `/${paper.imageSrc}`}
<ImageLoader
src={paper.imageSrc}
alt={paper.title}
class="h-auto w-full rounded-xl object-contain"
dimensions={paper.imageDimensions}
className="w-full"
imageClassName="rounded-xl"
/>
</div>

Expand Down
4 changes: 4 additions & 0 deletions src/virtual-modules.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module 'virtual:image-dimensions' {
const dimensions: Record<string, { width: number; height: number }>;
export default dimensions;
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true
Expand Down
56 changes: 56 additions & 0 deletions vite-plugin-image-dimensions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { readFileSync, readdirSync } from 'node:fs';
import { join } from 'node:path';
import { imageSize } from 'image-size';
import type { Plugin } from 'vite';

const VIRTUAL_ID = 'virtual:image-dimensions';
const RESOLVED_ID = '\0' + VIRTUAL_ID;
const IMAGES_DIR = 'static/images';

/**
* Reads the intrinsic dimensions of every file in `static/images` at build time
* and exposes them as a virtual module keyed by their `imageSrc` path
* (e.g. `images/foo.png`). This lets components reserve an image's aspect ratio
* before it loads (avoiding layout shift) without hand-maintaining a dimensions
* map — new images are picked up automatically.
*/
function computeDimensions(): Record<string, { width: number; height: number }> {
const dimensions: Record<string, { width: number; height: number }> = {};
for (const file of readdirSync(IMAGES_DIR)) {
try {
const { width, height } = imageSize(readFileSync(join(IMAGES_DIR, file)));
if (width && height) dimensions[`images/${file}`] = { width, height };
} catch {
// Not an image / unsupported format — skip it.
}
}
return dimensions;
}

export function imageDimensions(): Plugin {
return {
name: 'image-dimensions',
resolveId(id) {
if (id === VIRTUAL_ID) return RESOLVED_ID;
},
load(id) {
if (id === RESOLVED_ID) {
return `export default ${JSON.stringify(computeDimensions())};`;
}
},
configureServer(server) {
// Regenerate on image add/remove/change during dev.
const invalidate = (file: string) => {
if (!file.includes('static/images')) return;
const mod = server.moduleGraph.getModuleById(RESOLVED_ID);
if (mod) {
server.moduleGraph.invalidateModule(mod);
server.ws.send({ type: 'full-reload' });
}
};
server.watcher.on('add', invalidate);
server.watcher.on('unlink', invalidate);
server.watcher.on('change', invalidate);
}
};
}
3 changes: 2 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
import { imageDimensions } from './vite-plugin-image-dimensions.ts';

export default defineConfig({
plugins: [sveltekit()]
plugins: [imageDimensions(), sveltekit()]
});
3 changes: 2 additions & 1 deletion vitest.config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { defineConfig } from 'vitest/config';
import { sveltekit } from '@sveltejs/kit/vite';
import { imageDimensions } from './vite-plugin-image-dimensions.ts';

export default defineConfig({
plugins: [sveltekit()],
plugins: [imageDimensions(), sveltekit()],
test: {
environment: 'jsdom',
globals: true
Expand Down
Loading