@recapi/client 0.18.0 → 0.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/row.js CHANGED
@@ -8,47 +8,52 @@
8
8
  * @module row
9
9
  */
10
10
 
11
- import { REC_ID } from './client.js';
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
- /** A row shows 4 cards: recapi counts every item of a list as shown. */
14
- const ROW = 4;
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
15
 
16
- // :where() weighs nothing, so any rule of the site's restyles the cards. Four
17
- // across, two where four would be narrower than 150px (a phone). The height
18
- // is held while the list loads, so the page doesn't jump.
19
- const CSS = ':where(.recapi-row[aria-busy=true]){min-height:20rem}' +
20
- ':where(.recapi-row ul){display:grid;grid-template-columns:repeat(auto-fill,minmax(max(150px,(100% - 3rem)/4),1fr));gap:1rem;align-items:start;list-style:none;margin:0;padding:0}' +
21
- ':where(.recapi-row a){display:flex;flex-direction:column;gap:.25rem;color:inherit;text-decoration:none}' +
22
- ':where(.recapi-row img){display:block;width:100%;height:auto;aspect-ratio:1;object-fit:cover}' +
23
- ':where(.recapi-row .recapi-price){font-weight:600}';
24
-
25
- const escape = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
26
-
27
- /** Only http(s) addresses: a `javascript:` link in metadata must never reach the page. */
28
- function web(address) {
29
- if (typeof address !== 'string') return null;
30
- try {
31
- const url = new URL(address, location.href);
32
- return url.protocol === 'https:' || url.protocol === 'http:' ? url : null;
33
- } catch {
34
- return null;
35
- }
36
- }
16
+ const HELD = [...['margin', 'padding'].flatMap((box) => ['top', 'right', 'bottom', 'left'].map((side) => `${box}-${side}`)), 'list-style-type', 'list-style-image'];
37
17
 
38
18
  /**
39
- * A card's link with its list's id: in the fragment, unless the address has
40
- * its own (the site's, not ours to overwrite), it is the page already open (a
41
- * fragment wouldn't load it, so no view), or the id isn't one `landed()` reads
42
- * from a fragment.
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.
43
27
  */
44
- function carry(url, recommendationId) {
45
- if (!recommendationId) return url;
46
- const open = url.href.split('#')[0] === location.href.split('#')[0];
47
- if (url.hash || open || !REC_ID.test(recommendationId)) url.searchParams.set('rec', recommendationId);
48
- else url.hash = recommendationId;
49
- return url;
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
+ });
50
52
  }
51
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');
56
+
52
57
  /** The page's currency, as shops print it for search engines. */
