-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfoxy-wix.js
More file actions
372 lines (337 loc) · 13.4 KB
/
foxy-wix.js
File metadata and controls
372 lines (337 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('sidecart-detach', function () {
// Reset variants
document
.querySelectorAll("[data-hook='dropdown-base-text']")
.forEach((el) => (el.innerText = 'Select'));
});
FC.client.on('ready.done', function () {
foxyAddToCart();
let previousUrl = window.location.pathname;
const urlObserver = new MutationObserver(function () {
if (window.location.pathname !== previousUrl) {
previousUrl = window.location.pathname;
foxyAddToCart();
}
});
urlObserver.observe(document, { subtree: true, childList: true });
function foxyAddToCart() {
const buttonObserver = new MutationObserver(function (mutationsList) {
if (mutationsList.some((mutation) => mutation.type === 'childList')) {
// mini cart
const minicartBtn = document.querySelector(
"[data-hook='cart-icon-button']"
);
if (minicartBtn && !minicartBtn.hasAttribute('foxy-id')) {
minicartBtn.setAttribute('foxy-id', 'mini-cart-btn');
minicartBtn.addEventListener('click', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
FC.client.event('sidecart-show').trigger();
});
}
const minicartQty = document.querySelector(
'[data-hook="items-count"]'
);
if (minicartQty && !minicartQty.hasAttribute('data-fc-id')) {
minicartQty.setAttribute('data-fc-id', 'minicart-quantity');
FC.client.updateMiniCart();
}
const minicartLink = document.querySelector(
`a[href="https://${FC.settings.storedomain}/cart?cart=view"]`
);
if (minicartLink && !minicartLink.hasAttribute('foxy-id')) {
minicartLink.setAttribute('foxy-id', 'mini-cart-link');
minicartLink.addEventListener('click', (e) => {
e.preventDefault();
e.stopImmediatePropagation();
FC.client.event('sidecart-show').trigger();
});
}
// add-to-cart button
const wixAddBtn =
document.querySelector("[data-hook='add-to-cart']") ||
document.querySelector('[aria-label="Add to Cart"]') ||
document.querySelector('[data-hook="subscribe-button"]');
if (!!wixAddBtn && !wixAddBtn.hasAttribute('foxy-id')) {
wixAddBtn.setAttribute('foxy-id', 'add-to-cart');
wixAddBtn.addEventListener('click', (e) => handleAddToCart(e));
}
// Wix Bookings
const wixBookingContainer = document.querySelector(
'[data-hook="BookingCalendar-wrapper"]'
);
if (
wixBookingContainer &&
!wixBookingContainer.hasAttribute('foxy-id')
) {
const wixBookingBtn = document.querySelector(
'[data-hook="sidebar-cta"]'
);
if (wixBookingBtn && !wixBookingBtn.hasAttribute('foxy-id')) {
wixBookingContainer.setAttribute('foxy-id', 'booking-container');
wixBookingBtn.setAttribute('foxy-id', 'booking-btn');
document
.querySelector('[data-hook="service-details"] button')
.click();
setTimeout(() => {
document.querySelector(
'[data-hook="service-details"] button'
).style = 'display: none';
}, 0);
wixBookingBtn.addEventListener('click', (e) => {
e.stopPropagation();
const name = document.querySelector(
'[data-hook="slot-name"]'
)?.textContent;
const price = document.querySelector(
'[data-hook="slot-plan-type"]'
)?.textContent;
const startDate = document.querySelector(
'[data-hook="slot-date-and-time"]'
)?.textContent;
const location = document.querySelector(
'[data-hook="time-slot-details-location"]'
)?.textContent;
const duration = document.querySelector(
'[data-hook="time-slot-details-duration-aria-label"], [data-hook="time-slot-details-duration"]'
)?.textContent;
const slug = window.location.pathname.split('/').slice(-1)[0];
const staff = document.querySelector(
'[data-hook="dropdown-staffMember"]'
)
? document.querySelector(
'[data-hook="dropdown-staffMember"] [data-hook="dropdown-base-text"]'
)?.textContent
: document.querySelector(
'[data-hook="time-slot-details-staffMember"]'
)?.textContent;
const preferenceEls = Array.from(
document.querySelectorAll(
'[data-hook="slot-preferences-wrapper"] [data-hook="dropdown-custom"]'
)
);
const preferences = preferenceEls.map((el) => {
const name = el
.querySelector('[data-hook="dropdown-label"]')
.textContent.replace('*', '')
.trim();
const value = el.querySelector(
'[data-hook="dropdown-base-text"]'
).textContent;
if (!name || !value) {
return;
}
return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;
});
if (
preferenceEls.length > 0 &&
!preferences.some((preference) => Boolean(preference))
) {
alert('Please select an option for each preference');
return;
}
if (
name &&
price &&
startDate &&
location &&
staff &&
duration &&
slug
) {
window.location.href =
`https://${
FC.settings.storedomain
}/cart?name=${encodeURIComponent(
name
)}&price=${price}&Start_Date=${encodeURIComponent(
startDate
)}&Location=${encodeURIComponent(
location
)}&Staff=${encodeURIComponent(
staff
)}&Duration=${encodeURIComponent(
duration
)}&Slug=${slug}&quantity=1&quantity_max=1&url=${encodeURIComponent(
window.location.href
)}&empty=true&cart=checkout` +
(preferenceEls.length > 0
? `&${preferences.join('&')}`
: '');
} else {
console.error('Foxy: Some booking info is missing');
}
});
}
}
}
});
buttonObserver.observe(document.body, {
childList: true,
subtree: true,
});
}
function handleAddToCart(e) {
e.stopPropagation();
const name =
document.querySelector("[data-hook='product-title']")?.innerText ||
document.querySelector('[aria-label="foxy-product-name"]')?.innerText;
if (!name) {
console.error('Foxy: cannot find product name');
return;
}
let price = document
.querySelector("[data-hook='formatted-primary-price']")
?.innerText.replace(/[^\d,.]/g, '');
if (price.charAt(price.length - 3) === ',') {
price = price.replace(/[.]/g, '').replace(/[,]/g, '.');
}
if (!price) {
console.error('Foxy: cannot find product price');
return;
}
const slug = window.location.pathname.split('/').slice(-1)[0];
const quantity =
document.querySelector(
'[data-hook="number-input-spinner-input"], [data-hook="product-quantity-container"] input'
)?.value || 1;
const quantity_max =
document.querySelector(
'[data-hook="number-input-spinner-input"], [data-hook="product-quantity-container"] input'
)?.max || 0;
const code =
document.querySelector("[data-hook='sku']")?.innerText.split(': ')[1] ||
'';
const image =
document.querySelector('[data-hook="main-media-image-wrapper"] img')
?.src ||
document.querySelector("[data-hook='product-image']")?.src ||
document
.querySelector('[data-hook="responsive-gallery-media"]')
?.style.backgroundImage.slice(4, -1)
.replace(/"/g, '') ||
'';
const productParams = Array.from(
document.querySelectorAll(
'[data-hook="info-section-description"] li, [data-hook="description-wrapper"] li'
)
).map((el) => el.textContent.trim());
const category =
productParams
.find((param) => param.toLowerCase().startsWith('category'))
?.split(':')[1]
?.trim() || '';
const weight =
productParams
.find((param) => param.toLowerCase().startsWith('weight'))
?.match(/[\d.]+/)[0] ||
Array.from(
document.querySelectorAll('[data-hook="info-section-title"]')
)
.map((el) => el.textContent.trim())
.find((el) => el.toLowerCase().startsWith('weight'))
?.match(/[\d.]+/)[0] ||
document.querySelector('[data-foxy-product="weight"]')?.textContent ||
'';
// Subscriptions
const subContainer = document.querySelector(
'[data-hook="subscription-plans-container"]'
);
const subOption = subContainer?.querySelector(
'[data-checked="true"] input'
);
if (subContainer && !subOption) {
return;
}
let subFrequency;
let subEndDate;
if (subOption && subOption.ariaLabel !== 'One-time purchase') {
const subDetails = subOption
.closest('[data-hook="plan-item"]')
.querySelector('[data-hook="plan-details"]').innerText;
const match = subDetails.match(/every (\d*)\s*(\w+)/);
const frequency = match[1] ? parseInt(match[1]) : 1;
const unit = match[2][0];
subFrequency = `${frequency}${unit}`;
if (!subDetails.endsWith('until canceled')) {
const endsIn = subDetails.split('for ')[1].match(/\b\d+\b/)[0];
subEndDate = `${endsIn}${unit}`;
}
}
const atcLink =
`https://${FC.settings.storedomain}/cart?name=${encodeURIComponent(
name
)}&price=${price}&quantity=${quantity}&quantity_max=${quantity_max}&image=${encodeURIComponent(
image
)}&code=${encodeURIComponent(
code
)}&Slug=${slug}&url=${encodeURIComponent(window.location.href)}` +
(category ? `&category=${encodeURIComponent(category)}` : '') +
(weight ? `&weight=${weight}` : '') +
(subFrequency ? `&sub_frequency=${subFrequency}` : '') +
(subEndDate ? `&sub_enddate=${subEndDate}` : '');
// Dropdown options
const allVariantValues =
document.querySelectorAll("[data-hook='dropdown-base-text']").length !==
0
? Array.from(
document.querySelectorAll("[data-hook='dropdown-base-text']")
).map((div) => encodeURIComponent(div.innerText))
: Array.from(
document.querySelectorAll("[data-hook='native-select']")
).map((select) =>
encodeURIComponent(select.options[select.selectedIndex].text)
);
const allVariantName = Array.from(
document.querySelectorAll(
"[data-hook='options-dropdown-title'], [data-hook='dropdown-label']"
)
).map((div) => encodeURIComponent(div.innerText.replace(/\*$/, '')));
// Color option
const colorOption = document
.querySelector(
'[data-hook="product-colors-title"], [data-hook="color-picker-fieldset-label"]'
)
?.innerText.split(': ')
.map((el) => encodeURIComponent(el));
if (allVariantValues.length > 0 && !allVariantValues.includes('Select')) {
// if there are variants and all options are selected
let variantParams = '';
// add color option if exists
if (!!colorOption) {
if (colorOption.length === 2) {
variantParams += `&${colorOption[0]}=${colorOption[1].replace(
'*',
''
)}`;
} else {
return;
}
}
allVariantName.forEach(
(name, index) =>
(variantParams += `&${name}=${allVariantValues[index]}`)
);
FC.client.event('cart-submit').trigger({
data: { cart: 'add' },
url: atcLink + variantParams,
});
} else if (allVariantValues.length === 0 && colorOption?.length === 2) {
// only color options
FC.client.event('cart-submit').trigger({
data: { cart: 'add' },
url:
atcLink + `&${colorOption[0]}=${colorOption[1].replace('*', '')}`,
});
} else if (allVariantValues.length === 0 && !colorOption) {
// if there are no variants or color options
FC.client.event('cart-submit').trigger({
data: { cart: 'add' },
url: atcLink,
});
}
}
});
};