# App Block Storefront Events

Retail Cloud Connect™ App Blocks emit browser events for storefront integrations that need to react to search, collection, Dynamic Autocomplete, or product-card activity.

Use these events for small client-side integrations such as analytics, theme UI updates, custom success messages, debugging, or coordinating another script with the rendered search grid. They are integration hooks; they should not replace Retail Cloud Connect cart or search logic.

<br/>

## Browser Events

| Event                                               | Target     | App Block                    | Fired when {.compact}                                                                                     |
| --------------------------------------------------- | ---------- | ---------------------------- | --------------------------------------------------------------------------------------------------------- |
| `retail-connect:products:load:start`                | `window`   | Search Results, Product Grid | A product search or collection request starts.                                                            |
| `retail-connect:products:load:success`              | `window`   | Search Results, Product Grid | Product results and result metadata have loaded successfully.                                             |
| `retail-connect:products:load:failure`              | `window`   | Search Results, Product Grid | Product results fail to load.                                                                             |
| `retail-connect:search-grid:ready`                  | `document` | Search Results, Product Grid | The product grid has rendered and reached the next animation frame.                                       |
| `retail-connect:dynamic-autocomplete:open`          | `window`   | Dynamic Autocomplete         | The autocomplete dialog or theme-input popup opens.                                                       |
| `retail-connect:dynamic-autocomplete:close`         | `window`   | Dynamic Autocomplete         | The autocomplete dialog or theme-input popup closes.                                                      |
| `retail-connect:dynamic-autocomplete:search:submit` | `window`   | Dynamic Autocomplete         | A search is submitted through autocomplete.                                                               |
| `retail-connect:add-to-cart:success`                | `window`   | Product cards                | Shopify accepts a product-card add-to-cart request.                                                       |
| `retail-connect:add-to-cart:failure`                | `window`   | Product cards                | Shopify rejects the add-to-cart request, the network request fails, or the cart mutation cannot complete. |

<br/>

## Search Result Events

`retail-connect:products:load:start`, `retail-connect:products:load:success`, and `retail-connect:products:load:failure` describe the Search Results and Product Grid result loading lifecycle.

The load-start event detail includes the request context:

| Field                  | Description {.compact}                                                   |
| ---------------------- | ------------------------------------------------------------------------ |
| `query`                | Search query. Empty on collection browsing unless a query is active.     |
| `currentPage`          | Requested page number.                                                   |
| `pageSize`             | Requested products for the current scheduled page (36, 36, then 48).     |
| `orderField`           | Active sort field.                                                       |
| `filters`              | Filters sent to the Retail Cloud Connect storefront API.                 |
| `appliedCustomFilters` | Active custom filters.                                                   |
| `customFields`         | Additional fields requested for custom-filter checks.                    |
| `searchFiltersEnabled` | Whether search filters are enabled for the current App Block.            |
| `collectionId`         | Shopify collection id on Product Grid collection pages.                  |
| `collectionTags`       | Collection tags passed to the request, when present.                     |
| `loadMore`             | Whether the App Block is rendering multiple loaded pages.                |
| `storeKey`             | Search store key for this App Block instance.                            |
| `conversationId`       | Retail Cloud Connect search conversation id, when present.               |
| `autocompleteToken`    | Autocomplete attribution token, when the request came from autocomplete. |
| `autocompletePosition` | Autocomplete result position, when available.                            |

The load-success event includes the same request context plus result metadata:

| Field                | Description {.compact}                                                  |
| -------------------- | ----------------------------------------------------------------------- |
| `pagination`         | Current page, total pages, and total result count.                      |
| `facets`             | Visible facet metadata after custom-field-only facets are filtered out. |
| `checkedFacets`      | Facet metadata returned by the API for current filter relevance checks. |
| `products`           | Products currently loaded into the App Block.                           |
| `firstVisiblePage`   | First visible page in load-more mode.                                   |
| `loadedResultsCount` | Number of product cards currently rendered.                             |

The load-failure event includes the request context plus `error`, normalized to an object with at least `message` when possible.

<br/>

## Search Grid Ready

`retail-connect:search-grid:ready` is the public hook for scripts that need to run after the search or collection product grid has rendered. Listen on `document`.

```liquid
{%- if request.page_type == 'search' or request.page_type == 'collection' -%}
  <script>
    document.addEventListener('retail-connect:search-grid:ready', (event) => {
      const { pageType, resultCount, totalResultCount, gridElement } = event.detail;

      console.log('Retail Cloud Connect grid ready', {
        pageType,
        resultCount,
        totalResultCount,
        gridElement,
      });
    });
  </script>
{%- endif -%}
```

The event detail includes:

