@recapi/client 0.18.1 → 0.33.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -92,6 +92,12 @@ export interface ClientOptions {
92
92
  historyConfig?: Partial<HistoryConfig>;
93
93
  /** Initial storage consent, default `false`: nothing is stored until `true` or `setConsent(true)`. */
94
94
  consent?: boolean;
95
+ /**
96
+ * Default `true`: in a browser, a product's first view sends the name and
97
+ * category the page gives search engines, for similar products by name
98
+ * on a site that sent no catalog. `false` sends only the view.
99
+ */
100
+ describePages?: boolean;
95
101
  /**
96
102
  * Default `true`: when Do Not Track / Global Privacy Control is on, store
97
103
  * nothing, send no events and no visitor ids; recommendations still work.
@@ -129,6 +135,11 @@ export interface RecommendListsParams {
129
135
  allowRepeats?: boolean;
130
136
  }
131
137
 
138
+ /** A home page's second row, the visitor's opened and unbought products: ask it after the first row. */
139
+ export const RECENTLY_VIEWED: 'recently_viewed';
140
+ /** A product page's second row, what shoppers carted or bought with the product on screen. */
141
+ export const BOUGHT_TOGETHER: 'bought_together';
142
+
132
143
  /** An item's reason code: map the ones you want to your own label, show none for an unknown one. */
133
144
  export type ReasonCode =
134
145
  | 'for_you' | 'similar' | 'next' | 'bought_together' | 'trending' | 'popular' | 'new' | 'explore' | 'more'
@@ -180,9 +191,12 @@ export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
180
191
  /** `row()`'s only options: a site that wants another look draws `recommend()`'s list itself. */
181
192
  export interface RowOptions {
182
193
  placement?: string;
194
+ /** Without this key, the page's product (README "The page's product"); `''` is no context. */
183
195
  contextItemId?: string;
184
196
  /** Printed over the row; under the `bought_together` placement only over a product bought with this one. */
185
197
  heading?: string;
198
+ /** `false`: a product page missing the slot gets no row placed by itself (README "The page's product"). */
199
+ place?: boolean;
186
200
  }
187
201
 
188
202
  export interface RecapiClient {
@@ -190,7 +204,9 @@ export interface RecapiClient {
190
204
  * `value` is what the buyer paid for a purchase's line (a number of at least 0; 0 is a free line), `currency` its ISO 4217 code
191
205
  * (three letters, any case); a currency needs a value. An invalid pair throws `RecapiError('invalid_request')`, as a bad level does.
192
206
  */
193
- track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string }): void;
207
+ track(itemId: string, level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string; send?: boolean }): void;
208
+ /** The page's product, by its address (README "The page's product"): no product markup, nothing is sent. */
209
+ track(level: number | LevelName, options?: { recommendationId?: string | null; value?: number; currency?: string; send?: boolean }): void;
194
210
  /** Falls back to popular items on a network error, a timeout, a 5xx or a 429 (an empty list if those fail too), to an empty list on a 401 or 403; rejects on a bad request or a reply that isn't the API's. */
195
211
  recommend(params?: RecommendParams): Promise<RecommendResult>;
196
212
  /** Several lists in one call, billed as one recommendation; falls back as `recommend()` does, list by list. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@recapi/client",
3
- "version": "0.18.1",
3
+ "version": "0.33.1",
4
4
  "description": "Browser and Node client for the recapi recommendation API: local decayed history, event batching, attribution.",
5
5
  "homepage": "https://recapi.io/docs",
6
6
  "bugs": {
package/src/cards.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * The rules of every recommendation row, recapi.row()'s and the shop
3
- * platforms': changed here once. Each row keeps its own markup, which shops
4
- * have styled.
3
+ * platforms': changed here once. Each row keeps its own frame around the
4
+ * cards (list, slot, title's place), which shops have styled.
5
5
  *
6
6
  * @module cards
7
7
  */
@@ -15,9 +15,45 @@ export const ROW = 4;
15
15
  // across where four would be narrower than 150px (a phone).
16
16
  export const GRID = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start';
17
17
 
