create-abcart-theme 0.0.0-stage → 0.10.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.
Files changed (253) hide show
  1. package/CHANGELOG.md +127 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +2 -0
  4. package/README.md +64 -2
  5. package/bin/create-abcart-theme.mjs +4 -0
  6. package/package.json +47 -4
  7. package/src/args.mjs +113 -0
  8. package/src/banner.mjs +21 -0
  9. package/src/cli.mjs +119 -0
  10. package/src/create.mjs +82 -0
  11. package/src/package-manager.mjs +32 -0
  12. package/src/style.mjs +17 -0
  13. package/templates/default/.agents/skills/shopify-theme-asset-collector/SKILL.md +125 -0
  14. package/templates/default/.agents/skills/shopify-theme-asset-collector/scripts/collect_public_assets.py +370 -0
  15. package/templates/default/.agents/skills/wocart-docs/SKILL.md +146 -0
  16. package/templates/default/.agents/skills/wocart-theme-from-design/SKILL.md +58 -0
  17. package/templates/default/.agents/skills/wocart-theme-from-design/references/inputs-and-rights.md +47 -0
  18. package/templates/default/.agents/skills/wocart-theme-from-design/references/layout-rtl-and-phone.md +36 -0
  19. package/templates/default/.agents/skills/wocart-theme-from-design/references/measure-the-design.md +60 -0
  20. package/templates/default/.agents/skills/wocart-theme-from-design/references/tokens-sections-content.md +103 -0
  21. package/templates/default/.agents/skills/wocart-theme-from-design/references/verify-and-report.md +102 -0
  22. package/templates/default/.agents/skills/wocart-theme-from-design/scripts/compare-design.cjs +230 -0
  23. package/templates/default/.agents/skills/wocart-theme-from-design/scripts/qa-pages.cjs +219 -0
  24. package/templates/default/.dev.vars.example +12 -0
  25. package/templates/default/AGENTS.md +240 -0
  26. package/templates/default/README.md +184 -0
  27. package/templates/default/_gitignore +11 -0
  28. package/templates/default/astro.config.mjs +85 -0
  29. package/templates/default/package.json +36 -0
  30. package/templates/default/public/fonts/OFL.txt +96 -0
  31. package/templates/default/public/fonts/alexandria-arabic.woff2 +0 -0
  32. package/templates/default/public/fonts/fraunces-latin.woff2 +0 -0
  33. package/templates/default/src/actions/index.ts +22 -0
  34. package/templates/default/src/components/cart/AddToCartButton.astro +45 -0
  35. package/templates/default/src/components/cart/CartDrawer.astro +47 -0
  36. package/templates/default/src/components/cart/CartSummary.astro +11 -0
  37. package/templates/default/src/components/cart/FreeShipping.astro +7 -0
  38. package/templates/default/src/components/checkout/CheckoutMain.astro +29 -0
  39. package/templates/default/src/components/checkout/OrderForm.astro +280 -0
  40. package/templates/default/src/components/checkout/ThankYouMain.astro +68 -0
  41. package/templates/default/src/components/landing/LandingImages.astro +51 -0
  42. package/templates/default/src/components/landing/LandingOrder.astro +46 -0
  43. package/templates/default/src/components/landing/LandingProduct.astro +41 -0
  44. package/templates/default/src/components/listing/ListingMain.astro +93 -0
  45. package/templates/default/src/components/listing/PageMain.astro +52 -0
  46. package/templates/default/src/components/listing/Pagination.astro +31 -0
  47. package/templates/default/src/components/listing/SortControl.astro +35 -0
  48. package/templates/default/src/components/product/BuyBox.astro +96 -0
  49. package/templates/default/src/components/product/Description.astro +24 -0
  50. package/templates/default/src/components/product/Gallery.astro +66 -0
  51. package/templates/default/src/components/product/MobileBuyBar.astro +29 -0
  52. package/templates/default/src/components/product/OfferChoice.astro +66 -0
  53. package/templates/default/src/components/product/ProductMain.astro +40 -0
  54. package/templates/default/src/components/product/ProductReviews.astro +72 -0
  55. package/templates/default/src/components/product/RelatedProducts.astro +30 -0
  56. package/templates/default/src/components/product/blocks/BenefitsBlock.astro +13 -0
  57. package/templates/default/src/components/product/blocks/CollapsibleBlock.astro +20 -0
  58. package/templates/default/src/components/product/blocks/DescriptionBlock.astro +19 -0
  59. package/templates/default/src/components/product/blocks/DetailsBlock.astro +33 -0
  60. package/templates/default/src/components/product/blocks/GalleryBlock.astro +12 -0
  61. package/templates/default/src/components/product/blocks/OrderBlock.astro +30 -0
  62. package/templates/default/src/components/product/blocks/PriceBlock.astro +23 -0
  63. package/templates/default/src/components/product/blocks/RatingBlock.astro +16 -0
  64. package/templates/default/src/components/product/blocks/StockBlock.astro +22 -0
  65. package/templates/default/src/components/product/blocks/TextBlock.astro +11 -0
  66. package/templates/default/src/components/product/blocks/TitleBlock.astro +20 -0
  67. package/templates/default/src/components/reviews/ReviewCard.astro +46 -0
  68. package/templates/default/src/components/reviews/ReviewForm.astro +113 -0
  69. package/templates/default/src/components/reviews/VoiceNote.astro +60 -0
  70. package/templates/default/src/components/sections/CollectionCards.astro +65 -0
  71. package/templates/default/src/components/sections/Countdown.astro +57 -0
  72. package/templates/default/src/components/sections/Faq.astro +44 -0
  73. package/templates/default/src/components/sections/FeaturedProduct.astro +71 -0
  74. package/templates/default/src/components/sections/Hero.astro +99 -0
  75. package/templates/default/src/components/sections/ImageBanner.astro +46 -0
  76. package/templates/default/src/components/sections/ProductGrid.astro +47 -0
  77. package/templates/default/src/components/sections/RichText.astro +35 -0
  78. package/templates/default/src/components/sections/Steps.astro +46 -0
  79. package/templates/default/src/components/sections/Testimonials.astro +57 -0
  80. package/templates/default/src/components/shell/Footer.astro +80 -0
  81. package/templates/default/src/components/shell/Header.astro +89 -0
  82. package/templates/default/src/components/shell/LanguageMenu.astro +33 -0
  83. package/templates/default/src/components/shell/MobileMenu.astro +65 -0
  84. package/templates/default/src/components/shell/SearchDialog.astro +19 -0
  85. package/templates/default/src/components/shell/TopBar.astro +54 -0
  86. package/templates/default/src/components/shell/WhatsAppWidget.astro +111 -0
  87. package/templates/default/src/components/store/ContactMain.astro +79 -0
  88. package/templates/default/src/components/store/SearchMain.astro +56 -0
  89. package/templates/default/src/components/store/TrackOrderMain.astro +161 -0
  90. package/templates/default/src/components/surface/Area.astro +20 -0
  91. package/templates/default/src/components/surface/PreviewBridge.astro +24 -0
  92. package/templates/default/src/components/surface/Sections.astro +35 -0
  93. package/templates/default/src/components/ui/Breadcrumbs.astro +36 -0
  94. package/templates/default/src/components/ui/Button.astro +45 -0
  95. package/templates/default/src/components/ui/EditorPlaceholder.astro +24 -0
  96. package/templates/default/src/components/ui/Icon.astro +93 -0
  97. package/templates/default/src/components/ui/Logo.astro +36 -0
  98. package/templates/default/src/components/ui/Photo.astro +46 -0
  99. package/templates/default/src/components/ui/Price.astro +24 -0
  100. package/templates/default/src/components/ui/ProductCard.astro +41 -0
  101. package/templates/default/src/components/ui/Rating.astro +22 -0
  102. package/templates/default/src/components/ui/Section.astro +34 -0
  103. package/templates/default/src/components/ui/SectionHeading.astro +19 -0
  104. package/templates/default/src/env.d.ts +23 -0
  105. package/templates/default/src/layouts/StoreLayout.astro +145 -0
  106. package/templates/default/src/lib/browser-copy.ts +37 -0
  107. package/templates/default/src/lib/context.ts +89 -0
  108. package/templates/default/src/lib/coupon-notice.ts +47 -0
  109. package/templates/default/src/lib/i18n.ts +32 -0
  110. package/templates/default/src/lib/images.ts +38 -0
  111. package/templates/default/src/lib/listing-query.ts +41 -0
  112. package/templates/default/src/lib/money.ts +16 -0
  113. package/templates/default/src/lib/motion.ts +16 -0
  114. package/templates/default/src/lib/nav.ts +26 -0
  115. package/templates/default/src/lib/offer-tiles.ts +105 -0
  116. package/templates/default/src/lib/order-outcome.ts +66 -0
  117. package/templates/default/src/lib/otp-message.ts +21 -0
  118. package/templates/default/src/lib/products.ts +38 -0
  119. package/templates/default/src/lib/review-refusals.ts +31 -0
  120. package/templates/default/src/lib/store.ts +31 -0
  121. package/templates/default/src/lib/whatsapp.ts +29 -0
  122. package/templates/default/src/middleware.ts +23 -0
  123. package/templates/default/src/pages/404.astro +22 -0
  124. package/templates/default/src/pages/api/abandoned/convert.ts +4 -0
  125. package/templates/default/src/pages/api/abandoned/upsert.ts +4 -0
  126. package/templates/default/src/pages/api/cart/validate.ts +4 -0
  127. package/templates/default/src/pages/api/communes/[wilayaId].ts +4 -0
  128. package/templates/default/src/pages/api/otp/send.ts +4 -0
  129. package/templates/default/src/pages/api/otp/verify.ts +4 -0
  130. package/templates/default/src/pages/api/reviews/[productId].ts +3 -0
  131. package/templates/default/src/pages/api/reviews/eligibility.ts +3 -0
  132. package/templates/default/src/pages/api/reviews/submit.ts +3 -0
  133. package/templates/default/src/pages/api/reviews/upload.ts +3 -0
  134. package/templates/default/src/pages/category/[slug].astro +20 -0
  135. package/templates/default/src/pages/checkout.astro +25 -0
  136. package/templates/default/src/pages/collections/[handle].astro +20 -0
  137. package/templates/default/src/pages/contact.astro +17 -0
  138. package/templates/default/src/pages/index.astro +9 -0
  139. package/templates/default/src/pages/lp/[slug].astro +47 -0
  140. package/templates/default/src/pages/pages/[slug].astro +16 -0
  141. package/templates/default/src/pages/products/[handle].astro +37 -0
  142. package/templates/default/src/pages/products/index.astro +15 -0
  143. package/templates/default/src/pages/robots.txt.ts +9 -0
  144. package/templates/default/src/pages/search.astro +19 -0
  145. package/templates/default/src/pages/sitemap.xml.ts +12 -0
  146. package/templates/default/src/pages/thank-you.astro +33 -0
  147. package/templates/default/src/pages/track-order.astro +17 -0
  148. package/templates/default/src/pages/wocart-preview.astro +43 -0
  149. package/templates/default/src/pages/wocart-revalidate.ts +10 -0
  150. package/templates/default/src/pages/wocart-styles.css.ts +5 -0
  151. package/templates/default/src/pages/wocart-theme.json.ts +5 -0
  152. package/templates/default/src/scripts/cart.ts +371 -0
  153. package/templates/default/src/scripts/checkout/coupon.ts +96 -0
  154. package/templates/default/src/scripts/checkout/delivery.ts +86 -0
  155. package/templates/default/src/scripts/checkout/form.ts +54 -0
  156. package/templates/default/src/scripts/checkout/otp.ts +106 -0
  157. package/templates/default/src/scripts/checkout/picker.ts +169 -0
  158. package/templates/default/src/scripts/checkout/quote.ts +169 -0
  159. package/templates/default/src/scripts/checkout/submit.ts +113 -0
  160. package/templates/default/src/scripts/checkout/tracking.ts +74 -0
  161. package/templates/default/src/scripts/countdown.ts +29 -0
  162. package/templates/default/src/scripts/events.ts +4 -0
  163. package/templates/default/src/scripts/hero.ts +49 -0
  164. package/templates/default/src/scripts/listing.ts +13 -0
  165. package/templates/default/src/scripts/order-form.ts +100 -0
  166. package/templates/default/src/scripts/product.ts +306 -0
  167. package/templates/default/src/scripts/public-config.ts +79 -0
  168. package/templates/default/src/scripts/reviews.ts +358 -0
  169. package/templates/default/src/scripts/site.ts +131 -0
  170. package/templates/default/src/scripts/thank-you.ts +11 -0
  171. package/templates/default/src/scripts/voice-note.ts +94 -0
  172. package/templates/default/src/styles/base.css +1030 -0
  173. package/templates/default/src/styles/checkout.css +1111 -0
  174. package/templates/default/src/styles/global.css +12 -0
  175. package/templates/default/src/styles/product.css +871 -0
  176. package/templates/default/src/styles/reviews.css +533 -0
  177. package/templates/default/src/styles/sections.css +931 -0
  178. package/templates/default/src/styles/shell.css +970 -0
  179. package/templates/default/src/styles/tokens.css +583 -0
  180. package/templates/default/src/theme/api-routes.ts +10 -0
  181. package/templates/default/src/theme/content/catalog.ts +117 -0
  182. package/templates/default/src/theme/content/checkout.ts +168 -0
  183. package/templates/default/src/theme/content/editor.ts +21 -0
  184. package/templates/default/src/theme/content/index.ts +45 -0
  185. package/templates/default/src/theme/content/reviews.ts +76 -0
  186. package/templates/default/src/theme/content/shell.ts +59 -0
  187. package/templates/default/src/theme/content/types.ts +12 -0
  188. package/templates/default/src/theme/documents/catalog.json +11 -0
  189. package/templates/default/src/theme/documents/category.json +11 -0
  190. package/templates/default/src/theme/documents/checkout.json +11 -0
  191. package/templates/default/src/theme/documents/collection.json +11 -0
  192. package/templates/default/src/theme/documents/contact.json +11 -0
  193. package/templates/default/src/theme/documents/footer.area.json +11 -0
  194. package/templates/default/src/theme/documents/header.area.json +16 -0
  195. package/templates/default/src/theme/documents/home.json +313 -0
  196. package/templates/default/src/theme/documents/landing.json +8 -0
  197. package/templates/default/src/theme/documents/page.json +11 -0
  198. package/templates/default/src/theme/documents/product.json +125 -0
  199. package/templates/default/src/theme/documents/search.json +11 -0
  200. package/templates/default/src/theme/documents/thank-you.json +11 -0
  201. package/templates/default/src/theme/documents/track-order.json +11 -0
  202. package/templates/default/src/theme/fields.ts +61 -0
  203. package/templates/default/src/theme/key.ts +11 -0
  204. package/templates/default/src/theme/labels.ts +231 -0
  205. package/templates/default/src/theme/locales.ts +11 -0
  206. package/templates/default/src/theme/palette.ts +14 -0
  207. package/templates/default/src/theme/sections/collection-cards.ts +65 -0
  208. package/templates/default/src/theme/sections/faq.ts +74 -0
  209. package/templates/default/src/theme/sections/featured-product.ts +42 -0
  210. package/templates/default/src/theme/sections/hero.ts +47 -0
  211. package/templates/default/src/theme/sections/image-banner.ts +25 -0
  212. package/templates/default/src/theme/sections/index.ts +40 -0
  213. package/templates/default/src/theme/sections/landing.ts +150 -0
  214. package/templates/default/src/theme/sections/listing.ts +84 -0
  215. package/templates/default/src/theme/sections/product-grid.ts +42 -0
  216. package/templates/default/src/theme/sections/product.ts +297 -0
  217. package/templates/default/src/theme/sections/rich-text.ts +39 -0
  218. package/templates/default/src/theme/sections/shared.ts +54 -0
  219. package/templates/default/src/theme/sections/shell.ts +85 -0
  220. package/templates/default/src/theme/sections/store-pages.ts +101 -0
  221. package/templates/default/src/theme/sections/testimonials.ts +61 -0
  222. package/templates/default/src/theme/sections/thank-you.ts +35 -0
  223. package/templates/default/src/theme/settings.ts +124 -0
  224. package/templates/default/src/theme/theme.ts +65 -0
  225. package/templates/default/tests/fixtures/canvas-tote.json +62 -0
  226. package/templates/default/tests/fixtures/linen-shirt.json +128 -0
  227. package/templates/default/tests/unit/checkout.test.ts +241 -0
  228. package/templates/default/tests/unit/contract.test.ts +169 -0
  229. package/templates/default/tests/unit/contrast.test.ts +68 -0
  230. package/templates/default/tests/unit/copy.test.ts +101 -0
  231. package/templates/default/tests/unit/design-values.test.ts +95 -0
  232. package/templates/default/tests/unit/editability.test.ts +180 -0
  233. package/templates/default/tests/unit/fixtures.ts +91 -0
  234. package/templates/default/tests/unit/footer.test.ts +54 -0
  235. package/templates/default/tests/unit/guards.test.ts +340 -0
  236. package/templates/default/tests/unit/images.test.ts +26 -0
  237. package/templates/default/tests/unit/landing.test.ts +151 -0
  238. package/templates/default/tests/unit/languages.test.ts +42 -0
  239. package/templates/default/tests/unit/middleware.test.ts +53 -0
  240. package/templates/default/tests/unit/offer-tiles.test.ts +75 -0
  241. package/templates/default/tests/unit/render.ts +38 -0
  242. package/templates/default/tests/unit/reviews.test.ts +25 -0
  243. package/templates/default/tests/unit/rules.test.ts +59 -0
  244. package/templates/default/tests/unit/source.ts +75 -0
  245. package/templates/default/tests/unit/store-pages.test.ts +147 -0
  246. package/templates/default/tests/unit/studio.test.ts +202 -0
  247. package/templates/default/tests/unit/testimonials.test.ts +52 -0
  248. package/templates/default/tests/unit/thank-you.test.ts +52 -0
  249. package/templates/default/tests/unit/tracking.test.ts +29 -0
  250. package/templates/default/tests/unit/voice-note.test.ts +42 -0
  251. package/templates/default/tsconfig.json +13 -0
  252. package/templates/default/vitest.config.ts +15 -0
  253. package/templates/default/wrangler.jsonc +17 -0
