diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/.gitignore b/starter-templates/ocjs-create-react-app-web-and-service-worker/.gitignore new file mode 100644 index 00000000..4d29575d --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/.gitignore @@ -0,0 +1,23 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.js + +# testing +/coverage + +# production +/build + +# misc +.DS_Store +.env.local +.env.development.local +.env.test.local +.env.production.local + +npm-debug.log* +yarn-debug.log* +yarn-error.log* diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/README.md b/starter-templates/ocjs-create-react-app-web-and-service-worker/README.md new file mode 100644 index 00000000..8aacedf3 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/README.md @@ -0,0 +1,19 @@ +# Create React App opencascade.js Template using web worker, service worker and typescript +- opencascade.js operations are running on a **service worker** to avoid blocking the UI while performing CAD operations. +- The **service worker** is used in **production only** to cache the application including the large wasm file of opencascade.js to speed up loading times when visiting the website a second time. + +## Development + +Use `npm start` to start the development mode. In this mode the service worker does not work and therefore opencascade.js takes longer to reload. + +## Production +Use `npm run build` to create a production build `including the service worker`. +To test the service worker you can then serve the build. For example with `npx serve -s build`. +You will see on a second visit opencascade initializes faster. + +## More on service worker +The service worker can have some weird behaviour. It does not update the service worker on its own once a new version of the service worker is used in production build. If you find a solution for this please contribute it to this template. + +To make sure the new service worker is used unregister the service worker from within the dev tools in the browser manualy and then reload the website. + +If you want to **opt out of the service** worker go into `index.tsx` and change `serviceWorkerRegistration.register();` to `serviceWorkerRegistration.unregister();`. \ No newline at end of file diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/package.json b/starter-templates/ocjs-create-react-app-web-and-service-worker/package.json new file mode 100644 index 00000000..b84b93cb --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/package.json @@ -0,0 +1,58 @@ +{ + "name": "ocjs-cra-web-and-service-worker-typescript", + "version": "0.1.0", + "private": true, + "dependencies": { + "@google/model-viewer": "^1.12.0", + "@testing-library/jest-dom": "^5.16.4", + "@testing-library/react": "^13.3.0", + "@testing-library/user-event": "^13.5.0", + "@types/jest": "^27.5.2", + "@types/node": "^17.0.41", + "@types/react": "^18.0.12", + "@types/react-dom": "^18.0.5", + "opencascade.js": "^2.0.0-beta.6e177a4", + "react": "^18.1.0", + "react-dom": "^18.1.0", + "react-scripts": "5.0.1", + "typescript": "^4.7.3", + "web-vitals": "^2.1.4", + "workbox-background-sync": "^6.5.3", + "workbox-broadcast-update": "^6.5.3", + "workbox-cacheable-response": "^6.5.3", + "workbox-cli": "^6.5.3", + "workbox-core": "^6.5.3", + "workbox-expiration": "^6.5.3", + "workbox-google-analytics": "^6.5.3", + "workbox-navigation-preload": "^6.5.3", + "workbox-precaching": "^6.5.3", + "workbox-range-requests": "^6.5.3", + "workbox-routing": "^6.5.3", + "workbox-strategies": "^6.5.3", + "workbox-streams": "^6.5.3" + }, + "scripts": { + "start": "react-scripts start", + "build": "react-scripts build", + "test": "react-scripts test", + "eject": "react-scripts eject" + }, + "eslintConfig": { + "extends": [ + "react-app", + "react-app/jest" + ] + }, + "browserslist": { + "production": [ + ">0.2%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/public/favicon.ico b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/favicon.ico new file mode 100644 index 00000000..a11777cc Binary files /dev/null and b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/favicon.ico differ diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/public/index.html b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/index.html new file mode 100644 index 00000000..6a9f8c26 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/index.html @@ -0,0 +1,40 @@ + + + + + + + + + + + + + React App + + + +
+ + + diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/public/logo192.png b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/logo192.png new file mode 100644 index 00000000..fc44b0a3 Binary files /dev/null and b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/logo192.png differ diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/public/logo512.png b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/logo512.png new file mode 100644 index 00000000..a4e47a65 Binary files /dev/null and b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/logo512.png differ diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/public/manifest.json b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/manifest.json new file mode 100644 index 00000000..080d6c77 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/manifest.json @@ -0,0 +1,25 @@ +{ + "short_name": "React App", + "name": "Create React App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "64x64 32x32 24x24 16x16", + "type": "image/x-icon" + }, + { + "src": "logo192.png", + "type": "image/png", + "sizes": "192x192" + }, + { + "src": "logo512.png", + "type": "image/png", + "sizes": "512x512" + } + ], + "start_url": ".", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/public/robots.txt b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/robots.txt new file mode 100644 index 00000000..e9e57dc4 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/public/robots.txt @@ -0,0 +1,3 @@ +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.css b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.css new file mode 100644 index 00000000..8f27736e --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.css @@ -0,0 +1,29 @@ +.App { + text-align: center; +} + +.App-logo { + width: 25vw; + pointer-events: none; +} + +.App-header { + background-color: #18191a; + min-height: 100vh; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + font-size: calc(10px + 2vmin); + color: white; +} + +.App-link { + color: #b39b00; +} + +.App-viewport { + margin-top: 25px; + width: 500px; + height: 500px; +} \ No newline at end of file diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.test.tsx b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.test.tsx new file mode 100644 index 00000000..6e50d659 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.test.tsx @@ -0,0 +1,9 @@ +import React from 'react'; +import { render, screen } from '@testing-library/react'; +import App from './App'; + +test('renders learn opencascade.js link', () => { + render(); + const linkElement = screen.getByText(/learn opencascade.js/i); + expect(linkElement).toBeInTheDocument(); +}); diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.tsx b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.tsx new file mode 100644 index 00000000..bc659800 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/App.tsx @@ -0,0 +1,58 @@ +import { useEffect, useMemo, useState } from "react"; +import "./App.css"; +import "@google/model-viewer"; + +declare global { + namespace JSX { + interface IntrinsicElements { + 'model-viewer': ModelViewerJSX & React.DetailedHTMLProps, HTMLElement> ; + } + } +} + +interface ModelViewerJSX { + src: string + poster?: string + class?: string + // ... others +} + +function App() { + const [modelUrl, setModelUrl] = useState(); + const worker = useMemo(() => new Worker(new URL('./openCascadeWorker.ts', import.meta.url)), []); + + useEffect(() => { + worker.onmessage = ({ data }) => { + setModelUrl(data); + return () => worker.terminate(); + } + }, [worker]); + + return ( +
+
+ Ocjs Logo +

+ Edit src/App.js and save to reload. +

+ + Learn OpenCascade.js + + {modelUrl === undefined ? ( +

+ Loading... +

+ ) : ( + + )} +
+
+ ); +} + +export default App; \ No newline at end of file diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/index.css b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/index.css new file mode 100644 index 00000000..ec2585e8 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/index.css @@ -0,0 +1,13 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + monospace; +} diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/index.tsx b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/index.tsx new file mode 100644 index 00000000..70b64e8b --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/index.tsx @@ -0,0 +1,28 @@ +import React from 'react'; +import ReactDOM from 'react-dom/client'; +import './index.css'; +import App from './App'; +import * as serviceWorkerRegistration from './serviceWorkerRegistration'; +import reportWebVitals from './reportWebVitals'; + +const root = ReactDOM.createRoot( + document.getElementById('root') as HTMLElement +); +root.render( + + + +); + +// Opt into this service worker to cache the open cascade wasm file in a production build. +// | +// V +// If you want your app to work offline and load faster, you can change +// unregister() to register() below. Note this comes with some pitfalls. +// Learn more about service workers: https://cra.link/PWA +serviceWorkerRegistration.register(); + +// If you want to start measuring performance in your app, pass a function +// to log results (for example: reportWebVitals(console.log)) +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals +reportWebVitals(); diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/logo.svg b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/logo.svg new file mode 100644 index 00000000..6b60c104 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/logo.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/openCascadeWorker.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/openCascadeWorker.ts new file mode 100644 index 00000000..f3b79675 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/openCascadeWorker.ts @@ -0,0 +1,44 @@ +import initOpenCascade, { TopoDS_Shape } from "opencascade.js"; +import shapeToUrl from "./shapeToUrl"; + +/* eslint-disable no-restricted-globals */ + +initOpenCascade().then(oc => { + const sphere = new oc.BRepPrimAPI_MakeSphere_1(1); + + // Take shape and subtract a translated and scaled sphere from it + const makeCut = (shape: TopoDS_Shape, translation: [number, number, number], scale: number) => { + const tf = new oc.gp_Trsf_1(); + tf.SetTranslation_1(new oc.gp_Vec_4(translation[0], translation[1], translation[2])); + tf.SetScaleFactor(scale); + const loc = new oc.TopLoc_Location_2(tf); + + const cut = new oc.BRepAlgoAPI_Cut_3(shape, sphere.Shape().Moved(loc, false), new oc.Message_ProgressRange_1()); + cut.Build(new oc.Message_ProgressRange_1()); + + return cut.Shape(); + }; + + // Let's make some cuts + const cut1 = makeCut(sphere.Shape(), [0, 0, 0.7], 1); + const cut2 = makeCut(cut1, [0, 0, -0.7], 1); + const cut3 = makeCut(cut2, [0, 0.25, 1.75], 1.825); + const cut4 = makeCut(cut3, [4.8, 0, 0], 5); + + // Rotate around the Z axis + const makeRotation = (rotation: number) => { + const tf = new oc.gp_Trsf_1(); + tf.SetRotation_1(new oc.gp_Ax1_2(new oc.gp_Pnt_1(), new oc.gp_Dir_4(0, 0, 1)), rotation); + const loc = new oc.TopLoc_Location_2(tf); + return loc; + }; + + // Combine the result + const fuse = new oc.BRepAlgoAPI_Fuse_3(cut4, cut4.Moved(makeRotation(Math.PI), false), new oc.Message_ProgressRange_1()); + fuse.Build(new oc.Message_ProgressRange_1()); + const result = fuse.Shape().Moved(makeRotation(-30 * Math.PI / 180), false); + + self.postMessage(shapeToUrl(oc, result)); +}); + +export {} diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/react-app-env.d.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/react-app-env.d.ts new file mode 100644 index 00000000..6431bc5f --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/react-app-env.d.ts @@ -0,0 +1 @@ +/// diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/reportWebVitals.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/reportWebVitals.ts new file mode 100644 index 00000000..49a2a16e --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/reportWebVitals.ts @@ -0,0 +1,15 @@ +import { ReportHandler } from 'web-vitals'; + +const reportWebVitals = (onPerfEntry?: ReportHandler) => { + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + getCLS(onPerfEntry); + getFID(onPerfEntry); + getFCP(onPerfEntry); + getLCP(onPerfEntry); + getTTFB(onPerfEntry); + }); + } +}; + +export default reportWebVitals; diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/service-worker.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/service-worker.ts new file mode 100644 index 00000000..621b5010 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/service-worker.ts @@ -0,0 +1,80 @@ +/// +/* eslint-disable no-restricted-globals */ + +// This service worker can be customized! +// See https://developers.google.com/web/tools/workbox/modules +// for the list of available Workbox modules, or add any other +// code you'd like. +// You can also remove this file if you'd prefer not to use a +// service worker, and the Workbox build step will be skipped. + +import { clientsClaim } from 'workbox-core'; +import { ExpirationPlugin } from 'workbox-expiration'; +import { precacheAndRoute, createHandlerBoundToURL } from 'workbox-precaching'; +import { registerRoute } from 'workbox-routing'; +import { StaleWhileRevalidate } from 'workbox-strategies'; + +declare const self: ServiceWorkerGlobalScope; + +clientsClaim(); + +// Precache all of the assets generated by your build process. +// Their URLs are injected into the manifest variable below. +// This variable must be present somewhere in your service worker file, +// even if you decide not to use precaching. See https://cra.link/PWA +precacheAndRoute(self.__WB_MANIFEST); + +// Set up App Shell-style routing, so that all navigation requests +// are fulfilled with your index.html shell. Learn more at +// https://developers.google.com/web/fundamentals/architecture/app-shell +const fileExtensionRegexp = new RegExp('/[^/?]+\\.[^/]+$'); +registerRoute( + // Return false to exempt requests from being fulfilled by index.html. + ({ request, url }: { request: Request; url: URL }) => { + // If this isn't a navigation, skip. + if (request.mode !== 'navigate') { + return false; + } + + // If this is a URL that starts with /_, skip. + if (url.pathname.startsWith('/_')) { + return false; + } + + // If this looks like a URL for a resource, because it contains + // a file extension, skip. + if (url.pathname.match(fileExtensionRegexp)) { + return false; + } + + // Return true to signal that we want to use the handler. + return true; + }, + createHandlerBoundToURL(process.env.PUBLIC_URL + '/index.html') +); + +// An example runtime caching route for requests that aren't handled by the +// precache, in this case same-origin .wasm requests to speed up open cascade loading +registerRoute( + // Add in any other file extensions or routing criteria as needed. + ({ url }) => url.origin === self.location.origin && url.pathname.endsWith('.wasm'), + // Customize this strategy as needed, e.g., by changing to CacheFirst. + new StaleWhileRevalidate({ + cacheName: 'wasm', + plugins: [ + // Ensure that once this runtime cache reaches a maximum size the + // least-recently used images are removed. + new ExpirationPlugin({ maxEntries: 50 }), + ], + }) +); + +// This allows the web app to trigger skipWaiting via +// registration.waiting.postMessage({type: 'SKIP_WAITING'}) +self.addEventListener('message', (event) => { + if (event.data && event.data.type === 'SKIP_WAITING') { + self.skipWaiting(); + } +}); + +// Any other custom service worker logic can go here. diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/serviceWorkerRegistration.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/serviceWorkerRegistration.ts new file mode 100644 index 00000000..8bbd6864 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/serviceWorkerRegistration.ts @@ -0,0 +1,143 @@ +// This optional code is used to register a service worker. +// register() is not called by default. + +// This lets the app load faster on subsequent visits in production, and gives +// it offline capabilities. However, it also means that developers (and users) +// will only see deployed updates on subsequent visits to a page, after all the +// existing tabs open on the page have been closed, since previously cached +// resources are updated in the background. + +// To learn more about the benefits of this model and instructions on how to +// opt-in, read https://cra.link/PWA + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.0/8 are considered localhost for IPv4. + window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/) +); + +type Config = { + onSuccess?: (registration: ServiceWorkerRegistration) => void; + onUpdate?: (registration: ServiceWorkerRegistration) => void; +}; + +export function register(config?: Config) { + console.log("register"); + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebook/create-react-app/issues/2374 + return; + } + + window.addEventListener('load', () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + + if (isLocalhost) { + // This is running on localhost. Let's check if a service worker still exists or not. + checkValidServiceWorker(swUrl, config); + + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + 'This web app is being served cache-first by a service ' + + 'worker. To learn more, visit https://cra.link/PWA' + ); + }); + } else { + // Is not localhost. Just register service worker + registerValidSW(swUrl, config); + } + }); + } +} + +function registerValidSW(swUrl: string, config?: Config) { + navigator.serviceWorker + .register(swUrl) + .then((registration) => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + if (installingWorker == null) { + return; + } + installingWorker.onstatechange = () => { + if (installingWorker.state === 'installed') { + if (navigator.serviceWorker.controller) { + // At this point, the updated precached content has been fetched, + // but the previous service worker will still serve the older + // content until all client tabs are closed. + console.log( + 'New content is available and will be used when all ' + + 'tabs for this page are closed. See https://cra.link/PWA.' + ); + + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log('Content is cached for offline use.'); + + // Execute callback + if (config && config.onSuccess) { + config.onSuccess(registration); + } + } + } + }; + }; + }) + .catch((error) => { + console.error('Error during service worker registration:', error); + }); +} + +function checkValidServiceWorker(swUrl: string, config?: Config) { + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl, { + headers: { 'Service-Worker': 'script' }, + }) + .then((response) => { + // Ensure service worker exists, and that we really are getting a JS file. + const contentType = response.headers.get('content-type'); + if ( + response.status === 404 || + (contentType != null && contentType.indexOf('javascript') === -1) + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then((registration) => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl, config); + } + }) + .catch(() => { + console.log('No internet connection found. App is running in offline mode.'); + }); +} + +export function unregister() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready + .then((registration) => { + registration.unregister(); + }) + .catch((error) => { + console.error(error.message); + }); + } +} diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/setupTests.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/setupTests.ts new file mode 100644 index 00000000..8f2609b7 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/setupTests.ts @@ -0,0 +1,5 @@ +// jest-dom adds custom jest matchers for asserting on DOM nodes. +// allows you to do things like: +// expect(element).toHaveTextContent(/react/i) +// learn more: https://github.com/testing-library/jest-dom +import '@testing-library/jest-dom'; diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/src/shapeToUrl.ts b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/shapeToUrl.ts new file mode 100644 index 00000000..a52589a9 --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/src/shapeToUrl.ts @@ -0,0 +1,21 @@ +import { OpenCascadeInstance, TopoDS_Shape } from "opencascade.js"; + +// Takes a TopoDS_Shape, creates a GLB file from it and returns a ObjectURL +export default function shapeToUrl(oc: OpenCascadeInstance, shape: TopoDS_Shape) { + // Create a document and add our shape + const docHandle = new oc.Handle_TDocStd_Document_2(new oc.TDocStd_Document(new oc.TCollection_ExtendedString_1())); + const shapeTool = oc.XCAFDoc_DocumentTool.ShapeTool(docHandle.get().Main()).get(); + shapeTool.SetShape(shapeTool.NewShape(), shape); + + // Tell OpenCascade that we want our shape to get meshed + new oc.BRepMesh_IncrementalMesh_2(shape, 0.1, false, 0.1, false); + + // Export a GLB file (this will also perform the meshing) + const cafWriter = new oc.RWGltf_CafWriter(new oc.TCollection_AsciiString_2("./file.glb"), true); + cafWriter.Perform_2(docHandle, new oc.TColStd_IndexedDataMapOfStringString_1(), new oc.Message_ProgressRange_1()); + + // Read the GLB file from the virtual file system + const glbFile = oc.FS.readFile("./file.glb", { encoding: "binary" }); + + return URL.createObjectURL(new Blob([glbFile.buffer], { type: "model/gltf-binary" })); +}; diff --git a/starter-templates/ocjs-create-react-app-web-and-service-worker/tsconfig.json b/starter-templates/ocjs-create-react-app-web-and-service-worker/tsconfig.json new file mode 100644 index 00000000..a273b0cf --- /dev/null +++ b/starter-templates/ocjs-create-react-app-web-and-service-worker/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": [ + "dom", + "dom.iterable", + "esnext" + ], + "allowJs": true, + "skipLibCheck": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "strict": true, + "forceConsistentCasingInFileNames": true, + "noFallthroughCasesInSwitch": true, + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx" + }, + "include": [ + "src" + ] +}