# @fast-simon/storefront-kit

`@fast-simon/storefront-kit` is a versatile library for e-commerce platforms, providing easy integration of Fast Simon features like Visual Similarity and other complex functionalities into your online stores. Written in TSX, it offers a suite of fetcher functions for pulling data from Fast Simon servers and components for rendering, streamlining the integration process.

## Features

- **Visual similarity**: Enhance product discovery by showing visually similar products.
- **Customizable components**: Tailored to fit the design and functionality of your store.
- **Flexible fetcher functions**: Retrieve data effectively with minimal setup.
- **Easy integration with Shopify**, especially designed for use with Shopify Hydrogen.

## Installation

First, authenticate with Fast Simon private NPM packages:

```bash
npm config set "//registry.npmjs.org/:_authToken" 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
```

Then, install the package in your project:

```bash
npm install @fast-simon/storefront-kit
```

## Usage
### Adding Fast Simon fetcher function to the root loader
- import `getVisualSimilarityProducts` from `@fast-simon/storefront-kit` into the product page root file
- Invoke `getVisualSimilarityProducts` in your root loader function, passing the product id as a prop
- Pass down the result to the product page component, you can either await to the promise to resolved (which could have a negative performance impact) or just pass the promise down as a stream.

```js
import {getVisualSimilarityProducts} from '@fast-simon/storefront-kit';

export async function loader({params, request, context}: LoaderFunctionArgs) {
  // ... other code
  const visualSimilarityProducts = getVisualSimilarityProducts({
    UUID: 'Your store UUID here, you can find it in the Fast Simon dashboard',
    productId: product.id,
    storeId: 'Your store ID here, you can find it in the Fast Simon dashboard',
  });
  return defer({otherparam, visualSimilarityProducts});

```

### Using Fast Simon components

After fetching data using the getVisualSimilarityProducts function, you can display the results using components from the @fast-simon/storefront-kit. Here's an example of how to use the FastSimonWidget component along with retrieving the data using the useLoaderData:

```js
import { FastSimonWidget } from '@fast-simon/storefront-kit';

function ProductPage() {

  const {product, visualSimilarityProducts} = useLoaderData<typeof loader>();

  // ... other component logic

  return (
          <div>

            {/* ... other parts of your product page */}

            <FastSimonWidget title={'Similar Products'}
                             products={visualSimilarityProducts}/>

          </div>
  );
}
```

This component will render the visual similarity results in a visually appealing and interactive format.

## Shopify Markets Support

If your store uses [Shopify Markets](https://shopify.dev/docs/apps/markets) to sell in multiple countries, you can pass the `marketContext` option when creating the Fast Simon client. This ensures all API responses (search, collections, autocomplete, recommendations) are filtered to products available in the specified market.

### Setup in `server.ts`

Pass the customer's country code (from Hydrogen's locale detection) as `marketContext`:

```js
import { createFastSimonClient, FastSimonSession } from '@fast-simon/storefront-kit';

// In your fetch handler:
const locale = getLocaleFromRequest(request); // { country: 'CA', language: 'EN', ... }

const fastSimon = createFastSimonClient({
  cache,
  waitUntil,
  request,
  uuid: 'your-uuid',
  storeID: 'your-store-id',
  fastSimonSession,
  marketContext: locale.country, // e.g. "US", "CA", "GB"
});
```

When `marketContext` is provided, a `market_context` query parameter is appended to every API request. When omitted (default), no market filtering is applied and the behavior is unchanged.

## Configuration
### `getVisualSimilarityProducts` function
To customize the behavior of the getVisualSimilarityProducts function, you can pass the specs parameter to control aspects like:

- `maxSuggestions` - Max number of similar products to fetch
- `sources` - sources of the results, for example:
  - `similar_products` - products sharing category, tags or keyword similarity with the viewed product
  - `similar_products_by_attributes` - products sharing categories and chosen attributes (requires choosing relevant attributes in Fast Simon dashboard)
  - `similar_products_lookalike` - visually similar products (requires enabling Look-a-like Visually Similar Recommendations in Fast Simon dashboard)
  - `related_top_products` - popular products in the store

Refer to the API documentation for a full list of configurable parameters.
https://docs.fastsimon.com/api#operation/productRecommendations

### `FastSimonWidget` component
You can customize the FastSimonWidget component with various props to match your store's design and layout requirements.

`renderProduct` - a function that receives a product object and returns a React element. This allows you to customize the product card that is rendered for each product in the widget. For example:
```js
  <FastSimonWidget title={'Similar Products'}
                   products={visualSimilarityProducts}
                   renderProduct={(product, pos) => <MyProductCard key={product.id} product={product} />}/>
```


`title` - The title of the widget, for example `Similar Products` or `You may also like`
`breakpoints` - An object of breakpoints to control the number of products displayed in each device. For example:
```js
  <FastSimonWidget title={'Similar Products'}
                   products={visualSimilarityProducts}
                   breakpoints={{
                     mobile: 2,
                     tablet: 3,
                     desktop: 4,
                   }}/>
```

`carouselGap` - The gap between products in the carousel in pixel, default value is 16. For example:
```js
  <FastSimonWidget title={'Similar Products'}
                   products={visualSimilarityProducts}
                   carouselGap={16}/>
```

`RightArrowIcon` - A JSX element to use as the right arrow icon in the carousel. For example:
```js
  <FastSimonWidget title={'Similar Products'}
                   products={visualSimilarityProducts}
                   RightArrowIcon={<MyRightArrowIcon/>}/>
```
Don't worry about the left icon, we are rotating the icon automatically.

`imageAspectRatio` - The aspect ratio of the product image, default value is "2/3". For example:
```js
  <FastSimonWidget title={'Similar Products'}
                   products={visualSimilarityProducts}
                   imageAspectRatio={"2/3"}/>
```

Consult the component documentation for more details on customization options.

For any issues, questions, or suggestions, please refer to the GitHub repository of @fast-simon/storefront-kit or contact our support team.
