@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/src/shopify.js CHANGED
@@ -13,7 +13,14 @@
13
13
  */
14
14
 
15
15
  import { createClient, localStorageAdapter, memoryStorage } from './index.js';
16
- import { GRID, ROW, cardLink, cardStyle, carry, escape, hide, near, paired, web } from './cards.js';
16
+ import { GRID, blankStyle, blanks, card, cardLink, cardStyle, carry, drawable, headingAbove, heldRow, heldStyle, hide, inStock, listOf, listStyle, nameAttribute, nameOf, near, opened, paired, pictureOf, recentlyViewed, region, title, unheld, untitled, wasOf } from './cards.js';
17
+ import { fillRows, followReturns, landing } from './shops.js';
18
+ // Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
19
+ import './client.js';
20
+ import './history.js';
21
+ import './page.js';
22
+ import './storage.js';
23
+ import './transport.js';
17
24
 
18
25
  /**
19
26
  * The theme's piece: the visitor's consent, the cart attribute the pixel
@@ -24,7 +31,7 @@ import { GRID, ROW, cardLink, cardStyle, carry, escape, hide, near, paired, web
24
31
  * @param {{ apiKey: string, baseUrl: string, project: string, platform: string,
25
32
  * shopCurrency?: string|null, pageType?: string|null, customerId?: string|number|null,
26
33
  * boughtTogether?: string|false,
27
- * product?: { handle: string|null, title?: string|null, type?: string|null, tags?: string[]|null }|null }} options
34
+ * product?: { handle: string|null, title?: string|null, type?: string|null, tags?: string[]|null, available?: boolean|null }|null }} options
28
35
  */
