1.1.30 • Published 8 months ago

@fluid-commerce/widgets v1.1.30

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

FairShare Widget SDK

A powerful JavaScript SDK for seamlessly integrating FairShare e-commerce features into your website. This package has @fluid-commerce/fairshare as its dependency and should not be needed to be loaded separately.

Table of Contents

Installation

npm install @fluid-commerce/widgets 
// This should automatically install @fluid-commerce/fairshare as dependency

Quick Start

import FluidSDK from '@fluid-commerce/fairshare';
import { Widgets } from '@fluid-commerce/widgets';

// Initialize the SDK
FluidSDK.initialize({
  apiUrlHost: "https://api.yourcompany.com", // Your API endpoint URL
  fluid_shop: "yourcompany.fluid.app"        // Your shop identifier
});

// Access SDK features
const cart = FluidSDK.cart();
const chat = FluidSDK.chat();


// render Widgets in react 
<Widgets />

Core Concepts

The FairShare SDK provides four main components to enhance your e-commerce site:

  1. Cart - Shopping cart functionality with multiple display options
  2. Chat - Customer support chat integration
  3. Banner - Promotional banners and notifications
  4. Globals - Cross-cutting configurations like language, country, and affiliate tracking

Configuration

The SDK requires two key parameters:

  1. fluid_shop - Your Fluid shop identifier (always your Fluid subdomain, e.g., yourcompany.fluid.app)
  2. apiUrlHost - Your API endpoint URL (can be your Fluid subdomain URL or a custom domain)

Example: A shop might have fluid_shop of danphe.fluid.app but use either https://danphe.fluid.app or https://danphe.net (custom domain) as the apiUrlHost.

Configuration Options in Detail

You can customize the SDK behavior by providing a configuration object during initialization. Here's what each option controls:

FluidSDK.initialize({
  // Required parameters
  apiUrlHost: "https://api.yourcompany.com", // API endpoint URL (can be custom domain)
  fluid_shop: "yourcompany.fluid.app",       // Shop identifier (always your Fluid subdomain)
  
  // Optional parameters
  debug: false,  // When true, logs detailed SDK operations to console for troubleshooting
  
  featureConfig: {
    // Cart configuration
    cart: {
      show: true,               // Controls whether cart functionality is enabled at all
      flavor: 'drawer',         // How the cart appears:
                                //   'drawer' - Slides in from side of screen
                                //   'icon' - Shows as an icon with count
                                //   'none' - No visual cart but API still available
      selector: '#cart-count'   // CSS selector for DOM element to update with cart count
    },
    
    // Customer support chat configuration
    chat: {
      show: true,               // Controls whether chat widget is enabled
      name: 'Support',          // Display name for the support agent in chat
      preview: 'Need help?',    // Text that appears in the collapsed chat bubble
      color: '#4A90E2'          // Primary color for chat interface (buttons, headers)
    },
    
    // Promotional banner configuration
    banner: {
      show: true,               // Controls whether banners can be displayed
      text: 'Special Offer!',   // Default banner text
      buttonText: 'Shop Now',   // Default call-to-action button text
      backgroundColor: '#ff0000' // Background color of the banner
                                // Banner can be updated later via banner.update()
    },
  },
  // Affiliate tracking configuration
  affiliate: {
    autodetect: 'bestmatch',  // How to detect affiliate referrals:
                              //   'subdomain' - Look for affiliate in subdomain (affiliate.yourshop.com)
                              //   'path' - Look in URL path (/affiliate/username)
                              //   'bestmatch' - Try subdomain first, then path
                              //   'none' - Disable automatic detection

    // Manual affiliate configuration (optional, overrides autodetect):
    // username: 'john.doe',  // Affiliate's username
    // id: '123'              // Affiliate's unique ID
    // share_guid: 'abc'      // Affiliate's shareable guid
  }
});

Note: If you're migrating from an older version, FluidSDK.getInstance().initialize() is still supported for backward compatibility.

Features

Globals

The globals module provides access to company-wide settings and user context.

const globals = FluidSDK.global();

// Available Properties
console.log(globals.company);      // Company information including name, logo URL, support contact
console.log(globals.country);      // Current country code (e.g., 'US') - affects shipping, pricing, taxes
console.log(globals.language);     // Current language code (e.g., 'en') - affects text localization
console.log(globals.affiliate);    // Current affiliate information if any affiliate is being tracked

// Update methods
globals.changeCountry('CA');       // Switch to Canadian storefront (affects pricing, shipping options, taxes)
globals.changeLanguage('fr');      // Switch to French language (changes UI text if translations available)

