From 2e0e50c3aaa5f3ae6b5ac1335dab56171331d419 Mon Sep 17 00:00:00 2001 From: lrnselfreliance <33263708+lrnselfreliance@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:33:44 -0700 Subject: [PATCH] 3D previews load ASCII STLs, stand upright, and fit the preview modal (#952) * STL files preview with three's own STLLoader react-stl-viewer inlines a copy of three-stdlib 2.17.2's STLLoader, which reads ASCII STL text with LoaderUtils.decodeText. three removed that in r175, so every ASCII STL preview failed. The three-stdlib override never reached that copy, and react-stl-viewer has had no release since January 2024. The 3MF preview's three.js viewer now previews STL files too, loading each format with the loader that ships with three, so the loader always matches the installed three. react-stl-viewer and the three-stdlib override are removed. Co-Authored-By: Claude Opus 5.5 * An e2e spec previews ASCII and binary STL files in a real browser The STL preview only fails in a browser with WebGL, so the spec opens both encodings on the live stack and checks the dimensions line appears without a load error. fb:reset can now write binary files ({base64: ...}). Co-Authored-By: Claude Opus 5.5 * STL previews stand Z-up models upright STLs are Z-up (the 3D printing convention) and three is Y-up, so the preview rotates STL geometry to stand the model upright, as react-stl-viewer did. Model Z reads as Height again. Co-Authored-By: Claude Opus 5.5 * 3MF previews stand Z-up models upright too 3MF is Z-up like STL, so the rotation moves from the STL loader into the shared viewer and applies to every model. Model Z reads as Height. Co-Authored-By: Claude Opus 5.5 * File previews show their buttons without scrolling .preview-fit reserved a fixed 18.75rem for the rest of the preview modal, which was short: every framed preview overflowed a little, and a 3D model's dimensions line pushed the action buttons below the fold. The preview modal now fills its height as a flex column, and the .preview-fit takes whatever height is left. Previews without a .preview-fit keep their content's height. Co-Authored-By: Claude Opus 5.5 * 3D previews frame the model and light it brightly - The camera fits the model's bounding sphere into the narrower field of view, from a raised three-quarter front view, instead of backing off 2.2x along Z. - A hemisphere light and a headlight that follows the camera (from a little above and left) replace lights whose intensities were set before three's r155 lighting change and read dim. - Geometry without normals (3MF) gets creased normals, so flat faces no longer shade into their neighbors. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- app/cypress.config.js | 7 +- app/cypress/e2e/files/stl-preview.cy.js | 89 ++++++ app/jest/babelTransform.js | 4 +- app/package-lock.json | 393 ------------------------ app/package.json | 6 +- app/src/App.css | 35 ++- app/src/components/FilePreview.js | 137 +++++---- app/src/components/ModelPreview.test.js | 179 +++++++++++ app/src/components/STLLoader.test.js | 41 --- app/src/setupTests.js | 5 - 10 files changed, 388 insertions(+), 508 deletions(-) create mode 100644 app/cypress/e2e/files/stl-preview.cy.js create mode 100644 app/src/components/ModelPreview.test.js delete mode 100644 app/src/components/STLLoader.test.js diff --git a/app/cypress.config.js b/app/cypress.config.js index 1e57b0e4..325d913c 100644 --- a/app/cypress.config.js +++ b/app/cypress.config.js @@ -22,9 +22,14 @@ function sandboxPath(relativePath) { return resolved; } +function fileContent(content) { + return content && content.base64 !== undefined ? Buffer.from(content.base64, "base64") : (content ?? ""); +} + const fileBrowserTasks = { // Wipe the sandbox (including leftovers from a crashed run) and create the given files. // `files` maps sandbox-relative paths to file content; a trailing '/' makes a bare directory. + // Content is text, or `{base64: '...'}` for a binary file. "fb:reset": ({ files }) => { fs.rmSync(SANDBOX_DIR, { recursive: true, force: true }); fs.mkdirSync(SANDBOX_DIR, { recursive: true }); @@ -34,7 +39,7 @@ const fileBrowserTasks = { } else { const filePath = sandboxPath(relativePath); fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, content ?? ""); + fs.writeFileSync(filePath, fileContent(content)); } } return SANDBOX_NAME; diff --git a/app/cypress/e2e/files/stl-preview.cy.js b/app/cypress/e2e/files/stl-preview.cy.js new file mode 100644 index 00000000..2595eaaa --- /dev/null +++ b/app/cypress/e2e/files/stl-preview.cy.js @@ -0,0 +1,89 @@ +/* + * Previewing STL files, exercised against the live stack in a real browser (WebGL). + * + * An STL is either ASCII text or binary. Both must load in the preview: the dimensions line + * is only shown after the model has been parsed and framed, and a load failure is shown as an + * error (or thrown, which fails the test). + */ +import {assertWROLModeOff, SANDBOX, teardownFileBrowser} from '../../support/file-browser'; + +// One right triangle, legs of 2 along X and 1 along Y. +const ASCII_STL = `solid ASCII + facet normal 0 0 1 + outer loop + vertex 0 0 0 + vertex 2 0 0 + vertex 0 1 0 + endloop + endfacet +endsolid +`; + +function binaryStlBase64() { + // 80-byte header, uint32 triangle count, then one 50-byte triangle: normal, three vertices. + const buffer = new ArrayBuffer(84 + 50); + const view = new DataView(buffer); + view.setUint32(80, 1, true); + const floats = [0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0]; + floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true)); + return Cypress.Buffer.from(buffer).toString('base64'); +} + +// Requires the full stack (API + real media directory); CI runs only the React dev server. +(Cypress.env('CI') ? describe.skip : describe)('STL preview', () => { + + before(() => { + assertWROLModeOff(); + cy.task('fb:reset', { + files: { + 'ascii.stl': ASCII_STL, + 'binary.stl': {base64: binaryStlBase64()}, + }, + }); + cy.refreshFiles([SANDBOX]); + }); + + after(() => { + teardownFileBrowser(); + }); + + const openPreview = (name) => { + const params = new URLSearchParams({folders: `${SANDBOX}/`, preview: `${SANDBOX}/${name}`}); + cy.visit(`/files?${params}`); + cy.get('[role="dialog"]').should('contain', name); + }; + + const expectTriangleDimensions = () => { + // The triangle is 2 wide along X, which only a parsed model can report. Which axis + // reads as Height or Length depends on how the viewer orients the model, so only + // Width is asserted. + cy.get('[role="dialog"]').contains('Width:', {timeout: 20000}).parent() + .should('contain', 'Width: 2.00'); + cy.get('[role="dialog"]').should('not.contain', 'Failed to'); + }; + + it('previews an ASCII STL file', () => { + openPreview('ascii.stl'); + expectTriangleDimensions(); + }); + + it('previews a binary STL file', () => { + openPreview('binary.stl'); + expectTriangleDimensions(); + }); + + it('shows the action buttons without scrolling the preview', () => { + cy.viewport(1280, 720); + openPreview('binary.stl'); + // The dimensions line is the last thing the preview adds, so the layout is final. + expectTriangleDimensions(); + cy.get('.mantine-Modal-content').should(([content]) => { + expect(content.scrollHeight, 'preview modal content scrolls') + .to.be.at.most(content.clientHeight); + }); + cy.get('.wrolpi-modal-actions').should(([actions]) => { + expect(actions.getBoundingClientRect().bottom, 'action buttons bottom edge') + .to.be.at.most(actions.ownerDocument.defaultView.innerHeight); + }); + }); +}); diff --git a/app/jest/babelTransform.js b/app/jest/babelTransform.js index bd82e2b5..07e51c1d 100644 --- a/app/jest/babelTransform.js +++ b/app/jest/babelTransform.js @@ -1,6 +1,6 @@ 'use strict'; -// Replaces CRA's JS transform so Jest can load three.js. three (and three-stdlib) ship ES modules +// Replaces CRA's JS transform so Jest can load three.js. three ships ES modules // with static class blocks, which babel-preset-react-app's class-properties plugin rejects at our // pinned Babel version. Those files only need their imports converted to CommonJS; every other // file goes through CRA's transform unchanged. @@ -13,7 +13,7 @@ const threeTransform = babelJest.createTransformer({ plugins: [require.resolve('@babel/plugin-transform-modules-commonjs')], }); -const THREE_PATH = /[\\/]node_modules[\\/]three(-stdlib)?[\\/]/; +const THREE_PATH = /[\\/]node_modules[\\/]three[\\/]/; function pick(sourcePath) { return THREE_PATH.test(sourcePath) ? threeTransform : craTransform; diff --git a/app/package-lock.json b/app/package-lock.json index 84c29e38..59dff7fa 100644 --- a/app/package-lock.json +++ b/app/package-lock.json @@ -35,7 +35,6 @@ "react-qr-code": "^2.2.0", "react-router": "^7.18.5", "react-scripts": "5.0.1", - "react-stl-viewer": "^2.5.0", "three": "^0.186", "web-vitals": "^6.2.3" }, @@ -5446,62 +5445,6 @@ "url": "https://opencollective.com/webpack" } }, - "node_modules/@react-three/fiber": { - "version": "8.16.5", - "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.16.5.tgz", - "integrity": "sha512-ALRkdZj57mxgbvTHcSmepslgeWM0FXBMyII6l3gDodKhCLp3KRPXVOXKMo4jh7VhwTdYtEZeidkldYZtLSgnCw==", - "dependencies": { - "@babel/runtime": "^7.17.8", - "@types/react-reconciler": "^0.26.7", - "@types/webxr": "*", - "base64-js": "^1.5.1", - "buffer": "^6.0.3", - "its-fine": "^1.0.6", - "react-reconciler": "^0.27.0", - "react-use-measure": "^2.1.1", - "scheduler": "^0.21.0", - "suspend-react": "^0.1.3", - "zustand": "^3.7.1" - }, - "peerDependencies": { - "expo": ">=43.0", - "expo-asset": ">=8.4", - "expo-file-system": ">=11.0", - "expo-gl": ">=11.0", - "react": ">=18.0", - "react-dom": ">=18.0", - "react-native": ">=0.64", - "three": ">=0.133" - }, - "peerDependenciesMeta": { - "expo": { - "optional": true - }, - "expo-asset": { - "optional": true - }, - "expo-file-system": { - "optional": true - }, - "expo-gl": { - "optional": true - }, - "react-dom": { - "optional": true - }, - "react-native": { - "optional": true - } - } - }, - "node_modules/@react-three/fiber/node_modules/scheduler": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz", - "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==", - "dependencies": { - "loose-envify": "^1.1.0" - } - }, "node_modules/@rollup/plugin-babel": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz", @@ -6306,12 +6249,6 @@ "@types/node": "*" } }, - "node_modules/@types/draco3d": { - "version": "1.4.10", - "resolved": "https://registry.npmjs.org/@types/draco3d/-/draco3d-1.4.10.tgz", - "integrity": "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==", - "license": "MIT" - }, "node_modules/@types/eslint": { "version": "8.4.10", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.10.tgz", @@ -6452,11 +6389,6 @@ "@types/node": "*" } }, - "node_modules/@types/offscreencanvas": { - "version": "2019.7.0", - "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.0.tgz", - "integrity": "sha512-PGcyveRIpL1XIqK8eBsmRBt76eFgtzuPiSTyKHZxnGemp2yzGzWpjYKAfK3wIMiU7eH+851yEpiuP8JZerTmWg==" - }, "node_modules/@types/parse-json": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", @@ -6507,14 +6439,6 @@ "@types/react": "^18.0.0" } }, - "node_modules/@types/react-reconciler": { - "version": "0.26.7", - "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.26.7.tgz", - "integrity": "sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==", - "dependencies": { - "@types/react": "*" - } - }, "node_modules/@types/resolve": { "version": "1.17.1", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz", @@ -6610,11 +6534,6 @@ "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", "license": "MIT" }, - "node_modules/@types/webxr": { - "version": "0.5.16", - "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.16.tgz", - "integrity": "sha512-0E0Cl84FECtzrB4qG19TNTqpunw0F1YF0QZZnFMF6pDw1kNKJtrlTKlVB34stGIsHbZsYQ7H0tNjPfZftkHHoA==" - }, "node_modules/@types/ws": { "version": "8.18.1", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", @@ -8106,29 +8025,6 @@ "node-int64": "^0.4.0" } }, - "node_modules/buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, "node_modules/buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -9483,11 +9379,6 @@ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==" }, - "node_modules/debounce": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/debounce/-/debounce-1.2.1.tgz", - "integrity": "sha512-XRRe6Glud4rd/ZGQfiV1ruXSfbvfJedlV9Y6zOlP+2K04vBYiJEte6stfFkCP03aMnY5tsipamumUjL14fofug==" - }, "node_modules/debug": { "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", @@ -9916,11 +9807,6 @@ "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-5.1.0.tgz", "integrity": "sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA==" }, - "node_modules/draco3d": { - "version": "1.5.6", - "resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.6.tgz", - "integrity": "sha512-+3NaRjWktb5r61ZFoDejlykPEFKT5N/LkbXsaddlw6xNSXBanUYpFc2AXXpbJDilPHazcSreU/DpQIaxfX0NfQ==" - }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -11258,12 +11144,6 @@ "bser": "2.1.1" } }, - "node_modules/fflate": { - "version": "0.6.11", - "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.6.11.tgz", - "integrity": "sha512-3JyEFWGjFn7zHmoa9+zG1BmW7X2okcmAB+0Cnu9UFbVs/jCBnl2A8o065ZlXiw145K3eBM3uLuzrYXC0RK7eDg==", - "license": "MIT" - }, "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -13215,25 +13095,6 @@ "node": ">=8" } }, - "node_modules/its-fine": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/its-fine/-/its-fine-1.2.5.tgz", - "integrity": "sha512-fXtDA0X0t0eBYAGLVM5YsgJGsJ5jEmqZEPrGbzdf5awjv0xE7nqv3TVnvtUF060Tkes15DbDAKW/I48vsb6SyA==", - "dependencies": { - "@types/react-reconciler": "^0.28.0" - }, - "peerDependencies": { - "react": ">=18.0" - } - }, - "node_modules/its-fine/node_modules/@types/react-reconciler": { - "version": "0.28.8", - "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.8.tgz", - "integrity": "sha512-SN9c4kxXZonFhbX4hJrZy37yw9e7EIxcpHCxQv5JUS18wDE5ovkQKlqQEkufdJCCMfuI9BnjUJvhYeJ9x5Ra7g==", - "dependencies": { - "@types/react": "*" - } - }, "node_modules/jake": { "version": "10.9.4", "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", @@ -18265,11 +18126,6 @@ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" }, - "node_modules/potpack": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz", - "integrity": "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==" - }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -18855,29 +18711,6 @@ "react": "*" } }, - "node_modules/react-reconciler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.27.0.tgz", - "integrity": "sha512-HmMDKciQjYmBRGuuhIaKA1ba/7a+UsM5FzOZsMO2JYHt9Jh8reCb7j1eDC95NOyUlKM9KRyvdx0flBuDvYSBoA==", - "dependencies": { - "loose-envify": "^1.1.0", - "scheduler": "^0.21.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "peerDependencies": { - "react": "^18.0.0" - } - }, - "node_modules/react-reconciler/node_modules/scheduler": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz", - "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==", - "dependencies": { - "loose-envify": "^1.1.0" - } - }, "node_modules/react-refresh": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz", @@ -19224,20 +19057,6 @@ } } }, - "node_modules/react-stl-viewer": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/react-stl-viewer/-/react-stl-viewer-2.5.0.tgz", - "integrity": "sha512-jlYId05N0P9rKVEdOfLO1bPsS9SYfMRxjnKvhks6T/c4HU0BxnNcZpRr4gfpJU0nFL6HHgmVKhKTh1LCHNcZuA==", - "dependencies": { - "@react-three/fiber": "^8.15.5", - "three-stdlib": "2.17.2" - }, - "peerDependencies": { - "react": ">=18.0", - "react-dom": ">=18.0", - "three": ">=0.154" - } - }, "node_modules/react-style-singleton": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", @@ -19293,18 +19112,6 @@ "react-dom": ">=16.6.0" } }, - "node_modules/react-use-measure": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.1.tgz", - "integrity": "sha512-nocZhN26cproIiIduswYpV5y5lQpSQS1y/4KuvUCjSKmw7ZWIS/+g3aFnX3WdBkyuGUtTLif3UTqnLLhbDoQig==", - "dependencies": { - "debounce": "^1.2.1" - }, - "peerDependencies": { - "react": ">=16.13", - "react-dom": ">=16.13" - } - }, "node_modules/read-cache": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", @@ -20764,14 +20571,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/suspend-react": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/suspend-react/-/suspend-react-0.1.3.tgz", - "integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==", - "peerDependencies": { - "react": ">=17.0" - } - }, "node_modules/svg-parser": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/svg-parser/-/svg-parser-2.0.4.tgz", @@ -21176,23 +20975,6 @@ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==", "license": "MIT" }, - "node_modules/three-stdlib": { - "version": "2.36.1", - "resolved": "https://registry.npmjs.org/three-stdlib/-/three-stdlib-2.36.1.tgz", - "integrity": "sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==", - "license": "MIT", - "dependencies": { - "@types/draco3d": "^1.4.0", - "@types/offscreencanvas": "^2019.6.4", - "@types/webxr": "^0.5.2", - "draco3d": "^1.4.1", - "fflate": "^0.6.9", - "potpack": "^1.0.1" - }, - "peerDependencies": { - "three": ">=0.128.0" - } - }, "node_modules/throat": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.2.tgz", @@ -23058,22 +22840,6 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } - }, - "node_modules/zustand": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-3.7.2.tgz", - "integrity": "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==", - "engines": { - "node": ">=12.7.0" - }, - "peerDependencies": { - "react": ">=16.8" - }, - "peerDependenciesMeta": { - "react": { - "optional": true - } - } } }, "dependencies": { @@ -26694,34 +26460,6 @@ } } }, - "@react-three/fiber": { - "version": "8.16.5", - "resolved": "https://registry.npmjs.org/@react-three/fiber/-/fiber-8.16.5.tgz", - "integrity": "sha512-ALRkdZj57mxgbvTHcSmepslgeWM0FXBMyII6l3gDodKhCLp3KRPXVOXKMo4jh7VhwTdYtEZeidkldYZtLSgnCw==", - "requires": { - "@babel/runtime": "^7.17.8", - "@types/react-reconciler": "^0.26.7", - "@types/webxr": "*", - "base64-js": "^1.5.1", - "buffer": "^6.0.3", - "its-fine": "^1.0.6", - "react-reconciler": "^0.27.0", - "react-use-measure": "^2.1.1", - "scheduler": "^0.21.0", - "suspend-react": "^0.1.3", - "zustand": "^3.7.1" - }, - "dependencies": { - "scheduler": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz", - "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==", - "requires": { - "loose-envify": "^1.1.0" - } - } - } - }, "@rollup/plugin-babel": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/@rollup/plugin-babel/-/plugin-babel-5.3.1.tgz", @@ -27271,11 +27009,6 @@ "@types/node": "*" } }, - "@types/draco3d": { - "version": "1.4.10", - "resolved": "https://registry.npmjs.org/@types/draco3d/-/draco3d-1.4.10.tgz", - "integrity": "sha512-AX22jp8Y7wwaBgAixaSvkoG4M/+PlAcm3Qs4OW8yT9DM4xUpWKeFhLueTAyZF39pviAdcDdeJoACapiAceqNcw==" - }, "@types/eslint": { "version": "8.4.10", "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.4.10.tgz", @@ -27409,11 +27142,6 @@ "@types/node": "*" } }, - "@types/offscreencanvas": { - "version": "2019.7.0", - "resolved": "https://registry.npmjs.org/@types/offscreencanvas/-/offscreencanvas-2019.7.0.tgz", - "integrity": "sha512-PGcyveRIpL1XIqK8eBsmRBt76eFgtzuPiSTyKHZxnGemp2yzGzWpjYKAfK3wIMiU7eH+851yEpiuP8JZerTmWg==" - }, "@types/parse-json": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.0.tgz", @@ -27459,14 +27187,6 @@ "integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==", "requires": {} }, - "@types/react-reconciler": { - "version": "0.26.7", - "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.26.7.tgz", - "integrity": "sha512-mBDYl8x+oyPX/VBb3E638N0B7xG+SPk/EAMcVPeexqus/5aTpTphQi0curhhshOqRrc9t6OPoJfEUkbymse/lQ==", - "requires": { - "@types/react": "*" - } - }, "@types/resolve": { "version": "1.17.1", "resolved": "https://registry.npmjs.org/@types/resolve/-/resolve-1.17.1.tgz", @@ -27554,11 +27274,6 @@ "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==" }, - "@types/webxr": { - "version": "0.5.16", - "resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.16.tgz", - "integrity": "sha512-0E0Cl84FECtzrB4qG19TNTqpunw0F1YF0QZZnFMF6pDw1kNKJtrlTKlVB34stGIsHbZsYQ7H0tNjPfZftkHHoA==" - }, "@types/ws": { "version": "8.18.1", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", @@ -28619,15 +28334,6 @@ "node-int64": "^0.4.0" } }, - "buffer": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-6.0.3.tgz", - "integrity": "sha512-FTiCpNxtwiZZHEZbcbTIcZjERVICn9yq/pDFkTl95/AxzD1naBctN7YO68riM/gLSDY7sdrMby8hofADYuuqOA==", - "requires": { - "base64-js": "^1.3.1", - "ieee754": "^1.2.1" - } - }, "buffer-from": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", @@ -29553,11 +29259,6 @@ "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.13.tgz", "integrity": "sha512-oaMBel6gjolK862uaPQOVTA7q3TZhuSvuMQAAglQDOWYO9A91IrAOUJEyKVlqJlHE0vq5p5UXxzdPfMH/x6xNg==" }, - "debounce": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/debounce/-/debounce-1.2.1.tgz", - "integrity": "sha512-XRRe6Glud4rd/ZGQfiV1ruXSfbvfJedlV9Y6zOlP+2K04vBYiJEte6stfFkCP03aMnY5tsipamumUjL14fofug==" - }, "debug": { "version": "4.3.4", "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", @@ -29868,11 +29569,6 @@ "resolved": "https://registry.npmjs.org/dotenv-expand/-/dotenv-expand-5.1.0.tgz", "integrity": "sha512-YXQl1DSa4/PQyRfgrv6aoNjhasp/p4qs9FjJ4q4cQk+8m4r6k4ZSiEyytKG8f8W9gi8WsQtIObNmKd+tMzNTmA==" }, - "draco3d": { - "version": "1.5.6", - "resolved": "https://registry.npmjs.org/draco3d/-/draco3d-1.5.6.tgz", - "integrity": "sha512-+3NaRjWktb5r61ZFoDejlykPEFKT5N/LkbXsaddlw6xNSXBanUYpFc2AXXpbJDilPHazcSreU/DpQIaxfX0NfQ==" - }, "dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -30855,11 +30551,6 @@ "bser": "2.1.1" } }, - "fflate": { - "version": "0.6.11", - "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.6.11.tgz", - "integrity": "sha512-3JyEFWGjFn7zHmoa9+zG1BmW7X2okcmAB+0Cnu9UFbVs/jCBnl2A8o065ZlXiw145K3eBM3uLuzrYXC0RK7eDg==" - }, "file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -32168,24 +31859,6 @@ "istanbul-lib-report": "^3.0.0" } }, - "its-fine": { - "version": "1.2.5", - "resolved": "https://registry.npmjs.org/its-fine/-/its-fine-1.2.5.tgz", - "integrity": "sha512-fXtDA0X0t0eBYAGLVM5YsgJGsJ5jEmqZEPrGbzdf5awjv0xE7nqv3TVnvtUF060Tkes15DbDAKW/I48vsb6SyA==", - "requires": { - "@types/react-reconciler": "^0.28.0" - }, - "dependencies": { - "@types/react-reconciler": { - "version": "0.28.8", - "resolved": "https://registry.npmjs.org/@types/react-reconciler/-/react-reconciler-0.28.8.tgz", - "integrity": "sha512-SN9c4kxXZonFhbX4hJrZy37yw9e7EIxcpHCxQv5JUS18wDE5ovkQKlqQEkufdJCCMfuI9BnjUJvhYeJ9x5Ra7g==", - "requires": { - "@types/react": "*" - } - } - } - }, "jake": { "version": "10.9.4", "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", @@ -35583,11 +35256,6 @@ "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==" }, - "potpack": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/potpack/-/potpack-1.0.2.tgz", - "integrity": "sha512-choctRBIV9EMT9WGAZHn3V7t0Z2pMQyl0EZE6pFc/6ml3ssw7Dlf/oAOvFwjm1HVsqfQN8GfeFyJ+d8tRzqueQ==" - }, "prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -36008,25 +35676,6 @@ "qrcode-generator": "^2.0.4" } }, - "react-reconciler": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.27.0.tgz", - "integrity": "sha512-HmMDKciQjYmBRGuuhIaKA1ba/7a+UsM5FzOZsMO2JYHt9Jh8reCb7j1eDC95NOyUlKM9KRyvdx0flBuDvYSBoA==", - "requires": { - "loose-envify": "^1.1.0", - "scheduler": "^0.21.0" - }, - "dependencies": { - "scheduler": { - "version": "0.21.0", - "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.21.0.tgz", - "integrity": "sha512-1r87x5fz9MXqswA2ERLo0EbOAU74DpIUO090gIasYTqlVoJeMcl+Z1Rg7WHz+qtPujhS/hGIt9kxZOYBV3faRQ==", - "requires": { - "loose-envify": "^1.1.0" - } - } - } - }, "react-refresh": { "version": "0.11.0", "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.11.0.tgz", @@ -36239,15 +35888,6 @@ } } }, - "react-stl-viewer": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/react-stl-viewer/-/react-stl-viewer-2.5.0.tgz", - "integrity": "sha512-jlYId05N0P9rKVEdOfLO1bPsS9SYfMRxjnKvhks6T/c4HU0BxnNcZpRr4gfpJU0nFL6HHgmVKhKTh1LCHNcZuA==", - "requires": { - "@react-three/fiber": "^8.15.5", - "three-stdlib": "2.36.1" - } - }, "react-style-singleton": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/react-style-singleton/-/react-style-singleton-2.2.3.tgz", @@ -36278,14 +35918,6 @@ "prop-types": "^15.6.2" } }, - "react-use-measure": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.1.tgz", - "integrity": "sha512-nocZhN26cproIiIduswYpV5y5lQpSQS1y/4KuvUCjSKmw7ZWIS/+g3aFnX3WdBkyuGUtTLif3UTqnLLhbDoQig==", - "requires": { - "debounce": "^1.2.1" - } - }, "read-cache": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.0.tgz", @@ -37321,12 +36953,6 @@ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==" }, - "suspend-react": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/suspend-react/-/suspend-react-0.1.3.tgz", - "integrity": "sha512-aqldKgX9aZqpoDp3e8/BZ8Dm7x1pJl+qI3ZKxDN0i/IQTWUwBx/ManmlVJ3wowqbno6c2bmiIfs+Um6LbsjJyQ==", - "requires": {} - }, "svg-parser": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/svg-parser/-/svg-parser-2.0.4.tgz", @@ -37585,19 +37211,6 @@ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz", "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==" }, - "three-stdlib": { - "version": "2.36.1", - "resolved": "https://registry.npmjs.org/three-stdlib/-/three-stdlib-2.36.1.tgz", - "integrity": "sha512-XyGQrFmNQ5O/IoKm556ftwKsBg11TIb301MB5dWNicziQBEs2g3gtOYIf7pFiLa0zI2gUwhtCjv9fmjnxKZ1Cg==", - "requires": { - "@types/draco3d": "^1.4.0", - "@types/offscreencanvas": "^2019.6.4", - "@types/webxr": "^0.5.2", - "draco3d": "^1.4.1", - "fflate": "^0.6.9", - "potpack": "^1.0.1" - } - }, "throat": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/throat/-/throat-6.0.2.tgz", @@ -38927,12 +38540,6 @@ "version": "0.1.0", "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==" - }, - "zustand": { - "version": "3.7.2", - "resolved": "https://registry.npmjs.org/zustand/-/zustand-3.7.2.tgz", - "integrity": "sha512-PIJDIZKtokhof+9+60cpockVOq05sJzHCriyvaLBmEJixseQ1a5Kdov6fWZfWOu5SK9c+FhH1jU0tntLxRJYMA==", - "requires": {} } } } diff --git a/app/package.json b/app/package.json index cc62d915..22790335 100644 --- a/app/package.json +++ b/app/package.json @@ -30,7 +30,6 @@ "react-qr-code": "^2.2.0", "react-router": "^7.18.5", "react-scripts": "5.0.1", - "react-stl-viewer": "^2.5.0", "three": "^0.186", "web-vitals": "^6.2.3" }, @@ -74,7 +73,7 @@ "^.+\\.(js|jsx|mjs|cjs|ts|tsx)$": "/jest/babelTransform.js" }, "transformIgnorePatterns": [ - "node_modules/(?!(react-hotkeys-hook|three|three-stdlib)/)" + "node_modules/(?!(react-hotkeys-hook|three)/)" ] }, "overrides": { @@ -97,7 +96,6 @@ "fork-ts-checker-webpack-plugin": "^6.5.3", "react-scripts": { "typescript": "$typescript" - }, - "three-stdlib": "2.36.1" + } } } diff --git a/app/src/App.css b/app/src/App.css index 6b423219..0286fa80 100644 --- a/app/src/App.css +++ b/app/src/App.css @@ -293,9 +293,8 @@ pre.wrap-text { } } -/* Caps preview content to fit inside the file-preview Modal. - 300px reserves room for pathContent
, Modal.Header, Modal.Actions row,
-   inner content (e.g. STL dimensions banner), and modal padding.
+/* Caps preview content to fit inside a Modal (e.g. the Zim entry preview): 18.75rem is a guess at
+   everything else in the modal.  The file-preview Modal does not guess; see below.
    Use 100dvh so mobile browser chrome (URL bar) is accounted for. */
 .preview-fit {
     width: 100%;
@@ -309,6 +308,36 @@ pre.wrap-text {
     justify-content: center;
 }
 
+/* In the file-preview Modal, a .preview-fit takes whatever height the rest of the modal leaves
+   (path, header, a 3D model's dimensions line, the action buttons however they wrap) rather
+   than reserving a fixed amount, so the buttons are always on screen without scrolling.
+   The modal fills Mantine's maximum height only when it frames a .preview-fit; other previews
+   keep the height of their content. */
+.file-preview-modal-content:has(.preview-fit) {
+    height: calc(100dvh - var(--modal-y-offset) * 2);
+    display: flex;
+    flex-direction: column;
+}
+
+.file-preview-modal-content:has(.preview-fit) > .mantine-Modal-header {
+    flex: none;
+}
+
+.file-preview-modal-content:has(.preview-fit) > .mantine-Modal-body {
+    flex: 1 1 auto;
+    min-height: 0;
+    display: flex;
+    flex-direction: column;
+}
+
+/* The .preview-fit (a direct child of the body: MediaGate renders fragments) takes the leftover
+   height.  The other children keep theirs: a flex item never shrinks below its content. */
+.file-preview-modal-content .preview-fit {
+    flex: 1 1 0;
+    height: auto;
+    max-height: none;
+}
+
 /* Fresnel (Media) wraps iframes in a div which would otherwise shrink to the
    default iframe size; make it fill the preview so the iframe's 100% works. */
 .preview-fit .fresnel-container {
diff --git a/app/src/components/FilePreview.js b/app/src/components/FilePreview.js
index 8f343a14..1dcc8906 100644
--- a/app/src/components/FilePreview.js
+++ b/app/src/components/FilePreview.js
@@ -5,7 +5,6 @@ import {encodeMediaPath, isSupportedArchive, useLocalStorage} from "./Common";
 import {getFile, tagFileGroup, untagFileGroup} from "../api";
 import {ArchivePreviewContent} from "./ArchivePreview";
 import {CbzViewer} from "./CbzViewer";
-import {StlViewer} from "react-stl-viewer";
 import {Button, ButtonGroup, Header, Icon, IconButton, MediaGate, Menu, Modal, toast} from "./ui";
 import {useOneQuery} from "../hooks/customHooks";
 import {useEpubProgress, useMediaProgress} from "../hooks/useFileProgress";
@@ -218,7 +217,36 @@ function getAudioPreviewModal(previewFile) {
     
 }
 
-function ThreeMFPreviewModal({previewFile}) {
+// Each 3D format's loader ships with three, so it always matches the installed three.  Every
+// format is Z-up.
+const MODEL_FORMATS = {
+    '3mf': {
+        label: '3MF',
+        loader: async () => new (await import('three/examples/jsm/loaders/3MFLoader.js')).ThreeMFLoader(),
+        // A 3MF loads as a group of meshes.
+        toObject: (THREE, group) => group,
+    },
+    stl: {
+        label: 'STL',
+        loader: async () => new (await import('three/examples/jsm/loaders/STLLoader.js')).STLLoader(),
+        // An STL loads as a single geometry.
+        toObject: (THREE, geometry) => new THREE.Mesh(geometry),
+    },
+};
+
+/**
+ * How far a camera must stand from a sphere of `radius` for the whole sphere to be in view, with
+ * `margin` to spare.  The narrower of the vertical and horizontal fields of view decides: a tall,
+ * narrow viewer is limited by its width.
+ */
+export function modelCameraDistance(radius, verticalFovDegrees, aspect, margin = 1.02) {
+    const halfVertical = (verticalFovDegrees * Math.PI) / 360;
+    const halfHorizontal = Math.atan(Math.tan(halfVertical) * aspect);
+    return (radius / Math.sin(Math.min(halfVertical, halfHorizontal))) * margin;
+}
+
+function ModelPreviewModal({previewFile, format}) {
+    const {label, loader: getLoader, toObject} = MODEL_FORMATS[format];
     const containerRef = React.useRef(null);
     const [dimensions, setDimensions] = React.useState(null);
     const [error, setError] = React.useState(null);
@@ -227,7 +255,7 @@ function ThreeMFPreviewModal({previewFile}) {
     const name = path.replace(/^.*[\\\/]/, '');
 
     React.useEffect(() => {
-        // Imperative three.js viewer — mirrors react-stl-viewer behavior for .3mf files.
+        // Imperative three.js viewer.
         let cancelled = false;
         const container = containerRef.current;
         if (!container) return;
@@ -239,12 +267,12 @@ function ThreeMFPreviewModal({previewFile}) {
             try {
                 THREE = await import('three');
                 const {OrbitControls} = await import('three/examples/jsm/controls/OrbitControls.js');
-                const {ThreeMFLoader} = await import('three/examples/jsm/loaders/3MFLoader.js');
+                const {toCreasedNormals} = await import('three/examples/jsm/utils/BufferGeometryUtils.js');
+                const loader = await getLoader();
                 if (cancelled) return;
 
                 scene = new THREE.Scene();
-                // Transparent background so the modal/theme color shows through,
-                // matching react-stl-viewer's behavior.
+                // Transparent background so the modal/theme color shows through.
 
                 const width = container.clientWidth || 1;
                 const height = container.clientHeight || 1;
@@ -258,32 +286,40 @@ function ThreeMFPreviewModal({previewFile}) {
                 renderer.setSize(width, height);
                 container.appendChild(renderer.domElement);
 
-                scene.add(new THREE.AmbientLight(0xffffff, 0.6));
-                const dirLight = new THREE.DirectionalLight(0xffffff, 0.8);
-                dirLight.position.set(1, 1, 1);
-                scene.add(dirLight);
-                const dirLight2 = new THREE.DirectionalLight(0xffffff, 0.4);
-                dirLight2.position.set(-1, -1, -1);
-                scene.add(dirLight2);
+                // Sky above, darker ground below, so top and bottom read differently.  The headlight
+                // follows the camera, so whichever side the user orbits to is lit; it shines from a
+                // little above and left of the camera so faces turned toward the viewer still shade
+                // differently.
+                scene.add(new THREE.HemisphereLight(0xffffff, 0x404040, 2));
+                const headlight = new THREE.DirectionalLight(0xffffff, 2.5);
+                scene.add(headlight);
+                const headlightOffset = new THREE.Vector3();
 
                 controls = new OrbitControls(camera, renderer.domElement);
                 controls.enableDamping = true;
 
-                const loader = new ThreeMFLoader();
                 loader.load(
                     url,
-                    (group) => {
+                    (result) => {
                         if (cancelled) return;
+                        const group = toObject(THREE, result);
                         loadedGroup = group;
+                        // STL and 3MF are Z-up (the 3D printing convention) and three is Y-up, so
+                        // stand the model upright: model Z reads as Height, model Y as Length.
+                        group.rotation.x = -Math.PI / 2;
 
-                        // Match react-stl-viewer's violet so 3MFs without authored
-                        // materials are visible against either theme's background.
-                        // 3MF geometry often lacks vertex normals — compute them so
+                        // One violet for every model, so models without authored materials
+                        // are visible against either theme's background.
+                        // Geometry may lack vertex normals (3MF stores none) — compute them so
                         // MeshPhongMaterial can shade faces instead of rendering flat black.
+                        // Creased: curves are smoothed, but an edge sharper than 30 degrees stays
+                        // sharp, so flat faces do not shade into their neighbors.
                         group.traverse((obj) => {
                             if (obj.isMesh) {
                                 if (obj.geometry && !obj.geometry.attributes.normal) {
-                                    obj.geometry.computeVertexNormals();
+                                    const creased = toCreasedNormals(obj.geometry, Math.PI / 6);
+                                    obj.geometry.dispose();
+                                    obj.geometry = creased;
                                 }
                                 obj.material = new THREE.MeshPhongMaterial({
                                     color: 0x7353a8,
@@ -294,7 +330,9 @@ function ThreeMFPreviewModal({previewFile}) {
 
                         scene.add(group);
 
-                        // Frame the model: center it, then pull camera back along Z by bounding radius.
+                        // Frame the model: center it, then view it from the front, raised and a little
+                        // to the right, far enough back that its bounding sphere (every point of it)
+                        // fills the viewer.
                         const box = new THREE.Box3().setFromObject(group);
                         const size = new THREE.Vector3();
                         const center = new THREE.Vector3();
@@ -302,11 +340,11 @@ function ThreeMFPreviewModal({previewFile}) {
                         box.getCenter(center);
                         group.position.sub(center);
 
-                        const boundingRadius = Math.max(size.x, size.y, size.z) / 2 || 1;
-                        const fitDistance = boundingRadius / Math.tan((Math.PI * camera.fov) / 360);
-                        camera.position.set(0, 0, fitDistance * 2.2);
-                        camera.near = Math.max(0.1, fitDistance / 1000);
-                        camera.far = fitDistance * 100;
+                        const boundingRadius = size.length() / 2 || 1;
+                        const distance = modelCameraDistance(boundingRadius, camera.fov, camera.aspect);
+                        camera.position.set(0.6, 0.5, 1).normalize().multiplyScalar(distance);
+                        camera.near = distance / 100;
+                        camera.far = distance * 100;
                         camera.updateProjectionMatrix();
                         controls.target.set(0, 0, 0);
                         controls.update();
@@ -320,14 +358,17 @@ function ThreeMFPreviewModal({previewFile}) {
                     },
                     undefined,
                     (err) => {
-                        console.error('Failed to load 3MF', err);
-                        if (!cancelled) setError('Failed to load 3MF file.');
+                        console.error(`Failed to load ${label}`, err);
+                        if (!cancelled) setError(`Failed to load ${label} file.`);
                     },
                 );
 
                 const animate = () => {
                     animationId = requestAnimationFrame(animate);
                     controls.update();
+                    headlightOffset.set(-0.4, 0.6, 0).applyQuaternion(camera.quaternion)
+                        .multiplyScalar(camera.position.length());
+                    headlight.position.copy(camera.position).add(headlightOffset);
                     renderer.render(scene, camera);
                 };
                 animate();
@@ -341,8 +382,8 @@ function ThreeMFPreviewModal({previewFile}) {
                 });
                 resizeObserver.observe(container);
             } catch (err) {
-                console.error('3MF viewer init failed', err);
-                if (!cancelled) setError('Failed to initialize 3MF viewer.');
+                console.error(`${label} viewer init failed`, err);
+                if (!cancelled) setError(`Failed to initialize ${label} viewer.`);
             }
         })();
 
@@ -370,7 +411,7 @@ function ThreeMFPreviewModal({previewFile}) {
                 }
             }
         };
-    }, [url]);
+    }, [url, label, getLoader, toObject]);
 
     return 
         {name}
@@ -395,35 +436,12 @@ function ThreeMFPreviewModal({previewFile}) {
     
 }
 
-function STLPreviewModal({previewFile}) {
-    const [dimensions, setDimensions] = React.useState(null);
-    const url = getMediaPathURL(previewFile);
-    const path = previewFile.primary_path ?? previewFile.path;
-    const name = path.replace(/^.*[\\\/]/, '');
-    return 
-        {name}
-        
-            {dimensions && 
- Width: {dimensions.width.toFixed(2)} - {' | '} - Height: {dimensions.height.toFixed(2)} - {' | '} - Length: {dimensions.length.toFixed(2)} - {' | '} - Bounding Radius: {dimensions.boundingRadius.toFixed(2)} -
} - -
- setDimensions(dims)} - /> -
-
-
-
+export function ThreeMFPreviewModal({previewFile}) { + return ; +} + +export function STLPreviewModal({previewFile}) { + return ; } function getGenericPreviewModal(previewFile) { @@ -581,6 +599,7 @@ export function FilePreviewProvider({children}) { setPreviewModal( handleClose(e)} + classNames={{content: 'file-preview-modal-content'}} > {pathContent} diff --git a/app/src/components/ModelPreview.test.js b/app/src/components/ModelPreview.test.js new file mode 100644 index 00000000..b5542eb7 --- /dev/null +++ b/app/src/components/ModelPreview.test.js @@ -0,0 +1,179 @@ +// The 3D previews render the real loaders against the installed three. Only the WebGL renderer is +// faked (jsdom has no WebGL); parsing, meshing and framing all run, and the dimensions line is +// only shown once a model has been loaded. +import React from 'react'; +import {act, screen, waitFor} from '@testing-library/react'; +import {renderWithProviders} from '../test-utils'; +import {modelCameraDistance, STLPreviewModal, ThreeMFPreviewModal} from './FilePreview'; +import {zipSync} from 'three/examples/jsm/libs/fflate.module.js'; + +jest.mock('three', () => { + const actual = jest.requireActual('three'); + + class FakeWebGLRenderer { + constructor() { + this.domElement = global.document.createElement('canvas'); + } + + setClearColor() { + } + + setPixelRatio() { + } + + setSize() { + } + + render() { + } + + dispose() { + } + } + + return {...actual, WebGLRenderer: FakeWebGLRenderer}; +}); + +// One right triangle, legs of 2 along X and 1 along Y. +const ASCII_STL = `solid ASCII + facet normal 0 0 1 + outer loop + vertex 0 0 0 + vertex 2 0 0 + vertex 0 1 0 + endloop + endfacet +endsolid +`; + +function binaryStl() { + // 80-byte header, uint32 triangle count, then one 50-byte triangle: normal, three vertices. + const buffer = new ArrayBuffer(84 + 50); + const view = new DataView(buffer); + view.setUint32(80, 1, true); + const floats = [0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1, 0]; + floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true)); + return buffer; +} + +function threeMF() { + const model = ` + + + + + + + + + + + + + + + + + + +`; + const rels = ` + + +`; + // Copy into this realm's Uint8Array: fflate tells files from folders with `instanceof`, and + // Node's TextEncoder returns a Uint8Array from another realm than jsdom's. + const bytes = (text) => Uint8Array.from(new TextEncoder().encode(text)); + const zipped = zipSync({'_rels/.rels': bytes(rels), '3D/3dmodel.model': bytes(model)}); + return zipped.buffer.slice(zipped.byteOffset, zipped.byteOffset + zipped.byteLength); +} + +function serve(body) { + const bytes = typeof body === 'string' ? new TextEncoder().encode(body).buffer : body; + global.fetch = jest.fn(async () => ({ + ok: true, + status: 200, + statusText: 'OK', + headers: new Headers(), + arrayBuffer: async () => bytes, + })); +} + +beforeEach(() => { + global.ResizeObserver = class { + observe() { + } + + disconnect() { + } + }; +}); + +afterEach(() => { + delete global.fetch; +}); + +// The triangle spans 2 along X and 1 along Y, and is flat in Z; its bounding radius is half the +// box diagonal. Which extent reads as Height depends on how the viewer orients the model. +async function expectTriangleDimensions({height, length}) { + await waitFor(() => expect(screen.getByText(/Width:/)).toBeInTheDocument(), {timeout: 5000}); + const line = screen.getByText(/Width:/).closest('div').textContent; + expect(line).toContain('Width: 2.00'); + expect(line).toContain(`Height: ${height}`); + expect(line).toContain(`Length: ${length}`); + expect(line).toContain('Bounding Radius: 1.12'); +} + +// Models are Z-up, so the flat triangle lies down: its Y extent reads as Length. +const TRIANGLE_DIMENSIONS = {height: '0.00', length: '1.00'}; + +describe('STL preview', () => { + it('loads an ASCII STL file', async () => { + serve(ASCII_STL); + await act(async () => renderWithProviders()); + await expectTriangleDimensions(TRIANGLE_DIMENSIONS); + // three's FileLoader fetches a Request. + expect(global.fetch.mock.calls[0][0].url).toContain('/media/models/part.stl'); + }); + + it('loads a binary STL file', async () => { + serve(binaryStl()); + await act(async () => renderWithProviders()); + await expectTriangleDimensions(TRIANGLE_DIMENSIONS); + }); +}); + +describe('3MF preview', () => { + it('loads a 3MF file', async () => { + serve(threeMF()); + await act(async () => renderWithProviders()); + await expectTriangleDimensions(TRIANGLE_DIMENSIONS); + }); +}); + +describe('modelCameraDistance', () => { + // Half the angle a sphere of `radius` fills when seen from `distance`. + const sphereHalfAngle = (radius, distance) => Math.asin(radius / distance); + const halfVertical = (fov) => (fov * Math.PI) / 360; + const halfHorizontal = (fov, aspect) => Math.atan(Math.tan(halfVertical(fov)) * aspect); + + it.each([ + ['a wide viewer', 2], + ['a square viewer', 1], + ['a tall, narrow viewer', 0.5], + ])('fits the whole bounding sphere in %s, with little to spare', (_, aspect) => { + const radius = 24; + const fov = 50; + const distance = modelCameraDistance(radius, fov, aspect); + const narrowest = Math.min(halfVertical(fov), halfHorizontal(fov, aspect)); + // Every point of the sphere is in view... + expect(sphereHalfAngle(radius, distance)).toBeLessThanOrEqual(narrowest); + // ...and the sphere fills at least 90% of the narrower field of view. + expect(sphereHalfAngle(radius, distance)).toBeGreaterThan(narrowest * 0.9); + }); + + it('stands back in proportion to the model', () => { + expect(modelCameraDistance(10, 50, 1.5)).toBeCloseTo(modelCameraDistance(1, 50, 1.5) * 10); + }); +}); diff --git a/app/src/components/STLLoader.test.js b/app/src/components/STLLoader.test.js deleted file mode 100644 index 5996af52..00000000 --- a/app/src/components/STLLoader.test.js +++ /dev/null @@ -1,41 +0,0 @@ -// react-stl-viewer parses STL files with three-stdlib's STLLoader against our top-level three. -// Both STL encodings must parse with the installed three/three-stdlib pair. -import {STLLoader} from 'three-stdlib/loaders/STLLoader.js'; - -const ASCII_STL = `solid ASCII - facet normal 0 0 1 - outer loop - vertex 0 0 0 - vertex 1 0 0 - vertex 0 1 0 - endloop - endfacet -endsolid -`; - -function binaryStl() { - // 80-byte header, uint32 triangle count, then one 50-byte triangle. - const buffer = new ArrayBuffer(84 + 50); - const view = new DataView(buffer); - view.setUint32(80, 1, true); - const floats = [0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0]; - floats.forEach((value, i) => view.setFloat32(84 + i * 4, value, true)); - return buffer; -} - -describe('STLLoader', () => { - it('parses an ASCII STL file', () => { - const buffer = new TextEncoder().encode(ASCII_STL).buffer; - const geometry = new STLLoader().parse(buffer); - expect(geometry.getAttribute('position').count).toBe(3); - expect(Array.from(geometry.getAttribute('position').array)) - .toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0]); - }); - - it('parses a binary STL file', () => { - const geometry = new STLLoader().parse(binaryStl()); - expect(geometry.getAttribute('position').count).toBe(3); - expect(Array.from(geometry.getAttribute('position').array)) - .toEqual([0, 0, 0, 1, 0, 0, 0, 1, 0]); - }); -}); diff --git a/app/src/setupTests.js b/app/src/setupTests.js index dd26a247..1c72eb4d 100644 --- a/app/src/setupTests.js +++ b/app/src/setupTests.js @@ -13,11 +13,6 @@ import '@testing-library/jest-dom'; // Tests that exceed this will fail with a clear error message identifying the failing test jest.setTimeout(30000); -// Mock react-stl-viewer to avoid loading heavy three.js dependency in tests -jest.mock('react-stl-viewer', () => ({ - StlViewer: () => null, -})); - // Mock window.matchMedia (used by the responsive Media components) Object.defineProperty(window, 'matchMedia', { writable: true,