@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/src/shopify.js CHANGED
@@ -13,6 +13,14 @@
13
13
  */
14
14
 
15
15
  import { createClient, localStorageAdapter, memoryStorage } from './index.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';
16
24
 
17
25
  /**
18
26
  * The theme's piece: the visitor's consent, the cart attribute the pixel
@@ -23,7 +31,7 @@ import { createClient, localStorageAdapter, memoryStorage } from './index.js';
23
31
  * @param {{ apiKey: string, baseUrl: string, project: string, platform: string,
24
32
  * shopCurrency?: string|null, pageType?: string|null, customerId?: string|number|null,
25
33
  * boughtTogether?: string|false,
26
- * 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
27
35
  */
28
36
  export async function shopifyTheme(options) {
29
37
 
@@ -81,7 +89,8 @@ export async function shopifyTheme(options) {
81
89
  };
82
90
  // The pixel reads this state under the same project, whatever key it holds.
83
91
  const api = { apiKey: options.apiKey, baseUrl: options.baseUrl, platform: options.platform };
84
- 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 });
85
94
  // What the product pages sent (below) is remembered as recapi's history
86
95
  // is: withdrawing consent forgets it too.
87
96
  const DESCRIBED = 'recapi:described';
@@ -96,14 +105,11 @@ export async function shopifyTheme(options) {
96
105
  const { shopCurrency } = options;
97
106
  if (options.customerId) recapi.identify(String(options.customerId));
98
107
 
99
- // What the shop's admin says the product is: recapi names the product from
100
- // it when the shop sent no catalog (no products export, no webhook), so a
101
- // shop that only pasted this snippet gets similar products by name. Only
102
- // words: recapi never lets them overwrite what the shop sent itself. Sent
103
- // once per product per browser, again when the shop changes them. They say
104
- // nothing about the visitor, so they go with or without consent; what was
105
- // sent is remembered only where recapi may store (else once per page view,
106
- // which recapi writes only when the words changed).
108
+ // What the shop's admin says the product is: recapi names products from it
109
+ // when the shop sent no catalog (no export, no webhook), never over what
110
+ // the shop sent. Nothing about the visitor, so sent with or without
111
+ // consent: once per product per browser where recapi may store, else once
112
+ // per view (recapi writes only words that changed).
107
113
  const product = handle && { handle, title: options.product.title ?? null, type: options.product.type ?? null, tags: options.product.tags ?? null };
108
114
  const describe = () => {
109
115
  const body = JSON.stringify({ products: [product] });
@@ -139,15 +145,12 @@ export async function shopifyTheme(options) {
139
145
  body,
140
146
  keepalive
141
147
  });
142
- // While recapi has no catalog from the shop, it asks, in the answer above,
143
- // for a page of the shop's own product list, which every Shopify storefront
144
- // serves at /products.json to its visitors: a page of 250 products per page
145
- // view, so a shop that only pasted this snippet has its whole catalog named
146
- // after a few product views, its owner's own click-through included. recapi
147
- // keeps the progress, so this needs nothing stored on the device, and hands
148
- // each page to one browser at a time. Only once the browser is idle and the
149
- // row (when it is being drawn) is on the page; a refused or failed read
150
- // waits for the next page view, which gets the same page again.
148
+ // While recapi has no catalog from the shop, its answer above asks for a
149
+ // page of the shop's /products.json, which every storefront serves its
150
+ // visitors: 250 products a view, so a bare shop is named after a few views.
151
+ // recapi keeps the progress and hands each page to one browser at a time.
152
+ // Only once the browser is idle and the row drawn; a failed read waits for
153
+ // the next view, which gets the same page.
151
154
  let drawing = null;
152
155
  const idle = (callback) => (window.requestIdleCallback ? window.requestIdleCallback(callback, { timeout: 10000 }) : setTimeout(callback, 2000));
153
156
  const relay = async (page) => {
@@ -169,219 +172,227 @@ export async function shopifyTheme(options) {
169
172
  await seen(JSON.stringify({ page, products }), false).catch(() => null);
170
173
  };
171
174
  if (product && !editor) describe();
172
- // A card's link carries its recommendation: without consent nothing on the
173
- // device remembers which list showed the product. In the fragment, which no
174
- // server or crawler sees: each list's new ?rec= looks like another page.
175
- // ?rec= is still read: links already out there, and the cards that can't use
176
- // a fragment (below).
177
- const inFragment = /^#rec_[0-9a-f]+$/;
178
- const viewed = () => {
179
- const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
180
- const linked = fragment ?? new URLSearchParams(location.search).get('rec');
181
- recapi.track(handle, 'view', { recommendationId: linked });
182
- // recapi credits an explicit id to whoever brings it: drop it from the
183
- // address so a copied or shared link doesn't credit strangers' visits.
184
- // The other parameters (a variant) keep their exact text.
185
- if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
186
- else if (linked !== null) {
187
- const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
188
- history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
189
- }
190
- };
191
- // A browser may preload the link under the pointer, and a page it prerenders
192
- // runs this script though nobody may ever open it: a click nobody made must
193
- // not be credited.
194
- if (handle && !editor && document.prerendering) document.addEventListener('prerenderingchange', viewed);
195
- else if (handle && !editor) viewed();
175
+ if (handle && !editor) landing(recapi, handle);
196
176
 
197
177
  // Fills <div id="recapi-recommendations">&nbsp;</div> wherever the theme has one.
198
178
  const slot = document.getElementById('recapi-recommendations');
199
- // A product row in the theme's colours and fonts. :where() weighs
200
- // nothing, so any rule of the theme's restyles the cards. Four cards
201
- // across, as the theme's product grids show them, two where four would be
202
- // narrower than 150px (a phone). The page-width rule is for themes with
203
- // no page-width class of their own (below).
204
- const styleOf = (id) => '<style>' +
205
- `:where(#${id}){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;align-content:start}` +
206
- ':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}' +
207
- `:where(#${id} a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}` +
208
- `:where(#${id} img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}` +
209
- `:where(#${id} .recapi-price){font-weight:600}` +
210
- '</style>';
179
+ // A product row in the theme's colours and fonts. The page-width rule is
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';
182
+ const styleOf = (id) => `<style>:where(#${id}){${GRID};align-content:start}` +
183
+ `:where(#recapi-recommendations.page-width,.recapi-bought-together.page-width){${PAGE_WIDTH}}` +
184
+ `${listStyle(`#${id}`)}${cardStyle(`#${id}`)}</style>`;
211
185
  const style = styleOf('recapi-recommendations');
212
- // Dawn's Custom Liquid section spans the whole screen (no page-width box),
213
- // so a row there took 15 narrow columns from the left edge: it keeps to
214
- // the page width through the theme's own page-width class (Dawn's max-width
215
- // and side margins). Horizon's puts its content in the page's column
216
- // (section--page-width) unless the shop chose full width.
217
- const wide = slot && !slot.closest('.page-width, .section--page-width');
218
- if (wide) slot.classList.add('page-width');
219
- // Dawn and the themes built on it hide every empty div (div:empty
220
- // { display: none }): a slot pasted empty, as the quick start once
221
- // printed it, has no box, never comes near the screen, and the row would
222
- // never load. Its style, there at once, makes it not empty. A slot still
223
- // without a box is hidden by the theme or a section around it: the row
224
- // loads if that changes, and the shop's developer is told why it doesn't.
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;
208
+ // Dawn's Custom Liquid section spans the whole screen: a row there took 15
209
+ // narrow columns, so it takes the theme's page-width class. Horizon's
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');
216
+ // Dawn hides every empty div: a slot pasted empty (as the quick start once
217
+ // printed it) would have no box, never come near the screen, never load.
218
+ // Its style, there at once, fills it. A slot still without a box is hidden
219
+ // by the theme: the row loads if that changes, and the developer is told.
225
220
  if (slot && !slot.getClientRects().length) {
226
221
  slot.insertAdjacentHTML('afterbegin', style);
227
222
  if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
228
223
  }
229
- // Not only [hidden]: any display rule of the theme's beats that one, and
230
- // would leave a blank where the row should be.
231
- const hide = () => {
232
- slot.hidden = true;
233
- slot.style.setProperty('display', 'none', 'important');
234
- };
235
224
  // Each row its own placement, so the dashboard and the lift test tell them
236
225
  // apart. An unconfigured placement serves as the default one and joins its
237
226
  // lift test, so a shop's settings carry over.
238
- const { pageType } = options;
239
227
  const placement = handle ? 'product' : pageType === 'cart' ? 'cart' : 'section';
240
- // The row shows 4 cards. recapi counts every product of a list as shown,
241
- // so a spare asked for would get an impression and could be credited a
242
- // view it never caused: the row asks for 4. recapi learns products from
243
- // events and may not know one sold out or was deleted; one more list,
244
- // without the products already listed, then fills the gap.
245
- const ROW = 4;
246
228
  // A product page has a second row under the first: what shoppers bought
247
229
  // with the product on screen, under its own placement, which recapi serves
248
230
  // as bought together until the shop gives it settings of its own. The
249
231
  // option is its title; false turns it off. Pieces pasted before it get the
250
- // row too, with this title.
251
- 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
252
237
  ? (typeof options.boughtTogether === 'string' ? options.boughtTogether : 'Often bought together')
253
238
  : null;
254
- const rows = [{ placement, ...(handle ? { contextItemId: handle } : {}) }];
255
- if (together !== null) rows.push({ placement: 'bought_together', contextItemId: handle });
256
- // Through the call that takes all of a page's rows: billed as one, the
257
- // history sent once, and no product on two rows, the first row's first.
258
- // `counts` holds [row, count] pairs, the lists come back in their order.
259
- const ask = (counts, exclude) => recapi.recommendLists({
260
- lists: counts.map(([row, count]) => ({ count, ...rows[row] })),
261
- ...(exclude.length ? { exclude } : {})
262
- });
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);
263
302
  const draw = async () => {
264
- const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
265
303
  // Prices are in the currency's subunit (100000 is ¥1,000), in the
266
304
  // visitor's currency. A number and a symbol need no translation.
267
305
  const currency = window.Shopify?.currency?.active;
268
306
  const lang = document.documentElement?.lang;
269
307
  let money = null;
270
308
  try { if (currency && lang) money = new Intl.NumberFormat(lang, { style: 'currency', currency }); } catch {}
271
- const tag = (amount) => `<span class="recapi-price">${escape(amount)}</span>`;
272
- // Only http(s) addresses: metadata is the shop's, but a javascript: link
273
- // must never reach the page.
274
- const web = (address) => {
275
- try {
276
- const url = new URL(address, location.href);
277
- return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
278
- } catch {
279
- return null;
280
- }
281
- };
282
- // ?rec= only where a fragment can't carry the id: the address has its own
283
- // (a theme's, not ours to overwrite), it's the page already open (a
284
- // fragment wouldn't load it, so no view), or the page wouldn't read it back.
285
- const carry = (url, recommendationId) => {
286
- const open = url.href.split('#')[0] === location.href.split('#')[0];
287
- if (recommendationId && (url.hash || open || !inFragment.test(`#${recommendationId}`))) url.searchParams.set('rec', recommendationId);
288
- else if (recommendationId) url.hash = recommendationId;
289
- return url;
290
- };
291
- // An item's metadata (sent with PUT /v1/items) draws its card when it has
292
- // a name and a link, with no request to Shopify. Its price is text shown
309
+ // An item's metadata draws its card with no request to Shopify. Its price is text shown
293
310
  // as it is, or a number in the shop's currency: a visitor browsing in
294
311
  // another one gets Shopify's converted price from the lookup instead, as
295
312
  // does a product Shopify's webhook marked "available": false: it may be
296
313
  // sold out, or its stock untracked, and only the lookup knows which.
297
- const fromMetadata = (metadata, recommendationId) => {
298
- const link = metadata?.available !== false && typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? web(metadata.url) : null;
314
+ const fromMetadata = (metadata, recommendationId, why) => {
315
+ const link = cardLink(metadata);
299
316
  if (!link) return null;
300
- let price = '';
301
- 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;
302
320
  else if (typeof metadata.price === 'number') {
303
321
  if (currency !== shopCurrency) return null;
304
- if (money) price = tag(money.format(metadata.price));
322
+ price = money?.format(metadata.price) ?? null;
323
+ was = money && wasOf(metadata, money.format);
305
324
  }
306
- carry(link, recommendationId);
307
- const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
308
- return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}<span>${escape(metadata.name)}</span>${price}</a>`;
325
+ return card(carry(link, recommendationId).href, pictureOf(metadata), metadata.name, price, '', why, was);
309
326
  };
310
327
  // Shopify's CDN resizes on ?width=: a card needs no 2048 px original.
311
- const image = (src) => (src ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
328
+ const image = (src) => (drawable(src) ? `${src}${src.includes('?') ? '&' : '?'}width=400` : '');
312
329
  // Shopify gives a product's address as a path, and it stays one.
313
330
  const path = (address, recommendationId) => {
314
331
  const url = carry(new URL(address, location.href), recommendationId);
315
332
  return `${url.pathname}${url.search}${url.hash}`;
316
333
  };
317
- const fromProduct = (p, recommendationId) => (p?.available
318
- ? `<a href="${escape(path(p.url, recommendationId))}"><img src="${escape(image(p.featured_image))}" alt="" loading="lazy"><span>${escape(p.title)}</span>${money && Number.isFinite(p.price_min) ? tag(money.format(p.price_min / 100)) : ''}</a>`
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)))
319
338
  : null);
320
- // A list's cards, in recapi's order, each with its reason code. The
321
- // others come from the product's own page data, one request each.
322
- const cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
323
- let html = fromMetadata(metadata, recommendationId);
339
+ // A list's cards in recapi's order, with their reason codes; those
340
+ // without metadata from the product's page data, one request each.
341
+ cardsOf = async ({ recommendationId, items }) => (await Promise.all(items.map(async ({ itemId, metadata, why }) => {
342
+ let html = fromMetadata(metadata, recommendationId, why);
324
343
  if (!html) {
325
344
  const response = await fetch(`${root}products/${encodeURIComponent(itemId)}.js`).catch(() => null);
326
- html = fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId);
345
+ html = fromProduct(response?.ok ? await response.json().catch(() => null) : null, recommendationId, why);
327
346
  }
328
347
  return html && { html, why };
329
348
  }))).filter(Boolean);
330
- const lists = await ask(rows.map((_, row) => [row, ROW]), []);
331
- const cards = await Promise.all(lists.map(cardsOf));
332
- // Only a full list that couldn't fill its row: a shorter one means recapi
333
- // has no more to give, and a fallback (recapi slow, down or at a limit)
334
- // would only wait again. One more call for the short rows, without any
335
- // product either row listed.
336
- const short = lists.map((_, row) => row).filter((row) => cards[row].length < ROW && lists[row].items.length >= ROW && !lists[row].fallback);
337
- if (short.length) {
338
- // Refused (a key revoked mid-page): the rows keep the cards they have.
339
- const more = await ask(short.map((row) => [row, ROW - cards[row].length]), lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)))
340
- .catch((error) => { console.warn('recapi:', error); return []; });
341
- // A popular top-up (recapi slow or at a limit on this call) fills the
342
- // first row's gap with what that row shows anyway when recapi is down,
343
- // but under the bought-together title it would mislead: that row keeps
344
- // the cards it has.
345
- await Promise.all(more.map(async (list, k) => {
346
- if (short[k] === 1 && list.fallback) return;
347
- cards[short[k]] = [...cards[short[k]], ...await cardsOf(list)];
348
- }));
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);
349
371
  }
350
- const [first, second = []] = cards.map((row) => row.slice(0, ROW));
351
- if (first.length) slot.innerHTML = style + first.map(({ html }) => html).join('');
352
- else hide();
353
- // Each row shows or hides on its own. A popular fallback is not what was
354
- // bought together, so that row then stays away. The theme's own h2 rule
355
- // styles its title.
356
- if (second.length && !lists[1].fallback) {
357
- // The title only over a real pair among the cards drawn: a product
358
- // nobody bought with another yet gets similar ones, true cards under a
359
- // false title, so they show untitled, the first row's gap apart, and
360
- // read as more of it.
361
- const paired = second.some(({ why }) => why === 'bought_together');
362
- const title = together && paired ? `<h2 class="recapi-heading">${escape(together)}</h2>` : '';
363
- const more = paired ? '' : '<style>:where(.recapi-bought-together.recapi-more){margin-top:1rem}</style>';
364
- slot.insertAdjacentHTML('afterend', `<div class="recapi-bought-together${wide ? ' page-width' : ''}${paired ? '' : ' recapi-more'}">${title}<div id="recapi-bought-together">${styleOf('recapi-bought-together')}${more}${second.map(({ html }) => html).join('')}</div></div>`);
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.
377
+ const pair = paired(second);
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>`;
365
382
  }
383
+ if (seen.length) after += recentRow(seen);
384
+ if (after) slot.insertAdjacentHTML('afterend', after);
385
+ return undefined;
366
386
  };
367
387
  // recommendLists() rejects only on a bad request: a page still loses no more than its rows.
368
388
  const fill = () => (drawing = draw().catch((error) => {
369
- hide();
389
+ unheld();
390
+ box.innerHTML = '';
391
+ hide(box);
370
392
  console.warn('recapi:', error);
371
393
  }));
372
- // Only once the row comes within 400px of the screen, as Shopify's own
373
- // themes load theirs: each list is billed and counted as shown, and a
374
- // shopper who never scrolls down saw none. The div's min-height holds its
375
- // place meanwhile. The view above went at once.
376
- if (slot && typeof IntersectionObserver !== 'function') await fill();
377
- else if (slot) {
378
- const observer = new IntersectionObserver((entries) => {
379
- if (!entries.some((entry) => entry.isIntersecting)) return undefined;
380
- observer.disconnect();
381
- return fill();
382
- }, { rootMargin: '0px 0px 400px 0px' });
383
- observer.observe(slot);
384
- }
394
+ // The view above went at once.
395
+ if (box) await near([box], fill);
385
396
  }
386
397
 
387
398
  // Product URLs end in /products/<handle>, the theme's item id.