@recapi/client 0.18.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +396 -40
- package/index.d.ts +18 -1
- package/package.json +1 -1
- package/src/cards.js +253 -0
- package/src/client.js +445 -19
- package/src/index.js +3 -1
- package/src/magento.js +183 -149
- package/src/page.js +418 -0
- package/src/row.js +145 -79
- package/src/shopify.js +190 -179
- package/src/shops.js +197 -0
- package/src/woocommerce.js +157 -186
package/src/shops.js
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the shop platforms' pages share and recapi.row() doesn't need. Each
|
|
3
|
+
* platform module keeps what only it knows: its page, its own cards for
|
|
4
|
+
* products without metadata, its currency, its consent.
|
|
5
|
+
*
|
|
6
|
+
* @module shops
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { REC_ID } from './client.js';
|
|
10
|
+
import { ROW, earlierFirst, hasEarlier, opened, openedOf } from './cards.js';
|
|
11
|
+
import { onReturn } from './page.js';
|
|
12
|
+
|
|
13
|
+
// Its home before the plain tag needed it too (page.js): older callers import it here.
|
|
14
|
+
export { onReturn };
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* A product page's view, credited to the list in the card's link (the
|
|
18
|
+
* fragment, or ?rec=: old links, cards that can't use a fragment), which
|
|
19
|
+
* then leaves the address: a shared link must not credit strangers' visits.
|
|
20
|
+
* A prerendered page (a link under the pointer) may never be opened.
|
|
21
|
+
*/
|
|
22
|
+
export function landing(recapi, item) {
|
|
23
|
+
const viewed = () => {
|
|
24
|
+
const fragment = REC_ID.test(location.hash.slice(1)) ? location.hash.slice(1) : null;
|
|
25
|
+
const linked = fragment ?? new URLSearchParams(location.search).get('rec');
|
|
26
|
+
recapi.track(item, 'view', { recommendationId: linked });
|
|
27
|
+
if (fragment !== null) history.replaceState(history.state, '', `${location.pathname}${location.search}`);
|
|
28
|
+
else if (linked !== null) {
|
|
29
|
+
// The other parameters (a variant) keep their exact text.
|
|
30
|
+
const query = location.search.slice(1).split('&').filter((p) => p.split('=')[0] !== 'rec').join('&');
|
|
31
|
+
history.replaceState(history.state, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
if (document.prerendering) document.addEventListener('prerenderingchange', viewed);
|
|
35
|
+
else viewed();
|
|
36
|
+
// The card's link left the address with the first view.
|
|
37
|
+
onReturn(() => recapi.track(item, 'view', { recommendationId: null }));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A home page's Recently viewed row (`row`) after a return by Back or
|
|
43
|
+
* Forward: drawn again, alone, when the visitor's history changed since the
|
|
44
|
+
* page's rows were drawn, so it shows the product just opened, and shows at
|
|
45
|
+
* all for a visitor who had opened none. Else nothing is asked: the same row
|
|
46
|
+
* would be one more billed list. The other rows stay as the visitor saw them,
|
|
47
|
+
* and their products stay off this one. `put(cards)` replaces the row's
|
|
48
|
+
* cards, none hiding it. `hold()`, called before the request, may hold the
|
|
49
|
+
* row's place, the page not yet painted again, and returns what undoes it
|
|
50
|
+
* when the row keeps its old cards. The page calls the returned
|
|
51
|
+
* `drawing(rows, listed, fallback)` as it starts drawing its rows, the
|
|
52
|
+
* arrays then filled by fillRows, and the function it returns once they are.
|
|
53
|
+
*/
|
|
54
|
+
export function followReturns(recapi, row, contextItemId, cardsOf, put, hold) {
|
|
55
|
+
let started = false;
|
|
56
|
+
let drawn = null;
|
|
57
|
+
let others = () => [];
|
|
58
|
+
onReturn(async () => {
|
|
59
|
+
if (!started) return; // never near the screen: it draws once it is, from the history then
|
|
60
|
+
const now = openedOf(recapi);
|
|
61
|
+
if (now === drawn) return;
|
|
62
|
+
const undo = hold?.();
|
|
63
|
+
// Refused (a key revoked since) or failed (the stand-in list): the row
|
|
64
|
+
// keeps its cards, and the next return asks again.
|
|
65
|
+
try {
|
|
66
|
+
const fallback = [];
|
|
67
|
+
const [cards] = await fillRows(recapi, [row], contextItemId, cardsOf, { exclude: others(), fallback });
|
|
68
|
+
if (fallback[0]) {
|
|
69
|
+
undo?.();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
drawn = now;
|
|
73
|
+
put(cards);
|
|
74
|
+
} catch (error) {
|
|
75
|
+
undo?.();
|
|
76
|
+
console.warn('recapi:', error);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
return (rows, listed, fallback = []) => {
|
|
80
|
+
started = true;
|
|
81
|
+
const at = openedOf(recapi);
|
|
82
|
+
others = () => rows.flatMap((each, i) => (each === row ? [] : listed[i] ?? []));
|
|
83
|
+
// Only a real list marks the history drawn: after a failed first draw
|
|
84
|
+
// the next Back asks again, changed history or not.
|
|
85
|
+
return () => {
|
|
86
|
+
if (fallback[rows.indexOf(row)] === false) drawn = at;
|
|
87
|
+
};
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Storage for a shop whose server sends the orders, and can't read the
|
|
93
|
+
* browser's: each save (only with consent) also leaves in the "recapi"
|
|
94
|
+
* cookie the visitor's id and the list each clicked product came from, for
|
|
95
|
+
* a day, as long as a click is credited. Without consent the cookie goes.
|
|
96
|
+
*/
|
|
97
|
+
export function orderStorage(consent) {
|
|
98
|
+
const secure = location.protocol === 'https:' ? '; secure' : '';
|
|
99
|
+
const cookie = (value, maxAge) => {
|
|
100
|
+
document.cookie = `recapi=${value}; path=/; max-age=${maxAge}; samesite=lax${secure}`;
|
|
101
|
+
};
|
|
102
|
+
if (!consent && /(?:^|;\s*)recapi=/.test(document.cookie ?? '')) cookie('', 0);
|
|
103
|
+
const mirror = (saved) => {
|
|
104
|
+
let state;
|
|
105
|
+
try {
|
|
106
|
+
state = JSON.parse(saved);
|
|
107
|
+
} catch {
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (typeof state?.anonId !== 'string') return;
|
|
111
|
+
const clicked = (Array.isArray(state.shown) ? state.shown : []).filter((entry) => Array.isArray(entry) && entry.length >= 4);
|
|
112
|
+
// A browser drops a cookie over 4 KB: the products shown last stay.
|
|
113
|
+
let value;
|
|
114
|
+
do {
|
|
115
|
+
value = encodeURIComponent(JSON.stringify({ anon: state.anonId, recs: Object.fromEntries(clicked.map(([item, rec]) => [item, rec])) }));
|
|
116
|
+
} while (value.length > 3000 && clicked.shift());
|
|
117
|
+
cookie(value, 86400);
|
|
118
|
+
};
|
|
119
|
+
return {
|
|
120
|
+
getItem: (key) => localStorage.getItem(key),
|
|
121
|
+
// The cookie first: a full storage quota throws, and the order still needs it.
|
|
122
|
+
setItem: (key, value) => {
|
|
123
|
+
mirror(value);
|
|
124
|
+
localStorage.setItem(key, value);
|
|
125
|
+
},
|
|
126
|
+
removeItem: (key) => {
|
|
127
|
+
localStorage.removeItem(key);
|
|
128
|
+
cookie('', 0);
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* An order's products as the visitor's history knows them, when the shop's
|
|
135
|
+
* server sends the order: else the row would open with a product they just
|
|
136
|
+
* bought, as one they looked at. Once, however often the page is reloaded.
|
|
137
|
+
* Nothing to count leaves the client alone: reading its history would give
|
|
138
|
+
* the visitor of any page an id and a cookie.
|
|
139
|
+
*/
|
|
140
|
+
export function bought(recapi, items) {
|
|
141
|
+
if (!items?.length) return;
|
|
142
|
+
const known = new Set(recapi.getHistory().history.filter(([, , , level]) => level === 10).map(([item]) => item));
|
|
143
|
+
for (const item of items) if (!known.has(item)) recapi.track(item, 'purchase', { send: false });
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Each row's cards, at most 4, from `cardsOf(list)`, in one call for all of
|
|
148
|
+
* a page's rows: billed as one, no product on two rows. recapi counts every
|
|
149
|
+
* product of a list as shown, so a row asks for the 4 it shows, then once
|
|
150
|
+
* more, without any product listed, for a full list's gaps (sold out,
|
|
151
|
+
* deleted): a shorter list has no more, a fallback would only wait again.
|
|
152
|
+
* Bought together never shows popular products: they would belie its title.
|
|
153
|
+
* A top-up is a list of its own, so it may bring an earlier-opened product to
|
|
154
|
+
* a row that has its one: there it is a card like any other.
|
|
155
|
+
* A Recently viewed row shows only when its list has a product the visitor
|
|
156
|
+
* opened (else it is the first row's list again, under a false title), and
|
|
157
|
+
* none of its cards is marked: the title says it of all. Its list is not
|
|
158
|
+
* asked for when the history has no such product, nor the call made for it alone.
|
|
159
|
+
* `exclude` keeps products off every row; `listed[i]` gets row i's products,
|
|
160
|
+
* `fallback[i]` whether its list stood in for a failed call.
|
|
161
|
+
*/
|
|
162
|
+
export async function fillRows(recapi, rows, contextItemId, cardsOf, { exclude = [], listed = [], fallback = [] } = {}) {
|
|
163
|
+
const ask = (wanted, exclude) => recapi.recommendLists({
|
|
164
|
+
lists: wanted.map(([i, count]) => ({ count, placement: rows[i].placement, ...(contextItemId ? { contextItemId } : {}) })),
|
|
165
|
+
...(exclude.length ? { exclude } : {})
|
|
166
|
+
});
|
|
167
|
+
const recent = (i) => rows[i].placement === 'recently_viewed';
|
|
168
|
+
const unmarked = (list) => ({ ...list, items: list.items.map((item) => ({ ...item, why: undefined })) });
|
|
169
|
+
const draw = (list, i) => (list.fallback && rows[i].placement === 'bought_together' ? [] : cardsOf(recent(i) ? unmarked(list) : list));
|
|
170
|
+
const none = rows.some((_, i) => recent(i)) && !opened(recapi, contextItemId);
|
|
171
|
+
const asked = rows.map((_, i) => i).filter((i) => !none || !recent(i));
|
|
172
|
+
const got = asked.length ? await ask(asked.map((i) => [i, ROW]), exclude) : [];
|
|
173
|
+
const lists = rows.map(() => ({ items: [] }));
|
|
174
|
+
asked.forEach((i, k) => { lists[i] = got[k]; });
|
|
175
|
+
lists.forEach((list, i) => {
|
|
176
|
+
listed[i] = list.items.map(({ itemId }) => itemId);
|
|
177
|
+
fallback[i] = list.fallback === true;
|
|
178
|
+
});
|
|
179
|
+
// shortcut: an opened product the shop can't draw (sold out since) still lets the row show; the engine leaves out inactive ones.
|
|
180
|
+
const shows = lists.map((list, i) => !recent(i) || hasEarlier(list.items));
|
|
181
|
+
const cards = await Promise.all(lists.map((list, i) => (shows[i] ? draw(list, i) : [])));
|
|
182
|
+
const short = rows.map((_, i) => i).filter((i) => shows[i] && cards[i].length < ROW && lists[i].items.length >= ROW && !lists[i].fallback);
|
|
183
|
+
if (short.length) {
|
|
184
|
+
// Refused (a key revoked mid-page): the rows keep the cards they have.
|
|
185
|
+
try {
|
|
186
|
+
const more = await ask(short.map((i) => [i, ROW - cards[i].length]), [...exclude, ...listed.flat()]);
|
|
187
|
+
more.forEach((list, k) => listed[short[k]].push(...list.items.map(({ itemId }) => itemId)));
|
|
188
|
+
const extra = await Promise.all(more.map((list, k) => draw(hasEarlier(cards[short[k]])
|
|
189
|
+
? { ...list, items: list.items.map((item) => (hasEarlier([item]) ? { ...item, why: undefined } : item)) }
|
|
190
|
+
: list, short[k])));
|
|
191
|
+
short.forEach((i, k) => cards[i].push(...extra[k]));
|
|
192
|
+
} catch (error) {
|
|
193
|
+
console.warn('recapi:', error);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return cards.map((row) => earlierFirst(row.slice(0, ROW)));
|
|
197
|
+
}
|