UNPKG

@nosto/autocomplete

Version:

Library designed to simplify the implementation of search autocomplete functionality

1,070 lines (1,066 loc) 26 kB
"use strict"; var z = require("handlebars"), R = `<div class="ns-autocomplete-results"> {{#if response.keywords.hits.length}} <div class="ns-autocomplete-keywords"> <div class="ns-autocomplete-header"> Keywords </div> {{#each response.keywords.hits}} <div class="ns-autocomplete-keyword" data-ns-hit="{{toJson this}}" data-testid="keyword"> {{#if _highlight.keyword}} <span>{{{_highlight.keyword}}}</span> {{else}} <span>{{keyword}}</span> {{/if}} </div> {{/each}} </div> {{/if}} {{#if response.products.hits.length}} <div class="ns-autocomplete-products"> <div class="ns-autocomplete-header"> Products </div> {{#each response.products.hits}} <a class="ns-autocomplete-product" href="{{url}}" data-ns-hit="{{toJson this}}" data-testid="product"></a> <img class="ns-autocomplete-product-image" src="{{#if imageUrl}}{{ imageUrl }}{{else}}{{ imagePlaceholder }}{{/if}}" alt="{{name}}" width="60" height="40" /> <div class="ns-autocomplete-product-info"> {{#if brand}} <div class="ns-autocomplete-product-brand"> {{brand}} </div> {{/if}} <div class="ns-autocomplete-product-name"> {{name}} </div> <div> <span> {{price}}&euro; </span> {{#if showListPrice}} <span class="ns-autocomplete-product-list-price"> {{listPrice}}&euro; </span> {{/if}} </div> </div> </a> {{/each}} </div> {{/if}} {{#if history.length}} <div class="ns-autocomplete-history"> <div class="ns-autocomplete-header"> Recently searched </div> {{#each history}} <div class="ns-autocomplete-history-item" data-ns-hit="{{toJson this}}" data-testid="history"> {{item}} <a href="#" class="ns-autocomplete-history-item-remove" data-ns-remove-history="{{item}}"> &#x2715; </a> </div> {{/each}} </div> <div class="ns-autocomplete-history-clear"> <button type="button" class="ns-autocomplete-button" data-ns-remove-history="all"> Clear history </button> </div> {{/if}} {{#if response.keywords.hits.length}} {{#if response.products.hits.length}} <div class="ns-autocomplete-submit"> <button type="submit" class="ns-autocomplete-button"> See all search results </button> </div> {{/if}} {{/if}} </div> `; const ye = { helpers: { toJson: function() { return JSON.stringify(this); }, showListPrice: function() { return this.listPrice !== this.price; } } }; function F(e, t) { if (z === void 0) throw new Error("Handlebars is not defined. Please include the Handlebars dependency or library in your page."); const n = z.compile(e); return (r, o) => (r.innerHTML = n( { ...o, imagePlaceholder: "https://cdn.nosto.com/nosto/9/mock" }, t ?? ye ), Promise.resolve()); } function G() { window.nostojs = window.nostojs ?? function(e) { (window.nostojs.q = window.nostojs.q ?? []).push(e); }; } async function H(e) { return window.nostojs(e); } typeof window < "u" && (G(), H((e) => { e.internal.getSettings(); })), typeof window < "u" && G(); function ge(e) { H((t) => t.recordSearchClick("autocomplete", e)); } function he(e) { H((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 S(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) => S(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]) => S(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 k(e) { return (...t) => { b((n) => { (n.internal.context.mode.isPreview() ? console[e] : n.internal.logger[e])(...t); }); }; } const m = { debug: k("debug"), info: k("info"), warn: k("warn"), error: k("error") }; function we(e, t, n) { try { const r = JSON.stringify(t); n.setItem(e, r); } catch (r) { m.warn(r); } } function ve(e, t) { try { const n = t.getItem(e); if (n) return JSON.parse(n); } catch (n) { m.warn(n); } } let W, A; try { W = window.localStorage, A = window.sessionStorage; } catch (e) { m.warn(e), W = V(), A = V(); } function be(e, t) { we(e, t, A); } function Se(e) { return ve(e, A); } async function ke(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((c, f) => f(c), 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) { be(Z, { query: e, result: t, created: Date.now() }); } function Pe(e) { const t = Se(Z); if (!t || !Ee(t)) return null; const n = X(t.query); return !S(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 Ee(e) { return typeof e == "object" && e !== null && "query" in e && "result" in e && "created" in e; } async function Ie(e, { usePersistentCache: t, ...n }, r) { if (!t) return r(e, n); const o = await De(e, n, r); return Ce(e, o), o; } async function De(e, t, n) { const { from: r = 0, size: o = 0 } = e.products || {}, i = Pe(e); if (!i) return await n(e, t); const a = i?.products?.size ?? 0, c = i?.products?.hits ?? []; if (o === a) return i; if (o < a) return { ...i, products: { ...i.products, size: o, hits: c.slice(0, o), total: i.products?.total || 0 } }; const f = o - c.length, u = r > 0 ? r + 1 : o - f, s = { ...e, products: { ...e.products, from: u, size: f } }, l = await n(s, t); return { ...i, products: { ...i.products, size: o, hits: [...i.products?.hits || [], ...l.products?.hits || []], total: l.products?.total || 0 } }; } const Le = 3e4, N = /* @__PURE__ */ new Map(); function He(e, t) { const n = N.get(e); if (!n) return; const r = Date.now() - n.created > Le, o = S(t, n.query); if (r || !o) { N.delete(e); return; } return n.result; } function Ne(e, t, n) { N.set(e, { query: t, result: n, created: Date.now() }); } async function Te(e, t, n) { if (!t.useMemoryCache) return n(e, t); const r = JSON.stringify(e), o = He(r, e); if (o) return o; const i = await n(e, t); return Ne(r, e, i), i; } async function qe(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 Oe(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 (!je(a)) throw m.info("Skipping retry logic for", a), a; i++, await $e(n); } } function je(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 _e(e, t = {}) { const n = await new Promise(b); return Me( n.search, Oe, qe, Te, Ie, ke )(e, t); } function Me(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 T(e, t = {}) { const n = e.products?.fields ?? Je, r = e.products?.facets ?? ["*"], o = e.products?.size ?? 20, i = e.products?.from ?? 0, a = await _e( { ...e, products: { ...e.products, fields: n, facets: r, size: o, from: i } }, t ); return { query: e, response: a }; } const q = { serpPath: "/search", queryParamName: "query", enabled: !0 }; function Y() { return { minQueryLength: 2, historyEnabled: !0, historySize: 5, hitDecorators: [], nostoAnalytics: !0, googleAnalytics: q, routingHandler: (e) => { location.href = e; }, nativeSubmit: !1, submit: (e, t, n) => { e.length >= (t.minQueryLength ?? Y().minQueryLength) && T( { query: e }, { redirect: !0, track: t.nostoAnalytics ? "serp" : void 0, hitDecorators: t.hitDecorators, ...n } ); } }; } function xe(e, { onClick: t, onFocus: n, onInput: r, onKeyDown: o, onSubmit: i }, { form: a = e.form ?? void 0, nativeSubmit: c } = {}) { const f = []; function u(s, l, y) { s.addEventListener(l, y), f.push(() => s.removeEventListener(l, y)); } return (o || i) && u(e, "keydown", (s) => { const l = o?.(e.value, s.key); o && (s.key === "ArrowDown" || s.key === "ArrowUp") ? s.preventDefault() : i && s.key === "Enter" && (e.value !== "" && !s.repeat && !l && i(e.value), c || s.preventDefault()); }), i && a && (u(a, "submit", (s) => { c || s.preventDefault(), i(e.value); }), a.querySelectorAll("[type=submit]").forEach((s) => { u(s, "click", (l) => { c || 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((s) => s()); } }; } function ze(e) { e.setAttribute("autocomplete", "off"); } function Re(e, t, n, r, o, i, a) { let c = [], f = [], u = !0, s = -1; function l(d) { const g = d?.dataset?.nsHit; if (g) { const p = $(g); if (w(), 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 y() { u = !e.innerHTML.trim(), u || (c = Array.from(e.querySelectorAll("[data-ns-hit]")).map((d) => (se(d), d))); } function U() { Object.entries(a ?? {}).map(([d, g]) => { const p = `[data-ns-${d.replace(/([A-Z])/g, "-$1").toLowerCase()}]`; Array.from(e.querySelectorAll(p)).map((h) => { const me = h?.dataset?.[`ns${d.charAt(0).toUpperCase() + d.slice(1)}`], x = () => { g({ data: me, el: h, update: _ }); }; h.addEventListener("click", x), f.push(() => { h.removeEventListener("click", x); }); }); }); } function se(d) { const g = () => { l(d); }; d.addEventListener("click", g), f.push(() => { d.removeEventListener("click", g); }); } function I(d, g) { if (typeof g == "number" && c[g] && c[g].classList.remove("selected"), typeof d == "number" && c[d]) { c[d]?.classList.add("selected"); const p = c[d]?.dataset?.nsHit; if (p) { const h = $(p); if (h.item) { o(h.item); return; } if (h.keyword) { o(h.keyword); return; } } } } function D() { L(), c = [], f.forEach((d) => d()), f = []; } async function _(d) { D(), await n(e, d), setTimeout(() => { y(), U(), M(); }, 0); } function w() { L(), e.style.display = "none"; } function M() { u ? w() : e.style.display = ""; } function ce() { D(), u = !0, w(); } function J() { return e.style.display !== "none"; } function ae() { let d = s; s === c.length - 1 ? s = 0 : d = s++, I(s, d); } function ue() { if (v()) { let d = s; s === 0 ? s = c.length - 1 : d = s--, I(s, d); } else s = c.length - 1, I(s); } function le() { J() && v() && c[s] && l(c[s]); } function v() { return s > -1; } function de() { return c[s]; } function L() { v() && (c[s]?.classList.remove("selected"), s = -1); } function fe() { D(), u = !0, e.innerHTML = ""; } async function pe() { const d = await Promise.resolve(t); await Promise.resolve(n(e, d)), setTimeout(() => { y(), U(), w(); }, 0); } return pe(), { update: _, clear: ce, isOpen: J, goDown: ae, goUp: ue, handleSubmit: le, destroy: fe, show: M, hide: w, resetHighlight: L, hasHighlight: v, getHighlight: de, container: e }; } function $(e) { try { return JSON.parse(e) ?? {}; } catch (t) { return m.warn("Could not parse hit", t), {}; } } class ee extends Error { } function Fe(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 Ge({ config: e, history: t, input: n }) { let r; const o = (s, l, y) => typeof l.fetch == "function" ? l.fetch(s) : T( { query: s, ...l.fetch }, { track: l.nostoAnalytics ? "autocomplete" : void 0, redirect: !1, hitDecorators: l.hitDecorators, ...y } ); function i(s) { return Promise.resolve({ query: { query: s }, history: t?.getItems() }); } function a(s, l) { return r?.cancel(), s && s.length >= e.minQueryLength ? (r = Fe(o(s, e, l)), r.promise) : t ? i(s ?? "") : ( // @ts-expect-error type mismatch r?.promise ?? Promise.resolve({}) ); } function c(s) { return t && t.add(s), i(n.value); } function f(s) { return t && t.remove(s), i(n.value); } function u() { return t && t.clear(), i(n.value); } return { updateState: a, addHistoryItem: c, removeHistoryItem: f, clearHistory: u }; } function C(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 C(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 Ke([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 O = "nosto:autocomplete:gaEvent"; function P(e) { const { delay: t = !1, title: n = document.title, location: r = window.location.href } = e || {}; if (t) Be(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) { m.warn("Could not send pageview to GA", o); } } } const E = (e) => typeof e.googleAnalytics == "boolean" ? e.googleAnalytics : typeof e.googleAnalytics == "object" && e.googleAnalytics.enabled, j = (e, t) => { const n = E(t) ? typeof t.googleAnalytics == "boolean" ? q : { ...q, ...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) { m.warn("Could not create track url", r); return; } }; function Be(e, t) { localStorage.setItem(O, JSON.stringify({ title: e, location: t })); } function Qe() { const e = localStorage.getItem(O); if (typeof e == "string") { localStorage.removeItem(O); try { const t = JSON.parse(e); P(t); } catch (t) { m.warn("Could not consume pageView", t); } } } function Ve(e) { let t, n = !1; return (r) => { n ? (t && clearTimeout(t), t = setTimeout(async () => { await r(), n = !1; }, e)) : (r(), n = !0); }; } function We(e) { const t = "nosto:autocomplete:history"; let n = r(); function r() { try { return JSON.parse(localStorage.getItem(t) ?? "[]") ?? []; } catch (u) { return m.error("Could not get history items.", u), []; } } function o(u) { try { localStorage.setItem(t, JSON.stringify(u)); } catch (s) { m.error("Could not set history items.", s); } } function i(u) { o(n = [{ item: u }, ...n?.filter((s) => s.item !== u) || []].slice(0, e)); } function a() { o(n = []); } function c(u) { o(n = n.filter((s) => s.item !== u)); } function f() { return n; } return { add: i, clear: a, remove: c, getItems: f }; } function ne(e) { const t = { ...Y(), ...e }, n = t.historyEnabled ? We(t.historySize) : void 0, r = Ve(300); E(e) && setTimeout(Qe, 1e3); const o = C(e.inputSelector, HTMLInputElement).map((i) => { const a = Ge({ config: t, history: n, input: i }), c = Ze({ input: i, config: t, actions: a }); if (!c) return; ze(i); const f = xe( i, { onInput: async (s) => { r(async () => { const l = await a.updateState(s); c.update(l); }); }, onClick() { c.resetHighlight(); }, onFocus() { c.show(); }, onSubmit() { if (c.isOpen() && c.hasHighlight()) { const s = c.getHighlight()?.dataset?.nsHit; s && oe({ config: t, data: s, query: i.value }), c.handleSubmit(); } else re({ actions: a, config: t })(i.value); }, onKeyDown(s, l) { l === "Escape" ? c.hide() : l === "ArrowDown" ? c.isOpen() ? c.goDown() : c.show() : l === "ArrowUp" && c.isOpen() && c.goUp(); } }, { nativeSubmit: t.nativeSubmit } ), u = Ke([c.container, i], () => { c.hide(); }); return { open() { c.show(); }, close() { c.hide(); }, destroy() { f.destroy(), u.destroy(), c.destroy(); } }; }); return { destroy() { o.forEach((i) => i?.destroy()); }, open() { o.forEach((i) => i?.open()); }, close() { o.forEach((i) => i?.close()); } }; } function Ze({ input: e, config: t, actions: n }) { const r = typeof t.dropdownSelector == "function" ? C(t.dropdownSelector(e), HTMLElement) : C(t.dropdownSelector, HTMLElement); if (r.length === 0) { m.error(`No dropdown element found for input ${e}`); return; } else r.length > 1 && m.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 c = await n.clearHistory(); return a(c); } else if (i) { const c = await n.removeHistoryItem(i); return a(c); } }, hit: function({ data: i }) { i && oe({ config: t, data: i, query: e.value }); } } ); } async function oe({ config: e, data: t, query: n }) { if (!e.googleAnalytics && !e.nostoAnalytics) return; const r = $(t); e.nostoAnalytics && r && ge(r), E(e) && (r._redirect && P({ delay: !0, location: j(r.keyword, e) }), r.url && P({ delay: !0, location: j(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 && he(t), E(r) && P({ delay: !0, location: j(t, r) }), !i && typeof r?.submit == "function" && r.submit(t, r, n)); }; } const Xe = { defaultCurrency: "EUR", defaultLocale: "en-US", /** @hidden */ currencySettings: {} }, Ye = { 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 et(e = {}) { const t = { ...Xe, ...e }; e.currencySettings || b((r) => { t.currencySettings = r.internal.getSettings().currencySettings ?? {}; }); function n(r, o) { const { defaultCurrency: i, currencySettings: a, defaultLocale: c } = t, f = o ?? i, u = Ye[f] ?? c; if (f in a) { const s = a[f], l = new Intl.NumberFormat(u, { useGrouping: !!s.groupingSeparator, minimumFractionDigits: s.decimalPlaces, maximumFractionDigits: s.decimalPlaces }).formatToParts(r).map((y) => y.type === "group" ? s.groupingSeparator : y.type === "decimal" ? s.decimalCharacter : y.value).join(""); return s?.currencyBeforeAmount ? `${s.currencyToken}${l}` : `${l}${s?.currencyToken}`; } return new Intl.NumberFormat(u, { style: "currency", currency: f }).format(r); } return { formatCurrency: n }; } function tt(e) { const { formatCurrency: t } = et(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; }; } async function nt(e, { handler: t, defaultTemplate: n }) { const r = e.querySelector("script[autocomplete-template]")?.textContent, o = ot(e); if (!Object.keys(o).length) throw new Error("NostoAutocomplete: Missing required config."); return ne({ ...o, nativeSubmit: !0, render: t(r ?? n), submit(i) { e.querySelector(o.inputSelector).value = i, e.querySelector("form")?.submit(); } }); } function ot(e) { const t = e.querySelector("script[autocomplete-config]"); return t ? JSON.parse(t.textContent) : {}; } class ie extends HTMLElement { async connectedCallback() { return nt(this, { handler: F, defaultTemplate: R }); } } customElements.define("nosto-autocomplete", ie), exports.NostoAutocomplete = ie, exports.autocomplete = ne, exports.defaultHandlebarsTemplate = R, exports.fromHandlebarsTemplate = F, exports.priceDecorator = tt, exports.search = T; //# sourceMappingURL=autocomplete.cjs.map