53
58
  function pageCurrency() {
54
59
  const tag = document.querySelector('meta[property="product:price:currency"],meta[property="og:price:currency"],meta[itemprop="priceCurrency"]');
@@ -67,47 +72,42 @@ export function rows(client) {
67
72
  let group = null;
68
73
  let sheet = false;
69
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();
70
81
 
71
82
  const style = () => {
72
83
  if (sheet) return;
73
84
  sheet = true;
74
- // A constructed sheet passes a site's `style-src 'self'` CSP, which
75
- // refuses a <style> element; browsers before Safari 16.4 get the element.
76
- try {
77
- const css = new CSSStyleSheet();
78
- css.replaceSync(CSS);
79
- document.adoptedStyleSheets = [...document.adoptedStyleSheets, css];
80
- } catch {
81
- const el = document.createElement('style');
82
- el.textContent = CSS;
83
- document.head.append(el);
84
- }
85
+ addStyle(CSS);
85
86
  };
86
87
 
87
- const hide = (el) => {
88
+ const away = (el) => {
88
89
  el.removeAttribute('aria-busy');
89
- // Not only [hidden]: any display rule of the site's beats that one.
90
- el.hidden = true;
91
- el.style.setProperty('display', 'none', 'important');
90
+ if (blank.delete(el)) el.innerHTML = '';
91
+ hide(el);
92
+ hid.add(el);
92
93
  };
93
94
 
94
- const card = ({ metadata: m }, recommendationId, money) => {
95
- const link = m && m.available !== false && typeof m.name === 'string' ? web(m.url) : null;
95
+ const item = ({ metadata: m, why }, recommendationId, money) => {
96
+ const link = cardLink(m);
96
97
  if (!link) return null;
97
98
  let price = typeof m.price === 'string' ? m.price : '';
99
+ let was = null;
98
100
  if (typeof m.price === 'number') {
99
101
  const currency = typeof m.currency === 'string' ? m.currency : money;
100
102
  try {
101
- price = new Intl.NumberFormat(document.documentElement.lang || undefined, { style: 'currency', currency }).format(m.price);
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);
102
106
  } catch {
103
107
  unpriced = true;
104
108
  }
105
109
  }
106
- const picture = web(m.picture);
107
- return `<li><a href="${escape(carry(link, recommendationId).href)}">` +
108
- `${picture ? `<img src="${escape(picture.href)}" alt="" loading="lazy">` : ''}` +
109
- `<span class="recapi-name">${escape(m.name)}</span>` +
110
- `${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);
111
111
  };
112
112
 
113
113
  const draw = (row, list) => {
@@ -115,54 +115,112 @@ export function rows(client) {
115
115
  // A popular fallback is not what was bought together: that row stays away.
116
116
  const together = placement === 'bought_together';
117
117
  const money = pageCurrency();
118
- const cards = list.fallback && together ? [] : list.items.map((item) => ({ html: card(item, list.recommendationId, money), why: item.why })).filter(({ html }) => html);
118
+ const cards = list.fallback && together ? [] : list.items.map((each) => ({ html: item(each, list.recommendationId, money), why: each.why })).filter(({ html }) => html);
119
119
  if (!cards.length) {
120
120
  if (list.items.length) {
121
121
  const missing = ['name', 'url'].filter((key) => list.items.every(({ metadata }) => typeof metadata?.[key] !== 'string'));
122
122
  console.warn(`recapi: no card to draw: send each item's metadata with ${missing.join(' and ') || 'a name and an http(s) url'} (PUT /v1/items)`);
123
123
  }
124
- return hide(el);
124
+ return away(el);
125
+ }
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)]));
125
155
  }
126
- // The title only over a real pair: a product nobody bought with another
127
- // yet gets similar ones, true cards under a false title.
128
- const titled = heading && (!together || cards.some(({ why }) => why === 'bought_together'));
129
- el.innerHTML = `${titled ? `<h2 class="recapi-heading">${escape(heading)}</h2>` : ''}<ul role="list">${cards.map(({ html }) => html).join('')}</ul>`;
130
156
  el.removeAttribute('aria-busy');
131
157
  };
132
158
 
133
159
  const fill = async (members) => {
134
160
  try {
135
- const lists = await client.recommendLists({
136
- lists: members.map(({ placement, contextItemId }) => ({
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 }) => ({
137
165
  count: ROW,
138
166
  ...(placement ? { placement } : {}),
139
167
  ...(contextItemId ? { contextItemId } : {})
140
168
  }))
141
- });
169
+ }) : [];
170
+ const lists = members.map((row) => got[asked.indexOf(row)] ?? { items: [] });
142
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
+ });
143
179
  if (unpriced) {
144
180
  unpriced = false;
145
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">');
146
182
  }
147
183
  } catch (error) {
148
184
  // recommendLists() rejects only on a bad request: the page loses no more than its rows.
149
- members.forEach(({ el }) => hide(el));
185
+ members.forEach(({ el }) => away(el));
150
186
  console.warn('recapi:', error);
151
187
  }
152
188
  };
153
189
 
154
- const watch = (members) => {
155
- if (typeof IntersectionObserver !== 'function') return fill(members);
156
- // Each list is billed and counted as shown: a visitor who never scrolls
157
- // down saw none.
158
- const observer = new IntersectionObserver((entries) => {
159
- if (!entries.some((entry) => entry.isIntersecting)) return undefined;
160
- observer.disconnect();
161
- return fill(members);
162
- }, { rootMargin: '0px 0px 400px 0px' });
163
- for (const { el } of members) observer.observe(el);
164
- return undefined;
165
- };
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
+
221
+ // Each list is billed and counted as shown: a visitor who never scrolls
222
+ // down saw none.
223
+ const watch = (members) => near(members.map(({ el }) => el), () => fill(members));
166
224
 
167
225
  return (slot, { placement, contextItemId, heading } = {}) => {
168
226
  const el = typeof slot === 'string' ? document.querySelector(slot) : slot;
@@ -173,6 +231,14 @@ export function rows(client) {
173
231
  style();
174
232
  el.classList.add('recapi-row');
175
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
+ }
176
242
  if (!group) {
177
243
  group = [];
178
244
  queueMicrotask(() => {