18
- export const cardStyle = (scope) => `:where(${scope} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
18
+ /** A sale's old price beside the price, and the word only screen readers see before it. */
19
+ export const wasStyle = (scope) => `:where(${scope} .recapi-was){font-weight:400}` +
20
+ `:where(${scope} .recapi-unseen){position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}`;
21
+
22
+ /**
23
+ * A name takes two lines, a short one too, a long one cut with an ellipsis:
24
+ * a row's cards are as tall whatever their names, their prices line up, and
25
+ * the blank cards held while the list loads are as tall as the real ones
26
+ * (most names wrap on a phone; a third line moved the page 27 px as the row
27
+ * came). A browser without the `lh` unit draws short names at their height.
28
+ */
29
+ export const nameStyle = (scope) => `:where(${scope} a>span:first-of-type){min-height:2lh;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:2;overflow:hidden}`;
30
+
31
+ export const cardStyle = (scope) => `:where(${scope} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}${nameStyle(scope)}` +
19
32
  `:where(${scope} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
20
- `:where(${scope} .recapi-price){font-weight:600}`;
33
+ `:where(${scope} .recapi-price){font-weight:600}${wasStyle(scope)}`;
34
+
35
+ // A shop's list lays its cards out as its slot does, whose rules a theme or an
36
+ // older module may have set. Real boxes: Safari announces no list under
37
+ // display:contents. The resets outweigh a theme's rules for every list
38
+ // (`.content ul`), and give way to one naming the slot.
39
+ export const listStyle = (slot) => `:where(${slot}>ul){grid-column:1/-1;flex:1 1 100%;justify-self:stretch;min-width:0;display:inherit;grid:inherit;flex-flow:inherit;gap:inherit;place-content:inherit;place-items:inherit}` +
40
+ `:where(${slot})>ul[role][role][role],:where(${slot})>ul[role][role][role]>li{list-style:none;margin:0;padding:0}`;
41
+
42
+ /**
43
+ * A constructed sheet passes a site's `style-src 'self'` CSP, which refuses a
44
+ * <style> element; browsers before Safari 16.4 get the element.
45
+ */
46
+ export function addStyle(css) {
47
+ try {
48
+ const sheet = new CSSStyleSheet();
49
+ sheet.replaceSync(css);
50
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
51
+ } catch {
52
+ const el = document.createElement('style');
53
+ el.textContent = css;
54
+ document.head.append(el);
55
+ }
56
+ }
21
57
 
22
58
  export const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
23
59
 
@@ -32,6 +68,152 @@ export function web(address) {
32
68
  }
33
69
  }
34
70
 
