@recapi/client 0.11.2 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +59 -1
- package/package.json +1 -1
- package/src/magento.js +262 -0
- package/src/woocommerce.js +334 -0
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ are, gzipped, and browsers cache them:
|
|
|
35
35
|
|
|
36
36
|
```html
|
|
37
37
|
<script type="module">
|
|
38
|
-
import { createClient } from 'https://api.example.com/sdk/0.
|
|
38
|
+
import { createClient } from 'https://api.example.com/sdk/0.13.0/index.js';
|
|
39
39
|
|
|
40
40
|
const recapi = createClient({ apiKey: 'rk_pub_…', baseUrl: 'https://api.example.com', consent: false });
|
|
41
41
|
// From your cookie banner, once the visitor agrees: recapi.setConsent(true).
|
|
@@ -508,6 +508,30 @@ nothing, and can't show what WordPress.org would do with a same-named listing.
|
|
|
508
508
|
Nothing answers that filter yet, so a shop gets no update notice. A snippet
|
|
509
509
|
install has neither header's effect: both are comments there.
|
|
510
510
|
|
|
511
|
+
#### The served page code
|
|
512
|
+
|
|
513
|
+
From 0.12.0 the plugin's page script holds only what PHP knows about the page
|
|
514
|
+
and the shop's key: it imports `/sdk/<version>/woocommerce.js` from your API
|
|
515
|
+
and makes one call. The API serves that file beside `index.js`, with the same
|
|
516
|
+
day of cache, and an older version's address redirects to it. So a fix of the
|
|
517
|
+
row, consent or the events reaches every shop within a day, with nothing to
|
|
518
|
+
install again. A fix of the plugin's PHP (product sync, paid orders, settings)
|
|
519
|
+
still needs the new file.
|
|
520
|
+
|
|
521
|
+
The call and its options are a contract from 0.12.0 on: options may be added,
|
|
522
|
+
never renamed or dropped, as shops keep the plugin they installed.
|
|
523
|
+
|
|
524
|
+
| Call | Options |
|
|
525
|
+
|---|---|
|
|
526
|
+
| `woocommercePage(options)` | `apiKey`, `baseUrl`, `platform`; `page`, as PHP prints it: `products` (the Store API's products address), `product` (the product page's id, `null` elsewhere), `placement` (`product`, `cart` or `shortcode`), `heading` (the row's title, `null` for none), `together` (the second row's title, `null` when turned off), `orders` (`true` with a secret key: keep the `recapi` cookie), `consent` (`wp-consent-api`, `banner` or `no-banner`), `currency` (the shop's, `null` while the visitor browses in another), `order` (`items` and `customer` on the order-received page, else `null`). Resolves once the page's work is set up. |
|
|
527
|
+
|
|
528
|
+
Every plugin the quick start ever printed is kept in
|
|
529
|
+
`test/fixtures/woocommerce/<version>/` (0.11.2: the last one holding its own
|
|
530
|
+
page code), and `test/woocommerce_published.test.js` runs every case of
|
|
531
|
+
`test/woocommerce.test.js` through each against the current `src/`: a change
|
|
532
|
+
to the page script needs a new fixture, and a change to the served code must
|
|
533
|
+
keep every older plugin working.
|
|
534
|
+
|
|
511
535
|
### Magento
|
|
512
536
|
|
|
513
537
|
The Magento 2 module ([guide](https://recapi.io/docs/magento)) prints
|
|
@@ -519,6 +543,32 @@ pages it fills recapi's row, drawing each card from the item's `metadata`
|
|
|
519
543
|
or, without it, from the store; the row is printed with the store's own
|
|
520
544
|
products, which stay while recapi has none.
|
|
521
545
|
|
|
546
|
+
#### The served storefront code
|
|
547
|
+
|
|
548
|
+
From module 0.4.25 (library 0.13.0) the module's template holds only what
|
|
549
|
+
Magento knows about the page and the store's key: it imports
|
|
550
|
+
`/sdk/<version>/magento.js` from your API and makes one call, on Luma and on
|
|
551
|
+
Hyvä alike. The API serves that file beside `index.js`, with the same day of
|
|
552
|
+
cache, and an older version's address redirects to it. So a fix of the row,
|
|
553
|
+
consent or the events reaches every store within a day, with nothing to
|
|
554
|
+
install again. A fix of the module's PHP (catalog sync, orders) still needs
|
|
555
|
+
`composer update` or the new zip. The module's Content Security Policy
|
|
556
|
+
already allows the API's host, which serves both files.
|
|
557
|
+
|
|
558
|
+
The call and its options are a contract from 0.13.0 on: options may be added,
|
|
559
|
+
never renamed or dropped, as stores keep the module they installed.
|
|
560
|
+
|
|
561
|
+
| Call | Options |
|
|
562
|
+
|---|---|
|
|
563
|
+
| `magentoPage(page)` | `page`, as the module's block prints it: `api` (your API's address), `key` (the public key), `platform` (`magento/<module version>`), `product` (the product page's id, `null` elsewhere), `placement` (`product`, `cart` or `block`), `cookieRestriction` (`true` when Cookie Restriction Mode is on), `website` (the website's id, the key of the cookie notice's answer), `cards` (the store's card lookup for products without metadata), `currency` (the store's base currency, `null` while the visitor browses in another), `sdk` (the address it was imported from). Resolves once the page's work is set up. |
|
|
564
|
+
|
|
565
|
+
The storefront code of every module version is kept in
|
|
566
|
+
`test/fixtures/magento/<version>/` (`Block/Script.php` and the template;
|
|
567
|
+
0.4.24: the last one holding its own page code), and
|
|
568
|
+
`test/magento_published.test.js` runs every case of `test/magento.test.js`
|
|
569
|
+
through each against the current `src/`: a change to that code needs a new
|
|
570
|
+
fixture, and a change to the served code must keep every older module working.
|
|
571
|
+
|
|
522
572
|
### Node
|
|
523
573
|
|
|
524
574
|
```js
|
|
@@ -1052,6 +1102,14 @@ minifier, to keep zero dev dependencies.
|
|
|
1052
1102
|
|
|
1053
1103
|
## Changes
|
|
1054
1104
|
|
|
1105
|
+
- 2026-11-20: version 0.13.0. `magento.js`, served beside `index.js` with
|
|
1106
|
+
its day of cache: the Magento module's storefront code (the rows, consent,
|
|
1107
|
+
the view and the add-to-cart events). The module now prints only the page's
|
|
1108
|
+
values, so later fixes reach a store with nothing to install again.
|
|
1109
|
+
- 2026-11-20: version 0.12.0. `woocommerce.js`, served beside `index.js`
|
|
1110
|
+
with its day of cache: the WooCommerce plugin's page code (the rows,
|
|
1111
|
+
consent, cart and purchase events). The plugin now prints only the page's
|
|
1112
|
+
values, so later fixes reach a shop with nothing to install again.
|
|
1055
1113
|
- 2026-11-19: version 0.11.2. An API error's `docsUrl` is the address of
|
|
1056
1114
|
its section on the errors page, and its message ends with it.
|
|
1057
1115
|
- 2026-11-19: version 0.11.1. No code change: this page's links lead to
|
package/package.json
CHANGED
package/src/magento.js
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a Magento store's pages run: the visitor's consent (Cookie Restriction
|
|
3
|
+
* Mode), the add-to-cart events, the product view and the rows in
|
|
4
|
+
* `#recapi-recommendations` and `#recapi-bought-together`. The module's
|
|
5
|
+
* template (sdk/php/magento/view/frontend/templates/script.phtml) prints only
|
|
6
|
+
* what Magento knows about the page and imports this file from the API, on
|
|
7
|
+
* Luma and on Hyvä alike, so a fix here reaches every store within a day (the
|
|
8
|
+
* entry's cache), with nothing to install again. Its options are a contract:
|
|
9
|
+
* add, never rename or drop one (each published module's storefront code is a
|
|
10
|
+
* test fixture, test/fixtures/magento/).
|
|
11
|
+
*
|
|
12
|
+
* A file of its own rather than exports of index.js, which every other site
|
|
13
|
+
* loads: they would download a Magento row they never draw.
|
|
14
|
+
*
|
|
15
|
+
* @module @recapi/client/magento
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
import { createClient } from './index.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Runs a page of the store. Resolves once the page's work is set up (the row
|
|
22
|
+
* loads later, as the shopper scrolls near it, or at once without
|
|
23
|
+
* IntersectionObserver).
|
|
24
|
+
*
|
|
25
|
+
* @param {{ api: string, key: string, platform: string, product: string|null,
|
|
26
|
+
* placement: string, cookieRestriction: boolean, website: string,
|
|
27
|
+
* cards: string, currency: string|null }} page
|
|
28
|
+
*/
|
|
29
|
+
export async function magentoPage(page) {
|
|
30
|
+
// The server sends the orders and can't read the browser's storage: each
|
|
31
|
+
// time the library saves the visitor's state, the "recapi" cookie gets what
|
|
32
|
+
// a purchase needs, the visitor's id and the recommendation each clicked
|
|
33
|
+
// product came from (the saved list entries that have a click time). The
|
|
34
|
+
// library saves only with consent. A day, as long as the library credits a
|
|
35
|
+
// click.
|
|
36
|
+
const secure = location.protocol === 'https:' ? '; secure' : '';
|
|
37
|
+
const cookie = (value, maxAge) => {
|
|
38
|
+
document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
|
|
39
|
+
};
|
|
40
|
+
const mirror = (saved) => {
|
|
41
|
+
let state;
|
|
42
|
+
try {
|
|
43
|
+
state = JSON.parse(saved);
|
|
44
|
+
} catch {
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
if (typeof state?.anonId !== 'string') return;
|
|
48
|
+
const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
|
|
49
|
+
// A browser drops a cookie over 4 KB: the products shown last stay.
|
|
50
|
+
let value;
|
|
51
|
+
do {
|
|
52
|
+
value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
|
|
53
|
+
} while (value.length > 3000 && clicked.shift());
|
|
54
|
+
cookie(value, 86400);
|
|
55
|
+
};
|
|
56
|
+
const storage = {
|
|
57
|
+
getItem: (key) => localStorage.getItem(key),
|
|
58
|
+
setItem: (key, value) => {
|
|
59
|
+
localStorage.setItem(key, value);
|
|
60
|
+
mirror(value);
|
|
61
|
+
},
|
|
62
|
+
removeItem: (key) => localStorage.removeItem(key)
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
// Magento's Cookie Restriction Mode is the store's consent switch: on, the
|
|
66
|
+
// visitor's device keeps nothing until they accept the cookie notice, which
|
|
67
|
+
// writes {"<website id>": 1} into user_allowed_save_cookie. Without consent
|
|
68
|
+
// events still go out, without a visitor id.
|
|
69
|
+
const allowed = () => {
|
|
70
|
+
if (!page.cookieRestriction) return true;
|
|
71
|
+
const raw = /(?:^|;\s*)user_allowed_save_cookie=([^;]*)/.exec(document.cookie)?.[1];
|
|
72
|
+
try {
|
|
73
|
+
return JSON.parse(decodeURIComponent(raw))[page.website] === 1;
|
|
74
|
+
} catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
const consent = allowed();
|
|
79
|
+
const recapi = createClient({ apiKey: page.key, baseUrl: page.api, consent, storage, platform: page.platform });
|
|
80
|
+
// A visitor who took their consent back (deleted the notice's cookie) leaves
|
|
81
|
+
// no ids for their next order.
|
|
82
|
+
if (!consent && /(?:^|;\s*)recapi=/.test(document.cookie)) cookie('', 0);
|
|
83
|
+
|
|
84
|
+
// Luma and its children announce through jQuery, which RequireJS loads:
|
|
85
|
+
// the cookie notice's accept and the Ajax add to cart, with its products.
|
|
86
|
+
const jquery = (use) => {
|
|
87
|
+
if (typeof window.require === 'function') window.require(['jquery'], use);
|
|
88
|
+
else if (window.jQuery) use(window.jQuery);
|
|
89
|
+
};
|
|
90
|
+
jquery(($) => {
|
|
91
|
+
$(document).on('user:allowed:save:cookie', () => recapi.setConsent(allowed()));
|
|
92
|
+
$(document).on('ajax:addToCart', (event, data) => {
|
|
93
|
+
for (const id of data?.productIds ?? []) if (id) recapi.track(String(id), 'cart');
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
// Hyvä's cookie notice announces the accept on the window instead: the
|
|
97
|
+
// consent applies on the same page there too, not only from the next one.
|
|
98
|
+
window.addEventListener('user-allowed-save-cookie', () => recapi.setConsent(allowed()));
|
|
99
|
+
// Themes without jQuery (Hyvä) post the add-to-cart form, and the next page
|
|
100
|
+
// loads: counted at the submit, once no script stopped it for an Ajax call.
|
|
101
|
+
// Window listeners run last, so defaultPrevented is final here.
|
|
102
|
+
window.addEventListener('submit', (event) => {
|
|
103
|
+
const form = event.target;
|
|
104
|
+
if (event.defaultPrevented || !/\/checkout\/cart\/add\b/.test(form?.action ?? '')) return;
|
|
105
|
+
const id = form.querySelector?.('[name="product"]')?.value;
|
|
106
|
+
if (id) recapi.track(String(id), 'cart');
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// The product id is the item id. A card's link carries its recommendation:
|
|
110
|
+
// without consent nothing on the device remembers which list showed it. In the
|
|
111
|
+
// fragment, which no server or page cache sees: an unknown ?rec= gave every
|
|
112
|
+
// click from the row its own entry in the full-page cache. ?rec= is still read:
|
|
113
|
+
// links already out there, and the cards that can't use a fragment (below).
|
|
114
|
+
const inFragment = /^#rec_[0-9a-f]+$/;
|
|
115
|
+
const viewed = () => {
|
|
116
|
+
const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
|
|
117
|
+
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
118
|
+
recapi.track(page.product, 'view', { recommendationId: linked });
|
|
119
|
+
// recapi credits an explicit id to whoever brings it: drop it from the
|
|
120
|
+
// address so a copied or shared link doesn't credit strangers' visits.
|
|
121
|
+
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
122
|
+
else if (linked !== null) {
|
|
123
|
+
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
124
|
+
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
// A browser may preload the link under the pointer, and a page it prerenders
|
|
128
|
+
// runs this script though nobody may ever open it: a click nobody made must
|
|
129
|
+
// not be credited.
|
|
130
|
+
if (page.product && document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
131
|
+
else if (page.product) viewed();
|
|
132
|
+
|
|
133
|
+
// recapi's row (the product page's recommendations block) arrives printed
|
|
134
|
+
// with the store's own products in it: recapi's cards replace them when it
|
|
135
|
+
// has some to show, else they stay. A product page has a second row under it,
|
|
136
|
+
// "Often bought together" (unless the store turned it off), printed hidden
|
|
137
|
+
// and empty: it shows only once recapi has products for it.
|
|
138
|
+
const slot = document.getElementById('recapi-recommendations');
|
|
139
|
+
const together = page.product ? document.getElementById('recapi-bought-together') : null;
|
|
140
|
+
const rows = [
|
|
141
|
+
{ slot, placement: page.placement },
|
|
142
|
+
...(slot && together ? [{ slot: together, placement: 'bought_together', together: true }] : [])
|
|
143
|
+
];
|
|
144
|
+
const blockOf = (element) => element.closest?.('.recapi-recommendations') ?? element;
|
|
145
|
+
const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
146
|
+
// Only http(s) addresses: metadata is the shop's, but a javascript: link
|
|
147
|
+
// must never reach the page.
|
|
148
|
+
const web = (address) => {
|
|
149
|
+
try {
|
|
150
|
+
const url = new URL(address, location.href);
|
|
151
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
152
|
+
} catch {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
};
|
|
156
|
+
const lang = document.documentElement?.lang || undefined;
|
|
157
|
+
const money = (amount) => {
|
|
158
|
+
if (typeof amount === 'string') return amount;
|
|
159
|
+
if (typeof amount !== 'number' || !Number.isFinite(amount) || !page.currency) return null;
|
|
160
|
+
try {
|
|
161
|
+
return new Intl.NumberFormat(lang, { style: 'currency', currency: page.currency }).format(amount);
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
};
|
|
166
|
+
// An item's metadata draws its card when it has a name and a link (and a
|
|
167
|
+
// price the visitor's currency can show); the others come from the store.
|
|
168
|
+
const fromMetadata = (metadata) => {
|
|
169
|
+
if (typeof metadata?.name !== 'string' || typeof metadata.url !== 'string' || !web(metadata.url)) return null;
|
|
170
|
+
const price = metadata.price === undefined || metadata.price === null ? '' : money(metadata.price);
|
|
171
|
+
if (price === null) return null;
|
|
172
|
+
return { name: metadata.name, url: metadata.url, picture: typeof metadata.picture === 'string' ? metadata.picture : '', price };
|
|
173
|
+
};
|
|
174
|
+
// A row shows 4 cards. recapi counts every product of a list as shown, so
|
|
175
|
+
// a spare asked for would get an impression and could be credited a view it
|
|
176
|
+
// never caused: each row asks for 4. recapi may not know a product sold out
|
|
177
|
+
// or was disabled since the last sync; one more call, for the rows left
|
|
178
|
+
// short only and without the products already listed, then fills the gaps.
|
|
179
|
+
const ROW = 4;
|
|
180
|
+
// Through the call that takes all of a page's rows: billed as one, the
|
|
181
|
+
// history sent once, and no product on two rows (the first row's go first).
|
|
182
|
+
// Each row its own placement.
|
|
183
|
+
const ask = (wanted, exclude) => recapi.recommendLists({
|
|
184
|
+
lists: wanted.map(({ count, placement }) => ({ count, placement, ...(page.product ? { contextItemId: page.product } : {}) })),
|
|
185
|
+
...(exclude.length ? { exclude } : {})
|
|
186
|
+
});
|
|
187
|
+
// A list's cards, in recapi's order, each with the list's id: those whose
|
|
188
|
+
// metadata draws them, the others from the store in one request.
|
|
189
|
+
const cardsOf = async ({ recommendationId, items }) => {
|
|
190
|
+
const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata)]));
|
|
191
|
+
const missing = [...cards].filter(([id, card]) => !card && /^\d+$/.test(id)).map(([id]) => id);
|
|
192
|
+
if (missing.length) {
|
|
193
|
+
const url = new URL(page.cards, location.href);
|
|
194
|
+
url.searchParams.set('ids', missing.join(','));
|
|
195
|
+
const response = await fetch(url.href, { headers: { Accept: 'application/json' } }).catch(() => null);
|
|
196
|
+
const found = (response?.ok ? await response.json().catch(() => null) : null)?.cards;
|
|
197
|
+
for (const card of Array.isArray(found) ? found : []) if (cards.has(String(card?.id))) cards.set(String(card.id), card);
|
|
198
|
+
}
|
|
199
|
+
return [...cards.values()].filter((card) => card && web(card.url)).map((card) => ({ ...card, recommendationId }));
|
|
200
|
+
};
|
|
201
|
+
const html = (cards) => cards.slice(0, ROW).map(({ recommendationId, ...card }) => {
|
|
202
|
+
const link = web(card.url);
|
|
203
|
+
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
204
|
+
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
205
|
+
// fragment wouldn't load it, so no view), or the page wouldn't read it back.
|
|
206
|
+
const open = link.href.split('#')[0] === location.href.split('#')[0];
|
|
207
|
+
if (recommendationId && (link.hash || open || !inFragment.test(`#${recommendationId}`))) link.searchParams.set('rec', recommendationId);
|
|
208
|
+
else if (recommendationId) link.hash = recommendationId;
|
|
209
|
+
const picture = web(card.picture);
|
|
210
|
+
return `<a href="${escape(link.href)}">${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
|
|
211
|
+
`<span>${escape(card.name)}</span>${card.price ? `<span class="recapi-price">${escape(card.price)}</span>` : ''}</a>`;
|
|
212
|
+
});
|
|
213
|
+
// Each row's cards, drawn as far as recapi got: a row never waits on, nor
|
|
214
|
+
// loses its cards to, the other row or a later call.
|
|
215
|
+
const draw = async () => {
|
|
216
|
+
const lists = await ask(rows.map(({ placement }) => ({ count: ROW, placement })), []);
|
|
217
|
+
// Popular items (recapi slow, down or at a limit) are no bought-together row.
|
|
218
|
+
const cards = await Promise.all(lists.map((list, i) => (rows[i].together && list.fallback ? [] : cardsOf(list))));
|
|
219
|
+
// Only a full list that couldn't fill its row: a shorter one means recapi
|
|
220
|
+
// has no more to give, and a fallback would only wait again.
|
|
221
|
+
const short = rows.map((row, i) => i).filter((i) => cards[i].length < ROW && lists[i].items.length >= ROW && !lists[i].fallback);
|
|
222
|
+
if (short.length) {
|
|
223
|
+
try {
|
|
224
|
+
const more = await ask(short.map((i) => ({ count: ROW - cards[i].length, placement: rows[i].placement })),
|
|
225
|
+
lists.flatMap(({ items }) => items.map(({ itemId }) => itemId)));
|
|
226
|
+
const extra = await Promise.all(more.map(cardsOf));
|
|
227
|
+
short.forEach((i, k) => cards[i].push(...extra[k]));
|
|
228
|
+
} catch (error) {
|
|
229
|
+
// Rejected (a key revoked mid-page): the cards of the first call stay.
|
|
230
|
+
console.warn('recapi:', error);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
rows.forEach((row, i) => {
|
|
234
|
+
const drawn = html(cards[i]);
|
|
235
|
+
if (drawn.length) {
|
|
236
|
+
row.slot.innerHTML = drawn.join('');
|
|
237
|
+
blockOf(row.slot).hidden = false;
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
};
|
|
241
|
+
// A row with no card at all (no store product either) hides, title included.
|
|
242
|
+
// A rejected request (a revoked key: recapi's own error) keeps the store's.
|
|
243
|
+
const fill = async () => {
|
|
244
|
+
await draw().catch(() => 0);
|
|
245
|
+
for (const row of rows) if (!row.slot.children.length) blockOf(row.slot).hidden = true;
|
|
246
|
+
};
|
|
247
|
+
// Only once the row comes within 400px of the screen, as Magento's lazy
|
|
248
|
+
// images load: each list is billed and counted as shown, and a shopper who
|
|
249
|
+
// never scrolls down saw none. The view above went at once. The block is
|
|
250
|
+
// watched, not the cards' div: with no store product that div is empty, and
|
|
251
|
+
// a theme hiding every empty div (div:empty { display: none }, Dawn's rule)
|
|
252
|
+
// would leave nothing to come near the screen; the block has its title.
|
|
253
|
+
if (slot && typeof IntersectionObserver !== 'function') await fill();
|
|
254
|
+
else if (slot) {
|
|
255
|
+
const observer = new IntersectionObserver((entries) => {
|
|
256
|
+
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
257
|
+
observer.disconnect();
|
|
258
|
+
return fill();
|
|
259
|
+
}, { rootMargin: '0px 0px 400px 0px' });
|
|
260
|
+
observer.observe(blockOf(slot));
|
|
261
|
+
}
|
|
262
|
+
}
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a WooCommerce shop's pages run: the visitor's consent, the cart and
|
|
3
|
+
* purchase events, and the rows in `#recapi-recommendations`. The plugin
|
|
4
|
+
* (sdk/js/woocommerce/recapi.php) prints only what PHP knows about the page
|
|
5
|
+
* and imports this file from the API, so a fix here reaches every shop
|
|
6
|
+
* within a day (the entry's cache), with nothing to install again. Its
|
|
7
|
+
* options are a contract: add, never rename or drop one (each published
|
|
8
|
+
* plugin is a test fixture, test/fixtures/woocommerce/).
|
|
9
|
+
*
|
|
10
|
+
* A file of its own rather than exports of index.js, which every other site
|
|
11
|
+
* loads: they would download a WooCommerce row they never draw.
|
|
12
|
+
*
|
|
13
|
+
* @module @recapi/client/woocommerce
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { createClient } from './index.js';
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Runs a page of the shop. Resolves once the page's work is set up (the row
|
|
20
|
+
* loads later, as the shopper scrolls near it, or at once without
|
|
21
|
+
* IntersectionObserver).
|
|
22
|
+
*
|
|
23
|
+
* @param {{ apiKey: string, baseUrl: string, platform: string, page: {
|
|
24
|
+
* products: string, product: string|null, placement: string,
|
|
25
|
+
* heading?: string|null, together?: string|null, orders?: boolean,
|
|
26
|
+
* consent: 'wp-consent-api'|'banner'|'no-banner'|string,
|
|
27
|
+
* currency?: string|null,
|
|
28
|
+
* order?: { items: string[], customer: string|null }|null } }} options
|
|
29
|
+
*/
|
|
30
|
+
export async function woocommercePage({ apiKey, baseUrl, platform, page }) {
|
|
31
|
+
// recapi keeps a history on the visitor's device only with their consent,
|
|
32
|
+
// and the merchant says on WooCommerce → recapi where it comes from. The WP
|
|
33
|
+
// Consent API (wordpress.org/plugins/wp-consent-api) carries the answer of
|
|
34
|
+
// the shop's cookie banner (Complianz, CookieYes…): Statistics consent. With
|
|
35
|
+
// the API but no banner it reports allowed; without the API nothing is
|
|
36
|
+
// stored, and events go out without a visitor id. Another banner calls
|
|
37
|
+
// recapi.setConsent(), maybe before this module ran: the head's stand-in
|
|
38
|
+
// kept its answer. A shop that needs no banner has consent from the start.
|
|
39
|
+
const answered = window.recapi?.consent;
|
|
40
|
+
const consent = page.consent === 'no-banner'
|
|
41
|
+
|| (page.consent === 'banner' && answered === true)
|
|
42
|
+
|| (page.consent === 'wp-consent-api' && typeof window.wp_has_consent === 'function' && window.wp_has_consent('statistics') === true);
|
|
43
|
+
// With a secret key the server sends the order once paid (the buyer may
|
|
44
|
+
// never see the order-received page) and can't read the browser's storage:
|
|
45
|
+
// each time the library saves the visitor's state, which it does only with
|
|
46
|
+
// consent, the "recapi" cookie gets what a purchase needs, the visitor's id
|
|
47
|
+
// and the recommendation each clicked product came from (the saved list
|
|
48
|
+
// entries with a click time). A day, as long as the library credits a click.
|
|
49
|
+
const secure = location.protocol === 'https:' ? '; secure' : '';
|
|
50
|
+
const cookie = (value, maxAge) => {
|
|
51
|
+
document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
|
|
52
|
+
};
|
|
53
|
+
const mirror = (saved) => {
|
|
54
|
+
let state;
|
|
55
|
+
try {
|
|
56
|
+
state = JSON.parse(saved);
|
|
57
|
+
} catch {
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (typeof state?.anonId !== 'string') return;
|
|
61
|
+
const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
|
|
62
|
+
// A browser drops a cookie over 4 KB: the products shown last stay.
|
|
63
|
+
let value;
|
|
64
|
+
do {
|
|
65
|
+
value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
|
|
66
|
+
} while (value.length > 3000 && clicked.shift());
|
|
67
|
+
cookie(value, 86400);
|
|
68
|
+
};
|
|
69
|
+
const storage = page.orders ? {
|
|
70
|
+
getItem: (key) => localStorage.getItem(key),
|
|
71
|
+
// The cookie first: a full storage quota throws, and the order still
|
|
72
|
+
// needs it.
|
|
73
|
+
setItem: (key, value) => {
|
|
74
|
+
mirror(value);
|
|
75
|
+
localStorage.setItem(key, value);
|
|
76
|
+
},
|
|
77
|
+
removeItem: (key) => {
|
|
78
|
+
localStorage.removeItem(key);
|
|
79
|
+
cookie('', 0);
|
|
80
|
+
}
|
|
81
|
+
} : undefined;
|
|
82
|
+
const recapi = createClient({ apiKey, baseUrl, consent, storage, platform });
|
|
83
|
+
// A visitor without consent (or who took it back) leaves no ids for their
|
|
84
|
+
// next order.
|
|
85
|
+
if (page.orders && !consent && /(?:^|;\s*)recapi=/.test(document.cookie ?? '')) cookie('', 0);
|
|
86
|
+
window.recapi = { setConsent: (value) => recapi.setConsent(value === true) };
|
|
87
|
+
if (page.consent === 'wp-consent-api') {
|
|
88
|
+
document.addEventListener('wp_listen_for_consent_change', (event) => {
|
|
89
|
+
const answer = event.detail?.statistics;
|
|
90
|
+
if (answer === 'allow' || answer === 'deny') recapi.setConsent(answer === 'allow');
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// An add to cart reports its product in three ways: the classic product
|
|
95
|
+
// page posts its form (the page then reloads: count it now), an Ajax button
|
|
96
|
+
// (shop pages, some themes) fires jQuery's added_to_cart, and a block's
|
|
97
|
+
// button fires wc-blocks_added_to_cart, with no product. A button carries
|
|
98
|
+
// its product in data-product_id. One click may fire both events: it
|
|
99
|
+
// counts once.
|
|
100
|
+
let clicked = null;
|
|
101
|
+
const added = () => {
|
|
102
|
+
if (clicked) recapi.track(clicked, 'cart');
|
|
103
|
+
clicked = null;
|
|
104
|
+
};
|
|
105
|
+
document.addEventListener('click', (event) => {
|
|
106
|
+
const id = event.target?.closest?.('[data-product_id]')?.getAttribute('data-product_id');
|
|
107
|
+
if (id) clicked = id;
|
|
108
|
+
}, true);
|
|
109
|
+
document.addEventListener('submit', (event) => {
|
|
110
|
+
const form = event.target;
|
|
111
|
+
const id = event.submitter?.name === 'add-to-cart' ? event.submitter.value : form?.querySelector?.('[name="add-to-cart"]')?.value;
|
|
112
|
+
if (!id) return;
|
|
113
|
+
clicked = id;
|
|
114
|
+
added();
|
|
115
|
+
}, true);
|
|
116
|
+
window.jQuery?.(document.body).on('added_to_cart', added);
|
|
117
|
+
document.body?.addEventListener('wc-blocks_added_to_cart', added);
|
|
118
|
+
|
|
119
|
+
// The product id is the item id: the widget loads products by it. A
|
|
120
|
+
// card's link carries its recommendation: without consent nothing on the
|
|
121
|
+
// device remembers which list showed the product. In the fragment, which no
|
|
122
|
+
// server or page cache sees: an unknown ?rec= made every click from the row
|
|
123
|
+
// miss the shop's page cache. ?rec= is still read: links already out there,
|
|
124
|
+
// and the cards that can't use a fragment (below).
|
|
125
|
+
const inFragment = /^#rec_[0-9a-f]+$/;
|
|
126
|
+
const viewed = () => {
|
|
127
|
+
const fragment = inFragment.test(location.hash) ? location.hash.slice(1) : null;
|
|
128
|
+
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
129
|
+
recapi.track(page.product, 'view', { recommendationId: linked });
|
|
130
|
+
// recapi credits an explicit id to whoever brings it: drop it from the
|
|
131
|
+
// address so a copied or shared link doesn't credit strangers' visits.
|
|
132
|
+
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
133
|
+
else if (linked !== null) {
|
|
134
|
+
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
135
|
+
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
// A browser may preload the link under the pointer, and a page it prerenders
|
|
139
|
+
// runs this script though nobody may ever open it: a click nobody made must
|
|
140
|
+
// not be credited.
|
|
141
|
+
if (page.product && document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
142
|
+
else if (page.product) viewed();
|
|
143
|
+
|
|
144
|
+
// The checkout is the shop's own page, so the purchases find the visitor
|
|
145
|
+
// and the recommendations they clicked where the product pages left them.
|
|
146
|
+
if (page.order) {
|
|
147
|
+
if (page.order.customer) recapi.identify(page.order.customer);
|
|
148
|
+
for (const item of page.order.items) recapi.track(item, 'purchase');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
// Fills <div id="recapi-recommendations"></div>. A merchant who pasted one
|
|
152
|
+
// before the plugin printed its own would see an empty second row: the
|
|
153
|
+
// first is filled, the others removed. Not hidden: the cards' grid rule
|
|
154
|
+
// below matches every slot and beats the browser's [hidden] rule.
|
|
155
|
+
const [slot, ...others] = document.querySelectorAll('#recapi-recommendations');
|
|
156
|
+
for (const other of others) other.remove();
|
|
157
|
+
// Not only [hidden]: any display rule of the theme's beats that one, and
|
|
158
|
+
// would leave the slot's 320px blank.
|
|
159
|
+
const hide = () => {
|
|
160
|
+
slot.hidden = true;
|
|
161
|
+
slot.style.setProperty('display', 'none', 'important');
|
|
162
|
+
};
|
|
163
|
+
// A product row in the theme's colours and fonts. :where() weighs
|
|
164
|
+
// nothing, so any rule of the theme's restyles the cards.
|
|
165
|
+
const style = '<style>' +
|
|
166
|
+
':where(#recapi-recommendations){display:grid;grid-template-columns:repeat(auto-fill,minmax(150px,1fr));gap:1rem;align-items:start;align-content:start}' +
|
|
167
|
+
':where(#recapi-recommendations a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
|
|
168
|
+
':where(#recapi-recommendations img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
|
|
169
|
+
':where(#recapi-recommendations .recapi-price){font-weight:600}' +
|
|
170
|
+
'</style>';
|
|
171
|
+
// A theme that hides every empty div (div:empty { display: none }, Dawn's
|
|
172
|
+
// rule) hides a slot pasted empty: it would never come near the screen
|
|
173
|
+
// and the row would never load. Its style, there at once, makes it not
|
|
174
|
+
// empty. A slot still without a box is hidden by the theme or a block
|
|
175
|
+
// around it: the row loads if that changes, and the console says why.
|
|
176
|
+
if (slot && !slot.getClientRects().length) {
|
|
177
|
+
slot.insertAdjacentHTML('afterbegin', style);
|
|
178
|
+
if (!slot.getClientRects().length) console.warn('recapi: the page hides #recapi-recommendations (display: none), so the row loads only once it shows');
|
|
179
|
+
}
|
|
180
|
+
// Each row shows 4 cards. recapi counts every product of a list as shown,
|
|
181
|
+
// so a spare asked for would get an impression and could be credited a
|
|
182
|
+
// view it never caused: a row asks for 4. Without a secret key recapi
|
|
183
|
+
// may not know a product sold out or was deleted; one more call, for the
|
|
184
|
+
// rows short of cards and without the products already listed, then
|
|
185
|
+
// fills the gaps.
|
|
186
|
+
const ROW = 4;
|
|
187
|
+
// A product page has a second row, bought together, which the script
|
|
188
|
+
// adds under the first once it has cards: the printed page stays the same
|
|
189
|
+
// for every shop and every page cache, and an empty row leaves nothing.
|
|
190
|
+
const TOGETHER = 'recapi-bought-together';
|
|
191
|
+
const rows = [{ placement: page.placement, heading: page.heading }];
|
|
192
|
+
if (page.product && page.together !== null) rows.push({ placement: 'bought_together', heading: page.together });
|
|
193
|
+
// Through the call that takes all of a page's rows (billed as one, the
|
|
194
|
+
// history sent once, no product on two rows): the first row first, so a
|
|
195
|
+
// product both would list stays on it. Each row under its own placement.
|
|
196
|
+
const ask = (wanted, exclude) => recapi.recommendLists({
|
|
197
|
+
lists: wanted.map(([row, count]) => ({ count, placement: row.placement, ...(page.product ? { contextItemId: page.product } : {}) })),
|
|
198
|
+
...(exclude.length ? { exclude } : {})
|
|
199
|
+
});
|
|
200
|
+
const draw = async () => {
|
|
201
|
+
const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
202
|
+
// Only http(s) addresses: metadata is the shop's, but a javascript: link
|
|
203
|
+
// must never reach the page.
|
|
204
|
+
const web = (address) => {
|
|
205
|
+
try {
|
|
206
|
+
const url = new URL(address, location.href);
|
|
207
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
|
|
208
|
+
} catch {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
// ?rec= only where a fragment can't carry the id: the address has its own
|
|
213
|
+
// (a theme's, not ours to overwrite), it's the page already open (a
|
|
214
|
+
// fragment wouldn't load it, so no view), or the page wouldn't read it back.
|
|
215
|
+
const link = (address, recommendationId) => {
|
|
216
|
+
const url = web(address);
|
|
217
|
+
if (!url || !recommendationId) return url?.href ?? null;
|
|
218
|
+
const open = url.href.split('#')[0] === location.href.split('#')[0];
|
|
219
|
+
if (url.hash || open || !inFragment.test(`#${recommendationId}`)) url.searchParams.set('rec', recommendationId);
|
|
220
|
+
else url.hash = recommendationId;
|
|
221
|
+
return url.href;
|
|
222
|
+
};
|
|
223
|
+
const lang = document.documentElement?.lang;
|
|
224
|
+
const money = (amount, currency) => {
|
|
225
|
+
try {
|
|
226
|
+
if (!lang || !currency || !Number.isFinite(amount)) return '';
|
|
227
|
+
return `<span class="recapi-price">${escape(new Intl.NumberFormat(lang, { style: 'currency', currency }).format(amount))}</span>`;
|
|
228
|
+
} catch {
|
|
229
|
+
return '';
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
// A metadata card without a usable picture gets no image at all.
|
|
233
|
+
const card = (href, picture, name, price) =>
|
|
234
|
+
`<a href="${escape(href)}">${picture !== undefined ? `<img src="${escape(picture)}" alt="" loading="lazy">` : ''}<span>${escape(name)}</span>${price}</a>`;
|
|
235
|
+
// An item's metadata (sent with PUT /v1/items) draws its card when it has
|
|
236
|
+
// a name and a link, with no request to the shop. Its price is text shown
|
|
237
|
+
// as it is, or a number in the shop's currency: a visitor browsing in
|
|
238
|
+
// another one (a currency switcher) gets the Store API's price instead.
|
|
239
|
+
const fromMetadata = (metadata, recommendationId) => {
|
|
240
|
+
const href = typeof metadata?.url === 'string' && typeof metadata.name === 'string' ? link(metadata.url, recommendationId) : null;
|
|
241
|
+
if (!href) return null;
|
|
242
|
+
let price = '';
|
|
243
|
+
if (typeof metadata.price === 'string') price = `<span class="recapi-price">${escape(metadata.price)}</span>`;
|
|
244
|
+
else if (typeof metadata.price === 'number') {
|
|
245
|
+
if (!page.currency) return null;
|
|
246
|
+
price = money(metadata.price, page.currency);
|
|
247
|
+
}
|
|
248
|
+
const picture = typeof metadata.picture === 'string' ? web(metadata.picture) : null;
|
|
249
|
+
return card(href, picture?.href, metadata.name, price);
|
|
250
|
+
};
|
|
251
|
+
// Product names come as HTML (WordPress turns quotes into entities).
|
|
252
|
+
const text = (html) => String(html ?? '').replace(/<[^>]*>/g, '').replace(/&(#\d+|#x[0-9a-f]+|amp|lt|gt|quot);/gi, (entity, name) => {
|
|
253
|
+
const named = { amp: '&', lt: '<', gt: '>', quot: '"' }[name.toLowerCase()];
|
|
254
|
+
if (named) return named;
|
|
255
|
+
const code = name[1] === 'x' || name[1] === 'X' ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
|
|
256
|
+
return code > 0 && code <= 0x10ffff ? String.fromCodePoint(code) : entity;
|
|
257
|
+
});
|
|
258
|
+
// Prices are in the currency's minor unit. A number and a symbol need
|
|
259
|
+
// no translation.
|
|
260
|
+
const price = ({ prices: p }) => money(Number(p?.price) / 10 ** p?.currency_minor_unit, p?.currency_code);
|
|
261
|
+
// A list's cards, in recapi's order: those whose metadata draws them, the
|
|
262
|
+
// others from WooCommerce's Store API (public, one request for all).
|
|
263
|
+
const cardsOf = async ({ recommendationId, items }) => {
|
|
264
|
+
const cards = new Map(items.map(({ itemId, metadata }) => [itemId, fromMetadata(metadata, recommendationId)]));
|
|
265
|
+
const ids = [...cards].filter(([id, html]) => !html && /^\d+$/.test(id)).map(([id]) => id);
|
|
266
|
+
let products = [];
|
|
267
|
+
if (ids.length) {
|
|
268
|
+
const url = new URL(page.products, location.href);
|
|
269
|
+
url.searchParams.set('include', ids.join(','));
|
|
270
|
+
url.searchParams.set('per_page', String(ids.length));
|
|
271
|
+
const response = await fetch(url.href).catch(() => null);
|
|
272
|
+
products = (response?.ok ? await response.json().catch(() => null) : null) ?? [];
|
|
273
|
+
}
|
|
274
|
+
for (const p of products) {
|
|
275
|
+
const href = link(p.permalink, recommendationId);
|
|
276
|
+
if (cards.has(String(p.id)) && p.is_purchasable && p.is_in_stock && href) {
|
|
277
|
+
cards.set(String(p.id), card(href, p.images?.[0]?.thumbnail || p.images?.[0]?.src || '', text(p.name), price(p)));
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return [...cards.values()].filter(Boolean);
|
|
281
|
+
};
|
|
282
|
+
const lists = await ask(rows.map((row) => [row, ROW]), []);
|
|
283
|
+
const shown = await Promise.all(lists.map(cardsOf));
|
|
284
|
+
// Only a full list that couldn't fill its row: a shorter one means
|
|
285
|
+
// recapi has no more to give, and a fallback (recapi slow, down or at a
|
|
286
|
+
// limit) would only wait again.
|
|
287
|
+
const short = lists.flatMap((list, i) => (shown[i].length < ROW && list.items.length >= ROW && !list.fallback ? [i] : []));
|
|
288
|
+
if (short.length) {
|
|
289
|
+
// A refused top-up (a key revoked mid-page) costs the gaps, never the
|
|
290
|
+
// cards the first call already found.
|
|
291
|
+
try {
|
|
292
|
+
const more = await ask(short.map((i) => [rows[i], ROW - shown[i].length]), lists.flatMap((list) => list.items.map(({ itemId }) => itemId)));
|
|
293
|
+
const cards = await Promise.all(more.map(cardsOf));
|
|
294
|
+
short.forEach((row, k) => shown[row].push(...cards[k]));
|
|
295
|
+
} catch (error) {
|
|
296
|
+
console.warn('recapi:', error);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
const [first, together] = shown.map((cards) => cards.slice(0, ROW));
|
|
300
|
+
// The theme's own h2 rule styles a heading. Added only once the cards
|
|
301
|
+
// are in, so a row that stays hidden leaves no title behind.
|
|
302
|
+
const heading = (text) => (text ? `<h2 class="recapi-heading">${escape(text)}</h2>` : '');
|
|
303
|
+
// One row empty never hides the other. A fallback (recapi slow, down or
|
|
304
|
+
// at a limit) is popular products, not what shoppers bought together:
|
|
305
|
+
// under that title it would mislead, so that row waits for the next page.
|
|
306
|
+
if (together?.length && !lists[1].fallback) {
|
|
307
|
+
slot.insertAdjacentHTML('afterend', `${heading(rows[1].heading)}<div id="${TOGETHER}">${style.replaceAll('recapi-recommendations', TOGETHER)}${together.join('')}</div>`);
|
|
308
|
+
}
|
|
309
|
+
if (first.length) {
|
|
310
|
+
slot.innerHTML = style + first.join('');
|
|
311
|
+
if (page.heading) slot.insertAdjacentHTML('beforebegin', heading(page.heading));
|
|
312
|
+
} else {
|
|
313
|
+
hide();
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
// recommendLists() rejects only on a bad request: a page still loses no more than its rows.
|
|
317
|
+
const fill = () => draw().catch((error) => {
|
|
318
|
+
hide();
|
|
319
|
+
console.warn('recapi:', error);
|
|
320
|
+
});
|
|
321
|
+
// Only once the row comes within 400px of the screen, as Shopify's themes
|
|
322
|
+
// load theirs: each list is billed and counted as shown, and a shopper who
|
|
323
|
+
// never scrolls down saw none. The slot's min-height holds its place
|
|
324
|
+
// meanwhile. The view above went at once.
|
|
325
|
+
if (slot && typeof IntersectionObserver !== 'function') await fill();
|
|
326
|
+
else if (slot) {
|
|
327
|
+
const observer = new IntersectionObserver((entries) => {
|
|
328
|
+
if (!entries.some((entry) => entry.isIntersecting)) return undefined;
|
|
329
|
+
observer.disconnect();
|
|
330
|
+
return fill();
|
|
331
|
+
}, { rootMargin: '0px 0px 400px 0px' });
|
|
332
|
+
observer.observe(slot);
|
|
333
|
+
}
|
|
334
|
+
}
|