@recapi/client 0.18.0 → 0.33.0

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,9 +135,15 @@ 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'
146
+ | 'viewed_earlier'
135
147
  | (string & {});
136
148
 
137
149
  /** The object stored with the item (`PUT /v1/items`, `metadata`): name, picture, link, price... */
@@ -179,9 +191,12 @@ export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
179
191
  /** `row()`'s only options: a site that wants another look draws `recommend()`'s list itself. */
180
192
  export interface RowOptions {
181
193
  placement?: string;
194
+ /** Without this key, the page's product (README "The page's product"); `''` is no context. */
182
195
  contextItemId?: string;
183
196
  /** Printed over the row; under the `bought_together` placement only over a product bought with this one. */
184
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;
185
200
  }
186
201
 
187
202
  export interface RecapiClient {
@@ -189,7 +204,9 @@ export interface RecapiClient {
189
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
190
205
  * (three letters, any case); a currency needs a value. An invalid pair throws `RecapiError('invalid_request')`, as a bad level does.
191
206
  */
192
- 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;
193
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. */
194
211
  recommend(params?: RecommendParams): Promise<RecommendResult>;
195
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.0",
3
+ "version": "0.33.0",
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 ADDED
@@ -0,0 +1,253 @@
1
+ /**
2
+ * The rules of every recommendation row, recapi.row()'s and the shop
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
+ *
6
+ * @module cards
7
+ */
8
+
9
+ import { REC_ID } from './client.js';
10
+
11
+ /** recapi counts every item of a list as shown: a spare could be credited a view it never caused. */
12
+ export const ROW = 4;
13
+
14
+ // :where() weighs nothing: any rule of the site's restyles the cards. Two
15
+ // across where four would be narrower than 150px (a phone).
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
+
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 at least, a short one too: a row's cards are as
24
+ * tall whatever their names, their prices line up, and the blank cards held
25
+ * while the list loads are as tall as the real ones (most names wrap on a
26
+ * phone). A browser without the `lh` unit draws names at their own height.
27
+ */
28
+ export const nameStyle = (scope) => `:where(${scope} a>span:first-of-type){min-height:2lh}`;
29
+
30
+ export const cardStyle = (scope) => `:where(${scope} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}${nameStyle(scope)}` +
31
+ `:where(${scope} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
32
+ `:where(${scope} .recapi-price){font-weight:600}${wasStyle(scope)}`;
33
+
34
+ // A shop's list lays its cards out as its slot does, whose rules a theme or an
35
+ // older module may have set. Real boxes: Safari announces no list under
36
+ // display:contents. The resets outweigh a theme's rules for every list
37
+ // (`.content ul`), and give way to one naming the slot.
38
+ 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}` +
39
+ `:where(${slot})>ul[role][role][role],:where(${slot})>ul[role][role][role]>li{list-style:none;margin:0;padding:0}`;
40
+
41
+ /**
42
+ * A constructed sheet passes a site's `style-src 'self'` CSP, which refuses a
43
+ * <style> element; browsers before Safari 16.4 get the element.
44
+ */
45
+ export function addStyle(css) {
46
+ try {
47
+ const sheet = new CSSStyleSheet();
48
+ sheet.replaceSync(css);
49
+ document.adoptedStyleSheets = [...document.adoptedStyleSheets, sheet];
50
+ } catch {
51
+ const el = document.createElement('style');
52
+ el.textContent = css;
53
+ document.head.append(el);
54
+ }
55
+ }
56
+
57
+ export const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
58
+
59
+ /** Only http(s): a `javascript:` link in metadata must never reach the page. */
60
+ export function web(address) {
61
+ if (typeof address !== 'string') return null;
62
+ try {
63
+ const url = new URL(address, location.href);
64
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
65
+ } catch {
66
+ return null;
67
+ }
68
+ }
69
+
70
+ /** The API's reason code of the list's first card, a product the visitor opened earlier. */
71
+ const EARLIER = 'viewed_earlier';
72
+
73
+ // In the page's language, as the site's own words around it: no site has to
74
+ // translate it. English where we have none.
75
+ const inLanguage = (words, english) => words[document.documentElement?.lang?.slice(0, 2).toLowerCase()] ?? english;
76
+ 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' };
77
+
78
+ /** Says why a card the visitor knows is there; a <small>, so no theme needs a rule for it. */
79
+ const mark = (why) => (why === EARLIER
80
+ ? `<small class="recapi-seen">${inLanguage(LOOKED, 'You looked at this')}</small>`
81
+ : '');
82
+
83
+ // Read before the old price: a screen reader says no strikethrough.
84
+ const WAS = { fr: 'Avant', de: 'Vorher', es: 'Antes', it: 'Prima', nl: 'Was', pt: 'Antes' };
85
+
86
+ /**
87
+ * The price a sale cut, formatted as the price is (`money`, never one
88
+ * converted and one not): only the shop's own `list_price` above its `price`,
89
+ * both numbers. recapi computes no reduction.
90
+ */
91
+ export const wasOf = (metadata, money) => (typeof metadata?.list_price === 'number' && typeof metadata.price === 'number'
92
+ && Number.isFinite(metadata.list_price) && metadata.list_price > metadata.price ? money(metadata.list_price) : null);
93
+
94
+ export const hasEarlier = (cards) => cards.some(({ why }) => why === EARLIER);
95
+
96
+ /**
97
+ * What a Recently viewed row is drawn from: the products opened, newest
98
+ * last, and every product's strongest level (a purchase takes it off). The
99
+ * ages and weights move with the clock alone.
100
+ */
101
+ export const openedOf = (recapi) => {
102
+ const { history, recent } = recapi.getHistory();
103
+ return JSON.stringify([recent, history.map(([item, , , level]) => `${level ?? 0} ${item}`).sort()]);
104
+ };
105
+
106
+ /**
107
+ * Whether a Recently viewed row can have a card: a browser key's list reads
108
+ * no stored history, so with no product opened and unbought in this
109
+ * browser's, but the one on screen, it is another row's list under a false
110
+ * title, hidden, and the call would be billed for nothing.
111
+ */
112
+ export const opened = (recapi, contextItemId) => {
113
+ const { history, rejected } = recapi.getHistory();
114
+ return history.some(([item, , , level]) => level > 0 && level < 10 && item !== contextItemId && !rejected.includes(item));
115
+ };
116
+
117
+ /** A row's cards with the earlier-opened one first: a top-up that replaced a sold-out one brought it last. */
118
+ export const earlierFirst = (cards) => [...cards.filter(({ why }) => why === EARLIER), ...cards.filter(({ why }) => why !== EARLIER)];
119
+
120
+ /** An empty address draws a broken image, and may ask for the open page again. */
121
+ export const drawable = (picture) => typeof picture === 'string' && picture.trim() !== '';
122
+
123
+ /** The address of a metadata's picture, or undefined. */
124
+ export const pictureOf = (metadata) => (drawable(metadata?.picture) ? web(metadata.picture)?.href : undefined);
125
+
126
+ /** One line, so a reduced card is as tall as the others. */
127
+ 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>`;
128
+
129
+ // A light tint of the text's own grey on any background: a blank card reads
130
+ // as a card to come on a light theme and a dark one.
131
+ const TINT = '#7f7f7f1f';
132
+
133
+ /**
134
+ * A blank card's look, as tall as a card of `card()`: a square, the name's
135
+ * two lines and the price's line, in the site's own line height. Lines are
136
+ * text (a no-break space), so no theme's `:empty` rule hides them.
137
+ */
138
+ export const blankStyle = (scope) => `:where(${scope} .recapi-blank>li>span){display:flex;flex-direction:column;gap:.25rem}` +
139
+ `:where(${scope} .recapi-blank i){display:block;aspect-ratio:1;background:${TINT}}` +
140
+ `:where(${scope} .recapi-blank b){font-weight:inherit;background:linear-gradient(${TINT},${TINT}) 0 .25em/80% .75em no-repeat}` +
141
+ `:where(${scope} .recapi-blank b:first-of-type){min-height:2lh}:where(${scope} .recapi-blank b+b){background-size:40% .75em}`;
142
+
143
+ /**
144
+ * What a row holds while its list loads: blank cards in the row's own grid,
145
+ * where its cards will be, so nothing under the row moves when they arrive,
146
+ * whatever the width. Screen readers skip them: there is nothing to read yet.
147
+ */
148
+ 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>`;
149
+
150
+ /** A blank card's look in a held row of `heldRow()`, laid out by `grid`. */
151
+ export const heldStyle = (grid) => `:where(.recapi-held-cards){${grid}}${listStyle('.recapi-held-cards')}${blankStyle('.recapi-held-cards')}`;
152
+
153
+ /**
154
+ * The place of a row the script adds under the slot once it has cards (bought
155
+ * together, Recently viewed): its title's and its cards', blank. `classes`
156
+ * are the real row's, so a theme's rules for it apply to its place too.
157
+ * `titled` false: a row the shop gave no title holds no title line.
158
+ */
159
+ 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>`;
160
+
161
+ /**
162
+ * A blank line in place of a held title the row turned out not to have
163
+ * (bought together without a real pair): the line closing as the cards
164
+ * arrive would move the page under them.
165
+ */
166
+ export const untitled = () => `<div class="recapi-untitled" aria-hidden="true">${title('\u00a0')}</div>`;
167
+
168
+ /** Removes every held row's place, once the rows are drawn or hidden. */
169
+ export const unheld = () => document.querySelectorAll('.recapi-held').forEach((el) => el.remove());
170
+
171
+ /** Every row's card; `named` is recapi.row()'s class on the name, `why` the item's reason code, `was` the old price. */
172
+ 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">` : ''}` +
173
+ `<span${named}>${escape(name)}</span>${price == null ? '' : priced(price, was)}${mark(why)}</a>`;
174
+
175
+ /** A row's title, in the site's own h2 style; none without text. */
176
+ export const title = (text, id) => (text ? `<h2 class="recapi-heading"${id ? ` id="${escape(id)}"` : ''}>${escape(text)}</h2>` : '');
177
+
178
+ // What a screen reader calls a row whose page shows no heading.
179
+ const ROW_NAME = { fr: 'Recommandations', de: 'Empfehlungen', es: 'Recomendaciones', it: 'Consigliati', nl: 'Aanbevelingen', pt: 'Recomendações' };
180
+
181
+ // A sold-out product's row, whose cards can all be bought. The WooCommerce
182
+ // plugin and the Magento module print the same words.
183
+ 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' };
184
+ export const inStock = () => inLanguage(IN_STOCK, 'Other products in stock');
185
+ const RECENT = { fr: 'Vus récemment', de: 'Zuletzt angesehen', es: 'Vistos recientemente', it: 'Visti di recente', nl: 'Recent bekeken', pt: 'Vistos recentemente' };
186
+ /** The home page's second row's title: its products are those the visitor opened. */
187
+ export const recentlyViewed = () => inLanguage(RECENT, 'Recently viewed');
188
+
189
+ /** A row's name, as an attribute: the heading with this id, else these words. */
190
+ export const nameOf = (headingId, words) => (headingId ? ['aria-labelledby', headingId] : ['aria-label', words || inLanguage(ROW_NAME, 'Recommendations')]);
191
+
192
+ export const nameAttribute = ([attribute, value]) => ` ${attribute}="${escape(value)}"`;
193
+
194
+ /** The id of a heading on the page, given one when it has none. */
195
+ export function idOf(heading, id) {
196
+ if (!heading) return null;
197
+ heading.id ||= id;
198
+ return heading.id;
199
+ }
200
+
201
+ /** The id of the heading a site wrote right above its slot; not the `-title` a row gives its own. */
202
+ export function headingAbove(slot) {
203
+ const above = slot.previousElementSibling;
204
+ return /^H[1-6]$/i.test(above?.tagName) && above.textContent.trim() ? idOf(above, `${slot.id}-above`) : null;
205
+ }
206
+
207
+ /** The element a screen reader lists as the row; a role of the site's own stays. */
208
+ export function region(el, [attribute, value]) {
209
+ if (!el.getAttribute('role')) el.setAttribute('role', 'region');
210
+ el.setAttribute(attribute, value);
211
+ }
212
+
213
+ /** The role is spelled out: Safari announces no list that shows no bullets. */
214
+ export const listOf = (cards, name) => `<ul role="list"${nameAttribute(name)}>${cards.map(({ html }) => `<li>${html}</li>`).join('')}</ul>`;
215
+
216
+ export const cardLink = (metadata) => (metadata?.available !== false && typeof metadata?.name === 'string' ? web(metadata.url) : null);
217
+
218
+ /**
219
+ * The list's id in the fragment, which no server or crawler sees, unless the
220
+ * address has its own (not ours to overwrite), it is the page already open (a
221
+ * fragment wouldn't load it, so no view), or the page wouldn't read it back.
222
+ */
223
+ export function carry(url, recommendationId) {
224
+ if (!recommendationId) return url;
225
+ const open = url.href.split('#')[0] === location.href.split('#')[0];
226
+ if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
227
+ else url.hash = recommendationId;
228
+ return url;
229
+ }
230
+
231
+ /** The bought-together title only over a real pair: similar products under it would be true cards under a false title. */
232
+ export const paired = (cards) => cards.some(({ why }) => why === 'bought_together');
233
+
234
+ /** Not only [hidden]: any display rule of the site's beats that one. */
235
+ export function hide(el) {
236
+ el.hidden = true;
237
+ el.style.setProperty('display', 'none', 'important');
238
+ }
239
+
240
+ /**
241
+ * `then` once any element comes within 400px of the screen: each list is
242
+ * billed and counted as shown, and a visitor who never scrolls down saw none.
243
+ */
244
+ export function near(elements, then) {
245
+ if (typeof IntersectionObserver !== 'function') return then();
246
+ const observer = new IntersectionObserver((entries) => {
247
+ if (!entries.some((entry) => entry.isIntersecting)) return undefined;
248
+ observer.disconnect();
249
+ return then();
250
+ }, { rootMargin: '0px 0px 400px 0px' });
251
+ for (const el of elements) observer.observe(el);
252
+ return undefined;
253
+ }