UNPKG

@nosto/autocomplete

Version:

Library designed to simplify the implementation of search autocomplete functionality

905 lines (904 loc) 21.5 kB
"use strict"; function z() { window.nostojs = window.nostojs ?? function(e) { (window.nostojs.q = window.nostojs.q ?? []).push(e); }; } async function O(e) { return window.nostojs(e); } typeof window < "u" && (z(), O((e) => { e.internal.getSettings(); })), typeof window < "u" && z(); function se(e) { O((t) => t.recordSearchClick("autocomplete", e)); } function ae(e) { O((t) => t.recordSearchSubmit(e)); } function G() { window.nostojs = window.nostojs ?? function(e) { (window.nostojs.q = window.nostojs.q ?? []).push(e); }; } async function E(e) { return window.nostojs(e); } typeof window < "u" && (G(), E((e) => { e.internal.getSettings(); })), typeof window < "u" && G(); const J = (e) => String(e) === "[object Object]"; function R(e) { if (!J(e)) return !1; const t = e.constructor; if (t === void 0) return !0; const n = t.prototype; return !(!J(n) || !n.hasOwnProperty("isPrototypeOf")); } function D(e, t) { if (e === t) return !0; if (e instanceof Date && t instanceof Date) return e.getTime() === t.getTime(); if (Array.isArray(e) && Array.isArray(t)) return e.length !== t.length ? !1 : e.every((n, o) => D(n, t[o])); if (R(e) && R(t)) { const n = Object.entries(e); return n.length !== Object.keys(t).length ? !1 : n.every(([o, r]) => D(r, t[o])); } return !1; } function I(e) { return (...t) => { E((n) => { (n.internal.context.mode.isPreview() ? console[e] : n.internal.logger[e])(...t); }); }; } const m = { debug: I("debug"), info: I("info"), warn: I("warn"), error: I("error") }; async function ue(e, { hitDecorators: t, ...n }, o) { var r, i; const a = await o(e, n); if (!((i = (r = a.products) == null ? void 0 : r.hits) != null && i.length) || !(t != null && t.length)) return a; const s = (d) => t.reduce((l, c) => c(l), d); return { ...a, products: { ...a.products, hits: a.products.hits.map(s) } }; } function le(e, t, n) { const o = JSON.stringify(t); try { n.setItem(e, o); } catch (r) { m.warn(r); } } function fe(e, t) { try { const n = t.getItem(e); if (n) return JSON.parse(n); } catch (n) { m.warn(n); } } function de(e, t) { le(e, t, sessionStorage); } function ge(e) { return fe(e, sessionStorage); } const B = "nosto:search-js:cache", ye = 60 * 1e3; function pe(e, t) { de(B, { query: e, result: t, created: Date.now() }); } function me(e) { const t = ge(B); if (!t || !we(t)) return null; const n = K(t.query); return !D(K(e), n) || Date.now() - t.created > ye ? null : t.result; } function K(e) { const t = { ...e, time: void 0, products: { ...e.products, size: void 0 } }; return JSON.parse(JSON.stringify(t)); } function we(e) { return typeof e == "object" && e !== null && "query" in e && "result" in e && "created" in e; } async function he(e, { usePersistentCache: t, ...n }, o) { if (!t) return o(e, n); const r = await ve(e, n, o); return pe(e, r), r; } async function ve(e, t, n) { var o, r, i, a, s, d; const { from: l = 0, size: c = 0 } = e.products || {}, u = me(e); if (!u) return await n(e, t); const g = ((o = u?.products) == null ? void 0 : o.size) ?? 0, h = ((r = u?.products) == null ? void 0 : r.hits) ?? []; if (c === g) return u; if (c < g) return { ...u, products: { ...u.products, size: c, hits: h.slice(0, c), total: ((i = u.products) == null ? void 0 : i.total) || 0 } }; const A = c - h.length, v = l > 0 ? l + 1 : c - A, S = { ...e, products: { ...e.products, from: v, size: A } }, b = await n(S, t); return { ...u, products: { ...u.products, size: c, hits: [...((a = u.products) == null ? void 0 : a.hits) || [], ...((s = b.products) == null ? void 0 : s.hits) || []], total: ((d = b.products) == null ? void 0 : d.total) || 0 } }; } const Se = 3e4, j = /* @__PURE__ */ new Map(); function be(e, t) { const n = j.get(e); if (!n) return; const o = Date.now() - n.created > Se, r = D(t, n.query); if (o || !r) { j.delete(e); return; } return n.result; } function ke(e, t, n) { j.set(e, { query: t, result: n, created: Date.now() }); } async function Ae(e, t, n) { if (!t.useMemoryCache) return n(e, t); const o = JSON.stringify(e), r = be(o, e); if (r) return r; const i = await n(e, t); return ke(o, e, i), i; } function Ce(e) { return new Promise((t) => setTimeout(t, e)); } async function Ee(e, { maxRetries: t = 0, retryInterval: n = 0, ...o }, r) { let i = 0; for (; ; ) try { return await r(e, o); } catch (a) { if (i >= t) throw a; if (!De(a)) throw m.info("Skipping retry logic for", a), a; i++, await Ce(n); } } function De(e) { return !e || typeof e != "object" ? !1 : !("status" in e) || Ie(e.status); } function Ie(e) { return typeof e == "number" && (e < 400 || e >= 500); } async function Pe(e, t = {}) { const n = await new Promise(E); return Le(n.search, Ee, Ae, he, ue)(e, t); } function Le(e, ...t) { return t.reduce((n, o) => (r, i) => o(r, i, n), e); } const He = [ "productId", "url", "name", "imageUrl", "imageHash", "thumbUrl", "description", "brand", "variantId", "availability", "price", "priceText", "categoryIds", "categories", "customFields.key", "customFields.value", "priceCurrencyCode", "datePublished", "listPrice", "unitPricingBaseMeasure", "unitPricingUnit", "unitPricingMeasure", "googleCategory", "gtin", "ageGroup", "gender", "condition", "alternateImageUrls", "ratingValue", "reviewCount", "inventoryLevel", "skus.id", "skus.name", "skus.price", "skus.listPrice", "skus.priceText", "skus.url", "skus.imageUrl", "skus.inventoryLevel", "skus.customFields.key", "skus.customFields.value", "skus.availability", "pid", "onDiscount", "extra.key", "extra.value", "saleable", "available", "tags1", "tags2", "tags3" ]; async function T(e, t = {}) { const n = e.products?.fields ?? He, o = e.products?.facets ?? ["*"], r = e.products?.size ?? 20, i = e.products?.from ?? 0, a = await Pe( { ...e, products: { ...e.products, fields: n, facets: o, size: r, from: i } }, t ); return { query: e, response: a }; } const $ = { serpPath: "/search", queryParamName: "query", enabled: !0 }; function Q() { return { minQueryLength: 2, historyEnabled: !0, historySize: 5, hitDecorators: [], nostoAnalytics: !0, googleAnalytics: $, routingHandler: (e) => { location.href = e; }, nativeSubmit: !1, submit: (e, t, n) => { e.length >= (t.minQueryLength ?? Q().minQueryLength) && T( { query: e }, { redirect: !0, track: t.nostoAnalytics ? "serp" : void 0, hitDecorators: t.hitDecorators, ...n } ); } }; } function Ne(e) { e.setAttribute("autocomplete", "off"); } function Oe(e, { onClick: t, onFocus: n, onInput: o, onKeyDown: r, onSubmit: i }, { form: a = e.form ?? void 0, nativeSubmit: s } = {}) { const d = []; function l(c, u, g) { c.addEventListener(u, g), d.push(() => c.removeEventListener(u, g)); } return (r || i) && l(e, "keydown", (c) => { r?.(e.value, c.key), r && (c.key === "ArrowDown" || c.key === "ArrowUp") ? c.preventDefault() : i && c.key === "Enter" && (e.value !== "" && !c.repeat && i(e.value), s || c.preventDefault()); }), i && a && (l(a, "submit", (c) => { s || c.preventDefault(), i(e.value); }), a.querySelectorAll("[type=submit]").forEach((c) => { l(c, "click", (u) => { s || u.preventDefault(), i(e.value); }); })), t && l(e, "click", () => t(e.value)), n && l(e, "focus", () => n(e.value)), o && l(e, "input", () => o(e.value)), { destroy() { d.forEach((c) => c()); } }; } function je(e, t, n, o, r, i, a) { let s = [], d = [], l = !0, c = -1; function u(f) { const p = f?.dataset?.nsHit; if (p) { const y = q(p); if (k(), y?.item) { o(y.item); return; } if (y?.keyword) { o(y.keyword, { redirect: !!y?._redirect, isKeyword: !0 }), y?._redirect && i(y._redirect); return; } y?.url && i(y.url); } } function g() { l = !e.innerHTML.trim(), l || (s = Array.from( e.querySelectorAll("[data-ns-hit]") ).map((f) => (A(f), f))); } function h() { Object.entries(a ?? {}).map(([f, p]) => { const y = `[data-ns-${f.replace(/([A-Z])/g, "-$1").toLowerCase()}]`; Array.from(e.querySelectorAll(y)).map((w) => { const ce = w?.dataset?.[`ns${f.charAt(0).toUpperCase() + f.slice(1)}`], x = () => { p({ data: ce, el: w, update: b }); }; w.addEventListener("click", x), d.push(() => { w.removeEventListener("click", x); }); }); }); } function A(f) { const p = () => { u(f); }; f.addEventListener("click", p), d.push(() => { f.removeEventListener("click", p); }); } function v(f, p) { if (typeof p == "number" && s[p] && s[p].classList.remove("selected"), typeof f == "number" && s[f]) { s[f]?.classList.add("selected"); const y = s[f]?.dataset?.nsHit; if (y) { const w = q(y); if (w.item) { r(w.item); return; } if (w.keyword) { r(w.keyword); return; } } } } function S() { N(), s = [], d.forEach((f) => f()), d = []; } async function b(f) { S(), await n(e, f), setTimeout(() => { g(), h(), M(); }, 0); } function k() { N(), e.style.display = "none"; } function M() { l ? k() : e.style.display = ""; } function Y() { S(), l = !0, k(); } function F() { return e.style.display !== "none"; } function ee() { let f = c; c === s.length - 1 ? c = 0 : f = c++, v(c, f); } function te() { if (C()) { let f = c; c === 0 ? c = s.length - 1 : f = c--, v(c, f); } else c = s.length - 1, v(c); } function ne() { F() && C() && s[c] && u(s[c]); } function C() { return c > -1; } function oe() { return s[c]; } function N() { C() && (s[c]?.classList.remove("selected"), c = -1); } function re() { S(), l = !0, e.innerHTML = ""; } async function ie() { const f = await Promise.resolve(t); await Promise.resolve(n(e, f)), setTimeout(() => { g(), h(), k(); }, 0); } return ie(), { update: b, clear: Y, isOpen: F, goDown: ee, goUp: te, handleSubmit: ne, destroy: re, show: M, hide: k, resetHighlight: N, hasHighlight: C, getHighlight: oe, container: e }; } function q(e) { try { return JSON.parse(e) ?? {}; } catch (t) { return m.warn("Could not parse hit", t), {}; } } class V extends Error { } function Te(e) { let t = !1; return { promise: new Promise((n, o) => e.then( (r) => t ? o(new V("cancelled promise")) : n(r), (r) => o(t ? new V("cancelled promise") : r) )), cancel() { t = !0; } }; } function $e({ config: e, history: t, input: n }) { let o; const r = (c, u, g) => typeof u.fetch == "function" ? u.fetch(c) : T( { query: c, ...u.fetch }, { track: u.nostoAnalytics ? "autocomplete" : void 0, redirect: !1, hitDecorators: u.hitDecorators, ...g } ); function i(c) { return Promise.resolve({ query: { query: c }, history: t?.getItems() }); } function a(c, u) { return o?.cancel(), c && c.length >= e.minQueryLength ? (o = Te(r(c, e, u)), o.promise) : t ? i(c ?? "") : ( // @ts-expect-error type mismatch o?.promise ?? Promise.resolve({}) ); } function s(c) { return t && t.add(c), i(n.value); } function d(c) { return t && t.remove(c), i(n.value); } function l() { return t && t.clear(), i(n.value); } return { updateState: a, addHistoryItem: s, removeHistoryItem: d, clearHistory: l }; } function P(e, t) { return (typeof e == "string" ? Array.from(document.querySelectorAll(e)) : [e]).filter( (n) => t ? n instanceof t : !0 ); } function W(e, t) { let n = []; return P(e).forEach((o) => { const r = o.parentNode; r !== document && r instanceof Element && (n.push(r), n = n.concat(W(r))); }), n.filter( (o) => t === void 0 ); } function qe([e, t], n) { const o = (r) => { const i = r.target; i instanceof HTMLElement && e && i !== e && i !== t && !W(i).includes(e) && n(); }; return document.addEventListener("click", o), { destroy: () => { document.removeEventListener("click", o); } }; } const U = "nosto:autocomplete:gaEvent"; function L(e) { const { delay: t = !1, title: n = document.title, location: o = window.location.href } = e || {}; if (t) Ue(n, o); else { if ("gtag" in window && typeof window.gtag == "function") { const r = "google_tag_manager" in window && typeof window.google_tag_manager == "object" ? Object.keys(window.google_tag_manager || []).filter((i) => i.substring(0, 2) == "G-") : []; if (r.length > 1) for (let i = 0; i < r.length; i++) window.gtag("event", "page_view", { page_title: n, page_location: o, send_to: r[i] }); else window.gtag("event", "page_view", { page_title: n, page_location: o }); } if ("ga" in window && typeof window.ga == "function" && "getAll" in window.ga && typeof window.ga.getAll == "function") try { const r = new URL(o), i = window.ga.getAll(); i?.length > 0 && i[0]?.send("pageview", r.pathname + r.search); } catch (r) { m.warn("Could not send pageview to GA", r); } } } const H = (e) => typeof e.googleAnalytics == "boolean" ? e.googleAnalytics : typeof e.googleAnalytics == "object" && e.googleAnalytics.enabled, _ = (e, t) => { const n = H(t) ? typeof t.googleAnalytics == "boolean" ? $ : { ...$, ...t.googleAnalytics } : void 0; if (e && n) try { return new URL( `${n?.serpPath || location.pathname}?${`${encodeURIComponent( n.queryParamName )}=${encodeURIComponent(e).replace(/%20/g, "+")}`}`, window.location.origin ).toString(); } catch (o) { m.warn("Could not create track url", o); return; } }; function Ue(e, t) { localStorage.setItem(U, JSON.stringify({ title: e, location: t })); } function _e() { const e = localStorage.getItem(U); if (typeof e == "string") { localStorage.removeItem(U); try { const t = JSON.parse(e); L(t); } catch (t) { m.warn("Could not consume pageView", t); } } } function Me(e) { let t, n = !1; return (o) => { n ? (t && clearTimeout(t), t = setTimeout(async () => { await o(), n = !1; }, e)) : (o(), n = !0); }; } function Fe(e) { const t = "nosto:autocomplete:history"; let n = o(); function o() { try { return JSON.parse(localStorage.getItem(t) ?? "[]") ?? []; } catch (l) { return m.error("Could not get history items.", l), []; } } function r(l) { try { localStorage.setItem(t, JSON.stringify(l)); } catch (c) { m.error("Could not set history items.", c); } } function i(l) { r( n = [{ item: l }, ...n?.filter((c) => c.item !== l) || []].slice( 0, e ) ); } function a() { r(n = []); } function s(l) { r(n = n.filter((c) => c.item !== l)); } function d() { return n; } return { add: i, clear: a, remove: s, getItems: d }; } function xe(e) { const t = { ...Q(), ...e }, n = t.historyEnabled ? Fe(t.historySize) : void 0, o = Me(300); H(e) && setTimeout(_e, 1e3); const r = P(e.inputSelector, HTMLInputElement).map( (i) => { const a = $e({ config: t, history: n, input: i }), s = ze({ input: i, config: t, actions: a }); if (!s) return; Ne(i); const d = Oe(i, { onInput: async (c) => { o(async () => { const u = await a.updateState(c); s.update(u); }); }, onClick() { s.resetHighlight(); }, onFocus() { s.show(); }, onSubmit() { if (s.isOpen() && s.hasHighlight()) { const c = s.getHighlight()?.dataset?.nsHit; c && Z({ config: t, data: c, query: i.value }), s.handleSubmit(); } else X({ actions: a, config: t })(i.value); }, onKeyDown(c, u) { u === "Escape" ? s.hide() : u === "ArrowDown" ? s.isOpen() ? s.goDown() : s.show() : u === "ArrowUp" && s.isOpen() && s.goUp(); } }, { nativeSubmit: t.nativeSubmit }), l = qe( [s.container, i], () => { s.hide(); } ); return { open() { s.show(); }, close() { s.hide(); }, destroy() { d.destroy(), l.destroy(), s.destroy(); } }; } ); return { destroy() { r.forEach((i) => i?.destroy()); }, open() { r.forEach((i) => i?.open()); }, close() { r.forEach((i) => i?.close()); } }; } function ze({ input: e, config: t, actions: n }) { const o = typeof t.dropdownSelector == "function" ? P(t.dropdownSelector(e), HTMLElement) : P(t.dropdownSelector, HTMLElement); if (o.length === 0) { m.error(`No dropdown element found for input ${e}`); return; } else o.length > 1 && m.error( `Multiple dropdown elements found for input ${e}, using the first element` ); const r = o[0]; return je( r, n.updateState(e.value), t.render, X({ actions: n, config: t }), (i) => e.value = i, t.routingHandler, { removeHistory: async function({ data: i, update: a }) { if (i === "all") { const s = await n.clearHistory(); return a(s); } else if (i) { const s = await n.removeHistoryItem(i); return a(s); } }, hit: function({ data: i }) { i && Z({ config: t, data: i, query: e.value }); } } ); } async function Z({ config: e, data: t, query: n }) { if (!e.googleAnalytics && !e.nostoAnalytics) return; const o = q(t); e.nostoAnalytics && o && se(o), H(e) && (o._redirect && L({ delay: !0, location: _(o.keyword, e) }), o.url && L({ delay: !0, location: _(n, e) })); } function X(e) { return async (t, n) => { const { config: o, actions: r } = e, { redirect: i = !1 } = n ?? {}; t.length > 0 && (o.historyEnabled && r.addHistoryItem(t), o.nostoAnalytics && ae(t), H(o) && L({ delay: !0, location: _(t, o) }), !i && typeof o?.submit == "function" && o.submit(t, o, n)); }; } const Ge = { defaultCurrency: "EUR", defaultLocale: "en-US", /** @hidden */ currencySettings: {} }, Je = { EUR: "de-DE", GBP: "en-GB", USD: "en-US", AUD: "en-AU", CAD: "en-CA", //India, Afghanistan, Bangladesh, Bhutan, Myanmar, Nepal, and Pakistan uses lakhs and crores notation INR: "en-IN", AFN: "en-IN", BDT: "en-IN", BTN: "en-IN", MMK: "en-IN", NPR: "en-IN", PKR: "en-IN" }; function Re(e = {}) { const t = { ...Ge, ...e }; e.currencySettings || E((o) => { t.currencySettings = o.internal.getSettings().currencySettings ?? {}; }); function n(o, r) { const { defaultCurrency: i, currencySettings: a, defaultLocale: s } = t, d = r ?? i, l = Je[d] ?? s; if (d in a) { const c = a[d], u = new Intl.NumberFormat(l, { useGrouping: !!c.groupingSeparator, minimumFractionDigits: c.decimalPlaces, maximumFractionDigits: c.decimalPlaces }).formatToParts(o).map((g) => g.type === "group" ? c.groupingSeparator : g.type === "decimal" ? c.decimalCharacter : g.value).join(""); return c != null && c.currencyBeforeAmount ? `${c.currencyToken}${u}` : `${u}${c?.currencyToken}`; } return new Intl.NumberFormat(l, { style: "currency", currency: d }).format(o); } return { formatCurrency: n }; } function Be(e) { const { formatCurrency: t } = Re(e); function n(r, i) { const a = {}; return r.price !== void 0 && (a.priceText = t(r.price, i)), r.listPrice !== void 0 && (a.listPriceText = t(r.listPrice, i)), Object.assign({}, r, a); } function o(r) { return r.price !== void 0 || r.listPrice !== void 0; } return function(r) { if (!o(r)) return r; const i = n(r, r.priceCurrencyCode); return i.skus && i.skus.some(o) && (i.skus = i.skus.map((a) => o(a) ? n(a, r.priceCurrencyCode) : a)), i; }; } exports.autocomplete = xe, exports.priceDecorator = Be, exports.search = T; //# sourceMappingURL=autocomplete.cjs.map