npm package: @spreeai/web-sdk
Description: The SpreeAI Web SDK is a JavaScript library that simplifies the integration of SpreeAI services into web applications. It provides tools to interact with SpreeAI APIs efficiently.
Latest version: 1.1.0

# SpreeAI Web SDK

The SpreeAI Web SDK is a JavaScript library that simplifies the integration of SpreeAI services into web applications. It provides tools to interact with SpreeAI APIs efficiently.

## Installation

Install the package using npm or yarn:

```bash
npm install @spreeai/web-sdk
# or
yarn add @spreeai/web-sdk
```

Include the package as a script:

```html
<script type="module" src="https://unpkg.com/@spreeai/web-sdk@1.0.0"></script>
<link
  rel="stylesheet"
  href="https://unpkg.com/@spreeai/web-sdk@1.0.0/dist/web-sdk.css"
/>
```

## Usage

### Add an element in the location you want to mount the button

Give the button an id as a way to identify it

```html
<div id="try-on-buttton"></div>
```

### Importing the SDK

```javascript
import { tryOnButton } from "spreeai-web-sdk";
```

### Initializing the SDK

```javascript
tryOnButton({
  clientId: "your-client-id",
  elementId: "try-on-button",
  garmentId: "garment-id",
  partnerId: "partner-id",
  enableAddToCart: true, // Optional: Enable add-to-cart functionality
  events: {
    onTryOnButtonClick: event => {
      console.log("Try-on button clicked", event);
    },
    onAddToCartClicked: ({ garment, setIsLoading, closePopUp, onError }) => {
      // Handle add to cart
      setIsLoading(true);

      addToCart(garment)
        .then(() => {
          setIsLoading(false);
          closePopUp();
        })
        .catch(error => {
          setIsLoading(false);
          onError(error.message);
        });
    },
  },
  features: {
    loadingScreen: {
      videoUrl: "https://example.com/loading-video.mp4",
      loadingText: [
        "Preparing your virtual fitting room...",
        "Loading 3D models...",
        "Almost ready to try on!",
      ],
    },
    tryOnButton: {
      text: "Virtual Try On",
      iconUrl: "https://example.com/icon.png",
      iconHeight: "20px",
      backgroundColor: "#4CAF50",
      textColor: "#FFFFFF",
      borderRadius: "8px",
      fontSize: "16px",
      fontWeight: "600",
      padding: "12px 24px",
      border: "none",
      boxShadow: "0 4px 6px rgba(0, 0, 0, 0.1)",
      width: "100%",
    },
  },
});
```

## Features

- **Virtual Try-On**: Seamlessly integrate virtual try-on experiences for garments.
- **Add-to-Cart Integration**: Optional add-to-cart functionality with callbacks.
- **Customizable UI**: Extensive styling options for the try-on button.
- **Loading Screen Customization**: Configure custom loading videos and text.
- **Event Callbacks**: Track user interactions with the try-on experience.
- **Robust Error Handling**: Built-in error handling for API requests and user actions.

## API Reference

### `tryOnButton(options)`

Creates and renders a virtual try-on button in your web application.

#### Required Parameters

- **`clientId`** (string): Your SpreeAI client ID for authentication.
- **`elementId`** (string): The ID of the HTML element where the button will be mounted.
- **`garmentId`** (string): The unique identifier of the garment to try on.
- **`partnerId`** (string): Your SpreeAI partner ID.

#### Optional Parameters

- **`baseURL`** (string): Base URL for the try-on application. Default: `"https://protea-bridge.spreeai.com"`.
- **`baseApiURL`** (string): Base URL for the SpreeAI API. Default: `"https://api.spreeai.com"`.
- **`className`** (string): Additional CSS class name to apply to the button element.
- **`enableAddToCart`** (boolean): Enable add-to-cart functionality in the try-on experience. Default: `false`.

#### Button Configuration (Deprecated)

- **`button`** (object): Legacy button configuration object.
  - `button.text` (string): Button text. _Prefer using `features.tryOnButton.text` instead._

#### Features Configuration

##### `features.loadingScreen`

Configure the loading screen displayed while the try-on experience initializes.

- **`videoUrl`** (string): URL of a video to display during loading.
- **`loadingText`** (string[]): Array of 2-5 loading messages (max 42 characters each) to display sequentially.

##### `features.tryOnButton`

Customize the appearance and behavior of the try-on button.

**Text and Icon:**

- **`text`** (string): Button text. Default: `"Try It On"`.
- **`iconUrl`** (string): URL of an icon to display before the text.
- **`iconHeight`** (string): Height of the icon. Default: `"auto"`.

**Styling:**

- **`backgroundColor`** (string): Button background color (CSS color value).
- **`textColor`** (string): Button text color (CSS color value).
- **`width`** (string): Button width (CSS dimension).
- **`height`** (string): Button height (CSS dimension).
- **`fontSize`** (string): Font size (CSS dimension).
- **`fontWeight`** (string): Font weight (CSS font-weight value).
- **`padding`** (string): Button padding (CSS padding value).
- **`border`** (string): Border style (CSS border value).
- **`borderRadius`** (string): Border radius (CSS dimension).
- **`boxShadow`** (string): Box shadow (CSS box-shadow value).

