commit
Preview GLB and glTF files in a 3D viewer
Adds a "model" file kind for .glb and .gltf and an orbitable three.js viewer on their preview page. The viewer is lazy-loaded so three.js only downloads on model pages, and it fetches through /api/files so the raw bucket needs no CORS. Co-Authored-By: Sandrone <[email protected]>
diff --git a/deno.lock b/deno.lock
index bcb676f..39b6ecb 100644
--- a/deno.lock
+++ b/deno.lock
@@ -4,10 +4,12 @@
"npm:@cloudflare/workers-types@^5.20261024.1": "5.20261024.1",
"npm:@iconify-json/ic@^1.2.4": "1.2.4",
"npm:@sveltejs/vite-plugin-svelte@^7.3.1": "[email protected][email protected]",
+ "npm:@types/[email protected]": "0.187.0",
"npm:hono@^4.13.13": "4.13.13",
"npm:jose@^6.2.13": "6.2.13",
"npm:marked@^18.1.1": "18.1.1",
"npm:svelte@^5.57.2": "5.57.2",
+ "npm:[email protected]": "0.187.0",
"npm:typescript@^7.0.2": "7.0.2",
"npm:unplugin-icons@24": "[email protected][email protected]",
"npm:vite@^8.3.5": "8.3.5",
@@ -75,6 +77,9 @@
"@jridgewell/[email protected]"
]
},
+ "@dimforge/[email protected]": {
+ "integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow=="
+ },
"@emnapi/[email protected]": {
"integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
"dependencies": [
@@ -551,9 +556,29 @@
"vitefu"
]
},
+ "@tweenjs/[email protected]": {
+ "integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA=="
+ },
"@types/[email protected]": {
"integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg=="
},
+ "@types/[email protected]": {
+ "integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA=="
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-v+vKNarUtk4n2QRZ4+CN5ygMM0ARUjXjIQl0R/unMUfmStFeVqGbgqarbrpoGTXRZoulSH16ePrVJVxPJEbMUA==",
+ "dependencies": [
+ "@dimforge/rapier3d-compat",
+ "@tweenjs/tween.js",
+ "@types/stats.js",
+ "@types/webxr",
+ "fflate",
+ "meshoptimizer"
+ ]
+ },
+ "@types/[email protected]": {
+ "integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg=="
+ },
"@typescript/[email protected]": {
"integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
"os": ["aix"],
@@ -745,6 +770,9 @@
"picomatch"
]
},
+ "[email protected]": {
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="
+ },
"[email protected]": {
"integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
"os": ["darwin"],
@@ -869,6 +897,9 @@
"integrity": "sha512-zEGgrtUG8crk+TrMacJSVABU4DYDDkS8uqgU3ohrn/2fW9C2AEfUrO3m6IhpIpQpl7YcVpiXXC9cSMWDANT3dg==",
"bin": true
},
+ "[email protected]": {
+ "integrity": "sha512-oRFNWJRDA/WTrVj7NWvqa5HqE1t9MYDj2VaWirQCzCCrAd2GHrqR/sQezCxiWATPNlKTcRaPRHPJwIRoPBAp5g=="
+ },
"[email protected]": {
"integrity": "sha512-QNgCA/axizZ7kv7RV3nwbRoz+w4watBlwIsyXjwgYHw4eSw5BrR1F2152s3Kz+Bzy/YxjKFHrZl3LzBRbPgYoQ==",
"dependencies": [
@@ -1028,6 +1059,9 @@
"zimmerframe"
]
},
+ "[email protected]": {
+ "integrity": "sha512-Qiu7R+Cmh8CstZsY1uJOSWnVlfo7ZtNLV7mF8Jltk3LB3AtDu9cRZlcnRKkAk8Y4z6KKw35z7Y7Urd7jWY8etA=="
+ },
"[email protected]": {
"integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA=="
},
@@ -1195,10 +1229,12 @@
"npm:@cloudflare/workers-types@^5.20261024.1",
"npm:@iconify-json/ic@^1.2.4",
"npm:@sveltejs/vite-plugin-svelte@^7.3.1",
+ "npm:@types/[email protected]",
"npm:hono@^4.13.13",
"npm:jose@^6.2.13",
"npm:marked@^18.1.1",
"npm:svelte@^5.57.2",
+ "npm:[email protected]",
"npm:typescript@^7.0.2",
"npm:unplugin-icons@24",
"npm:vite@^8.3.5",
diff --git a/package.json b/package.json
index 2c761ba..fac36a0 100644
--- a/package.json
+++ b/package.json
@@ -20,7 +20,9 @@
"@cloudflare/workers-types": "^5.20261024.1",
"@iconify-json/ic": "^1.2.4",
"@sveltejs/vite-plugin-svelte": "^7.3.1",
+ "@types/three": "^0.187.0",
"svelte": "^5.57.2",
+ "three": "^0.187.0",
"typescript": "^7.0.2",
"unplugin-icons": "^24.0.0",
"vite": "^8.3.5",
diff --git a/public/style.css b/public/style.css
index 95b150f..a9b5e92 100644
--- a/public/style.css
+++ b/public/style.css
@@ -474,6 +474,40 @@ header nav a[aria-current="page"] { color: var(--text); }
tab-size: 2;
}
+.preview .model {
+ position: relative;
+ height: 75vh;
+ min-height: 20rem;
+ touch-action: none;
+}
+
+.preview .model canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ cursor: grab;
+}
+
+.preview .model canvas:active {
+ cursor: grabbing;
+}
+
+.preview .model-status {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ pointer-events: none;
+}
+
+.preview .model-tools {
+ position: absolute;
+ right: 0.75rem;
+ bottom: 0.75rem;
+ display: flex;
+ gap: 0.5rem;
+}
+
.preview .empty {
margin: 0;
padding: 2.5rem 1rem;
diff --git a/shared/kinds.ts b/shared/kinds.ts
index 1f145e7..d337656 100644
--- a/shared/kinds.ts
+++ b/shared/kinds.ts
@@ -1,14 +1,15 @@
// What a file is, going by its extension. Shared by the worker (link embeds)
// and the viewer (previews).
-export type Kind = "image" | "video" | "audio" | "pdf" | "text";
+export type Kind = "image" | "video" | "audio" | "pdf" | "model" | "text";
const EXTENSIONS: Record<Kind, string> = {
image: "png jpg jpeg gif webp avif svg ico bmp",
video: "mp4 webm mov",
audio: "mp3 ogg wav flac m4a",
pdf: "pdf",
- text: "txt md json js mjs cjs ts css html xml csv tsv yml yaml toml ini log sh ps1 py gltf",
+ model: "glb gltf",
+ text: "txt md json js mjs cjs ts css html xml csv tsv yml yaml toml ini log sh ps1 py",
};
const KINDS: Record<string, Kind> = Object.fromEntries(
diff --git a/web/src/lib/ModelViewer.svelte b/web/src/lib/ModelViewer.svelte
new file mode 100644
index 0000000..b10cc62
--- /dev/null
+++ b/web/src/lib/ModelViewer.svelte
@@ -0,0 +1,144 @@
+<!-- web/src/lib/ModelViewer.svelte -->
+
+<script lang="ts">
+ // Orbitable preview of a .glb or .gltf. Loaded lazily by Preview.svelte so
+ // three.js only downloads on model pages.
+
+ import { onMount } from "svelte";
+ import * as THREE from "three";
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
+ import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
+ import { RoomEnvironment } from "three/examples/jsm/environments/RoomEnvironment.js";
+ import { MeshoptDecoder } from "three/examples/jsm/libs/meshopt_decoder.module.js";
+
+ let { src, name }: { src: string; name: string } = $props();
+
+ let host: HTMLDivElement;
+ let status = $state("Loading model…");
+ let failed = $state(false);
+ let spinning = $state(true);
+ let resetView = () => {};
+
+ onMount(() => {
+ const renderer = new THREE.WebGLRenderer({
+ antialias: true,
+ alpha: true,
+ });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ host.appendChild(renderer.domElement);
+
+ const scene = new THREE.Scene();
+ const environment = new THREE.PMREMGenerator(renderer);
+ scene.environment = environment.fromScene(new RoomEnvironment(), 0.04).texture;
+
+ const camera = new THREE.PerspectiveCamera(45, 1, 0.01, 1000);
+ const controls = new OrbitControls(camera, renderer.domElement);
+ controls.enableDamping = true;
+ controls.autoRotateSpeed = 1.5;
+
+ // Stop the idle spin as soon as someone grabs the model
+ controls.addEventListener("start", () => {
+ spinning = false;
+ });
+
+ function resize() {
+ const width = host.clientWidth;
+ const height = host.clientHeight;
+ renderer.setSize(width, height, false);
+ camera.aspect = width / height;
+ camera.updateProjectionMatrix();
+ }
+
+ const observer = new ResizeObserver(resize);
+ observer.observe(host);
+ resize();
+
+ // Point the camera at the model's bounding sphere, whatever its scale
+ function frame(object: THREE.Object3D) {
+ const sphere = new THREE.Box3()
+ .setFromObject(object)
+ .getBoundingSphere(new THREE.Sphere());
+ const radius = sphere.radius || 1;
+ const distance = radius / Math.sin(THREE.MathUtils.degToRad(camera.fov / 2));
+
+ camera.near = distance / 100;
+ camera.far = distance * 100;
+ camera.position
+ .copy(sphere.center)
+ .add(new THREE.Vector3(0.6, 0.4, 1).normalize().multiplyScalar(distance));
+ camera.updateProjectionMatrix();
+
+ controls.target.copy(sphere.center);
+ controls.update();
+ }
+
+ let mixer: THREE.AnimationMixer | undefined;
+ const loader = new GLTFLoader();
+ loader.setMeshoptDecoder(MeshoptDecoder);
+
+ loader.load(
+ src,
+ (gltf) => {
+ scene.add(gltf.scene);
+ resetView = () => frame(gltf.scene);
+ resetView();
+
+ // Play the first animation, if the file has any
+ if (gltf.animations.length > 0) {
+ mixer = new THREE.AnimationMixer(gltf.scene);
+ mixer.clipAction(gltf.animations[0]).play();
+ }
+ status = "";
+ },
+ (progress) => {
+ if (progress.total > 0) {
+ status = `Loading model… ${Math.round((progress.loaded / progress.total) * 100)}%`;
+ }
+ },
+ (error) => {
+ console.error(error);
+ failed = true;
+ status = "Couldn't load this model. Download it instead.";
+ },
+ );
+
+ const clock = new THREE.Clock();
+ renderer.setAnimationLoop(() => {
+ controls.autoRotate = spinning;
+ controls.update();
+ mixer?.update(clock.getDelta());
+ renderer.render(scene, camera);
+ });
+
+ return () => {
+ renderer.setAnimationLoop(null);
+ observer.disconnect();
+ controls.dispose();
+ environment.dispose();
+ scene.traverse((object) => {
+ if (object instanceof THREE.Mesh) {
+ object.geometry.dispose();
+ const materials = Array.isArray(object.material) ? object.material : [object.material];
+ for (const material of materials) material.dispose();
+ }
+ });
+ renderer.dispose();
+ renderer.domElement.remove();
+ };
+ });
+</script>
+
+<div class="model" bind:this={host} role="img" aria-label={`3D model: ${name}`}>
+ {#if status}
+ <p class="empty model-status">{status}</p>
+ {/if}
+ {#if !failed}
+ <div class="model-tools">
+ <button class="btn" type="button" onclick={() => (spinning = !spinning)}>
+ {spinning ? "Stop spin" : "Spin"}
+ </button>
+ <button class="btn" type="button" onclick={() => resetView()}>Reset view</button>
+ </div>
+ {/if}
+</div>
diff --git a/web/src/routes/Preview.svelte b/web/src/routes/Preview.svelte
index 8b9936c..0c81bd7 100644
--- a/web/src/routes/Preview.svelte
+++ b/web/src/routes/Preview.svelte
@@ -83,6 +83,15 @@
<audio src={url} controls preload="metadata"></audio>
{:else if kind === "pdf"}
<iframe src={url} title={name}></iframe>
+ {:else if kind === "model"}
+ <!-- Same-origin URL: three.js fetches it, and raw has no CORS for this site -->
+ {#await import("../lib/ModelViewer.svelte")}
+ <p class="empty">Loading viewer…</p>
+ {:then { default: ModelViewer }}
+ <ModelViewer src={local} {name} />
+ {:catch}
+ <p class="empty">Couldn't load the 3D viewer.</p>
+ {/await}
{:else if text}
{#await text}
<p class="empty">Loading…</p>