Cart

The cart module handles shopping cart functionality.

const cart = FluidSDK.cart();

// Check cart state
console.log(cart.config);          // Cart configuration object (same as passed during initialization)
console.log(cart.state);           // Current cart state - can be:
                                   //   'loading' - Cart is in process of updating
                                   //   'ready' - Cart is ready to use
                                   //   'error' - Cart encountered an error (check console for details)
console.log(cart.data);            // Complete cart data including:
                                   //   items - Array of items in cart
                                   //   totals - Price breakdowns (subtotal, tax, shipping, etc.)
                                   //   shipping - Selected shipping method
                                   //   discounts - Applied discount codes

// Create a new cart
await cart.new({
  items: [
    { variant_id: 123, quantity: 2 }
  ]
});

// Add items to cart
await cart.add([
  { variant_id: 456, quantity: 1 }
]);

// Update item quantity
await cart.updateQuantity({
  variant_id: 123,
  quantity: 3
});

// Subscription Management
await cart.enableSubscription(123);     // Enable subscription for product
await cart.disableSubscription(123);    // Disable subscription for product

// Apply discount code
await cart.addDiscount('SUMMER20');  // Returns error if code is invalid or expired

// Update shipping address
await cart.updateAddress({
  name: 'Jane Smith',
  address1: '123 Main St',
  city: 'Boston',
  state: 'MA',
  postal_code: '02108',
  country_code: 'US'
});

// Update language/country
await cart.updateLanguage('es');
await cart.updateCountry('US');

// Update payment method
await cart.updatePaymentMethod({
  token: 'payment_token',
  last_four: '1111',
  card_type: 'visa',
  exp_month: '12',
  exp_year: '27'
});

// Update shipping method
await cart.updateShippingMethod({ id: 'shipping_method_id' });

// Display cart count in DOM element
cart.renderCount('#cart-count');

// Enrollment in special programs
await cart.enrollment(123);  // Pass enrollment_pack_id - used for special offers, 
                             // memberships, bundles, or subscription packages

Chat

The chat module provides customer support functionality.

const chat = FluidSDK.chat();

// Check chat configuration
console.log(chat.config);        // Chat configuration object (same as passed during initialization)
console.log(chat.state);         // Current chat state - can be:
                                 //   'hidden' - Chat widget is not visible
                                 //   'visible' - Chat widget is visible/expanded
                                 //   'minimized' - Chat is shown but minimized
                                 //   'connecting' - Chat is establishing connection
                                 //   'connected' - Chat connection established

// Control visibility
chat.show();                     // Show chat widget
chat.hide();                     // Hide chat widget

// Send a message
chat.sendMessage({
  text: 'Hello, I need help with my order.',  // Message content
  sender: 'user',                             // Who sent the message ('user' or 'system')
  name: 'John Doe',                           // Optional: User's name (for first message)
  phone: '9812345678',                        // Optional: User's phone (for first message)
  email: 'johndoe@gmail.com'                  // Optional: User's email (for first message)
});  
// Note: name, phone, and email are typically only needed for the first message
// to establish the customer's identity

Banner

The banner module handles promotional banners.

const banner = FluidSDK.banner();

// Check banner configuration
console.log(banner.config);      // Banner configuration object (same as passed during initialization)
                                 // Includes text, buttonText, backgroundColor, etc.

// Control visibility
banner.show();                   // Show banner
banner.hide();                   // Hide banner

// Update banner content
banner.update({
  text: 'Limited Time Offer!',        // Main banner message text
  buttonText: 'Claim Now',            // Text for the call-to-action button
  backgroundColor: '#00796b',         // Background color (hex, rgb, or color name)
  // Additional optional parameters:
  // buttonLink: '/offers/spring',    // Where the CTA button should link
  // dismissible: true,               // Whether users can dismiss the banner
  // expiresAt: '2023-06-30'          // Date when banner should stop showing
});

TypeScript Support

The SDK includes TypeScript definitions for improved development experience:

import FluidSDK from '@fluid-commerce/widgets';
import type { FluidConfig, CartItem } from '@fluid-commerce/fairshare';

// Type-safe configuration
const config: FluidConfig = {
  apiUrlHost: 'https://api.yourcompany.com',
  fluid_shop: 'yourcompany.fluid.app',
  debug: true,
  config: {
    cart: {
      show: true,
      flavor: 'drawer'
    }
  }
};

FluidSDK.initialize(config);

