UNPKG

@nosto/autocomplete

Version:

Library designed to simplify the implementation of search autocomplete functionality

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