@3dsource/metabox-modular-configurator-api 3.0.9 → 3.0.11

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,8 +1,6 @@
1
1
  # Metabox Modular Configurator API
2
2
 
3
- A powerful TypeScript API for integrating and controlling the Metabox Modular Configurator in web
4
- applications. This package provides seamless communication with 3D configurators, allowing you to control environments,
5
- components, component types, materials, and capture screenshots or PDFs.
3
+ TypeScript/JavaScript API for integrating Metabox Modular Configurator into web applications. Provides programmatic control over modular product configurations, component assembly, materials, environments, and export functionality.
6
4
 
7
5
  ## Table of Contents
8
6
 
@@ -36,6 +34,7 @@ components, component types, materials, and capture screenshots or PDFs.
36
34
  - [UI / Interface](#ui--interface)
37
35
  - [Camera / View](#camera--view)
38
36
  - [Showcase Control](#showcase-control)
37
+ - [Measurement Control](#measurement-control)
39
38
  - [Export / Media](#export--media)
40
39
  - [Unreal / Advanced](#unreal--advanced)
41
40
  - [Event Handling](#event-handling)
@@ -50,44 +49,64 @@ components, component types, materials, and capture screenshots or PDFs.
50
49
 
51
50
  ## Features
52
51
 
53
- - 🚀 Easy integration with any web framework (Angular, React, Vue, etc.)
54
- - 📱 Responsive design support
55
- - 🎨 Full control over materials, environments, and components
56
- - 📸 Screenshot and PDF generation
57
- - 🛒 Call-to-Action (CTA) data generation
58
- - 🎬 Showcase management
59
- - 📦 TypeScript support with full type definitions
60
- - 🌐 CDN support for quick prototyping
52
+ - Framework-agnostic integration (Angular, React, Vue, vanilla JS)
53
+ - Modular component assembly and configuration
54
+ - Material and environment management per component
55
+ - Real-time configuration state synchronization
56
+ - Screenshot and PDF export capabilities
57
+ - E-commerce CTA workflow support
58
+ - Showcase/animation playback control
59
+ - Full TypeScript type definitions
60
+ - CDN support for rapid prototyping
61
+ - Event-driven architecture for reactive UI
61
62
 
62
63
  ## Prerequisites
63
64
 
64
- - Modern web browser with ES6 module support
65
- - HTTPS connection (required for Unreal Engine)
66
- - Valid Metabox configurator ID (not a full URL)
65
+ **Runtime Requirements:**
67
66
 
68
- Important: integrateMetabox validates inputs at runtime. It requires a non-empty configuratorId and a non-empty containerId. The iframe URL is constructed internally as `https://{domain}/metabox-configurator/modular/{configuratorId}` with optional query parameters (introImage, introVideo, loadingImage). HTTPS is enforced and non-HTTPS URLs are rejected. It will throw if the container element is not found.
67
+ - Modern browser with ES6 module support (Chrome 61+, Firefox 60+, Safari 11+, Edge 79+)
68
+ - HTTPS connection (required by Unreal Engine streaming)
69
+ - Valid Metabox modular configurator ID
70
+
71
+ **Development Environment:**
72
+
73
+ - Node.js >= 20 (for NPM installation)
74
+ - npm > 9
75
+
76
+ **Important Notes:**
77
+
78
+ - `integrateMetabox()` validates inputs at runtime
79
+ - Requires non-empty `configuratorId` and `containerId`
80
+ - Iframe URL format: `https://{domain}/metabox-configurator/modular/{configuratorId}`
81
+ - Optional query parameters: `introImage`, `introVideo`, `loadingImage`
82
+ - HTTPS is strictly enforced (HTTP URLs will be rejected)
83
+ - Throws error if container element not found in DOM
69
84
 
70
85
  ## Installation
71
86
 
72
87
  ### NPM Installation (Recommended)
73
88
 
74
- For use with modern frameworks like Angular, React, Vue, etc.:
89
+ **Installation:**
75
90
 
76
91
  ```bash
77
92
  npm install @3dsource/metabox-modular-configurator-api@latest --save
78
93
  ```
79
94
 
80
- ### CDN Installation
95
+ **Import:**
81
96
 
82
- For direct browser usage without a build system:
97
+ ```typescript
98
+ import { integrateMetabox, Communicator, ModularConfiguratorEnvelope, SetComponent, SetComponentMaterial, SetEnvironment, GetScreenshot, saveImage } from '@3dsource/metabox-modular-configurator-api';
99
+ ```
100
+
101
+ ### CDN Installation (Quick Prototyping)
102
+
103
+ **jsDelivr:**
83
104
 
84
105
  ```javascript
85
- import { integrateMetabox, Communicator, SetEnvironment, SetComponent } from 'https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api@latest/+esm';
106
+ import { integrateMetabox, SetComponent, SetEnvironment, GetScreenshot, saveImage } from 'https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api@latest/+esm';
86
107
  ```
87
108
 
88
- Alternative CDN options:
89
-
90
- - **jsDelivr**: `https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api@latest/+esm`
109
+ > **Note:** For production, pin a specific version instead of using `@latest`
91
110
 
92
111
  ## Quick Start
93
112
 
@@ -275,87 +294,165 @@ configurator.changeMaterial('componentId', 'seat-fabric', 'leather-brown');
275
294
 
276
295
  ### System Terminology
277
296
 
278
- - **product** - 3D digital twin of the actual physical product within a Metabox system; concept is used in Basic configurator.
279
- - **productId** - Unique Product ID within the Metabox system; mandatory. Assigned by the Metabox system automatically after the product's 3D digital twin is uploaded into Metabox.
280
- - **environment** - 3D digital twin of the actual environment (room scene or other) within a Metabox system.
281
- - **environmentId** - Unique environment ID within the Metabox system; mandatory. Assigned by the Metabox system automatically after the environment's 3D digital twin is uploaded into Metabox.
282
- - **externalId** - Product or Material ID assigned to product or material in Metabox; optional; can be a combination of letters or numbers or both. Should be identical to the product SKU number in any other non-Metabox e-commerce system that is used for managing products, so Metabox can be integrated with such a system.
283
- - **showcase** - Exists as an attribute of product only; optional. If present, it means the product's digital twin contains a camera sequence that causes the video mode added automatically to the configurator by Metabox system to play this camera sequence.
284
- - **component** - Product in the Modular configurator context.
285
- - **componentId** - Unique Component ID within the Metabox system; mandatory. Assigned by the Metabox system automatically after the Modular configurator is created in Metabox.
286
- - **componentType** - Exists in Modular Configurator only; the name of the type of the product component, which can include one or several separate products of the same category (examples of product component types: truck wheel, truck bumper). It is set by an unreal artist while creating the digital twin model and is automatically added to the Metabox system after this twin is uploaded to Metabox.
287
- - **E‑Com Configurator** — can be created from any Basic or Modular Configurator by adding a CTA (call‑to‑action) button to the standard configurator right‑nav menu in the Metabox Configurator Manager (where users create and edit configurators).
288
- To enable the CTA button, add two mandatory parameters in the Configurator Manager:
289
- - Text label for the CTA button (examples: "Get Quote", "Contact Dealer").
290
- - Callback URL for an HTTP POST request. Response requirements:
291
- ```json
292
- {
293
- "redirectUrl": "https://your.site/thank-you-or-checkout"
294
- }
295
- ```
296
- When the user clicks the CTA button in the configurator:
297
- - Metabox generates a JSON payload with the current configuration and sends it to the specified Callback URL.
298
- - Your backend decides how to use the configuration JSON (e.g., generate a PDF or build a product list).
299
- - After your endpoint responds with a JSON containing "redirectUrl", the user is redirected in a new browser tab to that URL (a non‑Metabox page on your side) to complete the flow (e.g., leave contact information, proceed to checkout, etc.).
297
+ | Term | Description | Required | Context |
298
+ | --------------------- | -------------------------------------------------------------- | -------- | ---------------------- |
299
+ | **component** | Modular product part/assembly (e.g., wheel, bumper, seat) | Yes | Modular configurator |
300
+ | **componentId** | Unique component identifier (system-generated UUID) | Yes | Component management |
301
+ | **componentType** | Category/classification of component (e.g., "wheel", "bumper") | Yes | Component organization |
302
+ | **environment** | 3D scene/room environment for product visualization | Yes | Visual context |
303
+ | **environmentId** | Unique environment identifier (system-generated UUID) | Yes | Environment management |
304
+ | **product** | Base 3D digital twin referenced by components | Yes | Component definition |
305
+ | **productId** | Unique product identifier (system-generated UUID) | Yes | Product reference |
306
+ | **externalId** | Custom SKU/identifier for external system integration | No | E-commerce integration |
307
+ | **showcase** | Camera animation sequence attached to component | No | Component attribute |
308
+ | **slotId** | Material slot identifier on component/environment | Yes | Material assignment |
309
+ | **materialId** | Unique material identifier | Yes | Material assignment |
310
+ | **configurationTree** | Hierarchical structure of component assembly | - | State representation |
311
+
312
+ **Key Differences from Basic Configurator:**
313
+
314
+ | Aspect | Basic Configurator | Modular Configurator |
315
+ | ------------------------ | ---------------------------- | --------------------------------------- |
316
+ | **Product Model** | Single monolithic product | Composed of multiple components |
317
+ | **Configuration** | Select one product at a time | Assemble components by type |
318
+ | **Material Application** | Per-product slots | Per-component and per-environment slots |
319
+ | **State Complexity** | Flat structure | Hierarchical tree structure |
320
+
321
+ **E-Commerce Configurator (CTA Integration):**
322
+
323
+ E-Com configurators extend Basic/Modular configurators with a call-to-action button.
324
+
325
+ **Configuration:**
326
+
327
+ 1. **CTA Button Label:** Custom text (e.g., "Request Quote", "Add to Cart")
328
+ 2. **Callback URL:** HTTP POST endpoint for configuration data
329
+
330
+ **CTA Workflow:**
300
331
 
301
- ### Steps to build a custom menu
332
+ ```
333
+ User clicks CTA → Metabox POSTs config JSON → Backend processes → Returns { redirectUrl } → User redirected
334
+ ```
335
+
336
+ **Backend Response Format:**
337
+
338
+ ```json
339
+ {
340
+ "redirectUrl": "https://your.site/checkout-or-thank-you"
341
+ }
342
+ ```
343
+
344
+ **Use Cases:**
302
345
 
303
- Updated recommendations:
346
+ - Generate configuration PDFs
347
+ - Create a shopping cart with BOM (Bill of Materials)
348
+ - Send lead to CRM with component details
349
+ - Redirect to custom checkout with modular pricing
304
350
 
305
- - Use `configuratorDataUpdated` to hydrate custom UI and subscribe for deltas.
306
- - Hide built‑in menu: `ShowEmbeddedMenu(false)`; restore with `ShowEmbeddedMenu(true)`.
307
- - Hide overlay elements if replacing viewport controls: `ShowOverlayInterface(false)`.
351
+ ### Building a Custom UI
352
+
353
+ To create a custom modular configurator interface:
354
+
355
+ **1. Listen to Configuration State**
356
+
357
+ ```typescript
358
+ api.addEventListener('configuratorDataUpdated', (data: ModularConfiguratorEnvelope) => {
359
+ // Update UI with component tree, materials, environment
360
+ updateComponentSelector(data.componentsByComponentType);
361
+ updateMaterialOptions(data.componentMaterialsIds);
362
+ });
363
+ ```
364
+
365
+ **2. Hide Default UI Elements**
366
+
367
+ ```typescript
368
+ api.sendCommandToMetabox(new ShowEmbeddedMenu(false)); // Hide sidebar
369
+ api.sendCommandToMetabox(new ShowOverlayInterface(false)); // Hide viewport controls
370
+ ```
371
+
372
+ **3. Control Component Assembly**
373
+
374
+ ```typescript
375
+ // Add root component
376
+ api.sendCommandToMetabox(new SetComponent('component-id', 'wheel', true));
377
+
378
+ // Add child components
379
+ api.sendCommandToMetabox(new SetComponent('tire-id', 'tire', false));
380
+
381
+ // Apply materials per component
382
+ api.sendCommandToMetabox(new SetComponentMaterial('component-id', 'rim', 'chrome'));
383
+
384
+ // Change environment
385
+ api.sendCommandToMetabox(new SetEnvironment('environment-id'));
386
+ ```
387
+
388
+ **4. Export Configuration**
389
+
390
+ ```typescript
391
+ api.sendCommandToMetabox(new GetScreenshot('image/png', { x: 1920, y: 1080 }));
392
+ api.sendCommandToMetabox(new GetPdf());
393
+ api.sendCommandToMetabox(new GetCallToActionInformation());
394
+ ```
308
395
 
309
396
  ### Core Integration
310
397
 
311
- #### `integrateMetabox`
398
+ #### `integrateMetabox()`
312
399
 
313
- Integrates the Metabox Modular Configurator into the specified container element.
400
+ Embeds the Metabox Modular Configurator iframe and establishes communication channel.
314
401
 
315
- **TypeScript Signature:**
402
+ **Signature:**
316
403
 
317
404
  ```typescript
318
- declare function integrateMetabox(
319
- configuratorId: string,
320
- containerId: string, // defaults to 'embed3DSource'
321
- apiReadyCallback: (api: Communicator) => void, // required
322
- config?: IntegrateMetaboxConfig,
323
- ): void;
405
+ function integrateMetabox(configuratorId: string, containerId?: string, apiReadyCallback: (api: Communicator) => void, config?: IntegrateMetaboxConfig): void;
324
406
  ```
325
407
 
326
408
  **Parameters:**
327
409
 
328
- - `configuratorId` (required): Modular configurator ID (not full URL). Iframe src internally: `https://{domain}/metabox-configurator/modular/{configuratorId}`.
329
- - `containerId` (optional): Host element id (default `embed3DSource`).
330
- - `apiReadyCallback` (required): Called once the embedded app signals readiness (`appLoaded`).
331
- - `config` (optional):
332
- - `standalone?`: Disable built‑in template / UI logic inside iframe.
333
- - `introImage?`, `introVideo?`, `loadingImage?`: Optional URLs appended as query params when present.
334
- - `state?`: Optional initial configurator state.
335
- - `domain?`: Override default domain (HTTPS enforced).
410
+ | Parameter | Type | Required | Default | Description |
411
+ | ------------------ | ------------------------ | -------- | ----------------- | ---------------------------------------- |
412
+ | `configuratorId` | `string` | ✅ | - | Modular configurator UUID (not full URL) |
413
+ | `containerId` | `string` | ❌ | `'embed3DSource'` | DOM container element ID |
414
+ | `apiReadyCallback` | `function` | ✅ | - | Callback invoked when API is ready |
415
+ | `config` | `IntegrateMetaboxConfig` | ❌ | `{}` | Additional configuration options |
336
416
 
337
- **Throws:** Error if IDs empty, container missing, or computed iframe URL not HTTPS.
417
+ **Config Options (`IntegrateMetaboxConfig`):**
338
418
 
339
- **Notes:** A previous iframe with id `embeddedContent` is removed before adding a new one.
419
+ ```typescript
420
+ interface IntegrateMetaboxConfig {
421
+ standalone?: boolean; // Disable built-in Metabox UI
422
+ introImage?: string; // URL for intro image
423
+ introVideo?: string; // URL for intro video
424
+ loadingImage?: string; // URL for loading spinner
425
+ state?: ConfiguratorState; // Initial component tree state
426
+ domain?: string; // Override domain (HTTPS only)
427
+ }
428
+ ```
340
429
 
341
- **Example:**
430
+ **Validation & Errors:**
342
431
 
343
- ```typescript
344
- import { IntegrateMetaboxConfig } from '@3dsource/metabox-modular-configurator-api';
432
+ - Throws if `configuratorId` is empty
433
+ - Throws if a container element not found
434
+ - Throws if URL is not HTTPS
435
+ - Replaces existing iframe with ID `embeddedContent`
345
436
 
346
- const config: IntegrateMetaboxConfig = {
347
- introImage: 'https://example.com/intro.png',
348
- loadingImage: 'https://example.com/loading.png',
349
- standalone: false,
350
- };
437
+ **Example:**
351
438
 
439
+ ```typescript
352
440
  integrateMetabox(
353
- 'configurator-id',
354
- 'embed3DSource',
441
+ 'modular-config-uuid',
442
+ 'my-container',
355
443
  (api) => {
356
- console.log('API ready!', api);
444
+ console.log('Modular configurator ready');
445
+
446
+ // Set root component
447
+ api.sendCommandToMetabox(new SetComponent('comp-1', 'base', true));
448
+
449
+ // Set environment
450
+ api.sendCommandToMetabox(new SetEnvironment('env-1'));
451
+ },
452
+ {
453
+ standalone: true,
454
+ loadingImage: 'https://cdn.example.com/loader.gif',
357
455
  },
358
- config,
359
456
  );
360
457
  ```
361
458
 
@@ -372,9 +469,7 @@ The main API interface for sending commands and listening to events.
372
469
  ```typescript
373
470
  interface Communicator {
374
471
  sendCommandToMetabox<T extends keyof ToMetaboxMessagePayloads>(command: CommandBase<T>): void;
375
-
376
472
  addEventListener<K extends keyof FromMetaboxMessagePayloads>(eventType: K, listener: (data: FromMetaboxMessagePayloads[K]) => void): void;
377
-
378
473
  removeEventListener<K extends keyof FromMetaboxMessagePayloads>(eventType: K, listener: (data: FromMetaboxMessagePayloads[K]) => void): void;
379
474
  }
380
475
  ```
@@ -487,94 +582,179 @@ type ApplicationDeviceTypes = 'desktop' | 'tablet' | 'mobile';
487
582
 
488
583
  ### Command Classes
489
584
 
490
- All commands are dispatched via:
585
+ Commands control configurator behavior. Send via `api.sendCommandToMetabox(new CommandName(...))`.
586
+
587
+ #### Component & Environment Management
588
+
589
+ | Command | Parameters | Description |
590
+ | ------------------------ | --------------------------------------------------------- | ---------------------------------- |
591
+ | `SetComponent` | `componentId: string, typeId: string, isRoot: boolean` | Add/select component in assembly |
592
+ | `SetComponentMaterial` | `componentId: string, slotId: string, materialId: string` | Apply material to component slot |
593
+ | `SetEnvironment` | `environmentId: string` | Change environment/scene |
594
+ | `SetEnvironmentMaterial` | `slotId: string, materialId: string` | Apply material to environment slot |
595
+
596
+ **Component Assembly Example:**
491
597
 
492
598
  ```typescript
493
- api.sendCommandToMetabox(new SomeCommand(...));
599
+ // Set root component (e.g., vehicle chassis)
600
+ api.sendCommandToMetabox(new SetComponent('chassis-001', 'base', true));
601
+
602
+ // Add child component (e.g., wheel to chassis)
603
+ api.sendCommandToMetabox(new SetComponent('wheel-fr', 'wheel', false));
604
+
605
+ // Apply materials
606
+ api.sendCommandToMetabox(new SetComponentMaterial('chassis-001', 'body', 'metallic-blue'));
607
+ api.sendCommandToMetabox(new SetComponentMaterial('wheel-fr', 'rim', 'chrome'));
494
608
  ```
495
609
 
496
- #### Core Configuration Commands
610
+ #### UI Control
497
611
 
498
- - `SetComponent(id, typeId, isRoot)` – Add/select a component (root or child).
499
- - `SetComponentMaterial(componentId, slotId, materialId)` – Apply material to a component slot.
500
- - `SetEnvironment(id)` – Activate environment.
501
- - `SetEnvironmentMaterial(slotId, materialId)` – Apply material to environment slot.
612
+ | Command | Parameters | Description |
613
+ | ---------------------- | ------------------ | ---------------------------- |
614
+ | `ShowEmbeddedMenu` | `visible: boolean` | Show/hide right sidebar menu |
615
+ | `ShowOverlayInterface` | `visible: boolean` | Show/hide viewport controls |
502
616
 
503
- #### UI / Interface
617
+ #### Camera Control
504
618
 
505
- - `ShowEmbeddedMenu(visible)` – Toggle built‑in right sidebar menu.
506
- - `ShowOverlayInterface(visible)` – Toggle overlay UI elements (hotspots / viewport controls).
619
+ | Command | Parameters | Description |
620
+ | ------------- | -------------- | -------------------------------------------- |
621
+ | `ResetCamera` | None | Reset camera to default position |
622
+ | `ApplyZoom` | `zoom: number` | Apply zoom delta (positive=in, negative=out) |
507
623
 
508
- #### Camera / View
624
+ **Example:**
509
625
 
510
- - `ResetCamera()` – Reset to initial camera transform.
511
- - `ApplyZoom(zoom)` – Apply zoom delta (positive/negative). Respect configured min/max.
626
+ ```typescript
627
+ api.sendCommandToMetabox(new ApplyZoom(0.5)); // Zoom in
628
+ api.sendCommandToMetabox(new ApplyZoom(-0.25)); // Zoom out
629
+ api.sendCommandToMetabox(new ResetCamera()); // Reset view
630
+ ```
512
631
 
513
- #### Showcase Control
632
+ #### Showcase/Animation Control
514
633
 
515
- - `InitShowcase()` – Initialize a showcase sequence for current component/product context.
516
- - `PlayShowcase()` / `PauseShowcase()` / `StopShowcase()` – Playback controls.
634
+ | Command | Parameters | Description |
635
+ | --------------- | ---------- | ----------------------------------------- |
636
+ | `InitShowcase` | None | Initialize showcase for current component |
637
+ | `PlayShowcase` | None | Start/resume animation playback |
638
+ | `PauseShowcase` | None | Pause animation |
639
+ | `StopShowcase` | None | Stop and reset animation |
517
640
 
518
- #### Export / Media
641
+ #### Measurement Tools
519
642
 
520
- - `GetScreenshot(format, size?)` – Request ordered render; listen to `screenshotReady`.
521
- - `GetPdf()` – Request PDF generation (no dedicated completion event; follow status messages).
522
- - `GetCallToActionInformation()` – Trigger CTA flow; backend must respond with `{ redirectUrl }`.
643
+ | Command | Parameters | Description |
644
+ | ----------------- | ---------- | ---------------------------- |
645
+ | `ShowMeasurement` | None | Display component dimensions |
646
+ | `HideMeasurement` | None | Hide dimension overlay |
523
647
 
524
- #### Unreal / Advanced
648
+ #### Export & Media
525
649
 
526
- - `UnrealCommand(command: object | string)` – Send custom Unreal engine command (low‑level; not guaranteed stable).
527
- - `MetaboxConfig(appId, partialConfig)` – Initialization command auto‑sent internally.
650
+ | Command | Parameters | Description | Event Triggered |
651
+ | ---------------------------- | ------------------------------------------------- | -------------------- | ---------------------- |
652
+ | `GetScreenshot` | `format: MimeType, size?: {x: number, y: number}` | Render screenshot | `screenshotReady` |
653
+ | `GetPdf` | None | Generate PDF export | Server-side (no event) |
654
+ | `GetCallToActionInformation` | None | Trigger CTA workflow | Backend redirect |
528
655
 
529
- **Examples:**
656
+ **Screenshot Example:**
530
657
 
531
658
  ```typescript
532
- // Adjust zoom smoothly
533
- api.sendCommandToMetabox(new ApplyZoom(0.25)); // zoom in
534
- api.sendCommandToMetabox(new ApplyZoom(-0.25)); // zoom out
659
+ api.sendCommandToMetabox(new GetScreenshot('image/png', { x: 2048, y: 2048 }));
535
660
 
536
- // Low-level Unreal command (example payload)
537
- api.sendCommandToMetabox(new UnrealCommand({ action: 'SetLightIntensity', lightId: 'keyLight', value: 2.5 }));
661
+ api.addEventListener('screenshotReady', (imageData) => {
662
+ saveImage(imageData, 'assembly.png');
663
+ });
664
+ ```
665
+
666
+ #### Advanced Commands (Use with Caution)
667
+
668
+ | Command | Parameters | Description |
669
+ | --------------- | ------------------------------- | ----------------------------------- |
670
+ | `UnrealCommand` | `command: object \| string` | Send raw command to Unreal Engine |
671
+ | `MetaboxConfig` | `appId: string, config: object` | Internal initialization (auto-sent) |
538
672
 
539
- // Simpler string-based Unreal command variant (if supported)
673
+ **Warning:** `UnrealCommand` bypasses API validation. Use only for custom Unreal-specific features.
674
+
675
+ ```typescript
676
+ // Example: Custom lighting control
677
+ api.sendCommandToMetabox(
678
+ new UnrealCommand({
679
+ action: 'SetLightIntensity',
680
+ lightId: 'keyLight',
681
+ value: 2.5,
682
+ }),
683
+ );
684
+
685
+ // String-based command (if supported)
540
686
  api.sendCommandToMetabox(new UnrealCommand('SetSunTime 14:30'));
541
687
  ```
542
688
 
543
689
  ### Event Handling
544
690
 
545
- The below events originate from the embedded configurator (`FromMetaboxMessagePayloads`). Register via `api.addEventListener(name, handler)`.
691
+ Event-driven architecture for reactive state management. Register listeners via `api.addEventListener(eventName, handler)`.
546
692
 
547
- ### Available Events
693
+ #### Available Events
548
694
 
549
- | Event | Payload | Description |
550
- | ----------------------------- | ----------------------------- | --------------------------------------------------------------------- | -------------------- | ------- |
551
- | `configuratorDataUpdated` | `ModularConfiguratorEnvelope` | Any configuration change (components, types, materials, environment). |
552
- | `ecomConfiguratorDataUpdated` | `EcomConfigurator` | CTA label/callback updates (E‑Com enabled). |
553
- | `showcaseStatusChanged` | `ShowCaseStatus` | Showcase playback status: init, play, pause, stop. |
554
- | `dataChannelConnected` | `boolean` | Unreal data channel connectivity (true = connected). |
555
- | `viewportReady` | `boolean` | Unreal viewport visibility / readiness. |
556
- | `statusMessageChanged` | string or null | Loading / progress status messages. |
557
- | `screenshotReady` | string or null | Base64 image from latest screenshot (null if failed). |
558
- | `videoResolutionChanged` | object | Stream resolution changed. `{ width: number | null; height: number | null }` |
695
+ | Event | Payload Type | Description | Use Case |
696
+ | ----------------------------- | --------------------------------------------- | --------------------------- | ------------------------------------- |
697
+ | `configuratorDataUpdated` | `ModularConfiguratorEnvelope` | Configuration state changed | Sync UI with component tree/materials |
698
+ | `ecomConfiguratorDataUpdated` | `EcomConfigurator` | CTA configuration loaded | Display CTA button with label |
699
+ | `dataChannelConnected` | `boolean` | Unreal data channel status | Connection health monitoring |
700
+ | `viewportReady` | `boolean` | 3D viewport ready state | Hide loading, enable interactions |
701
+ | `showcaseStatusChanged` | `ShowCaseStatus` | Animation playback status | Update play/pause button state |
702
+ | `statusMessageChanged` | `string \| null` | Loading/progress message | Display user feedback |
703
+ | `screenshotReady` | `string \| null` | Base64 screenshot data | Download or display image |
704
+ | `videoResolutionChanged` | `{width: number\|null, height: number\|null}` | Stream resolution changed | Adjust viewport layout |
559
705
 
560
- ### Event Examples
706
+ #### Event Examples
707
+
708
+ **Configuration State Sync:**
561
709
 
562
710
  ```typescript
563
- api.addEventListener('configuratorDataUpdated', (env) => {
564
- console.log('Active environment:', env.environmentId);
565
- console.log('Components per type:', env.componentsByComponentType);
711
+ api.addEventListener('configuratorDataUpdated', (data: ModularConfiguratorEnvelope) => {
712
+ console.log('Environment:', data.environmentId);
713
+ console.log('Component tree:', data.configurationTree);
714
+ console.log('Components by type:', data.componentsByComponentType);
715
+ console.log('Component materials:', data.componentMaterialsIds);
716
+
717
+ // Update custom UI
718
+ updateComponentTree(data.configurationTree);
719
+ updateMaterialSelectors(data.componentMaterialsIds);
566
720
  });
721
+ ```
567
722
 
568
- api.addEventListener('screenshotReady', (img) => {
569
- if (img) saveImage(img, 'modular-configurator.png');
723
+ **Screenshot Handling:**
724
+
725
+ ```typescript
726
+ api.addEventListener('screenshotReady', (imageData: string | null) => {
727
+ if (!imageData) {
728
+ console.error('Screenshot failed');
729
+ return;
730
+ }
731
+
732
+ saveImage(imageData, `assembly-${Date.now()}.png`);
570
733
  });
734
+ ```
571
735
 
572
- api.addEventListener('dataChannelConnected', (connected) => {
573
- console.log('Unreal channel connected?', connected);
736
+ **Connection Monitoring:**
737
+
738
+ ```typescript
739
+ api.addEventListener('dataChannelConnected', (isConnected: boolean) => {
740
+ const indicator = document.getElementById('connection-status');
741
+ indicator.textContent = isConnected ? 'Connected' : 'Disconnected';
742
+ indicator.className = isConnected ? 'status-ok' : 'status-error';
574
743
  });
744
+ ```
745
+
746
+ **Loading State:**
575
747
 
576
- api.addEventListener('videoResolutionChanged', (res) => {
577
- console.log('Viewport resolution:', res.width, 'x', res.height);
748
+ ```typescript
749
+ api.addEventListener('viewportReady', (isReady: boolean) => {
750
+ if (isReady) {
751
+ hideLoadingSpinner();
752
+ enableComponentSelectors();
753
+ }
754
+ });
755
+
756
+ api.addEventListener('statusMessageChanged', (message: string | null) => {
757
+ document.getElementById('status-text').textContent = message || '';
578
758
  });
579
759
  ```
580
760
 
@@ -582,65 +762,127 @@ api.addEventListener('videoResolutionChanged', (res) => {
582
762
 
583
763
  ### Common Issues
584
764
 
585
- #### Configurator Not Loading
765
+ #### 1. Configurator Not Loading
766
+
767
+ **Symptoms:** Blank screen, iframe not appearing, loading indefinitely
586
768
 
587
- **Problem**: The configurator iframe doesn't appear or loads indefinitely.
769
+ **Root Causes & Solutions:**
588
770
 
589
- **Solutions**:
771
+ | Issue | Diagnostic | Solution |
772
+ | --------------------------- | ------------------------------------ | --------------------------------------------------------- |
773
+ | Invalid configurator ID | Browser console shows 404 errors | Verify modular configurator ID in Metabox admin |
774
+ | Container not found | `Error: Container element not found` | Ensure element exists before calling `integrateMetabox()` |
775
+ | HTTP instead of HTTPS | Mixed content warnings | Use HTTPS or test on localhost |
776
+ | Container has no dimensions | Invisible iframe (0x0) | Set explicit width/height on container element |
777
+ | CORS/iframe blocking | X-Frame-Options errors | Check domain allowlist in Metabox settings |
590
778
 
591
- 1. Verify the configurator ID is correct and accessible
592
- 2. Check that the container element exists in the DOM
593
- 3. Ensure the container has proper dimensions (width/height)
594
- 4. Check the browser console for CORS or network errors
779
+ **Diagnostic Code:**
595
780
 
596
781
  ```typescript
597
- // Ensure the element exists and ID is correct before calling
598
- integrateMetabox(configuratorId, 'embed3DSource', (api) => {
599
- console.log('API ready!');
782
+ const containerId = 'embed3DSource';
783
+ const container = document.getElementById(containerId);
784
+
785
+ if (!container) {
786
+ throw new Error(`Container #${containerId} not found`);
787
+ }
788
+
789
+ // Verify container has dimensions
790
+ const rect = container.getBoundingClientRect();
791
+ if (rect.width === 0 || rect.height === 0) {
792
+ console.warn('⚠️ Container has no dimensions');
793
+ }
794
+
795
+ if (location.protocol !== 'https:' && location.hostname !== 'localhost') {
796
+ console.warn('⚠️ HTTPS required for Unreal Engine streaming');
797
+ }
798
+
799
+ integrateMetabox('config-id', containerId, (api) => {
800
+ console.log('✅ Modular configurator loaded');
600
801
  });
601
802
  ```
602
803
 
603
- #### Commands Not Working
804
+ #### 2. Commands Not Working
805
+
806
+ **Symptoms:** Commands sent but no visual changes in configurator
604
807
 
605
- **Problem**: API commands are sent but don't affect the configurator.
808
+ **Common Mistakes:**
606
809
 
607
- **Solutions**:
810
+ | Mistake | Problem | Solution |
811
+ | ------------------------ | ------------------- | ----------------------------------------------- |
812
+ | Sending before API ready | Commands ignored | Only send in `apiReadyCallback` |
813
+ | Wrong component IDs | Component not found | Verify IDs from `configuratorDataUpdated` event |
814
+ | Root component not set | Blank configuration | Set root component first with `isRoot: true` |
815
+ | Type mismatch | Component rejected | Ensure `typeId` matches available types |
608
816
 
609
- 1. Ensure the API is ready before sending commands
610
- 2. Verify component/environment IDs are correct
611
- 3. Check that the configurator supports the specific command
817
+ **Correct Pattern:**
612
818
 
613
819
  ```typescript
614
- // Wait for API to be ready
615
- integrateMetabox(configuratorId, containerId, (api) => {
616
- // Only send commands after this callback
617
- api.sendCommandToMetabox(new SetEnvironment('env-001'));
820
+ integrateMetabox('config-id', 'container', (api) => {
821
+ // ✅ Correct: Commands sent after API ready
822
+
823
+ // First: Set root component
824
+ api.sendCommandToMetabox(new SetComponent('comp-1', 'chassis', true));
825
+
826
+ // Then: Add child components
827
+ api.sendCommandToMetabox(new SetComponent('comp-2', 'wheel', false));
828
+
829
+ // Finally: Apply materials
830
+ api.sendCommandToMetabox(new SetComponentMaterial('comp-1', 'body', 'blue'));
618
831
  });
832
+
833
+ // ❌ Wrong: Command sent too early
834
+ api.sendCommandToMetabox(new SetComponent('comp-1', 'chassis', true));
619
835
  ```
620
836
 
621
- #### TypeScript Errors
837
+ #### 3. TypeScript Errors
622
838
 
623
- **Problem**: TypeScript compilation errors with API types.
839
+ **Problem:** Compilation errors with API types
624
840
 
625
- **Solutions**:
841
+ **Solutions:**
626
842
 
627
- 1. Ensure you're importing types correctly:
843
+ **Import types correctly:**
628
844
 
629
845
  ```typescript
630
- import type { Communicator, ModularConfiguratorEnvelope } from '@3dsource/metabox-modular-configurator-api';
846
+ // ✅ Correct
847
+ import type { Communicator, ModularConfiguratorEnvelope, ModularConfiguratorComponent } from '@3dsource/metabox-modular-configurator-api';
848
+
849
+ // ❌ Wrong
850
+ import { Communicator } from '@3dsource/metabox-modular-configurator-api/types';
631
851
  ```
632
852
 
633
- 2. Update your `tsconfig.json` to include proper module resolution:
853
+ **Update `tsconfig.json`:**
634
854
 
635
855
  ```json
636
856
  {
637
857
  "compilerOptions": {
638
858
  "moduleResolution": "node",
639
- "esModuleInterop": true
859
+ "esModuleInterop": true,
860
+ "skipLibCheck": true,
861
+ "strict": true
640
862
  }
641
863
  }
642
864
  ```
643
865
 
866
+ #### 4. Component Tree Issues
867
+
868
+ **Problem:** Components not appearing in correct hierarchy
869
+
870
+ **Solution:** Understand component relationships
871
+
872
+ ```typescript
873
+ // Component tree structure:
874
+ // Root (chassis)
875
+ // ├── Child (wheel-front-left)
876
+ // ├── Child (wheel-front-right)
877
+ // └── Child (engine)
878
+
879
+ // Correct order:
880
+ api.sendCommandToMetabox(new SetComponent('chassis', 'base', true)); // Root first
881
+ api.sendCommandToMetabox(new SetComponent('wh-fl', 'wheel', false)); // Children after
882
+ api.sendCommandToMetabox(new SetComponent('wh-fr', 'wheel', false));
883
+ api.sendCommandToMetabox(new SetComponent('engine', 'engine', false));
884
+ ```
885
+
644
886
  ---
645
887
 
646
888
  For more examples and advanced usage, visit
@@ -648,57 +890,130 @@ our [documentation site](https://preview.3dsource.com/front-libraries/master/mod
648
890
 
649
891
  ## Standalone Mode
650
892
 
651
- Standalone mode lets you embed the Metabox renderer without the built‑in Metabox UI and template logic. This is ideal when you want to build a fully custom UI (menus, buttons, flows) and drive the configurator entirely through this API.
893
+ Headless rendering mode for custom UI implementations. Disables all built-in Metabox UI elements.
894
+
895
+ ### When to Use Standalone Mode
896
+
897
+ ✅ **Use When:**
652
898
 
653
- When standalone is enabled, the embedded page does not render Metabox’s internal menus, overlays, or template logic. You are responsible for sending commands (e.g., setComponent, setEnvironment, setComponentMaterialById) and listening to events to keep your UI in sync.
899
+ - Building fully custom modular configurator interface
900
+ - Implementing brand-specific component selection UX
901
+ - Integrating into existing design systems
902
+ - Requiring complete control over component assembly flow
654
903
 
655
- Key points:
904
+ ❌ **Don't Use When:**
656
905
 
657
- - Purpose: use when you need a 100% custom interface and logic on the host page.
658
- - Behavior: Metabox default UI, embedded menu and template logic are disabled on the iframe side.
659
- - Control: you drive everything with API commands and events.
906
+ - Quick prototyping with default UI is sufficient
907
+ - Minimal customization needed
908
+ - Limited development resources
660
909
 
661
- How to enable
910
+ ### Behavior Changes
662
911
 
663
- Pass as param to config with a standalone set to true when calling integrateMetabox.
912
+ | Feature | Default Mode | Standalone Mode |
913
+ | ------------------------- | ------------ | --------------- |
914
+ | Right sidebar menu | ✅ Visible | ❌ Hidden |
915
+ | Viewport overlays | ✅ Visible | ❌ Hidden |
916
+ | Template logic | ✅ Active | ❌ Disabled |
917
+ | API control | ⚠️ Partial | ✅ Full |
918
+ | Event system | ✅ Available | ✅ Available |
919
+ | Component tree management | ⚠️ Shared | ✅ Full control |
664
920
 
665
- TypeScript example:
921
+ ### Implementation
922
+
923
+ **TypeScript:**
666
924
 
667
925
  ```typescript
668
- import { integrateMetabox, Communicator, SetComponent, SetEnvironment } from '@3dsource/metabox-modular-configurator-api';
926
+ import { integrateMetabox, SetComponent, SetEnvironment, SetComponentMaterial } from '@3dsource/metabox-modular-configurator-api';
669
927
 
670
928
  integrateMetabox(
671
- 'configurator-id',
929
+ 'modular-config-id',
672
930
  'embed3DSource',
673
- (api: Communicator) => {
674
- // Send your initial commands to establish state
675
- api.sendCommandToMetabox(new SetComponent('your-component-id', 'your-type-id', true));
676
- api.sendCommandToMetabox(new SetEnvironment('your-environment-id'));
931
+ (api) => {
932
+ // REQUIRED: Set root component first
933
+ api.sendCommandToMetabox(new SetComponent('chassis-001', 'base', true));
934
+
935
+ // Optional: Add child components
936
+ api.sendCommandToMetabox(new SetComponent('wheel-fl', 'wheel', false));
937
+ api.sendCommandToMetabox(new SetComponent('wheel-fr', 'wheel', false));
938
+
939
+ // Optional: Set environment
940
+ api.sendCommandToMetabox(new SetEnvironment('studio-white'));
941
+
942
+ // Optional: Apply initial materials
943
+ api.sendCommandToMetabox(new SetComponentMaterial('chassis-001', 'body', 'metallic-blue'));
677
944
  },
678
945
  { standalone: true },
679
946
  );
680
947
  ```
681
948
 
682
- JavaScript (CDN) example:
949
+ **JavaScript (CDN):**
683
950
 
684
951
  ```html
685
952
  <script type="module">
686
953
  import { integrateMetabox, SetComponent, SetEnvironment } from 'https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api@latest/+esm';
687
954
 
688
955
  integrateMetabox(
689
- 'configurator-id',
690
- 'embed3DSource',
956
+ 'config-id',
957
+ 'container-id',
691
958
  (api) => {
692
- api.sendCommandToMetabox(new SetComponent('your-component-id', 'your-type-id', true));
693
- api.sendCommandToMetabox(new SetEnvironment('your-environment-id'));
959
+ // Must set a root component
960
+ api.sendCommandToMetabox(new SetComponent('comp-1', 'chassis', true));
961
+ api.sendCommandToMetabox(new SetEnvironment('env-1'));
694
962
  },
695
963
  { standalone: true },
696
964
  );
697
965
  </script>
698
966
  ```
699
967
 
700
- Notes and tips
968
+ ### Important Notes
969
+
970
+ ⚠️ **Critical:** Standalone mode starts with blank viewport. You **must** send `SetComponent` (with `isRoot: true`) and `SetEnvironment` commands to initialize.
971
+
972
+ ✅ **Working:**
973
+
974
+ - All events (`configuratorDataUpdated`, `screenshotReady`, etc.)
975
+ - All commands (component assembly, materials, environment)
976
+ - Screenshot and PDF export
977
+ - Validation (HTTPS enforcement, required parameters)
978
+
979
+ 🎯 **Best Practice:**
701
980
 
702
- - In standalone mode, nothing will change until you send initial commands (e.g., set component/environment). If you see a blank/default view, ensure you dispatch the necessary SetComponent/SetEnvironment commands once api is ready.
703
- - All events (like configuratorDataUpdated, screenshotReady) still work; use them to keep your UI synchronized.
704
- - The library sets the config.hostUrl and config.apiVersion automatically; you typically don’t need to pass them.
981
+ ```typescript
982
+ integrateMetabox(
983
+ 'id',
984
+ 'container',
985
+ (api) => {
986
+ // 1. Listen for state changes first
987
+ api.addEventListener('configuratorDataUpdated', (data) => {
988
+ updateCustomComponentTree(data.configurationTree);
989
+ updateMaterialSelectors(data.componentMaterialsIds);
990
+ });
991
+
992
+ // 2. Set root component (mandatory)
993
+ api.sendCommandToMetabox(new SetComponent('root-1', 'base', true));
994
+
995
+ // 3. Set environment
996
+ api.sendCommandToMetabox(new SetEnvironment('studio-env'));
997
+
998
+ // 4. Build component tree
999
+ api.sendCommandToMetabox(new SetComponent('child-1', 'wheel', false));
1000
+ api.sendCommandToMetabox(new SetComponent('child-2', 'wheel', false));
1001
+ },
1002
+ { standalone: true },
1003
+ );
1004
+ ```
1005
+
1006
+ ### Component Assembly in Standalone Mode
1007
+
1008
+ **Key Requirement:** Always set a root component first:
1009
+
1010
+ ```typescript
1011
+ // ✅ Correct order
1012
+ api.sendCommandToMetabox(new SetComponent('base', 'chassis', true)); // Root
1013
+ api.sendCommandToMetabox(new SetComponent('wh1', 'wheel', false)); // Child 1
1014
+ api.sendCommandToMetabox(new SetComponent('wh2', 'wheel', false)); // Child 2
1015
+
1016
+ // ❌ Wrong: No root component
1017
+ api.sendCommandToMetabox(new SetComponent('wh1', 'wheel', false));
1018
+ // Result: Nothing will render
1019
+ ```