UNPKG

@nosto/autocomplete

Version:

Library designed to simplify the implementation of search autocomplete functionality

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