cloudcommerce 2.3.1 → 2.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/ecomplus-stores/barra-doce/functions/many/package.json +3 -3
  3. package/ecomplus-stores/barra-doce/functions/ssr/package.json +6 -6
  4. package/ecomplus-stores/barra-doce/functions/with-apps/package.json +3 -3
  5. package/ecomplus-stores/barra-doce/package.json +2 -2
  6. package/package.json +6 -6
  7. package/packages/api/package.json +1 -1
  8. package/packages/apps/affiliate-program/package.json +1 -1
  9. package/packages/apps/correios/package.json +2 -2
  10. package/packages/apps/custom-payment/package.json +1 -1
  11. package/packages/apps/custom-shipping/package.json +1 -1
  12. package/packages/apps/datafrete/package.json +1 -1
  13. package/packages/apps/discounts/package.json +1 -1
  14. package/packages/apps/emails/package.json +1 -1
  15. package/packages/apps/fb-conversions/package.json +2 -2
  16. package/packages/apps/flash-courier/package.json +1 -1
  17. package/packages/apps/frenet/package.json +1 -1
  18. package/packages/apps/galaxpay/package.json +1 -1
  19. package/packages/apps/google-analytics/package.json +1 -1
  20. package/packages/apps/jadlog/package.json +1 -1
  21. package/packages/apps/loyalty-points/package.json +1 -1
  22. package/packages/apps/mandae/package.json +1 -1
  23. package/packages/apps/melhor-envio/package.json +1 -1
  24. package/packages/apps/mercadopago/package.json +1 -1
  25. package/packages/apps/pagarme/package.json +1 -1
  26. package/packages/apps/pagarme-v5/package.json +1 -1
  27. package/packages/apps/paghiper/package.json +1 -1
  28. package/packages/apps/pix/package.json +1 -1
  29. package/packages/apps/tiny-erp/package.json +1 -1
  30. package/packages/apps/webhooks/package.json +1 -1
  31. package/packages/cli/package.json +1 -1
  32. package/packages/config/package.json +1 -1
  33. package/packages/emails/package.json +1 -1
  34. package/packages/eslint/package.json +5 -5
  35. package/packages/events/package.json +1 -1
  36. package/packages/feeds/package.json +1 -1
  37. package/packages/firebase/package.json +2 -2
  38. package/packages/i18n/package.json +1 -1
  39. package/packages/modules/package.json +1 -1
  40. package/packages/passport/package.json +1 -1
  41. package/packages/ssr/lib/lib/analytics/send-to-ga4.js +2 -1
  42. package/packages/ssr/lib/lib/analytics/send-to-ga4.js.map +1 -1
  43. package/packages/ssr/lib/lib/analytics-events.js +11 -1
  44. package/packages/ssr/lib/lib/analytics-events.js.map +1 -1
  45. package/packages/ssr/lib/lib/serve-storefront.js +35 -21
  46. package/packages/ssr/lib/lib/serve-storefront.js.map +1 -1
  47. package/packages/ssr/package.json +3 -3
  48. package/packages/ssr/src/lib/analytics/send-to-ga4.ts +2 -0
  49. package/packages/ssr/src/lib/analytics-events.ts +11 -1
  50. package/packages/ssr/src/lib/serve-storefront.ts +36 -22
  51. package/packages/storefront/astro.config.mjs +4 -1
  52. package/packages/storefront/config/astro/vue-server.mjs +64 -0
  53. package/packages/storefront/dist/client/_astro/{AccountPage.3-eqV6OR.js → AccountPage.0M6_FdU6.js} +1 -1
  54. package/packages/storefront/dist/client/_astro/{CartSidebar.-Gy6eqIy.js → CartSidebar.L0Vbhsdt.js} +1 -1
  55. package/packages/storefront/dist/client/_astro/ProductDetails.FQtM5kpd.js +7 -0
  56. package/packages/storefront/dist/client/_astro/{ProductShelf.qbTNzuvn.js → ProductShelf.-4fsYkPB.js} +1 -1
  57. package/packages/storefront/dist/client/_astro/{ProductShelf.b77WjhZZ.js → ProductShelf.GAAhKdTN.js} +1 -1
  58. package/packages/storefront/dist/client/_astro/{SearchModal.WzDMBjqi.js → SearchModal.rasg5jV6.js} +1 -1
  59. package/packages/storefront/dist/client/_astro/SearchShowcase.kA6jICYo.js +1 -0
  60. package/packages/storefront/dist/client/_astro/ShopHeader.v_L96Y90.js +7 -0
  61. package/packages/storefront/dist/client/_astro/{_slug_.WkuZ8tvp.css → _slug_.4W7qhV-L.css} +1 -1
  62. package/packages/storefront/dist/client/_astro/customer-session.ZD6tLDQJ.js +7 -0
  63. package/packages/storefront/dist/client/_astro/{firebase-app.VduCDgof.js → firebase-app.iLdzDVjL.js} +1 -1
  64. package/packages/storefront/dist/client/_astro/hoisted.GaT7bmE3.js +1 -0
  65. package/packages/storefront/dist/client/_astro/{hoisted.xTPkED8g.js → hoisted.ICXGWNEA.js} +1 -1
  66. package/packages/storefront/dist/client/_astro/hoisted.XOXTrHqn.js +1 -0
  67. package/packages/storefront/dist/client/_astro/{index-dd468b12.fl8bpn8l.js → index-bea2a320.eWykogwr.js} +93 -93
  68. package/packages/storefront/dist/client/_astro/{shopping-cart.v-dB3kHB.js → shopping-cart.nSNNOrp9.js} +1 -1
  69. package/packages/storefront/dist/client/_astro/use-analytics.wTmoP8B1.js +1 -0
  70. package/packages/storefront/dist/client/_astro/{use-product-card.nNtSJVtB.js → use-product-card.UFr8SCuD.js} +1 -1
  71. package/packages/storefront/dist/client/_astro/use-text-value.lKqoIagH.js +4 -0
  72. package/packages/storefront/dist/server/chunks/{CartSidebar_blvgfFa-.mjs → CartSidebar_3_1aFp67.mjs} +1 -1
  73. package/packages/storefront/dist/server/chunks/{SearchModal_Sktaq643.mjs → SearchModal_2azP1u7P.mjs} +1 -1
  74. package/packages/storefront/dist/server/chunks/_.._19fCuQdO.mjs +5 -0
  75. package/packages/storefront/dist/server/chunks/{_page__9PfWVh79.mjs → _page__qqIVxbal.mjs} +1 -1
  76. package/packages/storefront/dist/server/chunks/{account_R4bpY7O1.mjs → account_vK6pmJlz.mjs} +1 -1
  77. package/packages/storefront/dist/server/chunks/astro/{assets-service_oQ4-9MNg.mjs → assets-service_631fRtTy.mjs} +66 -11
  78. package/packages/storefront/dist/server/chunks/{astro_ECsNQeA2.mjs → astro_u-oSb215.mjs} +8 -2
  79. package/packages/storefront/dist/server/chunks/{index__PeYBuja.mjs → index__05fnqFh.mjs} +1 -1
  80. package/packages/storefront/dist/server/chunks/{node_njrZIjT6.mjs → node_zqXXqc-u.mjs} +1 -1
  81. package/packages/storefront/dist/server/chunks/pages/{__XOsz50la.mjs → __ZucPYaOo.mjs} +380 -118
  82. package/packages/storefront/dist/server/chunks/pages/{_page__cIw_KTpN.mjs → _page__0sN9U0SD.mjs} +19 -3
  83. package/packages/storefront/dist/server/chunks/pages/account_OQr_6KN1.mjs +33 -0
  84. package/packages/storefront/dist/server/chunks/pages/{index_KP7Gn0ld.mjs → index_3IjgOEIq.mjs} +15 -4
  85. package/packages/storefront/dist/server/chunks/pages/node_OmjWRf8D.mjs +112 -0
  86. package/packages/storefront/dist/server/chunks/pages/~fallback_133FK-CP.mjs +59 -0
  87. package/packages/storefront/dist/server/chunks/~fallback_Wahcp9Wk.mjs +5 -0
  88. package/packages/storefront/dist/server/entry.mjs +9 -9
  89. package/packages/storefront/dist/server/manifest_9FASPYUE.mjs +202 -0
  90. package/packages/storefront/dist/server/renderers.mjs +45 -34
  91. package/packages/storefront/package.json +4 -4
  92. package/packages/storefront/server.d.ts +0 -1
  93. package/packages/storefront/src/lib/$storefront.d.ts +23 -16
  94. package/packages/storefront/src/lib/composables/use-pagination.ts +1 -3
  95. package/packages/storefront/src/lib/layouts/BaseHead.astro +5 -0
  96. package/packages/storefront/src/lib/scripts/push-analytics-events.ts +8 -6
  97. package/packages/storefront/src/lib/ssr-context.ts +46 -6
  98. package/packages/storefront/src/lib/state/use-analytics.ts +12 -11
  99. package/packages/storefront/src/lib/state/use-storage.ts +23 -9
  100. package/packages/test-base/package.json +1 -1
  101. package/packages/types/package.json +1 -1
  102. package/packages/storefront/dist/client/_astro/ProductDetails.ATGXfGhG.js +0 -7
  103. package/packages/storefront/dist/client/_astro/SearchShowcase.9gIA4Cq0.js +0 -1
  104. package/packages/storefront/dist/client/_astro/ShopHeader.Ee4OJr3q.js +0 -7
  105. package/packages/storefront/dist/client/_astro/customer-session.dSYHWdP4.js +0 -7
  106. package/packages/storefront/dist/client/_astro/ecom-icon_12falx.png +0 -0
  107. package/packages/storefront/dist/client/_astro/ecom-icon_15pqnO.png +0 -0
  108. package/packages/storefront/dist/client/_astro/ecom-icon_t3guw.png +0 -0
  109. package/packages/storefront/dist/client/_astro/headphone_T2Jjc.avif +0 -0
  110. package/packages/storefront/dist/client/_astro/headphone_Z1CG18r.webp +0 -0
  111. package/packages/storefront/dist/client/_astro/hoisted.d2SGwVMl.js +0 -1
  112. package/packages/storefront/dist/client/_astro/hoisted.x1b7VHef.js +0 -1
  113. package/packages/storefront/dist/client/_astro/logo_1UBsBq.webp +0 -0
  114. package/packages/storefront/dist/client/_astro/logo_Z1K5PE9.png +0 -0
  115. package/packages/storefront/dist/client/_astro/logo_Z1KIIl1.avif +0 -0
  116. package/packages/storefront/dist/client/_astro/passion_LHbe9.webp +0 -0
  117. package/packages/storefront/dist/client/_astro/passion_Z23MeUb.avif +0 -0
  118. package/packages/storefront/dist/client/_astro/rect8589_1TtOHY.png +0 -0
  119. package/packages/storefront/dist/client/_astro/rect8589_1f5opX.webp +0 -0
  120. package/packages/storefront/dist/client/_astro/rect8589_IUskt.webp +0 -0
  121. package/packages/storefront/dist/client/_astro/rect8589_Uxfdf.png +0 -0
  122. package/packages/storefront/dist/client/_astro/rect8589_Z15uApA.png +0 -0
  123. package/packages/storefront/dist/client/_astro/rect8589_Z1Ap1Im.avif +0 -0
  124. package/packages/storefront/dist/client/_astro/rect8589_Z1JT1HB.webp +0 -0
  125. package/packages/storefront/dist/client/_astro/rect8589_ZY9mtN.avif +0 -0
  126. package/packages/storefront/dist/client/_astro/rect8589_tMFW0.avif +0 -0
  127. package/packages/storefront/dist/client/_astro/rect859_1TgQXS.avif +0 -0
  128. package/packages/storefront/dist/client/_astro/rect859_2Nm1z.avif +0 -0
  129. package/packages/storefront/dist/client/_astro/rect859_DIqwR.png +0 -0
  130. package/packages/storefront/dist/client/_astro/rect859_Z1IKDb2.png +0 -0
  131. package/packages/storefront/dist/client/_astro/rect859_Z29FI4V.webp +0 -0
  132. package/packages/storefront/dist/client/_astro/rect859_Z2kFHGk.avif +0 -0
  133. package/packages/storefront/dist/client/_astro/rect859_ZkpPFI.webp +0 -0
  134. package/packages/storefront/dist/client/_astro/rect859_jXzBi.png +0 -0
  135. package/packages/storefront/dist/client/_astro/rect859_x1l16.webp +0 -0
  136. package/packages/storefront/dist/client/_astro/rect89_1TSfW7.avif +0 -0
  137. package/packages/storefront/dist/client/_astro/rect89_Z1re32x.webp +0 -0
  138. package/packages/storefront/dist/client/_astro/use-analytics._ef6TM4P.js +0 -1
  139. package/packages/storefront/dist/client/_astro/use-text-value.0OP9HCfP.js +0 -4
  140. package/packages/storefront/dist/client/~fallback.html +0 -99
  141. package/packages/storefront/dist/client/~index.html +0 -131
  142. package/packages/storefront/dist/server/chunks/_.._yTK2xBRC.mjs +0 -5
  143. package/packages/storefront/dist/server/chunks/pages/account_l-FHyDJd.mjs +0 -23
  144. package/packages/storefront/dist/server/chunks/pages/node_FoLtkdH1.mjs +0 -257
  145. package/packages/storefront/dist/server/chunks/pages/~fallback_KPp6Nh_p.mjs +0 -34
  146. package/packages/storefront/dist/server/chunks/~fallback_p7P7NIL5.mjs +0 -5
  147. package/packages/storefront/dist/server/images.dist.csv +0 -30
  148. package/packages/storefront/dist/server/images.src.csv +0 -11
  149. package/packages/storefront/dist/server/manifest_E6KbHQrT.mjs +0 -202
  150. package/packages/storefront/dist/server/static-builds.csv +0 -71