29
36
  export async function shopifyTheme(options) {
30
37
 
@@ -82,7 +89,8 @@ export async function shopifyTheme(options) {
82
89
  };
83
90
  // The pixel reads this state under the same project, whatever key it holds.
84
91
  const api = { apiKey: options.apiKey, baseUrl: options.baseUrl, platform: options.platform };
85
- const recapi = createClient({ ...api, project: options.project, consent, storage });
92
+ // The theme sends Shopify's own words for the product (describe, below).
93
+ const recapi = createClient({ ...api, project: options.project, consent, storage, describePages: false });
86
94
  // What the product pages sent (below) is remembered as recapi's history
87
95
  // is: withdrawing consent forgets it too.
88
96
  const DESCRIBED = 'recapi:described';
@@ -164,41 +172,47 @@ export async function shopifyTheme(options) {
164
172
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
165
173
  };
166
174
  if (product && !editor) describe();
167
- // A card's link carries its list's id (cards.js carry): without consent
168
- // nothing on the device remembers which list showed the product.
169
- const inFragment = /^#rec_[0-9a-f]+$/;
170
- const viewed = () => {
171
- const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
172
- const linked = fragment ?? new URLSearchParams(location.search).get('rec');
173
- recapi.track(handle, 'view', { recommendationId: linked });
174
- // recapi credits an explicit id to whoever brings it: drop it from the
175
- // address so a copied or shared link doesn't credit strangers' visits.
176
- // The other parameters (a variant) keep their exact text.
177
- if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
178
- else if (linked !== null) {
179
- const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
180
- history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
181
- }
182
- };
183
- // A browser may preload the link under the pointer, and a page it prerenders
184
- // runs this script though nobody may ever open it: a click nobody made must
185
- // not be credited.
186
- if (handle && !editor && document.prerendering) document.addEventListener('prerenderingchange', viewed);
187
- else if (handle && !editor) viewed();
175
+ if (handle && !editor) landing(recapi, handle);
188
176
 
189
177
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
190
178
  const slot = document.getElementById('recapi-recommendations');
191
179
  // A product row in the theme's colours and fonts. The page-width rule is
192
180
  // for themes with no page-width class of their own (below).
181
+ const PAGE_WIDTH = 'box-sizing:border-box;max-width:var(--page-width,1200px);margin-inline:auto;padding-inline:1.5rem';
193
182
  const styleOf = (id) => `<style>:where(#${id}){${GRID};align-content:start}` +
194
- ':where(#recapi-recommendations.page-width,.recapi-bought-together.page-width){box-sizing:border-box;max-width:var(--page-width,1200px);margin-inline:auto;padding-inline:1.5rem}' +
195
- `${cardStyle(`#${id}`)}</style>`;
183
+ `:where(#recapi-recommendations.page-width,.recapi-bought-together.page-width){${PAGE_WIDTH}}` +
184
+ `${listStyle(`#${id}`)}${cardStyle(`#${id}`)}</style>`;
196
185
  const style = styleOf('recapi-recommendations');
186
+ const { pageType } = options;
187
+ const RECENT = 'recapi-recently-viewed';
188
+ // A home page without the shop's box gets one of recapi's own, for
189
+ // Recently viewed alone: the guide places no box there. At the end of the
190
+ // page's main content, above the footer, else right before the section
191
+ // holding this piece. Not in the theme editor, where the shop sees only
192
+ // the rows it placed. The Shopify app's block will take this box's place.
193
+ const homeBox = () => {
194
+ const main = document.querySelector('main, [role="main"]');
195
+ const piece = [...document.querySelectorAll('script[type="module"]')].find((script) => script.textContent.includes('shopifyTheme'));
196
+ const section = piece?.closest('.shopify-section') ?? piece;
197
+ if (!main && !section) return null;
198
+ const box = document.createElement('div');
199
+ box.id = 'recapi-home';
200
+ // Its style keeps it from Dawn's empty-div rule. A shopper who opened a
201
+ // product will see the row: its place is held below.
202
+ box.innerHTML = '<style></style>';
203
+ if (main) main.append(box);
204
+ else section.before(box);
205
+ return box;
206
+ };
207
+ const ours = !slot && pageType === 'index' && !editor ? homeBox() : null;
197
208
  // Dawn's Custom Liquid section spans the whole screen: a row there took 15
198
209
  // narrow columns, so it takes the theme's page-width class. Horizon's
199
- // section--page-width keeps to the page's column already.
200
- const wide = slot && !slot.closest('.page-width, .section--page-width');
201
- if (wide) slot.classList.add('page-width');
210
+ // section--page-width keeps to the page's column already. Dawn keeps the
211
+ // page width inside each section of its main content, not around them:
212
+ // recapi's own box there needs the class too, on its row.
213
+ const box = slot ?? ours;
214
+ const wide = box && !box.closest('.page-width, .section--page-width');
215
+ if (wide && slot) slot.classList.add('page-width');
202
216
  // Dawn hides every empty div: a slot pasted empty (as the quick start once
203
217
  // printed it) would have no box, never come near the screen, never load.
204
218
  // Its style, there at once, fills it. A slot still without a box is hidden
@@ -210,24 +224,81 @@ export async function shopifyTheme(options) {
210
224
  // Each row its own placement, so the dashboard and the lift test tell them
211
225
  // apart. An unconfigured placement serves as the default one and joins its
212
226
  // lift test, so a shop's settings carry over.
213
- const { pageType } = options;
214
227
  const placement = handle ? 'product' : pageType === 'cart' ? 'cart' : 'section';
215
228
  // A product page has a second row under the first: what shoppers bought
216
229
  // with the product on screen, under its own placement, which recapi serves
217
230
  // as bought together until the shop gives it settings of its own. The
218
231
  // option is its title; false turns it off. Pieces pasted before it get the
219
- // row too, with this title.
220
- const together = handle && options.boughtTogether !== false
232
+ // row too, with this title. Nothing to buy with a sold-out product: no
233
+ // second row, and a title over the first unless the shop wrote its own. A
234
+ // piece pasted before 0.19.3 doesn't say.
235
+ const soldOut = handle && options.product.available === false;
236
+ const together = handle && !soldOut && options.boughtTogether !== false
221
237
  ? (typeof options.boughtTogether === 'string' ? options.boughtTogether : 'Often bought together')
222
238
  : null;
223
- const rows = [{ placement, ...(handle ? { contextItemId: handle } : {}) }];
224
- if (together !== null) rows.push({ placement: 'bought_together', contextItemId: handle });
225
- // One call for all of a page's rows: billed once, the history sent once,
226
- // no product on two rows. `counts` holds [row, count] pairs.
227
- const ask = (counts, exclude) => recapi.recommendLists({
228
- lists: counts.map(([row, count]) => ({ count, ...rows[row] })),
229
- ...(exclude.length ? { exclude } : {})
230
- });
239
+ const rows = ours ? [] : [{ placement }];
240
+ if (together !== null && !ours) rows.push({ placement: 'bought_together' });
241
+ // The home page's second row, or its only one in recapi's own box: the
242
+ // products this shopper opened before (a theme's own such section would
243
+ // make two: the guide says so).
244
+ const recent = pageType === 'index' && box !== null;
245
+ if (recent) rows.push({ placement: 'recently_viewed' });
246
+ const recentRow = (seen) => `<div class="${RECENT}${wide ? ' page-width' : ''}" role="region"${nameAttribute(nameOf(`${RECENT}-title`))}>${title(recentlyViewed(), `${RECENT}-title`)}<div id="${RECENT}">${styleOf(RECENT)}<style>:where(.${RECENT}.page-width){${PAGE_WIDTH}}</style>${listOf(seen, nameOf(`${RECENT}-title`))}</div></div>`;
247
+ // recapi's own box holds the row, else hides: its place is held no more.
248
+ // Its padding is a Dawn section's own, so the footer doesn't touch the cards.
249
+ // While the lists load, each row the page will get holds its place, in the
250
+ // page's width already: blank cards in its own grid at this width, under a
251
+ // blank title where the row has one. The pasted box's own hold (320 px for
252
+ // 4 s, a CSS animation, so a page whose script never comes closes up by
253
+ // itself) ends here. Bought together's place is a real pair's, with its
254
+ // title; Recently viewed's only for a shopper who opened a product.
255
+ const HELD = `<style>${heldStyle(`${GRID};align-content:start`)}:where(.recapi-held.page-width){${PAGE_WIDTH}}${blankStyle('#recapi-recommendations')}</style>`;
256
+ const heldClasses = (name) => `${name}${wide ? ' page-width' : ''}`;
257
+ const holdOurs = () => {
258
+ ours.innerHTML = `<style>:where(#recapi-home){padding-block:36px}</style>${HELD}${heldRow(heldClasses(RECENT))}`;
259
+ ours.hidden = false;
260
+ ours.style.removeProperty('display');
261
+ };
262
+ const titleAbove = slot && headingAbove(slot);
263
+ const ownTitle = soldOut && !titleAbove ? 'recapi-recommendations-title' : null;
264
+ const ownTitleStyle = '<style>:where(#recapi-recommendations>h2){grid-column:1/-1;flex:1 1 100%}</style>';
265
+ if (slot) {
266
+ slot.style.animation = 'none';
267
+ slot.innerHTML = style + HELD + (ownTitle ? ownTitleStyle + title('\u00a0') : '') + blanks();
268
+ const later = rows.slice(1).filter(({ placement }) => placement !== 'recently_viewed' || opened(recapi, handle));
269
+ slot.insertAdjacentHTML('afterend', later.map(({ placement }) => (placement === 'bought_together' ? heldRow(heldClasses('recapi-bought-together'), together !== '') : heldRow(heldClasses(RECENT)))).join(''));
270
+ } else if (ours && opened(recapi, handle)) holdOurs();
271
+ const putOurs = (seen) => {
272
+ if (!seen.length) return hide(ours);
273
+ ours.innerHTML = `<style>:where(#recapi-home){padding-block:36px}</style>${recentRow(seen)}`;
274
+ ours.hidden = false;
275
+ ours.style.removeProperty('display');
276
+ return undefined;
277
+ };
278
+ let cardsOf = null;
279
+ // Back to the home page: its Recently viewed row where it was, else under the others.
280
+ // A shopper who had opened nothing has no row yet: its place is held
281
+ // before the page shows again, so the footer doesn't move when it comes.
282
+ const holdReturn = () => {
283
+ if (document.getElementById(RECENT)) return null;
284
+ if (ours) {
285
+ holdOurs();
286
+ return () => hide(ours);
287
+ }
288
+ (document.querySelector('.recapi-bought-together') ?? slot).insertAdjacentHTML('afterend', heldRow(heldClasses(RECENT)));
289
+ return unheld;
290
+ };
291
+ const drawn = recent && followReturns(recapi, rows[rows.length - 1], handle, (list) => cardsOf(list), (seen) => {
292
+ if (ours) return putOurs(seen);
293
+ unheld();
294
+ const old = document.getElementById(RECENT)?.closest?.(`.${RECENT}`);
295
+ const html = seen.length ? recentRow(seen) : '';
296
+ if (old) {
297
+ old.insertAdjacentHTML('beforebegin', html);
298
+ old.remove();
299
+ } else (document.querySelector('.recapi-bought-together') ?? slot).insertAdjacentHTML('afterend', html);
300
+ return undefined;
301
+ }, holdReturn);
231
302
  const draw = async () => {
232
303
  // Prices are in the currency's subunit (100000 is ¥1,000), in the
233
304
  // visitor's currency. A number and a symbol need no translation.
@@ -235,84 +306,93 @@ export async function shopifyTheme(options) {
235
306
  const lang = document.documentElement?.lang;
236
307
  let money = null;
237
308
  try { if (currency && lang) money = new Intl.NumberFormat(lang, { style: 'currency', currency }); } catch {}
238
- const tag = (amount) => `<span class="recapi-price">${escape(amount)}</span>`;
239
309
  // An item's metadata draws its card with no request to Shopify. Its price is text shown
240
310
  // as it is, or a number in the shop's currency: a visitor browsing in
241
311
  // another one gets Shopify's converted price from the lookup instead, as
242
312
  // does a product Shopify's webhook marked "available": false: it may be
243
313
  // sold out, or its stock untracked, and only the lookup knows which.
244
- const anchor = (href, src, name, price) => `<a href="${escape(href)}">${src === null ? '' : `<img src="${escape(src)}" alt="" loading="lazy">`}<span>${escape(name)}</span>${price}</a>`;
245
- const fromMetadata = (metadata, recommendationId) => {
314
+ const fromMetadata = (metadata, recommendationId, why) => {
246
315
  const link = cardLink(metadata);
247
316
  if (!link) return null;
248
- let price = '';
249
- if (typeof metadata.price === 'string') price = tag(metadata.price);
317
+ let price = null;
318
+ let was = null;
319
+ if (typeof metadata.price === 'string') price = metadata.price;
250
320
  else if (typeof metadata.price === 'number') {
251
321
  if (currency !== shopCurrency) return null;
252
- if (money) price = tag(money.format(metadata.price));
322
+ price = money?.format(metadata.price) ?? null;
323
+ was = money && wasOf(metadata, money.format);
253
324
  }
254
- carry(link, recommendationId);
255
- return anchor(link.href, web(metadata.picture)?.href ?? null, metadata.name, price);
325
+ return card(carry(link, recommendationId).href, pictureOf(metadata), metadata.name, price, '', why, was);
256
326
  };
257
327
  // Shopify's CDN resizes on ?width=: a card needs no 2048 px original.
258
- const image = (src) => (src ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
328
+ const image = (src) => (drawable(src) ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
259
329
  // Shopify gives a product's address as a path, and it stays one.
260
330
  const path = (address, recommendationId) => {
261
331
  const url = carry(new URL(address, location.href), recommendationId);
262
332
  return `${url.pathname}${url.search}${url.hash}`;
263
333
  };
264
- const fromProduct = (p, recommendationId) => (p?.available
265
- ? anchor(path(p.url, recommendationId), image(p.featured_image), p.title, money && Number.isFinite(p.price_min) ? tag(money.format(p.price_min / 100)) : '')
334
+ // The theme's card strikes compare_at_price_min through; ours only when every variant is reduced.
335
+ const fromProduct = (p, recommendationId, why) => (p?.available
336
+ ? card(path(p.url, recommendationId), image(p.featured_image), p.title, money && Number.isFinite(p.price_min) ? money.format(p.price_min / 100) : null, '', why,
337
+ money && p.variants?.every((v) => v.compare_at_price > v.price) && wasOf({ price: p.price_min, list_price: p.compare_at_price_min }, (c) => money.format(c / 100)))
266
338
  : null);
267
339
  // A list's cards in recapi's order, with their reason codes; those
268
340
  // without metadata from the product's page data, one request each.
269
- const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
270
- let html = fromMetadata(metadata, recommendationId);
341
+ cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
342
+ let html = fromMetadata(metadata, recommendationId, why);
271
343
  if (!html) {
272
344
  const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
273
- html = fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
345
+ html = fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId, why);
274
346
  }
275
347
  return html && { html, why };
276
348
  }))).filter(Boolean);
277
- const lists = await ask(rows.map((_, row) => [row, ROW]), []);
278
- const cards = await Promise.all(lists.map(cardsOf));
279
- // recapi may not know a product sold out or was deleted: one more call
280
- // fills a full list's gaps, without any product listed. A shorter list
281
- // has no more to give, and a fallback (recapi slow, down or at a limit)
282
- // would only wait again.
283
- const short = lists.map((_, row) => row).filter((row) => cards[row].length < ROW && lists[row].items.length >= ROW && !lists[row].fallback);
284
- if (short.length) {
285
- // Refused (a key revoked mid-page): the rows keep the cards they have.
286
- const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
287
- .catch((error) => { console.warn('recapi:', error); return []; });
288
- // A popular top-up fills the first row's gap (what it shows anyway when
289
- // recapi is down), never bought together's.
290
- await Promise.all(more.map(async (list, k) => {
291
- if (short[k] === 1 && list.fallback) return;
292
- cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)];
293
- }));
349
+ // Each row's cards by its placement, not its place, should a home page
350
+ // ever carry a product too.
351
+ const listed = [];
352
+ const fallback = [];
353
+ const done = drawn && drawn(rows, listed, fallback);
354
+ const cards = await fillRows(recapi, rows, handle, cardsOf, { listed, fallback });
355
+ if (done) done();
356
+ if (ours) return putOurs(cards[0]);
357
+ const of = (name) => cards[rows.findIndex((row, i) => i && row.placement === name)] ?? [];
358
+ const [first] = cards;
359
+ const second = of('bought_together');
360
+ const seen = recent ? of('recently_viewed') : [];
361
+ // Else Shopify's row shows no heading of ours; the shop may have one above it.
362
+ const own = ownTitle;
363
+ const name = nameOf(titleAbove ?? own);
364
+ unheld();
365
+ if (first.length) {
366
+ region(slot, name);
367
+ slot.innerHTML = style + (own ? `${ownTitleStyle}${title(inStock(), own)}` : '') + listOf(first, name);
368
+ } else {
369
+ slot.innerHTML = '';
370
+ hide(slot);
294
371
  }
295
- const [first, second = []] = cards.map((row) => row.slice(0, ROW));
296
- if (first.length) slot.innerHTML = style + first.map(({ html }) => html).join('');
297
- else hide(slot);
298
- // Each row shows or hides on its own; a popular fallback is not what was
299
- // bought together, so that row stays away.
300
- if (second.length && !lists[1].fallback) {
301
- // Without a pair they show untitled, the first row's gap apart, and
302
- // read as more of it.
372
+ // Each row shows or hides on its own.
373
+ let after = '';
374
+ if (second.length) {
375
+ // Without a pair they show untitled, under the blank line held for
376
+ // the title; a shop that wrote an empty title has no line held.
303
377
  const pair = paired(second);
304
- const title = together && pair ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
305
- const more = pair ? '' : '<style>:where(.recapi-bought-together.recapi-more){margin-top:1rem}</style>';
306
- slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}${pair ? '' : ' recapi-more'}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${more}${second.map(({ html }) => html).join('')}</div></div>`);
378
+ const titled = pair && together;
379
+ const titleId = 'recapi-bought-together-title';
380
+ const its = titled ? nameOf(titleId) : name;
381
+ after += `<div class="recapi-bought-together${wide ? ' page-width' : ''}${pair ? '' : ' recapi-more'}" role="region"${nameAttribute(its)}>${titled ? title(together, titleId) : together ? untitled() : ''}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${listOf(second, its)}</div></div>`;
307
382
  }
383
+ if (seen.length) after += recentRow(seen);
384
+ if (after) slot.insertAdjacentHTML('afterend', after);
385
+ return undefined;
308
386
  };
309
387
  // recommendLists() rejects only on a bad request: a page still loses no more than its rows.
310
388
  const fill = () => (drawing = draw().catch((error) => {
311
- hide(slot);
389
+ unheld();
390
+ box.innerHTML = '';
391
+ hide(box);
312
392
  console.warn('recapi:', error);
313
393
  }));
314
394
  // The view above went at once.
315
- if (slot) await near([slot], fill);
395
+ if (box) await near([box], fill);
316
396
  }
317
397
 
318
398
  // Product URLs end in /products/<handle>, the theme's item id.
package/src/shops.js ADDED
@@ -0,0 +1,197 @@
1
+ /**
2
+ * What the shop platforms' pages share and recapi.row() doesn't need. Each
3
+ * platform module keeps what only it knows: its page, its own cards for
4
+ * products without metadata, its currency, its consent.
5
+ *
6
+ * @module shops
7
+ */
8
+
9
+ import { REC_ID } from './client.js';
10
+ import { ROW, earlierFirst, hasEarlier, opened, openedOf } from './cards.js';
11
+ import { onReturn } from './page.js';
12
+
13
+ // Its home before the plain tag needed it too (page.js): older callers import it here.
14
+ export { onReturn };
15
+
16
+ /**
17
+ * A product page's view, credited to the list in the card's link (the
18
+ * fragment, or ?rec=: old links, cards that can't use a fragment), which
19
+ * then leaves the address: a shared link must not credit strangers' visits.
20
+ * A prerendered page (a link under the pointer) may never be opened.
21
+ */
22
+ export function landing(recapi, item) {
23
+ const viewed = () => {
24
+ const fragment = REC_ID.test(location.hash.slice(1)) ? location.hash.slice(1) : null;
25
+ const linked = fragment ?? new URLSearchParams(location.search).get('rec');
26
+ recapi.track(item, 'view', { recommendationId: linked });
27
+ if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
28
+ else if (linked !== null) {
29
+ // The other parameters (a variant) keep their exact text.
30
+ const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
31
+ history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
32
+ }
33
+ };
34
+ if (document.prerendering) document.addEventListener('prerenderingchange', viewed);
35
+ else viewed();
36
+ // The card's link left the address with the first view.
37
+ onReturn(() => recapi.track(item, 'view', { recommendationId: null }));
38
+ }
39
+
40
+
41
+ /**
42
+ * A home page's Recently viewed row (`row`) after a return by Back or
43
+ * Forward: drawn again, alone, when the visitor's history changed since the
44
+ * page's rows were drawn, so it shows the product just opened, and shows at
45
+ * all for a visitor who had opened none. Else nothing is asked: the same row
46
+ * would be one more billed list. The other rows stay as the visitor saw them,
47
+ * and their products stay off this one. `put(cards)` replaces the row's
48
+ * cards, none hiding it. `hold()`, called before the request, may hold the
49
+ * row's place, the page not yet painted again, and returns what undoes it
50
+ * when the row keeps its old cards. The page calls the returned
51
+ * `drawing(rows, listed, fallback)` as it starts drawing its rows, the
52
+ * arrays then filled by fillRows, and the function it returns once they are.
53
+ */
54
+ export function followReturns(recapi, row, contextItemId, cardsOf, put, hold) {
55
+ let started = false;
56
+ let drawn = null;
57
+ let others = () => [];
58
+ onReturn(async () => {
59
+ if (!started) return; // never near the screen: it draws once it is, from the history then
60
+ const now = openedOf(recapi);
61
+ if (now === drawn) return;
62
+ const undo = hold?.();
63
+ // Refused (a key revoked since) or failed (the stand-in list): the row
64
+ // keeps its cards, and the next return asks again.
65
+ try {
66
+ const fallback = [];
67
+ const [cards] = await fillRows(recapi, [row], contextItemId, cardsOf, { exclude: others(), fallback });
68
+ if (fallback[0]) {
69
+ undo?.();
70
+ return;
71
+ }
72
+ drawn = now;
73
+ put(cards);
74
+ } catch (error) {
75
+ undo?.();
76
+ console.warn('recapi:', error);
77
+ }
78
+ });
79
+ return (rows, listed, fallback = []) => {
80
+ started = true;
81
+ const at = openedOf(recapi);
82
+ others = () => rows.flatMap((each, i) => (each === row ? [] : listed[i] ?? []));
83
+ // Only a real list marks the history drawn: after a failed first draw
84
+ // the next Back asks again, changed history or not.
85
+ return () => {
86
+ if (fallback[rows.indexOf(row)] === false) drawn = at;
87
+ };
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Storage for a shop whose server sends the orders, and can't read the
93
+ * browser's: each save (only with consent) also leaves in the "recapi"
94
+ * cookie the visitor's id and the list each clicked product came from, for
95
+ * a day, as long as a click is credited. Without consent the cookie goes.
96
+ */
97
+ export function orderStorage(consent) {
98
+ const secure = location.protocol === 'https:' ? '; secure' : '';
99
+ const cookie = (value, maxAge) => {
100
+ document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
101
+ };
102
+ if (!consent && /(?:^|;\s*)recapi=/.test(document.cookie ?? '')) cookie('', 0);
103
+ const mirror = (saved) => {
104
+ let state;
105
+ try {
106
+ state = JSON.parse(saved);
107
+ } catch {
108
+ return;
109
+ }
110
+ if (typeof state?.anonId !== 'string') return;
111
+ const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
112
+ // A browser drops a cookie over 4 KB: the products shown last stay.
113
+ let value;
114
+ do {
115
+ value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
116
+ } while (value.length > 3000 && clicked.shift());
117
+ cookie(value, 86400);
118
+ };
119
+ return {
120
+ getItem: (key) => localStorage.getItem(key),
121
+ // The cookie first: a full storage quota throws, and the order still needs it.
122
+ setItem: (key, value) => {
123
+ mirror(value);
124
+ localStorage.setItem(key, value);
125
+ },
126
+ removeItem: (key) => {
127
+ localStorage.removeItem(key);
128
+ cookie('', 0);
129
+ }
130
+ };
131
+ }
132
+
133
+ /**
134
+ * An order's products as the visitor's history knows them, when the shop's
135
+ * server sends the order: else the row would open with a product they just
136
+ * bought, as one they looked at. Once, however often the page is reloaded.
137
+ * Nothing to count leaves the client alone: reading its history would give
138
+ * the visitor of any page an id and a cookie.
139
+ */
140
+ export function bought(recapi, items) {
141
+ if (!items?.length) return;
142
+ const known = new Set(recapi.getHistory().history.filter(([, , , level]) => level === 10).map(([item]) => item));
143
+ for (const item of items) if (!known.has(item)) recapi.track(item, 'purchase', { send: false });
144
+ }
145
+
146
+ /**
147
+ * Each row's cards, at most 4, from `cardsOf(list)`, in one call for all of
148
+ * a page's rows: billed as one, no product on two rows. recapi counts every
149
+ * product of a list as shown, so a row asks for the 4 it shows, then once
150
+ * more, without any product listed, for a full list's gaps (sold out,
151
+ * deleted): a shorter list has no more, a fallback would only wait again.
152
+ * Bought together never shows popular products: they would belie its title.
153
+ * A top-up is a list of its own, so it may bring an earlier-opened product to
154
+ * a row that has its one: there it is a card like any other.
155
+ * A Recently viewed row shows only when its list has a product the visitor
156
+ * opened (else it is the first row's list again, under a false title), and
157
+ * none of its cards is marked: the title says it of all. Its list is not
158
+ * asked for when the history has no such product, nor the call made for it alone.
159
+ * `exclude` keeps products off every row; `listed[i]` gets row i's products,
160
+ * `fallback[i]` whether its list stood in for a failed call.
161
+ */
162
+ export async function fillRows(recapi, rows, contextItemId, cardsOf, { exclude = [], listed = [], fallback = [] } = {}) {
163
+ const ask = (wanted, exclude) => recapi.recommendLists({
164
+ lists: wanted.map(([i, count]) => ({ count, placement: rows[i].placement, ...(contextItemId ? { contextItemId } : {}) })),
165
+ ...(exclude.length ? { exclude } : {})
166
+ });
167
+ const recent = (i) => rows[i].placement === 'recently_viewed';
168
+ const unmarked = (list) => ({ ...list, items: list.items.map((item) => ({ ...item, why: undefined })) });
169
+ const draw = (list, i) => (list.fallback && rows[i].placement === 'bought_together' ? [] : cardsOf(recent(i) ? unmarked(list) : list));
170
+ const none = rows.some((_, i) => recent(i)) && !opened(recapi, contextItemId);
171
+ const asked = rows.map((_, i) => i).filter((i) => !none || !recent(i));
172
+ const got = asked.length ? await ask(asked.map((i) => [i, ROW]), exclude) : [];
173
+ const lists = rows.map(() => ({ items: [] }));
174
+ asked.forEach((i, k) => { lists[i] = got[k]; });
175
+ lists.forEach((list, i) => {
176
+ listed[i] = list.items.map(({ itemId }) => itemId);
177
+ fallback[i] = list.fallback === true;
178
+ });
179
+ // shortcut: an opened product the shop can't draw (sold out since) still lets the row show; the engine leaves out inactive ones.
180
+ const shows = lists.map((list, i) => !recent(i) || hasEarlier(list.items));
181
+ const cards = await Promise.all(lists.map((list, i) => (shows[i] ? draw(list, i) : [])));
182
+ const short = rows.map((_, i) => i).filter((i) => shows[i] && cards[i].length < ROW && lists[i].items.length >= ROW && !lists[i].fallback);
183
+ if (short.length) {
184
+ // Refused (a key revoked mid-page): the rows keep the cards they have.
185
+ try {
186
+ const more = await ask(short.map((i) => [i, ROW - cards[i].length]), [...exclude, ...listed.flat()]);
187
+ more.forEach((list, k) => listed[short[k]].push(...list.items.map(({ itemId }) => itemId)));
188
+ const extra = await Promise.all(more.map((list, k) => draw(hasEarlier(cards[short[k]])
189
+ ? { ...list, items: list.items.map((item) => (hasEarlier([item]) ? { ...item, why: undefined } : item)) }
190
+ : list, short[k])));
191
+ short.forEach((i, k) => cards[i].push(...extra[k]));
192
+ } catch (error) {
193
+ console.warn('recapi:', error);
194
+ }
195
+ }
196
+ return cards.map((row) => earlierFirst(row.slice(0, ROW)));
197
+ }