| Field              | Description {.compact}                                                  |
| ------------------ | ----------------------------------------------------------------------- |
| `blockId`          | Shopify App Block id, when available.                                   |
| `pageType`         | `search` or `collection`.                                               |
| `resultsPerRow`    | App Block grid column setting.                                          |
| `pageSize`         | Products requested for the current scheduled page.                      |
| `resultCount`      | Number of products currently rendered.                                  |
| `totalResultCount` | Total products returned by the API for the current query or collection. |
| `loadMore`         | Whether the App Block is rendering multiple loaded pages.               |
| `rootElement`      | App Block root element, or `null`.                                      |
| `gridElement`      | Product grid element, or `null`.                                        |

Use this event instead of observing private product-grid selectors.

<br/>

## Dynamic Autocomplete Events

Listen on `window` for Dynamic Autocomplete tracking. Search-trigger clicks prevent the control's default action and stop propagation so the theme's search drawer does not open alongside autocomplete; the dedicated events provide tracking hooks for both pointer and keyboard use.

`retail-connect:dynamic-autocomplete:open` and `retail-connect:dynamic-autocomplete:close` fire once when the dialog or theme-input popup becomes visible or closes. Mounting autocomplete, editing the query, or activating a trigger while it is already open does not emit another visibility event. Opening after supplied default products finish loading emits the same open event. Removing the App Block or navigating away does not guarantee a close event; use the search-submit event to track submissions.

`retail-connect:dynamic-autocomplete:search:submit` fires before autocomplete navigates, submits a search form, or updates a Search Results App Block on the current page. It covers typed queries, selected query suggestions, and View all actions. Blank queries and submissions canceled by a later edit, close, or submission do not emit this event. It records search submission rather than the completion of a results request.

The event payload is available on `event.detail`:

| Field                  | Event         | Description {.compact}                                                                                                |
| ---------------------- | ------------- | --------------------------------------------------------------------------------------------------------------------- |
| `blockId`              | All           | Shopify App Block id, when available.                                                                                 |
| `inputId`              | All           | Unique identifier for the autocomplete input instance.                                                                |
| `query`                | All           | Normalized current query for open/close; normalized submitted query for search submission.                            |
| `openerElement`        | Open, close   | The source input or trigger element that opened this instance. This is a DOM element; do not forward it to analytics. |
| `sourceQuery`          | Search submit | Normalized query typed before the submission or suggestion selection.                                                 |
| `autocompletePosition` | Search submit | Selected suggestion's attribution position, when available.                                                           |
| `autocompleteToken`    | Search submit | Selected suggestion's attribution token, when available.                                                              |

Install listeners on every template that includes Dynamic Autocomplete. For example, a store can forward search submissions to its analytics data layer:

```liquid
<script>
  window.addEventListener('retail-connect:dynamic-autocomplete:search:submit', (event) => {
    const detail = event.detail;
    if (!detail?.query) return;

    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'retail_connect_autocomplete_search',
      search_term: detail.query,
      source_query: detail.sourceQuery,
      block_id: detail.blockId,
    });
  });
</script>
```

The listeners observe activity; they should not submit another search or open another drawer.

<br/>

## Product Card Add-to-Cart Events

`retail-connect:add-to-cart:success` and `retail-connect:add-to-cart:failure` fire when a product card includes an add-to-cart component, such as `ADD_TO_BASKET` or `ADD_TO_BASKET_MODAL`.

The event payload is available on `event.detail`:

| Field             | Event   | Description {.compact}                                                                   |
| ----------------- | ------- | ---------------------------------------------------------------------------------------- |
| `detail.response` | Success | Shopify Ajax cart response body returned by `cart/add.js`.                               |
| `detail.response` | Failure | Shopify Ajax error response body when Shopify returns one.                               |
| `detail.error`    | Failure | JavaScript error object when the request throws before a Shopify response can be parsed. |

When the success event fires, the App Block has already posted to Shopify's Ajax `cart/add.js` endpoint. Theme code should not add the item again.

Product cards can appear on several storefront templates, so install add-to-cart listeners globally unless the store deliberately limits them to known page types.

```liquid
<script>
  window.addEventListener('retail-connect:add-to-cart:success', (event) => {
    const response = event.detail?.response;
    const items = Array.isArray(response?.items)
      ? response.items
      : response
        ? [response]
        : [];

    window.dataLayer = window.dataLayer || [];
    window.dataLayer.push({
      event: 'retail_connect_add_to_cart',
      source: 'retail_connect_product_card',
      ecommerce: {
        items: items.map((item) => ({
          item_id: item.product_id,
          item_variant: item.variant_id || item.id,
          item_name: item.product_title || item.title,
          quantity: item.quantity || 1,
        })),
      },
    });
  });
</script>
```

Common uses include analytics, opening a theme cart drawer, updating a mini-cart badge, or showing a small success message.

<br/>

## Search State and Runtime Controls

Each mounted Search Results or Product Grid App Block registers a reactive entry in `window.RCCSearchStores`. The entry becomes available when `rcc-search-store:registered` fires on `window`; its `detail.storeKey` identifies the entry.