@@ -0,0 +1,49 @@
1
+ import { bindEach } from "@abcart/theme/lifecycle";
2
+ import { motionMs } from "@/lib/motion";
3
+
4
+ bindEach<HTMLElement>("[data-hero]", (hero) => {
5
+ const slides = Array.from(hero.querySelectorAll<HTMLElement>("[data-hero-slide]"));
6
+ const dots = Array.from(hero.querySelectorAll<HTMLButtonElement>("[data-hero-dot]"));
7
+ if (slides.length < 2) return;
8
+ let index = 0;
9
+ let timer = 0;
10
+ const show = (next: number) => {
11
+ index = (next + slides.length) % slides.length;
12
+ slides.forEach((slide, i) => {
13
+ const active = i === index;
14
+ slide.dataset.active = active ? "true" : "false";
15
+ slide.setAttribute("aria-hidden", active ? "false" : "true");
16
+ slide.querySelectorAll<HTMLElement>("a").forEach((link) => (active ? link.removeAttribute("tabindex") : link.setAttribute("tabindex", "-1")));
17
+ });
18
+ dots.forEach((dot, i) => dot.setAttribute("aria-current", i === index ? "true" : "false"));
19
+ };
20
+ const stop = () => {
21
+ window.clearInterval(timer);
22
+ timer = 0;
23
+ };
24
+ const start = () => {
25
+ stop();
26
+ if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
27
+ timer = window.setInterval(() => show(index + 1), motionMs("--motion-hero-interval"));
28
+ };
29
+ hero.querySelector("[data-hero-prev]")?.addEventListener("click", () => {
30
+ show(index - 1);
31
+ start();
32
+ });
33
+ hero.querySelector("[data-hero-next]")?.addEventListener("click", () => {
34
+ show(index + 1);
35
+ start();
36
+ });
37
+ dots.forEach((dot) =>
38
+ dot.addEventListener("click", () => {
39
+ show(Number(dot.dataset.heroDot) || 0);
40
+ start();
41
+ }),
42
+ );
43
+ hero.addEventListener("mouseenter", stop);
44
+ hero.addEventListener("mouseleave", start);
45
+ hero.addEventListener("focusin", stop);
46
+ hero.addEventListener("focusout", start);
47
+ document.addEventListener("visibilitychange", () => (document.hidden ? stop() : start()));
48
+ start();
49
+ });
@@ -0,0 +1,13 @@
1
+ /**
2
+ * A listing's sort control: a choice reloads the listing in that order, from
3
+ * its first page, with no empty field in its address.
4
+ */
5
+ import { bindEach } from "@abcart/theme/lifecycle";
6
+
7
+ bindEach<HTMLFormElement>("[data-listing-sort]", (form) => {
8
+ form.addEventListener("change", () => {
9
+ const url = new URL(form.action);
10
+ for (const [name, value] of new FormData(form)) if (typeof value === "string" && value !== "") url.searchParams.set(name, value);
11
+ window.location.assign(url);
12
+ });
13
+ });
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The order form, product or basket: one entry that binds each form through
3
+ * the SDK's lifecycle and wires its parts (`./checkout/`). Every part returns
4
+ * what it must undo, so a form the editor's preview replaces leaves nothing
5
+ * bound behind.
6
+ */
7
+ import { bindCheckoutKey, toLocalAlgerianMobile } from "@abcart/storefront";
8
+ import { bindEach } from "@abcart/theme/lifecycle";
9
+ import { PRODUCT_CHANGE_EVENT } from "./events";
10
+ import { bindCoupon } from "./checkout/coupon";
11
+ import { bindDelivery } from "./checkout/delivery";
12
+ import { checkoutForm, config, type Cleanup } from "./checkout/form";
13
+ import { bindOtp } from "./checkout/otp";
14
+ import { bindPickers } from "./checkout/picker";
15
+ import { bindQuote } from "./checkout/quote";
16
+ import { bindSubmit, createSubmitter } from "./checkout/submit";
17
+ import { bindTracking } from "./checkout/tracking";
18
+
19
+ bindEach<HTMLFormElement>("[data-order-form]", initForm);
20
+
21
+ function initForm(form: HTMLFormElement) {
22
+ // One checkout, one order: a refresh, a retry or a resubmitted form is
23
+ // answered with the order already placed.
24
+ const unbindCheckoutKey = bindCheckoutKey(form);
25
+ const cleanups: Cleanup[] = [unbindCheckoutKey, bindPickers(form)];
26
+ const checkout = checkoutForm(form);
27
+ const { mode, basket, field } = checkout;
28
+
29
+ const delivery = bindDelivery(checkout, () => {
30
+ tracking.update();
31
+ void quote.refresh();
32
+ });
33
+ const tracking = bindTracking(checkout, delivery);
34
+ const submitter = createSubmitter(checkout, { quote: () => quote, otp: () => otp });
35
+ const coupon = bindCoupon(checkout, () => void quote.refresh());
36
+ const quote = bindQuote(checkout, {
37
+ delivery,
38
+ couponCode: coupon.code,
39
+ isSubmitting: submitter.isSubmitting,
40
+ onRender: (current) => {
41
+ coupon.render(current);
42
+ delivery.updateAddressRequirement();
43
+ },
44
+ onQuote: tracking.quoted,
45
+ });
46
+ const otp = bindOtp(checkout, submitter.send);
47
+ bindSubmit(checkout, { submitter, quote, coupon, otp, otpRequired: config.otpEnabled });
48
+ cleanups.push(tracking.stop, quote.stop);
49
+
50
+ const phoneInput = field<HTMLInputElement>("[name=phone]");
51
+ phoneInput?.addEventListener("change", () => {
52
+ const local = toLocalAlgerianMobile(phoneInput.value);
53
+ if (local) phoneInput.value = local;
54
+ otp.phoneChanged(phoneInput.value);
55
+ if (coupon.code()) quote.schedule(300);
56
+ });
57
+
58
+ if (mode === "direct") {
59
+ // The buy box above the form owns the variant, quantity and offer; the form posts them.
60
+ const product = form.closest<HTMLElement>("[data-product]");
61
+ const syncProductFields = () => {
62
+ for (const name of ["productId", "productName", "variantId", "variantLabel", "pricePerUnit", "offerId", "variantSelections", "quantity"]) {
63
+ const source = Array.from(product?.querySelectorAll<HTMLInputElement>(`[name="${name}"]`) ?? []).find((input) => !form.contains(input));
64
+ const target = field<HTMLInputElement>(`[name="${name}"]`);
65
+ if (source && target) target.value = source.value;
66
+ }
67
+ };
68
+ const onProductChange = () => {
69
+ syncProductFields();
70
+ quote.schedule();
71
+ };
72
+ product?.addEventListener(PRODUCT_CHANGE_EVENT, onProductChange);
73
+ cleanups.push(() => product?.removeEventListener(PRODUCT_CHANGE_EVENT, onProductChange));
74
+ syncProductFields();
75
+ } else if (basket) {
76
+ // A checkout with nothing to check out goes back to the catalog.
77
+ if (quote.items().length === 0) {
78
+ window.location.assign(config.routes.catalog);
79
+ return () => cleanups.forEach((cleanup) => cleanup());
80
+ }
81
+ cleanups.push(
82
+ basket.subscribe((lines) => {
83
+ if (lines.length === 0) return window.location.assign(config.routes.catalog);
84
+ tracking.update();
85
+ void quote.refresh();
86
+ }),
87
+ );
88
+ }
89
+
90
+ void quote.refresh();
91
+
92
+ if (config.turnstileEnabled && config.turnstileSiteKey && !document.querySelector('script[src*="challenges.cloudflare.com/turnstile"]')) {
93
+ const script = document.createElement("script");
94
+ script.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
95
+ script.async = true;
96
+ script.defer = true;
97
+ document.head.appendChild(script);
98
+ }
99
+ return () => cleanups.forEach((cleanup) => cleanup());
100
+ }
@@ -0,0 +1,306 @@
1
+ /**
2
+ * A product on the page: its photos, the options, the offer tiles or the
3
+ * quantity, and a variant for each piece of a multi-piece offer. The choice
4
+ * is written into the fields the order form and the basket read, and the
5
+ * prices follow the chosen variant. The phone's sticky bar shows what the
6
+ * choice costs — the server's quote once the form has it.
7
+ */
8
+ import {
9
+ formatMoney,
10
+ getOfferTierView,
11
+ initialVariant,
12
+ optionStates,
13
+ pickOption,
14
+ variantFor,
15
+ type OptionSelection,
16
+ storefrontTracking,
17
+ } from "@abcart/storefront";
18
+ import type { BrowserProduct } from "@/lib/products";
19
+ import { ORDER_QUOTE_EVENT, PRODUCT_CHANGE_EVENT } from "./events";
20
+ import { bindEach } from "@abcart/theme/lifecycle";
21
+ import { readPublicConfig, translate } from "./public-config";
22
+
23
+ const config = readPublicConfig();
24
+ const tr = (key: string, values?: Record<string, string | number>) => translate(config, key, values);
25
+ const money = (amount: number) => formatMoney(Math.round(amount), { symbol: config.symbol, locale: config.localeTag, decimals: 0 });
26
+ const labelOf = (variations: Readonly<Record<string, string>> | undefined) => Object.values(variations ?? {}).filter((value) => value !== "Default Title").join(" · ");
27
+
28
+ bindEach<HTMLElement>("[data-product]", (root) => {
29
+ const dataNode = root.querySelector<HTMLScriptElement>("[data-product-data]");
30
+ if (!dataNode?.textContent) return;
31
+ const product = JSON.parse(dataNode.textContent) as BrowserProduct;
32
+ const catalog = { variants: product.variants, trackInventory: product.trackInventory, variantOptions: product.variantOptions };
33
+ let variant = initialVariant(catalog);
34
+ let selection: OptionSelection = { ...(variant?.variations ?? {}) };
35
+
36
+ const all = <T extends Element>(selector: string) => Array.from(root.querySelectorAll<T>(selector));
37
+ const optionButtons = all<HTMLButtonElement>("[data-option]");
38
+ const tiles = all<HTMLLabelElement>("[data-tile]");
39
+ const units = root.querySelector<HTMLElement>("[data-offer-units]");
40
+ const unitRows = root.querySelector<HTMLElement>("[data-offer-unit-rows]");
41
+ const unitTemplate = root.querySelector<HTMLTemplateElement>("[data-offer-unit-template]");
42
+ const qtyInput = root.querySelector<HTMLInputElement>("[data-qty-input]");
43
+ const mobileBar = root.querySelector<HTMLElement>("[data-mobile-buy]");
44
+ const mobileTotal = root.querySelector<HTMLElement>("[data-mobile-total]");
45
+ /** The variant each piece of the chosen tile is ordered in, by its options. */
46
+ let pieces: OptionSelection[] = [];
47
+ /** Pieces the shopper set by hand keep their choice when the main options change. */
48
+ const touched = new Set<number>();
49
+
50
+ const price = () => variant?.price ?? product.price;
51
+ const compare = () => variant?.compareAtPrice ?? product.compareAtPrice ?? null;
52
+ const chosenTile = () => tiles.find((tile) => tile.querySelector<HTMLInputElement>("input")?.checked && !tile.hidden) ?? null;
53
+ const quantity = () => {
54
+ const tile = chosenTile();
55
+ if (tile) return Number(tile.dataset.quantity) || 1;
56
+ return Math.max(1, Math.min(Number(qtyInput?.max) || 100, Number(qtyInput?.value) || 1));
57
+ };
58
+ const setField = (name: string, value: string) => all<HTMLInputElement>(`input[type="hidden"][name="${name}"]`).forEach((input) => (input.value = value));
59
+ const stockOf = (candidate = variant) => (candidate ? candidate.inventory : product.inventory);
60
+ const soldOut = () => product.trackInventory && stockOf() <= 0;
61
+
62
+ function paintOptions() {
63
+ const states = optionStates(catalog, selection);
64
+ for (const button of optionButtons) {
65
+ const name = button.dataset.option ?? "";
66
+ const value = button.dataset.value ?? "";
67
+ const state = states[name]?.[value] ?? "unavailable";
68
+ button.dataset.state = state;
69
+ button.disabled = state === "unavailable";
70
+ button.setAttribute("aria-pressed", selection[name] === value ? "true" : "false");
71
+ }
72
+ all<HTMLElement>("[data-option-chosen]").forEach((node) => (node.textContent = selection[node.dataset.optionChosen ?? ""] ?? ""));
73
+ }
74
+
75
+ function paintPrice() {
76
+ const now = price();
77
+ const before = compare();
78
+ const discounted = before !== null && before > now;
79
+ all<HTMLElement>("[data-product-price]").forEach((node) => (node.textContent = money(now)));
80
+ all<HTMLElement>("[data-product-compare]").forEach((node) => {
81
+ node.textContent = discounted ? money(before) : "";
82
+ node.hidden = !discounted;
83
+ });
84
+ const percent = discounted ? Math.round((1 - now / before) * 100) : 0;
85
+ all<HTMLElement>("[data-product-save]").forEach((node) => {
86
+ node.textContent = discounted ? tr("product.save", { percent }) : "";
87
+ node.hidden = !discounted;
88
+ });
89
+ all<HTMLElement>("[data-gallery-sticker]").forEach((node) => {
90
+ node.textContent = `−${percent}%`;
91
+ node.hidden = !discounted;
92
+ });
93
+ }
94
+
95
+ function paintStock() {
96
+ const stock = root.querySelector<HTMLElement>("[data-stock]");
97
+ const out = soldOut();
98
+ if (stock) {
99
+ const low = !out && product.trackInventory && stock.dataset.lowAlert === "true" && stockOf() <= Math.max(product.lowStockThreshold, 1);
100
+ stock.dataset.out = out ? "true" : "false";
101
+ stock.dataset.low = low ? "true" : "false";
102
+ const text = stock.querySelector<HTMLElement>("[data-stock-text]");
103
+ if (text) text.textContent = out ? tr("product.soldOut") : low ? tr("product.lowStock", { count: stockOf() }) : tr("common.inStock");
104
+ }
105
+ all<HTMLButtonElement>("[data-add-to-cart], [data-checkout-submit]").forEach((button) => {
106
+ button.disabled = out;
107
+ });
108
+ if (qtyInput && product.trackInventory) qtyInput.max = String(Math.max(1, Math.min(100, stockOf())));
109
+ }
110
+
111
+ /** Tiles tied to another variant hide; a hidden choice falls back to the first tile shown. */
112
+ function showTiles() {
113
+ for (const tile of tiles) tile.hidden = Boolean(tile.dataset.variant) && tile.dataset.variant !== variant?.id;
114
+ if (tiles.length > 0 && !chosenTile()) {
115
+ const first = tiles.find((tile) => !tile.hidden)?.querySelector<HTMLInputElement>("input");
116
+ if (first) first.checked = true;
117
+ }
118
+ tiles.forEach((tile) => tile.classList.toggle("is-chosen", tile === chosenTile()));
119
+ }
120
+
121
+ /** What the chosen pieces cost at their own variants' prices; null until each piece is one that exists. */
122
+ function piecesPrice(): number | null {
123
+ if (pieces.length === 0) return null;
124
+ const matched = pieces.map((piece) => variantFor(product.variants, piece));
125
+ return matched.every(Boolean) ? matched.reduce((sum, match) => sum + match!.price, 0) : null;
126
+ }
127
+
128
+ /** Each tile's price at the chosen variant; the chosen tile at the variant of each of its pieces. */
129
+ function priceTiles() {
130
+ for (const tile of tiles) {
131
+ const offer = product.offers.find((candidate) => candidate.id === tile.dataset.offer);
132
+ if (tile.dataset.fixed === "true") continue;
133
+ const view = offer ? getOfferTierView(offer, price(), compare()) : null;
134
+ const ownPieces = tile === chosenTile() ? piecesPrice() : null;
135
+ const amount = ownPieces ?? (view ? view.price : price() * (Number(tile.dataset.quantity) || 1));
136
+ const crossed = view ? view.comparePrice : compare();
137
+ tile.querySelector<HTMLElement>("[data-tile-price]")!.textContent = money(amount);
138
+ const was = tile.querySelector<HTMLElement>("[data-tile-compare]");
139
+ if (was) {
140
+ was.hidden = !(crossed !== null && crossed > amount);
141
+ was.textContent = was.hidden ? "" : money(crossed!);
142
+ }
143
+ const save = tile.querySelector<HTMLElement>("[data-tile-save]");
144
+ if (save && view) {
145
+ save.hidden = view.savingsAmount <= 0;
146
+ save.textContent = save.hidden ? "" : tr("offer.saving", { amount: money(view.savingsAmount) });
147
+ }
148
+ }
149
+ }
150
+
151
+ /** A multi-piece tile on a product with options: one row of options per piece. */
152
+ function paintPieces() {
153
+ const tile = chosenTile();
154
+ const count = quantity();
155
+ const perPiece = Boolean(units && unitRows && unitTemplate && tile && count > 1 && !tile.dataset.variant);
156
+ if (units) units.hidden = !perPiece;
157
+ if (!perPiece || !unitRows || !unitTemplate) {
158
+ pieces = [];
159
+ touched.clear();
160
+ unitRows?.replaceChildren();
161
+ return;
162
+ }
163
+ pieces = Array.from({ length: count }, (_, index) => (touched.has(index) && pieces[index] ? pieces[index]! : { ...selection }));
164
+ unitRows.replaceChildren(
165
+ ...pieces.map((piece, index) => {
166
+ const row = unitTemplate.content.firstElementChild!.cloneNode(true) as HTMLElement;
167
+ row.querySelector<HTMLElement>("[data-offer-unit-label]")!.textContent = tr("offer.piece", { n: index + 1 });
168
+ const states = optionStates(catalog, piece);
169
+ row.querySelectorAll<HTMLButtonElement>("[data-unit-option]").forEach((button) => {
170
+ const name = button.dataset.unitOption ?? "";
171
+ const value = button.dataset.value ?? "";
172
+ const state = states[name]?.[value] ?? "unavailable";
173
+ button.dataset.state = state;
174
+ button.disabled = state === "unavailable";
175
+ button.setAttribute("aria-pressed", piece[name] === value ? "true" : "false");
176
+ button.addEventListener("click", () => {
177
+ const picked = pickOption(catalog, piece, name, value);
178
+ if (!picked.variant) return;
179
+ pieces[index] = picked.selection;
180
+ touched.add(index);
181
+ update();
182
+ });
183
+ });
184
+ return row;
185
+ }),
186
+ );
187
+ }
188
+
189
+ function writeFields() {
190
+ const tile = chosenTile();
191
+ setField("variantId", variant?.id ?? "");
192
+ setField("variantLabel", labelOf(variant?.variations));
193
+ setField("pricePerUnit", String(price()));
194
+ setField("quantity", String(quantity()));
195
+ setField("offerId", tile?.dataset.offer ?? "");
196
+ const selections = pieces
197
+ .map((piece) => variantFor(product.variants, piece))
198
+ .filter((match): match is NonNullable<typeof match> => match !== null)
199
+ .map((match) => ({ variantId: match.id, variantLabel: labelOf(match.variations) }));
200
+ setField("variantSelections", JSON.stringify(selections.length === pieces.length ? selections : []));
201
+ }
202
+
203
+ /** What the choice costs before the server answers: a tier's own price, else the unit price times the pieces. */
204
+ function estimate(): number {
205
+ const tile = chosenTile();
206
+ if (tile?.dataset.fixed === "true") return Number(tile.dataset.price) || price() * quantity();
207
+ const own = piecesPrice();
208
+ if (own !== null) return own;
209
+ const offer = product.offers.find((candidate) => candidate.id === tile?.dataset.offer);
210
+ return offer ? getOfferTierView(offer, price(), compare()).price : price() * quantity();
211
+ }
212
+
213
+ function update() {
214
+ paintOptions();
215
+ paintPrice();
216
+ showTiles();
217
+ paintPieces();
218
+ priceTiles();
219
+ paintStock();
220
+ writeFields();
221
+ if (mobileTotal) mobileTotal.textContent = money(estimate());
222
+ root.dispatchEvent(new CustomEvent(PRODUCT_CHANGE_EVENT, { bubbles: true }));
223
+ }
224
+
225
+ optionButtons.forEach((button) =>
226
+ button.addEventListener("click", () => {
227
+ const picked = pickOption(catalog, selection, button.dataset.option ?? "", button.dataset.value ?? "");
228
+ if (!picked.variant) return;
229
+ selection = { ...picked.selection };
230
+ variant = picked.variant;
231
+ if (variant.imageId) showImageId(variant.imageId);
232
+ update();
233
+ }),
234
+ );
235
+ tiles.forEach((tile) => tile.querySelector("input")?.addEventListener("change", () => {
236
+ touched.clear();
237
+ update();
238
+ }));
239
+ const step = (by: number) => {
240
+ if (!qtyInput) return;
241
+ qtyInput.value = String(Math.max(1, Math.min(Number(qtyInput.max) || 100, (Number(qtyInput.value) || 1) + by)));
242
+ update();
243
+ };
244
+ root.querySelector("[data-qty-minus]")?.addEventListener("click", () => step(-1));
245
+ root.querySelector("[data-qty-plus]")?.addEventListener("click", () => step(1));
246
+ qtyInput?.addEventListener("change", () => step(0));
247
+
248
+ root.addEventListener(ORDER_QUOTE_EVENT, (event) => {
249
+ const subtotal = (event as CustomEvent<{ subtotal: number }>).detail?.subtotal;
250
+ if (mobileTotal && Number.isFinite(subtotal)) mobileTotal.textContent = money(subtotal);
251
+ });
252
+
253
+ // ── Photos ──────────────────────────────────────────────────────────────
254
+ const track = root.querySelector<HTMLElement>("[data-gallery-track]");
255
+ const slides = all<HTMLElement>(".gallery__slide");
256
+ const thumbs = all<HTMLButtonElement>("[data-gallery-index]");
257
+ const counter = root.querySelector<HTMLElement>("[data-gallery-current]");
258
+ let current = 0;
259
+ const mark = (index: number) => {
260
+ current = index;
261
+ thumbs.forEach((thumb, at) => thumb.setAttribute("aria-current", at === index ? "true" : "false"));
262
+ if (counter) counter.textContent = String(index + 1);
263
+ };
264
+ const show = (index: number) => {
265
+ const slide = slides[(index + slides.length) % slides.length];
266
+ if (!slide) return;
267
+ const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
268
+ slide.scrollIntoView({ behavior: reduce ? "auto" : "smooth", block: "nearest", inline: "center" });
269
+ mark(slides.indexOf(slide));
270
+ };
271
+ function showImageId(imageId: string) {
272
+ const index = slides.findIndex((slide) => slide.dataset.imageId === imageId);
273
+ if (index >= 0) show(index);
274
+ }
275
+ if (track && slides.length > 1 && "IntersectionObserver" in window) {
276
+ const seen = new IntersectionObserver(
277
+ (entries) => {
278
+ for (const entry of entries) if (entry.isIntersecting) mark(slides.indexOf(entry.target as HTMLElement));
279
+ },
280
+ { root: track, threshold: 0.6 },
281
+ );
282
+ slides.forEach((slide) => seen.observe(slide));
283
+ }
284
+ thumbs.forEach((thumb) => thumb.addEventListener("click", () => show(Number(thumb.dataset.galleryIndex) || 0)));
285
+ root.querySelector("[data-gallery-prev]")?.addEventListener("click", () => show(current - 1));
286
+ root.querySelector("[data-gallery-next]")?.addEventListener("click", () => show(current + 1));
287
+ track?.addEventListener("keydown", (event) => {
288
+ const rtl = getComputedStyle(track).direction === "rtl";
289
+ if (event.key === "ArrowRight") show(current + (rtl ? -1 : 1));
290
+ else if (event.key === "ArrowLeft") show(current + (rtl ? 1 : -1));
291
+ else return;
292
+ event.preventDefault();
293
+ });
294
+
295
+ // ── The phone's sticky bar: away while any of the order form is on screen or above it ──
296
+ const form = root.querySelector<HTMLElement>("[data-order-scope]");
297
+ if (mobileBar && form && "IntersectionObserver" in window) {
298
+ new IntersectionObserver(([entry]) => {
299
+ if (!entry) return;
300
+ mobileBar.dataset.visible = entry.isIntersecting || entry.boundingClientRect.top < 0 ? "false" : "true";
301
+ }).observe(form);
302
+ }
303
+
304
+ update();
305
+ if (root.dataset.viewContent === "true") storefrontTracking().productViewed({ productId: product.id, price: price() });
306
+ });
@@ -0,0 +1,79 @@
1
+ import { storefrontPath, type CheckoutFormPolicy } from "@abcart/storefront";
2
+ import { formatMessage } from "@abcart/theme/messages";
3
+
4
+ interface PublicStoreConfig {
5
+ locale: string;
6
+ localeTag: string;
7
+ isRTL: boolean;
8
+ storeName: string;
9
+ currency: string;
10
+ symbol: string;
11
+ cartEnabled: boolean;
12
+ freeShippingThreshold: number | null;
13
+ otpEnabled: boolean;
14
+ turnstileEnabled: boolean;
15
+ turnstileSiteKey: string | null;
16
+ checkoutForm: CheckoutFormPolicy;
17
+ reviewsEnabled: boolean;
18
+ routes: {
19
+ checkout: string;
20
+ catalog: string;
21
+ search: string;
22
+ thankYou: string;
23
+ };
24
+ content: Record<string, string>;
25
+ }
26
+
27
+ let cached: PublicStoreConfig | null = null;
28
+
29
+ export function readPublicConfig(): PublicStoreConfig {
30
+ if (cached) return cached;
31
+ const element = document.getElementById("wocart-public");
32
+ cached = element?.textContent ? (JSON.parse(element.textContent) as PublicStoreConfig) : fallback();
33
+ return cached;
34
+ }
35
+
36
+ function fallback(): PublicStoreConfig {
37
+ return {
38
+ locale: "en",
39
+ localeTag: "en-DZ",
40
+ isRTL: false,
41
+ storeName: "Store",
42
+ currency: "DZD",
43
+ symbol: "DZD",
44
+ cartEnabled: false,
45
+ freeShippingThreshold: null,
46
+ otpEnabled: false,
47
+ turnstileEnabled: false,
48
+ turnstileSiteKey: null,
49
+ reviewsEnabled: false,
50
+ checkoutForm: {
51
+ address: "required",
52
+ notes: "optional",
53
+ email: "hidden",
54
+ deliveryOptions: { home: true, stopDesk: true },
55
+ customFields: [],
56
+ },
57
+ routes: {
58
+ checkout: storefrontPath("checkout"),
59
+ catalog: storefrontPath("catalog"),
60
+ search: storefrontPath("search"),
61
+ thankYou: storefrontPath("thankYou"),
62
+ },
63
+ content: {},
64
+ };
65
+ }
66
+
67
+ /** A message from the copy the page embeds, its plural form chosen by `count` and its numbers written for the language. */
68
+ export function translate(config: PublicStoreConfig, key: string, values?: Record<string, string | number>): string {
69
+ return formatMessage(config.content, key, values, { locale: config.localeTag });
70
+ }
71
+
72
+ export function escapeHtml(value: string): string {
73
+ return value
74
+ .replaceAll("&", "&amp;")
75
+ .replaceAll("<", "&lt;")
76
+ .replaceAll(">", "&gt;")
77
+ .replaceAll('"', "&quot;")
78
+ .replaceAll("'", "&#39;");
79
+ }