@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/page.js
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a product page tells search engines about its product, read as
|
|
3
|
+
* recapi's server reads it (server/internal/pageproduct; the shared pages
|
|
4
|
+
* are spec/page_product_vectors.json): schema.org Product in JSON-LD, then
|
|
5
|
+
* microdata, then Open Graph when it calls the page a product. Only what a browser sends:
|
|
6
|
+
* the name, category and the page's own address, never a picture or price,
|
|
7
|
+
* which recapi takes from nobody's browser.
|
|
8
|
+
*
|
|
9
|
+
* @module page
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/** The items API's title cap, in UTF-8 bytes. */
|
|
13
|
+
const MAX_NAME = 512;
|
|
14
|
+
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The page's JSON-LD blocks, meta tags and the properties of its first
|
|
18
|
+
* microdata Product, as the browser parsed them.
|
|
19
|
+
*
|
|
20
|
+
* @param {Document} doc
|
|
21
|
+
* @returns {{ scripts: string[], metas: Array<[string, string]>, micro: Array<[string, string]> | null }}
|
|
22
|
+
*/
|
|
23
|
+
export function pageOf(doc) {
|
|
24
|
+
const scripts = [];
|
|
25
|
+
for (const s of doc.querySelectorAll('script')) {
|
|
26
|
+
if ((s.getAttribute('type') ?? '').toLowerCase() === 'application/ld+json') scripts.push(s.textContent ?? '');
|
|
27
|
+
}
|
|
28
|
+
const metas = [];
|
|
29
|
+
for (const m of doc.querySelectorAll('meta')) metas.push([m.getAttribute('property') || m.getAttribute('name') || '', m.getAttribute('content') ?? '']);
|
|
30
|
+
let micro = null;
|
|
31
|
+
const scope = [...doc.querySelectorAll('[itemscope]')].find((e) => /schema\.org\/Product(Group)?$/.test(e.getAttribute('itemtype') ?? ''));
|
|
32
|
+
if (scope) {
|
|
33
|
+
micro = [];
|
|
34
|
+
for (const e of scope.querySelectorAll('[itemprop]')) {
|
|
35
|
+
// The product's own properties only: a review's or a brand's name sits in a scope of its own.
|
|
36
|
+
let up = e.parentElement;
|
|
37
|
+
while (up && up !== scope && up.getAttribute('itemscope') === null) up = up.parentElement;
|
|
38
|
+
if (up !== scope) continue;
|
|
39
|
+
const value = e.getAttribute('content') ?? e.getAttribute('href') ?? e.getAttribute('src') ?? e.textContent ?? '';
|
|
40
|
+
for (const prop of (e.getAttribute('itemprop') ?? '').split(/\s+/)) micro.push([prop, value]);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { scripts, metas, micro };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The page's product, or null when it carries no product markup. JSON-LD
|
|
48
|
+
* wins field by field, then microdata, then Open Graph. `url` is on the host of `at`
|
|
49
|
+
* (the page's address), else the page's own address without its query: a
|
|
50
|
+
* visitor's click and campaign ids ride there, and a site whose product
|
|
51
|
+
* address needs a query names it in its markup.
|
|
52
|
+
*
|
|
53
|
+
* @param {{ scripts: string[], metas: Array<[string, string]>, micro?: Array<[string, string]> | null }} page
|
|
54
|
+
* @param {string} at
|
|
55
|
+
* @returns {{ name: string, url: string, category: string } | null}
|
|
56
|
+
*/
|
|
57
|
+
export function readProduct(page, at) {
|
|
58
|
+
const p = read(page, at);
|
|
59
|
+
return p && { name: p.name, url: p.url, category: p.category };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The id of the page's product for a site that sends none of its own, or ''
|
|
64
|
+
* when the page carries no product markup: the address the markup names on
|
|
65
|
+
* the page's host, else the page's own, by `addressId`. Never the page's
|
|
66
|
+
* `sku`: most pages print none, and two rules in one shop would split its
|
|
67
|
+
* products.
|
|
68
|
+
*
|
|
69
|
+
* @param {{ scripts: string[], metas: Array<[string, string]>, micro?: Array<[string, string]> | null }} page
|
|
70
|
+
* @param {string} at
|
|
71
|
+
* @returns {string}
|
|
72
|
+
*/
|
|
73
|
+
export function pageProductId(page, at) {
|
|
74
|
+
const p = read(page, at);
|
|
75
|
+
return p ? addressId(p.own || at) : '';
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* The shape of an id the API makes (internal/ids: rec_ and hex), the only one
|
|
80
|
+
* read from an address: any other value is the site's own. Internal, shared
|
|
81
|
+
* with client.js, cards.js and shops.js; index.js doesn't export it.
|
|
82
|
+
*/
|
|
83
|
+
export const REC_ID = /^rec_[0-9a-f]+$/;
|
|
84
|
+
|
|
85
|
+
/** The API's id cap, in UTF-8 bytes. */
|
|
86
|
+
const MAX_ID = 256;
|
|
87
|
+
|
|
88
|
+
// What ad networks and mail tools add to a link to name the visitor or the
|
|
89
|
+
// campaign, never the product: the server's clickIDs (api/products_seen.go).
|
|
90
|
+
const CLICK_IDS = new Set(['gclid', 'gbraid', 'wbraid', 'dclid', 'fbclid', 'msclkid', 'ttclid', 'twclid', 'li_fat_id', 'yclid', 'igshid', 'srsltid', 'mc_cid', 'mc_eid', '_hsenc', '_hsmi', '_ga', '_gl']);
|
|
91
|
+
|
|
92
|
+
// What shop software adds to a product's address for one visitor: a session
|
|
93
|
+
// kept in the link when cookies are off, the currency or language switch
|
|
94
|
+
// (PrestaShop's SubmitCurrency, Shopware 5's __shop, xt:Commerce's XTCsid,
|
|
95
|
+
// Magento's ___store, Shopify's search trail _pos/_sid/_ss). Kept, one
|
|
96
|
+
// product would get one id per currency, or per visitor. Not `_locale`: a
|
|
97
|
+
// shop on the sample keeps its product's path in it.
|
|
98
|
+
const SWITCHES = new Set(['phpsessid', 'sid', 'sessionid', 'session_id', 'jsessionid', 'force_sid', 'xtcsid', 'oscsid', 'modsid', 'zenid', 'scoreid', 'stoken',
|
|
99
|
+
'submitcurrency', 'id_currency', 'currency', 'cur', '__currency', 'aelia_cs_currency',
|
|
100
|
+
'id_lang', 'lang', 'language', '__shop', '__redirect', '___store', '___from_store',
|
|
101
|
+
'_pos', '_sid', '_ss', '_psq', '_fid', '_v']);
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* A product id from its address (spec/page_product_vectors.json): path and
|
|
105
|
+
* query without scheme, host or fragment, percent-decoded where that keeps
|
|
106
|
+
* it readable, one trailing slash dropped, click and campaign ids and a
|
|
107
|
+
* visitor's session, currency and language switch dropped from the query
|
|
108
|
+
* and the site's own kept (a product addressed by
|
|
109
|
+
* `?product_id=40`). Over 256 bytes, a prefix and a hash of the whole: the
|
|
110
|
+
* same address always gives the same id. '' when `raw` is no http(s) address.
|
|
111
|
+
*
|
|
112
|
+
* @param {string} raw
|
|
113
|
+
* @returns {string}
|
|
114
|
+
*/
|
|
115
|
+
export function addressId(raw) {
|
|
116
|
+
let u;
|
|
117
|
+
try {
|
|
118
|
+
u = new URL(raw);
|
|
119
|
+
} catch {
|
|
120
|
+
return '';
|
|
121
|
+
}
|
|
122
|
+
if (u.protocol !== 'https:' && u.protocol !== 'http:') return '';
|
|
123
|
+
const query = u.search.slice(1).split('&').filter((pair) => {
|
|
124
|
+
if (pair === '') return false;
|
|
125
|
+
const [name, ...rest] = pair.split('=');
|
|
126
|
+
// A card's own `?rec=rec_…` credits the click, then leaves the address
|
|
127
|
+
// (client.js landed()): kept, the product would have a second id for the
|
|
128
|
+
// view that carries the credit. The site's own `?rec=1` stays.
|
|
129
|
+
if (name === 'rec' && REC_ID.test(rest.join('='))) return false;
|
|
130
|
+
let key = name;
|
|
131
|
+
try {
|
|
132
|
+
key = decodeURIComponent(key.replace(/\+/g, ' '));
|
|
133
|
+
} catch {}
|
|
134
|
+
key = key.toLowerCase();
|
|
135
|
+
return !CLICK_IDS.has(key) && !SWITCHES.has(key) && !key.startsWith('utm_');
|
|
136
|
+
}).join('&');
|
|
137
|
+
const path = u.pathname.length > 1 && u.pathname.endsWith('/') ? u.pathname.slice(0, -1) : u.pathname;
|
|
138
|
+
let id = query ? `${path}?${query}` : path;
|
|
139
|
+
try {
|
|
140
|
+
// decodeURI leaves reserved characters (/ ? & = #) encoded, so the
|
|
141
|
+
// decoded id still reads back to one address.
|
|
142
|
+
const decoded = decodeURI(id);
|
|
143
|
+
if (!/[\u0000-\u001f\u007f]/.test(decoded)) id = decoded;
|
|
144
|
+
} catch {}
|
|
145
|
+
return fit(id);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// Over the cap: the longest prefix cut on a character that leaves room for
|
|
149
|
+
// '~' and the FNV-1a 64 hash of the whole id's UTF-8, in 16 hex digits.
|
|
150
|
+
function fit(id) {
|
|
151
|
+
const bytes = new TextEncoder().encode(id);
|
|
152
|
+
if (bytes.length <= MAX_ID) return id;
|
|
153
|
+
let sum = 0xcbf29ce484222325n;
|
|
154
|
+
for (const b of bytes) sum = BigInt.asUintN(64, (sum ^ BigInt(b)) * 0x100000001b3n);
|
|
155
|
+
return `${cut(id, MAX_ID - 17)}~${sum.toString(16).padStart(16, '0')}`;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function read({ scripts, metas, micro = null }, at) {
|
|
159
|
+
let p = null;
|
|
160
|
+
const docs = [];
|
|
161
|
+
let node = null;
|
|
162
|
+
for (const text of scripts) {
|
|
163
|
+
try {
|
|
164
|
+
docs.push(JSON.parse(text));
|
|
165
|
+
} catch {
|
|
166
|
+
// Themes often print one broken block beside good ones.
|
|
167
|
+
continue;
|
|
168
|
+
}
|
|
169
|
+
node ??= findProduct(docs.at(-1), 0);
|
|
170
|
+
}
|
|
171
|
+
if (node) {
|
|
172
|
+
// Shoper splits one product over many blocks sharing its @id.
|
|
173
|
+
if (typeof node['@id'] === 'string' && node['@id']) for (const doc of docs) sameId(doc, node['@id'], node, 0);
|
|
174
|
+
const url = typeof node.url === 'string' ? onHost(node.url, at) : '';
|
|
175
|
+
p = { name: typeof node.name === 'string' ? clean(node.name) : '', url, own: url, category: category(node.category) };
|
|
176
|
+
}
|
|
177
|
+
if (micro) {
|
|
178
|
+
const prop = (k) => micro.find(([name]) => name === k)?.[1] ?? '';
|
|
179
|
+
p ??= { name: '', url: '', own: '', category: '' };
|
|
180
|
+
p.name ||= clean(prop('name'));
|
|
181
|
+
p.url ||= onHost(prop('url'), at);
|
|
182
|
+
p.own ||= p.url;
|
|
183
|
+
p.category ||= clean(prop('category'));
|
|
184
|
+
}
|
|
185
|
+
const og = {};
|
|
186
|
+
for (const [k, v] of metas) {
|
|
187
|
+
const key = k.toLowerCase();
|
|
188
|
+
if (key && !Object.hasOwn(og, key)) og[key] = v;
|
|
189
|
+
}
|
|
190
|
+
const type = (og['og:type'] ?? '').toLowerCase();
|
|
191
|
+
if (!p && (type === 'product' || type === 'og:product' || og['product:price:amount'] || og['og:price:amount'])) p = { name: '', url: '', own: '', category: '' };
|
|
192
|
+
if (!p) return null;
|
|
193
|
+
const site = clean(og['og:site_name'] ?? '');
|
|
194
|
+
// A " | Site" tail goes only when it names the page's own site.
|
|
195
|
+
const tail = [' | ', ' - ', ' – ', ' — '].map((sep) => sep + site).find((t) => site && clean(og['og:title'] ?? '').endsWith(t) && clean(og['og:title']).length > t.length);
|
|
196
|
+
p.name ||= tail ? clean(og['og:title']).slice(0, -tail.length) : clean(og['og:title'] ?? '');
|
|
197
|
+
p.category ||= clean(og['product:category'] ?? '');
|
|
198
|
+
p.own ||= onHost(og['og:url'] ?? '', at);
|
|
199
|
+
p.url ||= p.own || onHost(bare(at), at);
|
|
200
|
+
return p;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// One node, an array, a @graph wrapper (Yoast, Rank Math), a page whose
|
|
204
|
+
// mainEntity is the product.
|
|
205
|
+
function findProduct(v, depth) {
|
|
206
|
+
if (depth > 4 || v === null || typeof v !== 'object') return null;
|
|
207
|
+
if (Array.isArray(v)) {
|
|
208
|
+
for (const e of v) {
|
|
209
|
+
const p = findProduct(e, depth + 1);
|
|
210
|
+
if (p) return p;
|
|
211
|
+
}
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
const types = Array.isArray(v['@type']) ? v['@type'] : [v['@type']];
|
|
215
|
+
if (types.some((t) => typeof t === 'string' && ['Product', 'ProductGroup'].includes(t.slice(Math.max(t.lastIndexOf('/'), t.lastIndexOf(':')) + 1)))) return v;
|
|
216
|
+
return findProduct(v['@graph'], depth + 1) ?? findProduct(v.mainEntity, depth + 1);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// Fills node's missing fields from every node of v with its id.
|
|
220
|
+
function sameId(v, id, node, depth) {
|
|
221
|
+
if (depth > 4 || v === null || typeof v !== 'object') return;
|
|
222
|
+
if (Array.isArray(v)) {
|
|
223
|
+
for (const e of v) sameId(e, id, node, depth + 1);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (v['@id'] === id) for (const k of Object.keys(v)) if (!Object.hasOwn(node, k)) node[k] = v[k];
|
|
227
|
+
sameId(v['@graph'], id, node, depth + 1);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function category(v) {
|
|
231
|
+
if (typeof v === 'string') return clean(v);
|
|
232
|
+
if (Array.isArray(v)) {
|
|
233
|
+
const first = v.find((e) => typeof e === 'string' && e.trim() !== '');
|
|
234
|
+
if (first) return clean(first);
|
|
235
|
+
}
|
|
236
|
+
return '';
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// The entities some themes leave in JSON-LD unescaped, spaces collapsed, at
|
|
240
|
+
// most 512 bytes cut on a character.
|
|
241
|
+
function clean(s) {
|
|
242
|
+
const text = s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e) => {
|
|
243
|
+
if (e[0] !== '#') return ENTITIES[e.toLowerCase()] ?? m;
|
|
244
|
+
const code = e[1] === 'x' || e[1] === 'X' ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
|
245
|
+
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : m;
|
|
246
|
+
}).split(/\s+/).filter(Boolean).join(' ');
|
|
247
|
+
return cut(text, MAX_NAME);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
// At most `max` bytes of UTF-8, cut on a character.
|
|
251
|
+
function cut(text, max) {
|
|
252
|
+
let out = '';
|
|
253
|
+
let bytes = 0;
|
|
254
|
+
for (const ch of text) {
|
|
255
|
+
const n = ch.codePointAt(0) < 0x80 ? 1 : ch.codePointAt(0) < 0x800 ? 2 : ch.codePointAt(0) < 0x10000 ? 3 : 4;
|
|
256
|
+
if (bytes + n > max) break;
|
|
257
|
+
out += ch;
|
|
258
|
+
bytes += n;
|
|
259
|
+
}
|
|
260
|
+
return out;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* The page's http(s) address with no query or fragment, else ''.
|
|
265
|
+
*
|
|
266
|
+
* @param {string} at
|
|
267
|
+
* @returns {string}
|
|
268
|
+
*/
|
|
269
|
+
export function bare(at) {
|
|
270
|
+
try {
|
|
271
|
+
const u = new URL(at);
|
|
272
|
+
return u.protocol === 'https:' || u.protocol === 'http:' ? u.origin + u.pathname : '';
|
|
273
|
+
} catch {
|
|
274
|
+
return '';
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// An http(s) address on the page's host, resolved against it, else ''.
|
|
279
|
+
function onHost(s, at) {
|
|
280
|
+
if (s.trim() === '') return '';
|
|
281
|
+
try {
|
|
282
|
+
const u = new URL(s.trim(), at);
|
|
283
|
+
return (u.protocol === 'https:' || u.protocol === 'http:') && u.hostname !== '' && u.hostname === new URL(at).hostname ? u.href : '';
|
|
284
|
+
} catch {
|
|
285
|
+
return '';
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* `again` on each return to the page by Back or Forward that the browser
|
|
291
|
+
* shows from memory (the back/forward cache): none of the page's script runs
|
|
292
|
+
* again, and one page change in five on a phone is such a return.
|
|
293
|
+
*
|
|
294
|
+
* @param {() => void} again
|
|
295
|
+
* @returns {() => void} stops listening
|
|
296
|
+
*/
|
|
297
|
+
export function onReturn(again) {
|
|
298
|
+
const win = globalThis.window;
|
|
299
|
+
const shown = (event) => {
|
|
300
|
+
if (event.persisted) again();
|
|
301
|
+
};
|
|
302
|
+
win?.addEventListener?.('pageshow', shown);
|
|
303
|
+
return () => win?.removeEventListener?.('pageshow', shown);
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const NAVIGATED = 'recapi:navigate';
|
|
307
|
+
const PATCHED = Symbol.for('recapi.history');
|
|
308
|
+
// After a move without a reload, the page's product is read at these times
|
|
309
|
+
// (ms) until one differs from the last: a site builder swaps the markup after
|
|
310
|
+
// the address, at its own pace.
|
|
311
|
+
const AFTER_MOVE = [0, 300, 1000, 2500];
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Follows the page's product id (`pageProductId`) for calls that name none:
|
|
315
|
+
* `changed(id)` once the page is parsed ('' with no product), and again each
|
|
316
|
+
* time the id changes. A page with no product at first is read again at load
|
|
317
|
+
* and 2 s later (Square Online adds its markup by script). A site that moves
|
|
318
|
+
* between pages without reloading (Wix) is followed through pushState,
|
|
319
|
+
* replaceState and popstate; the same address twice is one page. Two copies
|
|
320
|
+
* of this library share one wrapper of `history`.
|
|
321
|
+
*
|
|
322
|
+
* `settled()`, if given, is called when a move's reads end on the same id:
|
|
323
|
+
* nothing changed, but the site may have drawn the page again.
|
|
324
|
+
* `returned(id)`, if given, is called when Back or Forward shows the page
|
|
325
|
+
* again from memory (`onReturn`), once its product is read.
|
|
326
|
+
*
|
|
327
|
+
* @param {(id: string) => void} changed
|
|
328
|
+
* @param {() => void} [settled]
|
|
329
|
+
* @param {(id: string) => void} [returned]
|
|
330
|
+
* @returns {() => void} stops following
|
|
331
|
+
*/
|
|
332
|
+
export function followProduct(changed, settled, returned) {
|
|
333
|
+
const win = globalThis.window;
|
|
334
|
+
const timers = new Set();
|
|
335
|
+
let id = null;
|
|
336
|
+
let move = 0;
|
|
337
|
+
let stopped = false;
|
|
338
|
+
const here = () => String(globalThis.location?.href ?? '').split('#')[0];
|
|
339
|
+
let address = here();
|
|
340
|
+
const readNow = () => {
|
|
341
|
+
try {
|
|
342
|
+
return pageProductId(pageOf(globalThis.document), String(globalThis.location?.href ?? ''));
|
|
343
|
+
} catch {
|
|
344
|
+
return '';
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
const later = (ms, fn) => {
|
|
348
|
+
const t = setTimeout(() => {
|
|
349
|
+
timers.delete(t);
|
|
350
|
+
if (!stopped) fn();
|
|
351
|
+
}, ms);
|
|
352
|
+
timers.add(t);
|
|
353
|
+
};
|
|
354
|
+
const take = (next) => {
|
|
355
|
+
if (next === id) return;
|
|
356
|
+
id = next;
|
|
357
|
+
changed(next);
|
|
358
|
+
};
|
|
359
|
+
const again = () => {
|
|
360
|
+
if (id === '' && move === 0) take(readNow());
|
|
361
|
+
};
|
|
362
|
+
const first = () => {
|
|
363
|
+
if (stopped) return;
|
|
364
|
+
take(readNow());
|
|
365
|
+
// Found at once, it stays: a later read of other markup would give the
|
|
366
|
+
// same product a second id.
|
|
367
|
+
if (id !== '') return;
|
|
368
|
+
if (globalThis.document.readyState === 'complete') later(2000, again);
|
|
369
|
+
else win?.addEventListener?.('load', () => {
|
|
370
|
+
again();
|
|
371
|
+
later(2000, again);
|
|
372
|
+
}, { once: true });
|
|
373
|
+
};
|
|
374
|
+
const moved = () => {
|
|
375
|
+
const now = here();
|
|
376
|
+
if (stopped || now === address) return;
|
|
377
|
+
address = now;
|
|
378
|
+
const before = id;
|
|
379
|
+
const mine = ++move;
|
|
380
|
+
const step = (k) => later(AFTER_MOVE[k] - (AFTER_MOVE[k - 1] ?? 0), () => {
|
|
381
|
+
if (mine !== move) return;
|
|
382
|
+
const next = readNow();
|
|
383
|
+
// The last page's markup, or none yet: the new one may still come.
|
|
384
|
+
if ((next === before || next === '') && k < AFTER_MOVE.length - 1) return step(k + 1);
|
|
385
|
+
if (next === id) settled?.();
|
|
386
|
+
else take(next);
|
|
387
|
+
});
|
|
388
|
+
step(0);
|
|
389
|
+
};
|
|
390
|
+
const history = globalThis.history;
|
|
391
|
+
if (win?.addEventListener && history && !history[PATCHED]) {
|
|
392
|
+
history[PATCHED] = true;
|
|
393
|
+
for (const name of ['pushState', 'replaceState']) {
|
|
394
|
+
const original = history[name];
|
|
395
|
+
if (typeof original !== 'function') continue;
|
|
396
|
+
history[name] = function (...args) {
|
|
397
|
+
const result = original.apply(this, args);
|
|
398
|
+
win.dispatchEvent(new Event(NAVIGATED));
|
|
399
|
+
return result;
|
|
400
|
+
};
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
win?.addEventListener?.(NAVIGATED, moved);
|
|
404
|
+
win?.addEventListener?.('popstate', moved);
|
|
405
|
+
const unreturn = returned ? onReturn(() => {
|
|
406
|
+
if (!stopped && id !== null) returned(id);
|
|
407
|
+
}) : () => {};
|
|
408
|
+
if (globalThis.document.readyState === 'loading') globalThis.document.addEventListener('DOMContentLoaded', first, { once: true });
|
|
409
|
+
else first();
|
|
410
|
+
return () => {
|
|
411
|
+
stopped = true;
|
|
412
|
+
for (const t of timers) clearTimeout(t);
|
|
413
|
+
timers.clear();
|
|
414
|
+
win?.removeEventListener?.(NAVIGATED, moved);
|
|
415
|
+
win?.removeEventListener?.('popstate', moved);
|
|
416
|
+
unreturn();
|
|
417
|
+
};
|
|
418
|
+
}
|
package/src/row.js
CHANGED
|
@@ -8,11 +8,51 @@
|
|
|
8
8
|
* @module row
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import { GRID, ROW, cardLink, cardStyle, carry,
|
|
11
|
+
import { GRID, ROW, addStyle, blankStyle, blanks, card, cardLink, cardStyle, carry, headingAbove, hide, listOf, nameOf, near, opened, openedOf, paired, pictureOf, region, title, untitled, wasOf } from './cards.js';
|
|
12
|
+
import { onReturn } from './page.js';
|
|
12
13
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
14
|
+
const CSS = `:where(.recapi-row ul){${GRID}}:where(.recapi-row ul,.recapi-bare ul){list-style:none;margin:0;padding:0}${cardStyle('.recapi-row')}${blankStyle('.recapi-row')}`;
|
|
15
|
+
|
|
16
|
+
const HELD = [...['margin', 'padding'].flatMap((box) => ['top', 'right', 'bottom', 'left'].map((side) => `${box}-${side}`)), 'list-style-type', 'list-style-image'];
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Keeps a site's rules for every list (`.content ul`) off the row's. Not the
|
|
20
|
+
* shops' listStyle(), whose weight would beat the documented `.recapi-row ul`:
|
|
21
|
+
* that one weighs the same as `.content ul`, so no selector of ours fits
|
|
22
|
+
* between them. A bare list beside the row tells them apart: what it gets too
|
|
23
|
+
* is every list's, what the row alone gets is its own.
|
|
24
|
+
* shortcut: read once per draw, so a rule naming the row that only a later
|
|
25
|
+
* width or style sheet brings, or that repeats every list's value, gives way
|
|
26
|
+
* to a held one; draw again on resize if a site meets it.
|
|
27
|
+
*/
|
|
28
|
+
function hold(el, count, titled) {
|
|
29
|
+
// A second one of a site's own component would run its code, which may call row() again.
|
|
30
|
+
const twin = document.createElement(el.localName.includes('-') ? 'div' : el.tagName);
|
|
31
|
+
twin.className = 'recapi-bare';
|
|
32
|
+
const own = [...el.querySelectorAll('ul,li')];
|
|
33
|
+
// A heading where the row has one: `h2 + ul` is every list's rule too.
|
|
34
|
+
twin.innerHTML = `${titled ? '<h2></h2>' : ''}<ul role="list">${'<li></li>'.repeat(count)}</ul>`;
|
|
35
|
+
el.after(twin);
|
|
36
|
+
const every = [...twin.querySelectorAll('ul,li')];
|
|
37
|
+
// Undisplayed, both give what the rules say: no used `auto`, no transition's start.
|
|
38
|
+
for (const box of [...own, ...every]) box.style.display = 'none';
|
|
39
|
+
// Every list's `3em` comes out the same under a text size of the row's own.
|
|
40
|
+
own.forEach((box, i) => { every[i].style.fontSize = getComputedStyle(box).fontSize; });
|
|
41
|
+
const read = (box) => { const style = getComputedStyle(box); return HELD.map((name) => style.getPropertyValue(name)); };
|
|
42
|
+
const held = own.map((box, i) => [read(box), read(every[i])]);
|
|
43
|
+
twin.remove();
|
|
44
|
+
own.forEach((box, i) => {
|
|
45
|
+
box.style.removeProperty('display');
|
|
46
|
+
const [its, theirs] = held[i];
|
|
47
|
+
HELD.forEach((name, k) => {
|
|
48
|
+
const none = name.startsWith('list') ? 'none' : '0px';
|
|
49
|
+
if (its[k] === theirs[k] && its[k] !== none) box.style.setProperty(name, none);
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The name a row's attributes give it. */
|
|
55
|
+
const called = (el) => document.getElementById(el.getAttribute('aria-labelledby'))?.textContent.trim() ?? el.getAttribute('aria-label');
|
|
16
56
|
|
|
17
57
|
/** The page's currency, as shops print it for search engines. */
|
|
18
58
|
function pageCurrency() {
|
|
@@ -32,45 +72,42 @@ export function rows(client) {
|
|
|
32
72
|
let group = null;
|
|
33
73
|
let sheet = false;
|
|
34
74
|
let unpriced = false;
|
|
75
|
+
const given = new WeakMap();
|
|
76
|
+
const hid = new WeakSet();
|
|
77
|
+
// Rows holding blank cards.
|
|
78
|
+
const blank = new WeakSet();
|
|
79
|
+
// A home page's Recently viewed rows, by slot: what each was drawn from.
|
|
80
|
+
const recent = new Map();
|
|
35
81
|
|
|
36
82
|
const style = () => {
|
|
37
83
|
if (sheet) return;
|
|
38
84
|
sheet = true;
|
|
39
|
-
|
|
40
|
-
// refuses a <style> element; browsers before Safari 16.4 get the element.
|
|
41
|
-
try {
|
|
42
|
-
const css = new CSSStyleSheet();
|
|
43
|
-
css.replaceSync(CSS);
|
|
44
|
-
document.adoptedStyleSheets = [...document.adoptedStyleSheets, css];
|
|
45
|
-
} catch {
|
|
46
|
-
const el = document.createElement('style');
|
|
47
|
-
el.textContent = CSS;
|
|
48
|
-
document.head.append(el);
|
|
49
|
-
}
|
|
85
|
+
addStyle(CSS);
|
|
50
86
|
};
|
|
51
87
|
|
|
52
88
|
const away = (el) => {
|
|
53
89
|
el.removeAttribute('aria-busy');
|
|
90
|
+
if (blank.delete(el)) el.innerHTML = '';
|
|
54
91
|
hide(el);
|
|
92
|
+
hid.add(el);
|
|
55
93
|
};
|
|
56
94
|
|
|
57
|
-
const
|
|
95
|
+
const item = ({ metadata: m, why }, recommendationId, money) => {
|
|
58
96
|
const link = cardLink(m);
|
|
59
97
|
if (!link) return null;
|
|
60
98
|
let price = typeof m.price === 'string' ? m.price : '';
|
|
99
|
+
let was = null;
|
|
61
100
|
if (typeof m.price === 'number') {
|
|
62
101
|
const currency = typeof m.currency === 'string' ? m.currency : money;
|
|
63
102
|
try {
|
|
64
|
-
|
|
103
|
+
const format = new Intl.NumberFormat(document.documentElement.lang || undefined, { style: 'currency', currency });
|
|
104
|
+
price = format.format(m.price);
|
|
105
|
+
was = wasOf(m, format.format);
|
|
65
106
|
} catch {
|
|
66
107
|
unpriced = true;
|
|
67
108
|
}
|
|
68
109
|
}
|
|
69
|
-
|
|
70
|
-
return `<li><a href="${escape(carry(link, recommendationId).href)}">` +
|
|
71
|
-
`${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
|
|
72
|
-
`<span class="recapi-name">${escape(m.name)}</span>` +
|
|
73
|
-
`${price ? `<span class="recapi-price">${escape(price)}</span>` : ''}</a></li>`;
|
|
110
|
+
return card(carry(link, recommendationId).href, pictureOf(m), m.name, price || null, ' class="recapi-name"', why, was);
|
|
74
111
|
};
|
|
75
112
|
|
|
76
113
|
const draw = (row, list) => {
|
|
@@ -78,7 +115,7 @@ export function rows(client) {
|
|
|
78
115
|
// A popular fallback is not what was bought together: that row stays away.
|
|
79
116
|
const together = placement === 'bought_together';
|
|
80
117
|
const money = pageCurrency();
|
|
81
|
-
const cards = list.fallback && together ? [] : list.items.map((
|
|
118
|
+
const cards = list.fallback && together ? [] : list.items.map((each) => ({ html: item(each, list.recommendationId, money), why: each.why })).filter(({ html }) => html);
|
|
82
119
|
if (!cards.length) {
|
|
83
120
|
if (list.items.length) {
|
|
84
121
|
const missing = ['name', 'url'].filter((key) => list.items.every(({ metadata }) => typeof metadata?.[key] !== 'string'));
|
|
@@ -86,21 +123,59 @@ export function rows(client) {
|
|
|
86
123
|
}
|
|
87
124
|
return away(el);
|
|
88
125
|
}
|
|
89
|
-
|
|
90
|
-
|
|
126
|
+
// Hidden by an earlier draw with no card, not by the site.
|
|
127
|
+
if (hid.delete(el)) {
|
|
128
|
+
el.hidden = false;
|
|
129
|
+
el.style.removeProperty('display');
|
|
130
|
+
}
|
|
131
|
+
el.id ||= `recapi-row-${Math.random().toString(36).slice(2)}`;
|
|
132
|
+
const titleId = `${el.id}-title`;
|
|
133
|
+
const shown = !together || paired(cards) ? heading : null;
|
|
134
|
+
// What the last draw gave the slot goes, unless the site has changed it since.
|
|
135
|
+
for (const [attribute, was, gave] of given.get(el) ?? []) {
|
|
136
|
+
if (el.getAttribute(attribute) !== gave) continue;
|
|
137
|
+
if (was === null) el.removeAttribute(attribute);
|
|
138
|
+
else el.setAttribute(attribute, was);
|
|
139
|
+
}
|
|
140
|
+
given.delete(el);
|
|
141
|
+
// Another client's draw may have left its title's id.
|
|
142
|
+
if (el.getAttribute('aria-labelledby') === titleId) el.removeAttribute('aria-labelledby');
|
|
143
|
+
const name = nameOf(shown ? titleId : el.getAttribute('aria-labelledby') || headingAbove(el), el.getAttribute('aria-label'));
|
|
144
|
+
blank.delete(el);
|
|
145
|
+
// A held title the row turned out not to have keeps its blank line: the page under it stays put.
|
|
146
|
+
el.innerHTML = (heading && !shown ? untitled() : title(shown, titleId)) + listOf(cards, name);
|
|
147
|
+
hold(el, cards.length, shown);
|
|
148
|
+
// A second landmark of the same name would say nothing: its list alone is named.
|
|
149
|
+
const words = name[0] === 'aria-label' ? name[1] : document.getElementById(name[1])?.textContent.trim();
|
|
150
|
+
const taken = [...document.querySelectorAll('.recapi-row[role=region]:not([hidden])')].some((row) => row !== el && called(row) === words);
|
|
151
|
+
if (!taken) {
|
|
152
|
+
const before = ['role', name[0]].map((attribute) => [attribute, el.getAttribute(attribute)]);
|
|
153
|
+
region(el, name);
|
|
154
|
+
given.set(el, before.map(([attribute, was]) => [attribute, was, el.getAttribute(attribute)]));
|
|
155
|
+
}
|
|
91
156
|
el.removeAttribute('aria-busy');
|
|
92
157
|
};
|
|
93
158
|
|
|
94
159
|
const fill = async (members) => {
|
|
95
160
|
try {
|
|
96
|
-
|
|
97
|
-
|
|
161
|
+
// A Recently viewed row with nothing opened in this browser is not asked for (shops.js fillRows).
|
|
162
|
+
const asked = members.filter(({ placement, contextItemId }) => placement !== 'recently_viewed' || opened(client, contextItemId));
|
|
163
|
+
const got = asked.length ? await client.recommendLists({
|
|
164
|
+
lists: asked.map(({ placement, contextItemId }) => ({
|
|
98
165
|
count: ROW,
|
|
99
166
|
...(placement ? { placement } : {}),
|
|
100
167
|
...(contextItemId ? { contextItemId } : {})
|
|
101
168
|
}))
|
|
102
|
-
});
|
|
169
|
+
}) : [];
|
|
170
|
+
const lists = members.map((row) => got[asked.indexOf(row)] ?? { items: [] });
|
|
103
171
|
members.forEach((row, k) => draw(row, lists[k]));
|
|
172
|
+
members.forEach((row, k) => {
|
|
173
|
+
recent.delete(row.el);
|
|
174
|
+
if (row.placement !== 'recently_viewed' || row.contextItemId) return;
|
|
175
|
+
const others = members.flatMap((each, i) => (i === k ? [] : lists[i].items.map(({ itemId }) => itemId)));
|
|
176
|
+
// A stand-in list (the call failed) is not what the history drew: the next Back asks again.
|
|
177
|
+
recent.set(row.el, { row, drawn: lists[k].fallback ? null : openedOf(client), others });
|
|
178
|
+
});
|
|
104
179
|
if (unpriced) {
|
|
105
180
|
unpriced = false;
|
|
106
181
|
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">');
|
|
@@ -112,6 +187,37 @@ export function rows(client) {
|
|
|
112
187
|
}
|
|
113
188
|
};
|
|
114
189
|
|
|
190
|
+
// Back or Forward to a home page the browser shows from memory: its
|
|
191
|
+
// Recently viewed row is drawn again, alone, when the visitor opened a
|
|
192
|
+
// product since, so it shows that product, and shows at all for a visitor
|
|
193
|
+
// who had opened none. Else nothing is asked: the same row would be one
|
|
194
|
+
// more billed list. The other rows keep their cards, and those products
|
|
195
|
+
// stay off this one. A row not yet drawn draws from the history then.
|
|
196
|
+
async function returned() {
|
|
197
|
+
for (const [el, each] of recent) {
|
|
198
|
+
if (!el.isConnected) {
|
|
199
|
+
recent.delete(el);
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
const now = openedOf(client);
|
|
203
|
+
if (now === each.drawn) continue;
|
|
204
|
+
// Refused (a key revoked since) or failed (the stand-in list): the row
|
|
205
|
+
// keeps its cards, and the next return asks again.
|
|
206
|
+
try {
|
|
207
|
+
const [list] = opened(client) ? await client.recommendLists({
|
|
208
|
+
lists: [{ count: ROW, placement: 'recently_viewed' }],
|
|
209
|
+
...(each.others.length ? { exclude: each.others } : {})
|
|
210
|
+
}) : [{ items: [] }];
|
|
211
|
+
if (list.fallback) continue;
|
|
212
|
+
each.drawn = now;
|
|
213
|
+
draw(each.row, list);
|
|
214
|
+
} catch (error) {
|
|
215
|
+
console.warn('recapi:', error);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
onReturn(returned);
|
|
220
|
+
|
|
115
221
|
// Each list is billed and counted as shown: a visitor who never scrolls
|
|
116
222
|
// down saw none.
|
|
117
223
|
const watch = (members) => near(members.map(({ el }) => el), () => fill(members));
|
|
@@ -125,6 +231,14 @@ export function rows(client) {
|
|
|
125
231
|
style();
|
|
126
232
|
el.classList.add('recapi-row');
|
|
127
233
|
el.setAttribute('aria-busy', 'true');
|
|
234
|
+
// While the list loads the row holds blank cards, and its title's line,
|
|
235
|
+
// where the real ones will be: a fixed height was a third of a phone's
|
|
236
|
+
// two lines of cards, and the page under it jumped. A slot the site
|
|
237
|
+
// filled with its own content keeps it until the cards come.
|
|
238
|
+
if (!el.innerHTML.trim() || blank.has(el)) {
|
|
239
|
+
el.innerHTML = title(heading ? '\u00a0' : '') + blanks();
|
|
240
|
+
blank.add(el);
|
|
241
|
+
}
|
|
128
242
|
if (!group) {
|
|
129
243
|
group = [];
|
|
130
244
|
queueMicrotask(() => {
|