metatroncubeswdev 1262e0f5ab
Some checks failed
CI / Lint, Unit & Integration Tests (push) Has been cancelled
feat: cross-theme cart placement for the storefront widget
Many themes only expose "Add section" for the cart's checkout area, not
"Add block" next to the actual Checkout button — Shopify gives apps no
supported way to inject a block into an arbitrary spot in a theme's own
section markup, so a manually-placed app block can only ever land as a
disconnected standalone section on those themes.

Add a JS-based fallback via the app embed (already loaded site-wide,
independent of block placement): app-embed.liquid now carries the same
config settings as the block plus an "auto-place on cart page" toggle
(default on), emitted as an inert <template> with the widget's config as
data-* attributes. datetime-widget.ts's maybeAutoPlaceOnCart() finds the
theme's own Checkout button by CSS selector (a few common patterns, most
specific first) and inserts a live widget immediately before it — skipped
entirely if a block-placed widget already exists on the page, or no
Checkout button can be found by any known selector.

Also fix shopify.app.toml: automatically_update_urls_on_dev was left on
after the app got a real, permanent production domain
(metatron-delivery.thedomainnest.com) — leaving it on meant a future local
`shopify app dev` session would silently overwrite the live app's
application_url with a temporary Cloudflare tunnel, breaking the deployed
app until someone noticed and redeployed with the real URL.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-03 18:19:59 -04:00

2 lines
11 KiB
JavaScript

