@recapi/client 0.17.2 → 0.18.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/README.md +55 -36
- package/index.d.ts +13 -0
- package/package.json +1 -1
- package/src/client.js +67 -3
- package/src/row.js +187 -0
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ are, gzipped, and browsers cache them:
|
|
|
35
35
|
|
|
36
36
|
```html
|
|
37
37
|
<script type="module">
|
|
38
|
-
import { createClient } from 'https://api.example.com/sdk/0.
|
|
38
|
+
import { createClient } from 'https://api.example.com/sdk/0.18.0/index.js';
|
|
39
39
|
|
|
40
40
|
const ITEM_ID = ''; // this page's product id
|
|
41
41
|
|
|
@@ -90,20 +90,18 @@ const recapi = createClient({
|
|
|
90
90
|
// itemId is that page's own id: an empty one sends nothing.
|
|
91
91
|
recapi.track(itemId, 'view');
|
|
92
92
|
|
|
93
|
-
//
|
|
94
|
-
//
|
|
95
|
-
//
|
|
96
|
-
//
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
}, { rootMargin: '0px 0px 400px 0px' });
|
|
106
|
-
observer.observe(slot);
|
|
93
|
+
// A row of 4 product cards in <div id="recommendations"></div>, drawn from
|
|
94
|
+
// each item's name, url, picture and price metadata once it nears the screen.
|
|
95
|
+
// It shows popular items if recapi is slow, failing or at your plan's limit,
|
|
96
|
+
// and hides when there is nothing to show. See row() below.
|
|
97
|
+
recapi.row('#recommendations', { contextItemId: itemId, heading: 'You may also like' });
|
|
98
|
+
|
|
99
|
+
// Or, instead of row(), your own look: recommend() gives the list. If recapi
|
|
100
|
+
// is slow, failing or at your plan's limit, it resolves with popular items,
|
|
101
|
+
// and with an empty list if those fail too or your key is refused (hide the
|
|
102
|
+
// slot): no try/catch needed. Call it only once the slot nears the screen
|
|
103
|
+
// (row() waits for you): each list is billed and counted as shown.
|
|
104
|
+
// const { items } = await recapi.recommend({ count: 8, tagsAny: ['sports'] });
|
|
107
105
|
|
|
108
106
|
// Later, the user clicks a recommended item and lands on its page (a
|
|
109
107
|
// view). No need to pass the recommendation id: the SDK remembers which
|
|
@@ -778,6 +776,8 @@ for (const item of items) {
|
|
|
778
776
|
a secret key: call the API from your backend for that.
|
|
779
777
|
- **`recommendLists({ lists, exclude, allowRepeats })`**: several rows in
|
|
780
778
|
one call, see [below](#several-rows-in-one-call).
|
|
779
|
+
- **`row(slot, { placement, contextItemId, heading })`**: a ready row, see
|
|
780
|
+
[The ready row](#the-ready-row).
|
|
781
781
|
- **`popular({ tagsAny, tagsAll, count })`** resolves to `{ items: [{ itemId, score, why, metadata }] }`.
|
|
782
782
|
A public key goes in `?key=`, so the response can be cached by a CDN.
|
|
783
783
|
[How the key is sent](#how-the-key-is-sent) gives the reason for the rest.
|
|
@@ -813,6 +813,31 @@ const [similar, more] = await recapi.recommendLists({
|
|
|
813
813
|
});
|
|
814
814
|
```
|
|
815
815
|
|
|
816
|
+
### The ready row
|
|
817
|
+
|
|
818
|
+
`row(slot, { placement, contextItemId, heading })` fills `slot` (an element
|
|
819
|
+
or a selector) with up to 4 cards, the shop rows' rules in one call:
|
|
820
|
+
|
|
821
|
+
- It holds the slot's height and asks only once the slot is within 400px
|
|
822
|
+
of the screen. Rows called together share one billed call, with no
|
|
823
|
+
product on two rows.
|
|
824
|
+
- A card needs the item's `name` and an http(s) `url` metadata; `picture`
|
|
825
|
+
and `price` show when present. A number price takes the item's `currency`,
|
|
826
|
+
else the page's `<meta property="product:price:currency">`. An item with
|
|
827
|
+
`available: false` is skipped.
|
|
828
|
+
- Each link carries its list's id, which the page it opens reads (see
|
|
829
|
+
[Consent](#consent-and-eprivacy)).
|
|
830
|
+
- The row hides when no card can be drawn; the console names the missing
|
|
831
|
+
keys. Under the `bought_together` placement, `heading` shows only over a
|
|
832
|
+
product bought with this one, and the row stays away when recapi answers
|
|
833
|
+
with popular items.
|
|
834
|
+
- Its styles weigh nothing (`:where`), so any rule of yours restyles it
|
|
835
|
+
(`.recapi-row ul`, `a`, `img`, `.recapi-heading`, `.recapi-name`,
|
|
836
|
+
`.recapi-price`), and pass a `style-src 'self'` CSP.
|
|
837
|
+
|
|
838
|
+
There are no other options: for another look, draw `recommend()`'s list.
|
|
839
|
+
The file (`row.js`) loads on the first call only.
|
|
840
|
+
|
|
816
841
|
### Errors and troubleshooting
|
|
817
842
|
|
|
818
843
|
Every failure is a `RecapiError` with `code`, `status` and `message`. The
|
|
@@ -1036,27 +1061,14 @@ A site that needs no banner (outside the EU, or with its own legal basis)
|
|
|
1036
1061
|
passes `consent: true`. Without consent, the SDK never reads or writes storage
|
|
1037
1062
|
and creates no anonymous id. The history and the attribution map live in memory for the
|
|
1038
1063
|
current page only. A single-page app keeps attribution. On a multi-page
|
|
1039
|
-
site, a
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
const { recommendationId, items } = await recapi.recommend({ count: 8 });
|
|
1048
|
-
// href = recommendationId ? `/p/${item.itemId}?rec=${recommendationId}` : `/p/${item.itemId}`
|
|
1049
|
-
|
|
1050
|
-
// On the item's page:
|
|
1051
|
-
const url = new URL(location.href);
|
|
1052
|
-
const rec = url.searchParams.get('rec');
|
|
1053
|
-
recapi.track('item-77', 'view', { recommendationId: rec }); // null: automatic attribution
|
|
1054
|
-
// Then drop it, so a copied or shared address doesn't credit strangers to that list.
|
|
1055
|
-
if (rec !== null) {
|
|
1056
|
-
url.searchParams.delete('rec');
|
|
1057
|
-
history.replaceState(history.state, '', url);
|
|
1058
|
-
}
|
|
1059
|
-
```
|
|
1064
|
+
site, a card's link carries its list's id: `row()` writes it, and the page
|
|
1065
|
+
it opens credits it with its first `track()` above level 0 that passes no
|
|
1066
|
+
`recommendationId`, then takes it out of the address so a shared link
|
|
1067
|
+
credits nobody. A list you draw yourself carries it the same way: end each
|
|
1068
|
+
link with `#${recommendationId}` (no fragment when it is null, a fallback).
|
|
1069
|
+
`?rec=<id>` is read too, for pages that need the id on the server. Either
|
|
1070
|
+
way only an id recapi makes (`rec_` and hex digits) is read: any other
|
|
1071
|
+
`#…` or `?rec=` value is the site's own and stays.
|
|
1060
1072
|
|
|
1061
1073
|
Events are still sent, without `anon_id`. Don't call `track()` if you
|
|
1062
1074
|
need no network at all. Withdrawing consent deletes the stored data.
|
|
@@ -1118,6 +1130,13 @@ minifier, to keep zero dev dependencies.
|
|
|
1118
1130
|
|
|
1119
1131
|
## Changes
|
|
1120
1132
|
|
|
1133
|
+
- 2026-11-24: version 0.18.0. `recapi.row(slot, { placement, contextItemId,
|
|
1134
|
+
heading })` draws a ready row of product cards from the items' metadata
|
|
1135
|
+
([The ready row](#the-ready-row)). `track()` above level 0 without a
|
|
1136
|
+
`recommendationId` key reads the id a card's link brought (`#rec_…` or
|
|
1137
|
+
`?rec=rec_…`, nothing else) and takes it out of the address, so a click is credited without
|
|
1138
|
+
consent.
|
|
1139
|
+
|
|
1121
1140
|
- 2026-11-24: version 0.17.2. `track()` with an empty item id (the
|
|
1122
1141
|
quick start's tag before its `ITEM_ID` is set) still sends nothing, and
|
|
1123
1142
|
its console line now says to set `ITEM_ID`.
|
package/index.d.ts
CHANGED
|
@@ -176,6 +176,14 @@ export interface PopularResult {
|
|
|
176
176
|
*/
|
|
177
177
|
export type LevelName = 'view' | 'cart' | 'purchase' | 'reject';
|
|
178
178
|
|
|
179
|
+
/** `row()`'s only options: a site that wants another look draws `recommend()`'s list itself. */
|
|
180
|
+
export interface RowOptions {
|
|
181
|
+
placement?: string;
|
|
182
|
+
contextItemId?: string;
|
|
183
|
+
/** Printed over the row; under the `bought_together` placement only over a product bought with this one. */
|
|
184
|
+
heading?: string;
|
|
185
|
+
}
|
|
186
|
+
|
|
179
187
|
export interface RecapiClient {
|
|
180
188
|
/**
|
|
181
189
|
* `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
|
|
@@ -197,6 +205,11 @@ export interface RecapiClient {
|
|
|
197
205
|
/** This device's anonymous id; null without consent or under Do Not Track. */
|
|
198
206
|
getAnonId(): string | null;
|
|
199
207
|
destroy(): Promise<void>;
|
|
208
|
+
/**
|
|
209
|
+
* Draws up to 4 cards from each item's `name`, `url`, `picture`, `price` and `currency` metadata into `slot` once it nears
|
|
210
|
+
* the screen, each link carrying its list's id. Rows asked for together share one call. Hides when no card can be drawn.
|
|
211
|
+
*/
|
|
212
|
+
row(slot: Element | string, options?: RowOptions): void;
|
|
200
213
|
}
|
|
201
214
|
|
|
202
215
|
export function createClient(options: ClientOptions): RecapiClient;
|
package/package.json
CHANGED
package/src/client.js
CHANGED
|
@@ -530,7 +530,8 @@ export function createClient(options) {
|
|
|
530
530
|
globalThis.document?.addEventListener?.('visibilitychange', onVisibility);
|
|
531
531
|
globalThis.window?.addEventListener?.('pagehide', flushOnHide);
|
|
532
532
|
|
|
533
|
-
|
|
533
|
+
let drawRow = null;
|
|
534
|
+
const client = {
|
|
534
535
|
/**
|
|
535
536
|
* Records an interaction: updates the local history immediately (so the
|
|
536
537
|
* next `recommend()` reflects it) and queues the event. Level 0 is an
|
|
@@ -551,12 +552,16 @@ export function createClient(options) {
|
|
|
551
552
|
* `value` is what the buyer paid for a purchase's line (0 for a free
|
|
552
553
|
* line), `currency` its ISO 4217 code (three letters, any case); a
|
|
553
554
|
* currency needs a value. An invalid pair throws, as a bad level does.
|
|
555
|
+
* Without a `recommendationId` key, an event above level 0 carries the
|
|
556
|
+
* id a card's link brought to the page (`#rec_…` or `?rec=`), which it
|
|
557
|
+
* takes out of the address.
|
|
554
558
|
*/
|
|
555
|
-
track(itemId, level,
|
|
559
|
+
track(itemId, level, options = {}) {
|
|
556
560
|
start();
|
|
561
|
+
const { value, currency } = options;
|
|
557
562
|
// A fallback list has a null id, and a page passing it on must not
|
|
558
563
|
// send `null` or lose the item's earlier, real attribution.
|
|
559
|
-
|
|
564
|
+
let recommendationId = options.recommendationId ?? undefined;
|
|
560
565
|
if (typeof level === 'string' && Object.hasOwn(LEVEL_NAMES, level)) level = LEVEL_NAMES[level];
|
|
561
566
|
if (!Number.isInteger(level) || level < -10 || level > 10) {
|
|
562
567
|
throw new RecapiError(
|
|
@@ -575,6 +580,10 @@ export function createClient(options) {
|
|
|
575
580
|
report(new RecapiError('invalid_request', rule), true);
|
|
576
581
|
return;
|
|
577
582
|
}
|
|
583
|
+
// The landing view: without consent nothing on the device remembers
|
|
584
|
+
// the list the visitor clicked, so the card's link carried its id. A
|
|
585
|
+
// page that passes the key reads the address itself (the shop rows).
|
|
586
|
+
if (level > 0 && !Object.hasOwn(options, 'recommendationId')) recommendationId = landed() ?? undefined;
|
|
578
587
|
if (quiet) return;
|
|
579
588
|
const t = now();
|
|
580
589
|
let attributed = recommendationId;
|
|
@@ -783,8 +792,63 @@ export function createClient(options) {
|
|
|
783
792
|
globalThis.document?.removeEventListener?.('visibilitychange', onVisibility);
|
|
784
793
|
globalThis.window?.removeEventListener?.('pagehide', flushOnHide);
|
|
785
794
|
return flush();
|
|
795
|
+
},
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Fills `slot` (an element or a selector) with a row of up to 4 product
|
|
799
|
+
* cards, drawn from each item's `name`, `url`, `picture`, `price` (and
|
|
800
|
+
* `currency`) metadata, once it comes within 400px of the screen. Each
|
|
801
|
+
* link carries its list's id. Rows asked for together share one call. The
|
|
802
|
+
* row hides when no card can be drawn; under the `bought_together`
|
|
803
|
+
* placement, `heading` shows only over a product bought with this one.
|
|
804
|
+
* Does nothing outside a browser.
|
|
805
|
+
*
|
|
806
|
+
* @param {Element | string} slot
|
|
807
|
+
* @param {{ placement?: string, contextItemId?: string, heading?: string }} [options]
|
|
808
|
+
*/
|
|
809
|
+
row(slot, options) {
|
|
810
|
+
if (typeof globalThis.document === 'undefined') return;
|
|
811
|
+
// Rows called in one task still reach the drawer in one task, in order.
|
|
812
|
+
drawRow ??= import('./row.js').then(({ rows }) => rows(client));
|
|
813
|
+
drawRow.then((draw) => draw(slot, options), (error) => globalThis.console?.warn('recapi: the row failed to load:', error));
|
|
786
814
|
}
|
|
787
815
|
};
|
|
816
|
+
return client;
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
/**
|
|
820
|
+
* The shape of an id the API makes (internal/ids: rec_ and hex), the only one
|
|
821
|
+
* read from an address: any other value is the site's own. Internal, shared
|
|
822
|
+
* with row.js; index.js doesn't export it.
|
|
823
|
+
*/
|
|
824
|
+
export const REC_ID = /^rec_[0-9a-f]+$/;
|
|
825
|
+
|
|
826
|
+
/**
|
|
827
|
+
* The recommendation id a card's link brought to this page, taken out of the
|
|
828
|
+
* address so a copied or shared link doesn't credit strangers' visits; null
|
|
829
|
+
* when there is none, or outside a browser. The fragment first (no server or
|
|
830
|
+
* page cache sees it), then `?rec=`; the address keeps everything else.
|
|
831
|
+
*/
|
|
832
|
+
function landed() {
|
|
833
|
+
const { location: here, history: past } = globalThis;
|
|
834
|
+
if (typeof here?.href !== 'string' || typeof past?.replaceState !== 'function') return null;
|
|
835
|
+
const url = new URL(here.href);
|
|
836
|
+
let rec = null;
|
|
837
|
+
if (REC_ID.test(url.hash.slice(1))) {
|
|
838
|
+
rec = url.hash.slice(1);
|
|
839
|
+
url.hash = '';
|
|
840
|
+
} else if (REC_ID.test(url.searchParams.get('rec') ?? '')) {
|
|
841
|
+
// ?rec=1 or ?rec=newest is the site's own parameter: it stays, and isn't sent.
|
|
842
|
+
rec = url.searchParams.get('rec');
|
|
843
|
+
// Not URLSearchParams.toString(): the site's other parameters keep their exact text.
|
|
844
|
+
const query = url.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
845
|
+
url.search = query;
|
|
846
|
+
}
|
|
847
|
+
if (rec === null) return null;
|
|
848
|
+
try {
|
|
849
|
+
past.replaceState(past.state, '', url.href.replace(/#$/, ''));
|
|
850
|
+
} catch {}
|
|
851
|
+
return rec;
|
|
788
852
|
}
|
|
789
853
|
|
|
790
854
|
/**
|
package/src/row.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The ready row of product cards (`recapi.row()`). The Shopify, WooCommerce
|
|
3
|
+
* and Magento rows follow the same rules; a site of any other kind gets them
|
|
4
|
+
* from one call instead of writing them. Loaded by the first `row()` call
|
|
5
|
+
* only: a site that draws its own list never downloads it. The page a card
|
|
6
|
+
* opens reads the link's id back with client.js's `landed()`.
|
|
7
|
+
*
|
|
8
|
+
* @module row
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { REC_ID } from './client.js';
|
|
12
|
+
|
|
13
|
+
/** A row shows 4 cards: recapi counts every item of a list as shown. */
|
|
14
|
+
const ROW = 4;
|
|
15
|
+
|
|
16
|
+
// :where() weighs nothing, so any rule of the site's restyles the cards. Four
|
|
17
|
+
// across, two where four would be narrower than 150px (a phone). The height
|
|
18
|
+
// is held while the list loads, so the page doesn't jump.
|
|
19
|
+
const CSS = ':where(.recapi-row[aria-busy=true]){min-height:20rem}' +
|
|
20
|
+
':where(.recapi-row ul){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;list-style:none;margin:0;padding:0}' +
|
|
21
|
+
':where(.recapi-row a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
|
|
22
|
+
':where(.recapi-row img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
|
|
23
|
+
':where(.recapi-row .recapi-price){font-weight:600}';
|
|
24
|
+
|
|
25
|
+
const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
26
|
+
|
|
27
|
+
/** Only http(s) addresses: a `javascript:` link in metadata must never reach the page. */
|
|
28
|
+
function web(address) {
|
|
29
|
+
if (typeof address !== 'string') return null;
|
|
30
|
+
try {
|
|
31
|
+
const url = new URL(address, location.href);
|
|
32
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
33
|
+
} catch {
|
|
34
|
+
return null;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* A card's link with its list's id: in the fragment, unless the address has
|
|
40
|
+
* its own (the site's, not ours to overwrite), it is the page already open (a
|
|
41
|
+
* fragment wouldn't load it, so no view), or the id isn't one `landed()` reads
|
|
42
|
+
* from a fragment.
|
|
43
|
+
*/
|
|
44
|
+
function carry(url, recommendationId) {
|
|
45
|
+
if (!recommendationId) return url;
|
|
46
|
+
const open = url.href.split('#')[0] === location.href.split('#')[0];
|
|
47
|
+
if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
|
|
48
|
+
else url.hash = recommendationId;
|
|
49
|
+
return url;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** The page's currency, as shops print it for search engines. */
|
|
53
|
+
function pageCurrency() {
|
|
54
|
+
const tag = document.querySelector('meta[property="product:price:currency"],meta[property="og:price:currency"],meta[itemprop="priceCurrency"]');
|
|
55
|
+
return tag?.getAttribute('content') || null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The client's `row()`: rows asked for in the same task share one call
|
|
60
|
+
* (billed as one, no product on two rows), made once any of them comes
|
|
61
|
+
* within 400px of the screen. State lives here, per client, never at module
|
|
62
|
+
* level: two copies of this file may load side by side.
|
|
63
|
+
*
|
|
64
|
+
* @param {{ recommendLists: Function }} client
|
|
65
|
+
*/
|
|
66
|
+
export function rows(client) {
|
|
67
|
+
let group = null;
|
|
68
|
+
let sheet = false;
|
|
69
|
+
let unpriced = false;
|
|
70
|
+
|
|
71
|
+
const style = () => {
|
|
72
|
+
if (sheet) return;
|
|
73
|
+
sheet = true;
|
|
74
|
+
// A constructed sheet passes a site's `style-src 'self'` CSP, which
|
|
75
|
+
// refuses a <style> element; browsers before Safari 16.4 get the element.
|
|
76
|
+
try {
|
|
77
|
+
const css = new CSSStyleSheet();
|
|
78
|
+
css.replaceSync(CSS);
|
|
79
|
+
document.adoptedStyleSheets = [...document.adoptedStyleSheets, css];
|
|
80
|
+
} catch {
|
|
81
|
+
const el = document.createElement('style');
|
|
82
|
+
el.textContent = CSS;
|
|
83
|
+
document.head.append(el);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
const hide = (el) => {
|
|
88
|
+
el.removeAttribute('aria-busy');
|
|
89
|
+
// Not only [hidden]: any display rule of the site's beats that one.
|
|
90
|
+
el.hidden = true;
|
|
91
|
+
el.style.setProperty('display', 'none', 'important');
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const card = ({ metadata: m }, recommendationId, money) => {
|
|
95
|
+
const link = m && m.available !== false && typeof m.name === 'string' ? web(m.url) : null;
|
|
96
|
+
if (!link) return null;
|
|
97
|
+
let price = typeof m.price === 'string' ? m.price : '';
|
|
98
|
+
if (typeof m.price === 'number') {
|
|
99
|
+
const currency = typeof m.currency === 'string' ? m.currency : money;
|
|
100
|
+
try {
|
|
101
|
+
price = new Intl.NumberFormat(document.documentElement.lang || undefined, { style: 'currency', currency }).format(m.price);
|
|
102
|
+
} catch {
|
|
103
|
+
unpriced = true;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const picture = web(m.picture);
|
|
107
|
+
return `<li><a href="${escape(carry(link, recommendationId).href)}">` +
|
|
108
|
+
`${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
|
|
109
|
+
`<span class="recapi-name">${escape(m.name)}</span>` +
|
|
110
|
+
`${price ? `<span class="recapi-price">${escape(price)}</span>` : ''}</a></li>`;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const draw = (row, list) => {
|
|
114
|
+
const { el, placement, heading } = row;
|
|
115
|
+
// A popular fallback is not what was bought together: that row stays away.
|
|
116
|
+
const together = placement === 'bought_together';
|
|
117
|
+
const money = pageCurrency();
|
|
118
|
+
const cards = list.fallback && together ? [] : list.items.map((item) => ({ html: card(item, list.recommendationId, money), why: item.why })).filter(({ html }) => html);
|
|
119
|
+
if (!cards.length) {
|
|
120
|
+
if (list.items.length) {
|
|
121
|
+
const missing = ['name', 'url'].filter((key) => list.items.every(({ metadata }) => typeof metadata?.[key] !== 'string'));
|
|
122
|
+
console.warn(`recapi: no card to draw: send each item's metadata with ${missing.join(' and ') || 'a name and an http(s) url'} (PUT /v1/items)`);
|
|
123
|
+
}
|
|
124
|
+
return hide(el);
|
|
125
|
+
}
|
|
126
|
+
// The title only over a real pair: a product nobody bought with another
|
|
127
|
+
// yet gets similar ones, true cards under a false title.
|
|
128
|
+
const titled = heading && (!together || cards.some(({ why }) => why === 'bought_together'));
|
|
129
|
+
el.innerHTML = `${titled ? `<h2 class="recapi-heading">${escape(heading)}</h2>` : ''}<ul role="list">${cards.map(({ html }) => html).join('')}</ul>`;
|
|
130
|
+
el.removeAttribute('aria-busy');
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const fill = async (members) => {
|
|
134
|
+
try {
|
|
135
|
+
const lists = await client.recommendLists({
|
|
136
|
+
lists: members.map(({ placement, contextItemId }) => ({
|
|
137
|
+
count: ROW,
|
|
138
|
+
...(placement ? { placement } : {}),
|
|
139
|
+
...(contextItemId ? { contextItemId } : {})
|
|
140
|
+
}))
|
|
141
|
+
});
|
|
142
|
+
members.forEach((row, k) => draw(row, lists[k]));
|
|
143
|
+
if (unpriced) {
|
|
144
|
+
unpriced = false;
|
|
145
|
+
console.warn('recapi: prices left out: a number needs a currency, in the item\'s metadata (currency: \'EUR\') or the page\'s <meta property="product:price:currency" content="EUR">');
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
// recommendLists() rejects only on a bad request: the page loses no more than its rows.
|
|
149
|
+
members.forEach(({ el }) => hide(el));
|
|
150
|
+
console.warn('recapi:', error);
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
|
|
154
|
+
const watch = (members) => {
|
|
155
|
+
if (typeof IntersectionObserver !== 'function') return fill(members);
|
|
156
|
+
// Each list is billed and counted as shown: a visitor who never scrolls
|
|
157
|
+
// down saw none.
|
|
158
|
+
const observer = new IntersectionObserver((entries) => {
|
|
159
|
+
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
160
|
+
observer.disconnect();
|
|
161
|
+
return fill(members);
|
|
162
|
+
}, { rootMargin: '0px 0px 400px 0px' });
|
|
163
|
+
for (const { el } of members) observer.observe(el);
|
|
164
|
+
return undefined;
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return (slot, { placement, contextItemId, heading } = {}) => {
|
|
168
|
+
const el = typeof slot === 'string' ? document.querySelector(slot) : slot;
|
|
169
|
+
if (!el) {
|
|
170
|
+
console.warn(`recapi: no element ${slot} on this page for the row`);
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
style();
|
|
174
|
+
el.classList.add('recapi-row');
|
|
175
|
+
el.setAttribute('aria-busy', 'true');
|
|
176
|
+
if (!group) {
|
|
177
|
+
group = [];
|
|
178
|
+
queueMicrotask(() => {
|
|
179
|
+
const members = group;
|
|
180
|
+
group = null;
|
|
181
|
+
watch(members);
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
// The same slot twice in one task is one row, with the last options.
|
|
185
|
+
group = [...group.filter((row) => row.el !== el), { el, placement, contextItemId, heading }];
|
|
186
|
+
};
|
|
187
|
+
}
|