@jay-framework/wix-cart 0.22.2 → 0.24.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.
@@ -1,659 +0,0 @@
1
- import { createJayContext, useGlobalContext } from "@jay-framework/runtime";
2
- import { registerReactiveGlobalContext, createSignal, useReactive, createEvent } from "@jay-framework/component";
3
- import { wixFetch, WIX_CLIENT_CONTEXT } from "@jay-framework/wix-server-client/client";
4
- import { makeJayStackComponent, makeJayInit } from "@jay-framework/fullstack-component";
5
- import { patch, REPLACE } from "@jay-framework/json-patch";
6
- async function getCurrentCart(client) {
7
- return wixFetch(client, "/ecom/v1/carts/current", { method: "GET" });
8
- }
9
- async function addToCurrentCart(client, lineItems) {
10
- return wixFetch(client, "/ecom/v1/carts/current/add-to-cart", {
11
- method: "POST",
12
- body: { lineItems }
13
- });
14
- }
15
- async function removeLineItemsFromCurrentCart(client, lineItemIds) {
16
- return wixFetch(client, "/ecom/v1/carts/current/remove-line-items", {
17
- method: "POST",
18
- body: { lineItemIds }
19
- });
20
- }
21
- async function updateCurrentCartLineItemQuantity(client, lineItems) {
22
- return wixFetch(client, "/ecom/v1/carts/current/update-line-items-quantity", {
23
- method: "POST",
24
- body: {
25
- lineItems: lineItems.map((item) => ({
26
- id: item._id,
27
- quantity: item.quantity
28
- }))
29
- }
30
- });
31
- }
32
- async function updateCurrentCart(client, cartInfo) {
33
- return wixFetch(client, "/ecom/v1/carts/current", {
34
- method: "PATCH",
35
- body: { cartInfo }
36
- });
37
- }
38
- async function removeCouponFromCurrentCart(client) {
39
- return wixFetch(client, "/ecom/v1/carts/current/remove-coupon", {
40
- method: "POST",
41
- body: {}
42
- });
43
- }
44
- async function estimateCurrentCartTotals(client) {
45
- return wixFetch(client, "/ecom/v1/carts/current/estimate-totals", {
46
- method: "POST",
47
- body: {}
48
- });
49
- }
50
- async function createCheckoutFromCurrentCart(client) {
51
- return wixFetch(client, "/ecom/v1/carts/current/create-checkout", {
52
- method: "POST",
53
- body: {}
54
- });
55
- }
56
- async function createRedirectSession(client, options) {
57
- return wixFetch(client, "/redirects-api/v1/redirect-session", {
58
- method: "POST",
59
- body: options
60
- });
61
- }
62
- function stripWixMediaResize(url) {
63
- return url.replace(/\/v1\/(?:fit|fill|crop)\/[^/]+\/file\.\w+$/, "");
64
- }
65
- function parseWixMediaUrl(url) {
66
- if (!url) return null;
67
- const match = url.match(
68
- /^wix:(image|video|document|audio):\/\/v1\/([^/]+)\/([^#]+)(?:#(.*))?$/
69
- );
70
- if (!match) return null;
71
- const [, type, mediaId, fileName, hashParams] = match;
72
- const result = {
73
- type,
74
- mediaId,
75
- fileName: decodeURIComponent(fileName)
76
- };
77
- if (hashParams) {
78
- const params = new URLSearchParams(hashParams);
79
- const originWidth = params.get("originWidth");
80
- const originHeight = params.get("originHeight");
81
- if (originWidth) result.originWidth = parseInt(originWidth, 10);
82
- if (originHeight) result.originHeight = parseInt(originHeight, 10);
83
- const posterUri = params.get("posterUri");
84
- const posterWidth = params.get("posterWidth");
85
- const posterHeight = params.get("posterHeight");
86
- if (posterUri) result.posterUri = decodeURIComponent(posterUri);
87
- if (posterWidth) result.posterWidth = parseInt(posterWidth, 10);
88
- if (posterHeight) result.posterHeight = parseInt(posterHeight, 10);
89
- }
90
- return result;
91
- }
92
- function formatWixMediaUrl(_id, url, resize) {
93
- const resizeFragment = "";
94
- if (url == null ? void 0 : url.startsWith("wix:")) {
95
- const parsed = parseWixMediaUrl(url);
96
- if (parsed) {
97
- return `https://static.wixstatic.com/media/${parsed.mediaId}${resizeFragment}`;
98
- }
99
- }
100
- if ((url == null ? void 0 : url.startsWith("http://")) || (url == null ? void 0 : url.startsWith("https://"))) {
101
- return stripWixMediaResize(url) + resizeFragment;
102
- }
103
- if (_id) {
104
- return `https://static.wixstatic.com/media/${_id}${resizeFragment}`;
105
- }
106
- return "";
107
- }
108
- function mapLineItem(item) {
109
- const catalogRef = item.catalogReference;
110
- const physicalProperties = item.physicalProperties;
111
- const priceData = item.price;
112
- const descriptionLines = item.descriptionLines || [];
113
- const variantParts = descriptionLines.filter((line) => line.name?.translated).map(
114
- (line) => `${line.name?.translated}: ${line.colorInfo?.translated || line.plainText?.translated || ""}`
115
- );
116
- const rawUrl = item.url;
117
- const urlString = typeof rawUrl === "string" ? rawUrl : rawUrl?.relativePath || rawUrl?.url || "";
118
- const slug = urlString.split("/").pop() || "";
119
- const rawImage = item.image;
120
- const imageUrl = typeof rawImage === "string" ? rawImage : rawImage?.url || "";
121
- const imageId = typeof rawImage === "string" ? "" : rawImage?.id || "";
122
- return {
123
- lineItemId: item._id || item.id || "",
124
- productId: catalogRef?.catalogItemId || "",
125
- productName: item.productName?.translated || item.productName?.original || "",
126
- productUrl: slug ? `/products/${slug}` : "",
127
- variantName: variantParts.join(" / "),
128
- sku: physicalProperties?.sku || "",
129
- image: {
130
- url: formatWixMediaUrl(imageId, imageUrl),
131
- altText: item.productName?.translated || ""
132
- },
133
- quantity: item.quantity || 1,
134
- unitPrice: {
135
- amount: priceData?.amount || "0",
136
- formattedAmount: priceData?.formattedAmount || ""
137
- },
138
- lineTotal: {
139
- amount: item.lineItemPrice?.amount || "0",
140
- formattedAmount: item.lineItemPrice?.formattedAmount || ""
141
- },
142
- lineDiscount: {
143
- amount: "0",
144
- formattedAmount: ""
145
- },
146
- hasDiscount: false
147
- };
148
- }
149
- function calculateTotalDiscount(appliedDiscounts) {
150
- if (!appliedDiscounts) return 0;
151
- return appliedDiscounts.reduce(
152
- (sum, d) => sum + parseFloat(d.merchantDiscount?.amount?.amount || "0"),
153
- 0
154
- );
155
- }
156
- function calculateItemCount(lineItems) {
157
- if (!lineItems) return 0;
158
- return lineItems.reduce((sum, item) => sum + (item.quantity || 0), 0);
159
- }
160
- function getEmptySummary() {
161
- return {
162
- itemCount: 0,
163
- subtotal: { amount: "0", formattedAmount: "$0.00" },
164
- discount: { amount: "0", formattedAmount: "" },
165
- hasDiscount: false,
166
- estimatedTax: { amount: "0", formattedAmount: "" },
167
- showTax: false,
168
- estimatedTotal: { amount: "0", formattedAmount: "$0.00" },
169
- currency: "USD"
170
- };
171
- }
172
- function mapCartSummary(cart) {
173
- if (!cart) {
174
- return getEmptySummary();
175
- }
176
- const totalDiscount = calculateTotalDiscount(cart.appliedDiscounts);
177
- const itemCount = calculateItemCount(cart.lineItems);
178
- return {
179
- itemCount,
180
- subtotal: {
181
- amount: "0",
182
- formattedAmount: "$0.00"
183
- },
184
- discount: {
185
- amount: totalDiscount.toString(),
186
- formattedAmount: totalDiscount > 0 ? `-$${totalDiscount.toFixed(2)}` : ""
187
- },
188
- hasDiscount: totalDiscount > 0,
189
- estimatedTax: {
190
- amount: "0",
191
- formattedAmount: ""
192
- },
193
- showTax: false,
194
- estimatedTotal: {
195
- amount: "0",
196
- formattedAmount: "$0.00"
197
- },
198
- currency: cart.currency || "USD"
199
- };
200
- }
201
- function mapCartToState(cart) {
202
- if (!cart) {
203
- return getEmptyCartState();
204
- }
205
- const lineItems = (cart.lineItems || []).map(mapLineItem);
206
- const appliedCoupon = cart.appliedDiscounts?.find((d) => d.coupon?.code)?.coupon?.code || "";
207
- return {
208
- cartId: cart._id || cart.id || "",
209
- isEmpty: lineItems.length === 0,
210
- lineItems,
211
- summary: mapCartSummary(cart),
212
- appliedCoupon,
213
- hasAppliedCoupon: !!appliedCoupon
214
- };
215
- }
216
- function getEmptyCartState() {
217
- return {
218
- cartId: "",
219
- isEmpty: true,
220
- lineItems: [],
221
- summary: getEmptySummary(),
222
- appliedCoupon: "",
223
- hasAppliedCoupon: false
224
- };
225
- }
226
- function mapCartToIndicator(cart) {
227
- if (!cart || !cart.lineItems?.length) {
228
- return {
229
- itemCount: 0,
230
- hasItems: false
231
- };
232
- }
233
- const itemCount = calculateItemCount(cart.lineItems);
234
- return {
235
- itemCount,
236
- hasItems: itemCount > 0
237
- };
238
- }
239
- function isCartNotFoundError(error) {
240
- const err = error;
241
- if (err?.response?.status === 404) return true;
242
- if (err?.status === 404) return true;
243
- if (err?.code === 404) return true;
244
- const message = err?.message?.toLowerCase() || "";
245
- if (message.includes("not found") && message.includes("cart")) return true;
246
- return false;
247
- }
248
- async function getCurrentCartOrNull(wixClient) {
249
- try {
250
- const response = await getCurrentCart(wixClient);
251
- return response.cart ?? null;
252
- } catch (error) {
253
- if (isCartNotFoundError(error)) {
254
- return null;
255
- }
256
- throw error;
257
- }
258
- }
259
- async function estimateCurrentCartTotalsOrNull(wixClient) {
260
- try {
261
- const response = await estimateCurrentCartTotals(wixClient);
262
- return response ?? null;
263
- } catch (error) {
264
- if (isCartNotFoundError(error)) {
265
- return null;
266
- }
267
- throw error;
268
- }
269
- }
270
- function mapEstimateTotalsToState(estimate) {
271
- if (!estimate?.cart) {
272
- return getEmptyCartState();
273
- }
274
- const cart = estimate.cart;
275
- const lineItems = (cart.lineItems || []).map(mapLineItem);
276
- const appliedCoupon = cart.appliedDiscounts?.find((d) => d.coupon?.code)?.coupon?.code || "";
277
- const itemCount = lineItems.reduce((sum, item) => sum + item.quantity, 0);
278
- const priceSummary = estimate.priceSummary;
279
- const taxSummary = estimate.taxSummary;
280
- const discountAmount = parseFloat(priceSummary?.discount?.amount || "0");
281
- const hasTax = parseFloat(taxSummary?.totalTax?.amount || "0") > 0;
282
- return {
283
- cartId: cart._id || cart.id || "",
284
- isEmpty: lineItems.length === 0,
285
- lineItems,
286
- summary: {
287
- itemCount,
288
- subtotal: {
289
- amount: priceSummary?.subtotal?.amount || "0",
290
- formattedAmount: priceSummary?.subtotal?.formattedAmount || "$0.00"
291
- },
292
- discount: {
293
- amount: discountAmount.toString(),
294
- formattedAmount: priceSummary?.discount?.formattedAmount || ""
295
- },
296
- hasDiscount: discountAmount > 0,
297
- estimatedTax: {
298
- amount: taxSummary?.totalTax?.amount || "0",
299
- formattedAmount: taxSummary?.totalTax?.formattedAmount || ""
300
- },
301
- showTax: hasTax,
302
- estimatedTotal: {
303
- amount: priceSummary?.total?.amount || priceSummary?.subtotal?.amount || "0",
304
- formattedAmount: priceSummary?.total?.formattedAmount || priceSummary?.subtotal?.formattedAmount || "$0.00"
305
- },
306
- currency: cart.currency || "USD"
307
- },
308
- appliedCoupon,
309
- hasAppliedCoupon: !!appliedCoupon
310
- };
311
- }
312
- const WIX_STORES_APP_ID = "215238eb-22a5-4c36-9e7b-e7c08025e04e";
313
- const WIX_CART_CONTEXT = createJayContext("wix:cart");
314
- function provideWixCartContext(thankYouUrl = "/thank-you") {
315
- const wixClientContext = useGlobalContext(WIX_CLIENT_CONTEXT);
316
- const wixClient = wixClientContext.client;
317
- const cartContext = registerReactiveGlobalContext(WIX_CART_CONTEXT, () => {
318
- const [itemCount, setItemCount] = createSignal(0);
319
- const [hasItems, setHasItems] = createSignal(false);
320
- const reactive = useReactive();
321
- const onItemAddedToCart = createEvent();
322
- function updateIndicatorFromCart(cart) {
323
- const indicator = mapCartToIndicator(cart);
324
- reactive.batchReactions(() => {
325
- setItemCount(indicator.itemCount);
326
- setHasItems(indicator.hasItems);
327
- });
328
- }
329
- async function refreshCartIndicator() {
330
- const cart = await getCurrentCartOrNull(wixClient);
331
- updateIndicatorFromCart(cart);
332
- }
333
- async function getEstimatedCart() {
334
- const estimate = await estimateCurrentCartTotalsOrNull(wixClient);
335
- return mapEstimateTotalsToState(estimate);
336
- }
337
- async function addToCart(productId, quantity = 1, options) {
338
- console.log(`[WixCart] Adding to cart: ${productId} x ${quantity}`, options);
339
- const catalogOptions = {};
340
- if (options?.variantId) catalogOptions.variantId = options.variantId;
341
- if (options?.modifiers) catalogOptions.options = options.modifiers;
342
- if (options?.customTextFields)
343
- catalogOptions.customTextFields = options.customTextFields;
344
- const lineItem = {
345
- catalogReference: {
346
- catalogItemId: productId,
347
- appId: WIX_STORES_APP_ID,
348
- ...Object.keys(catalogOptions).length > 0 ? { options: catalogOptions } : {}
349
- },
350
- quantity
351
- };
352
- const result = await addToCurrentCart(wixClient, [lineItem]);
353
- updateIndicatorFromCart(result.cart ?? null);
354
- onItemAddedToCart.emit();
355
- return { cartState: mapCartToState(result.cart ?? null) };
356
- }
357
- async function removeLineItems(lineItemIds) {
358
- const result = await removeLineItemsFromCurrentCart(wixClient, lineItemIds);
359
- updateIndicatorFromCart(result.cart ?? null);
360
- return { cartState: mapCartToState(result.cart ?? null) };
361
- }
362
- async function updateLineItemQuantity(lineItemId, quantity) {
363
- let result;
364
- if (quantity === 0) {
365
- result = await removeLineItemsFromCurrentCart(wixClient, [lineItemId]);
366
- } else {
367
- result = await updateCurrentCartLineItemQuantity(wixClient, [{ _id: lineItemId, quantity }]);
368
- }
369
- updateIndicatorFromCart(result.cart ?? null);
370
- return { cartState: mapCartToState(result.cart ?? null) };
371
- }
372
- async function clearCart() {
373
- const cart = await getCurrentCartOrNull(wixClient);
374
- if (cart?.lineItems?.length) {
375
- const lineItemIds = cart.lineItems.map((item) => item._id || "").filter(Boolean);
376
- if (lineItemIds.length > 0) {
377
- await removeLineItemsFromCurrentCart(wixClient, lineItemIds);
378
- }
379
- }
380
- setItemCount(0);
381
- setHasItems(false);
382
- }
383
- async function applyCoupon(couponCode) {
384
- const result = await updateCurrentCart(wixClient, { couponCode });
385
- updateIndicatorFromCart(result ?? null);
386
- return { cartState: mapCartToState(result ?? null) };
387
- }
388
- async function removeCoupon() {
389
- const result = await removeCouponFromCurrentCart(wixClient);
390
- updateIndicatorFromCart(result.cart ?? null);
391
- return { cartState: mapCartToState(result.cart ?? null) };
392
- }
393
- async function checkout() {
394
- const { checkoutId } = await createCheckoutFromCurrentCart(wixClient);
395
- if (!checkoutId) throw new Error("Failed to create checkout from cart");
396
- const postFlowUrl = window.location.origin + thankYouUrl;
397
- const { redirectSession } = await createRedirectSession(wixClient, {
398
- ecomCheckout: { checkoutId },
399
- callbacks: { postFlowUrl }
400
- });
401
- if (!redirectSession?.fullUrl) {
402
- throw new Error("Failed to create checkout redirect session");
403
- }
404
- return redirectSession.fullUrl;
405
- }
406
- return {
407
- cartIndicator: {
408
- itemCount,
409
- hasItems
410
- },
411
- refreshCartIndicator,
412
- getEstimatedCart,
413
- addToCart,
414
- removeLineItems,
415
- updateLineItemQuantity,
416
- clearCart,
417
- applyCoupon,
418
- removeCoupon,
419
- checkout,
420
- onItemAddedToCart
421
- };
422
- });
423
- console.log("[wix-cart] Client cart context initialized (reactive)");
424
- return cartContext;
425
- }
426
- function CartIndicatorInteractive(_props, refs, viewStateSignals, _carryForward, cartContext) {
427
- const { isLoading: [isLoading, setIsLoading], justAdded: [justAdded, setJustAdded] } = viewStateSignals;
428
- cartContext.onItemAddedToCart(() => {
429
- setJustAdded(true);
430
- setTimeout(() => setJustAdded(false), 1500);
431
- });
432
- refs.cartLink?.onclick(() => {
433
- });
434
- return {
435
- render: () => ({
436
- // Read directly from reactive global context signals
437
- itemCount: cartContext.cartIndicator.itemCount(),
438
- hasItems: cartContext.cartIndicator.hasItems(),
439
- isLoading: isLoading(),
440
- justAdded: justAdded()
441
- })
442
- };
443
- }
444
- const cartIndicator = makeJayStackComponent().withProps().withContexts(WIX_CART_CONTEXT).withInteractive(CartIndicatorInteractive);
445
- function mapLineItemToViewState(item) {
446
- return {
447
- lineItemId: item.lineItemId,
448
- productId: item.productId,
449
- productName: item.productName,
450
- productUrl: item.productUrl,
451
- variantName: item.variantName,
452
- sku: item.sku,
453
- image: item.image,
454
- quantity: item.quantity,
455
- isUpdatingQuantity: false,
456
- unitPrice: item.unitPrice,
457
- lineTotal: item.lineTotal,
458
- lineDiscount: item.lineDiscount,
459
- hasDiscount: item.hasDiscount,
460
- isRemoving: false
461
- };
462
- }
463
- function mapCartStateToViewState(cart) {
464
- return {
465
- isEmpty: cart.isEmpty,
466
- isLoading: false,
467
- isCheckingOut: false,
468
- lineItems: cart.lineItems.map(mapLineItemToViewState),
469
- summary: {
470
- itemCount: cart.summary.itemCount,
471
- subtotal: cart.summary.subtotal,
472
- discount: cart.summary.discount,
473
- hasDiscount: cart.summary.hasDiscount,
474
- estimatedTax: cart.summary.estimatedTax,
475
- showTax: cart.summary.showTax,
476
- estimatedTotal: cart.summary.estimatedTotal,
477
- currency: cart.summary.currency
478
- },
479
- coupon: {
480
- code: "",
481
- isApplying: false,
482
- appliedCode: cart.appliedCoupon,
483
- hasAppliedCoupon: cart.hasAppliedCoupon,
484
- errorMessage: "",
485
- hasError: false
486
- }
487
- };
488
- }
489
- function CartPageInteractive(_props, refs, viewStateSignals, _carryForward, cartContext) {
490
- const { isEmpty: [isEmpty, setIsEmpty], isLoading: [isLoading, setIsLoading], isCheckingOut: [isCheckingOut, setIsCheckingOut], lineItems: [lineItems, setLineItems], summary: [summary, setSummary], coupon: [coupon, setCoupon] } = viewStateSignals;
491
- async function loadCart() {
492
- try {
493
- setIsLoading(true);
494
- const cartState = await cartContext.getEstimatedCart();
495
- const viewState = mapCartStateToViewState(cartState);
496
- setIsEmpty(viewState.isEmpty);
497
- setLineItems(viewState.lineItems);
498
- setSummary(viewState.summary);
499
- setCoupon(viewState.coupon);
500
- } catch (error) {
501
- console.error("[CartPage] Failed to load cart:", error);
502
- } finally {
503
- setIsLoading(false);
504
- }
505
- }
506
- async function handleQuantityChange(lineItemId, newQuantity) {
507
- const itemIndex = lineItems().findIndex((item) => item.lineItemId === lineItemId);
508
- if (itemIndex === -1)
509
- return;
510
- setLineItems(patch(lineItems(), [
511
- { op: REPLACE, path: [itemIndex, "isUpdatingQuantity"], value: true }
512
- ]));
513
- try {
514
- await cartContext.updateLineItemQuantity(lineItemId, newQuantity);
515
- await loadCart();
516
- } catch (error) {
517
- console.error("[CartPage] Failed to update quantity:", error);
518
- setLineItems(patch(lineItems(), [
519
- { op: REPLACE, path: [itemIndex, "isUpdatingQuantity"], value: false }
520
- ]));
521
- }
522
- }
523
- async function handleRemoveItem(lineItemId) {
524
- const itemIndex = lineItems().findIndex((item) => item.lineItemId === lineItemId);
525
- if (itemIndex === -1)
526
- return;
527
- setLineItems(patch(lineItems(), [{ op: REPLACE, path: [itemIndex, "isRemoving"], value: true }]));
528
- try {
529
- await cartContext.removeLineItems([lineItemId]);
530
- await loadCart();
531
- } catch (error) {
532
- console.error("[CartPage] Failed to remove item:", error);
533
- setLineItems(patch(lineItems(), [
534
- { op: REPLACE, path: [itemIndex, "isRemoving"], value: false }
535
- ]));
536
- }
537
- }
538
- async function handleClearCart() {
539
- try {
540
- setIsLoading(true);
541
- await cartContext.clearCart();
542
- await loadCart();
543
- } catch (error) {
544
- console.error("[CartPage] Failed to clear cart:", error);
545
- setIsLoading(false);
546
- }
547
- }
548
- async function handleApplyCoupon() {
549
- const code = coupon().code.trim();
550
- if (!code)
551
- return;
552
- setCoupon(patch(coupon(), [
553
- { op: REPLACE, path: ["isApplying"], value: true },
554
- { op: REPLACE, path: ["hasError"], value: false },
555
- { op: REPLACE, path: ["errorMessage"], value: "" }
556
- ]));
557
- try {
558
- await cartContext.applyCoupon(code);
559
- await loadCart();
560
- } catch (error) {
561
- console.error("[CartPage] Failed to apply coupon:", error);
562
- setCoupon(patch(coupon(), [
563
- { op: REPLACE, path: ["isApplying"], value: false },
564
- { op: REPLACE, path: ["hasError"], value: true },
565
- { op: REPLACE, path: ["errorMessage"], value: "Invalid coupon code" }
566
- ]));
567
- }
568
- }
569
- async function handleRemoveCoupon() {
570
- try {
571
- await cartContext.removeCoupon();
572
- await loadCart();
573
- } catch (error) {
574
- console.error("[CartPage] Failed to remove coupon:", error);
575
- }
576
- }
577
- async function handleCheckout() {
578
- setIsCheckingOut(true);
579
- try {
580
- const checkoutUrl = await cartContext.checkout();
581
- window.location.href = checkoutUrl;
582
- } catch (e) {
583
- console.error("[wix-cart] Checkout redirect failed:", e);
584
- setIsCheckingOut(false);
585
- }
586
- }
587
- refs.clearCartButton?.onclick(handleClearCart);
588
- refs.checkoutButton?.onclick(handleCheckout);
589
- refs.coupon?.code?.oninput(({ event }) => {
590
- const code = event.target.value;
591
- setCoupon(patch(coupon(), [{ op: REPLACE, path: ["code"], value: code }]));
592
- });
593
- refs.coupon?.applyButton?.onclick(handleApplyCoupon);
594
- refs.coupon?.removeButton?.onclick(handleRemoveCoupon);
595
- refs.lineItems?.quantity.oninput(({ event, coordinate }) => {
596
- const lineItemId = coordinate[0];
597
- const newQty = parseInt(event.target.value) || 1;
598
- handleQuantityChange(lineItemId, newQty);
599
- });
600
- refs.lineItems?.decrementButton.onclick(({ viewState }) => {
601
- if (viewState.quantity > 1) {
602
- handleQuantityChange(viewState.lineItemId, viewState.quantity - 1);
603
- }
604
- });
605
- refs.lineItems?.incrementButton.onclick(({ viewState }) => {
606
- handleQuantityChange(viewState.lineItemId, viewState.quantity + 1);
607
- });
608
- refs.lineItems?.removeButton.onclick(({ viewState }) => {
609
- handleRemoveItem(viewState.lineItemId);
610
- });
611
- cartContext.onItemAddedToCart(() => loadCart());
612
- loadCart();
613
- return {
614
- render: () => ({
615
- isEmpty: isEmpty(),
616
- isLoading: isLoading(),
617
- isCheckingOut: isCheckingOut(),
618
- lineItems: lineItems(),
619
- summary: summary(),
620
- coupon: coupon()
621
- })
622
- };
623
- }
624
- const cartPage = makeJayStackComponent().withProps().withContexts(WIX_CART_CONTEXT).withInteractive(CartPageInteractive);
625
- function MiniCartInteractive(_props, refs, viewStateSignals, _carryForward, cartContext) {
626
- const { isOpen: [isOpen, setIsOpen] } = viewStateSignals;
627
- cartContext.onItemAddedToCart(() => {
628
- setIsOpen(true);
629
- });
630
- refs.openButton.onclick(() => {
631
- setIsOpen(true);
632
- });
633
- refs.closeButton.onclick(() => {
634
- setIsOpen(false);
635
- });
636
- return {
637
- render: () => ({
638
- isOpen: isOpen()
639
- })
640
- };
641
- }
642
- const miniCart = makeJayStackComponent().withProps().withContexts(WIX_CART_CONTEXT).withInteractive(MiniCartInteractive);
643
- const init = makeJayInit().withClient(async (data) => {
644
- console.log("[wix-cart] Initializing client-side cart context...");
645
- const { enableClientCart, thankYouUrl } = data;
646
- const cartContext = provideWixCartContext(thankYouUrl);
647
- if (enableClientCart) {
648
- cartContext.refreshCartIndicator();
649
- }
650
- console.log("[wix-cart] Client initialization complete");
651
- console.log(`[wix-cart] Cart enabled: ${enableClientCart}`);
652
- });
653
- export {
654
- WIX_CART_CONTEXT,
655
- cartIndicator,
656
- cartPage,
657
- init,
658
- miniCart
659
- };
package/dist/index.d.ts DELETED
@@ -1,17 +0,0 @@
1
- import { WixClient } from '@wix/sdk';
2
- import { W as WixCartService } from './index.client-Ca5v2viE.js';
3
- export { A as AddToCartOptions, q as CartIndicatorState, n as CartLineItem, C as CartOperationResult, l as CartState, o as CartSummary, R as ReactiveCartIndicator, b as WIX_CART_CONTEXT, a as WIX_CART_SERVICE, c as WixCartContext, d as WixCartInitData, r as cartIndicator, s as cartPage, j as estimateCurrentCartTotalsOrNull, i as getCurrentCartOrNull, h as getEmptyCartState, u as init, e as mapCartSummary, g as mapCartToIndicator, f as mapCartToState, k as mapEstimateTotalsToState, m as mapLineItem, t as miniCart, p as provideWixCartContext } from './index.client-Ca5v2viE.js';
4
- import '@jay-framework/runtime';
5
- import '@jay-framework/reactive';
6
- import '@jay-framework/fullstack-component';
7
- import '@jay-framework/component';
8
-
9
- /**
10
- * Server-side Wix Cart Service
11
- *
12
- * Provides the WixClient for cart operations on the server.
13
- */
14
-
15
- declare function provideWixCartService(wixClient: WixClient): WixCartService;
16
-
17
- export { WixCartService, provideWixCartService };