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