@wewear/virtual-try-on 1.1.0 → 1.3.0

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.
package/dist/index.esm.js CHANGED
@@ -1,9 +1,28 @@
1
- /**
2
- * WeWear Virtual Try-On Widget Implementation
3
- *
4
- * Core widget class that handles virtual try-on functionality integration.
5
- * Manages button creation, API communication, and modal display.
6
- */
1
+ async function callVirtualTryOnApi(baseUrl, ww_access_token, ww_user_id, ww_product_id, ww_image) {
2
+ try {
3
+ const formData = new FormData();
4
+ formData.append("ww_user_id", ww_user_id);
5
+ formData.append("ww_product_id", ww_product_id);
6
+ formData.append("ww_image", ww_image, "captured-image.jpg");
7
+ formData.append("ww_access_token", ww_access_token);
8
+ const response = await fetch(`${baseUrl}/api/virtual-try-on`, {
9
+ method: "POST",
10
+ body: formData,
11
+ });
12
+ if (!response.ok) {
13
+ console.error("[WeWear VTO] API request failed:", response.status, response.statusText);
14
+ return null;
15
+ }
16
+ const result = await response.json();
17
+ console.log("[WeWear VTO] API response:", result);
18
+ return result;
19
+ }
20
+ catch (error) {
21
+ console.error("[WeWear VTO] API call failed:", error);
22
+ return null;
23
+ }
24
+ }
25
+
7
26
  /** Default configuration constants */