`search(query)` starts a fresh search in the mounted block. It trims the query; clears shopper-selected filters; restores configured custom-filter and sort defaults; resets pagination, conversation, and autocomplete state; and refreshes the results. It preserves every configured default filter, including an active collection constraint.

For example, a theme can keep its search form on the current page when a Search App Block is mounted. Check `signals.collectionId` before taking over the form so a collection-scoped Product Grid continues to submit normally.

```js
document
  .querySelector('#your-search-form')
  ?.addEventListener('submit', (event) => {
    // Resolve the block through its root's data-search-store key. This
    // example only takes over when exactly one block is mounted; on
    // templates with several, scope the selector to the intended block,
    // for example '#main-search-section .rcc-search'.
    const roots = document.querySelectorAll('.rcc-search');
    const root = roots.length === 1 ? roots[0] : undefined;
    const search = root
      ? (window.RCCSearchStores ?? {})[root.dataset.searchStore]
      : undefined;
    const query = new FormData(event.currentTarget).get('q');

    if (
      !search ||
      search.signals.collectionId.value ||
      typeof query !== 'string' ||
      !query.trim()
    ) {
      return;
    }

    event.preventDefault();
    search.search(query);
  });
```

After the registration event fires, this two-line example changes the rendered collection and clears shopper-selected filters in one request.

```js
const search = Object.values(window.RCCSearchStores)[0];
search.setCollection('123456789', { clearFilters: true });
```

`setFilters(filters)` replaces shopper-selected filters, resets pagination to page 1, updates the URL query parameters, and refreshes the results. Each filter uses `{ field, value: string[] }`. It does not remove hidden default filters or the active collection constraint; pass an empty array to clear shopper-selected filters. Use `setCollection` rather than passing the reserved `attributes.rcc_collection_id` or `attributes.rcc_tags` fields.

`setCollection(collectionId, options?)` replaces the active collection constraint, clears collection tags from the previous page, resets pagination to page 1, and refreshes the results. Pass a Shopify numeric collection ID as a string or number. Pass `null` to render catalog-wide results.

Set `clearFilters: true` to clear shopper-selected facet filters as part of the same state transition, producing one result request for the final collection and filter state. This clears only `signals.userFilters`. It preserves non-collection `signals.defaultFilters`, request-level `window.Nimstrata.search.defaultFilters`, and `signals.appliedCustomFilters`.

Changing the collection clears the original collection title and description because metadata for the new collection is not available in the current page; it does not navigate or change the storefront URL path.

The root `.rcc-search` element exposes its key as `data-search-store` after registration. This can identify a particular block when a page contains more than one.

The entry's `signals` object contains read-only Preact signals. Read current state from `.value`, or call `.subscribe(callback)` and retain the returned unsubscribe function.

| Signal                                         | Value {.compact}                                                               |
| ---------------------------------------------- | ------------------------------------------------------------------------------ |
| `filters`, `userFilters`, `defaultFilters`     | Combined store filters, shopper selections, and App Block collection defaults. |
| `collectionId`, `collectionTags`               | Active collection constraint and collection tags.                              |
| `query`, `activeQuery`                         | Current input and last applied query.                                          |
| `currentPage`, `pagination`, `totalResults`    | Current and returned pagination state.                                         |
| `facets`, `checkedFacets`, `filterCount`       | Available facets and active refinement summary.                                |
| `appliedCustomFilters`, `orderField`           | Active custom switches and sort field.                                         |
| `products`, `isLoading`                        | Currently rendered product data and request state.                             |
| `searchParams`, `filterHash`                   | Computed URL query string and stable combined-filter identity.                 |
| `displaySettings`, `resultsPerRow`, `pageSize` | Current App Block rendering settings.                                          |

Use `search`, `setFilters`, and `setCollection` to make changes rather than assigning to a signal's `.value` or calling the registry entry's underlying store.

Search App Blocks dispatch these lifecycle events for the registry:

| Event                         | Target   | Purpose {.compact}                                                      |
| ----------------------------- | -------- | ----------------------------------------------------------------------- |
| `rcc-search-store:registered` | `window` | Announces that an entry is available in `window.RCCSearchStores`.       |
| `rcc-search-store:removed`    | `window` | Announces that an entry has been removed from `window.RCCSearchStores`. |

<br/>

## Best Practices

- Add custom listeners in `snippets/nimstrata.liquid`; see [nimstrata.liquid Setup](./nimstrata-liquid.md).
- Scope listeners to the page types that render the relevant App Blocks.
- Keep listeners idempotent so duplicate snippets do not send duplicate analytics events or open multiple UI layers.
- Treat event payloads as browser-visible data. Do not add customer identifiers, storefront tokens, or secrets to forwarded analytics payloads.
- Read `event.detail` defensively because Shopify Ajax and result response shapes can vary by request.
- Use failure events for diagnostics or carefully worded user messaging, but do not expose raw technical errors to shoppers.
