> ## Documentation Index
> Fetch the complete documentation index at: https://www.algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# ais-compare-bar

> Shows selected products and sends the selected records to the chat widget for an agent to compare.

For more information, see [Agent Studio](https://www.algolia.com/doc/guides/algolia-ai/agent-studio).

```vue Signature theme={"system"}
<ais-compare-bar
  configuration-id="string"
  // Optional parameters
  :min-items="number"
  :max-items="number"
  :transform-items="function"
  :class-names="object"
  :translations="object"
/>
```

## Import

> [tab] Component
>
> To ensure optimal bundle sizes,
> see [Optimize build size](https://www.algolia.com/doc/guides/building-search-ui/going-further/improve-performance/vue.md#optimize-build-size).
>
> ```js Vue icon=code theme={"system"}
> import { AisCompareBar } from "vue-instantsearch";
> // Use "vue-instantsearch/vue3/es" for Vue 3
>
> export default {
>   components: {
>     AisCompareBar,
>   },
>   // ...
> };
> ```

> [tab] Plugin
>
> This imports all widgets, even the ones you don't use.
> For more information, see [Get started with Vue InstantSearch](https://www.algolia.com/doc/guides/building-search-ui/getting-started/vue.md).
>
> ```js JavaScript icon="code" theme={"system"} theme={"system"}
> import Vue from "vue";
> import InstantSearch from "vue-instantsearch";
> // Use "vue-instantsearch/vue3/es" for Vue 3
>
> Vue.use(InstantSearch);
> ```

## About this widget

Use the `ais-compare-bar` widget to let users compare products with an Agent Studio agent.
The widget renders a comparison bar with the products users selected for comparison and a **Compare** button.
When users select **Compare**,
the widget opens the [`ais-chat`](https://www.algolia.com/doc/api-reference/widgets/chat/vue) widget on the same index and sends a comparison request with the selected records attached.
The widget clears the selection after sending the request.
The chat displays the agent's comparison of the attached records without showing the request as a user message.

The widget doesn't include controls for selecting products.
Add a **Compare** checkbox to each product in your [`ais-hits`](https://www.algolia.com/doc/api-reference/widgets/hits/vue) widget with a custom widget that uses the `connectCompare` connector, as shown in the [example](#examples).
To build a custom comparison bar or **Compare** button, use the same connector.
All `ais-compare-bar` widgets and `connectCompare` widgets in the same `ais-instant-search` share the same selection,
so the toggles and comparison bar update together.

The comparison bar stays hidden while the selection is empty.
Because `ais-compare-bar` opens the `ais-chat` widget,
you don't need an [`ais-chat-trigger`](https://www.algolia.com/doc/api-reference/widgets/chat-trigger/vue) widget.

The widget requires a comparison configuration, which controls the comparison goal and instructions.
Create it in the Agent Studio dashboard and pass its ID as [`configuration-id`](#param-configuration-id).

See also: [Compare products in chat](https://www.algolia.com/doc/guides/algolia-ai/agent-studio/how-to/product-comparison.md)

## Examples

The `CompareToggle` component is a custom widget that renders a **Compare** checkbox for one hit.
It uses `connectCompare` with the same configuration and limits as the comparison bar.

```vue CompareToggle.vue icon=code expandable theme={"system"}
<template>
  <label v-if="state">
    <input
      type="checkbox"
      :checked="selected"
      :disabled="!selected && !state.canAddItems"
      @change="state.toggleItem(item)"
    />
    Compare
  </label>
</template>

<script>
  import { createWidgetMixin } from "vue-instantsearch";
  // Use "vue-instantsearch/vue3/es" for Vue 3
  import { connectCompare } from "instantsearch.js/es/connectors";

  export default {
    mixins: [createWidgetMixin({ connector: connectCompare })],
    props: {
      item: {
        type: Object,
        required: true,
      },
    },
    computed: {
      widgetParams() {
        return {
          configurationId: "CONFIGURATION_ID",
          minItems: 2,
          maxItems: 3,
        };
      },
      selected() {
        return this.state.isSelected(this.item.objectID);
      },
    },
  };
</script>
```

```vue App.vue icon=code expandable theme={"system"}
<template>
  <ais-instant-search index-name="instant_search" :search-client="searchClient">
    <ais-search-box />
    <ais-hits>
      <template v-slot:item="{ item }">
        <article>
          <h2>{{ item.name }}</h2>
          <compare-toggle :item="item" />
        </article>
      </template>
    </ais-hits>
    <ais-compare-bar
      configuration-id="CONFIGURATION_ID"
      :min-items="2"
      :max-items="3"
    />
    <ais-chat agent-id="AGENT_ID" />
  </ais-instant-search>
</template>

<script>
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import "instantsearch.css/components/chat.css";
  import CompareToggle from "./CompareToggle.vue";

  export default {
    components: { CompareToggle },
    data() {
      return {
        searchClient: algoliasearch("ALGOLIA_APPLICATION_ID", "ALGOLIA_SEARCH_API_KEY"),
      };
    },
  };
</script>
```

## Props

**configuration-id** `string` *required*

The ID of the comparison configuration that controls how the agent compares products.
Create comparison configurations in the **Components** section of your agent in the Agent Studio dashboard.
For more information, see [Compare products in chat](https://www.algolia.com/doc/guides/algolia-ai/agent-studio/how-to/product-comparison.md).

The widget sends `__ALGOLIA_COMPARISON_<configurationId>__` as the user message,
with `comparison_configuration_id` and `selected_products` as [per-turn context](https://www.algolia.com/doc/guides/algolia-ai/agent-studio/how-to/turn-context.md).
`selected_products` holds the selected records as a JSON string, with internal attributes such as `_highlightResult` removed.

Agent Studio replaces the placeholder with the configured agent instructions, and the chat doesn't show a user message for it.
If the configuration doesn't exist or you turned it off,
the placeholder reaches the agent unchanged, so only set the ID of an enabled configuration.

```vue Vue icon=code theme={"system"}
<ais-compare-bar configuration-id="CONFIGURATION_ID" />
```

**min-items** `number` (default: 2)

The number of products users must select before they can compare.
The **Compare** button is unavailable until users select this number of products.
The value must be at least `2`.

Set `min-items` to the lower product limit in your comparison configuration.

```vue Vue icon=code theme={"system"}
<ais-compare-bar configuration-id="CONFIGURATION_ID" :min-items="2" />
```

**max-items** `number` (default: 3)

The largest number of products users can select.
When the selection reaches this limit, the widget ignores attempts to add more products and shows a hint.
The value must be greater than or equal to [`min-items`](#param-min-items).

Set `max-items` to the upper product limit in your comparison configuration.

```vue Vue icon=code theme={"system"}
<ais-compare-bar configuration-id="CONFIGURATION_ID" :max-items="4" />
```

**transform-items** `(items: object[]) =\> object[]`

A function that receives the selected records and returns the records to display in the comparison bar.
The widget sends these transformed records to the agent when users select **Compare**.
Use this function to remove long attributes, such as product descriptions.

Return one record for each selected record and preserve its `objectID`.
The selection itself, including `isSelected` and the limits, uses the original records.

```vue Vue icon=code theme={"system"}
<template>
  <ais-compare-bar
    configuration-id="CONFIGURATION_ID"
    :transform-items="transformItems"
  />
</template>

<script>
  export default {
    methods: {
      transformItems(items) {
        return items.map(({ description, ...item }) => item);
      },
    },
  };
</script>
```

**class-names** `object` (default: \{})

The [CSS classes you can override](https://www.algolia.com/doc/guides/building-search-ui/widgets/customize-an-existing-widget/vue.md#style-your-widgets):

* `ais-CompareBar`. The root element of the widget.
* `ais-CompareBar-header`. The header element.
* `ais-CompareBar-title`. The title element.
* `ais-CompareBar-count`. The selection count element.
* `ais-CompareBar-list`. The list of selected items.
* `ais-CompareBar-item`. Each selected item.
* `ais-CompareBar-itemLabel`. The label of each selected item.
* `ais-CompareBar-itemRemove`. The button that removes an item from the selection.
* `ais-CompareBar-hint`. The hint shown when users select fewer than `min-items` or reach `max-items`.
* `ais-CompareBar-actions`. The container of the action buttons.
* `ais-CompareBar-clearButton`. The button that clears the selection.
* `ais-CompareBar-compareButton`. The button that starts the comparison.

```vue Vue icon=code theme={"system"}
<ais-compare-bar
  configuration-id="CONFIGURATION_ID"
  :class-names="{
    'ais-CompareBar': 'MyCustomCompareBar',
    'ais-CompareBar-compareButton': 'MyCustomCompareBarButton',
  }"
/>
```

**translations** `object`

A dictionary of translations to customize the UI text and support internationalization.

* `title` (`string`). The title of the comparison bar. The default is `Compare`.
* `countText` (`(count: number, maxItems: number) => string`). The selection count. The default is `${count} of ${maxItems}`.
* `compareButtonText` (`(count: number) => string`). The label of the **Compare** button. The default is `Compare ${count}`.
* `clearButtonText` (`string`). The label of the **Clear all** button.
* `removeItemLabel` (`(itemLabel: string) => string`). The accessible label of each remove button. The default is `Remove ${itemLabel} from comparison`.
* `minItemsHint` (`(minItems: number) => string`). The hint shown while the selection is below `min-items`. The default is `Select at least ${minItems} products to compare.`
* `limitReachedHint` (`string`). The hint shown when the selection reaches `max-items`. The default is `Compare limit reached — remove a product to add another.`.

```vue Vue icon=code theme={"system"}
<ais-compare-bar
  configuration-id="CONFIGURATION_ID"
  :translations="{
    title: 'Your comparison',
    compareButtonText: (count) => `Compare ${count} products`,
  }"
/>
```

## Customize the UI

**item**

The slot to replace the label of each selected item.

By default, the label is the record's `name` or `title`, falling back to its `objectID`.

**Scope**

* `item: object`. The selected record.

```vue Vue icon=code theme={"system"}
<ais-compare-bar configuration-id="CONFIGURATION_ID">
  <template v-slot:item="{ item }">
    <img :src="item.image" alt="" width="24" height="24" />
    <span>{{ item.name }}</span>
  </template>
</ais-compare-bar>
```

## HTML output

```html HTML icon=code-xml expandable theme={"system"}
<section class="ais-CompareBar" aria-label="Compare">
  <div class="ais-CompareBar-header">
    <h3 class="ais-CompareBar-title">Compare</h3>
    <span class="ais-CompareBar-count" aria-live="polite">2 of 3</span>
  </div>
  <ul class="ais-CompareBar-list">
    <li class="ais-CompareBar-item" data-object-id="1">
      <span class="ais-CompareBar-itemLabel">Trail Jacket</span>
      <button class="ais-CompareBar-itemRemove" aria-label="Remove Trail Jacket from comparison">
        ...
      </button>
    </li>
    <li class="ais-CompareBar-item" data-object-id="2">
      <span class="ais-CompareBar-itemLabel">Storm Shell</span>
      <button class="ais-CompareBar-itemRemove" aria-label="Remove Storm Shell from comparison">
        ...
      </button>
    </li>
  </ul>
  <div class="ais-CompareBar-actions">
    <button class="ais-Button ais-Button--outline ais-Button--sm ais-CompareBar-clearButton">
      Clear all
    </button>
    <button class="ais-Button ais-Button--primary ais-Button--sm ais-CompareBar-compareButton">
      Compare 2
    </button>
  </div>
</section>
```

The widget doesn't render anything if the selection is empty.
Below `min-items` or at `max-items`, it adds a `div.ais-CompareBar-hint` element before the actions.

The `instantsearch.css` chat theme anchors the bar to the bottom center of the viewport.
Import `instantsearch.css/components/chat.css` to style it.

## Connector render state

A custom widget that uses `connectCompare` receives the following properties in `state`:

* `items` (`object[]`).
  The selected records, in selection order, after `transformItems`.
  Each item has at least an `objectID`.
* `isSelected` (`(objectID: string) => boolean`).
  Whether the record with this `objectID` is in the selection.
* `addItem` (`(item: object) => void`).
  Adds a record to the selection.
  It doesn't add the record if it's already selected or the selection has reached `maxItems`.
  Each record must have an `objectID`.
* `removeItem` (`(objectID: string) => void`).
  Removes the record with this `objectID` from the selection.
* `toggleItem` (`(item: object) => void`).
  Adds the record to the selection when it isn't selected, and removes it otherwise.
* `clearItems` (`() => void`).
  Empties the selection.
* `canAddItems` (`boolean`).
  Whether the selection is below `maxItems`.
* `canCompare` (`boolean`).
  Whether the selection has reached `minItems`.
* `minItems` (`number`).
  The resolved `minItems` value.
* `maxItems` (`number`).
  The resolved `maxItems` value.
* `compare` (`() => boolean`).
  Opens the `ais-chat` widget on the same index, sends the compare request with the selected records attached, and clears the selection.
  Returns `true` when it submits the message and `false` when the selection is below `minItems`, the page doesn't have an `ais-chat` widget, or the chat is busy.

The connector accepts the same parameters as the widget, in camel case: `configurationId` (required), `minItems`, `maxItems`, and `transformItems`.
Pass the same `configurationId`, `minItems`, and `maxItems` to every `connectCompare` widget and `ais-compare-bar` so they use the same configuration and limits.
