@akinon/next 2.0.0-beta.2 → 2.0.0-beta.20

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 (189) hide show
  1. package/.eslintrc.js +12 -0
  2. package/CHANGELOG.md +377 -7
  3. package/__tests__/next-config.test.ts +83 -0
  4. package/__tests__/tsconfig.json +23 -0
  5. package/api/auth.ts +133 -44
  6. package/api/barcode-search.ts +59 -0
  7. package/api/cache.ts +41 -5
  8. package/api/client.ts +21 -4
  9. package/api/form.ts +85 -0
  10. package/api/image-proxy.ts +75 -0
  11. package/api/product-categories.ts +53 -0
  12. package/api/similar-product-list.ts +63 -0
  13. package/api/similar-products.ts +111 -0
  14. package/api/virtual-try-on.ts +382 -0
  15. package/assets/styles/index.scss +84 -0
  16. package/babel.config.js +6 -0
  17. package/bin/pz-generate-routes.js +115 -0
  18. package/bin/pz-prebuild.js +1 -0
  19. package/bin/pz-predev.js +1 -0
  20. package/bin/pz-run-tests.js +99 -0
  21. package/bin/run-prebuild-tests.js +46 -0
  22. package/components/accordion.tsx +20 -5
  23. package/components/button.tsx +51 -36
  24. package/components/client-root.tsx +138 -2
  25. package/components/file-input.tsx +65 -3
  26. package/components/index.ts +1 -0
  27. package/components/input.tsx +1 -1
  28. package/components/link.tsx +46 -16
  29. package/components/logger-popup.tsx +213 -0
  30. package/components/modal.tsx +32 -16
  31. package/components/plugin-module.tsx +62 -3
  32. package/components/price.tsx +2 -2
  33. package/components/select.tsx +1 -1
  34. package/components/selected-payment-option-view.tsx +21 -0
  35. package/components/theme-editor/blocks/accordion-block.tsx +136 -0
  36. package/components/theme-editor/blocks/block-renderer-registry.tsx +77 -0
  37. package/components/theme-editor/blocks/button-block.tsx +593 -0
  38. package/components/theme-editor/blocks/counter-block.tsx +348 -0
  39. package/components/theme-editor/blocks/divider-block.tsx +20 -0
  40. package/components/theme-editor/blocks/embed-block.tsx +208 -0
  41. package/components/theme-editor/blocks/group-block.tsx +116 -0
  42. package/components/theme-editor/blocks/hotspot-block.tsx +147 -0
  43. package/components/theme-editor/blocks/icon-block.tsx +230 -0
  44. package/components/theme-editor/blocks/image-block.tsx +137 -0
  45. package/components/theme-editor/blocks/image-gallery-block.tsx +269 -0
  46. package/components/theme-editor/blocks/input-block.tsx +123 -0
  47. package/components/theme-editor/blocks/link-block.tsx +216 -0
  48. package/components/theme-editor/blocks/lottie-block.tsx +325 -0
  49. package/components/theme-editor/blocks/map-block.tsx +89 -0
  50. package/components/theme-editor/blocks/slider-block.tsx +595 -0
  51. package/components/theme-editor/blocks/tab-block.tsx +10 -0
  52. package/components/theme-editor/blocks/text-block.tsx +52 -0
  53. package/components/theme-editor/blocks/video-block.tsx +122 -0
  54. package/components/theme-editor/components/action-toolbar.tsx +305 -0
  55. package/components/theme-editor/components/designer-overlay.tsx +74 -0
  56. package/components/theme-editor/components/with-designer-features.tsx +142 -0
  57. package/components/theme-editor/dynamic-font-loader.tsx +79 -0
  58. package/components/theme-editor/hooks/use-designer-features.tsx +100 -0
  59. package/components/theme-editor/hooks/use-external-designer.tsx +95 -0
  60. package/components/theme-editor/hooks/use-native-widget-data.ts +188 -0
  61. package/components/theme-editor/hooks/use-visibility-context.ts +27 -0
  62. package/components/theme-editor/placeholder-registry.ts +31 -0
  63. package/components/theme-editor/sections/before-after-section.tsx +245 -0
  64. package/components/theme-editor/sections/contact-form-section.tsx +563 -0
  65. package/components/theme-editor/sections/countdown-campaign-banner-section.tsx +433 -0
  66. package/components/theme-editor/sections/coupon-banner-section.tsx +710 -0
  67. package/components/theme-editor/sections/divider-section.tsx +62 -0
  68. package/components/theme-editor/sections/featured-product-spotlight-section.tsx +507 -0
  69. package/components/theme-editor/sections/find-in-store-section.tsx +1995 -0
  70. package/components/theme-editor/sections/hover-showcase-section.tsx +326 -0
  71. package/components/theme-editor/sections/image-hotspot-section.tsx +142 -0
  72. package/components/theme-editor/sections/installment-options-section.tsx +1065 -0
  73. package/components/theme-editor/sections/notification-banner-section.tsx +173 -0
  74. package/components/theme-editor/sections/order-tracking-lookup-section.tsx +1379 -0
  75. package/components/theme-editor/sections/posts-slider-section.tsx +472 -0
  76. package/components/theme-editor/sections/pre-order-launch-banner-section.tsx +663 -0
  77. package/components/theme-editor/sections/section-renderer-registry.tsx +89 -0
  78. package/components/theme-editor/sections/section-wrapper.tsx +135 -0
  79. package/components/theme-editor/sections/shipping-threshold-progress-section.tsx +586 -0
  80. package/components/theme-editor/sections/stats-counter-section.tsx +486 -0
  81. package/components/theme-editor/sections/tabs-section.tsx +578 -0
  82. package/components/theme-editor/theme-block.tsx +102 -0
  83. package/components/theme-editor/theme-placeholder-client.tsx +218 -0
  84. package/components/theme-editor/theme-placeholder-wrapper.tsx +732 -0
  85. package/components/theme-editor/theme-placeholder.tsx +288 -0
  86. package/components/theme-editor/theme-section.tsx +1224 -0
  87. package/components/theme-editor/theme-settings-context.tsx +13 -0
  88. package/components/theme-editor/utils/index.ts +792 -0
  89. package/components/theme-editor/utils/iterator-utils.ts +234 -0
  90. package/components/theme-editor/utils/publish-window.ts +86 -0
  91. package/components/theme-editor/utils/visibility-rules.ts +188 -0
  92. package/data/client/account.ts +17 -2
  93. package/data/client/api.ts +2 -0
  94. package/data/client/basket.ts +66 -5
  95. package/data/client/checkout.ts +391 -99
  96. package/data/client/misc.ts +38 -2
  97. package/data/client/product.ts +19 -2
  98. package/data/client/user.ts +16 -8
  99. package/data/server/category.ts +11 -9
  100. package/data/server/flatpage.ts +11 -4
  101. package/data/server/form.ts +15 -4
  102. package/data/server/landingpage.ts +11 -4
  103. package/data/server/list.ts +5 -4
  104. package/data/server/menu.ts +11 -3
  105. package/data/server/product.ts +111 -55
  106. package/data/server/seo.ts +14 -4
  107. package/data/server/special-page.ts +5 -4
  108. package/data/server/widget.ts +90 -5
  109. package/data/urls.ts +16 -5
  110. package/hocs/client/with-segment-defaults.tsx +2 -2
  111. package/hocs/server/with-segment-defaults.tsx +65 -20
  112. package/hooks/index.ts +4 -0
  113. package/hooks/use-localization.ts +24 -10
  114. package/hooks/use-logger-context.tsx +114 -0
  115. package/hooks/use-logger.ts +92 -0
  116. package/hooks/use-loyalty-availability.ts +21 -0
  117. package/hooks/use-payment-options.ts +2 -1
  118. package/hooks/use-pz-params.ts +37 -0
  119. package/hooks/use-router.ts +51 -14
  120. package/hooks/use-sentry-uncaught-errors.ts +24 -0
  121. package/instrumentation/index.ts +10 -1
  122. package/instrumentation/node.ts +2 -20
  123. package/jest.config.js +25 -0
  124. package/lib/cache-handler.mjs +534 -16
  125. package/lib/cache.ts +272 -37
  126. package/localization/index.ts +2 -1
  127. package/localization/provider.tsx +2 -5
  128. package/middlewares/bfcache-headers.ts +18 -0
  129. package/middlewares/checkout-provider.ts +1 -1
  130. package/middlewares/complete-gpay.ts +32 -26
  131. package/middlewares/complete-masterpass.ts +33 -26
  132. package/middlewares/complete-wallet.ts +182 -0
  133. package/middlewares/default.ts +360 -215
  134. package/middlewares/index.ts +10 -2
  135. package/middlewares/locale.ts +34 -11
  136. package/middlewares/masterpass-rest-callback.ts +230 -0
  137. package/middlewares/oauth-login.ts +200 -57
  138. package/middlewares/pretty-url.ts +21 -8
  139. package/middlewares/redirection-payment.ts +32 -26
  140. package/middlewares/saved-card-redirection.ts +33 -26
  141. package/middlewares/three-d-redirection.ts +32 -26
  142. package/middlewares/url-redirection.ts +11 -1
  143. package/middlewares/wallet-complete-redirection.ts +206 -0
  144. package/package.json +25 -10
  145. package/plugins.d.ts +19 -4
  146. package/plugins.js +10 -1
  147. package/redux/actions.ts +47 -0
  148. package/redux/middlewares/checkout.ts +63 -138
  149. package/redux/middlewares/index.ts +14 -10
  150. package/redux/middlewares/pre-order/address.ts +7 -2
  151. package/redux/middlewares/pre-order/attribute-based-shipping-option.ts +7 -1
  152. package/redux/middlewares/pre-order/data-source-shipping-option.ts +7 -1
  153. package/redux/middlewares/pre-order/delivery-option.ts +7 -1
  154. package/redux/middlewares/pre-order/index.ts +16 -10
  155. package/redux/middlewares/pre-order/installment-option.ts +8 -1
  156. package/redux/middlewares/pre-order/payment-option-reset.ts +37 -0
  157. package/redux/middlewares/pre-order/payment-option.ts +7 -1
  158. package/redux/middlewares/pre-order/pre-order-validation.ts +8 -3
  159. package/redux/middlewares/pre-order/redirection.ts +8 -2
  160. package/redux/middlewares/pre-order/set-pre-order.ts +6 -2
  161. package/redux/middlewares/pre-order/shipping-option.ts +7 -1
  162. package/redux/middlewares/pre-order/shipping-step.ts +5 -1
  163. package/redux/reducers/checkout.ts +23 -3
  164. package/redux/reducers/index.ts +11 -3
  165. package/redux/reducers/root.ts +7 -2
  166. package/redux/reducers/widget.ts +80 -0
  167. package/sentry/index.ts +69 -13
  168. package/tailwind/content.js +16 -0
  169. package/types/commerce/account.ts +5 -1
  170. package/types/commerce/checkout.ts +35 -1
  171. package/types/commerce/widget.ts +33 -0
  172. package/types/index.ts +101 -6
  173. package/types/next-auth.d.ts +2 -2
  174. package/types/widget.ts +80 -0
  175. package/utils/app-fetch.ts +7 -2
  176. package/utils/generate-commerce-search-params.ts +3 -2
  177. package/utils/get-checkout-path.ts +3 -0
  178. package/utils/get-root-hostname.ts +28 -0
  179. package/utils/index.ts +64 -10
  180. package/utils/localization.ts +4 -0
  181. package/utils/mobile-3d-iframe.ts +8 -2
  182. package/utils/override-middleware.ts +7 -12
  183. package/utils/pz-segments.ts +92 -0
  184. package/utils/redirect-ignore.ts +35 -0
  185. package/utils/redirect.ts +9 -3
  186. package/utils/redirection-iframe.ts +8 -2
  187. package/utils/widget-styles.ts +107 -0
  188. package/views/error-page.tsx +93 -0
  189. package/with-pz-config.js +13 -6
