# Widget Library
> Documentation for the Segmentify Widget Library -- tested widgets that replace code written in the panel.
import { Card, CardGrid, LinkCard } from '@astrojs/starlight/components';
## What It Does
A widget receives data and settings only. There is no field for HTML, CSS
or JavaScript, so nothing untested reaches a customer's site.
Each widget sends its own events: impression, widget view, click, slider
arrows and add to basket.
The contract and its conformance scenarios are language-neutral. The web,
React Native, Swift and Kotlin renderers pass the same scenarios.
Every behaviour starts as a scenario and runs in happy-dom and in real
Chrome before it is released.
## Explore the Documentation
---
# Introduction
> What the Widget Library is, why it exists, and the words used throughout this documentation.
> This page explains what the Widget Library is, why it exists, and the words used throughout this documentation.
---
## What Is This Library?
Segmentify campaigns show widgets on a customer's website: product recommendations, popups, banners and more. Until now the HTML, CSS and JavaScript of a widget were written by hand in the panel, per campaign.
The Widget Library is an npm package, `@segmentify/widgets`, that replaces that code. A widget in the library is a tested component. The panel no longer sends code to it; it sends **data and settings**.
---
## Why It Exists
Code written in the panel cannot be reviewed or tested. In practice that meant:
- Almost every campaign carried its own copy of slider set-up, click tracking and add-to-basket code.
- A mistake in one copy only showed up on the customer's live site.
- Anyone who could edit a campaign could run any JavaScript on a customer's site.
A library turns each of those into something that is written once, tested, versioned and released.
---
## What a Widget Is Responsible For
A widget owns its **business flow**. For the recommendation widget that means:
- deciding whether it may be shown at all (device, minimum number of products),
- drawing itself from the settings it was given,
- sending the events Segmentify measures: impression, widget view, click, slider arrows,
- adding a product to the basket through the site's adapter.
It is **not** responsible for choosing products, for formatting prices or for talking to the Segmentify API. Those stay on the server and in `@segmentify/integration`.
---
## Status
The library is being rebuilt from zero. The table shows what exists today.
| Part | Status |
| --- | --- |
| Contract: runtime interface and config schema | Draft, revision 2 |
| Conformance scenario format and runner | Done |
| Recommendation widget: display rules, events, slider, add to basket, favourites, rating, badges, discount, account-specific fields, texts by language, theme, "data only" delivery, extension hooks, list and compact layouts | Done, tested in happy-dom and Chrome |
| Per-account extensions and basket / favourite adapters, in `@segmentify/integration` | Planned |
| Loading from `@segmentify/integration` | Planned |
| Settings validation in Sauron, settings UI in the dashboard | Planned |
| React Native, iOS and Android renderers | Planned |
---
## Words Used in These Pages
| Word | Meaning |
| --- | --- |
| **Widget** | A component of this library that shows one kind of campaign. |
| **Contract** | The runtime interface, the config schema and the event protocol. The same on every platform. |
| **Config** | The data and settings one widget instance receives. JSON, with a schema version. |
| **Runtime** | The object that connects a widget to the outside world. On the web `@segmentify/integration` provides it. |
| **Scenario** | A JSON file that describes a config, some steps and the runtime calls that must follow. |
| **Renderer** | The implementation of a widget on one platform. |
| **Native mode** | The mode of `@segmentify/integration` in which it renders everything itself and the legacy web SDK is not loaded. The library only supports this mode. |
| **Adapter** | Per-account code, kept in a repository, that adds a product to that site's own basket. |
---
## Next Steps
- To see how the parts fit together, read [Architecture](../02-architecture/).
- To see what a widget may call, read [Runtime Interface](../03-runtime-interface/).
- To work on the library, start with [Development](../10-development/).
---
# Architecture
> The layers of the Widget Library and the systems around it.
> This page shows the layers of the library, where each one lives, and how a setting made in the panel becomes a widget on a page.
---
## Three Layers
| Layer | What it is | Where it lives |
| --- | --- | --- |
| **Contract** | The runtime interface, the config schema, the event protocol and the conformance scenarios | `src/contract/`, `scenarios/`, `fixtures/` |
| **Renderers** | One implementation of each widget per platform | `src/recommendation/` for the web; the mobile SDKs for the others |
| **Runtime** | The connection to events, the basket and the page | `@segmentify/integration` on the web; the platform SDK on mobile |
The contract is the only layer shared by every platform. It is language-neutral on purpose: Swift and Kotlin cannot run TypeScript, so what they share with the web is the schema and the scenarios, not code.
---
## A Widget Does Not Import Integration
A widget never imports `@segmentify/integration`. It receives a `WidgetRuntime` and calls only that.
```
panel settings ──► server ──► event response
│
@segmentify/integration
│ builds the runtime
│ loads the widget (lazy chunk)
▼
renderRecommendation(config, runtime, document)
│
runtime.sendInteraction / addToBasket / ...
```
This has three effects:
- **Tests need no integration.** A recording runtime stands in for it.
- **Mobile uses the same shape.** The Swift and Kotlin SDKs implement the same interface.
- **The dependency points one way.** Integration depends on the library, never the reverse. A lint rule enforces it.
---
## The Systems Around It
| System | Role for widgets | Status |
| --- | --- | --- |
| **dashboard** (the panel) | Offers settings for a widget instead of a code editor | Planned |
| **sauron** (panel backend) | Validates the settings before they are saved | Planned |
| **gandalf** (engine) | Sends the config in the event response as structured data | Planned |
| **@segmentify/integration** | Builds the runtime, loads the widget, places it on the page | Planned |
| **widget-library** | The contract, the scenarios and the web widgets | In progress |
Today these systems still carry HTML, CSS and JavaScript for each campaign. The config-based path is added next to that one, so an old campaign and a new one can run on the same page.
---
## Catalog Entries Are Presets
The catalog in the panel lists about 200 campaign ideas. They are not 200 different widgets. Each entry is a **preset**: one widget plus a set of settings. The library therefore needs a small number of widgets, and the catalog needs one config per entry.
---
## Next Steps
- [Runtime Interface](../03-runtime-interface/) lists what a widget may call.
- [Config Schema](../04-config-schema/) lists what a widget is given.
- [Security Model](../09-security-model/) explains why the config carries no code.
---
# Runtime Interface
> The WidgetRuntime interface, the only way a widget talks to the outside world.
> This page describes `WidgetRuntime`: what a widget may ask for and what it may report. The source is `src/contract/runtime.ts`.
---
## The Interface
```ts
interface WidgetRuntime {
readonly capabilities: { addToBasket: boolean; favorites: boolean };
getContext(): WidgetContext;
sendInteraction(interaction: Interaction): void;
addToBasket(item: BasketItem): Promise;
toggleFavorite(item: FavoriteItem): Promise;
observeVisibility(root: unknown, onVisible: () => void): () => void;
getExtension(extensionId: string): WidgetExtension | undefined;
getProductCard(): ProductCard | undefined;
deliverData(delivery: DataDelivery): void;
reportError(error: WidgetError): void;
}
```
The library defines it. On the web `@segmentify/integration` implements it; on mobile the platform SDK does; in tests `createFakeRuntime()` does.
---
## Members
| Member | What the widget uses it for |
| --- | --- |
| `capabilities` | Whether this site can add to the basket or to favourites. A button is only drawn when the capability is `true`. |
| `getContext()` | The device, page type, language, currency and region of the current page view. |
| `sendInteraction()` | Sends one event. See [Events and Display Rules](../05-events-and-display-rules/). |
| `addToBasket()` | Sends the basket event and asks the site's adapter to add the product. Resolves to `'added'` or `'failed'`. |
| `toggleFavorite()` | Asks the site's adapter to add or remove a favourite and sends the favourite event for what happened: `favorite:add` after `'added'`, `favorite:remove` after `'removed'`, nothing after `'failed'`. Resolves to `'added'`, `'removed'` or `'failed'`. |
| `observeVisibility()` | Calls back once when the widget becomes visible. Returns a function that stops watching. |
| `getExtension()` | The registered per-account extension with this id, or `undefined`. A platform without extensions always answers `undefined`. See [Extensions](../08-recommendation-widget/#extensions). |
| `getProductCard()` | The account's product card, or `undefined`. Without one the widget draws the library card. A platform without account cards always answers `undefined`. See [The Account's Product Card](../08-recommendation-widget/#the-accounts-product-card). |
| `deliverData()` | In "data only" delivery, hands the data and its event functions to the site or app. See [Data Only Delivery](#data-only-delivery). |
| `reportError()` | Reports a problem the widget cannot fix itself. |
---
## Context
```ts
interface WidgetContext {
device: 'PC' | 'mobile' | 'tablet' | 'Unknown';
pageType: string; // 'Home Page', 'Product Page', ...
language: string;
currency: string;
region: string;
}
```
The widget never works these out itself. It does not read the user agent, the URL or the `lang` attribute of the page. The language in particular comes from the place the integration's initialising class was told to take it from; see [Languages and Texts](../06-languages-and-texts/).
---
## Interactions
```ts
interface Interaction {
type:
| 'impression'
| 'widget-view'
| 'click'
| 'slider:arrow:left'
| 'slider:arrow:right';
instanceId: string;
interactionId: string;
}
```
The type values are the ones `@segmentify/integration` already uses. Forwarding an interaction to Google Analytics is the runtime's job; a widget does not know about analytics tools.
---
## Errors
| Code | Reported when |
| --- | --- |
| `UNSUPPORTED_SCHEMA` | The config has a `schemaVersion` this version of the library does not know. |
| `DIV_SELECTOR_NOT_FOUND` | The placement target did not appear within 50 lookups, 100 ms apart. The name is the web SDK's alert type, so a runtime can send it as `event:alert` unchanged. |
| `EXTENSION_NOT_FOUND` | The config names an extension the runtime does not have. |
| `EXTENSION_FAILED` | The extension threw, or answered with something it may not. |
| `PRODUCT_CARD_FAILED` | The account's product card threw, or answered with something it may not. The widget drew the library card instead. |
| `BASKET_FAILED` | Adding to the basket failed or threw. |
| `FAVORITE_FAILED` | Adding to favourites failed or threw. |
---
## Data Only Delivery
With `delivery: 'data'` the site or app draws the recommendations itself. The widget draws nothing and calls `deliverData()` once with this handle:
```ts
interface DataDelivery {
instanceId: string;
title: string; // chosen by the context language
products: Product[];
observeView(root: unknown): void;
reportClick(productId: string): void;
addToBasket(productId: string, quantity?: number): Promise;
}
type DataBasketResult = 'added' | 'failed' | 'unknown-product' | 'unavailable';
```
| Member | What it does |
| --- | --- |
| `title`, `products` | What to draw. `products` is empty when a display rule fails or there is nothing to recommend; the site should then hide its area. |
| `observeView(root)` | Takes the element or view the site drew the data into. Sends `widget-view` once, when the runtime sees it visible. Only the first call is used. |
| `reportClick()` | Sends `click` for a delivered product. Any other id sends nothing. |
| `addToBasket()` | Sends `click`, then adds the product to the basket; `quantity` is 1 when left out. |
| `addToBasket()` resolves to | Meaning |
| --- | --- |
| `'added'` | The product is in the basket. |
| `'failed'` | The site's basket refused or threw. Also reported as `BASKET_FAILED`. |
| `'unknown-product'` | The id is not one of the delivered products. Nothing was sent. |
| `'unavailable'` | This runtime cannot add to the basket (`capabilities.addToBasket` is `false`). Nothing was sent. |
The last two are not failures: nothing was tried, so no error is reported.
This follows the callback delivery of the web SDK: the impression is sent first, then the site receives the title, the products and a way to have its element watched for `widget-view`.
The site sends its events through the handle, so they stay the same events a drawn widget sends.
:::note
How a site subscribes to the data is decided by the runtime. On the web that surface belongs to `@segmentify/integration` and is not built yet.
:::
---
## Next Steps
- [Config Schema](../04-config-schema/) describes what the widget is given.
- [Testing](../11-testing/) shows how the recording runtime is used.
---
# Config Schema
> Every setting a recommendation widget accepts, and what each one does.
> This page lists the settings of the recommendation widget. The source is `src/contract/config.ts`. Settings marked *planned* are in the schema but not yet drawn by the web widget.
---
## Principles
- The config carries **data and settings only**. No field holds HTML, CSS or JavaScript.
- The config is **versioned**. A widget that does not know the `schemaVersion` draws nothing and reports `UNSUPPORTED_SCHEMA`.
- **Every value is drawn as text.** See [Security Model](../09-security-model/).
---
## Stored Settings and Served Payload
The config exists in two forms, each with its own schema. Both are generated from the same types, so they cannot drift.
| Form | Schema | What it is | Who uses it |
| --- | --- | --- | --- |
| **Stored settings** | `schema/recommendation-widget-settings.v1.schema.json` | What the panel saves for a campaign | Sauron validates with it on write |
| **Served payload** | `schema/recommendation-widget-config.v1.schema.json` | What a widget is given to draw | The server builds it for a response; the widget reads it |
The served payload is the stored settings plus the **response part**: `instanceId`, `actionId`, `interactionId` and `products`. The server adds these four fields and changes no setting. Stored settings that carry one of them are refused, and so is a served payload that lacks one.
Every field on this page belongs to the stored settings unless it is marked *response part*.
---
## Identity
| Field | Meaning |
| --- | --- |
| `schemaVersion` | The version of this schema. Currently `1`. |
| `component` | `'recommendation'`. |
| `instanceId` | *Response part.* The campaign. |
| `actionId` | *Response part.* Sent as `interactionId` with the impression. |
| `interactionId` | *Response part.* Sent as `interactionId` with the widget view. |
| `delivery` | `'render'`: the widget draws itself. `'data'`: the site draws it; see [Data Only Delivery](../03-runtime-interface/#data-only-delivery). |
---
## Content
| Field | Meaning |
| --- | --- |
| `title` | The default title. |
| `titles` | Titles per language. See [Languages and Texts](../06-languages-and-texts/). |
| `titleLevel` | The level of the heading the title is drawn as, `2` to `6`. `2` (an `h2`) when not set. Chosen to fit the headings of the page around the widget. Web only. |
| `labels` | Default texts: `addToBasket`, `addToFavorites`, `seeAll`, and the texts for screen readers `oldPrice`, `discount`, `rating`. |
| `seeAll.url` | Optional. An `https` URL; draws a link in the header whose text is `labels.seeAll` ("See all" when not set). A tap sends no event. |
| `labelsByLanguage` | Those texts per language. |
| `products` | *Response part.* The products to show, already chosen and ordered by the server. |
### Products
A product has typed core fields and may carry any number of account-specific fields.
| Core field | Notes |
| --- | --- |
| `productId`, `name`, `url`, `image` | Required. |
| `price`, `priceText` | Required. `priceText` arrives formatted; the widget does not format prices. |
| `oldPrice`, `oldPriceText`, `brand` | Optional. |
| `discount` | Optional. A percentage; drawn as `-25%` in English and `-%25` in Turkish. |
| `rating`, `reviewCount` | Optional. Drawn as `4.5 (120)`, or `4.5` without a review count; `4,5 (120)` in Turkish. See [Numbers](../06-languages-and-texts/#numbers). |
| `badges` | Optional. The product's own badge texts, drawn after the [badges of the card](#badges-of-the-card) when `badge` is among `card.fields`. At most two badges are drawn, one on a compact card. A long text is cut on the card; the whole text stays in the markup. |
Fields the widget does not know are kept, never removed.
### Account-specific fields
To show one on the card, add an entry to `card.fields`:
```json
{ "path": "params.badgeLabel", "display": "badge" }
```
| Rule | Detail |
| --- | --- |
| `path` | A dot path into the product. Only the product's own properties are followed. |
| `display` | `'text'` or `'badge'`. |
| Lists | Each item of a list is drawn as its own element. |
| Not drawn | A missing path, an empty value or an object. |
| Always text | A value that contains HTML is shown as the characters it is made of. |
A field with no data draws nothing and takes no space on the card. The same holds for `brand`, `oldPrice`, `discount`, `rating` and `badge`.
### Badges of the Card
A badge is a part of the product card and is defined on the card, in `card.badges`. A badge is either a fixed text or the value of a field of the product.
```json
"card": {
"badges": [
{ "value": "discount" },
{ "text": "Members only", "texts": { "TR": "Üyelere özel" }, "when": "params.memberOnly" },
{ "text": "Free returns", "texts": { "TR": "Ücretsiz iade" } }
]
}
```
| Badge | Fields | Drawn |
| --- | --- | --- |
| Fixed text | `text`, optional `texts` by language (matched like `titles`) | On every product. |
| Fixed text with a condition | `text`, `texts`, `when` (a dot path into the product) | Only on a product that has the field: a text that is not empty, a number other than zero, `true`, or a list with an entry. |
| Product value | `value` (a dot path into the product) | The field as text. `discount` and `rating` are written the way the language writes them (`-25%`, `-%25`). A list gives one badge per entry. Nothing for a product without the field, a discount of zero, `true`, `false` or an object. |
| Rule | Detail |
| --- | --- |
| Order | The badges of the card in their order, then the product's own `badges` texts when `badge` is among `card.fields`. |
| How many | Two on a standard card, one on a compact card; the rest is left out. At most four definitions. |
| Without `badge` in `card.fields` | The badges of the card are still drawn; the product's own are not. |
| Conditions | Only "the product has this field". There are no comparisons; a rule such as "more than 20% off" belongs in the product data, as a field of its own. |
| Always text | A fixed text and a product value are both written as text, never as markup. |
| A badge is not both | An entry with `text` and `value` together, or with neither, is not valid. |
---
## Slot
One optional strip between the header and the cards. This version knows one kind, the countdown.
```json
"slot": {
"type": "countdown",
"endsAt": "2026-11-27T23:59:59+03:00",
"text": "Ends in",
"texts": { "TR": "Bitmesine kalan" }
}
```
| Field | Notes |
| --- | --- |
| `type` | `"countdown"`. |
| `endsAt` | The moment the countdown ends: an ISO-8601 date and time **with a time zone** (`Z` or an offset). Without a zone a time means a different moment on every device, so it is refused. |
| `text`, `texts` | Optional. The text before the time, by language, matched like `titles`. |
| Rule | Detail |
| --- | --- |
| What is drawn | The text and the time left as `HH:MM:SS`, in the digits of the context language, updated every second. |
| More than a day | Written in hours (`51:14:37`), so the format needs no words. |
| At the end | The slot removes itself. The widget stays, and nothing is sent. |
| Not drawn | An end time that is over, one that cannot be read, or a slot of a kind this version does not know. The widget is drawn without it. |
| Clock | The clock of the visitor's device. A device with a wrong clock shows a wrong time left. |
| Colours | `countdownBackground` and `countdownColor`; see [Theming](../13-theming/). |
---
## Placement
Web only.
| Field | Meaning |
| --- | --- |
| `placement.selector` | The element on the page the widget is placed relative to. |
| `placement.insert` | `APPEND`, `PREPEND`, `BEFORE`, `AFTER` or `SELF` (replace the element's content). |
---
## Layout
| Field | Meaning |
| --- | --- |
| `layout.type` | `'slider'`, `'grid'`, `'list'` or `'compact'`. See [Layouts](../08-recommendation-widget/#layouts). |
| `layout.breakpoints` | A list of `{ minWidth, columns, step, gap }`. |
| `layout.arrows` | Draw previous and next arrows on a slider. |
| `layout.loop` | On a slider, a step past an edge goes to the other edge, and no arrow is ever disabled. |
| `layout.pagination` | On a slider, draw one dot per page. |
A breakpoint applies when the **widget's own width** is at least `minWidth` pixels; the widest one that fits wins. `columns` is the number of cards visible in a row and may be fractional (`1.5`). `step` is the number of cards one arrow tap moves. `gap` is the space between cards in pixels.
---
## Card
| Field | Meaning |
| --- | --- |
| `card.fields` | Which product fields are drawn, in this order. |
| `card.addToBasket` | Draw an add-to-basket button, if the runtime can add to the basket. |
| `card.addToFavorites` | Draw a favourite button, if the runtime has favourites. |
| `card.openInNewTab` | Open the product in a new tab. |
| `card.nameLines` | Maximum lines for the product name, 1 to 10. Longer names are cut with an ellipsis. |
---
## Rules
| Field | Meaning |
| --- | --- |
| `rules.minProducts` | Minimum number of products per device. Below it the widget is not shown. Defaults to 1. |
| `rules.devices` | The devices the widget is shown on. All when absent. |
---
## Theme
`theme` is the campaign's own theme: a closed list of semantic and component tokens (colours, sizes, radii, a border, the font). It overrides, token by token, the theme set at initialisation and the site's CSS; the tokens, their fallbacks and the layers are on the [Theming](/13-theming/) page. There is no free CSS, and each value must have the form of its kind:
| Kind | Accepted |
| --- | --- |
| Colour | Hex with 3, 4, 6 or 8 digits; `rgb()`, `rgba()`, `hsl()` or `hsla()` with three components and an optional alpha, separated by commas or by spaces (alpha after `/`); `transparent`, `currentColor`, `inherit`; or one of the 148 colour names of CSS in lower case (`red`, `rebeccapurple`). Up to 64 characters. No other word and no other function |
| Length | A number with `px`, `rem`, `em` or `%`, or `0` |
| Font family | Families separated by commas. A family is a quoted name (letters, digits, spaces, hyphens, underscores; the quote is closed and holds no comma) or words separated by one space, each starting with a letter |
| Border | `none`, `0`, or a width in `px`, a style (`solid`, `dashed`, `dotted`) and a colour (hex, a colour name or a colour keyword) |
Each token becomes a CSS custom property on the widget element (`titleColor` → `--sgf-title-color`). The widget checks every value again before applying it, with the same rules as the schema; a value that does not have the form of its kind is ignored and the rest of the theme still applies.
With an empty theme the widget still looks finished: it inherits the page's font and text colour and uses neutral defaults for buttons, badges and arrows.
`paginationColor` and `paginationActiveColor` colour the pagination dots; they have no effect when `layout.pagination` is off.
---
## Value Rules
The schema also limits values, so a config cannot carry something a setting was never meant to hold.
| Value | Rule |
| --- | --- |
| Product URL, image URL | `https` only |
| Identifiers | Letters, digits, `_`, `.`, `:`, `-`; at most 64 characters |
| Texts | At most 300 characters; button texts at most 60 |
| Placement selector | At most 300 characters; no `<`, `>`, `{`, `}` |
| Custom field path | Letters, digits and underscores, separated by dots |
| Products | At most 100 |
| Breakpoints | 1 to 10; `columns` above 0 and at most 12 |
| Unknown fields | Rejected everywhere except on a product |
The generated schemas are `schema/recommendation-widget-settings.v1.schema.json` (stored settings) and `schema/recommendation-widget-config.v1.schema.json` (served payload). See [Security Model](../09-security-model/).
---
## Next Steps
- [Events and Display Rules](../05-events-and-display-rules/) explains what the widget does with these settings.
- A complete example config is in `fixtures/valid/reco-basic.json`.
---
# Events and Display Rules
> Which event a widget sends and when, and the rules that decide whether it is shown.
> This page defines the event protocol of the recommendation widget and the rules that decide whether it is shown at all.
---
## Display Rules
The rules are checked in this order. When one fails, the widget draws nothing and sends **no event**.
| # | Rule | On failure |
| --- | --- | --- |
| 1 | `schemaVersion` is known | `reportError('UNSUPPORTED_SCHEMA')` |
| 2 | If the config has an `extensionId`, the extension is registered and runs without a fault | `reportError('EXTENSION_NOT_FOUND')` or `reportError('EXTENSION_FAILED')` |
| 3 | If `rules.devices` exists, the current device is in it | Nothing |
| 4 | There are at least `rules.minProducts[device]` products (1 when not set), counted after the extension's product filter | Nothing |
| 5 | The extension's `shouldRender`, if it has one, answers `true` | Nothing |
| 6 | Web: `placement.selector` matches an element; looked up 50 times, 100 ms apart | `reportError('DIV_SELECTOR_NOT_FOUND')` |
Rules 3 to 5 are silent on purpose: a widget that is not meant for this device or page is not an error.
In data only delivery a failing rule from 2 on gives the site an empty delivery; see below.
---
## Events
| When | Call | How often |
| --- | --- | --- |
| The placement target is found and the widget is added to the page | `impression`, with `interactionId` = `actionId` | Once per render; never before the target is found |
| The widget becomes visible | `widget-view`, with `interactionId` = `interactionId` | Once |
| A product card is tapped | `click`, with `interactionId` = the product id | Every tap, before navigation |
| The previous or next arrow is tapped | `slider:arrow:left` or `slider:arrow:right`, with the same value as `interactionId` | Every tap that the arrow accepts; an arrow at its edge refuses the tap |
| A pagination dot is tapped | Nothing; by decision | |
| The see all link is tapped | Nothing | |
| The add-to-basket button is tapped | `click`, then `addToBasket` with `quantity: 1` | Every tap; the page does not navigate |
Every event carries the campaign's `instanceId`.
### In Data Only Delivery
The widget draws nothing, so the site reports what the visitor does through the delivered handle.
| When | Call | How often |
| --- | --- | --- |
| There is something to show | `impression`, then `deliverData` | Once |
| A display rule fails, or there are no products | `deliverData` with an empty product list; no `impression` | Once |
| The element given to `observeView(root)` becomes visible | `widget-view` | Once |
| The site calls `reportClick(productId)` | `click` | Every call for a delivered product |
| The site calls `addToBasket(productId, quantity)` | `click`, then `addToBasket` | Every call for a delivered product |
The impression is sent before the delivery, as in the callback delivery of the web SDK. As there, the site is also told when there is nothing to show, so it can hide the place it kept for the widget; an empty delivery sends no event afterwards either. No placement target is looked for in this mode, because the site decides where it draws.
### The Placement Target
A page may add the target after the campaign arrives. The widget looks for it 50 times, 100 ms apart, as the web SDK does. If it never appears, the widget reports `DIV_SELECTOR_NOT_FOUND` once and sends no impression. The runtime turns that report into the `event:alert` custom event.
---
## Impression and Widget View Are Different
An **impression** means the widget was delivered to the page. A **widget view** means the visitor could actually see it. A widget far down a long page has an impression and may never have a widget view.
Visibility is the runtime's knowledge, not the widget's: the widget asks `observeVisibility()` and sends `widget-view` the first time it is called back.
---
## Add to Basket
1. The button is drawn only when `card.addToBasket` is `true` **and** `runtime.capabilities.addToBasket` is `true`.
2. A tap sends `click` and then calls `runtime.addToBasket()`.
3. The button is disabled until the answer arrives, so a second tap cannot add the product twice.
4. On `'failed'`, or when the call throws, the widget reports `BASKET_FAILED` and enables the button again.
The card link and the button are separate elements next to each other. A tap on the button is therefore not a tap on the card, and the page does not navigate.
Adding to the site's own basket is different on every site. That part lives in a per-account adapter behind the runtime, not in the widget.
---
## Favourites
1. The button is drawn only when `card.addToFavorites` is `true` **and** `runtime.capabilities.favorites` is `true`.
2. A tap calls `runtime.toggleFavorite()`. The runtime sends the Segmentify favourite event, as it sends the basket event for add to basket: `favorite:add` when the product was added and `favorite:remove` when it was removed, with the product id. These are the web SDK's existing events. The widget itself sends no `click` for a favourite tap.
3. `'added'` shows the product as a favourite, `'removed'` as not a favourite.
4. On `'failed'`, or when the call throws, the widget reports `FAVORITE_FAILED` and keeps the previous state.
Every product starts as not a favourite. The state is not kept: after a page reload the button is not selected again. No source for an initial state is defined.
---
## Next Steps
- [Conformance Scenarios](../07-conformance-scenarios/) shows how each rule on this page is tested.
- [Runtime Interface](../03-runtime-interface/) lists the calls used here.
---
# Languages and Texts
> How a widget chooses its title and button texts by language.
> This page explains where the language comes from and how a widget picks its title and button texts.
---
## Where the Language Comes From
The widget reads one value: `runtime.getContext().language`.
It does not look at `window`, at the `lang` attribute of the page or at the browser's language. The class that initialises `@segmentify/integration` is told where the language of the site comes from, and the runtime reads it from there. There is one source of truth, and it is the integration's.
---
## Matching
The same rule is used for titles and for button texts.
1. An **exact** match on the language key.
2. Otherwise the **base language**: `tr-TR` matches the key `TR`.
3. Otherwise the **default**.
Keys compare case-insensitively, so `tr`, `TR` and `Tr` are the same key.
| Context language | Keys in the config | Result |
| --- | --- | --- |
| `TR` | `TR`, `EN` | `TR` |
| `tr-TR` | `TR`, `EN` | `TR` |
| `DE` | `TR`, `EN` | the default |
---
## Title
```json
{
"title": "Recommended for you",
"titles": { "TR": "Sizin için seçtiklerimiz" }
}
```
`title` is the default. `titles` holds one title per language.
---
## Button Texts
```json
{
"labels": { "addToBasket": "Add to cart" },
"labelsByLanguage": {
"TR": { "addToBasket": "Sepete ekle" }
}
}
```
For each text the widget takes the first that exists:
1. the entry for the language in `labelsByLanguage`,
2. the entry in `labels`,
3. the English default built into the library (`Add to basket`, `Add to favourites`, `See all`).
A language entry may set only some of the texts; the rest fall through.
---
## Numbers
The numbers the widget writes itself follow the context language, through the platform's own number formatting.
| Value | English | Turkish |
| --- | --- | --- |
| Rating `4.5` | `4.5` | `4,5` |
| Review count `1250` | `(1,250)` | `(1.250)` |
| Discount `25` | `-25%` | `-%25` |
A rating is rounded to one decimal and a discount to a whole percent.
The language may be written as `TR`, `tr-TR` or `tr_TR`. A language the platform does not know, or a malformed one, is formatted as English. It never falls back to the locale of the visitor's machine, so the same config looks the same everywhere.
Prices are not formatted by the widget: `priceText` and `oldPriceText` arrive ready from the server.
---
## Next Steps
- [Config Schema](../04-config-schema/) lists the other settings.
- The scenarios `13-*` and `05b-*`, `05c-*` under `scenarios/recommendation/` test this page.
---
# Conformance Scenarios
> The JSON scenarios that define correct widget behaviour on every platform.
> This page describes the scenario format. A scenario is the definition of a behaviour: if it is not in a scenario, it is not part of the contract.
---
## Why JSON
The web widget is TypeScript; the mobile renderers will be Swift and Kotlin. They cannot share code, but they can read the same files. A scenario says, in data, "with this config, after these steps, the runtime must have received exactly these calls". Each platform has a small runner that applies it.
Scenarios live in `scenarios/`, example configs in `fixtures/`. Both are published in the npm package.
---
## A Scenario
```json
{
"name": "a product tap sends click with the product id",
"config": "fixtures/valid/reco-basic.json",
"steps": [
{ "do": "render" },
{ "do": "tap", "target": "product:p2" }
],
"expect": {
"rendered": true,
"calls": [
{ "interaction": { "type": "impression", "instanceId": "scn_1", "interactionId": "act_1" } },
{ "interaction": { "type": "click", "instanceId": "scn_1", "interactionId": "p2" } }
]
}
}
```
---
## Fields
| Field | Meaning |
| --- | --- |
| `name` | One sentence that states the behaviour. |
| `platforms` | The platforms that run it. All when absent. |
| `requires` | What the runner must have. `"layout"`: real sizes and scrolling. `"styles"`: the computed CSS cascade. A runner without them, such as the happy-dom one, skips the scenario. |
| `initTheme` | The theme set when the library is initialised, before the widget renders (web: `setWidgetTheme`). |
| `now` | The moment the scenario starts at, ISO-8601 with a time zone. The runner sets its clock to it, and the clock stands still except in a `wait` step. Needed by anything that reads the time, such as a countdown. |
| `config` | The fixture to start from, as a path from the repository root. |
| `override` | Values deep-merged over the fixture. Arrays and primitives replace. |
| `context` | Parts of the runtime context to set (`device`, `language`, ...). |
| `capabilities` | Runtime capabilities to set. |
| `runtime` | What the runtime answers: `basketResult`, `favoriteResult`; `added` when absent. `hold: true` keeps the answers pending until an `answer` step. |
| `steps` | What happens, in order. |
| `expect` | What must be true afterwards. |
---
## Steps
| Step | Meaning |
| --- | --- |
| `{ "do": "render" }` | Mount the widget with the config. |
| `{ "do": "show" }` | The widget scrolls into view. |
| `{ "do": "resize", "width": 1200 }` | The widget's container becomes this wide, in pixels. |
| `{ "do": "tap", "target": "..." }` | The visitor taps a target. |
| `{ "do": "answer" }` | The runtime gives every answer it was holding. |
| `{ "do": "remove" }` | The page removes the widget. |
| `{ "do": "wait", "ms": 2000 }` | Time passes: this many milliseconds, with every timer that is due. |
| `{ "do": "observe-view" }` | Data only delivery: the site hands the element it drew to `observeView()`. A later `show` makes it visible. |
| `{ "do": "report-click", "productId": "p2" }` | Data only delivery: the site calls `reportClick()`. |
| `{ "do": "add-to-basket", "productId": "p2", "quantity": 2 }` | Data only delivery: the site calls `addToBasket()`. `quantity` is optional. |
Tap targets have stable names: `product:`, `basket:`, `favorite:`, `arrow-prev`, `arrow-next`, `page:`. Texts that are not tapped have names too, for example `countdown` and `slot-text`. On the web they are `data-target` attributes inside the widget.
---
## Expectations
| Field | Meaning |
| --- | --- |
| `rendered` | Whether the widget is on the page. |
| `calls` | **Every** runtime call, in order. Nothing more and nothing less. |
| `title` | The text of the title. |
| `texts` | The text of named targets. |
| `columns` | The number of cards visible in a row. |
| `enabled` | Targets that must exist and accept a tap. |
| `disabled` | Targets that must exist and refuse a tap. |
| `hidden` | Targets that must exist and be hidden. |
| `current` | Targets that must be marked as the current one, such as a pagination dot. |
| `layout` | The layout the product list must be in: `slider`, `grid`, `list` or `compact`. |
| `card` | The kind of card every product must be drawn as: `standard` or `compact`. |
| `labels` | The accessible label per target, for controls that show an icon. |
| `selected`, `unselected` | Toggle targets, such as a favourite, that must show as selected or not. |
| `absent` | Targets that must not exist. |
| `theme` | Theme tokens that must be applied, with their values. |
| `themeAbsent` | Theme tokens that must not be applied. |
| `effectiveTheme` | Theme tokens with the value the widget ends up with after the layers: campaign theme over initialisation theme. Needs `requires: ["styles"]`. |
| `effectiveThemeAbsent` | Theme tokens that must have no value after the layers. |
| `nameLines` | The line limit applied to product names. |
| `basketResults` | What each `add-to-basket` step resolved with, in order. |
A data delivery is recorded in `calls` as `{ "deliverData": { "instanceId", "title", "productIds" } }`.
`calls` is strict on purpose. A widget that sends one extra event fails the scenario, because an extra event is a measurement error.
---
## Writing a New One
1. Add a JSON file under `scenarios/recommendation/`. The number at the start of the name follows the scenario list in the contract.
2. Run `pnpm test:dom` and see it fail.
3. Implement the behaviour.
4. Run `pnpm check`; the scenario now runs in happy-dom and in Chrome.
---
## Next Steps
- [Testing](../11-testing/) explains the two environments the scenarios run in.
- [Events and Display Rules](../05-events-and-display-rules/) is the prose version of what the scenarios check.
---
# Recommendation Widget
> How the recommendation widget is rendered on the web and how it is built.
> This page describes the web implementation of the recommendation widget: how it is called, what it puts on the page and what it leaves to the page.
---
## Rendering
```ts
import { renderRecommendation } from '@segmentify/widgets';
const widget = await renderRecommendation(config, runtime, document);
```
| Argument | Meaning |
| --- | --- |
| `config` | A `RecommendationWidgetConfig`. See [Config Schema](../04-config-schema/). |
| `runtime` | A `WidgetRuntime`. See [Runtime Interface](../03-runtime-interface/). |
| `document` | The document to render into. |
It resolves with the widget element, or with `null` when a display rule says the widget must not be shown.
If the placement target is not on the page yet, it waits for it: 50 lookups, 100 ms apart. See [The Placement Target](../05-events-and-display-rules/#the-placement-target).
With `delivery: 'data'` it draws nothing and also returns `null`; the data goes to the runtime's `deliverData()`. See [Data Only Delivery](../03-runtime-interface/#data-only-delivery).
In production `@segmentify/integration` makes this call. Nothing on a customer's page calls it directly.
---
## What Ends Up on the Page
One custom element, ``, placed where `placement` says. Everything else is inside its **shadow root**:
```
#shadow-root