#### Events

##### `events.onTryOnButtonClick`

Callback fired when the try-on button is clicked, before the dialog opens.

**Event Object:**

```typescript
{
  name: "spreeai-try-on-button-clicked";
}
```

**Example:**

```javascript
onTryOnButtonClick: event => {
  console.log("Try-on initiated", event.name);
  // Track analytics, etc.
};
```

##### `events.onAddToCartClicked`

Callback fired when the user clicks the add-to-cart button in the try-on experience (requires `enableAddToCart: true`).

**Event Object:**

```typescript
{
  name: "spreeai-add-to-cart-clicked",
  garment: {
    id: string,
    partner_id: string,
    available: boolean,
    name: string,
    description?: string,
    // ... additional garment properties
  },
  setIsLoading: (loading: boolean) => void,
  closePopUp: () => void,
  onError: (message: string) => void
}
```

**Parameters:**

- **`garment`**: The garment object containing all garment details.
- **`setIsLoading(loading)`**: Function to control the loading state of the add-to-cart button in the iframe.
  - `loading` (boolean): `true` to show loading, `false` to hide.
- **`closePopUp()`**: Function to close the try-on dialog.
- **`onError(message)`**: Function to send an error message to the iframe for display.
  - `message` (string): The error message to display.

**Example:**

```javascript
onAddToCartClicked: async ({ garment, setIsLoading, closePopUp, onError }) => {
  setIsLoading(true);

  try {
    await fetch("/api/cart", {
      method: "POST",
      body: JSON.stringify({ garmentId: garment.id }),
    });

    setIsLoading(false);
    closePopUp();
    alert("Added to cart!");
  } catch (error) {
    setIsLoading(false);
    onError("Failed to add item to cart. Please try again.");
  }
};
```

## Complete Example

```javascript
import { tryOnButton } from "@spreeai/web-sdk";

tryOnButton({
  // Required
  clientId: "f3267114-9b01-0000-0100-b23099d74e92",
  elementId: "try-on-button",
  garmentId: "garment-12345",
  partnerId: "my-brand",

  // Optional
  baseApiURL: "https://api.spreeai.com",
  baseURL: "https://protea-bridge.spreeai.com",
  className: "custom-try-on-btn",
  enableAddToCart: true,

  // Events
  events: {
    onTryOnButtonClick: event => {
      console.log("Button clicked:", event.name);
      // Track in analytics
      analytics.track("try_on_started");
    },

    onAddToCartClicked: async ({
      garment,
      setIsLoading,
      closePopUp,
      onError,
    }) => {
      console.log("Adding to cart:", garment.name);
      setIsLoading(true);

      try {
        const response = await fetch("/api/cart/add", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            garmentId: garment.id,
            name: garment.name,
          }),
        });

        if (!response.ok) throw new Error("Failed to add to cart");

        setIsLoading(false);
        closePopUp();

        // Show success message
        showNotification("Item added to cart!");
      } catch (error) {
        setIsLoading(false);
        onError(error.message || "Something went wrong");
      }
    },
  },

  // Features
  features: {
    loadingScreen: {
      videoUrl: "https://cdn.example.com/loading-animation.mp4",
      loadingText: [
        "Preparing your virtual fitting room...",
        "Loading 3D models...",
        "Analyzing garment details...",
        "Almost ready!",
      ],
    },
    tryOnButton: {
      text: "Try It On",
      iconUrl: "https://cdn.example.com/try-on-icon.svg",
      iconHeight: "20px",
      backgroundColor: "#000000",
      textColor: "#FFFFFF",
      borderRadius: "4px",
      fontSize: "14px",
      fontWeight: "500",
      padding: "10px 20px",
      width: "100%",
      boxShadow: "0 2px 4px rgba(0,0,0,0.1)",
    },
  },
});
```

## TypeScript Support

The SDK is written in TypeScript and provides full type definitions. Import types as needed:

```typescript
import {
  tryOnButton,
  TryOnButtonOptions,
  TryOnButtonEvents,
  AddToCartClickedEvent,
  Garment,
} from "@spreeai/web-sdk";

const options: TryOnButtonOptions = {
  clientId: "your-client-id",
  elementId: "try-on-button",
  garmentId: "garment-123",
  partnerId: "partner-id",
  enableAddToCart: true,
  events: {
    onAddToCartClicked: (event: AddToCartClickedEvent) => {
      // Fully typed event object
      const garment: Garment = event.garment;
      event.setIsLoading(true);
    },
  },
};

tryOnButton(options);
```

## License

This project is licensed under the MIT License. See the [LICENSE](./LICENSE) file for details.

## Support

For questions or support, contact [support@spreeai.com](mailto:support@spreeai.com).