@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/README.md +416 -45
- package/index.d.ts +17 -1
- package/package.json +1 -1
- package/src/cards.js +186 -4
- package/src/client.js +446 -19
- package/src/index.js +3 -1
- package/src/magento.js +183 -149
- package/src/page.js +418 -0
- package/src/row.js +142 -28
- package/src/shopify.js +164 -84
- package/src/shops.js +197 -0
- package/src/woocommerce.js +157 -186
package/src/woocommerce.js
CHANGED
|
@@ -14,6 +14,14 @@
|
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
import { createClient } from './index.js';
|
|
17
|
+
import { blankStyle, blanks, card, cardStyle, carry, headingAbove, heldRow, heldStyle, hide, listOf, listStyle, nameAttribute, nameOf, near, paired, opened, pictureOf, recentlyViewed, region, title, unheld, untitled, wasOf, web } from './cards.js';
|
|
18
|
+
import { bought, fillRows, followReturns, landing, orderStorage } from './shops.js';
|
|
19
|
+
// Their own imports, named so the browser asks for all at once (TestEntriesImportTheirWholeGraph).
|
|
20
|
+
import './client.js';
|
|
21
|
+
import './history.js';
|
|
22
|
+
import './page.js';
|
|
23
|
+
import './storage.js';
|
|
24
|
+
import './transport.js';
|
|
17
25
|
|
|
18
26
|
/**
|
|
19
27
|
* Runs a page of the shop. Resolves once the page's work is set up (the row
|
|
@@ -26,7 +34,7 @@ import { createClient } from './index.js';
|
|
|
26
34
|
* consent: 'wp-consent-api'|'banner'|'no-banner'|string,
|
|
27
35
|
* currency?: string|null,
|
|
28
36
|
* order?: { items: string[], amounts?: ({ value: number, currency: string }|null)[],
|
|
29
|
-
* customer: string|null }|null } }} options
|
|
37
|
+
* customer: string|null, bought?: string[] }|null } }} options
|
|
30
38
|
*/
|
|
31
39
|
export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
32
40
|
// recapi keeps a history on the visitor's device only with their consent,
|
|
@@ -42,48 +50,9 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
42
50
|
|| (page.consent === 'banner' && answered === true)
|
|
43
51
|
|| (page.consent === 'wp-consent-api' && typeof window.wp_has_consent === 'function' && window.wp_has_consent('statistics') === true);
|
|
44
52
|
// With a secret key the server sends the order once paid (the buyer may
|
|
45
|
-
// never see the order-received page)
|
|
46
|
-
|
|
47
|
-
// consent, the "recapi" cookie gets what a purchase needs, the visitor's id
|
|
48
|
-
// and the recommendation each clicked product came from (the saved list
|
|
49
|
-
// entries with a click time). A day, as long as the library credits a click.
|
|
50
|
-
const secure = location.protocol === 'https:' ? '; secure' : '';
|
|
51
|
-
const cookie = (value, maxAge) => {
|
|
52
|
-
document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
|
|
53
|
-
};
|
|
54
|
-
const mirror = (saved) => {
|
|
55
|
-
let state;
|
|
56
|
-
try {
|
|
57
|
-
state = JSON.parse(saved);
|
|
58
|
-
} catch {
|
|
59
|
-
return;
|
|
60
|
-
}
|
|
61
|
-
if (typeof state?.anonId !== 'string') return;
|
|
62
|
-
const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
|
|
63
|
-
// A browser drops a cookie over 4 KB: the products shown last stay.
|
|
64
|
-
let value;
|
|
65
|
-
do {
|
|
66
|
-
value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
|
|
67
|
-
} while (value.length > 3000 && clicked.shift());
|
|
68
|
-
cookie(value, 86400);
|
|
69
|
-
};
|
|
70
|
-
const storage = page.orders ? {
|
|
71
|
-
getItem: (key) => localStorage.getItem(key),
|
|
72
|
-
// The cookie first: a full storage quota throws, and the order still
|
|
73
|
-
// needs it.
|
|
74
|
-
setItem: (key, value) => {
|
|
75
|
-
mirror(value);
|
|
76
|
-
localStorage.setItem(key, value);
|
|
77
|
-
},
|
|
78
|
-
removeItem: (key) => {
|
|
79
|
-
localStorage.removeItem(key);
|
|
80
|
-
cookie('', 0);
|
|
81
|
-
}
|
|
82
|
-
} : undefined;
|
|
53
|
+
// never see the order-received page), with the ids the cookie keeps.
|
|
54
|
+
const storage = page.orders ? orderStorage(consent) : undefined;
|
|
83
55
|
const recapi = createClient({ apiKey, baseUrl, consent, storage, platform });
|
|
84
|
-
// A visitor without consent (or who took it back) leaves no ids for their
|
|
85
|
-
// next order.
|
|
86
|
-
if (page.orders && !consent && /(?:^|;\s*)recapi=/.test(document.cookie ?? '')) cookie('', 0);
|
|
87
56
|
window.recapi = { setConsent: (value) => recapi.setConsent(value === true) };
|
|
88
57
|
if (page.consent === 'wp-consent-api') {
|
|
89
58
|
document.addEventListener('wp_listen_for_consent_change', (event) => {
|
|
@@ -103,7 +72,22 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
103
72
|
if (clicked) recapi.track(clicked, 'cart');
|
|
104
73
|
clicked = null;
|
|
105
74
|
};
|
|
75
|
+
// jQuery may come after this module: a speed plugin that delays classic
|
|
76
|
+
// scripts until the visitor's first touch, but not modules, or a theme
|
|
77
|
+
// loading it async. Its signal is taken when it is there, at the latest
|
|
78
|
+
// at the click that sets the product (its call answers later) or at load.
|
|
79
|
+
// Once: a cart counts once anyway (added() forgets the click), but a
|
|
80
|
+
// listener per click would pile up.
|
|
81
|
+
let jquery = false;
|
|
82
|
+
const subscribe = () => {
|
|
83
|
+
if (jquery || typeof window.jQuery !== 'function') return;
|
|
84
|
+
jquery = true;
|
|
85
|
+
window.jQuery(document.body).on('added_to_cart', added);
|
|
86
|
+
};
|
|
87
|
+
subscribe();
|
|
88
|
+
if (!jquery) window.addEventListener('load', subscribe, { once: true });
|
|
106
89
|
document.addEventListener('click', (event) => {
|
|
90
|
+
subscribe();
|
|
107
91
|
const id = event.target?.closest?.('[data-product_id]')?.getAttribute('data-product_id');
|
|
108
92
|
if (id) clicked = id;
|
|
109
93
|
}, true);
|
|
@@ -114,33 +98,12 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
114
98
|
clicked = id;
|
|
115
99
|
added();
|
|
116
100
|
}, true);
|
|
117
|
-
window.jQuery?.(document.body).on('added_to_cart', added);
|
|
118
101
|
document.body?.addEventListener('wc-blocks_added_to_cart', added);
|
|
119
102
|
|
|
120
103
|
// The product id is the item id: the widget loads products by it. A
|
|
121
|
-
// card's link carries its
|
|
122
|
-
//
|
|
123
|
-
|
|
124
|
-
// miss the shop's page cache. ?rec= is still read: links already out there,
|
|
125
|
-
// and the cards that can't use a fragment (below).
|
|
126
|
-
const inFragment = /^#rec_[0-9a-f]+$/;
|
|
127
|
-
const viewed = () => {
|
|
128
|
-
const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
|
|
129
|
-
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
130
|
-
recapi.track(page.product, 'view', { recommendationId: linked });
|
|
131
|
-
// recapi credits an explicit id to whoever brings it: drop it from the
|
|
132
|
-
// address so a copied or shared link doesn't credit strangers' visits.
|
|
133
|
-
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
134
|
-
else if (linked !== null) {
|
|
135
|
-
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
136
|
-
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
137
|
-
}
|
|
138
|
-
};
|
|
139
|
-
// A browser may preload the link under the pointer, and a page it prerenders
|
|
140
|
-
// runs this script though nobody may ever open it: a click nobody made must
|
|
141
|
-
// not be credited.
|
|
142
|
-
if (page.product && document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
143
|
-
else if (page.product) viewed();
|
|
104
|
+
// card's link carries its list's id in the fragment, which no page cache
|
|
105
|
+
// sees: an unknown ?rec= made every click from the row miss it.
|
|
106
|
+
if (page.product) landing(recapi, page.product);
|
|
144
107
|
|
|
145
108
|
// The checkout is the shop's own page, so the purchases find the visitor
|
|
146
109
|
// and the recommendations they clicked where the product pages left them.
|
|
@@ -148,28 +111,30 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
148
111
|
if (page.order.customer) recapi.identify(page.order.customer);
|
|
149
112
|
// An older plugin prints no amounts: its purchases go without one.
|
|
150
113
|
page.order.items.forEach((item, i) => recapi.track(item, 'purchase', page.order.amounts?.[i] ?? {}));
|
|
114
|
+
// Those the server counted, which the visitor's history can't know of.
|
|
115
|
+
bought(recapi, page.order.bought);
|
|
151
116
|
}
|
|
152
117
|
|
|
153
118
|
// Fills <div id="recapi-recommendations"></div>. A merchant who pasted one
|
|
154
119
|
// before the plugin printed its own would see an empty second row: the
|
|
155
120
|
// first is filled, the others removed. Not hidden: the cards' grid rule
|
|
156
121
|
// below matches every slot and beats the browser's [hidden] rule.
|
|
122
|
+
// The plugin's heading goes with its row: left alone, it would title nothing.
|
|
123
|
+
const titleId = 'recapi-recommendations-title';
|
|
157
124
|
const [slot, ...others] = document.querySelectorAll('#recapi-recommendations');
|
|
158
|
-
for (const other of others)
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
//
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
':where(#recapi-recommendations .recapi-price){font-weight:600}' +
|
|
172
|
-
'</style>';
|
|
125
|
+
for (const other of others) {
|
|
126
|
+
const above = other.previousElementSibling;
|
|
127
|
+
if (above?.id === titleId) above.remove();
|
|
128
|
+
other.remove();
|
|
129
|
+
}
|
|
130
|
+
// The shop's own related products the plugin printed in Related products'
|
|
131
|
+
// place: recapi's cards replace them, and without any they stay, title and
|
|
132
|
+
// all, as the page was before recapi (Magento's rule).
|
|
133
|
+
const standIn = Boolean(slot?.querySelector?.('li'));
|
|
134
|
+
// A product row in the theme's colours and fonts.
|
|
135
|
+
const GRID = 'display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start';
|
|
136
|
+
const styleOf = (id) => `<style>:where(#${id}){${GRID}}${listStyle(`#${id}`)}${cardStyle(`#${id}`)}</style>`;
|
|
137
|
+
const style = styleOf('recapi-recommendations');
|
|
173
138
|
// A theme that hides every empty div (div:empty { display: none }, Dawn's
|
|
174
139
|
// rule) hides a slot pasted empty: it would never come near the screen
|
|
175
140
|
// and the row would never load. Its style, there at once, makes it not
|
|
@@ -179,76 +144,106 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
179
144
|
slot.insertAdjacentHTML('afterbegin', style);
|
|
180
145
|
if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
|
|
181
146
|
}
|
|
182
|
-
// Each row shows 4 cards. recapi counts every product of a list as shown,
|
|
183
|
-
// so a spare asked for would get an impression and could be credited a
|
|
184
|
-
// view it never caused: a row asks for 4. Without a secret key recapi
|
|
185
|
-
// may not know a product sold out or was deleted; one more call, for the
|
|
186
|
-
// rows short of cards and without the products already listed, then
|
|
187
|
-
// fills the gaps.
|
|
188
|
-
const ROW = 4;
|
|
189
147
|
// A product page has a second row, bought together, which the script
|
|
190
148
|
// adds under the first once it has cards: the printed page stays the same
|
|
191
149
|
// for every shop and every page cache, and an empty row leaves nothing.
|
|
192
150
|
const TOGETHER = 'recapi-bought-together';
|
|
193
|
-
const rows = [{ placement: page.placement
|
|
194
|
-
if (page.product && page.together !== null) rows.push({ placement: 'bought_together'
|
|
195
|
-
//
|
|
196
|
-
//
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
151
|
+
const rows = [{ placement: page.placement }];
|
|
152
|
+
if (page.product && page.together !== null) rows.push({ placement: 'bought_together' });
|
|
153
|
+
// The front page's second row (WordPress marks its body "home"): the
|
|
154
|
+
// products this shopper opened before. A theme's own such section makes two.
|
|
155
|
+
const RECENT = 'recapi-recently-viewed';
|
|
156
|
+
// The plugin's own front-page slot holds that row alone, under its title.
|
|
157
|
+
const alone = page.placement === 'recently_viewed';
|
|
158
|
+
const heading = alone ? recentlyViewed() : page.heading;
|
|
159
|
+
const recent = !alone && document.body?.classList?.contains('home') === true;
|
|
160
|
+
if (recent) rows.push({ placement: 'recently_viewed' });
|
|
161
|
+
const recentRow = (seen) => {
|
|
162
|
+
const its = nameOf(`${RECENT}-title`);
|
|
163
|
+
return `${title(recentlyViewed(), `${RECENT}-title`)}<div id="${RECENT}" role="region"${nameAttribute(its)}>${styleOf(RECENT)}${listOf(seen, its)}</div>`;
|
|
164
|
+
};
|
|
165
|
+
// The printed holds last 4 s only (a CSS animation: recapi-gone from 0.33.0,
|
|
166
|
+
// which prints each row's blank place; an older plugin's box holds 320px),
|
|
167
|
+
// so a page whose script never comes closes up by itself. From here each
|
|
168
|
+
// row the page will get holds its place while the lists load: blank cards
|
|
169
|
+
// in its grid at this width, under a blank title where it has one (bought
|
|
170
|
+
// together's as a real pair's; Recently viewed's only for a shopper who
|
|
171
|
+
// opened a product), as tall as the printed ones: swapping them moves
|
|
172
|
+
// nothing. A box without that hold (the front page's, a pasted one) keeps
|
|
173
|
+
// its own height; the stand-in's cards are their real height already, and
|
|
174
|
+
// the place printed under them stays.
|
|
175
|
+
if (['recapi-hold', 'recapi-gone'].includes(slot?.style.animationName)) {
|
|
176
|
+
unheld();
|
|
177
|
+
slot.style.animation = 'none';
|
|
178
|
+
slot.innerHTML = `${style}<style>${heldStyle(GRID)}${blankStyle('#recapi-recommendations')}</style>${blanks()}`;
|
|
179
|
+
if (heading) slot.insertAdjacentHTML('beforebegin', `<div class="recapi-held" aria-hidden="true">${title('\u00a0')}</div>`);
|
|
180
|
+
const later = rows.slice(1).filter(({ placement }) => placement !== 'recently_viewed' || opened(recapi, page.product));
|
|
181
|
+
slot.insertAdjacentHTML('afterend', later.map(({ placement }) => heldRow('', placement !== 'bought_together' || page.together !== '')).join(''));
|
|
182
|
+
} else if (others.length) unheld();
|
|
183
|
+
else document.querySelectorAll('.recapi-held').forEach((el) => { el.style.animation = 'none'; });
|
|
184
|
+
// The slot's own row under its title; none hides it, title and all.
|
|
185
|
+
const show = (first) => {
|
|
186
|
+
unheld();
|
|
187
|
+
const name = nameOf(first.length && heading ? titleId : headingAbove(slot), heading);
|
|
188
|
+
if (first.length) {
|
|
189
|
+
region(slot, name);
|
|
190
|
+
slot.innerHTML = style + listOf(first, name);
|
|
191
|
+
// Hidden by an empty draw before a Back, not by the theme.
|
|
192
|
+
if (slot.hidden) {
|
|
193
|
+
slot.hidden = false;
|
|
194
|
+
slot.style.removeProperty('display');
|
|
195
|
+
}
|
|
196
|
+
if (heading && !document.getElementById(titleId)) slot.insertAdjacentHTML('beforebegin', title(heading, titleId));
|
|
197
|
+
} else if (!standIn) {
|
|
198
|
+
hide(slot);
|
|
199
|
+
document.getElementById(titleId)?.remove();
|
|
200
|
+
}
|
|
201
|
+
return name;
|
|
202
|
+
};
|
|
203
|
+
let cardsOf = null;
|
|
204
|
+
// Back to the front page: its Recently viewed row where it was, else under
|
|
205
|
+
// the others; the plugin's own slot draws it again in place.
|
|
206
|
+
const drawing = (recent || alone) && followReturns(recapi, rows[alone ? 0 : rows.length - 1], page.product, (list) => cardsOf(list), (seen) => {
|
|
207
|
+
if (alone) return show(seen);
|
|
208
|
+
unheld();
|
|
209
|
+
const old = [document.getElementById(`${RECENT}-title`), document.getElementById(RECENT)].filter(Boolean);
|
|
210
|
+
const html = seen.length ? recentRow(seen) : '';
|
|
211
|
+
if (!old.length) (document.getElementById(TOGETHER) ?? slot).insertAdjacentHTML('afterend', html);
|
|
212
|
+
else {
|
|
213
|
+
old[0].insertAdjacentHTML('beforebegin', html);
|
|
214
|
+
for (const el of old) el.remove();
|
|
215
|
+
}
|
|
216
|
+
return undefined;
|
|
201
217
|
});
|
|
202
218
|
const draw = async () => {
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
// must never reach the page.
|
|
206
|
-
const web = (address) => {
|
|
219
|
+
const lang = document.documentElement?.lang;
|
|
220
|
+
const money = (amount, currency) => {
|
|
207
221
|
try {
|
|
208
|
-
|
|
209
|
-
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
222
|
+
return lang && currency && Number.isFinite(amount) ? new Intl.NumberFormat(lang, { style: 'currency', currency }).format(amount) : null;
|
|
210
223
|
} catch {
|
|
211
224
|
return null;
|
|
212
225
|
}
|
|
213
226
|
};
|
|
214
|
-
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
215
|
-
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
216
|
-
// fragment wouldn't load it, so no view), or the page wouldn't read it back.
|
|
217
227
|
const link = (address, recommendationId) => {
|
|
218
228
|
const url = web(address);
|
|
219
|
-
|
|
220
|
-
const open = url.href.split('#')[0] === location.href.split('#')[0];
|
|
221
|
-
if (url.hash || open || !inFragment.test(`#${recommendationId}`)) url.searchParams.set('rec', recommendationId);
|
|
222
|
-
else url.hash = recommendationId;
|
|
223
|
-
return url.href;
|
|
224
|
-
};
|
|
225
|
-
const lang = document.documentElement?.lang;
|
|
226
|
-
const money = (amount, currency) => {
|
|
227
|
-
try {
|
|
228
|
-
if (!lang || !currency || !Number.isFinite(amount)) return '';
|
|
229
|
-
return `<span class="recapi-price">${escape(new Intl.NumberFormat(lang, { style: 'currency', currency }).format(amount))}</span>`;
|
|
230
|
-
} catch {
|
|
231
|
-
return '';
|
|
232
|
-
}
|
|
229
|
+
return url && carry(url, recommendationId).href;
|
|
233
230
|
};
|
|
234
|
-
// A metadata card without a usable picture gets no image at all.
|
|
235
|
-
const card = (href, picture, name, price) =>
|
|
236
|
-
`<a href="${escape(href)}">${picture !== undefined ? `<img src="${escape(picture)}" alt="" loading="lazy">` : ''}<span>${escape(name)}</span>${price}</a>`;
|
|
237
231
|
// An item's metadata (sent with PUT /v1/items) draws its card when it has
|
|
238
232
|
// a name and a link, with no request to the shop. Its price is text shown
|
|
239
233
|
// as it is, or a number in the shop's currency: a visitor browsing in
|
|
240
234
|
// another one (a currency switcher) gets the Store API's price instead.
|
|
241
|
-
const fromMetadata = (metadata, recommendationId) => {
|
|
235
|
+
const fromMetadata = (metadata, recommendationId, why) => {
|
|
242
236
|
const href = typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? link(metadata.url, recommendationId) : null;
|
|
243
237
|
if (!href) return null;
|
|
244
|
-
let price =
|
|
245
|
-
|
|
238
|
+
let price = null;
|
|
239
|
+
let was = null;
|
|
240
|
+
if (typeof metadata.price === 'string') price = metadata.price;
|
|
246
241
|
else if (typeof metadata.price === 'number') {
|
|
247
242
|
if (!page.currency) return null;
|
|
248
243
|
price = money(metadata.price, page.currency);
|
|
244
|
+
was = wasOf(metadata, (amount) => money(amount, page.currency));
|
|
249
245
|
}
|
|
250
|
-
|
|
251
|
-
return card(href, picture?.href, metadata.name, price);
|
|
246
|
+
return card(href, pictureOf(metadata), metadata.name, price, '', why, was);
|
|
252
247
|
};
|
|
253
248
|
// Product names come as HTML (WordPress turns quotes into entities).
|
|
254
249
|
const text = (html) => String(html ?? '').replace(/<[^>]*>/g, '').replace(/&(#\d+|#x[0-9a-f]+|amp|lt|gt|quot);/gi, (entity, name) => {
|
|
@@ -260,12 +255,17 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
260
255
|
// Prices are in the currency's minor unit. A number and a symbol need
|
|
261
256
|
// no translation.
|
|
262
257
|
const price = ({ prices: p }) => money(Number(p?.price) / 10 ** p?.currency_minor_unit, p?.currency_code);
|
|
258
|
+
// shortcut: the Store API doesn't say whether every variation is
|
|
259
|
+
// reduced, so a variable product shows one price here; the catalog
|
|
260
|
+
// sync's metadata knows.
|
|
261
|
+
const regular = ({ type, prices: p }) => (type !== 'variable' && Number(p?.regular_price) > Number(p?.price)
|
|
262
|
+
? money(Number(p.regular_price) / 10 ** p.currency_minor_unit, p.currency_code) : null);
|
|
263
263
|
// A list's cards, in recapi's order: those whose metadata draws them, the
|
|
264
264
|
// others from WooCommerce's Store API (public, one request for all). Each
|
|
265
265
|
// keeps its item's reason code.
|
|
266
|
-
|
|
266
|
+
cardsOf = async ({ recommendationId, items }) => {
|
|
267
267
|
const reasons = new Map(items.map(({ itemId, why }) => [itemId, why]));
|
|
268
|
-
const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata, recommendationId)]));
|
|
268
|
+
const cards = new Map(items.map(({ itemId, metadata, why }) => [itemId, fromMetadata(metadata, recommendationId, why)]));
|
|
269
269
|
const ids = [...cards].filter(([id, html]) => !html && /^\d+$/.test(id)).map(([id]) => id);
|
|
270
270
|
let products = [];
|
|
271
271
|
if (ids.length) {
|
|
@@ -278,71 +278,42 @@ export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
|
278
278
|
for (const p of products) {
|
|
279
279
|
const href = link(p.permalink, recommendationId);
|
|
280
280
|
if (cards.has(String(p.id)) && p.is_purchasable && p.is_in_stock && href) {
|
|
281
|
-
cards.set(String(p.id), card(href, p.images?.[0]?.thumbnail || p.images?.[0]?.src || '', text(p.name), price(p)));
|
|
281
|
+
cards.set(String(p.id), card(href, p.images?.[0]?.thumbnail || p.images?.[0]?.src || '', text(p.name), price(p), '', reasons.get(String(p.id)), regular(p)));
|
|
282
282
|
}
|
|
283
283
|
}
|
|
284
284
|
return [...cards].filter(([, html]) => html).map(([id, html]) => ({ html, why: reasons.get(id) }));
|
|
285
285
|
};
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
const
|
|
292
|
-
if (
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
const [first, together] = shown.map((cards) => cards.slice(0, ROW));
|
|
308
|
-
// The theme's own h2 rule styles a heading. Added only once the cards
|
|
309
|
-
// are in, so a row that stays hidden leaves no title behind.
|
|
310
|
-
const heading = (text) => (text ? `<h2 class="recapi-heading">${escape(text)}</h2>` : '');
|
|
311
|
-
// One row empty never hides the other. A fallback (recapi slow, down or
|
|
312
|
-
// at a limit) is popular products, not what shoppers bought together:
|
|
313
|
-
// under that title it would mislead, so that row waits for the next page.
|
|
314
|
-
if (together?.length && !lists[1].fallback) {
|
|
315
|
-
// The title only over a real pair among the cards drawn: a product
|
|
316
|
-
// nobody bought with another yet gets similar ones, true cards under a
|
|
317
|
-
// false title, so they show untitled, the first row's gap apart, and
|
|
318
|
-
// read as more of it.
|
|
319
|
-
const paired = together.some(({ why }) => why === 'bought_together');
|
|
320
|
-
const more = paired ? '' : `<style>:where(#${TOGETHER}){margin-top:1rem}</style>`;
|
|
321
|
-
slot.insertAdjacentHTML('afterend', `${paired ? heading(rows[1].heading) : ''}<div id="${TOGETHER}">${style.replaceAll('recapi-recommendations', TOGETHER)}${more}${together.map(({ html }) => html).join('')}</div>`);
|
|
322
|
-
}
|
|
323
|
-
if (first.length) {
|
|
324
|
-
slot.innerHTML = style + first.map(({ html }) => html).join('');
|
|
325
|
-
if (page.heading) slot.insertAdjacentHTML('beforebegin', heading(page.heading));
|
|
326
|
-
} else {
|
|
327
|
-
hide();
|
|
286
|
+
// Each row's cards by its placement, not its place: a front page that is
|
|
287
|
+
// also a product page (a shop's home set to one) has all three rows.
|
|
288
|
+
const listed = [];
|
|
289
|
+
const fallback = [];
|
|
290
|
+
const drawn = drawing && drawing(rows, listed, fallback);
|
|
291
|
+
const cards = await fillRows(recapi, rows, page.product, cardsOf, { listed, fallback });
|
|
292
|
+
if (drawn) drawn();
|
|
293
|
+
const of = (placement) => cards[rows.findIndex((row, i) => i && row.placement === placement)] ?? [];
|
|
294
|
+
const [first] = cards;
|
|
295
|
+
const together = of('bought_together');
|
|
296
|
+
const seen = recent ? of('recently_viewed') : [];
|
|
297
|
+
// One row empty never hides the other. The titles only once the cards
|
|
298
|
+
// are in, so a row that stays hidden leaves none behind; bought
|
|
299
|
+
// together's only over a real pair, else its cards show untitled, under
|
|
300
|
+
// the blank line held for the title (none for an empty title).
|
|
301
|
+
const name = show(first);
|
|
302
|
+
let after = '';
|
|
303
|
+
if (together.length) {
|
|
304
|
+
const titled = paired(together) && page.together;
|
|
305
|
+
const its = titled ? nameOf(`${TOGETHER}-title`) : name;
|
|
306
|
+
after += `${titled ? title(page.together, `${TOGETHER}-title`) : page.together ? untitled() : ''}<div id="${TOGETHER}" role="region"${nameAttribute(its)}>${styleOf(TOGETHER)}${listOf(together, its)}</div>`;
|
|
328
307
|
}
|
|
308
|
+
if (seen.length) after += recentRow(seen);
|
|
309
|
+
if (after) slot.insertAdjacentHTML('afterend', after);
|
|
329
310
|
};
|
|
330
311
|
// recommendLists() rejects only on a bad request: a page still loses no more than its rows.
|
|
331
312
|
const fill = () => draw().catch((error) => {
|
|
332
|
-
|
|
313
|
+
unheld();
|
|
314
|
+
if (!standIn) hide(slot);
|
|
333
315
|
console.warn('recapi:', error);
|
|
334
316
|
});
|
|
335
|
-
//
|
|
336
|
-
|
|
337
|
-
// never scrolls down saw none. The slot's min-height holds its place
|
|
338
|
-
// meanwhile. The view above went at once.
|
|
339
|
-
if (slot && typeof IntersectionObserver !== 'function') await fill();
|
|
340
|
-
else if (slot) {
|
|
341
|
-
const observer = new IntersectionObserver((entries) => {
|
|
342
|
-
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
343
|
-
observer.disconnect();
|
|
344
|
-
return fill();
|
|
345
|
-
}, { rootMargin: '0px 0px 400px 0px' });
|
|
346
|
-
observer.observe(slot);
|
|
347
|
-
}
|
|
317
|
+
// The slot's min-height holds its place meanwhile. The view above went at once.
|
|
318
|
+
if (slot) await near([slot], fill);
|
|
348
319
|
}
|