slicer-studio 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,18 +1,162 @@
1
1
  # slicer-studio
2
2
 
3
- A 3D printing studio as one custom element. Put `<slicer-studio>` on a page, on any stack, and customers can upload
4
- their models and see what printing them costs, or staff can slice them and inspect the G-code. It brings its own React,
5
- and a shadow root keeps its styles and your page's apart.
3
+ A 3D printing studio you add to any website with one HTML tag. Customers upload a model, make a few choices and see what
4
+ it costs to print. Staff can slice models and inspect the G-code.
6
5
 
7
- It needs a running [slicer-api](https://github.com/kerala-startup-mission/slicer-api), which does the slicing and holds
8
- your printers and prices.
6
+ ```html
7
+ <slicer-studio api-url="https://api.example.com"></slicer-studio>
8
+ ```
9
+
10
+ It is a standard custom element, so it works on any stack. It brings its own React, and a shadow root keeps its styles
11
+ and your page's apart.
12
+
13
+ **The price page** (`mode="quote"`, the default) takes up to 10 models at once and shows each one in 3D. Customers choose
14
+ the material, finish, strength and number of copies, then see the price, weight and print time. SLA and SLS jobs get an
15
+ email button to your lab instead of a price.
16
+
17
+ **Advanced** (`mode="advanced"`) is for staff. It offers every OrcaSlicer printer and preset, slices models, and shows the
18
+ G-code layer by layer. It also opens G-code and sliced 3MF files in the browser, with no upload.
19
+
20
+ ## Contents
21
+
22
+ - [How it works](#how-it-works)
23
+ - [Setup](#setup)
24
+ - [Frameworks](#frameworks)
25
+ - [Attributes](#attributes)
26
+ - [Options](#options)
27
+ - [Events and methods](#events-and-methods)
28
+ - [Layout and styling](#layout-and-styling)
29
+ - [Taking orders](#taking-orders)
30
+ - [Staff access](#staff-access)
31
+ - [Content Security Policy](#content-security-policy)
32
+ - [Troubleshooting](#troubleshooting)
33
+ - [Good to know](#good-to-know)
34
+
35
+ ## How it works
36
+
37
+ ```text
38
+ Your website Your server
39
+ +---------------------------+ +-----------------------------+
40
+ | <slicer-studio> | model | slicer-api (Docker) |
41
+ | upload, choices, | ----------> | OrcaSlicer |
42
+ | 3D view, price | <---------- | your printers and prices |
43
+ +---------------------------+ weight, +-----------------------------+
44
+ print time
45
+ ```
46
+
47
+ - **This package is the interface.** Slicing is done by
48
+ [slicer-api](https://github.com/kerala-startup-mission/slicer-api), which you run yourself. Each API has one set of
49
+ printers and prices, so a lab runs one API.
50
+ - **Models go only to your API.** The studio makes no other network calls.
51
+ - **Prices are worked out in the browser.** The API returns weight and time, and the studio multiplies the weight by
52
+ your price per gram. So you can change prices from your page, but you must not trust them when you charge
53
+ (see [Taking orders](#taking-orders)).
54
+ - **The package is already built.** You get ready-made JavaScript in `dist/`, and `npm install` adds no other packages.
55
+
56
+ ## Setup
9
57
 
10
- ## Quick start
58
+ You need Docker on the server that runs the API. On your website you need either npm or a page whose HTML you can edit.
59
+
60
+ ### 1. Run slicer-api
61
+
62
+ ```bash
63
+ git clone https://github.com/kerala-startup-mission/slicer-api.git
64
+ cd slicer-api
65
+ docker compose up --build -d
66
+ ```
67
+
68
+ The first build downloads OrcaSlicer (about 150 MB) and takes a few minutes. Then check that it is running:
69
+
70
+ ```bash
71
+ curl http://localhost:3000/health
72
+ ```
73
+
74
+ You should get `{"ok":true,"slicer":true}`.
75
+
76
+ ### 2. Set your printers and prices
77
+
78
+ Edit `config/printers.json` in slicer-api. Changes apply on the next page load, with no restart.
79
+
80
+ ```json
81
+ {
82
+ "currency": "INR",
83
+ "pricePerGram": { "PLA": 6, "PETG": 7, "ABS": 8, "TPU": 7 },
84
+ "priceRange": 20,
85
+ "printers": [
86
+ { "name": "Bambu Lab A1 0.4 nozzle", "default": true },
87
+ { "name": "Bambu Lab P1S 0.4 nozzle" }
88
+ ],
89
+ "regularMode": { "supports": true, "mode": "estimate" },
90
+ "contact": { "name": "Acme Labs", "email": "hello@example.com" }
91
+ }
92
+ ```
93
+
94
+ Printer names must match OrcaSlicer's exactly. To find yours:
95
+
96
+ ```bash
97
+ curl "http://localhost:3000/api/printers?q=bambu"
98
+ ```
99
+
100
+ [Options](#options) explains each value. Your page can override all of them except `printers`.
101
+
102
+ ### 3. Allow your website
103
+
104
+ Browsers block calls to the API from other sites until you allow them. Set these in slicer-api's `docker-compose.yml`:
105
+
106
+ ```yaml
107
+ services:
108
+ print-quote-api:
109
+ environment:
110
+ ALLOWED_ORIGINS: "https://www.example.com,https://example.com"
111
+ RATE_LIMIT_PER_MIN: "30"
112
+ TRUST_PROXY: "1"
113
+ ```
114
+
115
+ | Setting | What it does |
116
+ |---|---|
117
+ | `ALLOWED_ORIGINS` | The sites that embed the studio, comma-separated. An origin is the scheme, host and port, with no path, such as `http://localhost:5173`. |
118
+ | `RATE_LIMIT_PER_MIN` | Quotes per minute per visitor. Slices run one at a time, so turn this on for any public API. Each file is one request and a customer can send 10 at once, so 30 is a fair start. |
119
+ | `TRUST_PROXY` | How many proxies sit in front of the API. Without it, all visitors behind a proxy share one rate limit. |
120
+
121
+ Then apply the changes:
122
+
123
+ ```bash
124
+ docker compose up -d
125
+ ```
126
+
127
+ ### 4. Serve the API over HTTPS
128
+
129
+ A page on `https://` can't call an `http://` API, so a live site needs HTTPS on the API too. Put a proxy in front of it.
130
+ With nginx:
131
+
132
+ ```nginx
133
+ server {
134
+ listen 443 ssl;
135
+ server_name api.example.com;
136
+ # ssl_certificate and ssl_certificate_key go here
137
+
138
+ client_max_body_size 55m; # models can be up to 50 MB
139
+
140
+ location / {
141
+ proxy_pass http://127.0.0.1:3000;
142
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
143
+ proxy_read_timeout 300s; # a slice can wait for others in the queue
144
+ proxy_send_timeout 300s;
145
+ }
146
+ }
147
+ ```
148
+
149
+ You can also forward `/api/` and `/health` from your own domain. The studio then calls your site's own origin, so leave
150
+ out `api-url` and `ALLOWED_ORIGINS`.
151
+
152
+ ### 5. Add the studio to your page
11
153
 
12
154
  ```bash
13
155
  npm install slicer-studio
14
156
  ```
15
157
 
158
+ Import it once, anywhere in your JavaScript, then put the tag on your page:
159
+
16
160
  ```js
17
161
  import 'slicer-studio';
18
162
  ```
@@ -21,36 +165,317 @@ import 'slicer-studio';
21
165
  <slicer-studio api-url="https://api.example.com"></slicer-studio>
22
166
  ```
23
167
 
24
- Without a bundler, load it from a CDN:
168
+ [Frameworks](#frameworks) shows this for your stack, including how to use it without npm.
169
+
170
+ ### 6. Check that it works
171
+
172
+ 1. Open your page. The studio should appear.
173
+ 2. Drop an STL file on it.
174
+ 3. Click **Get the price**. A price should appear.
175
+
176
+ If it doesn't, see [Troubleshooting](#troubleshooting). Your browser's console usually names the problem.
177
+
178
+ ## Frameworks
179
+
180
+ Every example sets the same two options and logs the price. Replace `https://api.example.com` with your API.
181
+
182
+ Tested on Vite 8, React 18.3 and 19.3, Next.js 16, Vue 3.5, Nuxt 4, Angular 20, Svelte 5 and Laravel 13.
183
+
184
+ ### Plain HTML
185
+
186
+ No npm or build step. Load it from a CDN:
25
187
 
26
188
  ```html
27
- <script type="module" src="https://cdn.jsdelivr.net/npm/slicer-studio/dist/slicer-studio.js"></script>
189
+ <script type="module" src="https://cdn.jsdelivr.net/npm/slicer-studio@0.1.0/dist/slicer-studio.js"></script>
190
+
28
191
  <slicer-studio api-url="https://api.example.com"></slicer-studio>
192
+
193
+ <script>
194
+ const studio = document.querySelector('slicer-studio');
195
+ studio.config = { priceRange: 15, pricePerGram: { PLA: 5 } };
196
+ studio.addEventListener('estimate', e => console.log(e.detail));
197
+ </script>
198
+ ```
199
+
200
+ Keep the exact version in the link, so a new release can't change your page without you knowing.
201
+
202
+ To host it yourself, copy the whole `node_modules/slicer-studio/dist` folder to your site and point `src` at
203
+ `slicer-studio.js` inside it. It loads files from the `chunks` folder next to it, so one file on its own won't work.
204
+
205
+ ### Vite, webpack and other bundlers
206
+
207
+ ```js
208
+ import 'slicer-studio';
209
+
210
+ const studio = document.querySelector('slicer-studio');
211
+ studio.config = { priceRange: 15, pricePerGram: { PLA: 5 } };
212
+ studio.addEventListener('estimate', e => console.log(e.detail));
29
213
  ```
30
214
 
31
- Then allow your site on the API, under [Set up the API](#set-up-the-api).
215
+ Vite warns about chunk size when you build. That is expected, because the 3D view is large. It loads separately, after
216
+ the page.
217
+
218
+ ### React
219
+
220
+ This works on React 18 and 19. Set `config` and listen for events in an effect:
221
+
222
+ ```jsx
223
+ import { useEffect, useRef } from 'react';
224
+ import 'slicer-studio';
225
+
226
+ const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
227
+
228
+ export default function PrintPrices() {
229
+ const studio = useRef(null);
230
+
231
+ useEffect(() => {
232
+ const el = studio.current;
233
+ const onEstimate = e => console.log(e.detail);
234
+
235
+ el.config = options;
236
+ el.addEventListener('estimate', onEstimate);
237
+ return () => el.removeEventListener('estimate', onEstimate);
238
+ }, []);
239
+
240
+ return <slicer-studio ref={studio} api-url="https://api.example.com" />;
241
+ }
242
+ ```
243
+
244
+ React 19 has a shorter form, for apps that render only in the browser. The event name is lowercase:
245
+
246
+ ```jsx
247
+ <slicer-studio api-url="https://api.example.com" config={options} onestimate={onEstimate} />
248
+ ```
249
+
250
+ ### Next.js
251
+
252
+ Use the [React](#react) component above, with `'use client'` as its first line, in the App Router:
253
+
254
+ ```jsx
255
+ 'use client';
256
+
257
+ import { useEffect, useRef } from 'react';
258
+ import 'slicer-studio';
259
+
260
+ // the rest is the same as the React example
261
+ ```
262
+
263
+ Then use it from a page as usual. The import does nothing on the server, so you don't need `next/dynamic`.
264
+
265
+ **Don't use React 19's shorter form here.** After server rendering, React doesn't set `config` or `onestimate` on the
266
+ element. Nothing warns you: the studio ignores your options and your handler never runs.
267
+
268
+ ### Vue
269
+
270
+ Tell Vue's compiler this is a custom element, in `vite.config.js`:
271
+
272
+ ```js
273
+ import vue from '@vitejs/plugin-vue';
274
+ import { defineConfig } from 'vite';
275
+
276
+ export default defineConfig({
277
+ plugins: [vue({ template: { compilerOptions: { isCustomElement: tag => tag === 'slicer-studio' } } })],
278
+ });
279
+ ```
280
+
281
+ Then pass `config` as a property, with `.prop`:
282
+
283
+ ```vue
284
+ <script setup>
285
+ import 'slicer-studio';
286
+
287
+ const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
288
+ const onEstimate = e => console.log(e.detail);
289
+ </script>
290
+
291
+ <template>
292
+ <slicer-studio api-url="https://api.example.com" :config.prop="options" @estimate="onEstimate" />
293
+ </template>
294
+ ```
295
+
296
+ ### Nuxt
297
+
298
+ In `nuxt.config.ts`:
299
+
300
+ ```ts
301
+ export default defineNuxtConfig({
302
+ vue: { compilerOptions: { isCustomElement: tag => tag === 'slicer-studio' } },
303
+ });
304
+ ```
305
+
306
+ Load it in a browser-only plugin, `app/plugins/slicer-studio.client.ts` (on Nuxt 3, `plugins/slicer-studio.client.ts`):
307
+
308
+ ```ts
309
+ import 'slicer-studio';
310
+
311
+ export default defineNuxtPlugin(() => {});
312
+ ```
313
+
314
+ Then keep the tag out of server rendering with `<ClientOnly>`:
315
+
316
+ ```vue
317
+ <script setup>
318
+ const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
319
+ const onEstimate = e => console.log(e.detail);
320
+ </script>
321
+
322
+ <template>
323
+ <ClientOnly>
324
+ <slicer-studio api-url="https://api.example.com" :config.prop="options" @estimate="onEstimate" />
325
+ </ClientOnly>
326
+ </template>
327
+ ```
328
+
329
+ ### Angular
330
+
331
+ Add `CUSTOM_ELEMENTS_SCHEMA`, and load the package with `import()`. A plain `import 'slicer-studio'` puts it in your first
332
+ bundle, which fails the default size limit with `bundle initial exceeded maximum budget`.
333
+
334
+ ```ts
335
+ import { Component, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
336
+
337
+ @Component({
338
+ selector: 'app-root',
339
+ schemas: [CUSTOM_ELEMENTS_SCHEMA],
340
+ template: `
341
+ <slicer-studio api-url="https://api.example.com" [config]="options" (estimate)="onEstimate($event)"></slicer-studio>
342
+ `,
343
+ })
344
+ export class App {
345
+ options = { priceRange: 15, pricePerGram: { PLA: 5 } };
346
+
347
+ constructor() {
348
+ import('slicer-studio');
349
+ }
350
+
351
+ onEstimate(e: Event) {
352
+ console.log((e as CustomEvent).detail);
353
+ }
354
+ }
355
+ ```
356
+
357
+ TypeScript also needs a declaration for that `import()`, in `src/slicer-studio.d.ts`:
358
+
359
+ ```ts
360
+ declare module 'slicer-studio';
361
+ ```
362
+
363
+ ### Svelte
364
+
365
+ This is for Svelte 5:
366
+
367
+ ```svelte
368
+ <script>
369
+ import 'slicer-studio';
370
+
371
+ const options = { priceRange: 15, pricePerGram: { PLA: 5 } };
372
+ const onEstimate = e => console.log(e.detail);
373
+ </script>
374
+
375
+ <slicer-studio api-url="https://api.example.com" config={options} onestimate={onEstimate}></slicer-studio>
376
+ ```
377
+
378
+ ### Laravel
379
+
380
+ Run `npm install slicer-studio`, then add this to `resources/js/app.js`:
381
+
382
+ ```js
383
+ import 'slicer-studio';
384
+
385
+ document.querySelector('slicer-studio')?.addEventListener('estimate', e => console.log(e.detail));
386
+ ```
387
+
388
+ Add the API's address to `.env`, and read it in `config/services.php`:
389
+
390
+ ```dotenv
391
+ SLICER_API_URL=https://api.example.com
392
+ ```
393
+
394
+ ```php
395
+ 'slicer' => ['url' => env('SLICER_API_URL')],
396
+ ```
397
+
398
+ Pass the options from a route or controller:
399
+
400
+ ```php
401
+ Route::get('/prices', fn () => view('prices', [
402
+ 'studio' => ['priceRange' => 15, 'pricePerGram' => ['PLA' => 5]],
403
+ ]));
404
+ ```
405
+
406
+ And in the Blade template:
407
+
408
+ ```blade
409
+ @vite('resources/js/app.js')
410
+
411
+ <slicer-studio api-url="{{ config('services.slicer.url') }}" config='@json($studio)'></slicer-studio>
412
+ ```
413
+
414
+ ### Other server templates
415
+
416
+ Write `config` as JSON in the attribute, inside single quotes, and escape any `'` in the values as `&#39;`:
417
+
418
+ ```html
419
+ <slicer-studio api-url="https://api.example.com" config='{"priceRange":15,"pricePerGram":{"PLA":5}}'></slicer-studio>
420
+ ```
421
+
422
+ ### TypeScript
423
+
424
+ The package has no types of its own. `import 'slicer-studio'` works as it is, and Vue needs nothing more. For the tag in
425
+ React or Next.js, add this file, `slicer-studio.d.ts`, next to your component:
426
+
427
+ ```ts
428
+ import type { DetailedHTMLProps, HTMLAttributes } from 'react';
429
+
430
+ export interface SlicerStudioElement extends HTMLElement {
431
+ config: Record<string, unknown>;
432
+ getPrice(): Promise<void> | void;
433
+ }
434
+
435
+ declare module 'react' {
436
+ namespace JSX {
437
+ interface IntrinsicElements {
438
+ 'slicer-studio': DetailedHTMLProps<HTMLAttributes<SlicerStudioElement>, SlicerStudioElement> & {
439
+ 'api-url'?: string;
440
+ mode?: 'quote' | 'advanced';
441
+ theme?: 'light' | 'dark' | 'system';
442
+ config?: Record<string, unknown> | string;
443
+ onestimate?: (e: CustomEvent) => void;
444
+ };
445
+ }
446
+ }
447
+ }
448
+ ```
449
+
450
+ Then type your ref:
451
+
452
+ ```ts
453
+ import type { SlicerStudioElement } from './slicer-studio';
454
+
455
+ const studio = useRef<SlicerStudioElement>(null);
456
+ ```
32
457
 
33
458
  ## Attributes
34
459
 
35
460
  | Attribute | Values | Default |
36
461
  |---|---|---|
37
- | `api-url` | The slicer-api address | The page's own origin |
462
+ | `api-url` | The address of your slicer-api | Your page's own origin |
38
463
  | `mode` | `quote` (the price page) or `advanced` (the staff tools) | `quote` |
39
- | `theme` | `light`, `dark` or `system`. Setting it hides the theme switch | Follows the device, with a switch for the visitor |
40
- | `config` | JSON of the options below | Nothing overridden |
464
+ | `theme` | `light`, `dark` or `system`. Setting it hides the theme switch | Follows the device, and visitors can switch |
465
+ | `config` | JSON of the [options](#options) | Nothing overridden |
41
466
 
42
- The studio takes the width it is given, and lays itself out by that width, not the screen's. `quote` is as tall as its
43
- content. `advanced` fills `100dvh`; set your own `height` on the element to change that.
467
+ You can change any of them at any time. Changing `api-url` or `mode` clears the files in the studio.
44
468
 
45
469
  ## Options
46
470
 
47
- Set `config` as a property, or as a JSON attribute, which suits server templates. Every key is optional.
471
+ Options override slicer-api's `printers.json` for this page. Every key is optional. Set them as a property, which is
472
+ easiest from JavaScript, or as JSON in the `config` attribute, which suits server templates.
48
473
 
49
474
  ```js
50
475
  document.querySelector('slicer-studio').config = {
51
476
  // the same names as printers.json, and they win over it
52
477
  currency: 'INR',
53
- pricePerGram: { PLA: 5, PETG: 6 }, // only these materials change
478
+ pricePerGram: { PLA: 5, PETG: 6 },
54
479
  priceRange: 15,
55
480
  regularMode: { supports: false, mode: 'estimate' },
56
481
  contact: { name: 'Acme Labs', email: 'hello@example.com' },
@@ -66,31 +491,39 @@ document.querySelector('slicer-studio').config = {
66
491
 
67
492
  | Key | Meaning |
68
493
  |---|---|
69
- | `currency` | A code such as `INR` or `USD` |
70
- | `pricePerGram` | Price per gram by material, merged over the API's |
71
- | `priceRange` | Show costs, weights and times as a range: the calculated figure up to this percent more. `0` shows exact figures |
72
- | `regularMode.supports` | Whether estimates include supports |
73
- | `regularMode.mode` | `estimate` (instant, from the model's shape), `exact` (sliced by OrcaSlicer) or `auto` |
74
- | `contact` | The lab's `name`, and the `email` that SLA and SLS enquiries go to |
75
- | `defaultPrinter` | The printer for estimates, one the API has profiles for |
76
- | `defaults` | `material`, `quality` (`standard`, `medium`, `high`), `infill` (10, 15, 20, then every 10 to 90) and `walls` (1 to 6). They apply to files added after they are set |
77
- | `cards` | Which cards show. They keep their fixed order and the grid closes around the gaps |
78
-
79
- Costs are worked out in the browser, so `currency`, `pricePerGram` and `priceRange` need nothing from the API. Anything
80
- invalid is left out, with a warning in the console. `cards` and `defaults` apply to `quote` mode; the rest applies to both.
494
+ | `currency` | A three-letter code such as `INR` or `USD` |
495
+ | `pricePerGram` | Price per gram by material. Only the materials you list change |
496
+ | `priceRange` | Shows cost, weight and time as a range, from the calculated figure up to this percent more. `0` shows exact figures |
497
+ | `regularMode.supports` | `true` if estimates include supports |
498
+ | `regularMode.mode` | `estimate` is instant, from the model's shape. `exact` is sliced by OrcaSlicer, and takes seconds to minutes per file. `auto` uses `exact` when the server has OrcaSlicer |
499
+ | `contact` | Your lab's `name`, and the `email` that SLA and SLS enquiries go to. The email button hides while no email is set |
500
+ | `defaultPrinter` | The printer for estimates, which must be one the API has profiles for |
501
+ | `defaults.material` | `PLA`, `PETG`, `ABS` or `TPU`. If the printer doesn't offer it, the first one it does offer is used |
502
+ | `defaults.quality` | `standard` (0.2 mm), `medium` (0.15 mm) or `high` (0.1 mm) |
503
+ | `defaults.infill` | `10`, `15`, `20`, `30`, `40`, `50`, `60`, `70`, `80` or `90` |
504
+ | `defaults.walls` | `1` to `6` |
505
+ | `cards` | Which [cards](#cards) to show |
506
+
507
+ - Setting `config` replaces the whole object, so include everything you want each time.
508
+ - `pricePerGram`, `regularMode` and `contact` merge with the API's values key by key.
509
+ - `defaults` apply to files added after they are set.
510
+ - Anything invalid is left out, with a `slicer-studio:` warning in the console.
511
+ - In `advanced` mode, only `defaultPrinter` has an effect, and only until someone picks a printer. The studio then
512
+ remembers their choice.
81
513
 
82
514
  ### Cards
83
515
 
84
- The cards are `process`, `model`, `files`, `material` (material and finish), `strength`, `cost` and `contact` (shown for
85
- SLA and SLS). Hiding one also takes away what it does:
516
+ The price page is made of cards: `process`, `model`, `files`, `material` (material and finish), `strength`, `cost` and
517
+ `contact` (shown for SLA and SLS). They keep a fixed order, and the grid closes around any you hide. Hiding a card also
518
+ removes what it does:
86
519
 
87
520
  | Hidden | What happens |
88
521
  |---|---|
89
- | `process` | Always FDM. The theme switch sits on this card, so it goes too |
90
- | `material`, `strength` | Customers get the `defaults` values, which is how you fix a choice |
522
+ | `process` | Always FDM. The theme switch is on this card, so it goes too |
523
+ | `material`, `strength` | Customers get your `defaults`, which is how you fix a choice for them |
91
524
  | `files` | One file at a time: a new file replaces the current one |
92
- | `cost` | No Get the price button. Call `getPrice()` and show the `estimate` event yourself |
93
- | `model` and `files` | Nowhere to add a file, so `model` stays, with a console warning |
525
+ | `cost` | No **Get the price** button. Call `getPrice()` and show the `estimate` event yourself |
526
+ | `model` and `files` | There would be nowhere to add a file, so `model` stays, with a console warning |
94
527
 
95
528
  ## Events and methods
96
529
 
@@ -102,201 +535,193 @@ studio.addEventListener('estimate', e => {
102
535
  console.log(`${range.low} to ${range.high} ${currency} for ${files.length} files`);
103
536
  });
104
537
 
105
- studio.getPrice(); // what the Get the price button does
538
+ studio.getPrice(); // does what the Get the price button does
106
539
  ```
107
540
 
108
- `estimate` fires when every file is priced, and again when the totals change, such as when the customer changes the
109
- copies. `getPrice()` fires it again if everything is already priced. The event's `detail` holds:
110
-
111
- | Field | Meaning |
112
- |---|---|
113
- | `currency` | The currency code |
114
- | `range` | `{ low, high }` for all the files, or `null` while a material has no price |
115
- | `unpriced` | The materials with no price |
116
- | `gramsRange`, `secondsRange` | `{ low, high }` weight in grams and print time in seconds |
117
- | `quick` | `true` for estimates from the model's shape, not sliced |
118
- | `files` | One entry each: `name`, `file` (the customer's `File`), `copies`, `settings`, `range`, `gramsRange`, `secondsRange` |
541
+ ### `estimate`
119
542
 
120
- **Work the price out again on your server before you charge for it.** Anything in a browser can be changed, including
121
- this event.
543
+ Fires on the price page once every file is priced, and again whenever the totals change, such as when a customer changes
544
+ the copies. It doesn't fire for SLA or SLS, or in `advanced` mode. A typical `e.detail`:
122
545
 
123
- `modechange` fires when the Simple / Advanced switch is used, with `{ mode }` in its `detail`.
546
+ ```js
547
+ {
548
+ currency: 'INR',
549
+ range: { low: 61, high: 71 }, // total cost; null if a material has no price
550
+ gramsRange: { low: 12, high: 15 }, // total weight
551
+ secondsRange: { low: 1380, high: 1680 }, // total print time, with prints run one after another
552
+ unpriced: [], // materials with no price
553
+ quick: true, // true if estimated from the model's shape, not sliced
554
+ files: [{
555
+ name: 'bracket.stl',
556
+ file: File, // the customer's File object
557
+ copies: 1,
558
+ settings: { printer: '', material: 'PLA', quality: 'standard', infill: 15, walls: 3 },
559
+ range: { low: 61, high: 71 }, // these three are for all of this file's copies
560
+ gramsRange: { low: 12, high: 15 },
561
+ secondsRange: { low: 1380, high: 1680 },
562
+ }],
563
+ }
564
+ ```
124
565
 
125
- ## Set up the API
566
+ With `priceRange` at `0`, `low` and `high` are the same exact figure. Otherwise they are whole numbers.
126
567
 
127
- Set these on slicer-api. Its README explains each one.
568
+ ### `modechange`
128
569
 
129
- - `ALLOWED_ORIGINS`: the sites that embed the studio. Without it, browsers block calls from other sites.
130
- - `RATE_LIMIT_PER_MIN`: turn this on for any API a public page can reach.
131
- - `TRUST_PROXY`: how many proxies sit in front of the API.
132
- - Leave `API_KEY` unset behind a public price page. There is deliberately no attribute for a key: anything in a page's
133
- source is public.
570
+ Fires when someone uses the Simple / Advanced switch, with `{ mode }` in `detail`. The switch only appears in `advanced`
571
+ mode, and setting the attribute yourself doesn't fire the event.
134
572
 
135
- Each deployment has one `printers.json`, so a lab runs its own API for its own printers and prices.
573
+ ### `getPrice()`
136
574
 
137
- ## On your stack
575
+ Prices every file that needs it, and `estimate` fires when it's done. If everything is already priced, `estimate` fires
576
+ again. It does nothing while there are no files, while SLA or SLS is selected, while a price is being worked out, or
577
+ when the API can't be reached.
138
578
 
139
- **Laravel.** Import it in `resources/js/app.js`, then in a Blade template:
579
+ The element needs to be loaded first, so wait for it if your code might run earlier:
140
580
 
141
- ```blade
142
- <slicer-studio api-url="{{ config('services.slicer.url') }}" config='@json($studio)'></slicer-studio>
581
+ ```js
582
+ await customElements.whenDefined('slicer-studio');
583
+ studio.getPrice();
143
584
  ```
144
585
 
145
- **Vue.** Tell the compiler it's a custom element, in `vite.config.js`:
586
+ ## Layout and styling
146
587
 
147
- ```js
148
- vue({ template: { compilerOptions: { isCustomElement: tag => tag === 'slicer-studio' } } })
149
- ```
588
+ The studio is as wide as its container, and you can style the tag like any block:
150
589
 
151
- ```vue
152
- <slicer-studio api-url="https://api.example.com" :config.prop="options" @estimate="onEstimate" />
590
+ ```css
591
+ slicer-studio {
592
+ max-width: 1200px;
593
+ margin: 0 auto;
594
+ }
153
595
  ```
154
596
 
155
- **React 19** passes properties and events straight through:
597
+ - **Columns follow the studio's width, not the screen's.** It has one column below 640px, two up to 1023px and four from
598
+ 1024px, so a narrow sidebar gets the phone layout on a wide screen.
599
+ - **Height:** `quote` is as tall as its content. `advanced` fills `100dvh`, and your own `height` wins:
156
600
 
157
- ```jsx
158
- <slicer-studio api-url="https://api.example.com" config={options} onestimate={onEstimate} />
159
- ```
601
+ ```css
602
+ slicer-studio[mode="advanced"] { height: calc(100dvh - 64px); }
603
+ ```
160
604
 
161
- **React 18 and older** only set attributes, so use JSON and a ref:
605
+ - **Before it loads,** the tag has no size. To stop the page jumping, reserve some room:
162
606
 
163
- ```jsx
164
- const studio = useRef(null);
165
- useEffect(() => {
166
- const el = studio.current;
167
- el.addEventListener('estimate', onEstimate);
168
- return () => el.removeEventListener('estimate', onEstimate);
169
- }, []);
607
+ ```css
608
+ slicer-studio:not(:defined) { display: block; min-height: 600px; }
609
+ ```
170
610
 
171
- <slicer-studio ref={studio} api-url="https://api.example.com" config={JSON.stringify(options)} />
172
- ```
611
+ - **Your page's CSS can't reach inside.** There is no supported way to change the studio's colours or fonts yet, only
612
+ `theme`.
173
613
 
174
- Server rendering is safe: on a server the import does nothing, and the element starts in the browser.
614
+ ## Taking orders
175
615
 
176
- ## Good to know
616
+ **Work the price out again on your server before you charge for it.** Everything in a browser can be changed, including
617
+ the `estimate` event and your `pricePerGram`.
177
618
 
178
- - **Size:** about 210 kB gzipped to start, with the 3D view (about 250 kB) and the fonts (about 240 kB) loading after.
179
- - **Content Security Policy:** Advanced's G-code reader needs `worker-src blob:`. Fonts load as data URIs, so `font-src`
180
- needs `data:`.
181
- - **Browsers:** recent Chrome, Edge and Firefox, and Safari 16.4 or newer.
182
- - **One studio per page:** a second works, but both show every toast.
183
- - **Popups** stay inside your page's stacking context, so a host element with a `transform`, or a higher `z-index`, can
184
- cover them.
185
- - **Theming:** colours can't be overridden yet.
186
-
187
- ## What's inside: the price page
188
-
189
- This is `mode="quote"`.
190
-
191
- A bento of tiles: the customer's model is the big one, the choices sit around it, and the price is the black tile.
192
- Phones get one column in reading order. Every estimate uses the lab's default printer, and supports and exact or
193
- quick estimates follow the config (`regularMode`), so the customer is never asked about them.
194
-
195
- - **How should we print it?** FDM (filament), SLA (resin) or SLS (nylon powder), for all the files.
196
- - **FDM** is priced here, with the tiles below.
197
- - **SLA and SLS** are quoted by the lab's team for now: their tile says what the process is good for and has an
198
- "Email us about SLA / SLS" button, a ready email to `contact.email` listing the customer's files (the button
199
- hides while no email is set).
200
- - **Model**: drop one model or several anywhere on the page, or choose them; up to 10, each up to 50 MB. The
201
- selected model stands on a plate, with its size and size lines around it. The toolbar centres the model, zooms, shows or hides the size lines and goes
202
- fullscreen; the axes in the corner turn with the view, and clicking a letter looks along that axis; **Reset view**
203
- goes back to the starting angle. STL, 3MF and OBJ are previewed; STEP and IGES can't be, but are priced all the
204
- same. No sliced layers here: those are for Advanced, whose model preview is the same viewer.
205
- - **Your files**: a box to add more files, and a card for each, two to a page, with a picture of the model, its size and how it
206
- stands. Once priced, a card shows the weight, print time and cost of all its copies, with a stepper for how many
207
- (1 to 50); copies only multiply the figures, so changing them needs no new estimate. The choice tiles show the
208
- selected file's settings; the ⋮ menu copies a file's settings (not its copies) to the other files, or
209
- removes it. Choices made before uploading are what the first files start with.
210
- - **Material** (PLA, PETG, ABS, TPU), **Finish** (a three-stop slider: Standard 0.2 mm, Fine 0.15 mm, Extra fine
211
- 0.1 mm) and **Strength** (infill 10% to 90%, walls 1 to 6), per file.
212
- - **Estimated price**: "Get the price" works out each file that needs it, one after another (its card says why if
213
- one fails; the others carry on). Cost, weight and time all show as ranges: the calculated figure rounded down, up to
214
- `priceRange` percent more rounded up, in whole rupees, grams and minutes (₹21.93 with 20% reads ₹21 – ₹27), the
215
- files' ranges added up, and the ⓘ says how the price is worked out. Print time assumes the prints run one after
216
- another. After a change a warning says so and it offers "Update the price"; once everything is priced, **View
217
- details** opens one line per file and the totals.
218
-
219
- Customers never see a way into Advanced from this mode. Each mode keeps its own files, so switching starts the other
220
- one fresh.
221
-
222
- ## What's inside: Advanced
223
-
224
- This is `mode="advanced"`, with every option, for whoever runs the printers:
225
-
226
- 1. **Models**: one or several, as on the price page, with **Turn** buttons (tip forward, tip sideways, spin) to set which side the selected one prints on. Steps 2 to 4 are the
227
- selected model's settings, so each model can have its own printer and presets; "Use for all" copies them to
228
- the other models. Each row shows the model's weight and time once sliced, with the total under the list.
229
- 2. **Printer**: "Our printers" (from `printers.json`) come first. "My printer" uses the house templates in
230
- slicer-api's `templates/`. Otherwise pick a brand, then a model,
231
- then the nozzle; all of OrcaSlicer's printers are listed. The last printer is remembered.
232
- 3. **Material**: the materials that printer has profiles for; process and filament presets are under
233
- "Process and filament presets".
234
- 4. **Print settings**: layer height, supports, and bars for infill and walls. "Default" sends nothing, so the printer's
235
- own profile decides; the reset button next to a bar goes back to it.
236
-
237
- "Slice model" (or "Slice 3 models") sends each model that needs it to `/api/quote` with `gcode=true`, one after
238
- another, and the view opens the selected model's G-code; select another row to see its own. G-code you already have opens
239
- with "Open G-code" (or drop it on the page), and so do sliced 3MF projects from Bambu Studio and OrcaSlicer
240
- (`.gcode.3mf`): with several plates it asks which one, and shows the plate's thumbnail under print details.
241
- These files are read in your browser, nothing is uploaded.
242
-
243
- In the view, lines are colored by feature with the share of filament each uses. Click a feature to hide it,
244
- Alt-click to see only it. The ruler on the right is the print's Z axis: drag its top and bottom handles to show
245
- only those layers. Switch between 3D, top and front views, show travel moves, drag to orbit, scroll to zoom,
246
- right-drag to pan. Weight, time and filament length are under the view; the info button has every detail.
247
-
248
- If the API has `API_KEY` set, enter it with the key icon; it is kept in that browser.
249
-
250
- ## Working on this repo
251
-
252
- Start slicer-api first (its `docker compose up --build -d` serves the API on port 3000).
619
+ The event includes each customer's `File`, so you can send the order to your server:
620
+
621
+ ```js
622
+ let order = null;
623
+ studio.addEventListener('estimate', e => { order = e.detail; });
624
+
625
+ orderButton.addEventListener('click', async () => {
626
+ const form = new FormData();
627
+ for (const { file, copies, settings } of order.files) {
628
+ form.append('models', file);
629
+ form.append('lines', JSON.stringify({ copies, settings }));
630
+ }
631
+ await fetch('/orders', { method: 'POST', body: form });
632
+ });
633
+ ```
634
+
635
+ Then have your server ask slicer-api for each file's weight, with the same settings:
253
636
 
254
637
  ```bash
255
- npm install
256
- npm run dev
638
+ curl https://api.example.com/api/quote \
639
+ -F model=@bracket.stl \
640
+ -F "printer=Bambu Lab A1 0.4 nozzle" \
641
+ -F material=PLA -F quality=standard -F infill=15 -F walls=3 \
642
+ -F supports=true \
643
+ -F mode=estimate
257
644
  ```
258
645
 
259
- It opens at http://localhost:5173, with `/api` and `/health` forwarded to port 3000 (set `API_URL` for another address).
260
- `npm test` runs the tests. `npm run build` makes the package in `dist/`, and `npm run build:site` makes our own page in
261
- `dist-site/`.
646
+ ```json
647
+ { "stats": { "weightG": 12.33, "seconds": 1437, "sizeMm": [30, 30, 30], "volumeCm3": 27, "watertight": true, "estimated": true } }
648
+ ```
262
649
 
263
- `src/element.js` is the element. It mounts `src/studio/Studio.jsx`, which picks the mode: the price page is
264
- `components/quote/QuotePage.jsx` (with a component per card next to it) and Advanced is `components/AdvancedPage.jsx`.
265
- What both share, the file list and slicing each file in turn, is `hooks/useModelFiles.js` on top of `lib/model-files.js`.
650
+ - The studio's `settings` leave out the printer, supports and mode. Send your `defaultPrinter`, `regularMode.supports` and
651
+ `regularMode.mode` for those.
652
+ - The cost is `weightG × copies × price per gram`. The page shows that rounded down as `low`, and
653
+ `cost × (1 + priceRange / 100)` rounded up as `high`.
266
654
 
267
- `patches/` fixes Radix UI, which reads `document.activeElement` and so can't see focus move inside a shadow root.
268
- `npm install` applies the patches. When a Radix update comes, check that they still apply, and that arrow keys and Tab
269
- still work in menus and dialogs.
655
+ ## Staff access
270
656
 
271
- ### Our own page
657
+ `mode="advanced"` is not a lock. Anyone can change an attribute in their browser's tools, so put staff pages behind your
658
+ own login.
272
659
 
273
- `index.html` and `src/site.js` are the page we host: the element filling the window, with Advanced at `#advanced`.
660
+ - **Don't use `API_KEY` on an API that serves a public price page.** The studio could load but not price anything, and a
661
+ key in a page's source isn't secret. That is why there is no attribute for one.
662
+ - **`API_KEY` does suit a staff-only API.** Advanced shows a key button, and keeps the key in that browser.
663
+ - **`ALLOWED_ORIGINS` limits browsers, not scripts,** so a public API still needs `RATE_LIMIT_PER_MIN`.
274
664
 
275
- ```bash
276
- docker compose up --build -d
277
- ```
665
+ ## Content Security Policy
278
666
 
279
- It is at http://localhost:8080. nginx forwards `/api` and `/health` to `API_UPSTREAM`, which defaults to the API on the
280
- same machine:
667
+ If your site sends a CSP header, it needs these:
281
668
 
282
- ```bash
283
- API_UPSTREAM=http://api.example.com:3000 docker compose up --build -d
669
+ ```text
670
+ script-src 'self';
671
+ connect-src https://api.example.com;
672
+ img-src 'self' data: blob:;
673
+ font-src data:;
674
+ worker-src blob:;
284
675
  ```
285
676
 
286
- Sites can also embed this page in an iframe. Each time its height changes, it tells the parent page, which can size the
287
- frame so it never scrolls inside:
677
+ | Directive | Why |
678
+ |---|---|
679
+ | `script-src` | Add `https://cdn.jsdelivr.net` if you load the package from the CDN |
680
+ | `connect-src` | Your API. Leave it as `'self'` if the API is on your own origin |
681
+ | `img-src` | Model pictures on the file cards |
682
+ | `font-src` | The fonts are built in as data URIs. Without this the studio uses system fonts |
683
+ | `worker-src` | Advanced's G-code reader. Without this it shows `Could not read this G-code: parser failed` |
288
684
 
289
- ```html
290
- <iframe id="sfl-quote" src="https://quote.example.org/" title="3D printing prices" allow="fullscreen" style="width: 100%; border: 0; height: 900px"></iframe>
291
- <script>
292
- addEventListener('message', e => {
293
- if (e.origin !== 'https://quote.example.org' || !e.data || e.data.type !== 'superfablab-quote:height') return;
294
- document.getElementById('sfl-quote').style.height = e.data.height + 'px';
295
- });
296
- </script>
297
- ```
685
+ `style-src` needs nothing added. Without `'unsafe-inline'`, the console logs two `Applying inline style violates` errors
686
+ from the toast library. They are harmless, because the studio's styles don't depend on them.
687
+
688
+ ## Troubleshooting
689
+
690
+ | What you see | Cause | Fix |
691
+ |---|---|---|
692
+ | Nothing on the page, and the tag has no size | The package didn't load | Run `customElements.get('slicer-studio')` in the console. If it's `undefined`, check your import or script tag |
693
+ | `The server can't be reached.` and `blocked by CORS policy` in the console | Your site isn't allowed | Add its exact origin to `ALLOWED_ORIGINS`, then run `docker compose up -d` |
694
+ | `The server can't be reached.` and `ERR_CONNECTION_REFUSED` in the console | Wrong `api-url`, or the API is down | Check `https://your-api/health` in a browser |
695
+ | `The server can't be reached.` and `Mixed Content` in the console | An `https://` page is calling an `http://` API | [Serve the API over HTTPS](#4-serve-the-api-over-https) |
696
+ | `No price set for PLA yet` | That material has no price | Add it to `pricePerGram` |
697
+ | `Missing or wrong x-api-key` | The API has `API_KEY` set | Remove it from a public API, see [Staff access](#staff-access) |
698
+ | `Too many requests. Try again in a minute.` | The rate limit was reached | Raise `RATE_LIMIT_PER_MIN` |
699
+ | A large file fails, with status 413 in the browser's Network tab | Your proxy's upload limit is too low | Raise `client_max_body_size` in nginx |
700
+ | `slicer-studio: config is not valid JSON` | An object reached the `config` attribute as `[object Object]` | Set the `config` property in an effect, or use `JSON.stringify` |
701
+ | `slicer-studio: unknown config key` | A typo in an option's name | Check it against [Options](#options) |
702
+ | Your options and events do nothing, with no error | React 19's short form after server rendering | Use the [effect](#react) instead |
703
+ | `Failed to resolve component: slicer-studio` | Vue doesn't know the tag | Set `isCustomElement`, see [Vue](#vue) |
704
+ | `bundle initial exceeded maximum budget` | Angular's size limit | Load it with `import()`, see [Angular](#angular) |
705
+ | `Could not find a declaration file for module 'slicer-studio'` | TypeScript and `import()` | Add `declare module 'slicer-studio';`, see [Angular](#angular) |
706
+ | Popups appear in the wrong place or behind your header | A parent has a `transform`, or your header has a higher `z-index` | Remove the `transform`, or lower the header's `z-index` |
298
707
 
299
- Replace `https://quote.example.org` with where this page is served. `allow="fullscreen"` lets the model preview go
300
- fullscreen; without it that button stays away.
708
+ ## Good to know
301
709
 
302
- Built with React, react-three-fiber (three.js), Tailwind CSS, Radix UI, cmdk, Motion, TanStack Query, Lucide icons and Sonner.
710
+ - **Browsers:** Chrome and Edge 111+, Firefox 128+, Safari 16.4+. The 3D views need WebGL.
711
+ - **Files:** STL, 3MF, OBJ, STEP and IGES, up to 10 at once and 50 MB each, with at most 500,000 triangles. STEP and IGES
712
+ are priced but have no 3D preview. A model too big for the printer's bed gets an error on its card.
713
+ - **Size:** about 210 kB gzipped to start, with the 3D view (about 250 kB) and the fonts (about 240 kB) loading after.
714
+ - **Server rendering:** importing the package on a server is safe, and does nothing. The studio has no server-rendered
715
+ content, so set `config` and listeners in browser code, or give `config` as a JSON attribute.
716
+ - **One studio per page:** a second one works, but both show every toast.
717
+ - **Moving and removing:** moving the tag in the page keeps the customer's files. Removing it clears them.
718
+ - **What it adds to your page:** its fonts, some CSS `@property` rules, and one `<style>` for toasts. Nothing else touches
719
+ your page.
720
+ - **What it stores:** in `localStorage`, the visitor's theme (`print-preview.theme`) and, in Advanced, the last printer
721
+ (`print-preview.printer`) and the API key (`gcode-viewer.api-key`).
722
+ - **Updating:** run `npm update slicer-studio`, or change the version in your CDN link. Price and printer changes need no
723
+ update, because the studio reads them from the API.
724
+
725
+ ## License
726
+
727
+ ISC