"use strict";(()=>{var E=Object.defineProperty;var S=(i,t,e)=>t in i?E(i,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):i[t]=e;var l=(i,t,e)=>S(i,typeof t!="symbol"?t+"":t,e);var M="/apps/scheduling";function y(i){let t=Math.floor(i/60),e=i%60,n=t<12?"AM":"PM";return`${t%12===0?12:t%12}:${e.toString().padStart(2,"0")} ${n}`}function m(i){return h(i.slice(0,10))}function b(i){return i.arrivalRangeStart&&i.arrivalRangeEnd?`Arrives ${m(i.arrivalRangeStart)}\u2013${m(i.arrivalRangeEnd)}`:i.arrivalRangeStart?`Arrives from ${m(i.arrivalRangeStart)}`:i.arrivalRangeEnd?`Arrives by ${m(i.arrivalRangeEnd)}`:`${y(i.startMin)}\u2013${y(i.endMin)}`}function h(i){let[t,e,n]=i.split("-").map(Number);return new Date(Date.UTC(t,e-1,n)).toLocaleDateString(void 0,{weekday:"short",month:"short",day:"numeric",timeZone:"UTC"})}function _(i){let t=i.dataset,e=[];return t.showShipping==="true"&&e.push({value:"SHIPPING",label:t.labelShipping||"Shipping",attrLabel:t.attrLabelShipping||"Shipping date"}),t.showLocalDelivery==="true"&&e.push({value:"LOCAL_DELIVERY",label:t.labelLocalDelivery||"Local delivery",attrLabel:t.attrLabelLocalDelivery||"Delivery date"}),t.showPickup==="true"&&e.push({value:"PICKUP",label:t.labelPickup||"Pickup",attrLabel:t.attrLabelPickup||"Pickup date"}),{root:i,heading:t.heading||"",locationId:t.locationId||null,googleMapsApiKey:t.googleMapsApiKey||null,methods:e,labels:{chooseDate:t.labelChooseDate||"Choose a date",chooseTime:t.labelChooseTime||"Choose a time",noDates:t.labelNoDates||"No dates are available right now.",confirmed:t.labelConfirmed||"Confirmed for",change:t.labelChange||"Change",loading:t.labelLoading||"Loading available dates\u2026",error:t.labelError||"Couldn't load available dates. Please try again.",postalCodeLabel:t.labelPostalCode||"Enter your postal/ZIP code",postalCodeSubmit:t.labelPostalCodeSubmit||"Check availability",outOfArea:t.labelOutOfArea||"Sorry, we don't deliver to this address."}}}async function C(){var e;let t=await(await fetch("/cart.js",{headers:{Accept:"application/json"}})).json();return{token:t.token,lines:((e=t.items)!=null?e:[]).map(n=>{var a,o;return{vendor:(a=n.vendor)!=null?a:"",productType:(o=n.product_type)!=null?o:"",productId:`gid://shopify/Product/${n.product_id}`}})}}async function k(i,t,e,n){let a=new URLSearchParams({method:i,days:"14"});t&&a.set("locationId",t),n&&a.set("postalCode",n),e.lines.length>0&&(a.set("cartLines",JSON.stringify(e.lines.map(s=>({vendor:s.vendor,productType:s.productType})))),a.set("productIds",e.lines.map(s=>s.productId).join(",")));let o=await fetch(`${M}/availability?${a.toString()}`,{headers:{Accept:"application/json"}}),r=await o.json();if(!o.ok)throw new Error(r.error||`Request failed (${o.status})`);return r}async function L(i){let t=await fetch(`${M}/hold`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(i)}),e=await t.json();return!t.ok&&i.intent==="create"?{success:!1,error:e.error||"Slot unavailable"}:e}async function A(i,t,e){await fetch("/cart/update.js",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({attributes:{[i]:e,...t}})})}var p=null;function I(i){return p||(p=new Promise((t,e)=>{let n="__ddMapsReady";window[n]=()=>t();let a=document.createElement("script");a.src=`https://maps.googleapis.com/maps/api/js?key=${encodeURIComponent(i)}&callback=${n}`,a.async=!0,a.onerror=()=>e(new Error("Failed to load Google Maps")),document.head.appendChild(a)}),p)}async function T(i,t,e,n,a){try{await I(t);let o=window.google,r=new o.maps.Map(i,{center:{lat:e,lng:n},zoom:13});new o.maps.Marker({position:{lat:e,lng:n},map:r,title:a})}catch{i.hidden=!0}}var f=class{constructor(t){l(this,"config");l(this,"el",{heading:document.createElement("h3"),methodRow:document.createElement("div"),postalRow:document.createElement("div"),mapContainer:document.createElement("div"),dateRow:document.createElement("div"),timeRow:document.createElement("div"),status:document.createElement("p"),confirmation:document.createElement("div")});l(this,"selectedMethod",null);l(this,"selectedDate",null);l(this,"availability",null);l(this,"heldSlot",null);this.config=t}mount(){let{root:t,heading:e,methods:n}=this.config;t.classList.add("dd-widget--ready"),t.innerHTML="",n.length!==0&&(e&&(this.el.heading.className="dd-widget__heading",this.el.heading.textContent=e,t.appendChild(this.el.heading)),this.el.methodRow.className="dd-widget__row dd-widget__methods",this.el.postalRow.className="dd-widget__row dd-widget__postal",this.el.postalRow.hidden=!0,this.el.mapContainer.className="dd-widget__map",this.el.mapContainer.hidden=!0,this.el.dateRow.className="dd-widget__row dd-widget__dates",this.el.timeRow.className="dd-widget__row dd-widget__times",this.el.status.className="dd-widget__status",this.el.confirmation.className="dd-widget__confirmation",this.el.confirmation.hidden=!0,t.append(this.el.confirmation,this.el.methodRow,this.el.postalRow,this.el.mapContainer,this.el.dateRow,this.el.timeRow,this.el.status),n.length===1?this.selectMethod(n[0]):this.renderMethods())}renderMethods(){var t;this.el.methodRow.innerHTML="";for(let e of this.config.methods){let n=document.createElement("button");n.type="button",n.className="dd-widget__pill",n.textContent=e.label,n.setAttribute("aria-pressed",String(((t=this.selectedMethod)==null?void 0:t.value)===e.value)),n.addEventListener("click",()=>this.selectMethod(e)),this.el.methodRow.appendChild(n)}}async selectMethod(t){if(this.selectedMethod=t,this.selectedDate=null,this.el.timeRow.innerHTML="",this.el.dateRow.innerHTML="",this.el.mapContainer.hidden=!0,this.el.confirmation.hidden=!1,this.el.confirmation.hidden=!0,this.config.methods.length>1&&this.renderMethods(),t.value==="LOCAL_DELIVERY"){this.renderPostalCodeInput(t);return}this.el.postalRow.hidden=!0,await this.loadAvailability(t)}renderPostalCodeInput(t){this.el.postalRow.hidden=!1,this.el.postalRow.innerHTML="",this.el.status.textContent="";let e=document.createElement("input");e.type="text",e.className="dd-widget__input",e.placeholder=this.config.labels.postalCodeLabel,e.setAttribute("aria-label",this.config.labels.postalCodeLabel);let n=document.createElement("button");n.type="button",n.className="dd-widget__pill",n.textContent=this.config.labels.postalCodeSubmit,n.addEventListener("click",async()=>{let a=e.value.trim();a&&await this.loadAvailability(t,a)}),e.addEventListener("keydown",a=>{a.key==="Enter"&&n.click()}),this.el.postalRow.append(e,n)}async loadAvailability(t,e){this.el.status.textContent=this.config.labels.loading,this.el.dateRow.innerHTML="";try{let n=await C();if(this.availability=await k(t.value,this.config.locationId,n,e),!this.availability.locationId){this.el.status.textContent=this.availability.error||this.config.labels.outOfArea;return}t.value==="PICKUP"&&this.config.googleMapsApiKey&&this.showPickupMap(),this.renderDates()}catch{this.el.status.textContent=this.config.labels.error}}showPickupMap(){var e;let t=this.availability;!(t!=null&&t.locationLat)||!(t!=null&&t.locationLng)||!this.config.googleMapsApiKey||(this.el.mapContainer.hidden=!1,T(this.el.mapContainer,this.config.googleMapsApiKey,t.locationLat,t.locationLng,(e=t.locationName)!=null?e:""))}renderDates(){var e,n;let t=Object.keys((n=(e=this.availability)==null?void 0:e.dates)!=null?n:{}).sort();if(this.el.dateRow.innerHTML="",t.length===0){this.el.status.textContent=this.config.labels.noDates;return}this.el.status.textContent=this.config.labels.chooseDate;for(let a of t){let o=document.createElement("button");o.type="button",o.className="dd-widget__pill",o.textContent=h(a),o.setAttribute("aria-pressed",String(this.selectedDate===a)),o.addEventListener("click",()=>this.selectDate(a)),this.el.dateRow.appendChild(o)}}selectDate(t){var n,a;this.selectedDate=t;for(let o of Array.from(this.el.dateRow.children))o.setAttribute("aria-pressed",String(o.textContent===h(t)));let e=(a=(n=this.availability)==null?void 0:n.dates[t])!=null?a:[];this.el.timeRow.innerHTML="",this.el.status.textContent=this.config.labels.chooseTime;for(let o of e){let r=document.createElement("button");r.type="button",r.className="dd-widget__pill",r.textContent=b(o),r.addEventListener("click",()=>this.selectSlot(t,o)),this.el.timeRow.appendChild(r)}}async selectSlot(t,e){var s;let n=this.selectedMethod,a=this.availability,o=a.rate?` (${a.rate.label})`:"",r=e.arrivalRangeStart||e.arrivalRangeEnd?`Ships ${h(t)}, ${b(e)}${o}`:`${h(t)}, ${b(e)}${o}`;this.el.status.textContent=this.config.labels.loading;try{let u=await C(),w=await L({intent:"create",locationId:a.locationId,method:n.value,date:t,startMin:e.startMin,cartToken:u.token,cartLines:u.lines.map(g=>({vendor:g.vendor,productType:g.productType})),productIds:u.lines.map(g=>g.productId)});if(!w.success){this.el.status.textContent=w.error||this.config.labels.error,await this.selectMethod(n);return}this.heldSlot={locationId:a.locationId,method:n.value,date:t,startMin:e.startMin,cartToken:u.token,zoneId:(s=a.zoneId)!=null?s:null};let d={dd_method:n.value,dd_date:t,dd_start_min:String(e.startMin),dd_end_min:String(e.endMin),dd_location_id:a.locationId};a.zoneId&&(d.dd_zone_id=a.zoneId),a.rate&&(d.dd_rate_label=a.rate.label),e.arrivalRangeStart&&(d.dd_arrival_range_start=e.arrivalRangeStart),e.arrivalRangeEnd&&(d.dd_arrival_range_end=e.arrivalRangeEnd),await A(n.attrLabel,d,r),this.el.status.textContent="",this.el.methodRow.hidden=!0,this.el.postalRow.hidden=!0,this.el.mapContainer.hidden=!0,this.el.dateRow.hidden=!0,this.el.timeRow.hidden=!0,this.el.confirmation.hidden=!1,this.el.confirmation.innerHTML="";let v=document.createElement("p");v.textContent=`${this.config.labels.confirmed} ${r}`;let c=document.createElement("button");c.type="button",c.className="dd-widget__link",c.textContent=this.config.labels.change,c.addEventListener("click",()=>{this.heldSlot&&(L({intent:"release",...this.heldSlot}),this.heldSlot=null),this.el.methodRow.hidden=!1,this.el.dateRow.hidden=!1,this.el.timeRow.hidden=!1,this.el.confirmation.hidden=!0}),this.el.confirmation.append(v,c)}catch{this.el.status.textContent=this.config.labels.error}}},P=['form[action*="/cart"] button[name="checkout"]','form[action*="/cart"] input[name="checkout"]','[name="checkout"]',"#checkout",'a[href="/checkout"]'];function D(){for(let i of P){let t=document.querySelector(i);if(t)return t}return null}function N(){return window.location.pathname.replace(/\/+$/,"").endsWith("/cart")}function $(){if(!N()||document.querySelector("[data-dd-widget]"))return;let i=document.getElementById("dd-widget-cart-template");if(!i)return;let t=D();if(!t)return;let e=document.createElement("div");e.setAttribute("data-dd-widget",""),e.classList.add("dd-widget--cart-injected");for(let n of Array.from(i.attributes))n.name!=="id"&&e.setAttribute(n.name,n.value);t.insertAdjacentElement("beforebegin",e),new f(_(e)).mount()}function R(){document.querySelectorAll("[data-dd-widget]").forEach(t=>{new f(_(t)).mount()}),$()}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",R):R();})();