@@ -1,6 +1,6 @@
1
1
  import { defineComponent, h, createSSRApp } from 'vue';
2
2
  import { renderToString } from 'vue/server-renderer';
3
- import { m as mod, n as createApp } from './chunks/pages/__XOsz50la.mjs';
3
+ import { o as mod, p as createApp } from './chunks/pages/__ZucPYaOo.mjs';
4
4
 
5
5
  const setup = async (app) => {
6
6
  if ('default' in mod) {
@@ -8,6 +8,8 @@ const setup = async (app) => {
8
8
  }
9
9
  };
10
10
 
11
+ /* eslint-disable no-restricted-syntax */
12
+
11
13
  /**
12
14
  * Astro passes `children` as a string of HTML, so we need
13
15
  * a wrapper `div` to render that content as VNodes.
@@ -15,48 +17,57 @@ const setup = async (app) => {
15
17
  * This is the Vue + JSX equivalent of using `<div v-html="value" />`
16
18
  */
17
19
  const StaticHtml = defineComponent({
18
- props: {
19
- value: String,
20
- name: String,
21
- hydrate: {
22
- type: Boolean,
23
- default: true,
24
- },
25
- },
26
- setup({ name, value, hydrate }) {
27
- if (!value) return () => null;
28
- let tagName = hydrate ? 'astro-slot' : 'astro-static-slot';
29
- return () => h(tagName, { name, innerHTML: value });
30
- },
20
+ props: {
21
+ value: String,
22
+ name: String,
23
+ hydrate: {
24
+ type: Boolean,
25
+ default: true,
26
+ },
27
+ },
28
+ setup({ name, value, hydrate }) {
29
+ if (!value) return () => null;
30
+ const tagName = hydrate ? 'astro-slot' : 'astro-static-slot';
31
+ return () => h(tagName, { name, innerHTML: value });
32
+ },
31
33
  });
32
34
 
35
+ /**
36
+ * Other frameworks have `shouldComponentUpdate` in order to signal
37
+ * that this subtree is entirely static and will not be updated
38
+ *
39
+ * Fortunately, Vue is smart enough to figure that out without any
40
+ * help from us, so this just works out of the box!
41
+ */
42
+
33
43
  function check(Component) {
34
- return !!Component['ssrRender'] || !!Component['__ssrInlineRender'];
44
+ return !!Component.ssrRender || !!Component.__ssrInlineRender;
35
45
  }
36
46
 
37
47
  async function renderToStaticMarkup(Component, inputProps, slotted, metadata) {
38
- const slots = {};
39
- const props = { ...inputProps };
40
- delete props.slot;
41
- for (const [key, value] of Object.entries(slotted)) {
42
- slots[key] = () =>
43
- h(StaticHtml, {
44
- value,
45
- name: key === 'default' ? undefined : key,
46
- // Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
47
- hydrate: metadata.astroStaticSlot ? !!metadata.hydrate : true,
48
- });
49
- }
50
- const app = createSSRApp({ render: () => h(Component, props, slots) });
51
- await setup(app);
52
- const html = await renderToString(app);
53
- return { html };
48
+ const slots = {};
49
+ const props = { ...inputProps };
50
+ delete props.slot;
51
+ const sid = this.result?.cookies?.get('sid')?.value;
52
+ for (const [key, value] of Object.entries(slotted)) {
53
+ slots[key] = () => h(StaticHtml, {
54
+ value,
55
+ name: key === 'default' ? undefined : key,
56
+ // Adjust how this is hydrated only when the version of Astro supports `astroStaticSlot`
57
+ hydrate: metadata.astroStaticSlot ? !!metadata.hydrate : true,
58
+ });
59
+ }
60
+ const app = createSSRApp({ render: () => h(Component, props, slots) });
61
+ app.provide('sid', sid);
62
+ await setup(app);
63
+ const html = await renderToString(app);
64
+ return { html };
54
65
  }
55
66
 
56
67
  const _renderer0 = {
57
- check,
58
- renderToStaticMarkup,
59
- supportsAstroStaticSlot: true,
68
+ check,
69
+ renderToStaticMarkup,
70
+ supportsAstroStaticSlot: true,
60
71
  };
61
72
 
62
73
  const renderers = [Object.assign({"name":"@astrojs/vue","clientEntrypoint":"@astrojs/vue/client.js","serverEntrypoint":"@astrojs/vue/server.js"}, { ssr: _renderer0 }),];
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloudcommerce/storefront",
3
3
  "type": "module",
4
- "version": "2.3.1",
4
+ "version": "2.3.2",
5
5
  "description": "E-Com Plus Cloud Commerce storefront with Astro",
6
6
  "bin": {
7
7
  "storefront": "./scripts/build-prod.sh"
@@ -43,18 +43,18 @@
43
43
  "@types/gtag.js": "^0.0.18",
44
44
  "@vite-pwa/astro": "^0.2.0",
45
45
  "@vueuse/core": "10.7.2",
46
- "astro": "4.3.1",
46
+ "astro": "4.3.2",
47
47
  "astro-capo": "^0.0.1",
48
48
  "chroma-js": "^2.4.2",
49
49
  "dotenv": "^16.4.1",
50
- "firebase": "^10.7.2",
50
+ "firebase": "^10.8.0",
51
51
  "image-size": "^1.1.1",
52
52
  "mime": "^3.0.0",
53
53
  "mitt": "^3.0.1",
54
54
  "semver": "^7.5.4",
55
55
  "sharp": "^0.32.6",
56
56
  "tailwindcss": "^3.4.1",
57
- "unocss": "^0.58.4",
57
+ "unocss": "^0.58.5",
58
58
  "unplugin-auto-import": "^0.17.5",
59
59
  "vite": "^5.0.11",
60
60
  "vite-plugin-pwa": "^0.17.5",
@@ -11,7 +11,6 @@ declare global {
11
11
  assetsPrefix: string,
12
12
  }
13
13
  }
14
- var astroUrl: URL;
15
14
 
16
15
  var $storefront: $Storefront & {
17
16
  onLoad: (callback: (...args: any[]) => void) => void,
@@ -7,24 +7,31 @@ import type {
7
7
  } from '@cloudcommerce/api/types';
8
8
  import type { SettingsContent } from '@@sf/content';
9
9
 
10
+ export type StorefrontApiContext = {
11
+ resource: 'products',
12
+ doc: Products,
13
+ timestamp: number,
14
+ } | {
15
+ resource: 'categories',
16
+ doc: Categories,
17
+ timestamp: number,
18
+ } | {
19
+ resource: 'brands',
20
+ doc: Brands,
21
+ timestamp: number,
22
+ } | {
23
+ resource: 'collections',
24
+ doc: Collections,
25
+ timestamp: number,
26
+ };
27
+
10
28
  export type $Storefront = {
11
29
  settings: Partial<SettingsContent>,
12
- apiContext?: {
13
- resource: 'products',
14
- doc: Products,
15
- timestamp: number,
16
- } | {
17
- resource: 'categories',
18
- doc: Categories,
19
- timestamp: number,
20
- } | {
21
- resource: 'brands',
22
- doc: Brands,
23
- timestamp: number,
24
- } | {
25
- resource: 'collections',
26
- doc: Collections,
27
- timestamp: number,
30
+ url: URL,
31
+ apiContext?: StorefrontApiContext,
32
+ getSession: (sid?: string) => {
33
+ url: URL,
34
+ apiContext?: StorefrontApiContext,
28
35
  },
29
36
  data: Record<string, any> & {
30
37
  categories?: Array<Partial<Categories>>,
@@ -57,9 +57,7 @@ const usePagination = (props: Props) => {
57
57
 
58
58
  const baseUrl = ref('');
59
59
  watch(toRef(props, 'isUrlPath'), () => {
60
- const url = import.meta.env.SSR
61
- ? global.astroUrl
62
- : new URL(window.location.toString());
60
+ const { url } = globalThis.$storefront;
63
61
  if (props.isUrlPath && !url.pathname.endsWith('/')) {
64
62
  url.pathname += '/';
65
63
  } else {
@@ -135,11 +135,16 @@ if (apiDoc) {
135
135
  inlineClientJS += `
136
136
  window._firstLoadContextId = '${apiDoc._id}';`;
137
137
  contextInlineClientJS = `
138
+ $storefront.url = new URL(window.location.toString());
138
139
  $storefront.apiContext = ${JSON.stringify({
139
140
  resource: apiContext.resource,
140
141
  doc: minifyApiDoc({ ...apiDoc }),
141
142
  timestamp: Date.now(),
142
143
  })};
144
+ $storefront.getSession = (/* sid */) => {
145
+ url: $storefront.url,
146
+ apiContext: $storefront.apiContext,
147
+ };
143
148
  $storefront.context /* DEPRECATED */ = $storefront.apiContext;
144
149
  _emitApiContext('${apiDoc._id}');`;
145
150
  } else {
@@ -18,27 +18,29 @@ type AnalyticsEvent = {
18
18
  name: string,
19
19
  params?: Record<string, any>,
20
20
  };
21
+ type AnalyticsVariantCtx = Partial<ReturnType<typeof useAnalytics>>;
21
22
  let eventsToSend: Array<AnalyticsEvent> = [];
22
- const _sendServerEvents = useDebounceFn(() => {
23
+ const _sendServerEvents = useDebounceFn((variantCtx?: AnalyticsVariantCtx) => {
23
24
  afetch(`/_analytics`, {
24
25
  method: 'POST',
25
26
  body: {
27
+ exp_variant_string: variantCtx?.expVariantString,
26
28
  ...getAnalyticsContext(),
27
29
  events: eventsToSend,
28
30
  },
29
31
  });
30
32
  eventsToSend = [];
31
33
  }, 200);
32
- const sendServerEvent = (analyticsEvent: AnalyticsEvent) => {
33
- eventsToSend.push(analyticsEvent);
34
- _sendServerEvents();
35
- };
36
34
 
37
35
  if (
38
36
  !import.meta.env.SSR
39
37
  && !window.location.search.includes(`__isrV=${deployRand}`)
40
38
  ) {
41
- useAnalytics();
39
+ const variantCtx = useAnalytics();
40
+ const sendServerEvent = (analyticsEvent: AnalyticsEvent) => {
41
+ eventsToSend.push(analyticsEvent);
42
+ _sendServerEvents(variantCtx);
43
+ };
42
44
  watchGtagEvents(async (evMessage) => {
43
45
  const { name, params } = evMessage.event;
44
46
  sendServerEvent({ type: 'gtag', name, params });
@@ -3,7 +3,9 @@ import type { BaseConfig } from '@cloudcommerce/config';
3
3
  import type { ApiError, ApiEndpoint } from '@cloudcommerce/api';
4
4
  import type { ResourceId, CategoriesList, BrandsList } from '@cloudcommerce/api/types';
5
5
  import type { ContentGetter, SettingsContent, PageContent } from '@@sf/content';
6
+ import type { StorefrontApiContext } from '@@sf/$storefront';
6
7
  import { EventEmitter } from 'node:events';
8
+ import { inject, getCurrentInstance } from 'vue';
7
9
  import api from '@cloudcommerce/api';
8
10
  import _getConfig from '../../config/storefront.config.mjs';
9
11
  import { termify } from '../helpers/sf-utils';
@@ -38,14 +40,42 @@ declare global {
38
40
  if (!globalThis.$apiPrefetchEndpoints) {
39
41
  globalThis.$apiPrefetchEndpoints = [];
40
42
  }
43
+ const sessions: Record<string, {
44
+ url: URL,
45
+ apiContext?: StorefrontApiContext,
46
+ _timer?: NodeJS.Timeout,
47
+ }> = {};
48
+ // Internal global just to early clear session objects from memory
49
+ global.__sfSessions = sessions;
41
50
  if (!globalThis.$storefront) {
42
- globalThis.$storefront = {
51
+ globalThis.$storefront = new Proxy({
43
52
  settings: {},
53
+ data: {},
54
+ url: undefined as any,
55
+ getSession(sid?: string) {
56
+ if (!sid && !!getCurrentInstance()) {
57
+ sid = inject('sid');
58
+ }
59
+ const {
60
+ url,
61
+ apiContext,
62
+ } = (sid && sessions[sid]) || (global.__sfSession as typeof sessions[string]);
63
+ return { url, apiContext };
64
+ },
44
65
  onLoad(callback: (...args: any[]) => void) {
45
66
  emitter.once('load', callback);
46
67
  },
47
- data: {},
48
- };
68
+ }, {
69
+ get(target, prop) {
70
+ if (prop === 'apiContext') {
71
+ return target.getSession().apiContext;
72
+ }
73
+ if (prop === 'url') {
74
+ return target.getSession().url;
75
+ }
76
+ return target[prop];
77
+ },
78
+ });
49
79
  }
50
80
 
51
81
  declare global {
@@ -81,7 +111,9 @@ const loadRouteContext = async (
81
111
  apiPrefetchEndpoints?: ApiPrefetchEndpoints;
82
112
  } = {},
83
113
  ) => {
84
- globalThis.astroUrl = Astro.url;
114
+ const sid = `${Date.now() + Math.random()}`;
115
+ sessions[sid] = { url: Astro.url };
116
+ global.__sfSession = sessions[sid];
85
117
  const startedAt = Date.now();
86
118
  let urlPath = Astro.url.pathname;
87
119
  const isPreview = urlPath.startsWith('/~preview');
@@ -154,11 +186,16 @@ const loadRouteContext = async (
154
186
  .catch(console.warn);
155
187
  const apiDoc = apiContext.doc as Record<string, any>;
156
188
  apiState[`${apiResource}/${apiDoc._id}`] = apiDoc;
157
- globalThis.$storefront.apiContext = {
189
+ sessions[sid].apiContext = {
158
190
  resource: apiResource,
159
191
  doc: apiDoc as any,
160
192
  timestamp: Date.now(),
161
193
  };
194
+ sessions[sid]._timer = setTimeout(() => {
195
+ // @ts-ignore
196
+ sessions[sid] = null;
197
+ delete sessions[sid];
198
+ }, 6000);
162
199
  resolve(null);
163
200
  })
164
201
  .catch((err: ApiError) => {
@@ -240,10 +277,13 @@ const loadRouteContext = async (
240
277
  apiContext,
241
278
  apiState,
242
279
  isPreview,
280
+ sid,
243
281
  // Astro,
244
282
  };
245
283
  Astro.locals.routeContext = routeContext;
246
- emitter.emit('load', routeContext);
284
+ Astro.cookies.set('sid', sid);
285
+ Astro.response.headers.set('X-SId', sid);
286
+ emitter.emit('load', { ...config, apiState });
247
287
  globalThis.__sfIds = {}; // see helpers/sf-utils.ts
248
288
  return routeContext;
249
289
  };
@@ -227,8 +227,13 @@ export const useAnalytics = ({
227
227
  gtag,
228
228
  GTAG_TAG_ID,
229
229
  GA_TRACKING_ID,
230
+ GIT_BRANCH,
230
231
  } = window as { [k:string]: any, gtag?: Gtag.Gtag };
231
232
  const tagId = GTAG_TAG_ID || GA_TRACKING_ID;
233
+ // https://developers.google.com/analytics/devguides/collection/ga4/integration
234
+ const expVariantString: string | null = GIT_BRANCH && experimentId
235
+ ? `${experimentId}-${GIT_BRANCH}`
236
+ : (GIT_BRANCH?.startsWith('main-') && GIT_BRANCH) || null;
232
237
  if (typeof gtag === 'function') {
233
238
  if (tagId) {
234
239
  ['client_id', 'session_id', 'gclid'].forEach((key) => {
@@ -237,17 +242,10 @@ export const useAnalytics = ({
237
242
  });
238
243
  });
239
244
  }
240
- const { GIT_BRANCH } = window;
241
- if (GIT_BRANCH) {
242
- // https://developers.google.com/analytics/devguides/collection/ga4/integration
243
- const expVariantString = experimentId
244
- ? `${experimentId}-${window.GIT_BRANCH}`
245
- : GIT_BRANCH.startsWith('main-') && GIT_BRANCH;
246
- if (expVariantString) {
247
- gtag('event', 'experience_impression', {
248
- exp_variant_string: expVariantString,
249
- });
250
- }
245
+ if (expVariantString) {
246
+ gtag('event', 'experience_impression', {
247
+ exp_variant_string: expVariantString,
248
+ });
251
249
  }
252
250
  }
253
251
  const url = new URL(window.location.toString());
@@ -315,6 +313,9 @@ export const useAnalytics = ({
315
313
  }
316
314
  }, 300);
317
315
  }
316
+ return {
317
+ expVariantString,
318
+ };
318
319
  };
319
320
 
320
321
  export default useAnalytics;
@@ -5,23 +5,37 @@ const useStorage = <T extends {}>(
5
5
  key: string,
6
6
  initialValue: T,
7
7
  storage = globalThis.localStorage,
8
+ isWithBroadcast = true,
8
9
  ) => {
9
10
  if (!storage) {
10
11
  return reactive<T>(initialValue);
11
12
  }
12
- let persistedValue: T | undefined | null;
13
- const sessionJson = storage.getItem(key);
14
- if (sessionJson) {
15
- try {
16
- persistedValue = JSON.parse(sessionJson);
17
- } catch (e) {
18
- persistedValue = null;
19
- storage.removeItem(key);
13
+ // eslint-disable-next-line consistent-return
14
+ const getStorageItem = () => {
15
+ const sessionJson = storage.getItem(key);
16
+ if (sessionJson) {
17
+ try {
18
+ return JSON.parse(sessionJson) as T;
19
+ } catch (e) {
20
+ storage.removeItem(key);
21
+ return null;
22
+ }
20
23
  }
21
- }
24
+ };
25
+ const persistedValue = getStorageItem();
22
26
  const state = reactive<T>(persistedValue || initialValue);
27
+ let bc: BroadcastChannel | undefined;
28
+ if (isWithBroadcast && !import.meta.env.SSR && globalThis.BroadcastChannel) {
29
+ bc = new BroadcastChannel(key);
30
+ bc.onmessage = (event) => {
31
+ if (event.data === 'set') {
32
+ Object.assign(state, getStorageItem());
33
+ }
34
+ };
35
+ }
23
36
  watchDebounced(state, () => {
24
37
  storage.setItem(key, JSON.stringify(state));
38
+ if (bc) bc.postMessage('set');
25
39
  }, {
26
40
  debounce: 50,
27
41
  });
@@ -2,7 +2,7 @@
2
2
  "name": "@cloudcommerce/test-base",
3
3
  "private": true,
4
4
  "type": "module",
5
- "version": "2.3.1",
5
+ "version": "2.3.2",
6
6
  "description": "E-Com Plus Cloud Commerce basic setup for testing",
7
7
  "main": "lib/index.js",
8
8
  "repository": {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cloudcommerce/types",
3
3
  "type": "module",
4
- "version": "2.3.1",
4
+ "version": "2.3.2",
5
5
  "description": "E-Com Plus Cloud Commerce reusable type definitions",
6
6
  "main": "index.ts",
7
7
  "repository": {
@@ -1,7 +0,0 @@
1
- import{d as R,a as C,N as A,O as u,P as m,a0 as P,W as V,R as b,S as v,Y as w,U as z,V as k,Z as I,ac as F,a7 as H,M as J,r as L,w as T,aa as M,c as Q,T as q,Q as S,ad as K,I as X,$}from"./sf-utils.c42cbZ9W.js";import{_ as E,w as W}from"./_plugin-vue_export-helper.xATGHWd9.js";import{u as tt}from"./index.ShNlAyu1.js";import{a as et}from"./shopping-cart.v-dB3kHB.js";import{u as ot}from"./use-product-card.nNtSJVtB.js";import{C as it,Q as rt}from"./QuantitySelector.v7L8EYOR.js";import{P as at}from"./Prices.xI1rdM1e.js";import{_ as j}from"./customer-session.dSYHWdP4.js";import"./server-data.4C60Esyt.js";import{g as nt}from"./img-sizes.gxAI9JNh.js";import"./index.KfrHdfOH.js";import{g as st}from"./grid-title.pK2Nn3i-.js";import"./price.Easct8WC.js";import"./use-analytics._ef6TM4P.js";import"./afetch.OifQZgwR.js";import"./name.VA3MEpe0.js";import"./i18n.zhlBzJt8.js";import"./img.AnjeGdy_.js";import"./modules-info.HP6478mG.js";import"./format-money.1_HtF5S2.js";const D=(i,n,l)=>{if(typeof i!="object"||i===null)return[];let t=[];if(typeof i=="object"&&i!==null)if(Array.isArray(i))i.length&&(i[0].specifications?i.forEach(e=>{t=t.concat(D(e,n,l))}):i[0].text&&(t=i));else{const{specifications:e}=i;if(e)for(const s in e)e[s]&&s===n&&(t=e[n]);if(t&&!t.length&&Array.isArray(l)&&l.length){let s,d;return l&&(d=l.find(r=>r.grid_id===n))&&d.options&&(s=d.options.map(r=>{let a;return r.colors&&r.colors.length?a=r.colors[0]:a=r.option_id,{text:r.text,value:a}})),D(s,n)}}return t},Y=D,lt=(i,n,l,t=", ")=>{let e=Y(i,n,l);if(e.length){let s=e[0].text;for(let d=1;d<e.length;d++)s+=t+e[d].text;return s}return null},Z=lt,ct=(i,n,l,t)=>{const e=Y(i,l,t);for(let s=0;s<e.length;s++)if(e[s].text===n)return e[s].value},dt=ct,ut=(i,n,l,t)=>{let e={};return i&&Array.isArray(i.variations)&&i.variations.forEach(s=>{if(l&&s.quantity<=0)return;let d=s.specifications,r=a=>Z(s,a,t);if(d){if(n){for(let a in n)if(n.hasOwnProperty(a)&&(!d[a]||r(a)!==n[a]))return}for(let a in d)if(d.hasOwnProperty(a)){let f=r(a);if(!e.hasOwnProperty(a))e[a]=[];else if(e[a].indexOf(f)!==-1)continue;e[a].push(f)}}}),e},B=ut,mt=R({__name:"ImagesGallery",props:{pictures:{}},setup(i,{expose:n}){n();const l=C(0),t=C("");let e;const s=C(!1),r={activeIndex:l,psId:t,get lightbox(){return e},set lightbox(a){e=a},isLoadingLightbox:s,zoom:a=>{if(t.value=`ps-${H()}`,!e&&!s.value){s.value=!0;const f="photoswipe-style";Promise.all([j(()=>import("./photoswipe-lightbox.esm.dZBqKD9u.js"),__vite__mapDeps([])),j(()=>import("./photoswipe.esm.Ylh9TGkz.js"),__vite__mapDeps([])),!document.getElementById(f)&&j(()=>import("./photoswipe.0V7m2jWu.js"),__vite__mapDeps([]))]).then(([{default:o},{default:c},_])=>{if(_){const{default:y}=_,p=document.createElement("style");p.id=f,p.textContent=y,document.head.appendChild(p)}e=new o({gallery:`#${t.value} > div`,children:"a",pswpModule:c,showAnimationDuration:300,hideAnimationDuration:300}),e.init(),e.loadAndOpen(a),s.value=!1})}},get getImgSizes(){return nt}};return Object.defineProperty(r,"__isScriptSetup",{enumerable:!1,value:!0}),r}}),ft={class:"-mx-4 flex w-screen gap-3 sm:mx-0 sm:w-full md:h-[525px] 2xl:gap-5"},gt=["onClick"],pt=v("span",{class:"absolute bottom-0 block h-2 w-full bg-gradient-to-b from-transparent to-white"},null,-1),_t={class:"relative aspect-square h-full grow md:aspect-auto"},ht={key:0,class:"bg-base-200 i-arrow-path absolute left-1/2 top-1/2 -ml-7 -mt-7 size-14 animate-spin","aria-label":"Carregando"},vt={key:1,class:"mt-2 flex justify-center gap-1.5 md:hidden"},yt=["aria-label","onClick"];function bt(i,n,l,t,e,s){const d=A("AImg"),r=A("CarouselControl"),a=A("Carousel"),f=A("ALink");return u(),m("div",ft,[l.pictures.length>1?(u(),P(a,{key:0,axis:"y",class:"group hidden w-[300px] shrink-0 md:block"},{controls:V(()=>[v("span",null,[l.pictures.length>6?(u(),P(r,{key:0,class:"text-primary hover:bg-primary-300/60 !bottom-3 !left-1/2 -ml-5 size-10 rounded-full bg-white/60 text-xl opacity-0 shadow-sm ring-1 ring-black/5 group-hover:opacity-90"})):b("",!0),pt])]),default:V(()=>[(u(!0),m(w,null,I(Math.ceil(l.pictures.length/2),o=>(u(),m("li",{key:o,class:z(["grid w-full grid-cols-2 gap-3 px-1 pb-3",o===1&&"pt-1"])},[(u(!0),m(w,null,I([1,2].map(c=>(o-1)*2+(c-1)),c=>(u(),m(w,{key:`${o}-${c}`},[c<l.pictures.length?(u(),m("button",{key:0,class:"bg-secondary-100 block rounded md:h-[175px]",onClick:_=>t.activeIndex=c},[k(d,{picture:l.pictures[c],class:z(["ring-secondary/10 size-full rounded border-2 object-cover opacity-90 transition-colors",c===t.activeIndex?"border-secondary/50 ring-4 cursor-auto":"border-transparent hover:border-primary hover:ring-4 hover:ring-primary/20"])},null,8,["picture","class"])],8,gt)):b("",!0)],64))),128))],2))),128))]),_:1})):b("",!0),v("div",_t,[k(a,{as:"div",index:t.activeIndex,"onUpdate:index":n[1]||(n[1]=o=>t.activeIndex=o),class:z(["text-base-600 [&_i]:i-arrow-right mx-auto size-full max-w-[525px] [&>*]:h-full [&_i]:mx-2 [&_i]:text-2xl",t.isLoadingLightbox&&"opacity-80"]),id:t.psId},{default:V(()=>[n[0]||(F(-1),n[0]=(u(!0),m(w,null,I(l.pictures,(o,c)=>(u(),P(f,{key:`big-${c}`,href:o.zoom?.size&&o.zoom.url,"data-pswp-width":t.getImgSizes(o.zoom||"").width,"data-pswp-height":t.getImgSizes(o.zoom||"").height,target:"_blank",rel:"noreferrer",class:z(["shrink-0 basis-full",o.zoom?.size&&"cursor-zoom-in"]),onClick:W(()=>o.zoom?.size&&t.zoom(c),["prevent"])},{default:V(()=>[k(d,{picture:o,"preferred-size":"big",class:"size-full rounded object-cover",fetchpriority:c===0?"high":"low",loading:c===0?"eager":"lazy"},null,8,["picture","fetchpriority","loading"])]),_:2},1032,["href","data-pswp-width","data-pswp-height","class","onClick"]))),128)),F(1),n[0])]),_:1},8,["index","class","id"]),t.isLoadingLightbox?(u(),m("i",ht)):b("",!0),l.pictures.length>1?(u(),m("ul",vt,[(u(!0),m(w,null,I(l.pictures.length,o=>(u(),m("li",{key:`d-${o}`},[v("button",{class:z(["bg-base-700 block h-1.5 w-3 rounded-full",t.activeIndex!==o-1&&"opacity-40"]),"aria-label":`Imagem ${o}`,onClick:c=>t.activeIndex=o-1},null,10,yt)]))),128))])):b("",!0)])])}const xt=E(mt,[["render",bt]]),kt=i=>{const n=J(i.grids||globalThis.$storefront.data.grids||[]);n.length||window.addEventListener("storefront:data:data",()=>{globalThis.$storefront.data.grids?.forEach(o=>n.push(o))},{once:!0});const l=L({}),t=L({});T(M(i,"variations"),()=>{Object.assign(t,B(i,void 0,!0));const o=B(i);Object.keys(o).forEach(c=>{t[c]?l[c]=t[c]:delete l[c]})},{immediate:!0});const e=Q(()=>Object.keys(l)),s=L({}),d=C(),r=({optionText:o,gridId:c,gridIndex:_})=>{s[c]=o;const y={};for(let g=0;g<=_;g++){const h=e[g];s[h]&&(y[h]=s[h])}const p=B(i,y,!0);for(let g=_+1;g<e.value.length;g++){const h=e[g],O=p[h];t[h]=O,s[h]&&!O.includes(s[h])&&delete s[h]}const x=i.variations.slice(0);for(let g=0;g<x.length;g++){const h=x[g],{specifications:O}=h,N=Object.keys(O);for(let G=0;G<N.length;G++){const U=N[G];if(s[U]!==Z(h,U)){x.splice(g,1),g-=1;break}}}d.value=x[0]?._id||null};return T(M(i,"variationId"),o=>{if(!o||o===d.value)return;const c=i.variations.find(x=>x._id===o);if(!c){d.value=null;return}const{specifications:_}=c,y=Object.keys(_),p=(x=0)=>{const g=y[x];if(y[x]&&_[g]&&_[g].length===1){const h=_[g][0].text;l[g].find(O=>O===h)&&(r({optionText:h,gridId:g,gridIndex:e.value.indexOf(g)}),p(x+1))}};p()},{immediate:!0}),{grids:n,variationsGrids:l,activeVariationsGrids:t,selectOption:r,selectedOptions:s,variationId:d,getGridTitle:o=>st(o,n),getColorOptionBg:o=>{const c=o.split(",").map(_=>dt(i.variations,_.trim(),"colors"));return c.length>1?`background:linear-gradient(to right bottom, ${c[0]} 50%, ${c[1]} 50%)`:`background:${c[0]}`}}},wt=R({__name:"SkuSelector",props:{variations:{},variationId:{},grids:{}},emits:["update:variationId"],setup(i,{expose:n,emit:l}){n();const t=i,e=l,{variationsGrids:s,activeVariationsGrids:d,selectOption:r,selectedOptions:a,variationId:f,getGridTitle:o,getColorOptionBg:c}=kt(t);T(f,y=>{e("update:variationId",y)});const _={props:t,emit:e,variationsGrids:s,activeVariationsGrids:d,selectOption:r,selectedOptions:a,variationId:f,getGridTitle:o,getColorOptionBg:c};return Object.defineProperty(_,"__isScriptSetup",{enumerable:!1,value:!0}),_}}),St={class:"text-base-700 text-sm font-medium"},Ct={key:0,class:"text-base-800"},Ot={key:0,class:"mt-2 flex gap-2"},zt=["onClick"];function Vt(i,n,l,t,e,s){return u(),m("div",null,[(u(!0),m(w,null,I(t.variationsGrids,(d,r)=>(u(),m("div",{key:r,class:"mt-3"},[v("span",St,[q(S(t.getGridTitle(r))+": ",1),t.selectedOptions[r]?(u(),m("strong",Ct,S(t.selectedOptions[r]),1)):b("",!0)]),d.length<7?(u(),m("ul",Ot,[(u(!0),m(w,null,I(d,(a,f)=>(u(),m("li",{key:`${r}-${f}`},[v("button",{class:z(["ring-primary/60 rounded border",[t.selectedOptions[r]===a?"border-primary ring-2":null,r==="colors"?"size-9 text-[0px]":"px-2.5 py-2 leading-none",t.activeVariationsGrids[r].includes(a)?"border-primary-400 bg-primary-100 text-primary-950":"border-primary-300 bg-primary-200 text-primary-600"]]),style:K(r==="colors"&&t.getColorOptionBg(a)),onClick:o=>t.selectOption({optionText:a,gridId:r,gridIndex:f})},S(a),15,zt)]))),128))])):b("",!0)]))),128))])}const It=E(wt,[["render",Vt]]),At={};function Pt(i,n){return u(),m("div")}const Tt=E(At,[["render",Pt]]),Et=R({__name:"ProductDetails",props:{product:{default:()=>globalThis.$storefront.apiContext?.doc}},setup(i,{expose:n}){n();const l=i,{product:t,title:e,isActive:s}=ot(l),d=C(t.min_quantity||1),r=tt("history"),a=C(!1),f=C(null);T(f,p=>{p&&(r.var=p,a.value=!1)}),X(()=>{T(r,({var:p})=>{typeof p=="string"&&p&&(f.value=p)},{immediate:!0})});const o=Q(()=>!!(!t.variations?.length||f.value)),c=p=>(o.value?a.value=!1:(p&&p.preventDefault(),a.value=!0),!a.value),y={props:l,product:t,title:e,isActive:s,quantity:d,params:r,hasSkuSelectionAlert:a,variationId:f,isSkuSelected:o,checkVariation:c,addToCart:()=>{c()&&et(t,f.value?f.value:void 0)},CheckoutLink:it,QuantitySelector:rt,Prices:at,ImagesGallery:xt,SkuSelector:It,ShippingCalculator:Tt};return Object.defineProperty(y,"__isScriptSetup",{enumerable:!1,value:!0}),y}}),Gt={class:"ui-section relative grid grid-cols-1 items-start gap-5 md:gap-4 lg:grid-cols-4 2xl:gap-6"},Lt={class:"w-full lg:col-span-3"},jt={class:"lg:sticky-header:translate-y-14 top-0 py-4 transition-transform lg:sticky"},Bt={class:"text-secondary-900 ui-text-brand text-lg"},qt={key:0,class:"mt-5"},Dt={key:0,class:"ui-alert inline-block"},Rt=v("i",{class:"i-arrow-right ml-1 -rotate-90"},null,-1),Nt={class:"mt-5 flex flex-wrap items-center gap-x-4 gap-y-2 md:flex-nowrap lg:mt-4 lg:flex-wrap"},Ut=v("i",{class:"i-chevron-double-right mr-1"},null,-1),Ft=["data-tooltip"],Mt={class:"w-full lg:col-span-3"};function Qt(i,n,l,t,e,s){const d=A("Fade");return u(),m("section",Gt,[v("div",Lt,[t.product.pictures?.length?(u(),P(t.ImagesGallery,{key:0,pictures:t.product.pictures},null,8,["pictures"])):b("",!0)]),v("div",jt,[v("h1",Bt,S(t.title),1),t.isActive?(u(),m("div",qt,[k(t.Prices,{product:t.product,"is-big":"","is-literal":""},null,8,["product"]),t.product.variations?(u(),P(t.SkuSelector,{key:0,variations:t.product.variations,"variation-id":t.variationId,"onUpdate:variationId":n[0]||(n[0]=r=>t.variationId=r),class:"my-4"},null,8,["variations","variation-id"])):b("",!0),k(d,{slide:"down"},{default:V(()=>[t.hasSkuSelectionAlert?(u(),m("div",Dt,[q(S("Por favor selecione uma opção em cada campo acima")+" "),Rt])):b("",!0)]),_:1}),v("div",Nt,[k(t.QuantitySelector,{modelValue:t.quantity,"onUpdate:modelValue":n[1]||(n[1]=r=>t.quantity=r),min:t.product.min_quantity,max:t.product.quantity,class:"border-base-100 rounded md:mr-5 lg:mb-2 lg:mr-auto lg:border-2"},null,8,["modelValue","min","max"]),k(t.CheckoutLink,{class:"ui-btn-lg ui-btn-primary grow text-center",to:"checkout","cart-item":{product_id:t.product._id,quantity:t.quantity,variation_id:t.variationId||void 0},"data-tooltip":t.isSkuSelected?null:"Escolha os detalhes do produto para comprar",onClick:t.checkVariation},{default:V(()=>[Ut,q(" "+S("Comprar"))]),_:1},8,["cart-item","data-tooltip"]),v("button",{class:"ui-btn-lg ui-btn-contrast grow",onClick:W(t.addToCart,["prevent"]),"data-tooltip":t.isSkuSelected?null:"Escolha os detalhes do produto para comprar"},S("Adicionar ao carrinho"),8,Ft)]),k(t.ShippingCalculator)])):b("",!0)]),v("div",Mt,[$(i.$slots,"description")])])}const me=E(Et,[["render",Qt]]);export{me as default};
2
- function __vite__mapDeps(indexes) {
3
- if (!__vite__mapDeps.viteFileDeps) {
4
- __vite__mapDeps.viteFileDeps = []
5
- }
6
- return indexes.map((i) => __vite__mapDeps.viteFileDeps[i])
7
- }
@@ -1 +0,0 @@
1
- import{a as F,c as _,d as z,a8 as he,I as ae,w as D,m as le,Y as V,ae as ge,af as xe,a6 as _e,ag as j,F as N,M as ye,ah as Oe,aa as Pe,N as se,O as k,P as w,S as h,V as T,W as E,U as q,Z as Q,Q as L,T as U,$ as ke,a0 as G,X as ne,R as I,a1 as Se}from"./sf-utils.c42cbZ9W.js";import{_ as Y,w as te,b as oe,v as we}from"./_plugin-vue_export-helper.xATGHWd9.js";import{u as Le}from"./index.ShNlAyu1.js";import{i as Fe}from"./server-data.4C60Esyt.js";import{i as Re,a as Ce,b as ie,c as Ee,d as Te,e as Me,f as Ae,g as Be,h as De,j as je,k as Ie,P as Ue}from"./ProductShelf.qbTNzuvn.js";import{S as Ve}from"./use-analytics._ef6TM4P.js";import{u as ue,g as $e}from"./index.KfrHdfOH.js";import{g as ze}from"./grid-title.pK2Nn3i-.js";import{f as W}from"./format-money.1_HtF5S2.js";import{u as $,f as Ne,c as M,w as Ke,a as We,h as qe,o as A,t as Qe,i as X,b as He,E as Ge,s as Xe,A as Z,T as Ye,d as re,e as Ze,l as Je,N as ce,p as et,g as tt,O as at,j as C,D as st}from"./use-text-value.0OP9HCfP.js";import"./customer-session.dSYHWdP4.js";import"./use-product-card.nNtSJVtB.js";import"./price.Easct8WC.js";import"./name.VA3MEpe0.js";import"./i18n.zhlBzJt8.js";import"./img.AnjeGdy_.js";import"./shopping-cart.v-dB3kHB.js";import"./Prices.xI1rdM1e.js";import"./modules-info.HP6478mG.js";import"./afetch.OifQZgwR.js";function nt(e,s,i){let a=F(i?.value),t=_(()=>e.value!==void 0);return[_(()=>t.value?e.value:a.value),function(r){return t.value||(a.value=r),s?.(r)}]}function de(e={},s=null,i=[]){for(let[a,t]of Object.entries(e))fe(i,pe(s,a),t);return i}function pe(e,s){return e?e+"["+s+"]":s}function fe(e,s,i){if(Array.isArray(i))for(let[a,t]of i.entries())fe(e,pe(s,a.toString()),t);else i instanceof Date?e.push([s,i.toISOString()]):typeof i=="boolean"?e.push([s,i?"1":"0"]):typeof i=="string"?e.push([s,i]):typeof i=="number"?e.push([s,`${i}`]):i==null?e.push([s,""]):de(i,s,e)}function rt(e,s){return e===s}var lt=(e=>(e[e.Open=0]="Open",e[e.Closed=1]="Closed",e))(lt||{}),ot=(e=>(e[e.Single=0]="Single",e[e.Multi=1]="Multi",e))(ot||{}),it=(e=>(e[e.Pointer=0]="Pointer",e[e.Other=1]="Other",e))(it||{});function ut(e){requestAnimationFrame(()=>requestAnimationFrame(e))}let ve=Symbol("ListboxContext");function J(e){let s=_e(ve,null);if(s===null){let i=new Error(`<${e} /> is missing a parent <Listbox /> component.`);throw Error.captureStackTrace&&Error.captureStackTrace(i,J),i}return s}let ct=z({name:"Listbox",emits:{"update:modelValue":e=>!0},props:{as:{type:[Object,String],default:"template"},disabled:{type:[Boolean],default:!1},by:{type:[String,Function],default:()=>rt},horizontal:{type:[Boolean],default:!1},modelValue:{type:[Object,String,Number,Boolean],default:void 0},defaultValue:{type:[Object,String,Number,Boolean],default:void 0},form:{type:String,optional:!0},name:{type:String,optional:!0},multiple:{type:[Boolean],default:!1}},inheritAttrs:!1,setup(e,{slots:s,attrs:i,emit:a}){let t=F(1),r=F(null),p=F(null),c=F(null),d=F([]),l=F(""),o=F(null),P=F(1);function f(m=n=>n){let n=o.value!==null?d.value[o.value]:null,u=at(m(d.value.slice()),O=>A(O.dataRef.domRef)),v=n?u.indexOf(n):null;return v===-1&&(v=null),{options:u,activeOptionIndex:v}}let y=_(()=>e.multiple?1:0),[b,g]=nt(_(()=>e.modelValue),m=>a("update:modelValue",m),_(()=>e.defaultValue)),S=_(()=>b.value===void 0?$(y.value,{1:[],0:void 0}):b.value),x={listboxState:t,value:S,mode:y,compare(m,n){if(typeof e.by=="string"){let u=e.by;return m?.[u]===n?.[u]}return e.by(m,n)},orientation:_(()=>e.horizontal?"horizontal":"vertical"),labelRef:r,buttonRef:p,optionsRef:c,disabled:_(()=>e.disabled),options:d,searchQuery:l,activeOptionIndex:o,activationTrigger:P,closeListbox(){e.disabled||t.value!==1&&(t.value=1,o.value=null)},openListbox(){e.disabled||t.value!==0&&(t.value=0)},goToOption(m,n,u){if(e.disabled||t.value===1)return;let v=f(),O=Ne(m===M.Specific?{focus:M.Specific,id:n}:{focus:m},{resolveItems:()=>v.options,resolveActiveIndex:()=>v.activeOptionIndex,resolveId:B=>B.id,resolveDisabled:B=>B.dataRef.disabled});l.value="",o.value=O,P.value=u??1,d.value=v.options},search(m){if(e.disabled||t.value===1)return;let n=l.value!==""?0:1;l.value+=m.toLowerCase();let u=(o.value!==null?d.value.slice(o.value+n).concat(d.value.slice(0,o.value+n)):d.value).find(O=>O.dataRef.textValue.startsWith(l.value)&&!O.dataRef.disabled),v=u?d.value.indexOf(u):-1;v===-1||v===o.value||(o.value=v,P.value=1)},clearSearch(){e.disabled||t.value!==1&&l.value!==""&&(l.value="")},registerOption(m,n){let u=f(v=>[...v,{id:m,dataRef:n}]);d.value=u.options,o.value=u.activeOptionIndex},unregisterOption(m){let n=f(u=>{let v=u.findIndex(O=>O.id===m);return v!==-1&&u.splice(v,1),u});d.value=n.options,o.value=n.activeOptionIndex,P.value=1},theirOnChange(m){e.disabled||g(m)},select(m){e.disabled||g($(y.value,{0:()=>m,1:()=>{let n=j(x.value.value).slice(),u=j(m),v=n.findIndex(O=>x.compare(u,j(O)));return v===-1?n.push(u):n.splice(v,1),n}}))}};Ke([p,c],(m,n)=>{var u;x.closeListbox(),We(n,qe.Loose)||(m.preventDefault(),(u=A(p))==null||u.focus())},_(()=>t.value===0)),he(ve,x),Qe(_(()=>$(t.value,{0:X.Open,1:X.Closed})));let R=_(()=>{var m;return(m=A(p))==null?void 0:m.closest("form")});return ae(()=>{D([R],()=>{if(!R.value||e.defaultValue===void 0)return;function m(){x.theirOnChange(e.defaultValue)}return R.value.addEventListener("reset",m),()=>{var n;(n=R.value)==null||n.removeEventListener("reset",m)}},{immediate:!0})}),()=>{let{name:m,modelValue:n,disabled:u,form:v,...O}=e,B={open:t.value===0,disabled:u,value:S.value};return le(V,[...m!=null&&S.value!=null?de({[m]:S.value}).map(([K,ee])=>le(He,Ge({features:Xe.Hidden,key:K,as:"input",type:"hidden",hidden:!0,readOnly:!0,form:v,name:K,value:ee}))):[],Z({ourProps:{},theirProps:{...i,...Ye(O,["defaultValue","onUpdate:modelValue","horizontal","multiple","by"])},slot:B,slots:s,attrs:i,name:"Listbox"})])}}}),dt=z({name:"ListboxButton",props:{as:{type:[Object,String],default:"button"},id:{type:String,default:()=>`headlessui-listbox-button-${re()}`}},setup(e,{attrs:s,slots:i,expose:a}){let t=J("ListboxButton");a({el:t.buttonRef,$el:t.buttonRef});function r(l){switch(l.key){case C.Space:case C.Enter:case C.ArrowDown:l.preventDefault(),t.openListbox(),N(()=>{var o;(o=A(t.optionsRef))==null||o.focus({preventScroll:!0}),t.value.value||t.goToOption(M.First)});break;case C.ArrowUp:l.preventDefault(),t.openListbox(),N(()=>{var o;(o=A(t.optionsRef))==null||o.focus({preventScroll:!0}),t.value.value||t.goToOption(M.Last)});break}}function p(l){switch(l.key){case C.Space:l.preventDefault();break}}function c(l){t.disabled.value||(t.listboxState.value===0?(t.closeListbox(),N(()=>{var o;return(o=A(t.buttonRef))==null?void 0:o.focus({preventScroll:!0})})):(l.preventDefault(),t.openListbox(),ut(()=>{var o;return(o=A(t.optionsRef))==null?void 0:o.focus({preventScroll:!0})})))}let d=Ze(_(()=>({as:e.as,type:s.type})),t.buttonRef);return()=>{var l,o;let P={open:t.listboxState.value===0,disabled:t.disabled.value,value:t.value.value},{id:f,...y}=e,b={ref:t.buttonRef,id:f,type:d.value,"aria-haspopup":"listbox","aria-controls":(l=A(t.optionsRef))==null?void 0:l.id,"aria-expanded":t.listboxState.value===0,"aria-labelledby":t.labelRef.value?[(o=A(t.labelRef))==null?void 0:o.id,f].join(" "):void 0,disabled:t.disabled.value===!0?!0:void 0,onKeydown:r,onKeyup:p,onClick:c};return Z({ourProps:b,theirProps:y,slot:P,attrs:s,slots:i,name:"ListboxButton"})}}}),pt=z({name:"ListboxOptions",props:{as:{type:[Object,String],default:"ul"},static:{type:Boolean,default:!1},unmount:{type:Boolean,default:!0},id:{type:String,default:()=>`headlessui-listbox-options-${re()}`}},setup(e,{attrs:s,slots:i,expose:a}){let t=J("ListboxOptions"),r=F(null);a({el:t.optionsRef,$el:t.optionsRef});function p(l){switch(r.value&&clearTimeout(r.value),l.key){case C.Space:if(t.searchQuery.value!=="")return l.preventDefault(),l.stopPropagation(),t.search(l.key);case C.Enter:if(l.preventDefault(),l.stopPropagation(),t.activeOptionIndex.value!==null){let o=t.options.value[t.activeOptionIndex.value];t.select(o.dataRef.value)}t.mode.value===0&&(t.closeListbox(),N(()=>{var o;return(o=A(t.buttonRef))==null?void 0:o.focus({preventScroll:!0})}));break;case $(t.orientation.value,{vertical:C.ArrowDown,horizontal:C.ArrowRight}):return l.preventDefault(),l.stopPropagation(),t.goToOption(M.Next);case $(t.orientation.value,{vertical:C.ArrowUp,horizontal:C.ArrowLeft}):return l.preventDefault(),l.stopPropagation(),t.goToOption(M.Previous);case C.Home:case C.PageUp:return l.preventDefault(),l.stopPropagation(),t.goToOption(M.First);case C.End:case C.PageDown:return l.preventDefault(),l.stopPropagation(),t.goToOption(M.Last);case C.Escape:l.preventDefault(),l.stopPropagation(),t.closeListbox(),N(()=>{var o;return(o=A(t.buttonRef))==null?void 0:o.focus({preventScroll:!0})});break;case C.Tab:l.preventDefault(),l.stopPropagation();break;default:l.key.length===1&&(t.search(l.key),r.value=setTimeout(()=>t.clearSearch(),350));break}}let c=Je(),d=_(()=>c!==null?(c.value&X.Open)===X.Open:t.listboxState.value===0);return()=>{var l,o;let P={open:t.listboxState.value===0},{id:f,...y}=e,b={"aria-activedescendant":t.activeOptionIndex.value===null||(l=t.options.value[t.activeOptionIndex.value])==null?void 0:l.id,"aria-multiselectable":t.mode.value===1?!0:void 0,"aria-labelledby":(o=A(t.buttonRef))==null?void 0:o.id,"aria-orientation":t.orientation.value,id:f,onKeydown:p,role:"listbox",tabIndex:0,ref:t.optionsRef};return Z({ourProps:b,theirProps:y,slot:P,attrs:s,slots:i,features:ce.RenderStrategy|ce.Static,visible:d.value,name:"ListboxOptions"})}}}),ft=z({name:"ListboxOption",props:{as:{type:[Object,String],default:"li"},value:{type:[Object,String,Number,Boolean]},disabled:{type:Boolean,default:!1},id:{type:String,default:()=>`headlessui-listbox.option-${re()}`}},setup(e,{slots:s,attrs:i,expose:a}){let t=J("ListboxOption"),r=F(null);a({el:r,$el:r});let p=_(()=>t.activeOptionIndex.value!==null?t.options.value[t.activeOptionIndex.value].id===e.id:!1),c=_(()=>$(t.mode.value,{0:()=>t.compare(j(t.value.value),j(e.value)),1:()=>j(t.value.value).some(x=>t.compare(j(x),j(e.value)))})),d=_(()=>$(t.mode.value,{1:()=>{var x;let R=j(t.value.value);return((x=t.options.value.find(m=>R.some(n=>t.compare(j(n),j(m.dataRef.value)))))==null?void 0:x.id)===e.id},0:()=>c.value})),l=et(r),o=_(()=>({disabled:e.disabled,value:e.value,get textValue(){return l()},domRef:r}));ae(()=>t.registerOption(e.id,o)),ge(()=>t.unregisterOption(e.id)),ae(()=>{D([t.listboxState,c],()=>{t.listboxState.value===0&&c.value&&$(t.mode.value,{1:()=>{d.value&&t.goToOption(M.Specific,e.id)},0:()=>{t.goToOption(M.Specific,e.id)}})},{immediate:!0})}),xe(()=>{t.listboxState.value===0&&p.value&&t.activationTrigger.value!==0&&N(()=>{var x,R;return(R=(x=A(r))==null?void 0:x.scrollIntoView)==null?void 0:R.call(x,{block:"nearest"})})});function P(x){if(e.disabled)return x.preventDefault();t.select(e.value),t.mode.value===0&&(t.closeListbox(),N(()=>{var R;return(R=A(t.buttonRef))==null?void 0:R.focus({preventScroll:!0})}))}function f(){if(e.disabled)return t.goToOption(M.Nothing);t.goToOption(M.Specific,e.id)}let y=tt();function b(x){y.update(x)}function g(x){y.wasMoved(x)&&(e.disabled||p.value||t.goToOption(M.Specific,e.id,0))}function S(x){y.wasMoved(x)&&(e.disabled||p.value&&t.goToOption(M.Nothing))}return()=>{let{disabled:x}=e,R={active:p.value,selected:c.value,disabled:x},{id:m,value:n,disabled:u,...v}=e,O={id:m,ref:r,role:"option",tabIndex:x===!0?void 0:-1,"aria-disabled":x===!0?!0:void 0,"aria-selected":c.value,disabled:void 0,onClick:P,onFocus:f,onPointerenter:b,onMouseenter:b,onPointermove:g,onMousemove:g,onPointerleave:S,onMouseleave:S};return Z({ourProps:O,theirProps:v,slot:R,attrs:i,slots:s,name:"ListboxOption"})}}});const me=({searchEngine:e,fixedParams:s})=>{const i=_(()=>{const t={};return Object.keys(e.params).forEach(r=>{if(s?.[r])return;const p=e.params[r];if(p!==void 0){switch(r){case"sort":case"term":case"limit":case"offset":case"count":case"buckets":case"fields":return}t[r]=p}}),t}),a=_(()=>{const t=Object.keys(i.value),r=[];return t.forEach(p=>{const c=p.replace(/[^\w.]/g,"");if(c==="specs"&&Array.isArray(i.value[p])){i.value[p].forEach(d=>{const[l]=d.split(":"),o=`specs.${l}`;r.includes(o)||r.push(o)});return}r.includes(c)||r.push(c)}),r.length});return{activeFilters:i,filtersCount:a}},vt=e=>{const{searchEngine:s,fixedParams:i}=e,a=_(()=>s.meta),t=_(()=>s.meta.buckets),{activeFilters:r,filtersCount:p}=me(e);D(s.params,()=>{s.fetch()});let c=null;const d=()=>{Object.keys(s.params).forEach(n=>{i?.[n]||delete s.params[n]}),c=null},l=({min:n,max:u})=>`${n||null}/${u||null}`,o=_(()=>{const{params:n}=s;return{min:Number(n["price>"]),max:Number(n["price<"])}}),P=F([]),f=ue(()=>{P.value.splice(0),t.value?.prices?.forEach(n=>{n.min&&(n.min=Math.round(n.min*100)/100),n.max&&(n.max=Math.round(n.max*100)/100),P.value.push({range:n,key:l(n)})}),Number.isNaN(o.value.min)||P.value.find(({range:u})=>u.min===o.value.min&&u.max===o.value.max)||P.value.unshift({range:{...o.value,count:a.value.count||0,avg:null},key:l(o.value)})},50);f();const y=F(l(o.value));D(y,()=>{c="price";const n=P.value.find(({range:u})=>l(u)===y.value);if(n){const{min:u,max:v}=n.range;u?s.params["price>"]=u:delete s.params["price>"],v?s.params["price<"]=v:delete s.params["price<"];return}delete s.params["price>"],delete s.params["price<"]});const b=({min:n,max:u})=>n&&u?u===n?W(u):`${W(n)} ${ie.toLowerCase()} ${W(u)}`:!n&&u?`${ie} ${W(u)}`:`${Ee} ${W(n||0)}`,g=F([]),S=ue(()=>{for(let u=0;u<g.value.length;u++){const{field:v}=g.value[u];v!==c&&(g.value.splice(u,1),u-=1)}const n=t.value;if(n&&([["brands",Re],["categories",Ce]].forEach(([u,v])=>{const O=`${u}.name`;n[O]&&c!==O&&g.value.push({title:v,options:n[O],field:O})}),n.specs)){const{grids:u}=globalThis.$storefront.data;Object.keys(n.specs).forEach(v=>{const[O,B]=v.split(":");if(B){const K=`specs.${O}`;if(c===K)return;const ee=ze(O,u||[]);let H=g.value.find(be=>be.field===K);H||(H={title:ee,options:{},field:K},g.value.push(H)),H.options[B]=n.specs[v]}})}},50);S();const x=(n,u)=>{const[,v]=n.split(".");return["specs,",`${v}:${u}`]},R=(n,u)=>{n.startsWith("specs.")&&([n,u]=x(n,u));const v=r.value[n];return!!(v===u||Array.isArray(v)&&v.includes(u))},m=(n,u)=>{c=n,console.log({_lastParamChanged:c}),n.startsWith("specs.")&&([n,u]=x(n,u));const v=!R(n,u);let O=s.params[n];if(Array.isArray(O)||(O=[],s.params[n]=O),v)O.push(u);else for(let B=0;B<O.length;B++)if(O[B]===u){O.splice(B,1);break}};return D(t,()=>{c!=="price"&&f(),S()}),{resultMeta:a,resultBuckets:t,activeFilters:r,filtersCount:p,clearFilters:d,getPriceRangeKey:l,priceRanges:P,priceRangeKey:y,getPriceRangeLabel:b,filterOptions:g,checkFilterOption:R,toggleFilterOption:m}},mt=e=>{let{term:s}=e;const a=e.canUseUrlParams!==!1?Le("history"):null;e.ssrError&&(console.error(new Error(`SSR search error: ${e.ssrError}`)),window.location.pathname.startsWith("/s/")&&(window.location.href=`/s?q=${encodeURIComponent(s||"")}`));const t=ye(e.products||[]),r=new Ve({debounce:50});s===void 0&&(s=new URLSearchParams(window.location.search).get("q")||null),s!==void 0&&(r.term.value=s),e.pageSize&&(r.pageSize.value=e.pageSize),Object.assign(r.params,e.fixedParams);let p=!1;a&&Object.keys(a).forEach(b=>{if(a[b]){if(b.startsWith("f\\")){const g=b.substring(2);r.params[g]=a[b],e.fixedParams?.[g]!==a[b]&&(p=!0);return}if(b==="sort"){if(r.params.sort=a.sort,typeof a.sort=="string"&&e.resultMeta?.sort?.length===1){const{field:g,order:S}=e.resultMeta.sort[0];if((S?g:`-${g}`)===a.sort)return}p=!0;return}if(b==="p"){const g=parseInt(String(a.p),10);if(g>=1){if(r.pageNumber.value=g,e.resultMeta?.limit){const{offset:S,limit:x}=e.resultMeta;if((S?Math.ceil(S/x):1)===g)return}p=!0}}}}),r.wasFetched.value||((e.products||e.resultMeta)&&!p&&r.setResult({result:e.products,meta:e.resultMeta}),(!e.products||p)&&r.fetch().catch(console.error)),r.isWithCount.value=!0,r.isWithBuckets.value=!0;const c=F({count:0,...e.resultMeta||r.meta});D(r.products,()=>{t.splice(0),r.products.forEach(b=>t.push(b)),c.value={count:0,...r.meta}});const d=_(()=>{const{count:b}=r.meta;return!b||t.length<2?1:Math.ceil(b/r.pageSize.value)});D(r.pageNumber,b=>{a&&(a.p=`${b}`),r.fetch()});const l=()=>{D(r.isFetching,b=>{const g=e.showcase?.value;!b&&g&&setTimeout(()=>{Oe(g,Fe?-25:0)},50)})};r.wasFetched.value?l():$e(r.wasFetched,l);const{activeFilters:o,filtersCount:P}=me({searchEngine:r,fixedParams:e.fixedParams});a&&D(o,b=>{a&&Object.keys(a).forEach(g=>{g.startsWith("f\\")&&delete a[g]}),Object.keys(b).forEach(g=>{const S=b[g];if(typeof S=="string"||typeof S=="number"){a[`f\\${g}`]=`${S}`;return}Array.isArray(S)&&typeof S[0]=="string"&&(a[`f\\${g}`]=S)})});const f=[{value:null,label:Te},{value:"-sales",label:Me},{value:"price",label:Ae},{value:"-price",label:Be},{value:"-price_discount",label:De},{value:"-created_at",label:je},{value:"name",label:Ie}],y=F(null);return D(y,()=>{r.params.sort=y.value||void 0,r.fetch()}),a&&(typeof a.sort=="string"&&a.sort&&(y.value=a.sort),D(r.params,b=>{delete a.sort,b.sort&&(a.sort=String(b.sort))})),{searchEngine:r,fetching:r.fetching.value,isFetching:r.isFetching,products:t,resultMeta:c,totalPages:d,activeFilters:o,filtersCount:P,sortOptions:f,sortOption:y}},bt=e=>{const s=_(()=>e.totalPages?e.totalPages:e.totalItems&&e.pageSize?Math.ceil(e.totalItems/e.pageSize):1),i=_(()=>{const f=e.page||1;return f<1?1:f>s.value?s.value:f}),a=_(()=>e.maxPages||10),t=_(()=>{if(s.value<=a.value)return 1;const f=Math.floor(a.value/2),y=Math.ceil(a.value/2)-1;return i.value<=f?1:i.value+y>=s.value?s.value-a.value+1:i.value-f}),r=_(()=>{if(s.value<=a.value)return s.value;const f=Math.floor(a.value/2),y=Math.ceil(a.value/2)-1;return i.value<=f?a.value:i.value+y>=s.value?s.value:i.value+y}),p=_(()=>Array.from(Array(r.value+1-t.value).keys()).map(f=>t.value+f)),c=F("");D(Pe(e,"isUrlPath"),()=>{const f=new URL(window.location.toString());e.isUrlPath&&!f.pathname.endsWith("/")?f.pathname+="/":f.searchParams.delete("p"),c.value=`${f.pathname}${f.search}`},{immediate:!0});const d=f=>e.isUrlPath?`../${f}`:`?p=${f}`,l=_(()=>p.value.map(f=>c.value+d(f))),o=_(()=>i.value<=1?null:c.value+d(i.value-1)),P=_(()=>i.value>=s.value?null:c.value+d(i.value+1));return{totalPages:s,startPage:t,endPage:r,pages:p,pageLinks:l,prevPageLink:o,nextPageLink:P}},ht=z({__name:"Pagination",props:{totalItems:{},totalPages:{},page:{default:1},pageSize:{},maxPages:{default:7},isUrlPath:{type:Boolean,default:!1}},emits:["update:page"],setup(e,{expose:s,emit:i}){s();const a=e,t=i,{pages:r,pageLinks:p,prevPageLink:c,nextPageLink:d}=bt(a),l={props:a,emit:t,pages:r,pageLinks:p,prevPageLink:c,nextPageLink:d};return Object.defineProperty(l,"__isScriptSetup",{enumerable:!1,value:!0}),l}}),gt={class:"text-base-900 flex justify-center gap-1.5 text-center text-sm font-medium leading-9"},xt=h("i",{class:"i-arrow-right rotate-180"},null,-1),_t=h("span",{class:"ml-1.5 hidden md:inline"},L("Anterior"),-1),yt=h("span",{class:"mr-1.5 hidden md:inline"},L("Próximo"),-1),Ot=h("i",{class:"i-arrow-right"},null,-1);function Pt(e,s,i,a,t,r){const p=se("ALink");return k(),w("ol",gt,[h("li",null,[T(p,{href:a.prevPageLink,onClick:s[0]||(s[0]=te(c=>a.prevPageLink&&a.emit("update:page",i.page-1),["prevent"])),class:q(["mr-1 block min-w-9 rounded border px-3",a.prevPageLink?"border-base-100 hover:bg-base-100":"border-transparent text-base-500"])},{default:E(()=>[xt,_t]),_:1},8,["href","class"])]),(k(!0),w(V,null,Q(a.pages,(c,d)=>(k(),w("li",{key:c},[T(p,{href:c!==i.page?a.pageLinks[d]:null,onClick:te(l=>a.emit("update:page",c),["prevent"]),class:q(["block w-9 rounded border ring-black/10",c===i.page?"bg-base-50 border-base-100 ring text-base-700":"border-transparent hover:bg-base-100"])},{default:E(()=>[U(L(c),1)]),_:2},1032,["href","onClick","class"])]))),128)),h("li",null,[T(p,{href:a.nextPageLink,onClick:s[1]||(s[1]=te(c=>a.nextPageLink&&a.emit("update:page",i.page+1),["prevent"])),class:q(["ml-1 block min-w-9 rounded border px-3",a.nextPageLink?"border-base-100 hover:bg-base-100":"border-transparent text-base-500"])},{default:E(()=>[yt,Ot]),_:1},8,["href","class"])])])}const kt=Y(ht,[["render",Pt]]),St=z({__name:"Collapse",props:{title:{}},setup(e,{expose:s}){s();const i={};return Object.defineProperty(i,"__isScriptSetup",{enumerable:!1,value:!0}),i}}),wt={class:"group my-4 md:my-5 [&_i]:open:-rotate-90"},Lt={role:"button",class:"text-base-700 hover:text-base-800 [&>i]:hover:text-primary list-none text-2xl font-medium lowercase group-open:mb-3"},Ft=h("i",{class:"i-chevron-right mr-1 rotate-90"},null,-1);function Rt(e,s,i,a,t,r){return k(),w("details",wt,[h("summary",Lt,[Ft,h("span",null,L(i.title),1)]),ke(e.$slots,"default")])}const Ct=Y(St,[["render",Rt]]),Et=z({__name:"SearchFilters",props:{searchEngine:{},fixedParams:{}},setup(e,{expose:s}){s();const i=e,{resultBuckets:a,activeFilters:t,filtersCount:r,clearFilters:p,priceRanges:c,priceRangeKey:d,getPriceRangeLabel:l,filterOptions:o,checkFilterOption:P,toggleFilterOption:f}=vt(i),y={props:i,resultBuckets:a,activeFilters:t,filtersCount:r,clearFilters:p,priceRanges:c,priceRangeKey:d,getPriceRangeLabel:l,filterOptions:o,checkFilterOption:P,toggleFilterOption:f,Collapse:Ct};return Object.defineProperty(y,"__isScriptSetup",{enumerable:!1,value:!0}),y}}),Tt={class:"bg-base-50/40 h-screen overflow-y-auto"},Mt={class:"px-6 pb-3 pt-5 text-center"},At=h("i",{class:"i-trash ml-0.5"},null,-1),Bt={key:1,class:"text-base-500 border border-transparent pb-1 text-base font-semibold"},Dt={key:0,class:"px-6 pb-3"},jt={class:"space-y-1.5"},It=["id","value"],Ut=["for"],Vt={class:"text-base-500 font-medium"},$t={key:0,class:"flex items-center"},zt=h("label",{for:"priceRange-null",class:"cursor-pointer px-3 text-sm"},L("Qualquer preço"),-1),Nt={class:"space-y-1.5"},Kt=["id","value","checked","onChange"],Wt=["for"],qt={class:"text-base-500 font-medium"};function Qt(e,s,i,a,t,r){return k(),w("aside",Tt,[h("header",Mt,[a.filtersCount?(k(),w("button",{key:0,class:"ui-btn-sm ui-btn-danger py-1",onClick:s[0]||(s[0]=(...p)=>a.clearFilters&&a.clearFilters(...p))},[U(L("Limpar filtros")+" "),At])):(k(),w("p",Bt,L("Filtrar resultados")))]),a.resultBuckets?(k(),w("article",Dt,[a.priceRanges?(k(),G(a.Collapse,{key:0,title:"Preço",class:"[&>summary]:text-xl",open:""},{default:E(()=>[h("div",jt,[(k(!0),w(V,null,Q(a.priceRanges,({range:p,key:c})=>(k(),w("div",{key:`prices-${c}`,class:"flex items-center"},[ne(h("input",{type:"radio",id:`priceRange-${c}`,name:"priceRange",value:c,"onUpdate:modelValue":s[1]||(s[1]=d=>a.priceRangeKey=d)},null,8,It),[[oe,a.priceRangeKey]]),h("label",{for:`priceRange-${c}`,class:"cursor-pointer px-3 text-sm"},[U(L(a.getPriceRangeLabel(p))+" ",1),h("small",Vt," ("+L(p.count)+") ",1)],8,Ut)]))),128)),a.activeFilters["price<"]||a.activeFilters["price>"]?(k(),w("div",$t,[ne(h("input",{type:"radio",id:"priceRange-null",name:"priceRange",value:null,"onUpdate:modelValue":s[2]||(s[2]=p=>a.priceRangeKey=p)},null,512),[[oe,a.priceRangeKey]]),zt])):I("",!0)])]),_:1})):I("",!0),(k(!0),w(V,null,Q(a.filterOptions,({title:p,options:c,field:d})=>(k(),G(a.Collapse,{key:d,title:p,class:"[&>summary]:text-xl",open:!!a.activeFilters[d]},{default:E(()=>[h("div",Nt,[(k(!0),w(V,null,Q(c,(l,o,P)=>(k(),w("div",{key:`${d}-${P}`,class:"flex items-center"},[h("input",{type:"checkbox",id:`${d}-${o}`,value:o,checked:a.checkFilterOption(d,o),onChange:f=>a.toggleFilterOption(d,o)},null,40,Kt),h("label",{for:`${d}-${o}`,class:"cursor-pointer px-3 text-sm"},[U(L(o)+" ",1),h("small",qt," ("+L(l)+") ",1)],8,Wt)]))),128))])]),_:2},1032,["title","open"]))),128))])):I("",!0)])}const Ht=Y(Et,[["render",Qt]]),Gt=z({__name:"SearchShowcase",props:{term:{},pageSize:{},fixedParams:{},products:{},resultMeta:{},ssrError:{},canUseUrlParams:{type:Boolean,default:!0},showcase:{}},async setup(e,{expose:s}){s();const i=e,a=F(null),{searchEngine:t,fetching:r,isFetching:p,products:c,resultMeta:d,totalPages:l,filtersCount:o,sortOptions:P,sortOption:f}=mt({...i,showcase:a}),y=_(()=>t.wasFetched.value),b=_(()=>t.term.value),g=_(()=>y&&!!(d.value.count>4||o.value)),S=F(!1),x={props:i,showcase:a,searchEngine:t,fetching:r,isFetching:p,products:c,resultMeta:d,totalPages:l,filtersCount:o,sortOptions:P,sortOption:f,wasFetched:y,searchTerm:b,hasFiltersBar:g,isFiltersOpen:S,get Listbox(){return ct},get ListboxButton(){return dt},get ListboxOptions(){return pt},get ListboxOption(){return ft},Drawer:st,Pagination:kt,ProductShelf:Ue,SearchFilters:Ht};return Object.defineProperty(x,"__isScriptSetup",{enumerable:!1,value:!0}),x}}),Xt={class:"text-base-800 inline font-bold italic"},Yt={key:1,class:"ui-section relative min-h-[300px]"},Zt={ref:"showcase",class:"relative"},Jt={key:0,class:"to-base-100 ui-section-slim sticky-header:translate-y-16 lg:sticky-header:translate-y-14 sticky top-0 z-[12] flex items-center justify-between rounded-b bg-white/80 px-6 py-4 shadow-sm backdrop-blur-sm transition-transform"},ea={class:"text-base-700 font-medium lowercase"},ta=h("span",{class:"hidden lg:inline"},L("Itens encontrados"),-1),aa=h("span",{class:"lg:hidden"},L("Produtos"),-1),sa={class:"flex items-center gap-4"},na=h("span",{class:"hidden text-xl leading-none md:block"},[h("i",{class:"text-base-600 i-adjustments-horizontal m-0"})],-1),ra=h("span",{class:"hidden md:inline"},L("Filtrar produtos"),-1),la=h("span",{class:"md:hidden"},[h("i",{class:"i-adjustments-horizontal mr-1"}),U(" "+L("Filtrar"))],-1),oa={key:0,class:"outline-3 outline-secondary/80 ui-badge-pill-sm absolute -right-1.5 -top-1 outline"},ia={class:"w-5"},ua={class:"i-check"},ca={key:0,class:"mt-3 lg:mt-4"},da={key:0,class:"absolute left-0 top-0 z-[14] size-full bg-white/40"};function pa(e,s,i,a,t,r){const p=se("Skeleton"),c=se("Fade");return k(),w(V,null,[a.searchTerm?(k(),w("section",{key:0,class:q(["text-base-700 ui-section-slim px-6 text-center text-xl lowercase",a.hasFiltersBar?"relative z-[14] -mb-4":"mb-0"])},[U(L("Buscando por")+" "),h("h1",Xt,L(a.searchTerm),1)],2)):I("",!0),a.isFetching&&!a.products.length?(k(),w("div",Yt,[T(p,{class:"absolute top-0 w-full px-5","is-bold":"","is-large":""})])):I("",!0),h("article",Zt,[T(c,null,{default:E(()=>[a.hasFiltersBar?(k(),w("section",Jt,[h("strong",ea,[a.resultMeta.count>1?(k(),w(V,{key:0},[U(L(a.resultMeta.count)+" ",1),ta,aa],64)):I("",!0)]),h("div",sa,[na,h("button",{onClick:s[0]||(s[0]=d=>a.isFiltersOpen=!a.isFiltersOpen),class:"ui-btn-sm ui-btn-secondary relative"},[ra,la,a.filtersCount?(k(),w("span",oa,L(a.filtersCount),1)):I("",!0)]),T(a.Listbox,{modelValue:a.sortOption,"onUpdate:modelValue":s[1]||(s[1]=d=>a.sortOption=d),as:"div",class:"text-base-800 relative text-sm"},{default:E(()=>[T(a.ListboxButton,{id:e.$useId("ss"),class:"ui-btn-sm ui-btn-secondary"},{default:E(()=>[U(L("Ordenar"))]),_:1},8,["id"]),T(c,null,{default:E(()=>[T(a.ListboxOptions,{class:"divide-base-100 absolute right-0 mt-2 divide-y rounded bg-white shadow ring-1 ring-black/5 focus:outline-none"},{default:E(()=>[(k(!0),w(V,null,Q(a.sortOptions,({label:d,value:l})=>(k(),G(a.ListboxOption,{key:l||"sort",value:l,as:"template"},{default:E(({selected:o,active:P})=>[h("li",null,[(k(),G(Se(o?"div":"button"),{class:q(["flex w-full py-2 pl-3 pr-6",!o&&P&&"bg-secondary-100 text-secondary"])},{default:E(()=>[h("div",ia,[ne(h("i",ua,null,512),[[we,o]])]),U(" "+L(d),1)]),_:2},1032,["class"]))])]),_:2},1032,["value"]))),128))]),_:1})]),_:1})]),_:1},8,["modelValue"])])])):I("",!0)]),_:1}),T(a.ProductShelf,{products:a.products,"is-grid":""},{append:E(()=>[T(c,{slide:"down"},{default:E(()=>[!a.isFetching&&a.totalPages>1?(k(),w("nav",ca,[T(a.Pagination,{page:a.searchEngine.pageNumber.value,"onUpdate:page":s[2]||(s[2]=d=>a.searchEngine.pageNumber.value=d),"total-pages":a.totalPages},null,8,["page","total-pages"])])):I("",!0)]),_:1})]),_:1},8,["products"]),T(c,null,{default:E(()=>[a.isFetching?(k(),w("div",da)):I("",!0)]),_:1})],512),T(a.Drawer,{modelValue:a.isFiltersOpen,"onUpdate:modelValue":s[3]||(s[3]=d=>a.isFiltersOpen=d),placement:"end","backdrop-target":null,"can-lock-scroll":!1,class:"!z-[80] bg-white shadow [&_[data-drawer-close]]:bg-white/80"},{default:E(()=>[T(a.SearchFilters,{"search-engine":a.searchEngine},null,8,["search-engine"])]),_:1},8,["modelValue"])],64)}const Ma=Y(Gt,[["render",pa]]);export{Ma as default};