BlueGit

timfa filemanager

feat: server-side STL/OBJ thumbnail generation via geometry projection + Sharp

- Add MODEL_EXTS, isModelPath, geometry parsers (ASCII/binary STL, OBJ),
  projectModelVector, createModelSvgBuffer and generateModelThumb to
  thumbnail-cache.js; thumbnails are now generated as WebP on disk
- syncThumbnailCacheOnce picks up model files alongside images and videos
- Client getThumbnailKind now returns 'image' for MODEL_EXTS so the
  existing /api/files/thumbnail endpoint is used (blob URL, cached on disk)
- Remove all client-side geometry parsing functions (createModelSvgFromPolygons,
  projectModelVector, resolveObjIndex, parseObjPolygons,
  parseAsciiStlPolygons, parseBinaryStlPolygons,
  parseModelPolygonsFromBlob, modelThumbnailDataUrl) from app.js
- Update STL tile test to expect a blob URL from the thumbnail endpoint
- Add thumbnail-cache test for STL server-side generation (WebP output)

timfa Tim Falken · pushed by timfa

Authored 2026-05-15 · 6 months ago

Hash
64190b25340565dc631cbdd958f8928266076fae
Parent
fbc0f4c6
5 files changed +280 −274
.github/technical-reference.md +1 −1
@@ -6,7 +6,7 @@
6 6 - GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
7 7
8 8 ## server/thumbnail-cache.js
9 - syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files and video files (frame around 10% via ffprobe/ffmpeg); removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
9 - syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files, video files (ffprobe/ffmpeg frame at ~10%), and 3D model files (STL/OBJ, isometric SVG projection via Sharp); removes stale thumbnails and updates manifest hashes.
10 10 - startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
11 11 - stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
12 12 - getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
@@ -6,7 +6,7 @@
6- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
6- GET /share/:token - Calls buildShareOpenGraphPage to serve share.html with injected OG meta tags for all visitors; social media crawlers see rich preview data, browsers get the full interactive page.
7
7
8## server/thumbnail-cache.js
8## server/thumbnail-cache.js
9- syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files and video files (frame around 10% via ffprobe/ffmpeg); removes stale thumbnails and updates manifest hashes while preserving prior cache entries for temporarily unavailable roots (e.g. removable mounts).
9- syncThumbnailCacheOnce() - Mirrors configured roots and userPath into public/thumbs and generates 99x99-max WebP thumbnails for image files, video files (ffprobe/ffmpeg frame at ~10%), and 3D model files (STL/OBJ, isometric SVG projection via Sharp); removes stale thumbnails and updates manifest hashes.
10- startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
10- startThumbnailCacheLoop() - Schedules cache sync runs 5 seconds after boot and 5 seconds after each run completes.
11- stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
11- stopThumbnailCacheLoop() - Stops scheduled background cache sync runs.
12- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
12- getCachedThumbnailInfo(sourceFile) - Returns cached thumbnail path/content-type when present; null when not ready.
public/app.js +1 −265
@@ -4603,8 +4603,7 @@ function setThumbnailPending (iconEl, pending)
4603 4603 function getThumbnailKind (name)
4604 4604 {
4605 4605 const ext = extOf(name || '');
4606 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext)) return 'image';
4607 if (MODEL_EXTS.has(ext)) return 'model';
4606 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || MODEL_EXTS.has(ext)) return 'image';
4608 4607 if (CODE_EXTS.has(ext)) return 'text';
4609 4608 return 'badge';
4610 4609 }
@@ -4612,7 +4611,6 @@ function getThumbnailKind (name)
4612 4611 function maxThumbBytesForKind (kind)
4613 4612 {
4614 4613 if (kind === 'image') return 15 * 1024 * 1024;
4615 if (kind === 'model') return 15 * 1024 * 1024;
4616 4614 if (kind === 'text') return 1024 * 1024;
4617 4615 return 0;
4618 4616 }
@@ -4712,271 +4710,9 @@ function badgeThumbnailDataUrl (name, kind)
4712 4710 async function buildThumbnailSource (item, blob, kind)
4713 4711 {
4714 4712 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
4715 if (kind === 'model') return await modelThumbnailDataUrl(item, blob);
4716 4713 return badgeThumbnailDataUrl(item.name, kind);
4717 4714 }
4718 4715
4719 function createModelSvgFromPolygons (polygons)
4720 {
4721 const width = 160;
4722 const height = 200;
4723 const pad = 12;
4724
4725 let minX = Infinity;
4726 let minY = Infinity;
4727 let maxX = -Infinity;
4728 let maxY = -Infinity;
4729
4730 for (const poly of polygons)
4731 {
4732 for (const point of poly.points)
4733 {
4734 minX = Math.min(minX, point.x);
4735 minY = Math.min(minY, point.y);
4736 maxX = Math.max(maxX, point.x);
4737 maxY = Math.max(maxY, point.y);
4738 }
4739 }
4740
4741 if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY))
4742 {
4743 return null;
4744 }
4745
4746 const boxW = Math.max(1, maxX - minX);
4747 const boxH = Math.max(1, maxY - minY);
4748 const scale = Math.min((width - pad * 2) / boxW, (height - pad * 2 - 18) / boxH);
4749 const cx = (minX + maxX) / 2;
4750 const cy = (minY + maxY) / 2;
4751
4752 const svgPolys = polygons.map((poly) =>
4753 {
4754 const pts = poly.points.map((point) =>
4755 {
4756 const x = width / 2 + (point.x - cx) * scale;
4757 const y = 18 + height / 2 + (point.y - cy) * scale;
4758 return `${x.toFixed(1)},${y.toFixed(1)}`;
4759 }).join(' ');
4760
4761 return `<polygon points="${pts}" fill="rgba(47,109,255,0.28)" stroke="#7ea2ff" stroke-width="0.9" stroke-linejoin="round"/>`;
4762 }).join('');
4763
4764 return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
4765 <svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
4766 <defs>
4767 <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
4768 <stop offset="0%" stop-color="#111826"/>
4769 <stop offset="100%" stop-color="#0d111a"/>
4770 </linearGradient>
4771 </defs>
4772 <rect width="${width}" height="${height}" rx="10" fill="url(#bg)"/>
4773 <rect x="0" y="0" width="${width}" height="28" fill="#2f6dff"/>
4774 <text x="80" y="17" font-family="sans-serif" font-size="12" text-anchor="middle" fill="#ffffff" font-weight="700">3D</text>
4775 ${svgPolys}
4776 </svg>
4777 `)}`;
4778 }
4779
4780 function projectModelVector (vector)
4781 {
4782 const x = vector.x;
4783 const y = vector.y;
4784 const z = vector.z;
4785 const ry = Math.PI / 4;
4786 const rx = -Math.PI / 5;
4787
4788 const x1 = x * Math.cos(ry) + z * Math.sin(ry);
4789 const z1 = -x * Math.sin(ry) + z * Math.cos(ry);
4790 const y2 = y * Math.cos(rx) - z1 * Math.sin(rx);
4791 const z2 = y * Math.sin(rx) + z1 * Math.cos(rx);
4792
4793 return { x: x1, y: y2, z: z2 };
4794 }
4795
4796 function resolveObjIndex (token, vertexCount)
4797 {
4798 const raw = Number.parseInt(String(token || '').split('/')[0], 10);
4799 if (!Number.isFinite(raw) || raw === 0) return null;
4800 const index = raw < 0 ? vertexCount + raw : raw - 1;
4801 if (index < 0 || index >= vertexCount) return null;
4802 return index;
4803 }
4804
4805 function parseObjPolygons (text)
4806 {
4807 const vertices = [];
4808 const faces = [];
4809 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
4810
4811 for (const lineRaw of lines)
4812 {
4813 const line = lineRaw.trim();
4814 if (!line || line.startsWith('#')) continue;
4815
4816 if (/^v\s+/i.test(line))
4817 {
4818 const parts = line.split(/\s+/);
4819 if (parts.length >= 4)
4820 {
4821 const x = Number(parts[1]);
4822 const y = Number(parts[2]);
4823 const z = Number(parts[3]);
4824 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
4825 {
4826 vertices.push({ x, y, z });
4827 }
4828 }
4829 continue;
4830 }
4831
4832 if (/^f\s+/i.test(line))
4833 {
4834 const parts = line.split(/\s+/).slice(1);
4835 if (parts.length >= 3) faces.push(parts);
4836 }
4837 }
4838
4839 const polygons = [];
4840 for (const face of faces)
4841 {
4842 const indices = face
4843 .map((token) => resolveObjIndex(token, vertices.length))
4844 .filter((index) => index != null);
4845
4846 if (indices.length < 3) continue;
4847 const anchor = vertices[indices[0]];
4848 for (let i = 1; i < indices.length - 1; i++)
4849 {
4850 const b = vertices[indices[i]];
4851 const c = vertices[indices[i + 1]];
4852 if (anchor && b && c)
4853 {
4854 polygons.push({ points: [anchor, b, c] });
4855 }
4856 }
4857 }
4858
4859 return polygons;
4860 }
4861
4862 function parseAsciiStlPolygons (text)
4863 {
4864 const polygons = [];
4865 const vertices = [];
4866 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
4867
4868 for (const lineRaw of lines)
4869 {
4870 const line = lineRaw.trim();
4871 if (!/^vertex\s+/i.test(line)) continue;
4872 const parts = line.split(/\s+/);
4873 if (parts.length < 4) continue;
4874 const x = Number(parts[1]);
4875 const y = Number(parts[2]);
4876 const z = Number(parts[3]);
4877 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
4878 {
4879 vertices.push({ x, y, z });
4880 }
4881 }
4882
4883 for (let i = 0; i + 2 < vertices.length; i += 3)
4884 {
4885 polygons.push({ points: [vertices[i], vertices[i + 1], vertices[i + 2]] });
4886 }
4887
4888 return polygons;
4889 }
4890
4891 function parseBinaryStlPolygons (buffer)
4892 {
4893 const polygons = [];
4894 if (!buffer || buffer.byteLength < 84) return polygons;
4895
4896 const view = new DataView(buffer);
4897 const triCount = view.getUint32(80, true);
4898 let offset = 84;
4899
4900 for (let i = 0; i < triCount; i++)
4901 {
4902 if (offset + 50 > buffer.byteLength) break;
4903 offset += 12; // normal
4904 const points = [];
4905 for (let v = 0; v < 3; v++)
4906 {
4907 const x = view.getFloat32(offset, true);
4908 const y = view.getFloat32(offset + 4, true);
4909 const z = view.getFloat32(offset + 8, true);
4910 points.push({ x, y, z });
4911 offset += 12;
4912 }
4913 offset += 2; // attribute byte count
4914 polygons.push({ points });
4915 }
4916
4917 return polygons;
4918 }
4919
4920 async function parseModelPolygonsFromBlob (blob, type)
4921 {
4922 const extType = String(type || '').toLowerCase();
4923 if (extType === 'obj')
4924 {
4925 return parseObjPolygons(await blob.text());
4926 }
4927
4928 if (extType === 'stl')
4929 {
4930 const text = await blob.text();
4931 if (/\bvertex\s+/i.test(text) && /\bfacet\s+/i.test(text))
4932 {
4933 return parseAsciiStlPolygons(text);
4934 }
4935
4936 try
4937 {
4938 return parseBinaryStlPolygons(await blob.arrayBuffer());
4939 } catch
4940 {
4941 return [];
4942 }
4943 }
4944
4945 return [];
4946 }
4947
4948 async function modelThumbnailDataUrl (item, blob)
4949 {
4950 const type = modelPreviewType(item && item.name);
4951 if (!type) return badgeThumbnailDataUrl(item.name, 'badge');
4952
4953 let modelPolygons;
4954 try
4955 {
4956 modelPolygons = await parseModelPolygonsFromBlob(blob, type);
4957 } catch
4958 {
4959 return badgeThumbnailDataUrl(item.name, 'badge');
4960 }
4961
4962 if (!modelPolygons.length) return badgeThumbnailDataUrl(item.name, 'badge');
4963
4964 const polygons = [];
4965 for (const poly of modelPolygons)
4966 {
4967 const projectedPoints = poly.points.map((point) => projectModelVector(point));
4968 polygons.push({
4969 points: projectedPoints.map((point) => ({ x: point.x, y: point.y })),
4970 depth: projectedPoints.reduce((sum, point) => sum + point.z, 0) / projectedPoints.length,
4971 });
4972 }
4973
4974 polygons.sort((a, b) => a.depth - b.depth);
4975 const svgUrl = createModelSvgFromPolygons(polygons);
4976 if (svgUrl) return svgUrl;
4977 return badgeThumbnailDataUrl(item.name, 'badge');
4978 }
4979
4980 4716 function observeThumbnailIcon (iconEl)
4981 4717 {
4982 4718 if (!iconEl || !iconEl.isConnected) return;
@@ -4603,8 +4603,7 @@ function setThumbnailPending (iconEl, pending)
4603function getThumbnailKind (name)
4603function getThumbnailKind (name)
4604{
4604{
4605 const ext = extOf(name || '');
4605 const ext = extOf(name || '');
4606 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext)) return 'image';
4606 if (IMAGE_EXTS.has(ext) || VIDEO_EXTS.has(ext) || MODEL_EXTS.has(ext)) return 'image';
4607 if (MODEL_EXTS.has(ext)) return 'model';
4608 if (CODE_EXTS.has(ext)) return 'text';
4607 if (CODE_EXTS.has(ext)) return 'text';
4609 return 'badge';
4608 return 'badge';
4610}
4609}
@@ -4612,7 +4611,6 @@ function getThumbnailKind (name)
4612function maxThumbBytesForKind (kind)
4611function maxThumbBytesForKind (kind)
4613{
4612{
4614 if (kind === 'image') return 15 * 1024 * 1024;
4613 if (kind === 'image') return 15 * 1024 * 1024;
4615 if (kind === 'model') return 15 * 1024 * 1024;
4616 if (kind === 'text') return 1024 * 1024;
4614 if (kind === 'text') return 1024 * 1024;
4617 return 0;
4615 return 0;
4618}
4616}
@@ -4712,271 +4710,9 @@ function badgeThumbnailDataUrl (name, kind)
4712async function buildThumbnailSource (item, blob, kind)
4710async function buildThumbnailSource (item, blob, kind)
4713{
4711{
4714 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
4712 if (kind === 'text') return textThumbnailDataUrl(await blob.text());
4715 if (kind === 'model') return await modelThumbnailDataUrl(item, blob);
4716 return badgeThumbnailDataUrl(item.name, kind);
4713 return badgeThumbnailDataUrl(item.name, kind);
4717}
4714}
4718
4715
4719function createModelSvgFromPolygons (polygons)
4720{
4721 const width = 160;
4722 const height = 200;
4723 const pad = 12;
4724
4725 let minX = Infinity;
4726 let minY = Infinity;
4727 let maxX = -Infinity;
4728 let maxY = -Infinity;
4729
4730 for (const poly of polygons)
4731 {
4732 for (const point of poly.points)
4733 {
4734 minX = Math.min(minX, point.x);
4735 minY = Math.min(minY, point.y);
4736 maxX = Math.max(maxX, point.x);
4737 maxY = Math.max(maxY, point.y);
4738 }
4739 }
4740
4741 if (!Number.isFinite(minX) || !Number.isFinite(minY) || !Number.isFinite(maxX) || !Number.isFinite(maxY))
4742 {
4743 return null;
4744 }
4745
4746 const boxW = Math.max(1, maxX - minX);
4747 const boxH = Math.max(1, maxY - minY);
4748 const scale = Math.min((width - pad * 2) / boxW, (height - pad * 2 - 18) / boxH);
4749 const cx = (minX + maxX) / 2;
4750 const cy = (minY + maxY) / 2;
4751
4752 const svgPolys = polygons.map((poly) =>
4753 {
4754 const pts = poly.points.map((point) =>
4755 {
4756 const x = width / 2 + (point.x - cx) * scale;
4757 const y = 18 + height / 2 + (point.y - cy) * scale;
4758 return `${x.toFixed(1)},${y.toFixed(1)}`;
4759 }).join(' ');
4760
4761 return `<polygon points="${pts}" fill="rgba(47,109,255,0.28)" stroke="#7ea2ff" stroke-width="0.9" stroke-linejoin="round"/>`;
4762 }).join('');
4763
4764 return `data:image/svg+xml;charset=UTF-8,${encodeURIComponent(`
4765 <svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">
4766 <defs>
4767 <linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">
4768 <stop offset="0%" stop-color="#111826"/>
4769 <stop offset="100%" stop-color="#0d111a"/>
4770 </linearGradient>
4771 </defs>
4772 <rect width="${width}" height="${height}" rx="10" fill="url(#bg)"/>
4773 <rect x="0" y="0" width="${width}" height="28" fill="#2f6dff"/>
4774 <text x="80" y="17" font-family="sans-serif" font-size="12" text-anchor="middle" fill="#ffffff" font-weight="700">3D</text>
4775 ${svgPolys}
4776 </svg>
4777 `)}`;
4778}
4779
4780function projectModelVector (vector)
4781{
4782 const x = vector.x;
4783 const y = vector.y;
4784 const z = vector.z;
4785 const ry = Math.PI / 4;
4786 const rx = -Math.PI / 5;
4787
4788 const x1 = x * Math.cos(ry) + z * Math.sin(ry);
4789 const z1 = -x * Math.sin(ry) + z * Math.cos(ry);
4790 const y2 = y * Math.cos(rx) - z1 * Math.sin(rx);
4791 const z2 = y * Math.sin(rx) + z1 * Math.cos(rx);
4792
4793 return { x: x1, y: y2, z: z2 };
4794}
4795
4796function resolveObjIndex (token, vertexCount)
4797{
4798 const raw = Number.parseInt(String(token || '').split('/')[0], 10);
4799 if (!Number.isFinite(raw) || raw === 0) return null;
4800 const index = raw < 0 ? vertexCount + raw : raw - 1;
4801 if (index < 0 || index >= vertexCount) return null;
4802 return index;
4803}
4804
4805function parseObjPolygons (text)
4806{
4807 const vertices = [];
4808 const faces = [];
4809 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
4810
4811 for (const lineRaw of lines)
4812 {
4813 const line = lineRaw.trim();
4814 if (!line || line.startsWith('#')) continue;
4815
4816 if (/^v\s+/i.test(line))
4817 {
4818 const parts = line.split(/\s+/);
4819 if (parts.length >= 4)
4820 {
4821 const x = Number(parts[1]);
4822 const y = Number(parts[2]);
4823 const z = Number(parts[3]);
4824 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
4825 {
4826 vertices.push({ x, y, z });
4827 }
4828 }
4829 continue;
4830 }
4831
4832 if (/^f\s+/i.test(line))
4833 {
4834 const parts = line.split(/\s+/).slice(1);
4835 if (parts.length >= 3) faces.push(parts);
4836 }
4837 }
4838
4839 const polygons = [];
4840 for (const face of faces)
4841 {
4842 const indices = face
4843 .map((token) => resolveObjIndex(token, vertices.length))
4844 .filter((index) => index != null);
4845
4846 if (indices.length < 3) continue;
4847 const anchor = vertices[indices[0]];
4848 for (let i = 1; i < indices.length - 1; i++)
4849 {
4850 const b = vertices[indices[i]];
4851 const c = vertices[indices[i + 1]];
4852 if (anchor && b && c)
4853 {
4854 polygons.push({ points: [anchor, b, c] });
4855 }
4856 }
4857 }
4858
4859 return polygons;
4860}
4861
4862function parseAsciiStlPolygons (text)
4863{
4864 const polygons = [];
4865 const vertices = [];
4866 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
4867
4868 for (const lineRaw of lines)
4869 {
4870 const line = lineRaw.trim();
4871 if (!/^vertex\s+/i.test(line)) continue;
4872 const parts = line.split(/\s+/);
4873 if (parts.length < 4) continue;
4874 const x = Number(parts[1]);
4875 const y = Number(parts[2]);
4876 const z = Number(parts[3]);
4877 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
4878 {
4879 vertices.push({ x, y, z });
4880 }
4881 }
4882
4883 for (let i = 0; i + 2 < vertices.length; i += 3)
4884 {
4885 polygons.push({ points: [vertices[i], vertices[i + 1], vertices[i + 2]] });
4886 }
4887
4888 return polygons;
4889}
4890
4891function parseBinaryStlPolygons (buffer)
4892{
4893 const polygons = [];
4894 if (!buffer || buffer.byteLength < 84) return polygons;
4895
4896 const view = new DataView(buffer);
4897 const triCount = view.getUint32(80, true);
4898 let offset = 84;
4899
4900 for (let i = 0; i < triCount; i++)
4901 {
4902 if (offset + 50 > buffer.byteLength) break;
4903 offset += 12; // normal
4904 const points = [];
4905 for (let v = 0; v < 3; v++)
4906 {
4907 const x = view.getFloat32(offset, true);
4908 const y = view.getFloat32(offset + 4, true);
4909 const z = view.getFloat32(offset + 8, true);
4910 points.push({ x, y, z });
4911 offset += 12;
4912 }
4913 offset += 2; // attribute byte count
4914 polygons.push({ points });
4915 }
4916
4917 return polygons;
4918}
4919
4920async function parseModelPolygonsFromBlob (blob, type)
4921{
4922 const extType = String(type || '').toLowerCase();
4923 if (extType === 'obj')
4924 {
4925 return parseObjPolygons(await blob.text());
4926 }
4927
4928 if (extType === 'stl')
4929 {
4930 const text = await blob.text();
4931 if (/\bvertex\s+/i.test(text) && /\bfacet\s+/i.test(text))
4932 {
4933 return parseAsciiStlPolygons(text);
4934 }
4935
4936 try
4937 {
4938 return parseBinaryStlPolygons(await blob.arrayBuffer());
4939 } catch
4940 {
4941 return [];
4942 }
4943 }
4944
4945 return [];
4946}
4947
4948async function modelThumbnailDataUrl (item, blob)
4949{
4950 const type = modelPreviewType(item && item.name);
4951 if (!type) return badgeThumbnailDataUrl(item.name, 'badge');
4952
4953 let modelPolygons;
4954 try
4955 {
4956 modelPolygons = await parseModelPolygonsFromBlob(blob, type);
4957 } catch
4958 {
4959 return badgeThumbnailDataUrl(item.name, 'badge');
4960 }
4961
4962 if (!modelPolygons.length) return badgeThumbnailDataUrl(item.name, 'badge');
4963
4964 const polygons = [];
4965 for (const poly of modelPolygons)
4966 {
4967 const projectedPoints = poly.points.map((point) => projectModelVector(point));
4968 polygons.push({
4969 points: projectedPoints.map((point) => ({ x: point.x, y: point.y })),
4970 depth: projectedPoints.reduce((sum, point) => sum + point.z, 0) / projectedPoints.length,
4971 });
4972 }
4973
4974 polygons.sort((a, b) => a.depth - b.depth);
4975 const svgUrl = createModelSvgFromPolygons(polygons);
4976 if (svgUrl) return svgUrl;
4977 return badgeThumbnailDataUrl(item.name, 'badge');
4978}
4979
4980function observeThumbnailIcon (iconEl)
4716function observeThumbnailIcon (iconEl)
4981{
4717{
4982 if (!iconEl || !iconEl.isConnected) return;
4718 if (!iconEl || !iconEl.isConnected) return;
server/thumbnail-cache.js +238 −2
@@ -20,6 +20,7 @@ const IMAGE_EXTS = new Set([
20 20 const VIDEO_EXTS = new Set([
21 21 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
22 22 ]);
23 const MODEL_EXTS = new Set(['stl', 'obj']);
23 24
24 25 let loopTimer = null;
25 26 let loopStarted = false;
@@ -71,6 +72,12 @@ function isVideoPath (filePath)
71 72 return VIDEO_EXTS.has(ext);
72 73 }
73 74
75 function isModelPath (filePath)
76 {
77 const ext = path.extname(filePath).slice(1).toLowerCase();
78 return MODEL_EXTS.has(ext);
79 }
80
74 81 function ffmpegPath ()
75 82 {
76 83 return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
@@ -328,6 +335,212 @@ async function generateVideoThumb (sourceFile, thumbPath)
328 335 }
329 336 }
330 337
338 // ---------------------------------------------------------------------------
339 // 3D model geometry parsing and thumbnail generation
340 // ---------------------------------------------------------------------------
341
342 function projectModelVector (v)
343 {
344 const ry = Math.PI / 4;
345 const rx = -Math.PI / 5;
346 const x1 = v.x * Math.cos(ry) + v.z * Math.sin(ry);
347 const z1 = -v.x * Math.sin(ry) + v.z * Math.cos(ry);
348 const y2 = v.y * Math.cos(rx) - z1 * Math.sin(rx);
349 return { x: x1, y: y2, z: v.y * Math.sin(rx) + z1 * Math.cos(rx) };
350 }
351
352 function parseAsciiStlPolygons (text)
353 {
354 const polygons = [];
355 const vertices = [];
356 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
357 for (const lineRaw of lines)
358 {
359 const line = lineRaw.trim();
360 if (!/^vertex\s+/i.test(line)) continue;
361 const parts = line.split(/\s+/);
362 if (parts.length < 4) continue;
363 const x = Number(parts[1]);
364 const y = Number(parts[2]);
365 const z = Number(parts[3]);
366 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
367 {
368 vertices.push({ x, y, z });
369 }
370 }
371 for (let i = 0; i + 2 < vertices.length; i += 3)
372 {
373 polygons.push({ points: [vertices[i], vertices[i + 1], vertices[i + 2]] });
374 }
375 return polygons;
376 }
377
378 function parseBinaryStlPolygons (buf)
379 {
380 const polygons = [];
381 if (!buf || buf.length < 84) return polygons;
382 const triCount = buf.readUInt32LE(80);
383 let offset = 84;
384 for (let i = 0; i < triCount; i++)
385 {
386 if (offset + 50 > buf.length) break;
387 offset += 12; // skip normal
388 const points = [];
389 for (let v = 0; v < 3; v++)
390 {
391 const x = buf.readFloatLE(offset);
392 const y = buf.readFloatLE(offset + 4);
393 const z = buf.readFloatLE(offset + 8);
394 points.push({ x, y, z });
395 offset += 12;
396 }
397 offset += 2; // attribute byte count
398 polygons.push({ points });
399 }
400 return polygons;
401 }
402
403 function resolveObjIndex (token, vertexCount)
404 {
405 const raw = Number.parseInt(String(token || '').split('/')[0], 10);
406 if (!Number.isFinite(raw) || raw === 0) return null;
407 const index = raw < 0 ? vertexCount + raw : raw - 1;
408 if (index < 0 || index >= vertexCount) return null;
409 return index;
410 }
411
412 function parseObjPolygons (text)
413 {
414 const vertices = [];
415 const faces = [];
416 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
417 for (const lineRaw of lines)
418 {
419 const line = lineRaw.trim();
420 if (!line || line.startsWith('#')) continue;
421 if (/^v\s+/i.test(line))
422 {
423 const parts = line.split(/\s+/);
424 if (parts.length >= 4)
425 {
426 const x = Number(parts[1]);
427 const y = Number(parts[2]);
428 const z = Number(parts[3]);
429 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
430 {
431 vertices.push({ x, y, z });
432 }
433 }
434 }
435 else if (/^f\s+/i.test(line))
436 {
437 const parts = line.split(/\s+/).slice(1);
438 if (parts.length >= 3) faces.push(parts);
439 }
440 }
441 const polygons = [];
442 for (const face of faces)
443 {
444 const indices = face
445 .map((t) => resolveObjIndex(t, vertices.length))
446 .filter((i) => i != null);
447 if (indices.length < 3) continue;
448 const anchor = vertices[indices[0]];
449 for (let i = 1; i < indices.length - 1; i++)
450 {
451 const b = vertices[indices[i]];
452 const c = vertices[indices[i + 1]];
453 if (anchor && b && c) polygons.push({ points: [anchor, b, c] });
454 }
455 }
456 return polygons;
457 }
458
459 async function parseModelPolygons (sourceFile, ext)
460 {
461 const buf = await fs.promises.readFile(sourceFile);
462 if (ext === 'obj') return parseObjPolygons(buf.toString('utf8'));
463 // STL: probe first 256 bytes for ASCII keyword
464 const probe = buf.toString('utf8', 0, Math.min(buf.length, 256));
465 if (/facet/i.test(probe)) return parseAsciiStlPolygons(buf.toString('utf8'));
466 return parseBinaryStlPolygons(buf);
467 }
468
469 function createModelSvgBuffer (polygons)
470 {
471 const width = 160;
472 const height = 200;
473 const pad = 12;
474 let minX = Infinity;
475 let minY = Infinity;
476 let maxX = -Infinity;
477 let maxY = -Infinity;
478 for (const poly of polygons)
479 {
480 for (const pt of poly.points)
481 {
482 if (pt.x < minX) minX = pt.x;
483 if (pt.y < minY) minY = pt.y;
484 if (pt.x > maxX) maxX = pt.x;
485 if (pt.y > maxY) maxY = pt.y;
486 }
487 }
488 if (!Number.isFinite(minX)) return null;
489 const boxW = Math.max(1, maxX - minX);
490 const boxH = Math.max(1, maxY - minY);
491 const scale = Math.min((width - pad * 2) / boxW, (height - pad * 2 - 18) / boxH);
492 const cx = (minX + maxX) / 2;
493 const cy = (minY + maxY) / 2;
494 const svgPolys = polygons.map((poly) =>
495 {
496 const pts = poly.points.map((pt) =>
497 {
498 const x = width / 2 + (pt.x - cx) * scale;
499 const y = 18 + height / 2 + (pt.y - cy) * scale;
500 return `${x.toFixed(1)},${y.toFixed(1)}`;
501 }).join(' ');
502 return `<polygon points="${pts}" fill="rgba(47,109,255,0.28)" stroke="#7ea2ff" stroke-width="0.9" stroke-linejoin="round"/>`;
503 }).join('');
504 return Buffer.from(
505 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
506 + `<defs><linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">`
507 + `<stop offset="0%" stop-color="#111826"/><stop offset="100%" stop-color="#0d111a"/>`
508 + `</linearGradient></defs>`
509 + `<rect width="${width}" height="${height}" rx="10" fill="url(#bg)"/>`
510 + `<rect x="0" y="0" width="${width}" height="28" fill="#2f6dff"/>`
511 + `<text x="80" y="17" font-family="sans-serif" font-size="12" text-anchor="middle" fill="#ffffff" font-weight="700">3D</text>`
512 + svgPolys
513 + `</svg>`,
514 'utf8',
515 );
516 }
517
518 async function generateModelThumb (sourceFile, thumbPath)
519 {
520 const ext = path.extname(sourceFile).slice(1).toLowerCase();
521 const rawPolygons = await parseModelPolygons(sourceFile, ext);
522 if (!rawPolygons.length) throw new Error('No geometry found in model file');
523
524 const polygons = rawPolygons.map((poly) =>
525 {
526 const projected = poly.points.map(projectModelVector);
527 return {
528 points: projected.map((p) => ({ x: p.x, y: p.y })),
529 depth: projected.reduce((s, p) => s + p.z, 0) / projected.length,
530 };
531 });
532 polygons.sort((a, b) => a.depth - b.depth);
533
534 const svgBuf = createModelSvgBuffer(polygons);
535 if (!svgBuf) throw new Error('Failed to create SVG for model');
536
537 await ensureDir(path.dirname(thumbPath));
538 await sharp(svgBuf, { density: 144 })
539 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
540 .webp({ quality: 80 })
541 .toFile(thumbPath);
542 }
543
331 544 function effectiveRoots ()
332 545 {
333 546 const config = loadConfig();
@@ -419,7 +632,9 @@ async function syncThumbnailCacheOnce ()
419 632 ? 'image'
420 633 : isVideoPath(filePath)
421 634 ? 'video'
422 : null;
635 : isModelPath(filePath)
636 ? 'model'
637 : null;
423 638 if (!kind) return;
424 639
425 640 let stat;
@@ -485,9 +700,30 @@ async function syncThumbnailCacheOnce ()
485 700 return;
486 701 }
487 702
703 if (kind === 'video')
704 {
705 try
706 {
707 await generateVideoThumb(filePath, thumbPath);
708 } catch
709 {
710 return;
711 }
712
713 nextManifest.files[filePath] = {
714 sha256: null,
715 size: stat.size,
716 mtimeMs: stat.mtimeMs,
717 thumbRelPath,
718 kind,
719 };
720 return;
721 }
722
723 // kind === 'model'
488 724 try
489 725 {
490 await generateVideoThumb(filePath, thumbPath);
726 await generateModelThumb(filePath, thumbPath);
491 727 } catch
492 728 {
493 729 return;
@@ -20,6 +20,7 @@ const IMAGE_EXTS = new Set([
20const VIDEO_EXTS = new Set([
20const VIDEO_EXTS = new Set([
21 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
21 'mp4', 'mkv', 'mov', 'avi', 'webm', 'ogv', 'm4v', 'ts', 'mpeg', 'mpg',
22]);
22]);
23const MODEL_EXTS = new Set(['stl', 'obj']);
23
24
24let loopTimer = null;
25let loopTimer = null;
25let loopStarted = false;
26let loopStarted = false;
@@ -71,6 +72,12 @@ function isVideoPath (filePath)
71 return VIDEO_EXTS.has(ext);
72 return VIDEO_EXTS.has(ext);
72}
73}
73
74
75function isModelPath (filePath)
76{
77 const ext = path.extname(filePath).slice(1).toLowerCase();
78 return MODEL_EXTS.has(ext);
79}
80
74function ffmpegPath ()
81function ffmpegPath ()
75{
82{
76 return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
83 return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
@@ -328,6 +335,212 @@ async function generateVideoThumb (sourceFile, thumbPath)
328 }
335 }
329}
336}
330
337
338// ---------------------------------------------------------------------------
339// 3D model geometry parsing and thumbnail generation
340// ---------------------------------------------------------------------------
341
342function projectModelVector (v)
343{
344 const ry = Math.PI / 4;
345 const rx = -Math.PI / 5;
346 const x1 = v.x * Math.cos(ry) + v.z * Math.sin(ry);
347 const z1 = -v.x * Math.sin(ry) + v.z * Math.cos(ry);
348 const y2 = v.y * Math.cos(rx) - z1 * Math.sin(rx);
349 return { x: x1, y: y2, z: v.y * Math.sin(rx) + z1 * Math.cos(rx) };
350}
351
352function parseAsciiStlPolygons (text)
353{
354 const polygons = [];
355 const vertices = [];
356 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
357 for (const lineRaw of lines)
358 {
359 const line = lineRaw.trim();
360 if (!/^vertex\s+/i.test(line)) continue;
361 const parts = line.split(/\s+/);
362 if (parts.length < 4) continue;
363 const x = Number(parts[1]);
364 const y = Number(parts[2]);
365 const z = Number(parts[3]);
366 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
367 {
368 vertices.push({ x, y, z });
369 }
370 }
371 for (let i = 0; i + 2 < vertices.length; i += 3)
372 {
373 polygons.push({ points: [vertices[i], vertices[i + 1], vertices[i + 2]] });
374 }
375 return polygons;
376}
377
378function parseBinaryStlPolygons (buf)
379{
380 const polygons = [];
381 if (!buf || buf.length < 84) return polygons;
382 const triCount = buf.readUInt32LE(80);
383 let offset = 84;
384 for (let i = 0; i < triCount; i++)
385 {
386 if (offset + 50 > buf.length) break;
387 offset += 12; // skip normal
388 const points = [];
389 for (let v = 0; v < 3; v++)
390 {
391 const x = buf.readFloatLE(offset);
392 const y = buf.readFloatLE(offset + 4);
393 const z = buf.readFloatLE(offset + 8);
394 points.push({ x, y, z });
395 offset += 12;
396 }
397 offset += 2; // attribute byte count
398 polygons.push({ points });
399 }
400 return polygons;
401}
402
403function resolveObjIndex (token, vertexCount)
404{
405 const raw = Number.parseInt(String(token || '').split('/')[0], 10);
406 if (!Number.isFinite(raw) || raw === 0) return null;
407 const index = raw < 0 ? vertexCount + raw : raw - 1;
408 if (index < 0 || index >= vertexCount) return null;
409 return index;
410}
411
412function parseObjPolygons (text)
413{
414 const vertices = [];
415 const faces = [];
416 const lines = String(text || '').replace(/\r\n/g, '\n').split('\n');
417 for (const lineRaw of lines)
418 {
419 const line = lineRaw.trim();
420 if (!line || line.startsWith('#')) continue;
421 if (/^v\s+/i.test(line))
422 {
423 const parts = line.split(/\s+/);
424 if (parts.length >= 4)
425 {
426 const x = Number(parts[1]);
427 const y = Number(parts[2]);
428 const z = Number(parts[3]);
429 if (Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z))
430 {
431 vertices.push({ x, y, z });
432 }
433 }
434 }
435 else if (/^f\s+/i.test(line))
436 {
437 const parts = line.split(/\s+/).slice(1);
438 if (parts.length >= 3) faces.push(parts);
439 }
440 }
441 const polygons = [];
442 for (const face of faces)
443 {
444 const indices = face
445 .map((t) => resolveObjIndex(t, vertices.length))
446 .filter((i) => i != null);
447 if (indices.length < 3) continue;
448 const anchor = vertices[indices[0]];
449 for (let i = 1; i < indices.length - 1; i++)
450 {
451 const b = vertices[indices[i]];
452 const c = vertices[indices[i + 1]];
453 if (anchor && b && c) polygons.push({ points: [anchor, b, c] });
454 }
455 }
456 return polygons;
457}
458
459async function parseModelPolygons (sourceFile, ext)
460{
461 const buf = await fs.promises.readFile(sourceFile);
462 if (ext === 'obj') return parseObjPolygons(buf.toString('utf8'));
463 // STL: probe first 256 bytes for ASCII keyword
464 const probe = buf.toString('utf8', 0, Math.min(buf.length, 256));
465 if (/facet/i.test(probe)) return parseAsciiStlPolygons(buf.toString('utf8'));
466 return parseBinaryStlPolygons(buf);
467}
468
469function createModelSvgBuffer (polygons)
470{
471 const width = 160;
472 const height = 200;
473 const pad = 12;
474 let minX = Infinity;
475 let minY = Infinity;
476 let maxX = -Infinity;
477 let maxY = -Infinity;
478 for (const poly of polygons)
479 {
480 for (const pt of poly.points)
481 {
482 if (pt.x < minX) minX = pt.x;
483 if (pt.y < minY) minY = pt.y;
484 if (pt.x > maxX) maxX = pt.x;
485 if (pt.y > maxY) maxY = pt.y;
486 }
487 }
488 if (!Number.isFinite(minX)) return null;
489 const boxW = Math.max(1, maxX - minX);
490 const boxH = Math.max(1, maxY - minY);
491 const scale = Math.min((width - pad * 2) / boxW, (height - pad * 2 - 18) / boxH);
492 const cx = (minX + maxX) / 2;
493 const cy = (minY + maxY) / 2;
494 const svgPolys = polygons.map((poly) =>
495 {
496 const pts = poly.points.map((pt) =>
497 {
498 const x = width / 2 + (pt.x - cx) * scale;
499 const y = 18 + height / 2 + (pt.y - cy) * scale;
500 return `${x.toFixed(1)},${y.toFixed(1)}`;
501 }).join(' ');
502 return `<polygon points="${pts}" fill="rgba(47,109,255,0.28)" stroke="#7ea2ff" stroke-width="0.9" stroke-linejoin="round"/>`;
503 }).join('');
504 return Buffer.from(
505 `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}" viewBox="0 0 ${width} ${height}">`
506 + `<defs><linearGradient id="bg" x1="0" y1="0" x2="0" y2="1">`
507 + `<stop offset="0%" stop-color="#111826"/><stop offset="100%" stop-color="#0d111a"/>`
508 + `</linearGradient></defs>`
509 + `<rect width="${width}" height="${height}" rx="10" fill="url(#bg)"/>`
510 + `<rect x="0" y="0" width="${width}" height="28" fill="#2f6dff"/>`
511 + `<text x="80" y="17" font-family="sans-serif" font-size="12" text-anchor="middle" fill="#ffffff" font-weight="700">3D</text>`
512 + svgPolys
513 + `</svg>`,
514 'utf8',
515 );
516}
517
518async function generateModelThumb (sourceFile, thumbPath)
519{
520 const ext = path.extname(sourceFile).slice(1).toLowerCase();
521 const rawPolygons = await parseModelPolygons(sourceFile, ext);
522 if (!rawPolygons.length) throw new Error('No geometry found in model file');
523
524 const polygons = rawPolygons.map((poly) =>
525 {
526 const projected = poly.points.map(projectModelVector);
527 return {
528 points: projected.map((p) => ({ x: p.x, y: p.y })),
529 depth: projected.reduce((s, p) => s + p.z, 0) / projected.length,
530 };
531 });
532 polygons.sort((a, b) => a.depth - b.depth);
533
534 const svgBuf = createModelSvgBuffer(polygons);
535 if (!svgBuf) throw new Error('Failed to create SVG for model');
536
537 await ensureDir(path.dirname(thumbPath));
538 await sharp(svgBuf, { density: 144 })
539 .resize({ width: 99, height: 99, fit: 'inside', withoutEnlargement: true })
540 .webp({ quality: 80 })
541 .toFile(thumbPath);
542}
543
331function effectiveRoots ()
544function effectiveRoots ()
332{
545{
333 const config = loadConfig();
546 const config = loadConfig();
@@ -419,7 +632,9 @@ async function syncThumbnailCacheOnce ()
419 ? 'image'
632 ? 'image'
420 : isVideoPath(filePath)
633 : isVideoPath(filePath)
421 ? 'video'
634 ? 'video'
422 : null;
635 : isModelPath(filePath)
636 ? 'model'
637 : null;
423 if (!kind) return;
638 if (!kind) return;
424
639
425 let stat;
640 let stat;
@@ -485,9 +700,30 @@ async function syncThumbnailCacheOnce ()
485 return;
700 return;
486 }
701 }
487
702
703 if (kind === 'video')
704 {
705 try
706 {
707 await generateVideoThumb(filePath, thumbPath);
708 } catch
709 {
710 return;
711 }
712
713 nextManifest.files[filePath] = {
714 sha256: null,
715 size: stat.size,
716 mtimeMs: stat.mtimeMs,
717 thumbRelPath,
718 kind,
719 };
720 return;
721 }
722
723 // kind === 'model'
488 try
724 try
489 {
725 {
490 await generateVideoThumb(filePath, thumbPath);
726 await generateModelThumb(filePath, thumbPath);
491 } catch
727 } catch
492 {
728 {
493 return;
729 return;
tests/page.load.test.js +5 −6
@@ -908,7 +908,7 @@ describe('page load smoke test', () =>
908 908 dom.window.close();
909 909 });
910 910
911 test('stl tiles use a model thumbnail instead of a badge', async () =>
911 test('stl tiles use a server-generated thumbnail instead of a badge', async () =>
912 912 {
913 913 listFixture = {
914 914 '/data': [
@@ -921,10 +921,8 @@ describe('page load smoke test', () =>
921 921 },
922 922 ],
923 923 };
924 downloadFixture['/data/part.stl'] = {
925 type: 'model/stl',
926 body: 'solid part\nfacet normal 0 0 1\n outer loop\n vertex 0 0 0\n vertex 1 0 0\n vertex 0 1 0\n endloop\nendfacet\nendsolid part\n',
927 };
924 // Thumbnail is served by the server cache endpoint (no client-side geometry parsing).
925 // thumbnailStatusFixture defaults to 200, so the endpoint returns a mock WebP blob.
928 926
929 927 const { dom, runtimeErrors } = await bootClient();
930 928 expect(runtimeErrors).toEqual([]);
@@ -935,7 +933,8 @@ describe('page load smoke test', () =>
935 933 expect(icon).toBeTruthy();
936 934 expect(icon.classList.contains('thumb-pending')).toBe(false);
937 935 expect(icon.dataset.thumbReady).toBe('1');
938 expect(String(icon.querySelector('image').getAttribute('href') || '')).toMatch(/^data:image\/svg\+xml/);
936 // href is a blob URL created from the server-returned WebP
937 expect(String(icon.querySelector('image').getAttribute('href') || '')).toMatch(/^blob:/);
939 938
940 939 dom.window.close();
941 940 });
@@ -908,7 +908,7 @@ describe('page load smoke test', () =>
908 dom.window.close();
908 dom.window.close();
909 });
909 });
910
910
911 test('stl tiles use a model thumbnail instead of a badge', async () =>
911 test('stl tiles use a server-generated thumbnail instead of a badge', async () =>
912 {
912 {
913 listFixture = {
913 listFixture = {
914 '/data': [
914 '/data': [
@@ -921,10 +921,8 @@ describe('page load smoke test', () =>
921 },
921 },
922 ],
922 ],
923 };
923 };
924 downloadFixture['/data/part.stl'] = {
924 // Thumbnail is served by the server cache endpoint (no client-side geometry parsing).
925 type: 'model/stl',
925 // thumbnailStatusFixture defaults to 200, so the endpoint returns a mock WebP blob.
926 body: 'solid part\nfacet normal 0 0 1\n outer loop\n vertex 0 0 0\n vertex 1 0 0\n vertex 0 1 0\n endloop\nendfacet\nendsolid part\n',
927 };
928
926
929 const { dom, runtimeErrors } = await bootClient();
927 const { dom, runtimeErrors } = await bootClient();
930 expect(runtimeErrors).toEqual([]);
928 expect(runtimeErrors).toEqual([]);
@@ -935,7 +933,8 @@ describe('page load smoke test', () =>
935 expect(icon).toBeTruthy();
933 expect(icon).toBeTruthy();
936 expect(icon.classList.contains('thumb-pending')).toBe(false);
934 expect(icon.classList.contains('thumb-pending')).toBe(false);
937 expect(icon.dataset.thumbReady).toBe('1');
935 expect(icon.dataset.thumbReady).toBe('1');
938 expect(String(icon.querySelector('image').getAttribute('href') || '')).toMatch(/^data:image\/svg\+xml/);
936 // href is a blob URL created from the server-returned WebP
937 expect(String(icon.querySelector('image').getAttribute('href') || '')).toMatch(/^blob:/);
939
938
940 dom.window.close();
939 dom.window.close();
941 });
940 });
tests/thumbnail-cache.test.js +35 −0
@@ -244,4 +244,39 @@ describe('thumbnail cache worker', () =>
244 244 expect(ffmpegArgs).toContain('-ss');
245 245 expect(ffmpegArgs).toContain('2.000');
246 246 });
247
248 test('creates cached thumbnail for STL model files using server-side geometry projection', async () =>
249 {
250 const mod = loadModule();
251
252 const stlContent = [
253 'solid test',
254 'facet normal 0 0 1',
255 ' outer loop',
256 ' vertex 0 0 0',
257 ' vertex 1 0 0',
258 ' vertex 0 1 0',
259 ' endloop',
260 'endfacet',
261 'endsolid test',
262 ].join('\n');
263
264 const modelPath = path.join(sourceRoot, 'models', 'part.stl');
265 fs.mkdirSync(path.dirname(modelPath), { recursive: true });
266 fs.writeFileSync(modelPath, stlContent, 'utf8');
267
268 await mod.syncThumbnailCacheOnce();
269
270 const thumbPath = mod.getThumbPathForSourceFile(modelPath);
271 expect(fs.existsSync(thumbPath)).toBe(true);
272
273 const meta = await sharp(thumbPath).metadata();
274 expect(meta.format).toBe('webp');
275 expect(meta.width).toBeLessThanOrEqual(99);
276 expect(meta.height).toBeLessThanOrEqual(99);
277
278 const info = await mod.getCachedThumbnailInfo(modelPath);
279 expect(info).toBeTruthy();
280 expect(info.thumbPath).toBe(thumbPath);
281 });
247 282 });
@@ -244,4 +244,39 @@ describe('thumbnail cache worker', () =>
244 expect(ffmpegArgs).toContain('-ss');
244 expect(ffmpegArgs).toContain('-ss');
245 expect(ffmpegArgs).toContain('2.000');
245 expect(ffmpegArgs).toContain('2.000');
246 });
246 });
247
248 test('creates cached thumbnail for STL model files using server-side geometry projection', async () =>
249 {
250 const mod = loadModule();
251
252 const stlContent = [
253 'solid test',
254 'facet normal 0 0 1',
255 ' outer loop',
256 ' vertex 0 0 0',
257 ' vertex 1 0 0',
258 ' vertex 0 1 0',
259 ' endloop',
260 'endfacet',
261 'endsolid test',
262 ].join('\n');
263
264 const modelPath = path.join(sourceRoot, 'models', 'part.stl');
265 fs.mkdirSync(path.dirname(modelPath), { recursive: true });
266 fs.writeFileSync(modelPath, stlContent, 'utf8');
267
268 await mod.syncThumbnailCacheOnce();
269
270 const thumbPath = mod.getThumbPathForSourceFile(modelPath);
271 expect(fs.existsSync(thumbPath)).toBe(true);
272
273 const meta = await sharp(thumbPath).metadata();
274 expect(meta.format).toBe('webp');
275 expect(meta.width).toBeLessThanOrEqual(99);
276 expect(meta.height).toBeLessThanOrEqual(99);
277
278 const info = await mod.getCachedThumbnailInfo(modelPath);
279 expect(info).toBeTruthy();
280 expect(info.thumbPath).toBe(thumbPath);
281 });
247});
282});