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
Section titled “Rendering”import { renderRecommendation } from '@segmentify/widgets';
const widget = await renderRecommendation(config, runtime, document);| Argument | Meaning |
|---|---|
config |
A RecommendationWidgetConfig. See Config Schema. |
runtime |
A WidgetRuntime. See 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.
With delivery: 'data' it draws nothing and also returns null; the data goes to the runtime’s deliverData(). See 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
Section titled “What Ends Up on the Page”One custom element, <sgf-recommendation>, placed where placement says. Everything else is inside its shadow root:
<sgf-recommendation role="region" aria-label="the title"> #shadow-root <style> layout and theme rules header <h2> title h2, or the level in titleLevel <a> see all when the config has one <button> previous arrow, <button> next arrow slot when the config has one: a countdown <ul> product list one item per product <li> card <a> link the fields listed in card.fields, in that order (compact card: the image, then a column with the rest) <button> add to basket, when enabled <button> favourite, when enabled pagination dots when enabledWith an account product card there is a second <style> with the card’s styles, and each card is a list item around what the account card drew.
Semantic Markup
Section titled “Semantic Markup”Every part is the element HTML has for it, so a screen reader, a search engine and a reader view can tell what it is. This is a rule for every component of the library, not a property of this one, and a test holds each component to it (see Testing).
| Part | Element | Why |
|---|---|---|
| The widget | The host, with role="region" and the title as its name |
A visitor can jump to it and hears what it is. The name is on the host because a reference by id cannot leave a shadow root |
| Title | A heading: h2, or h3 to h6 with titleLevel |
It takes its place in the headings of the page. Never h1: a page has one, and it is not a widget’s |
| Product list | ul, one li per product |
A slider, a grid and a list are all lists; the number of products is announced |
| Product | a around the image and texts |
One link per product, named by the product |
| Old price | del, after a text for screen readers (“Old price”) |
Removed text; the eye sees the line through it, a screen reader is told |
| Discount, rating | Their text, after a text for screen readers (“Discount”, “Rating”) | “-25%” and “4.5 (120)” say nothing without what they are |
| Add to basket, favourite, arrows | button with a name; the favourite has aria-pressed, the arrows name the list they move with aria-controls |
|
| Countdown | role="timer" |
Not read out on every tick |
The texts for screen readers are labels of the config (oldPrice, discount, rating), per language like the button texts. They stand before the element they describe, not inside it, so the text of a price is exactly what the product says. They are in the markup and take no room on the page.
Not article for a card: a list item already says “one of these”, and an article per product makes a screen reader announce more, not better.
A card drawn by an account is the account’s markup; the library wraps it in the list item and cannot make the inside semantic.
The Default Look
Section titled “The Default Look”The look with an empty theme follows the “Segmentify Widgets” design system.
| Part | Default |
|---|---|
| Title | 20/28 semibold; 17/24 when the widget is narrower than 600 px. A titleSize from the theme applies at every width. |
| Header | The title on the left; the see all link and the arrows on the right, above the cards. |
| Slot | Optional, between the header and the cards. A countdown: its text, then the time left on a pill in countdownBackground and countdownColor, with digits of one width so the pill does not jump. See Slot. |
| Card | Round corners of 8 px, no border, no ground. The image is square on a light grey ground while it loads. |
| Texts | Brand 12/16 upper case; name 14/20; price 16/22 bold; old price 13/18 struck through; discount 13/18 bold; rating 12/16. |
| Prices | The price, the old price and the discount share one row, where the first of them stands in card.fields. |
| Badges | The badges of the card (card.badges: fixed texts and product values), then the product’s own. Over the top left of the image, stacked; at most two are drawn. A badge is one line; a text that does not fit is cut with an ellipsis, and a badge never lies under the favourite button. On a compact card one badge is drawn, with the texts. |
| Favourite | A round button over the top right of the image. |
| Arrows | Round, 40 px, with a soft shadow. Not shown on a touch screen, where the row scrolls by swipe. |
| Pagination | Dots of 8 px under the cards; the current one is a pill of 24 px. |
Layouts
Section titled “Layouts”layout.type |
What it draws | Card | Arrows, loop, pagination |
|---|---|---|---|
slider |
One row that scrolls | Standard | Yes |
grid |
Rows that wrap | Standard | No |
list |
A vertical stack, each card as wide as the widget | Compact | No |
compact |
One row that scrolls, like the slider | Compact | Yes |
The breakpoints give the column count, step and gap for slider, grid and compact. A list uses only the gap.
The Compact Card
Section titled “The Compact Card”A standard card stacks its fields under a square image. A compact card is a row: a 72 px square image on the left, the other fields of card.fields in a column next to it, and the buttons on the right.
On a compact card add to basket and favourite are icon buttons of 36 px. Their text (labels, labelsByLanguage) is not drawn; it is the accessible label of the button. The events are the same as on a standard card.
A compact card usually reads best with card.nameLines: 1.
The Slider
Section titled “The Slider”There is no slider library. The slider is the browser’s own horizontal scrolling with scroll snapping:
- The list is a flex row that scrolls on the x axis.
- Each card’s width comes from two custom properties, the column count and the gap.
- The widget watches its own width with
ResizeObserverand applies the widest breakpoint that fits. - An arrow scrolls the list by
stepcard widths.
| Part | Behaviour |
|---|---|
| Arrows | The previous arrow refuses a tap at the start and the next arrow at the end. Both are hidden when every product fits in the row. |
layout.loop |
A step past an edge goes to the other edge. No arrow is disabled. |
layout.pagination |
One dot per page; the current one is marked and follows the scroll position. A tap on a dot goes to its page and sends no event. No dot is drawn when there is one page. |
A page is one step: with 5 products, 2 per row and a step of 2 there are 3 pages.
Because the breakpoints follow the widget’s width and not the window’s, the same config works in a narrow sidebar and in a full-width section.
What the Page Can and Cannot Change
Section titled “What the Page Can and Cannot Change”| The page… | Result |
|---|---|
styles a, span, img, button |
Does not reach inside the widget. |
sets a width or margin on sgf-recommendation |
Applies. The page owns where the widget sits. |
| sets a font or text colour on an ancestor | Inherited by the widget, unless the theme sets its own. |
sets a theme token on :root or an ancestor (--sgf-primary: …) |
Applies, over the initialisation theme and under the campaign theme. See Theming. |
The first row is what shadow DOM guarantees. The others are by design and are fixed by tests.
Leaving the Page
Section titled “Leaving the Page”sgf-recommendation is a custom element. When it is removed from the page, by the site or by a single-page application’s navigation, the widget stops its width observer, its scroll listeners and its visibility observer. Leaving is final: a widget put back on the page is not started again.
A campaign can also be cancelled from outside with an AbortSignal:
const controller = new AbortController();renderRecommendation(config, runtime, document, { signal: controller.signal });
controller.abort(); // the page changedWhen abort() is called |
What happens |
|---|---|
| Before the render started | Nothing is drawn or sent. |
| While the widget waits for its placement target | The wait stops. No error is reported. |
| After the widget was drawn | The widget is removed from the page and stops everything. |
| In data only delivery | The element the site handed to observeView() is no longer watched. |
Extensions
Section titled “Extensions”Some accounts need behaviour no setting can express. An extension is code in a repository, reviewed and tested, that a config names with extensionId. The runtime hands it over through getExtension().
interface WidgetExtension { filterProducts?(products, context): Product[]; shouldRender?(config, context): boolean;}| Hook | What it can do |
|---|---|
filterProducts |
Return some of the products it was given, in any order. It sees every field of a product, also account-specific ones. The minimum product count applies to what it returns. |
shouldRender |
Return false to keep the widget off the page. It sees the config with the products that would be shown. |
An extension is not trusted:
| It cannot | Because |
|---|---|
| Change a product or a setting | It receives frozen copies. An attempt throws. |
| Add a product | Its answer is read as a list of product ids and applied to the original products. |
| Return a product twice, or something that is not a list or a boolean | The answer is checked. |
Any of these, and any error thrown, reports EXTENSION_FAILED and the widget is not shown. A config that names an extension the runtime does not have reports EXTENSION_NOT_FOUND and is not shown either.
There are no extensions on mobile.
Where Extensions Live
Section titled “Where Extensions Live”Extensions live in @segmentify/integration, next to the per-account basket and favourite adapters. Integration registers them and answers getExtension(). This library only defines what an extension may do and guards the widget against it; it holds no account code.
| Part | Lives in |
|---|---|
The WidgetExtension type and the guard around it |
This library |
| The extensions themselves, their tests and their registry | @segmentify/integration |
Basket and favourite adapters, behind addToBasket() and toggleFavorite() |
@segmentify/integration |
Because the guard is in the widget, it holds wherever the extension comes from. An adapter has no such guard: it is ordinary integration code and is reviewed and tested there.
The Account’s Product Card
Section titled “The Account’s Product Card”The card described above is the library’s own. It is the default. An account whose cards must look like the cards of its own site defines one product card, as code in its integration repository, and the runtime hands it over through getProductCard(). Every widget that draws product cards then uses it.
The widget stays the container. Placement, layout, breakpoints, arrows, pagination, the impression, widget-view, teardown and every event are the widget’s. The card only draws.
interface ProductCard { styles?: string; render(input: ProductCardInput): HTMLElement | undefined;}
interface ProductCardInput { product: Product; // frozen copy form: 'standard' | 'compact'; // compact in the list and compact layouts context: WidgetContext; // frozen copy labels: WidgetLabels; // for the context language badges: string[]; // resolved badge texts of this product, not capped fields: CardField[]; // card.fields of the config document: Document; parts: { createLink(): HTMLAnchorElement; basketButton?: HTMLButtonElement; favoriteButton?: HTMLButtonElement; };}// in the account's integration codeexport const productCard: ProductCard = { styles: `.acme-card { background: var(--sgf-card-background); }`, render: ({ product, parts, document }) => { const root = document.createElement('article'); root.className = 'acme-card'; const link = parts.createLink(); link.textContent = product.name; root.append(link); if (parts.basketButton) root.append(parts.basketButton); return root; },};Badges belong to the card, so an account card draws them itself. badges holds the texts the library card would draw for this product, already resolved: the badges of the card in the context language, then the product’s own. The account card decides where they stand and how many it shows.
Events Stay in the Widget
Section titled “Events Stay in the Widget”A card never sends an event and never calls the basket or favourite adapter. It receives the parts that do, already wired, and decides where they stand and how they look.
| Part | What the widget already did |
|---|---|
parts.createLink() |
A new link each call: it leads to the product, opens a new tab when card.openInNewTab is set, and sends click. A card must place at least one. |
parts.basketButton |
Sends click, then calls addToBasket(); disabled while the answer is pending; reports BASKET_FAILED. Its text is the label. Missing when the config or the runtime turns add to basket off. |
parts.favoriteButton |
Calls toggleFavorite() and keeps aria-pressed up to date; reports FAVORITE_FAILED. It has an accessible name but no text or icon: the card’s styles must draw it, for example from aria-pressed. Missing when the config or the runtime turns favourites off. |
Fallback to the Library Card
Section titled “Fallback to the Library Card”| What happens | What the widget draws | Reported |
|---|---|---|
| The runtime has no product card | The library card | nothing |
render returns undefined for a product |
The library card for that product, the account card for the others | nothing |
render throws |
The library card for every product | PRODUCT_CARD_FAILED, once |
render returns something that is not a new element (a text, an element already on the page, the same element twice) |
The library card for every product | PRODUCT_CARD_FAILED, once |
The returned element holds no link from parts.createLink() |
The library card for every product | PRODUCT_CARD_FAILED, once |
The returned element holds a script, iframe, object or embed, an inline event handler (on… attribute) or a javascript: address |
The library card for every product | PRODUCT_CARD_FAILED, once |
styles is not a text, or getProductCard() throws |
The library card for every product | PRODUCT_CARD_FAILED, once |
A failure never keeps the widget off the page, and the events of the library card work as always.
Styles
Section titled “Styles”stylesis added once, inside the widget’s shadow root, after the library’s styles. It reaches nothing outside the widget, and the site’s styles reach nothing inside.- The library’s card styles do not apply to an account card: its wrapper is
data-card="custom"and its parts are nameddata-part="product-link","basket"and"favorite"with adata-product-id, not thedata-targetnames the library card uses. - The theme tokens are there as the
--sgf-*variables, so an account card can follow the account theme and a campaign theme. - The layout still sizes the card: the wrapper is the slider, grid or list item.
What Is Not Guarded
Section titled “What Is Not Guarded”An extension cannot put anything on the page; an account card can. It builds elements itself. The widget refuses what can run code (see the table above), but it cannot check the texts, links and images a card draws, and it looks at the card once, when it is drawn: a card that changes its elements later is not checked again. Those are guarded where the card lives: pull request review, tests and the same lint rules in the integration repository (no HTML strings, no dynamic code). The product it receives is the validated one.
A button may stand inside the link: a tap on it sends one click and does not open the product.
There are no account cards on mobile. A mobile renderer draws its own default card.
| Part | Lives in |
|---|---|
The ProductCard type, the parts with an event and the fallback |
This library |
| The account’s card, its styles and its tests | @segmentify/integration |
Not Yet Implemented
Section titled “Not Yet Implemented”- Loading from
@segmentify/integration, including the registry of account product cards.
Next Steps
Section titled “Next Steps”- Events and Display Rules lists what the widget sends.
- Testing shows how the layout is checked in a real browser.