@3dsource/metabox-modular-configurator-api 3.0.10 → 3.0.12

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