UNPKG

@nosto/autocomplete

Version:

Library designed to simplify the implementation of search autocomplete functionality

1,014 lines (1,013 loc) 25.7 kB
"use strict"; var d = require("react/jsx-runtime"); function ae({ response: e, history: t }) { const n = !!e?.keywords?.hits?.length, o = !!e?.products?.hits?.length, r = !!t?.length; return !n && !o && !r ? null : /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-results", children: !n && !o && r ? /* @__PURE__ */ d.jsx(ue, { history: t }) : n || o ? /* @__PURE__ */ d.jsxs(d.Fragment, { children: [ n && /* @__PURE__ */ d.jsx(le, { keywords: e.keywords.hits }), o && /* @__PURE__ */ d.jsx(de, { products: e.products.hits }), /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-submit", children: /* @__PURE__ */ d.jsx("button", { type: "submit", className: "ns-autocomplete-button", children: "See all search results" }) }) ] }) : null }); } function ue({ history: e }) { return /* @__PURE__ */ d.jsxs(d.Fragment, { children: [ /* @__PURE__ */ d.jsxs("div", { className: "ns-autocomplete-history", children: [ /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-header", children: "Recently searched" }), e?.map((t, n) => /* @__PURE__ */ d.jsxs( "div", { className: "ns-autocomplete-history-item", "data-ns-hit": JSON.stringify(t), "data-testid": "history", children: [ t.item, /* @__PURE__ */ d.jsx( "a", { href: "#", className: "ns-autocomplete-history-item-remove", "data-ns-remove-history": t.item, children: "\u2715" } ) ] }, n )) ] }), /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-history-clear", children: /* @__PURE__ */ d.jsx( "button", { type: "button", className: "ns-autocomplete-button", "data-ns-remove-history": "all", children: "Clear history" } ) }) ] }); } function le({ keywords: e }) { return /* @__PURE__ */ d.jsxs("div", { className: "ns-autocomplete-keywords", children: [ /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-header", children: "Keywords" }), e?.map((t, n) => /* @__PURE__ */ d.jsx( "div", { className: "ns-autocomplete-keyword", "data-ns-hit": JSON.stringify(t), "data-testid": "keyword", children: t._highlight && t._highlight.keyword ? /* @__PURE__ */ d.jsx( "span", { dangerouslySetInnerHTML: { __html: t._highlight.keyword } } ) : /* @__PURE__ */ d.jsx("span", { children: t.keyword }) }, n )) ] }); } function de({ products: e }) { return /* @__PURE__ */ d.jsxs("div", { className: "ns-autocomplete-products", children: [ /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-header", children: "Products" }), e.map((t) => /* @__PURE__ */ d.jsxs( "a", { className: "ns-autocomplete-product", href: "#", "data-ns-hit": JSON.stringify(t), "data-testid": "product", children: [ /* @__PURE__ */ d.jsx( "img", { className: "ns-autocomplete-product-image", src: t.imageUrl, alt: t.name, width: "60", height: "40" } ), /* @__PURE__ */ d.jsxs("div", { className: "ns-autocomplete-product-info", children: [ t.brand && /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-product-brand", children: t.brand }), /* @__PURE__ */ d.jsx("div", { className: "ns-autocomplete-product-name", children: t.name }), /* @__PURE__ */ d.jsxs("div", { children: [ /* @__PURE__ */ d.jsxs("span", { children: [ t.price, "\u20AC" ] }), t.listPrice && t.listPrice !== t.price && /* @__PURE__ */ d.jsxs("span", { className: "ns-autocomplete-product-list-price", children: [ t.listPrice, "\u20AC" ] }) ] }) ] }) ] }, t.productId )) ] }); } function R() { 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" && (R(), O((e) => { e.internal.getSettings(); })), typeof window < "u" && R(); function fe(e) { O((t) => t.recordSearchClick("autocomplete", e)); } function me(e) { O((t) => t.recordSearchSubmit(e)); } function z() { window.nostojs = window.nostojs ?? function(e) { (window.nostojs.q = window.nostojs.q ?? []).push(e); }; } async function x(e) { return window.nostojs(e); } typeof window < "u" && (z(), x((e) => { e.internal.getSettings(); })), typeof window < "u" && z(); const G = (e) => String(e) === "[object Object]"; function K(e) { if (!G(e)) return !1; const t = e.constructor; if (t === void 0) return !0; const n = t.prototype; return !(!G(n) || !n.hasOwnProperty("isPrototypeOf")); } function C(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) => C(n, t[o])); if (K(e) && K(t)) { const n = Object.entries(e); return n.length !== Object.keys(t).length ? !1 : n.every(([o, r]) => C(r, t[o])); } return !1; } function P(e) { return (...t) => { x((n) => { (n.internal.context.mode.isPreview() ? console[e] : n.internal.logger[e])(...t); }); }; } const h = { debug: P("debug"), info: P("info"), warn: P("warn"), error: P("error") }; async function pe(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 c = (m) => t.reduce((l, s) => s(l), m); return { ...a, products: { ...a.products, hits: a.products.hits.map(c) } }; } function ye(e, t, n) { const o = JSON.stringify(t); try { n.setItem(e, o); } catch (r) { h.warn(r); } } function ge(e, t) { try { const n = t.getItem(e); if (n) return JSON.parse(n); } catch (n) { h.warn(n); } } function he(e, t) { ye(e, t, sessionStorage); } function we(e) { return ge(e, sessionStorage); } const B = "nosto:search-js:cache", ve = 60 * 1e3; function Se(e, t) { he(B, { query: e, result: t, created: Date.now() }); } function be(e) { const t = we(B); if (!t || !ke(t)) return null; const n = Q(t.query); return !C(Q(e), n) || Date.now() - t.created > ve ? null : t.result; } function Q(e) { const t = { ...e, time: void 0, products: { ...e.products, size: void 0 } }; return JSON.parse(JSON.stringify(t)); } function ke(e) { return typeof e == "object" && e !== null && "query" in e && "result" in e && "created" in e; } async function je(e, { usePersistentCache: t, ...n }, o) { if (!t) return o(e, n); const r = await Ae(e, n, o); return Se(e, r), r; } async function Ae(e, t, n) { var o, r, i, a, c, m; const { from: l = 0, size: s = 0 } = e.products || {}, u = be(e); if (!u) return await n(e, t); const p = ((o = u?.products) == null ? void 0 : o.size) ?? 0, v = ((r = u?.products) == null ? void 0 : r.hits) ?? []; if (s === p) return u; if (s < p) return { ...u, products: { ...u.products, size: s, hits: v.slice(0, s), total: ((i = u.products) == null ? void 0 : i.total) || 0 } }; const A = s - v.length, S = l > 0 ? l + 1 : s - A, b = { ...e, products: { ...e.products, from: S, size: A } }, k = await n(b, t); return { ...u, products: { ...u.products, size: s, hits: [...((a = u.products) == null ? void 0 : a.hits) || [], ...((c = k.products) == null ? void 0 : c.hits) || []], total: ((m = k.products) == null ? void 0 : m.total) || 0 } }; } const Ne = 3e4, H = /* @__PURE__ */ new Map(); function xe(e, t) { const n = H.get(e); if (!n) return; const o = Date.now() - n.created > Ne, r = C(t, n.query); if (o || !r) { H.delete(e); return; } return n.result; } function Ce(e, t, n) { H.set(e, { query: t, result: n, created: Date.now() }); } async function Pe(e, t, n) { if (!t.useMemoryCache) return n(e, t); const o = JSON.stringify(e), r = xe(o, e); if (r) return r; const i = await n(e, t); return Ce(o, e, i), i; } function Ee(e) { return new Promise((t) => setTimeout(t, e)); } async function Ie(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 h.info("Skipping retry logic for", a), a; i++, await Ee(n); } } function De(e) { return !e || typeof e != "object" ? !1 : !("status" in e) || Le(e.status); } function Le(e) { return typeof e == "number" && (e < 400 || e >= 500); } async function Oe(e, t = {}) { const n = await new Promise(x); return He(n.search, Ie, Pe, je, pe)(e, t); } function He(e, ...t) { return t.reduce((n, o) => (r, i) => o(r, i, n), e); } const $e = [ "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 $(e, t = {}) { const n = e.products?.fields ?? $e, o = e.products?.facets ?? ["*"], r = e.products?.size ?? 20, i = e.products?.from ?? 0, a = await Oe( { ...e, products: { ...e.products, fields: n, facets: o, size: r, from: i } }, t ); return { query: e, response: a }; } const T = { serpPath: "/search", queryParamName: "query", enabled: !0 }; function V() { return { minQueryLength: 2, historyEnabled: !0, historySize: 5, hitDecorators: [], nostoAnalytics: !0, googleAnalytics: T, routingHandler: (e) => { location.href = e; }, nativeSubmit: !1, submit: (e, t, n) => { e.length >= (t.minQueryLength ?? V().minQueryLength) && $( { query: e }, { redirect: !0, track: t.nostoAnalytics ? "serp" : void 0, hitDecorators: t.hitDecorators, ...n } ); } }; } function Te(e) { e.setAttribute("autocomplete", "off"); } function qe(e, { onClick: t, onFocus: n, onInput: o, onKeyDown: r, onSubmit: i }, { form: a = e.form ?? void 0, nativeSubmit: c } = {}) { const m = []; function l(s, u, p) { s.addEventListener(u, p), m.push(() => s.removeEventListener(u, p)); } return (r || i) && l(e, "keydown", (s) => { r?.(e.value, s.key), r && (s.key === "ArrowDown" || s.key === "ArrowUp") ? s.preventDefault() : i && s.key === "Enter" && (e.value !== "" && !s.repeat && i(e.value), c || s.preventDefault()); }), i && a && (l(a, "submit", (s) => { c || s.preventDefault(), i(e.value); }), a.querySelectorAll("[type=submit]").forEach((s) => { l(s, "click", (u) => { c || 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() { m.forEach((s) => s()); } }; } function _e(e, t, n, o, r, i, a) { let c = [], m = [], l = !0, s = -1; function u(f) { const g = f?.dataset?.nsHit; if (g) { const y = q(g); if (j(), 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 p() { l = !e.innerHTML.trim(), l || (c = Array.from( e.querySelectorAll("[data-ns-hit]") ).map((f) => (A(f), f))); } function v() { Object.entries(a ?? {}).map(([f, g]) => { 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)}`], J = () => { g({ data: ce, el: w, update: k }); }; w.addEventListener("click", J), m.push(() => { w.removeEventListener("click", J); }); }); }); } function A(f) { const g = () => { u(f); }; f.addEventListener("click", g), m.push(() => { f.removeEventListener("click", g); }); } function S(f, g) { if (typeof g == "number" && c[g] && c[g].classList.remove("selected"), typeof f == "number" && c[f]) { c[f]?.classList.add("selected"); const y = c[f]?.dataset?.nsHit; if (y) { const w = q(y); if (w.item) { r(w.item); return; } if (w.keyword) { r(w.keyword); return; } } } } function b() { L(), c = [], m.forEach((f) => f()), m = []; } async function k(f) { b(), await n(e, f), setTimeout(() => { p(), v(), M(); }, 0); } function j() { L(), e.style.display = "none"; } function M() { l ? j() : e.style.display = ""; } function ee() { b(), l = !0, j(); } function F() { return e.style.display !== "none"; } function te() { let f = s; s === c.length - 1 ? s = 0 : f = s++, S(s, f); } function ne() { if (N()) { let f = s; s === 0 ? s = c.length - 1 : f = s--, S(s, f); } else s = c.length - 1, S(s); } function oe() { F() && N() && c[s] && u(c[s]); } function N() { return s > -1; } function re() { return c[s]; } function L() { N() && (c[s]?.classList.remove("selected"), s = -1); } function ie() { b(), l = !0, e.innerHTML = ""; } async function se() { const f = await Promise.resolve(t); await Promise.resolve(n(e, f)), setTimeout(() => { p(), v(), j(); }, 0); } return se(), { update: k, clear: ee, isOpen: F, goDown: te, goUp: ne, handleSubmit: oe, destroy: ie, show: M, hide: j, resetHighlight: L, hasHighlight: N, getHighlight: re, container: e }; } function q(e) { try { return JSON.parse(e) ?? {}; } catch (t) { return h.warn("Could not parse hit", t), {}; } } class W extends Error { } function Ue(e) { let t = !1; return { promise: new Promise((n, o) => e.then( (r) => t ? o(new W("cancelled promise")) : n(r), (r) => o(t ? new W("cancelled promise") : r) )), cancel() { t = !0; } }; } function Me({ config: e, history: t, input: n }) { let o; const r = (s, u, p) => typeof u.fetch == "function" ? u.fetch(s) : $( { query: s, ...u.fetch }, { track: u.nostoAnalytics ? "autocomplete" : void 0, redirect: !1, hitDecorators: u.hitDecorators, ...p } ); function i(s) { return Promise.resolve({ query: { query: s }, history: t?.getItems() }); } function a(s, u) { return o?.cancel(), s && s.length >= e.minQueryLength ? (o = Ue(r(s, e, u)), o.promise) : t ? i(s ?? "") : ( // @ts-expect-error type mismatch o?.promise ?? Promise.resolve({}) ); } function c(s) { return t && t.add(s), i(n.value); } function m(s) { return t && t.remove(s), i(n.value); } function l() { return t && t.clear(), i(n.value); } return { updateState: a, addHistoryItem: c, removeHistoryItem: m, clearHistory: l }; } function E(e, t) { return (typeof e == "string" ? Array.from(document.querySelectorAll(e)) : [e]).filter( (n) => t ? n instanceof t : !0 ); } function Z(e, t) { let n = []; return E(e).forEach((o) => { const r = o.parentNode; r !== document && r instanceof Element && (n.push(r), n = n.concat(Z(r))); }), n.filter( (o) => t === void 0 ); } function Fe([e, t], n) { const o = (r) => { const i = r.target; i instanceof HTMLElement && e && i !== e && i !== t && !Z(i).includes(e) && n(); }; return document.addEventListener("click", o), { destroy: () => { document.removeEventListener("click", o); } }; } const _ = "nosto:autocomplete:gaEvent"; function I(e) { const { delay: t = !1, title: n = document.title, location: o = window.location.href } = e || {}; if (t) Je(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) { h.warn("Could not send pageview to GA", r); } } } const D = (e) => typeof e.googleAnalytics == "boolean" ? e.googleAnalytics : typeof e.googleAnalytics == "object" && e.googleAnalytics.enabled, U = (e, t) => { const n = D(t) ? typeof t.googleAnalytics == "boolean" ? T : { ...T, ...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) { h.warn("Could not create track url", o); return; } }; function Je(e, t) { localStorage.setItem(_, JSON.stringify({ title: e, location: t })); } function Re() { const e = localStorage.getItem(_); if (typeof e == "string") { localStorage.removeItem(_); try { const t = JSON.parse(e); I(t); } catch (t) { h.warn("Could not consume pageView", t); } } } function ze(e) { let t, n = !1; return (o) => { n ? (t && clearTimeout(t), t = setTimeout(async () => { await o(), n = !1; }, e)) : (o(), n = !0); }; } function Ge(e) { const t = "nosto:autocomplete:history"; let n = o(); function o() { try { return JSON.parse(localStorage.getItem(t) ?? "[]") ?? []; } catch (l) { return h.error("Could not get history items.", l), []; } } function r(l) { try { localStorage.setItem(t, JSON.stringify(l)); } catch (s) { h.error("Could not set history items.", s); } } function i(l) { r( n = [{ item: l }, ...n?.filter((s) => s.item !== l) || []].slice( 0, e ) ); } function a() { r(n = []); } function c(l) { r(n = n.filter((s) => s.item !== l)); } function m() { return n; } return { add: i, clear: a, remove: c, getItems: m }; } function Ke(e) { const t = { ...V(), ...e }, n = t.historyEnabled ? Ge(t.historySize) : void 0, o = ze(300); D(e) && setTimeout(Re, 1e3); const r = E(e.inputSelector, HTMLInputElement).map( (i) => { const a = Me({ config: t, history: n, input: i }), c = Be({ input: i, config: t, actions: a }); if (!c) return; Te(i); const m = qe(i, { onInput: async (s) => { o(async () => { const u = await a.updateState(s); c.update(u); }); }, onClick() { c.resetHighlight(); }, onFocus() { c.show(); }, onSubmit() { if (c.isOpen() && c.hasHighlight()) { const s = c.getHighlight()?.dataset?.nsHit; s && X({ config: t, data: s, query: i.value }), c.handleSubmit(); } else Y({ actions: a, config: t })(i.value); }, onKeyDown(s, u) { u === "Escape" ? c.hide() : u === "ArrowDown" ? c.isOpen() ? c.goDown() : c.show() : u === "ArrowUp" && c.isOpen() && c.goUp(); } }, { nativeSubmit: t.nativeSubmit }), l = Fe( [c.container, i], () => { c.hide(); } ); return { open() { c.show(); }, close() { c.hide(); }, destroy() { m.destroy(), l.destroy(), c.destroy(); } }; } ); return { destroy() { r.forEach((i) => i?.destroy()); }, open() { r.forEach((i) => i?.open()); }, close() { r.forEach((i) => i?.close()); } }; } function Be({ input: e, config: t, actions: n }) { const o = typeof t.dropdownSelector == "function" ? E(t.dropdownSelector(e), HTMLElement) : E(t.dropdownSelector, HTMLElement); if (o.length === 0) { h.error(`No dropdown element found for input ${e}`); return; } else o.length > 1 && h.error( `Multiple dropdown elements found for input ${e}, using the first element` ); const r = o[0]; return _e( r, n.updateState(e.value), t.render, Y({ actions: n, config: t }), (i) => e.value = i, t.routingHandler, { removeHistory: async function({ data: i, update: a }) { if (i === "all") { const c = await n.clearHistory(); return a(c); } else if (i) { const c = await n.removeHistoryItem(i); return a(c); } }, hit: function({ data: i }) { i && X({ config: t, data: i, query: e.value }); } } ); } async function X({ config: e, data: t, query: n }) { if (!e.googleAnalytics && !e.nostoAnalytics) return; const o = q(t); e.nostoAnalytics && o && fe(o), D(e) && (o._redirect && I({ delay: !0, location: U(o.keyword, e) }), o.url && I({ delay: !0, location: U(n, e) })); } function Y(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 && me(t), D(o) && I({ delay: !0, location: U(t, o) }), !i && typeof o?.submit == "function" && o.submit(t, o, n)); }; } const Qe = { defaultCurrency: "EUR", defaultLocale: "en-US", /** @hidden */ currencySettings: {} }, Ve = { 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 We(e = {}) { const t = { ...Qe, ...e }; e.currencySettings || x((o) => { t.currencySettings = o.internal.getSettings().currencySettings ?? {}; }); function n(o, r) { const { defaultCurrency: i, currencySettings: a, defaultLocale: c } = t, m = r ?? i, l = Ve[m] ?? c; if (m in a) { const s = a[m], u = new Intl.NumberFormat(l, { useGrouping: !!s.groupingSeparator, minimumFractionDigits: s.decimalPlaces, maximumFractionDigits: s.decimalPlaces }).formatToParts(o).map((p) => p.type === "group" ? s.groupingSeparator : p.type === "decimal" ? s.decimalCharacter : p.value).join(""); return s != null && s.currencyBeforeAmount ? `${s.currencyToken}${u}` : `${u}${s?.currencyToken}`; } return new Intl.NumberFormat(l, { style: "currency", currency: m }).format(o); } return { formatCurrency: n }; } function Ze(e) { const { formatCurrency: t } = We(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 = ae, exports.autocomplete = Ke, exports.priceDecorator = Ze, exports.search = $; //# sourceMappingURL=autocomplete.cjs.map