@@ -0,0 +1,732 @@
1
+ 'use client';
2
+
3
+ import { useEffect, useState, useMemo } from 'react';
4
+ import ThemeSection, { Section } from './theme-section';
5
+ import {
6
+ registerPlaceholder,
7
+ unregisterPlaceholder
8
+ } from './placeholder-registry';
9
+ import { ThemeSettingsProvider } from './theme-settings-context';
10
+ import { generateThemeCSS } from './utils';
11
+ import { useVisibilityContext } from './hooks/use-visibility-context';
12
+ import { applyVisibilityRulesToSections } from './utils/visibility-rules';
13
+ import { isPublishWindowVisible } from './utils/publish-window';
14
+ import { buildClientRequestUrl } from '../../utils';
15
+
16
+ // Helper function to inject theme colors as CSS custom properties
17
+ const injectThemeColors = (settings: Record<string, unknown>) => {
18
+ if (!settings) return;
19
+
20
+ const root = document.documentElement;
21
+
22
+ // Primary Styling colors
23
+ if (settings.primaryColor) {
24
+ root.style.setProperty('--theme-primary', settings.primaryColor as string);
25
+ }
26
+ if (settings.secondaryColor) {
27
+ root.style.setProperty(
28
+ '--theme-secondary',
29
+ settings.secondaryColor as string
30
+ );
31
+ }
32
+ if (settings.color3) {
33
+ root.style.setProperty('--theme-color3', settings.color3 as string);
34
+ }
35
+ if (settings.color4) {
36
+ root.style.setProperty('--theme-color4', settings.color4 as string);
37
+ }
38
+ if (settings.backgroundColor) {
39
+ root.style.setProperty(
40
+ '--theme-background',
41
+ settings.backgroundColor as string
42
+ );
43
+ document.body.style.backgroundColor = settings.backgroundColor as string;
44
+ }
45
+
46
+ // Also set opacity values if needed
47
+ if (settings.primaryOpacity !== undefined) {
48
+ root.style.setProperty(
49
+ '--theme-primary-opacity',
50
+ String(settings.primaryOpacity)
51
+ );
52
+ }
53
+ if (settings.secondaryOpacity !== undefined) {
54
+ root.style.setProperty(
55
+ '--theme-secondary-opacity',
56
+ String(settings.secondaryOpacity)
57
+ );
58
+ }
59
+ if (settings.color3Opacity !== undefined) {
60
+ root.style.setProperty(
61
+ '--theme-color3-opacity',
62
+ String(settings.color3Opacity)
63
+ );
64
+ }
65
+ if (settings.color4Opacity !== undefined) {
66
+ root.style.setProperty(
67
+ '--theme-color4-opacity',
68
+ String(settings.color4Opacity)
69
+ );
70
+ }
71
+ if (settings.backgroundOpacity !== undefined) {
72
+ root.style.setProperty(
73
+ '--theme-background-opacity',
74
+ String(settings.backgroundOpacity)
75
+ );
76
+ }
77
+ if (settings.breadcrumbSeparator) {
78
+ root.style.setProperty(
79
+ '--theme-breadcrumb-separator',
80
+ `"${settings.breadcrumbSeparator}"`
81
+ );
82
+ root.style.setProperty('--theme-breadcrumb-icon-display', 'none');
83
+ } else {
84
+ root.style.removeProperty('--theme-breadcrumb-separator');
85
+ root.style.removeProperty('--theme-breadcrumb-icon-display');
86
+ }
87
+
88
+ if (settings.mainMenuSticky !== undefined) {
89
+ const isSticky = settings.mainMenuSticky;
90
+ root.style.setProperty(
91
+ '--theme-header-position',
92
+ isSticky ? 'sticky' : 'relative'
93
+ );
94
+ root.style.setProperty('--theme-header-top', isSticky ? '0' : 'auto');
95
+ root.style.setProperty('--theme-header-z-index', isSticky ? '40' : 'auto');
96
+
97
+ // Sticky positioning requires ancestors to not have overflow: hidden
98
+ // We force overflow-x to 'clip' (modern browsers) or 'visible' to fix this
99
+ if (isSticky) {
100
+ document.body.style.overflowX = 'clip';
101
+ } else {
102
+ document.body.style.overflowX = '';
103
+ }
104
+ }
105
+ };
106
+
107
+ // Helper function to load Google Font
108
+ const loadGoogleFont = (fontFamily: string, fontWeight?: string) => {
109
+ if (!fontFamily || fontFamily === 'inherit') return;
110
+
111
+ const cleanFontFamily = fontFamily.replace(/['"]/g, '').trim();
112
+
113
+ // Skip system fonts
114
+ const systemFonts = [
115
+ 'Arial',
116
+ 'Helvetica',
117
+ 'Times New Roman',
118
+ 'Georgia',
119
+ 'Courier New',
120
+ 'Verdana'
121
+ ];
122
+ if (systemFonts.includes(cleanFontFamily)) return;
123
+
124
+ const weights = fontWeight || '100;300;400;500;600;700;800;900';
125
+ const fontParam = `${cleanFontFamily.replace(/\s+/g, '+')}:wght@${weights}`;
126
+ const fontUrl = `https://fonts.googleapis.com/css2?family=${fontParam}&display=swap`;
127
+
128
+ const linkId = `google-font-${cleanFontFamily
129
+ .replace(/\s+/g, '-')
130
+ .toLowerCase()}`;
131
+
132
+ // Check if already loaded
133
+ if (document.getElementById(linkId)) return;
134
+
135
+ const link = document.createElement('link');
136
+ link.id = linkId;
137
+ link.href = fontUrl;
138
+ link.rel = 'stylesheet';
139
+ document.head.appendChild(link);
140
+ };
141
+
142
+ interface ThemePlaceholderWrapperProps {
143
+ slug: string;
144
+ initialSections: Section[];
145
+ initialPlaceholderId: string;
146
+ isDesignMode: boolean;
147
+ dataSources?: any[];
148
+ initialThemeSettings?: Record<string, unknown> | null;
149
+ }
150
+
151
+ declare global {
152
+ interface Window {
153
+ __iframeReadySent?: boolean;
154
+ __productPickerPreviewListenerAttached?: boolean;
155
+ }
156
+ }
157
+
158
+ const postProductPickerResponse = (
159
+ requestId: string,
160
+ ok: boolean,
161
+ result?: unknown,
162
+ error?: string
163
+ ) => {
164
+ if (!window.parent) {
165
+ return;
166
+ }
167
+
168
+ window.parent.postMessage(
169
+ {
170
+ type: 'PRODUCT_PICKER_RESPONSE',
171
+ data: {
172
+ requestId,
173
+ ok,
174
+ result,
175
+ error
176
+ }
177
+ },
178
+ '*'
179
+ );
180
+ };
181
+
182
+ const attachProductPickerPreviewListener = () => {
183
+ if (
184
+ typeof window === 'undefined' ||
185
+ window.__productPickerPreviewListenerAttached
186
+ ) {
187
+ return;
188
+ }
189
+
190
+ window.__productPickerPreviewListenerAttached = true;
191
+
192
+ window.addEventListener('message', async event => {
193
+ const type = event.data?.type;
194
+ const requestId = event.data?.data?.requestId;
195
+
196
+ if (
197
+ ![
198
+ 'PRODUCT_PICKER_SEARCH',
199
+ 'PRODUCT_PICKER_RESOLVE_URL',
200
+ 'PRODUCT_PICKER_GET_PRODUCT'
201
+ ].includes(type) ||
202
+ typeof requestId !== 'string'
203
+ ) {
204
+ return;
205
+ }
206
+
207
+ try {
208
+ if (type === 'PRODUCT_PICKER_SEARCH') {
209
+ const query = String(event.data?.data?.query || '').trim();
210
+
211
+ if (!query) {
212
+ postProductPickerResponse(requestId, true, { groups: [] });
213
+ return;
214
+ }
215
+
216
+ const response = await fetch(
217
+ buildClientRequestUrl(
218
+ `/autocomplete/?search_text=${encodeURIComponent(query)}`
219
+ )
220
+ );
221
+
222
+ if (!response.ok) {
223
+ throw new Error(`Autocomplete request failed with ${response.status}.`);
224
+ }
225
+
226
+ postProductPickerResponse(requestId, true, await response.json());
227
+ return;
228
+ }
229
+
230
+ if (type === 'PRODUCT_PICKER_RESOLVE_URL') {
231
+ const path = String(event.data?.data?.path || '').trim();
232
+
233
+ if (!path) {
234
+ postProductPickerResponse(requestId, true, { results: [] });
235
+ return;
236
+ }
237
+
238
+ const response = await fetch(
239
+ buildClientRequestUrl(
240
+ `/pretty_urls/?new_path__exact=${encodeURIComponent(path)}`
241
+ )
242
+ );
243
+
244
+ if (!response.ok) {
245
+ throw new Error(`Pretty URL request failed with ${response.status}.`);
246
+ }
247
+
248
+ postProductPickerResponse(requestId, true, await response.json());
249
+ return;
250
+ }
251
+
252
+ const productPk = Number.parseInt(String(event.data?.data?.pk || ''), 10);
253
+ if (!Number.isFinite(productPk) || productPk <= 0) {
254
+ throw new Error('Product PK is invalid.');
255
+ }
256
+
257
+ const response = await fetch(
258
+ buildClientRequestUrl(`/product/${productPk}/`)
259
+ );
260
+
261
+ if (!response.ok) {
262
+ throw new Error(`Product request failed with ${response.status}.`);
263
+ }
264
+
265
+ postProductPickerResponse(requestId, true, await response.json());
266
+ } catch (error) {
267
+ postProductPickerResponse(
268
+ requestId,
269
+ false,
270
+ undefined,
271
+ error instanceof Error ? error.message : 'Preview request failed.'
272
+ );
273
+ }
274
+ });
275
+ };
276
+
277
+ export default function ThemePlaceholderWrapper({
278
+ slug,
279
+ initialSections,
280
+ initialPlaceholderId,
281
+ isDesignMode,
282
+ dataSources: initialDataSources = [],
283
+ initialThemeSettings = null
284
+ }: ThemePlaceholderWrapperProps) {
285
+ const [sections, setSections] = useState<Section[]>(initialSections);
286
+ const [placeholderSlug, setPlaceholderSlug] =
287
+ useState<string>(initialPlaceholderId);
288
+ const [selectedSectionId, setSelectedSectionId] = useState<string | null>(
289
+ null
290
+ );
291
+ const [selectedBlockId, setSelectedBlockId] = useState<string | null>(null);
292
+ const [currentBreakpoint, setCurrentBreakpoint] = useState<string>('desktop');
293
+ const [isDesigner, setIsDesigner] = useState(isDesignMode);
294
+ const [dataSources, setDataSources] = useState<any[]>(initialDataSources);
295
+ const [themeSettings, setThemeSettings] = useState<Record<
296
+ string,
297
+ unknown
298
+ > | null>(initialThemeSettings);
299
+
300
+ // Inject theme colors when settings change
301
+ useEffect(() => {
302
+ if (themeSettings) {
303
+ injectThemeColors(themeSettings);
304
+ }
305
+ }, [themeSettings]);
306
+
307
+ // Inject custom fonts from theme settings
308
+ useEffect(() => {
309
+ if (!themeSettings?.customFonts) return;
310
+ const customFonts = themeSettings.customFonts as {
311
+ name: string;
312
+ sources: { dataUrl: string; format: string }[];
313
+ }[];
314
+
315
+ customFonts.forEach((font) => {
316
+ if (!font.name || !Array.isArray(font.sources) || font.sources.length === 0) return;
317
+
318
+ const styleId = `custom-font-${font.name.replace(/\s+/g, '-').toLowerCase()}`;
319
+ const existing = document.getElementById(styleId);
320
+ if (existing) existing.remove(); // Re-inject in case sources changed
321
+
322
+ const src = font.sources
323
+ .map((s) => `url('${s.dataUrl}') format('${s.format}')`)
324
+ .join(', ');
325
+
326
+ const style = document.createElement('style');
327
+ style.id = styleId;
328
+ style.textContent = `@font-face { font-family: '${font.name}'; src: ${src}; font-display: swap; }`;
329
+ document.head.appendChild(style);
330
+ });
331
+ }, [themeSettings]);
332
+
333
+ // Load fonts from initial sections on mount (for production site, not iframe)
334
+ useEffect(() => {
335
+ if (typeof window === 'undefined') return;
336
+
337
+ // Helper to extract and load fonts from blocks
338
+ const loadFontsFromBlocks = (blocks: Section['blocks']) => {
339
+ if (!blocks) return;
340
+
341
+ blocks.forEach((block) => {
342
+ const fontFamily =
343
+ block.styles?.['font-family']?.desktop ||
344
+ block.styles?.['font-family']?.mobile;
345
+ if (fontFamily && fontFamily !== 'inherit') {
346
+ loadGoogleFont(fontFamily);
347
+ }
348
+
349
+ // Recursively check nested blocks
350
+ if (block.blocks) {
351
+ loadFontsFromBlocks(block.blocks as Section['blocks']);
352
+ }
353
+ });
354
+ };
355
+
356
+ // Load fonts from all initial sections
357
+ initialSections.forEach((section) => {
358
+ loadFontsFromBlocks(section.blocks);
359
+ });
360
+ }, [initialSections]);
361
+
362
+ // Handle responsive breakpoint detection when not in iframe (e.g. production site)
363
+ useEffect(() => {
364
+ if (typeof window === 'undefined') return;
365
+
366
+ const checkIsInIframe = () => {
367
+ try {
368
+ return window.self !== window.top;
369
+ } catch (e) {
370
+ return true;
371
+ }
372
+ };
373
+
374
+ if (!checkIsInIframe()) {
375
+ const checkBreakpoint = () => {
376
+ const width = window.innerWidth;
377
+ // Use 1024px as the cutoff for desktop/mobile based on DEFAULT_BREAKPOINTS
378
+ const newBreakpoint = width < 1024 ? 'mobile' : 'desktop';
379
+
380
+ setCurrentBreakpoint((prev) => {
381
+ if (prev !== newBreakpoint) {
382
+ return newBreakpoint;
383
+ }
384
+ return prev;
385
+ });
386
+ };
387
+
388
+ let timeoutId: ReturnType<typeof setTimeout>;
389
+ const handleResize = () => {
390
+ clearTimeout(timeoutId);
391
+ timeoutId = setTimeout(checkBreakpoint, 200);
392
+ };
393
+
394
+ // Initial check
395
+ checkBreakpoint();
396
+
397
+ window.addEventListener('resize', handleResize);
398
+ return () => {
399
+ window.removeEventListener('resize', handleResize);
400
+ clearTimeout(timeoutId);
401
+ };
402
+ }
403
+ }, []);
404
+
405
+ useEffect(() => {
406
+ if (!isDesigner) return;
407
+ if (dataSources && dataSources.length > 0) {
408
+ setSections((prevSections) => {
409
+ return prevSections.map((section) => {
410
+ if (section.dataSourceId) {
411
+ const dataSource = dataSources.find(
412
+ (ds: any) => ds.id === section.dataSourceId
413
+ );
414
+
415
+ return {
416
+ ...section,
417
+ dataSource: dataSource || section.dataSource
418
+ };
419
+ }
420
+ return section;
421
+ });
422
+ });
423
+ }
424
+ }, [dataSources, isDesigner]);
425
+
426
+ useEffect(() => {
427
+ if (typeof window === 'undefined') {
428
+ return;
429
+ }
430
+
431
+ const checkIsInIframe = () => {
432
+ return window.self !== window.top;
433
+ };
434
+
435
+ const isInIframe = checkIsInIframe();
436
+
437
+ if (isInIframe && window.parent) {
438
+ attachProductPickerPreviewListener();
439
+
440
+ // Only send IFRAME_READY once per page session to prevent re-initialization
441
+ if (!window.__iframeReadySent) {
442
+ window.parent.postMessage(
443
+ {
444
+ type: 'IFRAME_READY'
445
+ },
446
+ '*'
447
+ );
448
+ window.__iframeReadySent = true;
449
+ }
450
+
451
+ registerPlaceholder(slug);
452
+ }
453
+
454
+ const handleMessage = (event: MessageEvent) => {
455
+ switch (event.data?.type) {
456
+ case 'SET_THEME_EDITOR_COOKIE':
457
+ if (event.data.data) {
458
+ setIsDesigner(true);
459
+ }
460
+ break;
461
+
462
+ case 'LOAD_THEME':
463
+ case 'UPDATE_THEME': {
464
+ const theme = event.data.data?.theme;
465
+
466
+ // Inject theme colors as CSS custom properties
467
+ if (theme?.settings) {
468
+ injectThemeColors(theme.settings);
469
+ setThemeSettings(theme.settings);
470
+ }
471
+
472
+ // Load fonts from typography settings
473
+ if (
474
+ theme?.settings?.typography &&
475
+ Array.isArray(theme.settings.typography)
476
+ ) {
477
+ const uniqueFonts = new Set<string>();
478
+ theme.settings.typography.forEach(
479
+ (variant: { fontFamily?: string }) => {
480
+ if (variant.fontFamily && variant.fontFamily !== 'inherit') {
481
+ uniqueFonts.add(variant.fontFamily);
482
+ }
483
+ }
484
+ );
485
+ uniqueFonts.forEach((font) => loadGoogleFont(font));
486
+ }
487
+
488
+ // Load fonts from block styles (for text blocks with custom fonts)
489
+ if (theme?.placeholders) {
490
+ // Recursive function to load fonts from nested blocks
491
+ const loadFontsFromBlocks = (blocks: any[]) => {
492
+ blocks?.forEach((block) => {
493
+ const fontFamily =
494
+ block.styles?.['font-family']?.desktop ||
495
+ block.styles?.['font-family']?.mobile;
496
+ if (fontFamily && fontFamily !== 'inherit') {
497
+ loadGoogleFont(fontFamily);
498
+ }
499
+ // Recursively check nested blocks
500
+ if (block.blocks && block.blocks.length > 0) {
501
+ loadFontsFromBlocks(block.blocks);
502
+ }
503
+ });
504
+ };
505
+
506
+ theme.placeholders.forEach(
507
+ (p: {
508
+ sections?: Array<{
509
+ blocks?: Array<any>;
510
+ }>;
511
+ }) => {
512
+ p.sections?.forEach((section) => {
513
+ loadFontsFromBlocks(section.blocks || []);
514
+ });
515
+ }
516
+ );
517
+ }
518
+
519
+ if (theme?.placeholders) {
520
+ const placeholder = theme.placeholders.find(
521
+ (p: { slug: string }) => p.slug === slug
522
+ );
523
+
524
+ if (placeholder) {
525
+ setPlaceholderSlug(placeholder.slug);
526
+
527
+ // Store dataSources in state for editor mode
528
+ if (theme.dataSources) {
529
+ setDataSources(theme.dataSources);
530
+ }
531
+
532
+ if (placeholder.sections) {
533
+ // In editor mode: Complete override with theme editor's data
534
+ // This allows unsaved sections to render with editor's product data
535
+ setSections(() => {
536
+ return placeholder.sections.map((incomingSection: any) => {
537
+ let dataSource = null;
538
+ if (incomingSection.dataSourceId && theme.dataSources) {
539
+ dataSource = theme.dataSources.find(
540
+ (ds: any) => ds.id === incomingSection.dataSourceId
541
+ );
542
+ }
543
+
544
+ // Deep clone the section to ensure React detects changes
545
+ // Especially important for nested blocks and styles
546
+ return {
547
+ ...incomingSection,
548
+ blocks: incomingSection.blocks
549
+ ? JSON.parse(JSON.stringify(incomingSection.blocks))
550
+ : [],
551
+ styles: incomingSection.styles
552
+ ? { ...incomingSection.styles }
553
+ : {},
554
+ properties: incomingSection.properties
555
+ ? { ...incomingSection.properties }
556
+ : {},
557
+ dataSource: dataSource || null
558
+ };
559
+ });
560
+ });
561
+ }
562
+ }
563
+ }
564
+ break;
565
+ }
566
+
567
+ case 'SELECT_SECTION': {
568
+ const { sectionId } = event.data.data || {};
569
+ if (sectionId) {
570
+ setSelectedSectionId(sectionId);
571
+ setSelectedBlockId(null);
572
+ }
573
+ break;
574
+ }
575
+
576
+ case 'SELECT_BLOCK': {
577
+ const { blockId } = event.data.data || {};
578
+ if (blockId) {
579
+ setSelectedBlockId(blockId);
580
+ setSelectedSectionId(null);
581
+ }
582
+ break;
583
+ }
584
+
585
+ case 'CHANGE_BREAKPOINT': {
586
+ const { breakpoint } = event.data.data || {};
587
+ if (breakpoint) {
588
+ setCurrentBreakpoint(breakpoint);
589
+ }
590
+ break;
591
+ }
592
+
593
+ case 'CLEAR_SELECTION': {
594
+ setSelectedSectionId(null);
595
+ setSelectedBlockId(null);
596
+ break;
597
+ }
598
+
599
+ case 'LOAD_FONT': {
600
+ const { fontFamily, fontWeight } = event.data.data || {};
601
+ if (fontFamily) {
602
+ loadGoogleFont(fontFamily, fontWeight);
603
+ }
604
+ break;
605
+ }
606
+
607
+ case 'LOAD_CUSTOM_FONT': {
608
+ const { name, sources } = event.data.data || {};
609
+ if (!name || !Array.isArray(sources) || sources.length === 0) break;
610
+
611
+ const styleId = `custom-font-${name.replace(/\s+/g, '-').toLowerCase()}`;
612
+ if (document.getElementById(styleId)) break;
613
+
614
+ const src = sources
615
+ .map((s: { dataUrl: string; format: string }) => `url('${s.dataUrl}') format('${s.format}')`)
616
+ .join(', ');
617
+
618
+ const style = document.createElement('style');
619
+ style.id = styleId;
620
+ style.textContent = `@font-face { font-family: '${name}'; src: ${src}; font-display: swap; }`;
621
+ document.head.appendChild(style);
622
+ break;
623
+ }
624
+ }
625
+ };
626
+
627
+ window.addEventListener('message', handleMessage);
628
+ return () => {
629
+ window.removeEventListener('message', handleMessage);
630
+ unregisterPlaceholder(slug);
631
+ };
632
+ }, [slug]);
633
+
634
+ const sendAction = (
635
+ action: string,
636
+ data: {
637
+ placeholderId?: string;
638
+ sectionId?: string;
639
+ blockId?: string;
640
+ label?: string;
641
+ }
642
+ ) => {
643
+ if (window.parent) {
644
+ window.parent.postMessage(
645
+ {
646
+ type: action,
647
+ data
648
+ },
649
+ '*'
650
+ );
651
+ }
652
+ };
653
+
654
+ const dynamicCSS = useMemo(
655
+ () =>
656
+ generateThemeCSS(sections, isDesigner ? currentBreakpoint : undefined),
657
+ [sections, isDesigner, currentBreakpoint]
658
+ );
659
+ const visibilityContext = useVisibilityContext(currentBreakpoint);
660
+ const renderedSections = useMemo(
661
+ () => applyVisibilityRulesToSections(sections, visibilityContext),
662
+ [sections, visibilityContext]
663
+ );
664
+
665
+ return (
666
+ <ThemeSettingsProvider value={themeSettings}>
667
+ {dynamicCSS && <style dangerouslySetInnerHTML={{ __html: dynamicCSS }} />}
668
+ <div
669
+ data-placeholder={slug}
670
+ className="theme-placeholder"
671
+ style={{ backgroundColor: 'var(--theme-background)' }}
672
+ >
673
+ {renderedSections
674
+ .sort((a, b) => a.order - b.order)
675
+ .filter((section) =>
676
+ !section.hidden &&
677
+ (isDesigner ||
678
+ isPublishWindowVisible(section.properties?.['publish-window']))
679
+ )
680
+ .map((section) => (
681
+ <ThemeSection
682
+ key={section.id}
683
+ section={section}
684
+ placeholderId={placeholderSlug}
685
+ isDesigner={isDesigner}
686
+ isSelected={selectedSectionId === section.id}
687
+ selectedBlockId={selectedBlockId}
688
+ currentBreakpoint={currentBreakpoint}
689
+ onSelect={setSelectedSectionId}
690
+ onMoveUp={() =>
691
+ sendAction('MOVE_SECTION_UP', {
692
+ placeholderId: placeholderSlug,
693
+ sectionId: section.id
694
+ })
695
+ }
696
+ onMoveDown={() =>
697
+ sendAction('MOVE_SECTION_DOWN', {
698
+ placeholderId: placeholderSlug,
699
+ sectionId: section.id
700
+ })
701
+ }
702
+ onDuplicate={() =>
703
+ sendAction('DUPLICATE_SECTION', {
704
+ placeholderId: placeholderSlug,
705
+ sectionId: section.id
706
+ })
707
+ }
708
+ onToggleVisibility={() =>
709
+ sendAction('TOGGLE_SECTION_VISIBILITY', {
710
+ placeholderId: placeholderSlug,
711
+ sectionId: section.id
712
+ })
713
+ }
714
+ onDelete={() =>
715
+ sendAction('DELETE_SECTION', {
716
+ placeholderId: placeholderSlug,
717
+ sectionId: section.id
718
+ })
719
+ }
720
+ onRename={(newLabel) =>
721
+ sendAction('RENAME_SECTION', {
722
+ placeholderId: placeholderSlug,
723
+ sectionId: section.id,
724
+ label: newLabel
725
+ })
726
+ }
727
+ />
728
+ ))}
729
+ </div>
730
+ </ThemeSettingsProvider>
731
+ );
732
+ }