// Type-safe cart operations
const items: CartItem[] = [
  { variant_id: 123, quantity: 1 }
];

const cart = FluidSDK.cart();
await cart.add(items);

Framework Integrations

Next.js Integration

To use Fluid Fair Share SDK with Next.js, you'll need to handle the client-side initialization properly. Here's a recommended approach: Creating a Fairshare Initializer Component Create a client component to initialize the SDK:

// components/FairshareInitializer.tsx
"use client";
import { useEffect, useState } from "react";
import FluidSDK from "@fluid-commerce/fairshare";
import {Widgets} from "@fluid-commerce/widgets";


export default function FairshareInitializer() {
  const [isInitialized, setIsInitialized] = useState(false);
  useEffect(() => {
    // Skip if already initialized
    if (isInitialized || typeof window === 'undefined') return;
    const initializeFairshare = async () => {
      try { 
        await FluidSDK.initialize({
          fluid_shop: yourapp.fluid.app,
          apiUrlHost: http://yourapp.fluid.app,
          country: "us",
        });
        
        console.log("Fairshare initialized successfully");
        setIsInitialized(true);
      } catch (err) {
        console.error('Error initializing FluidSDK:', err);
      }
    };
  }, [isInitialized]);
  return (<Widgets />);
}

Add to Your Layout

Include the initializer component in your app layout:

// app/layout.tsx
import FairshareInitializer from '@/components/FairshareInitializer';
export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {/* Initialize Fairshare SDK */}
        <FairshareInitializer />
        {children}
      </body>
    </html>
  );
}

Troubleshooting

Common issues and solutions:

  1. Initialization Errors
  • Ensure your apiUrlHost and fluid_shop are correctly configured
  • The fluid_shop must be your Fluid subdomain (e.g., yourcompany.fluid.app)
  • The apiUrlHost can be either your Fluid URL or a custom domain that points to your shop
  • Check browser console for detailed error messages when debug: true
  • Initialization must occur before any feature methods are called
  1. Cart Not Showing
  • Verify that cart.config.show is set to true
  • Confirm your CSS selector in cart.config.selector exists in the DOM
  • Try a different flavor setting if the current one isn't working
  • Check if any CSS on your site might be hiding the cart elements
  1. API Connection Issues
  • Check your network tab for failed requests and error codes
  • Ensure CORS is properly configured on your API server
  • Verify your site is using HTTPS if your API requires secure connections
  • Check if there are any network firewalls blocking API calls
  1. Chat Problems
  • If chat appears but doesn't connect, check your network tab for failed WebSocket connections
  • If chat agents don't receive messages, verify your chat configuration in the Fluid admin panel
  • For customer identification issues, ensure you're passing name/email with the first message
  1. Banner Issues
  • If banners don't appear, check if banner.config.show is true
  • If banners appear but look incorrect, check for CSS conflicts with your site
  • For banners that should be temporary, verify you've set the correct expiresAt date

For additional help, contact our support team at support@fluid-commerce.com

1.1.30

8 months ago

1.1.29

8 months ago

1.1.28

8 months ago

1.1.27

8 months ago

1.1.26

9 months ago

1.1.25

9 months ago

1.1.24

9 months ago

1.1.23

9 months ago

1.1.22

9 months ago

1.1.21

9 months ago

1.1.20

9 months ago

1.1.19

9 months ago

1.1.18

9 months ago

1.1.17

9 months ago

1.1.16

9 months ago

1.1.15

9 months ago

1.1.14

9 months ago

1.1.13

9 months ago

1.1.12

9 months ago

1.1.11

9 months ago

1.1.10

9 months ago

1.1.9

9 months ago

1.1.9-beta.1

9 months ago

1.1.8

9 months ago

1.1.7

9 months ago

1.1.6

9 months ago

1.1.5

9 months ago

1.1.4

9 months ago

1.1.3

9 months ago

1.1.2

9 months ago

1.1.1

9 months ago

1.0.19

9 months ago

1.0.18

10 months ago

1.0.17

10 months ago

1.0.16

10 months ago

1.0.15

10 months ago

1.0.14

10 months ago

1.0.13

10 months ago

1.0.12

10 months ago

1.0.11

10 months ago

1.0.10

10 months ago

1.0.9

10 months ago

1.0.8

11 months ago

1.0.7

11 months ago

1.0.6

11 months ago

1.0.5

11 months ago

1.0.4

11 months ago

1.0.3

11 months ago

1.0.2

11 months ago

1.0.1

11 months ago

1.0.0

11 months ago