71
+ /** The API's reason code of the list's first card, a product the visitor opened earlier. */
72
+ const EARLIER = 'viewed_earlier';
73
+
74
+ // In the page's language, as the site's own words around it: no site has to
75
+ // translate it. English where we have none.
76
+ const inLanguage = (words, english) => words[document.documentElement?.lang?.slice(0, 2).toLowerCase()] ?? english;
77
+ const LOOKED = { fr: 'Vous l’avez déjà vu', de: 'Schon angesehen', es: 'Ya lo has visto', it: 'L’hai già visto', nl: 'Eerder bekeken', pt: 'Já viu este' };
78
+
79
+ /** Says why a card the visitor knows is there; a <small>, so no theme needs a rule for it. */
80
+ const mark = (why) => (why === EARLIER
81
+ ? `<small class="recapi-seen">${inLanguage(LOOKED, 'You looked at this')}</small>`
82
+ : '');
83
+
84
+ // Read before the old price: a screen reader says no strikethrough.
85
+ const WAS = { fr: 'Avant', de: 'Vorher', es: 'Antes', it: 'Prima', nl: 'Was', pt: 'Antes' };
86
+
87
+ /**
88
+ * The price a sale cut, formatted as the price is (`money`, never one
89
+ * converted and one not): only the shop's own `list_price` above its `price`,
90
+ * both numbers. recapi computes no reduction.
91
+ */
92
+ export const wasOf = (metadata, money) => (typeof metadata?.list_price === 'number' && typeof metadata.price === 'number'
93
+ && Number.isFinite(metadata.list_price) && metadata.list_price > metadata.price ? money(metadata.list_price) : null);
94
+
95
+ export const hasEarlier = (cards) => cards.some(({ why }) => why === EARLIER);
96
+
97
+ /**
98
+ * What a Recently viewed row is drawn from: the products opened, newest
99
+ * last, and every product's strongest level (a purchase takes it off). The
100
+ * ages and weights move with the clock alone.
101
+ */
102
+ export const openedOf = (recapi) => {
103
+ const { history, recent } = recapi.getHistory();
104
+ return JSON.stringify([recent, history.map(([item, , , level]) => `${level ?? 0} ${item}`).sort()]);
105
+ };
106
+
107
+ /**
108
+ * Whether a Recently viewed row can have a card: a browser key's list reads
109
+ * no stored history, so with no product opened and unbought in this
110
+ * browser's, but the one on screen, it is another row's list under a false
111
+ * title, hidden, and the call would be billed for nothing.
112
+ */
113
+ export const opened = (recapi, contextItemId) => {
114
+ const { history, rejected } = recapi.getHistory();
115
+ return history.some(([item, , , level]) => level > 0 && level < 10 && item !== contextItemId && !rejected.includes(item));
116
+ };
117
+
118
+ /** A row's cards with the earlier-opened one first: a top-up that replaced a sold-out one brought it last. */
119
+ export const earlierFirst = (cards) => [...cards.filter(({ why }) => why === EARLIER), ...cards.filter(({ why }) => why !== EARLIER)];
120
+
121
+ /** An empty address draws a broken image, and may ask for the open page again. */
122
+ export const drawable = (picture) => typeof picture === 'string' && picture.trim() !== '';
123
+
124
+ /** The address of a metadata's picture, or undefined. */
125
+ export const pictureOf = (metadata) => (drawable(metadata?.picture) ? web(metadata.picture)?.href : undefined);
126
+
127
+ /** One line, so a reduced card is as tall as the others. */
128
+ const priced = (price, was) => `<span class="recapi-price">${was ? `<s class="recapi-was"><span class="recapi-unseen">${inLanguage(WAS, 'Was')} </span>${escape(was)}</s> ` : ''}${escape(price)}</span>`;
129
+
130
+ // A light tint of the text's own grey on any background: a blank card reads
131
+ // as a card to come on a light theme and a dark one.
132
+ const TINT = '#7f7f7f1f';
133
+
134
+ /**
135
+ * A blank card's look, as tall as a card of `card()`: a square, the name's
136
+ * two lines and the price's line, in the site's own line height. Lines are
137
+ * text (a no-break space), so no theme's `:empty` rule hides them.
138
+ */
139
+ export const blankStyle = (scope) => `:where(${scope} .recapi-blank>li>span){display:flex;flex-direction:column;gap:.25rem}` +
140
+ `:where(${scope} .recapi-blank i){display:block;aspect-ratio:1;background:${TINT}}` +
141
+ `:where(${scope} .recapi-blank b){font-weight:inherit;background:linear-gradient(${TINT},${TINT}) 0 .25em/80% .75em no-repeat}` +
142
+ `:where(${scope} .recapi-blank b:first-of-type){min-height:2lh}:where(${scope} .recapi-blank b+b){background-size:40% .75em}`;
143
+
144
+ /**
145
+ * What a row holds while its list loads: blank cards in the row's own grid,
146
+ * where its cards will be, so nothing under the row moves when they arrive,
147
+ * whatever the width. Screen readers skip them: there is nothing to read yet.
148
+ */
149
+ export const blanks = () => `<ul role="list" class="recapi-blank" aria-hidden="true">${'<li><span><i></i><b>\u00a0</b><b>\u00a0</b></span></li>'.repeat(ROW)}</ul>`;
150
+
151
+ /** A blank card's look in a held row of `heldRow()`, laid out by `grid`. */
152
+ export const heldStyle = (grid) => `:where(.recapi-held-cards){${grid}}${listStyle('.recapi-held-cards')}${blankStyle('.recapi-held-cards')}`;
153
+
154
+ /**
155
+ * The place of a row the script adds under the slot once it has cards (bought
156
+ * together, Recently viewed): its title's and its cards', blank. `classes`
157
+ * are the real row's, so a theme's rules for it apply to its place too.
158
+ * `titled` false: a row the shop gave no title holds no title line.
159
+ */
160
+ export const heldRow = (classes = '', titled = true) => `<div class="recapi-held${classes ? ` ${classes}` : ''}" aria-hidden="true">${titled ? title('\u00a0') : ''}<div class="recapi-held-cards">${blanks()}</div></div>`;
161
+
162
+ /**
163
+ * A blank line in place of a held title the row turned out not to have
164
+ * (bought together without a real pair): the line closing as the cards
165
+ * arrive would move the page under them.
166
+ */
167
+ export const untitled = () => `<div class="recapi-untitled" aria-hidden="true">${title('\u00a0')}</div>`;
168
+
169
+ /** Removes every held row's place, once the rows are drawn or hidden. */
170
+ export const unheld = () => document.querySelectorAll('.recapi-held').forEach((el) => el.remove());
171
+
172
+ /** Every row's card; `named` is recapi.row()'s class on the name, `why` the item's reason code, `was` the old price. */
173
+ export const card = (href, picture, name, price, named = '', why = undefined, was = null) => `<a href="${escape(href)}">${drawable(picture) ? `<img src="${escape(picture)}" alt="" loading="lazy">` : ''}` +
174
+ `<span${named}>${escape(name)}</span>${price == null ? '' : priced(price, was)}${mark(why)}</a>`;
175
+
176
+ /** A row's title, in the site's own h2 style; none without text. */
177
+ export const title = (text, id) => (text ? `<h2 class="recapi-heading"${id ? ` id="${escape(id)}"` : ''}>${escape(text)}</h2>` : '');
178
+
179
+ // What a screen reader calls a row whose page shows no heading.
180
+ const ROW_NAME = { fr: 'Recommandations', de: 'Empfehlungen', es: 'Recomendaciones', it: 'Consigliati', nl: 'Aanbevelingen', pt: 'Recomendações' };
181
+
182
+ // A sold-out product's row, whose cards can all be bought. The WooCommerce
183
+ // plugin and the Magento module print the same words.
184
+ const IN_STOCK = { fr: 'Autres produits en stock', de: 'Weitere Produkte auf Lager', es: 'Otros productos disponibles', it: 'Altri prodotti disponibili', nl: 'Andere producten op voorraad', pt: 'Outros produtos disponíveis' };
185
+ export const inStock = () => inLanguage(IN_STOCK, 'Other products in stock');
186
+ const RECENT = { fr: 'Vus récemment', de: 'Zuletzt angesehen', es: 'Vistos recientemente', it: 'Visti di recente', nl: 'Recent bekeken', pt: 'Vistos recentemente' };
187
+ /** The home page's second row's title: its products are those the visitor opened. */
188
+ export const recentlyViewed = () => inLanguage(RECENT, 'Recently viewed');
189
+
190
+ /** A row's name, as an attribute: the heading with this id, else these words. */
191
+ export const nameOf = (headingId, words) => (headingId ? ['aria-labelledby', headingId] : ['aria-label', words || inLanguage(ROW_NAME, 'Recommendations')]);
192
+
193
+ export const nameAttribute = ([attribute, value]) => ` ${attribute}="${escape(value)}"`;
194
+
195
+ /** The id of a heading on the page, given one when it has none. */
196
+ export function idOf(heading, id) {
197
+ if (!heading) return null;
198
+ heading.id ||= id;
199
+ return heading.id;
200
+ }
201
+
202
+ /** The id of the heading a site wrote right above its slot; not the `-title` a row gives its own. */
203
+ export function headingAbove(slot) {
204
+ const above = slot.previousElementSibling;
205
+ return /^H[1-6]$/i.test(above?.tagName) && above.textContent.trim() ? idOf(above, `${slot.id}-above`) : null;
206
+ }
207
+
208
+ /** The element a screen reader lists as the row; a role of the site's own stays. */
209
+ export function region(el, [attribute, value]) {
210
+ if (!el.getAttribute('role')) el.setAttribute('role', 'region');
211
+ el.setAttribute(attribute, value);
212
+ }
213
+
214
+ /** The role is spelled out: Safari announces no list that shows no bullets. */
215
+ export const listOf = (cards, name) => `<ul role="list"${nameAttribute(name)}>${cards.map(({ html }) => `<li>${html}</li>`).join('')}</ul>`;
216
+
35
217
  export const cardLink = (metadata) => (metadata?.available !== false && typeof metadata?.name === 'string' ? web(metadata.url) : null);
36
218
 
37
219
  /**