8
27
  const DEFAULT_CONFIG = {
9
28
  BASE_URL: "https://virtual-try-on-widget.vercel.app",
@@ -23,335 +42,583 @@ const Z_INDEX = {
23
42
  BUTTON: 10,
24
43
  MODAL: 99999,
25
44
  };
26
- class VirtualTryOnWidget {
27
- constructor(config = {}) {
28
- this.config = {
29
- baseUrl: config.baseUrl || DEFAULT_CONFIG.BASE_URL,
30
- productPageSelector: config.productPageSelector || DEFAULT_CONFIG.PRODUCT_PAGE_SELECTOR,
31
- gallerySelector: config.gallerySelector || DEFAULT_CONFIG.GALLERY_SELECTOR,
32
- skuSelector: config.skuSelector || DEFAULT_CONFIG.SKU_SELECTOR,
33
- buttonPosition: config.buttonPosition || DEFAULT_CONFIG.BUTTON_POSITION,
45
+ /** Camera constraints for optimal capture */
46
+ const CAMERA_CONSTRAINTS = {
47
+ video: {
48
+ width: { ideal: 1280 },
49
+ height: { ideal: 720 },
50
+ facingMode: "user", // Front-facing camera
51
+ },
52
+ audio: false,
53
+ };
54
+ /** Image capture settings */
55
+ const IMAGE_SETTINGS = {
56
+ FORMAT: "image/jpeg",
57
+ QUALITY: 0.8,
58
+ };
59
+
60
+ async function startCamera(video, loadingIndicator, captureButton) {
61
+ console.log("[WeWear VTO] Starting camera...");
62
+ try {
63
+ console.log("[WeWear VTO] Requesting camera access...");
64
+ const stream = await navigator.mediaDevices.getUserMedia(CAMERA_CONSTRAINTS);
65
+ video.srcObject = stream;
66
+ video.onloadedmetadata = () => {
67
+ console.log("[WeWear VTO] Camera stream loaded successfully");
68
+ loadingIndicator.style.display = "none";
69
+ captureButton.style.display = "flex";
34
70
  };
35
71
  }
36
- /**
37
- * Retrieves a cookie value by name
38
- * @param name - Cookie name to retrieve
39
- * @returns Cookie value or null if not found
40
- */
41
- getCookie(name) {
42
- var _a;
43
- if (typeof document === "undefined")
44
- return null;
45
- const value = `; ${document.cookie}`;
46
- const parts = value.split(`; ${name}=`);
47
- if (parts.length === 2) {
48
- const part = parts.pop();
49
- return part ? ((_a = part.split(";").shift()) === null || _a === void 0 ? void 0 : _a.trim()) || null : null;
50
- }
51
- return null;
72
+ catch (error) {
73
+ console.error("[WeWear VTO] Camera access error:", error);
74
+ loadingIndicator.innerHTML =
75
+ "Camera access denied. Please allow camera permissions.";
52
76
  }
53
- /**
54
- * Makes API call to virtual try-on service
55
- * @param ww_access_token - Optional authentication token
56
- * @param ww_user_id - User identifier
57
- /**
58
- * Creates the virtual try-on button element
59
- * @param onClick - Click handler function
60
- * @returns Button container element
61
- */
62
- createButton(onClick) {
63
- const container = document.createElement("div");
64
- container.className = CSS_CLASSES.BUTTON_CONTAINER;
65
- const positionStyles = this.getPositionStyles();
66
- container.style.cssText = `
67
- position: absolute;
68
- ${positionStyles}
69
- display: flex;
70
- border-radius: 50%;
71
- background: #000000;
72
- padding: 4px;
73
- box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
74
- z-index: ${Z_INDEX.BUTTON};
75
- transition: transform 0.2s ease, box-shadow 0.2s ease;
76
- `;
77
- const button = document.createElement("button");
78
- button.type = "button";
79
- button.className = CSS_CLASSES.BUTTON;
80
- button.setAttribute("aria-label", "Virtual Try-On");
81
- button.setAttribute("title", "Try this product virtually");
82
- button.style.cssText = `
83
- display: flex;
84
- width: 36px;
85
- height: 36px;
86
- cursor: pointer;
87
- align-items: center;
88
- justify-content: center;
89
- border-radius: 50%;
90
- padding: 10px;
91
- border: none;
92
- background: transparent;
93
- color: #ffffff;
94
- `;
95
- // Add hover effects
96
- container.addEventListener("mouseenter", () => {
97
- container.style.transform = "scale(1.05)";
98
- container.style.boxShadow = "0 30px 60px -12px rgba(0, 0, 0, 0.35)";
99
- });
100
- container.addEventListener("mouseleave", () => {
101
- container.style.transform = "scale(1)";
102
- container.style.boxShadow = "0 25px 50px -12px rgba(0, 0, 0, 0.25)";
77
+ }
78
+ function stopCamera(video) {
79
+ const stream = video.srcObject;
80
+ if (stream) {
81
+ const tracks = stream.getTracks();
82
+ tracks.forEach((track) => {
83
+ track.stop();
103
84
  });
104
- button.innerHTML = `
105
- <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
106
- <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"></path>
107
- <circle cx="12" cy="13" r="3"></circle>
108
- </svg>
109
- `;
110
- button.onclick = onClick;
111
- container.appendChild(button);
112
- return container;
85
+ video.srcObject = null;
113
86
  }
114
- /**
115
- * Gets CSS position styles based on button position configuration
116
- * @returns CSS position string
117
- */
118
- getPositionStyles() {
119
- switch (this.config.buttonPosition) {
120
- case "bottom-left":
121
- return "left: 20px; bottom: 20px;";
122
- case "top-right":
123
- return "right: 20px; top: 20px;";
124
- case "top-left":
125
- return "left: 20px; top: 20px;";
126
- default:
127
- return "right: 20px; bottom: 20px;";
128
- }
87
+ }
88
+ async function captureImageFromVideo(video, canvas) {
89
+ // Set canvas dimensions to match video
90
+ canvas.width = video.videoWidth;
91
+ canvas.height = video.videoHeight;
92
+ // Draw video frame to canvas
93
+ const ctx = canvas.getContext("2d");
94
+ if (!ctx) {
95
+ throw new Error("Could not get canvas context");
129
96
  }
130
- /**
131
- * Displays the virtual try-on result in a modal
132
- * @param imageUrl - URL of the virtual try-on image
133
- */
134
- showImageModal(imageUrl) {
135
- // Remove any existing modals first
136
- const existingModals = document.querySelectorAll(`.${CSS_CLASSES.MODAL}`);
137
- existingModals.forEach((modal) => {
138
- modal.remove();
139
- });
140
- // Create modal container
141
- const modal = document.createElement("div");
142
- modal.className = CSS_CLASSES.MODAL;
143
- modal.style.cssText = `
144
- position: fixed;
145
- top: 0;
146
- left: 0;
147
- width: 100%;
148
- height: 100%;
149
- background-color: rgba(0, 0, 0, 0.9);
150
- display: flex;
151
- align-items: center;
152
- justify-content: center;
153
- z-index: ${Z_INDEX.MODAL};
154
- padding: 20px;
155
- box-sizing: border-box;
156
- `;
157
- // Create image container
158
- const imageContainer = document.createElement("div");
159
- imageContainer.style.cssText = `
160
- position: relative;
161
- max-width: 90%;
162
- max-height: 90%;
163
- background-color: white;
164
- border-radius: 8px;
165
- box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
166
- overflow: hidden;
167
- `;
168
- // Create image element
169
- const image = document.createElement("img");
170
- image.src = imageUrl;
171
- image.alt = "Virtual Try-On Result";
172
- image.style.cssText = `
173
- width: 100%;
174
- height: 100%;
175
- object-fit: contain;
176
- display: block;
177
- `;
178
- // Create close button
179
- const closeButton = document.createElement("button");
180
- closeButton.innerHTML = "×";
181
- closeButton.style.cssText = `
182
- position: absolute;
183
- top: 10px;
184
- right: 10px;
185
- width: 30px;
186
- height: 30px;
187
- border: none;
188
- background-color: rgba(0, 0, 0, 0.7);
189
- color: white;
190
- font-size: 20px;
191
- font-weight: bold;
192
- cursor: pointer;
193
- border-radius: 50%;
194
- display: flex;
195
- align-items: center;
196
- justify-content: center;
197
- `;
198
- closeButton.onclick = () => {
199
- modal.remove();
200
- };
201
- // Close on backdrop click
202
- modal.onclick = (e) => {
203
- if (e.target === modal) {
204
- modal.remove();
97
+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
98
+ // Convert canvas to blob
99
+ return new Promise((resolve, reject) => {
100
+ canvas.toBlob((blob) => {
101
+ if (blob) {
102
+ resolve(blob);
205
103
  }
206
- };
207
- // Close on Escape key
208
- const handleEscape = (e) => {
209
- if (e.key === "Escape") {
210
- modal.remove();
211
- document.removeEventListener("keydown", handleEscape);
104
+ else {
105
+ reject(new Error("Failed to create blob from canvas"));
212
106
  }
213
- };
214
- document.addEventListener("keydown", handleEscape);
215
- imageContainer.appendChild(image);
216
- imageContainer.appendChild(closeButton);
217
- modal.appendChild(imageContainer);
218
- document.body.appendChild(modal);
107
+ }, IMAGE_SETTINGS.FORMAT, IMAGE_SETTINGS.QUALITY);
108
+ });
109
+ }
110
+
111
+ function getCookie(name) {
112
+ var _a;
113
+ if (typeof document === "undefined")
114
+ return null;
115
+ const value = `; ${document.cookie}`;
116
+ const parts = value.split(`; ${name}=`);
117
+ if (parts.length === 2) {
118
+ const part = parts.pop();
119
+ return part ? ((_a = part.split(";").shift()) === null || _a === void 0 ? void 0 : _a.trim()) || null : null;
219
120
  }
220
- /**
221
- * Shows the camera capture modal
222
- * @param ww_access_token - Access token for API
223
- * @param ww_user_id - User identifier
224
- * @param ww_product_id - Product identifier
225
- */
226
- showCameraModal(ww_access_token, ww_user_id, ww_product_id) {
227
- console.log("[WeWear VTO] Opening camera modal...");
228
- // Remove any existing modals first
229
- const existingModals = document.querySelectorAll(`.${CSS_CLASSES.MODAL}`);
230
- existingModals.forEach((modal) => {
231
- modal.remove();
232
- });
233
- // Create modal container
234
- const modal = document.createElement("div");
235
- modal.className = CSS_CLASSES.MODAL;
236
- modal.style.cssText = `
237
- position: fixed;
238
- top: 0;
239
- left: 0;
240
- width: 100%;
241
- height: 100%;
242
- background-color: rgba(0, 0, 0, 0.95);
243
- display: flex;
244
- flex-direction: column;
245
- align-items: center;
246
- justify-content: center;
247
- z-index: ${Z_INDEX.MODAL};
248
- padding: 20px;
249
- box-sizing: border-box;
250
- `;
251
- // Create camera container
252
- const cameraContainer = document.createElement("div");
253
- cameraContainer.style.cssText = `
254
- position: relative;
255
- width: 100%;
256
- max-width: 500px;
257
- height: 70vh;
258
- background-color: #000;
259
- border-radius: 12px;
260
- overflow: hidden;
261
- display: flex;
262
- flex-direction: column;
263
- align-items: center;
264
- justify-content: center;
265
- `;
266
- // Create video element
267
- const video = document.createElement("video");
268
- video.autoplay = true;
269
- video.playsInline = true;
270
- video.muted = true;
271
- video.style.cssText = `
272
- width: 100%;
273
- height: 100%;
274
- object-fit: cover;
275
- border-radius: 12px;
276
- `;
277
- // Create canvas for capturing
278
- const canvas = document.createElement("canvas");
279
- canvas.style.display = "none";
280
- // Create capture button
281
- const captureButton = document.createElement("button");
282
- captureButton.innerHTML = `
283
- <svg width="24" height="24" viewBox="0 0 24 24" fill="white">
284
- <circle cx="12" cy="12" r="10" stroke="white" stroke-width="2" fill="none"/>
285
- <circle cx="12" cy="12" r="6" fill="white"/>
121
+ return null;
122
+ }
123
+ function getPositionStyles(position) {
124
+ switch (position) {
125
+ case "bottom-left":
126
+ return "left: 20px; bottom: 20px;";
127
+ case "top-right":
128
+ return "right: 20px; top: 20px;";
129
+ case "top-left":
130
+ return "left: 20px; top: 20px;";
131
+ default:
132
+ return "right: 20px; bottom: 20px;";
133
+ }
134
+ }
135
+ function removeElements(selector) {
136
+ const elements = document.querySelectorAll(selector);
137
+ elements.forEach((element) => {
138
+ element.remove();
139
+ });
140
+ }
141
+
142
+ function createButtonContainer(buttonPosition, hasVirtualTryOn = false, onCameraClick, onRefreshClick, onToggleClick, isShowingVirtualTryOn = false) {
143
+ const container = document.createElement("div");
144
+ container.className = `${CSS_CLASSES.BUTTON_CONTAINER} ww-button-group`;
145
+ const positionStyles = getPositionStyles(buttonPosition);
146
+ container.style.cssText = `
147
+ position: absolute;
148
+ ${positionStyles}
149
+ display: flex;
150
+ border-radius: 9999px;
151
+ background: white;
152
+ padding: 4px;
153
+ box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
154
+ z-index: ${Z_INDEX.BUTTON};
155
+ `;
156
+ // Camera button
157
+ const cameraButton = document.createElement("button");
158
+ cameraButton.type = "button";
159
+ cameraButton.className = `${CSS_CLASSES.BUTTON} ww-camera-btn`;
160
+ cameraButton.setAttribute("aria-label", "Virtual Try-On");
161
+ cameraButton.style.cssText = `
162
+ display: flex;
163
+ width: 36px;
164
+ height: 36px;
165
+ cursor: pointer;
166
+ align-items: center;
167
+ justify-content: center;
168
+ border-radius: 9999px;
169
+ padding: 8px;
170
+ border: none;
171
+ background: transparent;
172
+ color: currentColor;
173
+ `;
174
+ cameraButton.innerHTML = `
175
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-camera">
176
+ <path d="M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z"></path>
177
+ <circle cx="12" cy="13" r="3"></circle>
178
+ </svg>
179
+ `;
180
+ cameraButton.onclick = onCameraClick;
181
+ container.appendChild(cameraButton);
182
+ // Add refresh and toggle buttons if we have a virtual try-on
183
+ if (hasVirtualTryOn) {
184
+ // Refresh button - calls API again
185
+ if (onRefreshClick) {
186
+ const refreshButton = document.createElement("button");
187
+ refreshButton.type = "button";
188
+ refreshButton.className = "ww-refresh-btn";
189
+ refreshButton.setAttribute("aria-label", "Refresh virtual try-on");
190
+ refreshButton.style.cssText = `
191
+ display: flex;
192
+ width: 36px;
193
+ height: 36px;
194
+ cursor: pointer;
195
+ align-items: center;
196
+ justify-content: center;
197
+ border-radius: 9999px;
198
+ padding: 8px;
199
+ border: none;
200
+ background: transparent;
201
+ color: currentColor;
202
+ `;
203
+ refreshButton.innerHTML = `
204
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-refresh-ccw">
205
+ <path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"></path>
206
+ <path d="M3 3v5h5"></path>
207
+ <path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"></path>
208
+ <path d="M16 16h5v5"></path>
209
+ </svg>
210
+ `;
211
+ refreshButton.onclick = onRefreshClick;
212
+ container.appendChild(refreshButton);
213
+ }
214
+ // Toggle button (scan-face) - switches between original and virtual try-on
215
+ if (onToggleClick) {
216
+ const toggleButton = document.createElement("button");
217
+ toggleButton.type = "button";
218
+ toggleButton.className = "ww-toggle-btn";
219
+ toggleButton.setAttribute("aria-label", isShowingVirtualTryOn ? "Show Original Image" : "Show Virtual Try-On");
220
+ toggleButton.style.cssText = `
221
+ display: flex;
222
+ width: 36px;
223
+ height: 36px;
224
+ cursor: pointer;
225
+ align-items: center;
226
+ justify-content: center;
227
+ border-radius: 9999px;
228
+ padding: 8px;
229
+ border: none;
230
+ background: ${isShowingVirtualTryOn ? "rgba(0, 0, 0)" : "none"};
231
+ color: ${isShowingVirtualTryOn ? "white" : "currentColor"};
232
+ `;
233
+ toggleButton.innerHTML = `
234
+ <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-scan-face">
235
+ <path d="M3 7V5a2 2 0 0 1 2-2h2"></path>
236
+ <path d="M17 3h2a2 2 0 0 1 2 2v2"></path>
237
+ <path d="M21 17v2a2 2 0 0 1-2 2h-2"></path>
238
+ <path d="M7 21H5a2 2 0 0 1-2-2v-2"></path>
239
+ <path d="M8 14s1.5 2 4 2 4-2 4-2"></path>
240
+ <path d="M9 9h.01"></path>
241
+ <path d="M15 9h.01"></path>
242
+ </svg>
243
+ `;
244
+ toggleButton.onclick = onToggleClick;
245
+ container.appendChild(toggleButton);
246
+ }
247
+ }
248
+ return container;
249
+ }
250
+ function createButton(buttonPosition, onClick) {
251
+ return createButtonContainer(buttonPosition, false, onClick);
252
+ }
253
+
254
+ function showCameraModal(callbacks) {
255
+ console.log("[WeWear VTO] Opening camera modal...");
256
+ // Remove any existing modals first
257
+ removeElements(`.${CSS_CLASSES.MODAL}`);
258
+ // Create modal container
259
+ const modal = document.createElement("div");
260
+ modal.className = CSS_CLASSES.MODAL;
261
+ modal.style.cssText = `
262
+ position: fixed;
263
+ top: 0;
264
+ left: 0;
265
+ width: 100%;
266
+ height: 100%;
267
+ background-color: rgba(0, 0, 0, 0.95);
268
+ display: flex;
269
+ flex-direction: column;
270
+ align-items: center;
271
+ justify-content: center;
272
+ z-index: ${Z_INDEX.MODAL};
273
+ padding: 20px;
274
+ box-sizing: border-box;
275
+ `;
276
+ // Create camera container
277
+ const cameraContainer = document.createElement("div");
278
+ cameraContainer.style.cssText = `
279
+ position: relative;
280
+ width: 100%;
281
+ max-width: 500px;
282
+ height: 70vh;
283
+ background-color: #000;
284
+ border-radius: 12px;
285
+ overflow: hidden;
286
+ display: flex;
287
+ flex-direction: column;
288
+ align-items: center;
289
+ justify-content: center;
290
+ `;
291
+ // Create video element
292
+ const video = document.createElement("video");
293
+ video.autoplay = true;
294
+ video.playsInline = true;
295
+ video.muted = true;
296
+ video.style.cssText = `
297
+ width: 100%;
298
+ height: 100%;
299
+ object-fit: cover;
300
+ border-radius: 12px;
301
+ `;
302
+ // Create canvas for capturing
303
+ const canvas = document.createElement("canvas");
304
+ canvas.style.display = "none";
305
+ // Create capture button
306
+ const captureButton = document.createElement("button");
307
+ captureButton.innerHTML = "";
308
+ captureButton.style.cssText = `
309
+ position: absolute;
310
+ bottom: 20px;
311
+ left: 50%;
312
+ transform: translateX(-50%);
313
+ width: 60px;
314
+ height: 60px;
315
+ border: 3px solid white;
316
+ background-color: rgba(0, 0, 0, 0.7);
317
+ border-radius: 50%;
318
+ cursor: pointer;
319
+ display: none;
320
+ align-items: center;
321
+ justify-content: center;
322
+ transition: all 0.2s ease;
323
+ `;
324
+ // Create close button
325
+ const closeButton = document.createElement("button");
326
+ closeButton.innerHTML = "×";
327
+ closeButton.style.cssText = `
328
+ position: absolute;
329
+ top: 15px;
330
+ right: 15px;
331
+ width: 40px;
332
+ height: 40px;
333
+ border: none;
334
+ background-color: rgba(0, 0, 0, 0.7);
335
+ color: white;
336
+ font-size: 24px;
337
+ font-weight: bold;
338
+ cursor: pointer;
339
+ border-radius: 50%;
340
+ display: flex;
341
+ align-items: center;
342
+ justify-content: center;
343
+ `;
344
+ // Create loading indicator
345
+ const loadingIndicator = document.createElement("div");
346
+ loadingIndicator.innerHTML = "Initializing camera...";
347
+ loadingIndicator.style.cssText = `
348
+ color: white;
349
+ font-size: 16px;
350
+ position: absolute;
351
+ top: 50%;
352
+ left: 50%;
353
+ transform: translate(-50%, -50%);
354
+ `;
355
+ // Add event listeners
356
+ closeButton.onclick = () => {
357
+ stopCamera(video);
358
+ modal.remove();
359
+ };
360
+ captureButton.onclick = async () => {
361
+ await callbacks.onCapture(video, canvas);
362
+ };
363
+ // Assemble the camera modal
364
+ cameraContainer.appendChild(video);
365
+ cameraContainer.appendChild(canvas);
366
+ cameraContainer.appendChild(captureButton);
367
+ cameraContainer.appendChild(closeButton);
368
+ cameraContainer.appendChild(loadingIndicator);
369
+ modal.appendChild(cameraContainer);
370
+ document.body.appendChild(modal);
371
+ console.log("[WeWear VTO] Camera modal added to DOM");
372
+ // Start camera
373
+ startCamera(video, loadingIndicator, captureButton);
374
+ }
375
+
376
+ /**
377
+ * Creates a loading overlay that can be shown in different containers
378
+ */
379
+ function createLoadingOverlay(text = "Processing...") {
380
+ const overlay = document.createElement("div");
381
+ overlay.className = "ww-loading-overlay";
382
+ overlay.style.cssText = `
383
+ position: absolute;
384
+ top: 0;
385
+ left: 0;
386
+ width: 100%;
387
+ height: 100%;
388
+ background-color: rgba(0, 0, 0, 0.8);
389
+ display: flex;
390
+ flex-direction: column;
391
+ align-items: center;
392
+ justify-content: center;
393
+ z-index: ${Z_INDEX.MODAL + 1};
394
+ border-radius: inherit;
395
+ `;
396
+ // Add CSS animation to the document if not already added
397
+ if (!document.getElementById("ww-loading-animation")) {
398
+ const style = document.createElement("style");
399
+ style.id = "ww-loading-animation";
400
+ style.textContent = `
401
+ @keyframes ww-pulse {
402
+ 0%, 100% { opacity: 0.7; transform: scale(1); }
403
+ 50% { opacity: 1; transform: scale(1.05); }
404
+ }
405
+ .ww-loading-overlay .ww-logo {
406
+ animation: ww-pulse 2s ease-in-out infinite;
407
+ }
408
+ `;
409
+ document.head.appendChild(style);
410
+ }
411
+ overlay.innerHTML = `
412
+ <div style="display: flex; flex-direction: column; align-items: center; gap: 24px; color: white;">
413
+ <svg class="ww-logo" width="80" height="50" viewBox="0 0 214 135" fill="none" xmlns="http://www.w3.org/2000/svg">
414
+ <g clip-path="url(#clip0_3624_12755)">
415
+ <path d="M102.906 74.8679C102.906 77.9717 101.574 80.7453 98.9104 83.1887C96.6871 85.1918 93.9025 86.6997 90.5566 87.7123C87.695 88.5708 84.6462 89 81.4104 89C73.8821 89 68.0047 87.0189 63.7783 83.0566C59.5519 87.0189 53.6855 89 46.1792 89C42.9434 89 39.9057 88.5708 37.066 87.7123C33.7201 86.6997 30.9245 85.1918 28.6792 83.1887C26.0157 80.7453 24.684 77.9717 24.684 74.8679V41.6509H32.3774V74.8679C32.3774 76.2547 33.489 77.5645 35.7123 78.7972C37.3632 79.7217 39.0692 80.3711 40.8302 80.7453C42.5252 81.1195 44.3082 81.3066 46.1792 81.3066C48.0063 81.3066 49.7673 81.1195 51.4623 80.7453C53.2453 80.3711 54.9623 79.7217 56.6132 78.7972C58.8585 77.5645 59.9811 76.2547 59.9811 74.8679V41.6509H67.6085V74.8679C67.6085 76.2547 68.7311 77.5645 70.9764 78.7972C72.6274 79.7217 74.3443 80.3711 76.1274 80.7453C77.8223 81.1195 79.5833 81.3066 81.4104 81.3066C83.2814 81.3066 85.0755 81.1195 86.7925 80.7453C88.5314 80.3711 90.2264 79.7217 91.8774 78.7972C94.1006 77.5645 95.2123 76.2547 95.2123 74.8679V41.6509H102.906V74.8679ZM189.283 74.8679C189.283 77.9717 187.951 80.7453 185.288 83.1887C183.064 85.1918 180.28 86.6997 176.934 87.7123C174.072 88.5708 171.024 89 167.788 89C160.259 89 154.382 87.0189 150.156 83.0566C145.929 87.0189 140.063 89 132.557 89C129.321 89 126.283 88.5708 123.443 87.7123C120.097 86.6997 117.302 85.1918 115.057 83.1887C112.393 80.7453 111.061 77.9717 111.061 74.8679V41.6509H118.755V74.8679C118.755 76.2547 119.866 77.5645 122.09 78.7972C123.741 79.7217 125.447 80.3711 127.208 80.7453C128.903 81.1195 130.686 81.3066 132.557 81.3066C134.384 81.3066 136.145 81.1195 137.84 80.7453C139.623 80.3711 141.34 79.7217 142.991 78.7972C145.236 77.5645 146.358 76.2547 146.358 74.8679V41.6509H153.986V74.8679C153.986 76.2547 155.108 77.5645 157.354 78.7972C159.005 79.7217 160.722 80.3711 162.505 80.7453C164.2 81.1195 165.961 81.3066 167.788 81.3066C169.659 81.3066 171.453 81.1195 173.17 80.7453C174.909 80.3711 176.604 79.7217 178.255 78.7972C180.478 77.5645 181.59 76.2547 181.59 74.8679V41.6509H189.283V74.8679Z" fill="white"/>
416
+ </g>
417
+ <defs>
418
+ <clipPath id="clip0_3624_12755">
419
+ <rect width="214" height="135" fill="white"/>
420
+ </clipPath>
421
+ </defs>
286
422
  </svg>
287
- `;
288
- captureButton.style.cssText = `
289
- position: absolute;
290
- bottom: 20px;
291
- left: 50%;
292
- transform: translateX(-50%);
293
- width: 60px;
294
- height: 60px;
295
- border: 3px solid white;
296
- background-color: transparent;
297
- border-radius: 50%;
298
- cursor: pointer;
299
- display: none;
300
- align-items: center;
301
- justify-content: center;
302
- transition: all 0.2s ease;
303
- `;
304
- // Create close button
305
- const closeButton = document.createElement("button");
306
- closeButton.innerHTML = "×";
307
- closeButton.style.cssText = `
308
- position: absolute;
309
- top: 15px;
310
- right: 15px;
311
- width: 40px;
312
- height: 40px;
313
- border: none;
314
- background-color: rgba(0, 0, 0, 0.7);
315
- color: white;
316
- font-size: 24px;
317
- font-weight: bold;
318
- cursor: pointer;
319
- border-radius: 50%;
320
- display: flex;
321
- align-items: center;
322
- justify-content: center;
323
- `;
324
- // Create loading indicator
325
- const loadingIndicator = document.createElement("div");
326
- loadingIndicator.innerHTML = "Initializing camera...";
327
- loadingIndicator.style.cssText = `
328
- color: white;
329
- font-size: 16px;
330
- position: absolute;
331
- top: 50%;
332
- left: 50%;
333
- transform: translate(-50%, -50%);
334
- `;
335
- // Add event listeners
336
- closeButton.onclick = () => {
337
- this.stopCamera(video);
338
- modal.remove();
339
- };
340
- captureButton.onclick = () => {
341
- this.captureImage(video, canvas, ww_access_token, ww_user_id, ww_product_id, modal);
423
+ <div style="font-size: 16px; font-weight: 500; text-align: center; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">${text}</div>
424
+ </div>
425
+ `;
426
+ return overlay;
427
+ }
428
+ /**
429
+ * Shows a loading overlay in a modal container
430
+ */
431
+ function showModalLoading(text = "Processing...") {
432
+ const modal = document.querySelector(`.${CSS_CLASSES.MODAL}`);
433
+ if (!modal)
434
+ return;
435
+ // Remove any existing loading overlays
436
+ removeModalLoading();
437
+ const loadingOverlay = createLoadingOverlay(text);
438
+ modal.appendChild(loadingOverlay);
439
+ }
440
+ /**
441
+ * Removes loading overlay from modal
442
+ */
443
+ function removeModalLoading() {
444
+ const modal = document.querySelector(`.${CSS_CLASSES.MODAL}`);
445
+ if (!modal)
446
+ return;
447
+ const existingOverlay = modal.querySelector(".ww-loading-overlay");
448
+ if (existingOverlay) {
449
+ existingOverlay.remove();
450
+ }
451
+ }
452
+ /**
453
+ * Shows a loading overlay in the product gallery container
454
+ */
455
+ function showProductLoading(container, text = "Generating virtual try-on...") {
456
+ // Remove any existing loading overlays
457
+ removeProductLoading(container);
458
+ // Make container relative if it's not already positioned
459
+ const computedStyle = window.getComputedStyle(container);
460
+ if (computedStyle.position === "static") {
461
+ container.style.position = "relative";
462
+ }
463
+ const loadingOverlay = createLoadingOverlay(text);
464
+ container.appendChild(loadingOverlay);
465
+ }
466
+ /**
467
+ * Removes loading overlay from product container
468
+ */
469
+ function removeProductLoading(container) {
470
+ const existingOverlay = container.querySelector(".ww-loading-overlay");
471
+ if (existingOverlay) {
472
+ existingOverlay.remove();
473
+ }
474
+ }
475
+
476
+ function showReviewModal(imageBlob, callbacks) {
477
+ console.log("[WeWear VTO] Opening review modal...");
478
+ // Remove any existing modals first
479
+ removeElements(`.${CSS_CLASSES.MODAL}`);
480
+ // Create image URL for preview
481
+ const imageUrl = URL.createObjectURL(imageBlob);
482
+ // Create modal container
483
+ const modal = document.createElement("div");
484
+ modal.className = CSS_CLASSES.MODAL;
485
+ modal.style.cssText = `
486
+ position: fixed;
487
+ top: 0;
488
+ left: 0;
489
+ width: 100%;
490
+ height: 100%;
491
+ background-color: rgba(0, 0, 0, 0.95);
492
+ display: flex;
493
+ flex-direction: column;
494
+ align-items: center;
495
+ justify-content: center;
496
+ z-index: ${Z_INDEX.MODAL};
497
+ padding: 20px;
498
+ box-sizing: border-box;
499
+ gap: 20px;
500
+ `;
501
+ // Create review container
502
+ const reviewContainer = document.createElement("div");
503
+ reviewContainer.style.cssText = `
504
+ position: relative;
505
+ width: 100%;
506
+ max-width: 500px;
507
+ height: 63vh;
508
+ background-color: #000;
509
+ border-radius: 12px;
510
+ overflow: hidden;
511
+ display: flex;
512
+ flex-direction: column;
513
+ align-items: center;
514
+ justify-content: center;
515
+ `;
516
+ // Create image element
517
+ const image = document.createElement("img");
518
+ image.src = imageUrl;
519
+ image.alt = "Review your photo";
520
+ image.style.cssText = `
521
+ width: 100%;
522
+ height: 100%;
523
+ object-fit: cover;
524
+ border-radius: 12px;
525
+ `;
526
+ // Create close button
527
+ const closeButton = document.createElement("button");
528
+ closeButton.innerHTML = "×";
529
+ closeButton.style.cssText = `
530
+ position: absolute;
531
+ top: 15px;
532
+ right: 15px;
533
+ width: 40px;
534
+ height: 40px;
535
+ border: none;
536
+ background-color: rgba(0, 0, 0, 0.7);
537
+ color: white;
538
+ font-size: 24px;
539
+ font-weight: bold;
540
+ cursor: pointer;
541
+ border-radius: 50%;
542
+ display: flex;
543
+ align-items: center;
544
+ justify-content: center;
545
+ `;
546
+ // Create button container
547
+ const buttonContainer = document.createElement("div");
548
+ buttonContainer.style.cssText = `
549
+ display: flex;
550
+ gap: 15px;
551
+ width: 100%;
552
+ max-width: 500px;
553
+ `;
554
+ // Create retake button
555
+ const retakeButton = document.createElement("button");
556
+ retakeButton.textContent = "Retake";
557
+ retakeButton.style.cssText = `
558
+ flex: 1;
559
+ padding: 12px 24px;
560
+ background-color: rgba(255, 255, 255, 0.9);
561
+ color: black;
562
+ border-radius: 8px;
563
+ border: none;
564
+ font-size: 16px;
565
+ font-weight: normal;
566
+ cursor: pointer;
567
+ `;
568
+ // Create use photo button
569
+ const usePhotoButton = document.createElement("button");
570
+ usePhotoButton.textContent = "Use Photo";
571
+ usePhotoButton.style.cssText = `
572
+ flex: 1;
573
+ padding: 12px 24px;
574
+ background-color: rgba(0, 0, 0, 0.7);
575
+ color: white;
576
+ border-radius: 8px;
577
+ border: none;
578
+ font-size: 16px;
579
+ font-weight: normal;
580
+ cursor: pointer;
581
+ `;
582
+ // Add event listeners
583
+ closeButton.onclick = () => {
584
+ URL.revokeObjectURL(imageUrl); // Clean up
585
+ modal.remove();
586
+ };
587
+ retakeButton.onclick = () => {
588
+ URL.revokeObjectURL(imageUrl); // Clean up
589
+ modal.remove();
590
+ callbacks.onRetake();
591
+ };
592
+ usePhotoButton.onclick = async () => {
593
+ URL.revokeObjectURL(imageUrl); // Clean up
594
+ modal.remove();
595
+ await callbacks.onAccept(imageBlob);
596
+ };
597
+ // Assemble the review modal
598
+ buttonContainer.appendChild(retakeButton);
599
+ buttonContainer.appendChild(usePhotoButton);
600
+ reviewContainer.appendChild(image);
601
+ reviewContainer.appendChild(closeButton);
602
+ modal.appendChild(reviewContainer);
603
+ modal.appendChild(buttonContainer);
604
+ document.body.appendChild(modal);
605
+ console.log("[WeWear VTO] Review modal added to DOM");
606
+ }
607
+
608
+ class VirtualTryOnWidget {
609
+ constructor(config = {}) {
610
+ this.virtualTryOnImageUrl = null;
611
+ this.isShowingVirtualTryOn = false;
612
+ this.lastApiParams = null;
613
+ this.config = {
614
+ baseUrl: config.baseUrl || DEFAULT_CONFIG.BASE_URL,
615
+ productPageSelector: config.productPageSelector || DEFAULT_CONFIG.PRODUCT_PAGE_SELECTOR,
616
+ gallerySelector: config.gallerySelector || DEFAULT_CONFIG.GALLERY_SELECTOR,
617
+ skuSelector: config.skuSelector || DEFAULT_CONFIG.SKU_SELECTOR,
618
+ buttonPosition: config.buttonPosition || DEFAULT_CONFIG.BUTTON_POSITION,
342
619
  };
343
- // Assemble the camera modal
344
- cameraContainer.appendChild(video);
345
- cameraContainer.appendChild(canvas);
346
- cameraContainer.appendChild(captureButton);
347
- cameraContainer.appendChild(closeButton);
348
- cameraContainer.appendChild(loadingIndicator);
349
- modal.appendChild(cameraContainer);
350
- document.body.appendChild(modal);
351
- console.log("[WeWear VTO] Camera modal added to DOM");
352
- // Start camera
353
- this.startCamera(video, loadingIndicator, captureButton);
354
- } /**
620
+ }
621
+ /**
355
622
  * Initializes the virtual try-on widget on the current page
356
623
  * @returns Promise that resolves when initialization is complete
357
624
  */
@@ -372,7 +639,7 @@ class VirtualTryOnWidget {
372
639
  container.style.position = "relative";
373
640
  }
374
641
  // Create and add the virtual try-on button
375
- const button = this.createButton(async () => {
642
+ const button = createButton(this.config.buttonPosition, async () => {
376
643
  await this.handleTryOnClick();
377
644
  });
378
645
  container.appendChild(button);
@@ -391,352 +658,252 @@ class VirtualTryOnWidget {
391
658
  console.log("[WeWear VTO] Button clicked, starting try-on process...");
392
659
  try {
393
660
  // Get required data
394
- const ww_access_token = this.getCookie("ww_access_token");
395
- const ww_user_id = this.getCookie("ww_user_id");
661
+ const ww_access_token = getCookie("ww_access_token");
662
+ const ww_user_id = getCookie("ww_user_id");
396
663
  const skuElement = document.querySelector(this.config.skuSelector);
397
664
  const ww_product_id = (_a = skuElement === null || skuElement === void 0 ? void 0 : skuElement.textContent) === null || _a === void 0 ? void 0 : _a.trim();
398
665
  console.log("[WeWear VTO] Retrieved data:", {
399
666
  ww_user_id,
400
667
  ww_product_id,
401
- ww_access_token: !!ww_access_token,
668
+ ww_access_token,
402
669
  });
403
670
  // Validate required data
404
671
  if (!ww_user_id) {
405
672
  console.warn("[WeWear VTO] Missing required cookie: ww_user_id");
406
- this.showError("Please sign in to use virtual try-on");
407
673
  return;
408
674
  }
409
675
  if (!ww_product_id) {
410
676
  console.warn("[WeWear VTO] Product SKU not found:", this.config.skuSelector);
411
- this.showError("Product information not available");
677
+ return;
678
+ }
679
+ if (!ww_access_token) {
680
+ console.warn("[WeWear VTO] Missing required cookie: ww_access_token");
412
681
  return;
413
682
  }
414
683
  // Show camera capture modal
415
- this.showCameraModal(ww_access_token, ww_user_id, ww_product_id);
684
+ this.showCameraModalWithCallbacks(ww_access_token, ww_user_id, ww_product_id);
416
685
  }
417
686
  catch (error) {
418
687
  console.error("[WeWear VTO] Try-on request failed:", error);
419
- this.showError("An unexpected error occurred. Please try again.");
420
688
  }
421
689
  }
422
690
  /**
423
- * Shows an error message to the user
424
- * @param message - Error message to display
691
+ * Shows camera modal with appropriate callbacks
425
692
  * @private
426
693
  */
427
- showError(message) {
428
- // Simple alert for now - could be enhanced with a custom modal
429
- alert(`WeWear Virtual Try-On: ${message}`);
694
+ showCameraModalWithCallbacks(ww_access_token, ww_user_id, ww_product_id) {
695
+ const callbacks = {
696
+ onCapture: async (video, canvas) => {
697
+ try {
698
+ // Capture image from video
699
+ const imageBlob = await captureImageFromVideo(video, canvas);
700
+ // Stop camera and show review modal
701
+ stopCamera(video);
702
+ // Show review modal instead of immediately processing
703
+ this.showReviewModalWithCallbacks(imageBlob, ww_access_token, ww_user_id, ww_product_id);
704
+ }
705
+ catch (error) {
706
+ console.error("[WeWear VTO] Image capture error:", error);
707
+ }
708
+ },
709
+ };
710
+ showCameraModal(callbacks);
430
711
  }
431
712
  /**
432
- * Starts the camera stream
433
- * @param video - Video element to display camera stream
434
- * @param loadingIndicator - Loading indicator element
435
- * @param captureButton - Capture button element
713
+ * Shows review modal with appropriate callbacks
714
+ * @private
436
715
  */
437
- async startCamera(video, loadingIndicator, captureButton) {
438
- console.log("[WeWear VTO] Starting camera...");
716
+ showReviewModalWithCallbacks(imageBlob, ww_access_token, ww_user_id, ww_product_id) {
717
+ const callbacks = {
718
+ onRetake: () => {
719
+ // Reopen camera modal
720
+ this.showCameraModalWithCallbacks(ww_access_token, ww_user_id, ww_product_id);
721
+ },
722
+ onAccept: async (acceptedImageBlob) => {
723
+ await this.processAcceptedImage(acceptedImageBlob, ww_access_token, ww_user_id, ww_product_id);
724
+ },
725
+ };
726
+ showReviewModal(imageBlob, callbacks);
727
+ }
728
+ /**
729
+ * Processes the accepted image by calling the API
730
+ * @private
731
+ */
732
+ async processAcceptedImage(imageBlob, ww_access_token, ww_user_id, ww_product_id) {
439
733
  try {
440
- const constraints = {
441
- video: {
442
- width: { ideal: 1280 },
443
- height: { ideal: 720 },
444
- facingMode: "user", // Front-facing camera
445
- },
446
- audio: false,
447
- };
448
- console.log("[WeWear VTO] Requesting camera access...");
449
- const stream = await navigator.mediaDevices.getUserMedia(constraints);
450
- video.srcObject = stream;
451
- video.onloadedmetadata = () => {
452
- console.log("[WeWear VTO] Camera stream loaded successfully");
453
- loadingIndicator.style.display = "none";
454
- captureButton.style.display = "flex";
734
+ console.log("[WeWear VTO] Processing accepted image...");
735
+ // Show loading in the review modal first
736
+ showModalLoading("Processing image...");
737
+ // Store the API parameters for potential refresh
738
+ this.lastApiParams = {
739
+ imageBlob,
740
+ ww_access_token,
741
+ ww_user_id,
742
+ ww_product_id,
455
743
  };
744
+ // Call the API with the accepted image
745
+ const result = await callVirtualTryOnApi(this.config.baseUrl, ww_access_token, ww_user_id, ww_product_id, imageBlob);
746
+ // Remove modal loading and close modal
747
+ removeModalLoading();
748
+ removeElements(`.${CSS_CLASSES.MODAL}`);
749
+ if (result === null || result === void 0 ? void 0 : result.imageUrl) {
750
+ this.replaceProductImage(result.imageUrl);
751
+ }
752
+ else {
753
+ console.error("[WeWear VTO] Invalid API response:", result);
754
+ }
456
755
  }
457
756
  catch (error) {
458
- console.error("[WeWear VTO] Camera access error:", error);
459
- loadingIndicator.innerHTML =
460
- "Camera access denied. Please allow camera permissions.";
757
+ console.error("[WeWear VTO] Error processing accepted image:", error);
758
+ // Remove loading on error
759
+ removeModalLoading();
461
760
  }
462
761
  }
463
762
  /**
464
- * Stops the camera stream
465
- * @param video - Video element with camera stream
763
+ * Recalls the virtual try-on API with the same parameters
764
+ * @private
466
765
  */
467
- stopCamera(video) {
468
- const stream = video.srcObject;
469
- if (stream) {
470
- const tracks = stream.getTracks();
471
- tracks.forEach((track) => {
472
- track.stop();
473
- });
474
- video.srcObject = null;
766
+ async refreshVirtualTryOn() {
767
+ if (!this.lastApiParams) {
768
+ console.warn("[WeWear VTO] No previous API parameters available for refresh");
769
+ return;
475
770
  }
476
- }
477
- /**
478
- * Captures an image from the video stream
479
- * @param video - Video element with camera stream
480
- * @param canvas - Canvas element for capturing
481
- * @param ww_access_token - Access token for API
482
- * @param ww_user_id - User identifier
483
- * @param ww_product_id - Product identifier
484
- * @param modal - Modal element to close after processing
485
- */
486
- async captureImage(video, canvas, ww_access_token, ww_user_id, ww_product_id, modal) {
487
771
  try {
488
- // Set canvas dimensions to match video
489
- canvas.width = video.videoWidth;
490
- canvas.height = video.videoHeight;
491
- // Draw video frame to canvas
492
- const ctx = canvas.getContext("2d");
493
- if (!ctx) {
494
- throw new Error("Could not get canvas context");
772
+ console.log("[WeWear VTO] Refreshing virtual try-on with previous parameters...");
773
+ // Show loading in the product area
774
+ const container = document.querySelector(this.config.gallerySelector);
775
+ if (container instanceof HTMLElement) {
776
+ showProductLoading(container, "Generating new virtual try-on...");
777
+ }
778
+ // Call the API with the stored parameters
779
+ const result = await callVirtualTryOnApi(this.config.baseUrl, this.lastApiParams.ww_access_token, this.lastApiParams.ww_user_id, this.lastApiParams.ww_product_id, this.lastApiParams.imageBlob);
780
+ if (result === null || result === void 0 ? void 0 : result.imageUrl) {
781
+ this.virtualTryOnImageUrl = result.imageUrl;
782
+ // Find the gallery container and update the image
783
+ const container = document.querySelector(this.config.gallerySelector);
784
+ if (container instanceof HTMLElement) {
785
+ removeProductLoading(container);
786
+ this.showVirtualTryOnImage(container);
787
+ this.updateButtonContainer(container);
788
+ }
789
+ }
790
+ else {
791
+ console.error("[WeWear VTO] Invalid API response on refresh:", result);
792
+ // Remove loading on error
793
+ const container = document.querySelector(this.config.gallerySelector);
794
+ if (container instanceof HTMLElement) {
795
+ removeProductLoading(container);
796
+ }
495
797
  }
496
- ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
497
- // Convert canvas to blob
498
- const blob = await new Promise((resolve, reject) => {
499
- canvas.toBlob((blob) => {
500
- if (blob) {
501
- resolve(blob);
502
- }
503
- else {
504
- reject(new Error("Failed to create blob from canvas"));
505
- }
506
- }, "image/jpeg", 0.8);
507
- });
508
- // Stop camera and close camera modal
509
- this.stopCamera(video);
510
- modal.remove();
511
- // Show review modal instead of immediately processing
512
- this.showReviewModal(blob, ww_access_token, ww_user_id, ww_product_id);
513
798
  }
514
799
  catch (error) {
515
- console.error("[WeWear VTO] Image capture error:", error);
516
- this.showError("Failed to capture image. Please try again.");
800
+ console.error("[WeWear VTO] Error refreshing virtual try-on:", error);
801
+ // Remove loading on error
802
+ const container = document.querySelector(this.config.gallerySelector);
803
+ if (container instanceof HTMLElement) {
804
+ removeProductLoading(container);
805
+ }
517
806
  }
518
807
  }
519
808
  /**
520
- * Shows the review modal for captured image
521
- * @param imageBlob - Captured image blob
522
- * @param ww_access_token - Access token for API
523
- * @param ww_user_id - User identifier
524
- * @param ww_product_id - Product identifier
525
- */
526
- showReviewModal(imageBlob, ww_access_token, ww_user_id, ww_product_id) {
527
- console.log("[WeWear VTO] Opening review modal...");
528
- // Remove any existing modals first
529
- const existingModals = document.querySelectorAll(`.${CSS_CLASSES.MODAL}`);
530
- existingModals.forEach((modal) => {
531
- modal.remove();
532
- });
533
- // Create image URL for preview
534
- const imageUrl = URL.createObjectURL(imageBlob);
535
- // Create modal container (same as camera modal)
536
- const modal = document.createElement("div");
537
- modal.className = CSS_CLASSES.MODAL;
538
- modal.style.cssText = `
539
- position: fixed;
540
- top: 0;
541
- left: 0;
542
- width: 100%;
543
- height: 100%;
544
- background-color: rgba(0, 0, 0, 0.95);
545
- display: flex;
546
- flex-direction: column;
547
- align-items: center;
548
- justify-content: center;
549
- z-index: ${Z_INDEX.MODAL};
550
- padding: 20px;
551
- box-sizing: border-box;
552
- `;
553
- // Create review container (similar to camera container)
554
- const reviewContainer = document.createElement("div");
555
- reviewContainer.style.cssText = `
556
- position: relative;
557
- width: 100%;
558
- max-width: 500px;
559
- height: 70vh;
560
- background-color: #000;
561
- border-radius: 12px;
562
- overflow: hidden;
563
- display: flex;
564
- flex-direction: column;
565
- align-items: center;
566
- justify-content: center;
567
- `;
568
- // Create image element (replaces video element)
569
- const image = document.createElement("img");
570
- image.src = imageUrl;
571
- image.alt = "Review your photo";
572
- image.style.cssText = `
573
- width: 100%;
574
- height: 100%;
575
- object-fit: cover;
576
- border-radius: 12px;
577
- `;
578
- // Create close button (same as camera modal)
579
- const closeButton = document.createElement("button");
580
- closeButton.innerHTML = "×";
581
- closeButton.style.cssText = `
582
- position: absolute;
583
- top: 15px;
584
- right: 15px;
585
- width: 40px;
586
- height: 40px;
587
- border: none;
588
- background-color: rgba(0, 0, 0, 0.7);
589
- color: white;
590
- font-size: 24px;
591
- font-weight: bold;
592
- cursor: pointer;
593
- border-radius: 50%;
594
- display: flex;
595
- align-items: center;
596
- justify-content: center;
597
- `;
598
- // Create button container positioned at bottom (similar to capture button position)
599
- const buttonContainer = document.createElement("div");
600
- buttonContainer.style.cssText = `
601
- position: absolute;
602
- bottom: 20px;
603
- left: 50%;
604
- transform: translateX(-50%);
605
- display: flex;
606
- gap: 15px;
607
- width: calc(100% - 40px);
608
- max-width: 300px;
609
- `;
610
- // Create retake button
611
- const retakeButton = document.createElement("button");
612
- retakeButton.textContent = "Retake";
613
- retakeButton.style.cssText = `
614
- flex: 1;
615
- padding: 12px 24px;
616
- background-color: transparent;
617
- color: white;
618
- border: 2px solid white;
619
- border-radius: 8px;
620
- font-size: 16px;
621
- font-weight: 600;
622
- cursor: pointer;
623
- transition: all 0.2s ease;
624
- `;
625
- // Create use photo button
626
- const usePhotoButton = document.createElement("button");
627
- usePhotoButton.textContent = "Use Photo";
628
- usePhotoButton.style.cssText = `
629
- flex: 1;
630
- padding: 12px 24px;
631
- background-color: white;
632
- color: black;
633
- border: 2px solid white;
634
- border-radius: 8px;
635
- font-size: 16px;
636
- font-weight: 600;
637
- cursor: pointer;
638
- transition: all 0.2s ease;
639
- `;
640
- // Add hover effects
641
- retakeButton.addEventListener("mouseenter", () => {
642
- retakeButton.style.backgroundColor = "white";
643
- retakeButton.style.color = "black";
644
- });
645
- retakeButton.addEventListener("mouseleave", () => {
646
- retakeButton.style.backgroundColor = "transparent";
647
- retakeButton.style.color = "white";
648
- });
649
- usePhotoButton.addEventListener("mouseenter", () => {
650
- usePhotoButton.style.backgroundColor = "rgba(255, 255, 255, 0.9)";
651
- });
652
- usePhotoButton.addEventListener("mouseleave", () => {
653
- usePhotoButton.style.backgroundColor = "white";
654
- });
655
- // Add event listeners
656
- closeButton.onclick = () => {
657
- URL.revokeObjectURL(imageUrl); // Clean up
658
- modal.remove();
659
- };
660
- retakeButton.onclick = () => {
661
- URL.revokeObjectURL(imageUrl); // Clean up
662
- modal.remove();
663
- // Reopen camera modal
664
- this.showCameraModal(ww_access_token, ww_user_id, ww_product_id);
665
- };
666
- usePhotoButton.onclick = async () => {
667
- URL.revokeObjectURL(imageUrl); // Clean up
668
- modal.remove();
669
- // Process the image
670
- await this.processAcceptedImage(imageBlob, ww_access_token, ww_user_id, ww_product_id);
671
- };
672
- // Assemble the review modal (similar to camera modal)
673
- buttonContainer.appendChild(retakeButton);
674
- buttonContainer.appendChild(usePhotoButton);
675
- reviewContainer.appendChild(image);
676
- reviewContainer.appendChild(closeButton);
677
- reviewContainer.appendChild(buttonContainer);
678
- modal.appendChild(reviewContainer);
679
- document.body.appendChild(modal);
680
- console.log("[WeWear VTO] Review modal added to DOM");
681
- }
682
- /**
683
- * Processes the accepted image by calling the API
684
- * @param imageBlob - Accepted image blob
685
- * @param ww_access_token - Access token for API
686
- * @param ww_user_id - User identifier
687
- * @param ww_product_id - Product identifier
809
+ * Replaces the product image in the gallery with the virtual try-on result
810
+ * @private
688
811
  */
689
- async processAcceptedImage(imageBlob, ww_access_token, ww_user_id, ww_product_id) {
812
+ replaceProductImage(imageUrl) {
690
813
  try {
691
- console.log("[WeWear VTO] Processing accepted image...");
692
- // Call the API with the accepted image
693
- const result = await this.callVirtualTryOnApiWithImage(ww_access_token, ww_user_id, ww_product_id, imageBlob);
694
- if (result === null || result === void 0 ? void 0 : result.imageUrl) {
695
- this.showImageModal(result.imageUrl);
814
+ // Store the virtual try-on image URL
815
+ this.virtualTryOnImageUrl = imageUrl;
816
+ // Find the gallery container
817
+ const container = document.querySelector(this.config.gallerySelector);
818
+ if (!container || !(container instanceof HTMLElement)) {
819
+ console.warn("[WeWear VTO] Gallery container not found for image replacement:", this.config.gallerySelector);
820
+ return;
696
821
  }
697
- else {
698
- console.error("[WeWear VTO] Invalid API response:", result);
822
+ // Store the original content if not already stored
823
+ if (!container.hasAttribute("data-ww-original-content")) {
824
+ container.setAttribute("data-ww-original-content", container.innerHTML);
699
825
  }
826
+ // Show the virtual try-on image initially
827
+ this.showVirtualTryOnImage(container);
828
+ // Replace the button container with the new multi-button version
829
+ this.updateButtonContainer(container);
830
+ console.log("[WeWear VTO] Product image replaced with virtual try-on result");
700
831
  }
701
832
  catch (error) {
702
- console.error("[WeWear VTO] Error processing accepted image:", error);
703
- this.showError("Failed to process image. Please try again.");
833
+ console.error("[WeWear VTO] Error replacing product image:", error);
704
834
  }
705
835
  }
706
836
  /**
707
- * Makes API call to virtual try-on service with captured image
708
- * @param ww_access_token - Optional authentication token
709
- * @param ww_user_id - User identifier
710
- * @param ww_product_id - Product identifier
711
- * @param imageBlob - Captured image blob
712
- * @returns Promise with virtual try-on result or null if failed
837
+ * Updates the button container to show all available buttons
838
+ * @private
713
839
  */
714
- async callVirtualTryOnApiWithImage(ww_access_token, ww_user_id, ww_product_id, imageBlob) {
715
- try {
716
- // Create form data for multipart upload
717
- const formData = new FormData();
718
- formData.append("ww_user_id", ww_user_id);
719
- formData.append("ww_product_id", ww_product_id);
720
- formData.append("image", imageBlob, "captured-image.jpg");
721
- if (ww_access_token) {
722
- formData.append("ww_access_token", ww_access_token);
840
+ updateButtonContainer(container) {
841
+ // Remove existing button containers
842
+ const existingButtons = container.querySelectorAll(`.${CSS_CLASSES.BUTTON_CONTAINER}`);
843
+ existingButtons.forEach((btn) => {
844
+ btn.remove();
845
+ });
846
+ // Create new button container with all buttons
847
+ const buttonContainer = createButtonContainer(this.config.buttonPosition, this.virtualTryOnImageUrl !== null, async () => {
848
+ await this.handleTryOnClick();
849
+ }, async () => {
850
+ await this.refreshVirtualTryOn();
851
+ }, () => {
852
+ if (this.isShowingVirtualTryOn) {
853
+ this.showOriginalImage(container);
723
854
  }
724
- const response = await fetch(`${this.config.baseUrl}/api/virtual-try-on`, {
725
- method: "POST",
726
- body: formData,
727
- });
728
- if (!response.ok) {
729
- console.error("[WeWear VTO] API request failed:", response.status, response.statusText);
730
- return null;
855
+ else {
856
+ this.showVirtualTryOnImage(container);
731
857
  }
732
- const result = await response.json();
733
- console.log("[WeWear VTO] API response:", result);
734
- return result;
858
+ this.updateButtonContainer(container);
859
+ }, this.isShowingVirtualTryOn);
860
+ container.appendChild(buttonContainer);
861
+ }
862
+ /**
863
+ * Shows the virtual try-on image in the container
864
+ * @private
865
+ */
866
+ showVirtualTryOnImage(container) {
867
+ if (!this.virtualTryOnImageUrl) {
868
+ console.warn("[WeWear VTO] No virtual try-on image URL available");
869
+ return;
735
870
  }
736
- catch (error) {
737
- console.error("[WeWear VTO] API call failed:", error);
738
- return null;
871
+ // Clear existing content except buttons
872
+ const existingButtons = container.querySelectorAll(`.${CSS_CLASSES.BUTTON_CONTAINER}`);
873
+ container.innerHTML = "";
874
+ const image = document.createElement("img");
875
+ image.src = this.virtualTryOnImageUrl;
876
+ image.alt = "Virtual Try-On Result";
877
+ image.style.cssText = `
878
+ width: 100%;
879
+ height: 100%;
880
+ object-fit: cover;
881
+ border-radius: 8px;
882
+ `;
883
+ container.appendChild(image);
884
+ // Re-add buttons
885
+ existingButtons.forEach((btn) => {
886
+ container.appendChild(btn);
887
+ });
888
+ this.isShowingVirtualTryOn = true;
889
+ }
890
+ /**
891
+ * Shows the original product image in the container
892
+ * @private
893
+ */
894
+ showOriginalImage(container) {
895
+ const originalContent = container.getAttribute("data-ww-original-content");
896
+ if (originalContent) {
897
+ // Store existing buttons
898
+ const existingButtons = container.querySelectorAll(`.${CSS_CLASSES.BUTTON_CONTAINER}`);
899
+ // Restore original content
900
+ container.innerHTML = originalContent;
901
+ // Re-add buttons
902
+ existingButtons.forEach((btn) => {
903
+ container.appendChild(btn);
904
+ });
739
905
  }
906
+ this.isShowingVirtualTryOn = false;
740
907
  }
741
908
  /**
742
909
  * Destroys the widget and cleans up resources
@@ -744,15 +911,13 @@ class VirtualTryOnWidget {
744
911
  destroy() {
745
912
  try {
746
913
  // Remove all buttons
747
- const buttons = document.querySelectorAll(`.${CSS_CLASSES.BUTTON_CONTAINER}`);
748
- buttons.forEach((button) => {
749
- button.remove();
750
- });
914
+ removeElements(`.${CSS_CLASSES.BUTTON_CONTAINER}`);
751
915
  // Remove all modals
752
- const modals = document.querySelectorAll(`.${CSS_CLASSES.MODAL}`);
753
- modals.forEach((modal) => {
754
- modal.remove();
755
- });
916
+ removeElements(`.${CSS_CLASSES.MODAL}`);
917
+ // Reset state
918
+ this.virtualTryOnImageUrl = null;
919
+ this.isShowingVirtualTryOn = false;
920
+ this.lastApiParams = null;
756
921
  console.log("[WeWear VTO] Widget destroyed successfully");
757
922
  }
758
923
  catch (error) {
@@ -761,17 +926,7 @@ class VirtualTryOnWidget {
761
926
  }
762
927
  }
763
928
 
764
- /**
765
- * WeWear Virtual Try-On Widget Auto-Installer
766
- *
767
- * Provides automatic initialization and management of the virtual try-on widget.
768
- * Handles DOM ready states and widget lifecycle management.
769
- */
770
929
  let widgetInstance = null;
771
- /**
772
- * Initializes the virtual try-on widget with optional configuration
773
- * @param config - Widget configuration options
774
- */
775
930
  function initVirtualTryOn(config) {
776
931
  try {
777
932
  // Clean up any existing instance
@@ -799,9 +954,6 @@ function initVirtualTryOn(config) {
799
954
  console.error("[WeWear VTO] Initialization error:", error);
800
955
  }
801
956
  }
802
- /**
803
- * Destroys the current widget instance and cleans up resources
804
- */
805
957
  function destroyVirtualTryOn() {
806
958
  try {
807
959
  if (widgetInstance) {
@@ -814,10 +966,12 @@ function destroyVirtualTryOn() {
814
966
  console.error("[WeWear VTO] Error destroying widget:", error);
815
967
  }
816
968
  }
817
- // Auto-initialize if window object exists (browser environment)
969
+ function getWidgetInstance() {
970
+ return widgetInstance;
971
+ }
818
972
  if (typeof window !== "undefined") {
819
973
  initVirtualTryOn();
820
974
  }
821
975
 
822
- export { VirtualTryOnWidget, destroyVirtualTryOn, initVirtualTryOn };
976
+ export { VirtualTryOnWidget, destroyVirtualTryOn, getWidgetInstance, initVirtualTryOn };
823
977
  //# sourceMappingURL=index.esm.js.map