@3dsource/metabox-modular-configurator-api 0.0.2 → 0.0.4-dev.0

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,8 @@
1
1
  # Metabox Modular Configurator API
2
2
 
3
- A powerful JavaScript/TypeScript API for integrating and controlling the Metabox Modular Configurator in web
3
+ A powerful TypeScript API for integrating and controlling the Metabox Modular Configurator in web
4
4
  applications. This package provides seamless communication with 3D configurators, allowing you to control environments,
5
- components, materials, and capture screenshots or PDFs.
5
+ components, component types, materials, and capture screenshots or PDFs.
6
6
 
7
7
  ## Table of Contents
8
8
 
@@ -11,8 +11,13 @@ components, materials, and capture screenshots or PDFs.
11
11
  - [Installation](#installation)
12
12
  - [Quick Start](#quick-start)
13
13
  - [API Reference](#api-reference)
14
+ - [System Terminology](#system-terminology)
15
+ - [Core Integration](#core-integration)
16
+ - [Type Definitions](#type-definitions)
17
+ - [Command Classes](#command-classes)
14
18
  - [Examples](#examples)
15
19
  - [Event Handling](#event-handling)
20
+ - [Troubleshooting](#troubleshooting)
16
21
  - [Contributing](#contributing)
17
22
 
18
23
  ## Features
@@ -51,7 +56,7 @@ import { integrateMetabox, Communicator, SetEnvironment, SetComponent } from 'ht
51
56
 
52
57
  Alternative CDN options:
53
58
 
54
- - **jsDelivr**: `https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api@0.0.1/+esm`
59
+ - **jsDelivr**: `https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api@0.0.3/+esm`
55
60
 
56
61
  ## Quick Start
57
62
 
@@ -92,7 +97,7 @@ Create a container element where the configurator will be embedded:
92
97
 
93
98
  ```html
94
99
  <script type="module">
95
- import { integrateMetabox, SetEnvironment, ShowOverlayInterface, SetEnvironmentMaterial, SetComponent, SetComponentMaterial, ShowEmbeddedMenu, GetScreenshot, GetPdf, saveImage, Communicator, FromMetaboxApiAction } from 'https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api';
100
+ import { GetPdf, GetScreenshot, integrateMetabox, saveImage, SetComponent, SetComponentMaterial, SetEnvironment, SetEnvironmentMaterial, ShowEmbeddedMenu, ShowOverlayInterface } from 'https://cdn.jsdelivr.net/npm/@3dsource/metabox-modular-configurator-api';
96
101
 
97
102
  // Replace it with your actual configurator URL
98
103
  const configuratorUrl = 'https://metabox.3dsource.com/metabox-configurator/modular/your-configurator-id';
@@ -101,12 +106,12 @@ Create a container element where the configurator will be embedded:
101
106
  console.log('Configurator API ready!');
102
107
 
103
108
  // Listen for configurator data updates
104
- api.addEventListener('configuratorData', (data) => {
109
+ api.addEventListener('configuratorDataUpdated', (data) => {
105
110
  console.log('Configurator data:', data);
106
111
  });
107
112
 
108
113
  // Listen for screenshot events
109
- api.addEventListener('screenshot', (data) => {
114
+ api.addEventListener('screenshotReady', (data) => {
110
115
  saveImage(data, 'configurator-screenshot.png');
111
116
  });
112
117
 
@@ -126,19 +131,19 @@ Create a container element where the configurator will be embedded:
126
131
  #### TypeScript/Angular/React
127
132
 
128
133
  ```typescript
129
- import { integrateMetabox, Communicator, ModularConfiguratorEnvelope, SetEnvironment, ShowOverlayInterface, GetScreenshot, saveImage } from '@3dsource/metabox-modular-configurator-api';
134
+ import { integrateMetabox, Communicator, ModularConfiguratorEnvelope, SetEnvironment, ShowOverlayInterface, GetScreenshot, saveImage, SetComponent, SetComponentMaterial, type MimeType, ShowEmbeddedMenu } from '@3dsource/metabox-modular-configurator-api';
130
135
 
131
136
  class ConfiguratorIntegration {
132
137
  private api: Communicator | null = null;
138
+ private readonly configuratorUrl: string;
133
139
 
134
- constructor() {
140
+ constructor(configuratorUrl: string) {
141
+ this.configuratorUrl = configuratorUrl;
135
142
  this.initialize();
136
143
  }
137
144
 
138
145
  private initialize(): void {
139
- const configuratorUrl = 'https://metabox.3dsource.com/metabox-configurator/modular/your-configurator-id';
140
-
141
- integrateMetabox(configuratorUrl, 'embed3DSource', (api) => {
146
+ integrateMetabox(this.configuratorUrl, 'embed3DSource', (api: Communicator) => {
142
147
  this.api = api;
143
148
  this.setupEventListeners();
144
149
  this.setupInitialState();
@@ -148,41 +153,105 @@ class ConfiguratorIntegration {
148
153
  private setupEventListeners(): void {
149
154
  if (!this.api) return;
150
155
 
151
- this.api.addEventListener('configuratorData', (data: ModularConfiguratorEnvelope) => {
156
+ // Listen for configuration data changes
157
+ this.api.addEventListener('configuratorDataUpdated', (data: ModularConfiguratorEnvelope) => {
152
158
  console.log('Configurator data updated:', data);
153
159
  this.handleConfiguratorData(data);
154
160
  });
155
161
 
156
- this.api.addEventListener('screenshot', (data: string) => {
157
- saveImage(data, 'configurator-render.png');
162
+ // Handle screenshot events
163
+ this.api.addEventListener('screenshotReady', (imageData: string | null) => {
164
+ saveImage(imageData ?? '', 'configurator-render.png');
165
+ });
166
+
167
+ // Handle viewport ready events
168
+ this.api.addEventListener('viewportReady', (isReady: boolean) => {
169
+ console.log('Viewport ready:', isReady);
170
+ });
171
+
172
+ // Handle status messages
173
+ this.api.addEventListener('statusMessageChanged', (message: string | null) => {
174
+ console.log('Status message:', message);
158
175
  });
159
176
  }
160
177
 
161
178
  private setupInitialState(): void {
162
179
  if (!this.api) return;
163
180
 
181
+ // Configure initial environment and components
182
+ this.api.sendCommandToMetaBox(new SetEnvironment('default-environment'));
183
+ this.api.sendCommandToMetaBox(new SetComponent('main-product', 'chair', true));
164
184
  this.api.sendCommandToMetaBox(new ShowOverlayInterface(true));
165
- this.api.sendCommandToMetaBox(new GetScreenshot('image/png', { x: 1024, y: 1024 }));
185
+ this.api.sendCommandToMetaBox(new ShowEmbeddedMenu(true));
166
186
  }
167
187
 
168
188
  private handleConfiguratorData(data: ModularConfiguratorEnvelope): void {
189
+ // Access typed data properties according to actual interface
190
+ console.log('Configurator:', data.configurator);
191
+ console.log('Configuration tree:', data.configurationTree);
192
+ console.log('Components by type:', data.componentsByComponentType);
193
+ console.log('Component materials:', data.componentMaterialsIds);
194
+ console.log('Environment ID:', data.environmentId);
195
+ console.log('Environment materials:', data.environmentMaterialsIds);
196
+
169
197
  // Process configurator data according to your needs
170
- // This data contains information about current configuration state
198
+ this.updateUI(data);
171
199
  }
172
200
 
173
- public takeScreenshot(): void {
201
+ private updateUI(data: ModularConfiguratorEnvelope): void {
202
+ // Update your application UI based on configurator state
203
+ // This method would contain your specific UI update logic
204
+ }
205
+
206
+ // Public API methods
207
+ public takeScreenshot(format: MimeType = 'image/png', size?: { x: number; y: number }): void {
174
208
  if (this.api) {
175
- this.api.sendCommandToMetaBox(new GetScreenshot('image/png', { x: 1920, y: 1080 }));
209
+ this.api.sendCommandToMetaBox(new GetScreenshot(format, size));
210
+ }
211
+ }
212
+
213
+ public changeMaterial(slotId: string, materialId: string): void {
214
+ if (this.api) {
215
+ this.api.sendCommandToMetaBox(new SetComponentMaterialById(slotId, materialId));
216
+ }
217
+ }
218
+
219
+ public changeEnvironment(environmentId: string): void {
220
+ if (this.api) {
221
+ this.api.sendCommandToMetaBox(new SetEnvironment(environmentId));
176
222
  }
177
223
  }
224
+
225
+ public destroy(): void {
226
+ // Clean up resources when component is destroyed
227
+ this.api = null;
228
+ }
178
229
  }
179
230
 
180
- // Initialize the configurator
181
- new ConfiguratorIntegration();
231
+ // Usage example
232
+ const configurator = new ConfiguratorIntegration('https://metabox.3dsource.com/metabox-configurator/modular/your-configurator-id');
233
+
234
+ // Take a high-resolution screenshot
235
+ configurator.takeScreenshot('image/png', { x: 1920, y: 1080 });
236
+
237
+ // Change material
238
+ configurator.changeMaterial('seat-fabric', 'leather-brown');
182
239
  ```
183
240
 
184
241
  ## API Reference
185
242
 
243
+ ### System Terminology
244
+
245
+ - **product** - 3D digital twin of the actual physical product within a Metabox system; concept is used in Basic configurator.
246
+ - **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.
247
+ - **environment** - 3D digital twin of the actual environment (room scene or other) within a Metabox system.
248
+ - **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.
249
+ - **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.
250
+ - **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.
251
+ - **component** - Product in the Modular configurator context.
252
+ - **componentId** - Unique Component ID within the Metabox system; mandatory. Assigned by the Metabox system automatically after the Modular configurator is created in Metabox.
253
+ - **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.
254
+
186
255
  ### Core Integration
187
256
 
188
257
  #### `integrateMetabox(configuratorUrl, containerId, apiReadyCallback)`
@@ -191,9 +260,15 @@ Integrates the Metabox modular configurator into the specified container.
191
260
 
192
261
  **Parameters:**
193
262
 
194
- - `configuratorUrl` (string): The URL of your Metabox configurator
195
- - `containerId` (string): The ID of the HTML element where the configurator will be embedded
196
- - `apiReadyCallback` (function): Callback function that receives the API communicator instance
263
+ - `configuratorUrl` (`string`): The URL of your Metabox configurator
264
+ - `containerId` (`string`): The ID of the HTML element where the configurator will be embedded
265
+ - `apiReadyCallback` (`(api: Communicator) => void`): Callback function that receives the API communicator instance
266
+
267
+ **TypeScript Signature:**
268
+
269
+ ```typescript
270
+ declare function integrateMetabox(configuratorUrl: string, containerId: string, apiReadyCallback: (api: Communicator) => void): void;
271
+ ```
197
272
 
198
273
  **Example:**
199
274
 
@@ -203,6 +278,178 @@ integrateMetabox('https://metabox.3dsource.com/metabox-configurator/modular/your
203
278
  });
204
279
  ```
205
280
 
281
+ ### Type Definitions
282
+
283
+ The API provides comprehensive TypeScript support with the following key interfaces and types:
284
+
285
+ #### Core Types
286
+
287
+ ##### `Communicator`
288
+
289
+ The main API interface for sending commands and listening to events.
290
+
291
+ ```typescript
292
+ interface Communicator {
293
+ sendCommandToMetaBox<T extends keyof ToMetaboxMessagePayloads>(command: CommandBase<T>): void;
294
+
295
+ addEventListener<K extends keyof FromMetaboxMessagePayloads>(eventType: K, listener: (data: FromMetaboxMessagePayloads[K]) => void): void;
296
+
297
+ removeEventListener<K extends keyof FromMetaboxMessagePayloads>(eventType: K, listener: (data: FromMetaboxMessagePayloads[K]) => void): void;
298
+ }
299
+ ```
300
+
301
+ ##### `ModularConfiguratorEnvelope`
302
+
303
+ The main data structure contains the complete configurator state.
304
+
305
+ ```typescript
306
+ interface ModularConfiguratorEnvelope {
307
+ /** Represents the modular configurator api with its components, component types, and environments */
308
+ configurator: InitialModularConfigurator;
309
+ /** The unique tree of components and parent and component type id */
310
+ configurationTree: ComponentWithParent[];
311
+ /** A record mapping all components by current component type */
312
+ componentsByComponentType: Record<string, string>;
313
+ /** A record mapping component material selection */
314
+ componentMaterialsIds: SelectedIds;
315
+ /** The unique environment identifier */
316
+ environmentId: string;
317
+ /** A record mapping environment material selections */
318
+ environmentMaterialsIds: SelectedIds;
319
+ }
320
+ ```
321
+
322
+ ##### `ModularConfiguratorComponent`
323
+
324
+ Represents a component in the configurator.
325
+
326
+ ```typescript
327
+ interface ModularConfiguratorComponent {
328
+ /** The id unique identifier. */
329
+ id: string;
330
+ /** The modular configurator component type identifier. */
331
+ componentType: ModularConfiguratorComponentType;
332
+ /** Display the name for the product. */
333
+ name: string;
334
+ /** Position index of the product. */
335
+ position: number;
336
+ /** The detailed product information. */
337
+ product: Product;
338
+ /** Connectors between connectors and virtual sockets. */
339
+ virtualSocketToConnectorsMap?: ModularConfiguratorVirtualSocketToConnector[];
340
+ /** GraphQL typename for the component. */
341
+ __typename: 'ModularConfiguratorComponent';
342
+ }
343
+ ```
344
+
345
+ ##### `Material`
346
+
347
+ Represents a material that can be applied to components or environments.
348
+
349
+ ```typescript
350
+ interface Material {
351
+ /** Unique identifier for the material. */
352
+ id: string;
353
+ /** Title or name of the material. */
354
+ title: string;
355
+ /** Unique external id for the material. */
356
+ externalId: string;
357
+ /** List of thumbnails for the material. */
358
+ thumbnailList: Thumbnail[];
359
+ /** GraphQL typename for the material. */
360
+ __typename: 'Material';
361
+ }
362
+ ```
363
+
364
+ ##### `Environment`
365
+
366
+ Represents an environment/scene configuration.
367
+
368
+ ```typescript
369
+ interface Environment {
370
+ /** Unique identifier for the environment. */
371
+ id: string;
372
+ /** Title or name of the environment. */
373
+ title: string;
374
+ /** Flag indicating if UDS is enabled. */
375
+ udsEnabled: boolean;
376
+ /** The north yaw of the sun in the environment. */
377
+ sunNorthYaw: number;
378
+ /** The UDS hour setting for the environment. */
379
+ udsHour: number;
380
+ /** List of thumbnails for the environment (optional). */
381
+ thumbnailList: Thumbnail[];
382
+ /** List of slots for the environment (optional). */
383
+ slots: Slot[];
384
+ /** GraphQL typename for the environment. */
385
+ __typename: 'Environment';
386
+ }
387
+ ```
388
+
389
+ #### Command Payload Types
390
+
391
+ All commands use strongly typed payloads defined in `ToMetaboxMessagePayloads`:
392
+
393
+ ```typescript
394
+ interface ToMetaboxMessagePayloads {
395
+ setEnvironment: { id: string };
396
+ setEnvironmentMaterialById: { slotId: string; materialId: string };
397
+ setComponent: { id: string; typeId: string; isRoot: boolean };
398
+ setComponentType: { typeId: string };
399
+ setComponentMaterialById: { slotId: string; materialId: string };
400
+ getScreenshot: { format: MimeType; size?: { x: number; y: number } };
401
+ getPdf: void;
402
+ showEmbeddedMenu: { visible: boolean };
403
+ showOverlayInterface: { visible: boolean };
404
+ forceSetDeviceType: { deviceType: ApplicationDeviceTypes };
405
+ resetCamera: void;
406
+ applyZoom: { zoom: number };
407
+ initShowcase: { productId: string };
408
+ playShowcase: void;
409
+ pauseShowcase: void;
410
+ stopShowcase: void;
411
+ sendCommandToUnreal: object;
412
+ }
413
+ ```
414
+
415
+ #### Utility Types
416
+
417
+ ##### `MimeType`
418
+
419
+ Supported image formats for screenshots.
420
+
421
+ ```typescript
422
+ type MimeType = 'image/png' | 'image/jpeg' | 'image/webp';
423
+ ```
424
+
425
+ ##### `ApplicationDeviceTypes`
426
+
427
+ Device type options for responsive behavior.
428
+
429
+ ```typescript
430
+ type ApplicationDeviceTypes = 'desktop' | 'tablet' | 'mobile';
431
+ ```
432
+
433
+ ##### `Position` and `Rotation`
434
+
435
+ 3D coordinate and rotation structures.
436
+
437
+ ```typescript
438
+ interface Position {
439
+ x: number;
440
+ y: number;
441
+ z: number;
442
+ }
443
+
444
+ interface Rotation {
445
+ x: number;
446
+ y: number;
447
+ z: number;
448
+ }
449
+ ```
450
+
451
+ ### Command Classes
452
+
206
453
  ### Environment & Scene Control
207
454
 
208
455
  #### `SetEnvironment(environmentId)`
@@ -346,8 +593,17 @@ Captures a screenshot of the current configurator view.
346
593
 
347
594
  **Parameters:**
348
595
 
349
- - `mimeType` (string): Image format ('image/png', 'image/jpeg')
350
- - `size` (object, optional): Dimensions `{ x: number, y: number }`
596
+ - `mimeType` (`string`): Image format ('image/png', 'image/jpeg')
597
+ - `size` (`{ x: number; y: number }`, optional): Screenshot dimensions in pixels
598
+
599
+ **TypeScript Interface:**
600
+
601
+ ```typescript
602
+ interface ScreenshotSize {
603
+ x: number; // Width in pixels
604
+ y: number; // Height in pixels
605
+ }
606
+ ```
351
607
 
352
608
  **Example:**
353
609
 
@@ -377,9 +633,7 @@ Utility function to save image data to a file.
377
633
  **Example:**
378
634
 
379
635
  ```typescript
380
- api.addEventListener('screenshot', (data) => {
381
- saveImage(data, 'my-configuration.png');
382
- });
636
+ saveImage(data, 'my-configuration.png');
383
637
  ```
384
638
 
385
639
  ### Showcase Control
@@ -426,16 +680,6 @@ Sends custom commands directly to the Unreal Engine.
426
680
  api.sendCommandToMetaBox(new UnrealCommand('SetLightIntensity 2.5'));
427
681
  ```
428
682
 
429
- #### `WatchCallbacks()`
430
-
431
- Enables watching for callbacks from the Unreal Engine.
432
-
433
- **Example:**
434
-
435
- ```typescript
436
- api.sendCommandToMetaBox(new WatchCallbacks());
437
- ```
438
-
439
683
  ## Examples
440
684
 
441
685
  ### Complete Product Configurator
@@ -445,7 +689,7 @@ import { integrateMetabox, Communicator, ModularConfiguratorEnvelope, SetEnviron
445
689
 
446
690
  class ProductConfigurator {
447
691
  private api: Communicator | null = null;
448
- private currentConfig: any = {};
692
+ private currentConfig: ModularConfiguratorEnvelope | null = null;
449
693
 
450
694
  constructor(configuratorUrl: string) {
451
695
  integrateMetabox(configuratorUrl, 'embed3DSource', (api) => {
@@ -509,66 +753,206 @@ class ProductConfigurator {
509
753
  link.click();
510
754
  }
511
755
  }
512
-
513
- // Usage
514
- const configurator = new ProductConfigurator('https://metabox.3dsource.com/metabox-configurator/modular/your-product-id');
515
756
  ```
516
757
 
517
758
  ### React Hook Example
518
759
 
519
760
  ```typescript
520
- import { useEffect, useRef, useState } from 'react';
521
- import { integrateMetabox, Communicator, SetEnvironment, GetScreenshot } from '@3dsource/metabox-modular-configurator-api';
761
+ import { useCallback, useEffect, useRef, useState } from 'react';
762
+ import {
763
+ Communicator,
764
+ GetScreenshot,
765
+ integrateMetabox,
766
+ ModularConfiguratorEnvelope,
767
+ SetComponent,
768
+ SetComponentMaterial,
769
+ SetEnvironment,
770
+ } from '@3dsource/metabox-modular-configurator-api';
771
+
772
+ interface UseMetaboxConfiguratorOptions {
773
+ configuratorUrl: string;
774
+ autoInitialize?: boolean;
775
+ }
522
776
 
523
- export const useMetaboxConfigurator = (configuratorUrl: string) => {
777
+ interface UseMetaboxConfiguratorReturn {
778
+ containerRef: React.RefObject<HTMLDivElement>;
779
+ api: Communicator | null;
780
+ isReady: boolean;
781
+ configData: ModularConfiguratorEnvelope | null;
782
+ isLoading: boolean;
783
+ error: string | null;
784
+ // Actions
785
+ changeEnvironment: (environmentId: string) => void;
786
+ takeScreenshot: (format?: MimeType, size?: { x: number; y: number }) => void;
787
+ changeMaterial: (slotId: string, materialId: string) => void;
788
+ addComponent: (id: string, typeId: string, isRoot?: boolean) => void;
789
+ initialize: () => void;
790
+ destroy: () => void;
791
+ }
792
+
793
+ export const useMetaboxConfigurator = ({
794
+ configuratorUrl,
795
+ autoInitialize = true,
796
+ }: UseMetaboxConfiguratorOptions): UseMetaboxConfiguratorReturn => {
524
797
  const [api, setApi] = useState<Communicator | null>(null);
525
- const [isReady, setIsReady] = useState(false);
526
- const [configData, setConfigData] = useState(null);
798
+ const [isReady, setIsReady] = useState<boolean>(false);
799
+ const [isLoading, setIsLoading] = useState<boolean>(false);
800
+ const [error, setError] = useState<string | null>(null);
801
+ const [configData, setConfigData] = useState<ModularConfiguratorEnvelope | null>(null);
527
802
  const containerRef = useRef<HTMLDivElement>(null);
528
803
 
529
- useEffect(() => {
530
- if (!containerRef.current || !configuratorUrl) return;
804
+ const initialize = useCallback(() => {
805
+ if (!containerRef.current || !configuratorUrl || isLoading) return;
806
+
807
+ setIsLoading(true);
808
+ setError(null);
809
+
810
+ try {
811
+ const containerId = 'metabox-container-' + Date.now();
812
+ containerRef.current.id = containerId;
531
813
 
532
- const containerId = 'metabox-container-' + Date.now();
533
- containerRef.current.id = containerId;
814
+ integrateMetabox(configuratorUrl, containerId, (apiInstance: Communicator) => {
815
+ setApi(apiInstance);
816
+ setIsReady(true);
817
+ setIsLoading(false);
534
818
 
535
- integrateMetabox(configuratorUrl, containerId, (apiInstance) => {
536
- setApi(apiInstance);
537
- setIsReady(true);
819
+ // Set up event listeners
820
+ apiInstance.addEventListener('configuratorData', (data: ModularConfiguratorEnvelope) => {
821
+ setConfigData(data);
822
+ });
538
823
 
539
- apiInstance.addEventListener('configuratorData', (data) => {
540
- setConfigData(data);
824
+ apiInstance.addEventListener('screenshot', (imageData: string) => {
825
+ // Handle screenshot data - could emit custom event or callback
826
+ console.log('Screenshot ready:', imageData);
827
+ });
828
+
829
+ apiInstance.addEventListener('pdf', (pdfData: string) => {
830
+ // Handle PDF data
831
+ console.log('PDF ready:', pdfData);
832
+ });
541
833
  });
542
- });
834
+ } catch (err) {
835
+ setError(err instanceof Error ? err.message : 'Failed to initialize configurator');
836
+ setIsLoading(false);
837
+ }
838
+ }, [configuratorUrl, isLoading]);
839
+
840
+ const destroy = useCallback(() => {
841
+ setApi(null);
842
+ setIsReady(false);
843
+ setIsLoading(false);
844
+ setConfigData(null);
845
+ setError(null);
846
+ }, []);
543
847
 
544
- return () => {
545
- setApi(null);
546
- setIsReady(false);
547
- setConfigData(null);
548
- };
549
- }, [configuratorUrl]);
848
+ useEffect(() => {
849
+ if (autoInitialize) {
850
+ initialize();
851
+ }
852
+
853
+ return destroy;
854
+ }, [initialize, destroy, autoInitialize]);
550
855
 
551
- const changeEnvironment = (environmentId: string) => {
552
- if (api) {
856
+ // Action methods
857
+ const changeEnvironment = useCallback((environmentId: string) => {
858
+ if (api && isReady) {
553
859
  api.sendCommandToMetaBox(new SetEnvironment(environmentId));
554
860
  }
555
- };
861
+ }, [api, isReady]);
862
+
863
+ const takeScreenshot = useCallback((
864
+ format: MimeType = 'image/png',
865
+ size?: { x: number; y: number },
866
+ ) => {
867
+ if (api && isReady) {
868
+ api.sendCommandToMetaBox(new GetScreenshot(format, size));
869
+ }
870
+ }, [api, isReady]);
556
871
 
557
- const takeScreenshot = () => {
558
- if (api) {
559
- api.sendCommandToMetaBox(new GetScreenshot('image/png'));
872
+ const changeMaterial = useCallback((slotId: string, materialId: string) => {
873
+ if (api && isReady) {
874
+ api.sendCommandToMetaBox(new SetComponentMaterial(slotId, materialId));
560
875
  }
561
- };
876
+ }, [api, isReady]);
877
+
878
+ const addComponent = useCallback((id: string, typeId: string, isRoot: boolean = false) => {
879
+ if (api && isReady) {
880
+ api.sendCommandToMetaBox(new SetComponent(id, typeId, isRoot));
881
+ }
882
+ }, [api, isReady]);
562
883
 
563
884
  return {
564
885
  containerRef,
565
886
  api,
566
887
  isReady,
567
888
  configData,
889
+ isLoading,
890
+ error,
568
891
  changeEnvironment,
569
892
  takeScreenshot,
893
+ changeMaterial,
894
+ addComponent,
895
+ initialize,
896
+ destroy,
570
897
  };
571
898
  };
899
+
900
+ // Usage example in a React component
901
+ const ConfiguratorComponent: React.FC = () => {
902
+ const {
903
+ containerRef,
904
+ isReady,
905
+ isLoading,
906
+ error,
907
+ configData,
908
+ changeEnvironment,
909
+ takeScreenshot,
910
+ changeMaterial,
911
+ } = useMetaboxConfigurator({
912
+ configuratorUrl: 'https://metabox.3dsource.com/metabox-configurator/modular/your-id',
913
+ });
914
+
915
+ const handleEnvironmentChange = (envId: string) => {
916
+ changeEnvironment(envId);
917
+ };
918
+
919
+ const handleTakeScreenshot = () => {
920
+ takeScreenshot('image/png', { x: 1920, y: 1080 });
921
+ };
922
+
923
+ if (error) {
924
+ return <div className="error">Error loading configurator: {error}</div>;
925
+ }
926
+
927
+ return (
928
+ <div className="configurator-wrapper">
929
+ {isLoading && <div className="loading">Loading configurator...</div>}
930
+
931
+ <div ref={containerRef} className="configurator-container" />
932
+
933
+ {isReady && (
934
+ <div className="controls">
935
+ <button onClick={() => handleEnvironmentChange('showroom-1')}>
936
+ Showroom Environment
937
+ </button>
938
+ <button onClick={() => changeMaterial('seat', 'leather-brown')}>
939
+ Brown Leather
940
+ </button>
941
+ <button onClick={handleTakeScreenshot}>
942
+ Take Screenshot
943
+ </button>
944
+ </div>
945
+ )}
946
+
947
+ {configData && (
948
+ <div className="config-info">
949
+ <p>Components: {configData.componentsByComponentType ? Object.keys(configData.componentsByComponentType).length : 0}</p>
950
+ <p>Environment: {configData.environmentId}</p>
951
+ </div>
952
+ )}
953
+ </div>
954
+ );
955
+ };
572
956
  ```
573
957
 
574
958
  ## Event Handling
@@ -577,28 +961,30 @@ The API provides several events that you can listen to for real-time updates:
577
961
 
578
962
  ### Available Events
579
963
 
580
- | Event Name | Description | Data Type |
581
- | ------------------ | ------------------------------------- | ----------------------------- |
582
- | `configuratorData` | Fired when configuration data changes | `ModularConfiguratorEnvelope` |
583
- | `screenshot` | Fired when a screenshot is ready | `string` (base64 image data) |
584
- | `showcaseStatus` | Fired when showcase status changes | `object` |
585
- | `pdf` | Fired when PDF generation is complete | `string` (PDF data) |
964
+ | Event Name | Description | Data Type |
965
+ | ------------------------- | ------------------------------------- | ----------------------------- |
966
+ | `configuratorDataUpdated` | Fired when configuration data changes | `ModularConfiguratorEnvelope` |
967
+ | `screenshotReady` | Fired when a screenshot is ready | `string` (base64 image data) |
968
+ | `showcaseStatusChanged` | Fired when showcase status changes | `ShowCaseStatus` |
969
+ | `viewportReady` | Fired when viewport is ready | `boolean` |
970
+ | `statusMessageChanged` | Fired when status message changes | `string \| null` |
586
971
 
587
972
  ### Event Listener Examples
588
973
 
589
974
  ```typescript
590
975
  // Listen for configuration changes
591
- api.addEventListener('configuratorData', (data: ModularConfiguratorEnvelope) => {
976
+ api.addEventListener('configuratorDataUpdated', (data: ModularConfiguratorEnvelope) => {
592
977
  console.log('Configuration updated:', data);
593
978
 
594
979
  // Access specific data
595
- console.log('Components:', data.components);
596
- console.log('Environment:', data.environment);
597
- console.log('Materials:', data.materials);
980
+ console.log('Configurator:', data.configurator);
981
+ console.log('Configuration tree:', data.configurationTree);
982
+ console.log('Components by type:', data.componentsByComponentType);
983
+ console.log('Environment ID:', data.environmentId);
598
984
  });
599
985
 
600
986
  // Handle screenshot events
601
- api.addEventListener('screenshot', (imageData: string) => {
987
+ api.addEventListener('screenshotReady', (imageData: string) => {
602
988
  // imageData is a base64 encoded image
603
989
  const img = document.createElement('img');
604
990
  img.src = imageData;
@@ -606,18 +992,19 @@ api.addEventListener('screenshot', (imageData: string) => {
606
992
  });
607
993
 
608
994
  // Monitor showcase playback
609
- api.addEventListener('showcaseStatus', (status) => {
995
+ api.addEventListener('showcaseStatusChanged', (status: ShowCaseStatus) => {
610
996
  console.log('Showcase status:', status);
611
997
  // Handle play/pause/stop states
612
998
  });
613
999
 
614
- // Handle PDF generation
615
- api.addEventListener('pdf', (pdfData: string) => {
616
- // Create download link for PDF
617
- const link = document.createElement('a');
618
- link.href = pdfData;
619
- link.download = 'configuration.pdf';
620
- link.click();
1000
+ // Handle viewport ready events
1001
+ api.addEventListener('viewportReady', (isReady: boolean) => {
1002
+ console.log('Viewport ready:', isReady);
1003
+ });
1004
+
1005
+ // Handle status messages
1006
+ api.addEventListener('statusMessageChanged', (message: string | null) => {
1007
+ console.log('Status message:', message);
621
1008
  });
622
1009
  ```
623
1010