@beneviasoftware/storefront 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.txt ADDED
@@ -0,0 +1,13 @@
1
+ Copyright (c) Benevia Software. All rights reserved.
2
+
3
+ This software is proprietary and confidential.
4
+
5
+ No right to use, copy, modify, distribute, sublicense, publish, or create derivative works
6
+ from this software is granted except under a separate written license agreement from
7
+ Benevia Software.
8
+
9
+ If you wish to evaluate, license, or otherwise use this software, contact:
10
+ info@benevia.software
11
+
12
+ Any use of this software without an applicable written license agreement from Benevia
13
+ Software is prohibited.
package/README.md CHANGED
@@ -1,3 +1,195 @@
1
- # Temporary Holding Version
1
+ # @beneviasoftware/storefront
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Web components that sell from a Benevia store's live availability. They work on any site, static or not, with or
4
+ without a framework. The site supplies the look.
5
+
6
+ ## Use it on a site
7
+
8
+ Load the package once, then place a picker for each listing (and a grid of them on the shop page):
9
+
10
+ ```html
11
+ <script type="module" src="https://cdn.jsdelivr.net/npm/@beneviasoftware/storefront@0.0.1/dist/storefront.js"></script>
12
+
13
+ <benevia-product-picker
14
+ api-url="https://api.example.com"
15
+ store-key="YOUR-STORE-KEY"
16
+ listing="RH"
17
+ date-label="Hatch date">
18
+ </benevia-product-picker>
19
+ ```
20
+
21
+ unpkg works the same way: `https://unpkg.com/@beneviasoftware/storefront@0.0.1/dist/storefront.js`.
22
+ With a bundler, `npm install @beneviasoftware/storefront` and `import '@beneviasoftware/storefront';`.
23
+
24
+ ## `<benevia-product-picker>`
25
+
26
+ Shows one listing: its options and prices, the dates with how many are left, a quantity, and "Add to cart".
27
+ It calls `GET {api-url}/api/storefront/{store-key}/listings/{listing}`, which has the listing's availability. Components on
28
+ one page that ask for the same listing within 30 seconds share one request, as long as the API caches it. `GET …/listings` is the catalog: every listing with its prices,
29
+ without availability.
30
+
31
+ | Attribute | Required | Meaning |
32
+ |---|---|---|
33
+ | `api-url` | yes | Benevia API base URL. |
34
+ | `store-key` | yes | The store's key. The API only answers origins listed for that key. |
35
+ | `listing` | yes¹ | The listing `id` to show. |
36
+ | `listing-param` | no | ¹Instead of `listing`, read the id from this query parameter of the page's URL, so one page shows any listing: `<benevia-product-picker listing-param="listing">` on `breed.html?listing=RH`. A URL without it shows "This item is not available." |
37
+ | `option-label` | no | Heading for the options. Default `Option`. |
38
+ | `date-label` | no | Heading for the dates, for example `Hatch date`. Default `Date`. |
39
+
40
+ While it loads, the picker shows placeholders in its own shape, so the page doesn't jump when it fills in.
41
+ Counts of 1,000 or more read as "1,000+ left". Sold-out dates are crossed out and can't be picked. Quantity stays
42
+ between 1 and the count left on the chosen date. Dates and prices follow the `lang` of the nearest element that has
43
+ one, so set `<html lang="en-US">`.
44
+
45
+ ### Add to cart
46
+
47
+ "Add to cart" puts the line in the cart for the picker's `store-key` (see `<benevia-cart>`) and fires
48
+ `benevia-add-to-cart` (bubbles, crosses the shadow root), for sites that want to react:
49
+
50
+ ```js
51
+ document.addEventListener('benevia-add-to-cart', event => {
52
+ const { listingId, optionId, date, quantity, unitPrice, currency } = event.detail;
53
+ });
54
+ ```
55
+
56
+ ### Styling
57
+
58
+ The picker inherits the page's font and text color. Set these custom properties on it or any parent:
59
+
60
+ | Property | Default |
61
+ |---|---|
62
+ | `--benevia-font-family` | inherited |
63
+ | `--benevia-color-text` | inherited |
64
+ | `--benevia-color-muted` | `#66665f` |
65
+ | `--benevia-color-accent` | `#2f6b3a` (selected choice, button) |
66
+ | `--benevia-color-accent-text` | `#fff` |
67
+ | `--benevia-color-border` | `#c9c9c2` |
68
+ | `--benevia-color-surface` | `transparent` (choices, quantity) |
69
+ | `--benevia-color-sold-out` | muted color |
70
+ | `--benevia-color-error` | `#a3261b` |
71
+ | `--benevia-color-focus` | accent color |
72
+ | `--benevia-radius` | `6px` |
73
+ | `--benevia-spacing` | `1rem` |
74
+
75
+ For anything else, style these parts with `::part()`:
76
+
77
+ | Part | Element |
78
+ |---|---|
79
+ | `picker` | the outer container |
80
+ | `name`, `description` | listing name and description |
81
+ | `options`, `dates` | the option and date groups |
82
+ | `option`, `date` | each choice; `count` is the "left" text on a date |
83
+ | `option-selected`, `date-selected` | the chosen option and date |
84
+ | `option-sold-out`, `date-sold-out` | sold-out choices |
85
+ | `option-name` | the option line when a listing has only one option |
86
+ | `quantity`, `quantity-label`, `quantity-input` | the quantity field |
87
+ | `price`, `total`, `price-breaks` | unit price, line total, and the "25 or more" list |
88
+ | `add-button` | the "Add to cart" button |
89
+ | `status` | loading, error and "Added" messages; also `loading` or `error` |
90
+ | `empty` | "No dates are open yet." |
91
+
92
+ ```css
93
+ benevia-product-picker {
94
+ --benevia-color-accent: #8a3b12;
95
+ --benevia-radius: 999px;
96
+ }
97
+ benevia-product-picker::part(add-button) {
98
+ text-transform: uppercase;
99
+ }
100
+ ```
101
+
102
+ ## `<benevia-product-grid>`
103
+
104
+ The store's catalog: a card for each listing with its image, name and "From $X each" (the lowest price of any option
105
+ and quantity). Each card links to the site's page for that listing, where a picker shows its dates and counts. It calls
106
+ `GET …/listings` once, without availability, so it stays quick for a store with 70 or more listings.
107
+
108
+ ```html
109
+ <benevia-product-grid
110
+ api-url="https://api.example.com"
111
+ store-key="YOUR-STORE-KEY"
112
+ listing-href="breed.html?listing={id}">
113
+ </benevia-product-grid>
114
+ ```
115
+
116
+ With 70 breeds, one page that shows any listing (a picker with `listing-param="listing"`) saves writing a page per
117
+ breed.
118
+
119
+ | Attribute | Required | Meaning |
120
+ |---|---|---|
121
+ | `api-url`, `store-key` | yes | Same as the picker. |
122
+ | `listing-href` | yes | Each card's link. `{id}` becomes the listing id (`breed.html?listing={id}`). `{slug}` becomes the listing name in lowercase words joined by `-` (`Rhode Island Red` → `rhode-island-red`), for a page per listing; renaming the listing in Benevia changes its slug. |
123
+ | `category` | no | Show only listings in this category. Several grids on a page share one request. |
124
+
125
+ While the catalog loads, the grid shows placeholder cards (part `card-loading`) to hold the space.
126
+ Images load lazily and keep a fixed shape, so cards line up and nothing jumps while they load. A listing without an
127
+ image gets an empty box in its place (part `image-placeholder`); give it a background to show a stand-in.
128
+
129
+ Styling uses the same custom properties as the picker, plus `--benevia-card-width` (narrowest a column gets,
130
+ default `10rem`, which fits two columns on a phone) and `--benevia-image-aspect-ratio` (default `1`).
131
+ Parts: `grid`, `list`, `card`, `card-loading`, `image`, `image-placeholder`, `name`, `price`, `empty`, `status`.
132
+
133
+ ## `<benevia-cart>`
134
+
135
+ A cart button with the item count. It opens a drawer with the cart's lines grouped by date: quantity (up to the
136
+ count left), unit price at that quantity, line total, remove, the subtotal, and "Checkout".
137
+
138
+ ```html
139
+ <benevia-cart api-url="https://api.example.com" store-key="YOUR-STORE-KEY" date-label="Hatch date">
140
+ Cart
141
+ <p slot="footer">We'll confirm your order by phone.</p>
142
+ </benevia-cart>
143
+ ```
144
+
145
+ | Attribute | Required | Meaning |
146
+ |---|---|---|
147
+ | `api-url`, `store-key` | yes | Same as the picker. The cart reads names, prices and counts from each listing in it. |
148
+ | `date-label` | no | Shown before each date group. Default `Date`. |
149
+
150
+ The element's content is the button label (`Cart` when empty), so a site can use its own icon. The `footer` slot
151
+ goes under the subtotal.
152
+
153
+ The cart is kept in the browser's `localStorage` per store key, so it lasts across pages and visits and is shared
154
+ between tabs. When storage is blocked it lasts until the page closes. Each line is priced at its own quantity.
155
+ Lines whose date is gone or sold out move to "No longer available" and are left out of the subtotal. A line above
156
+ the count left says so (part `line-note`); checkout won't place it until it fits.
157
+
158
+ "Checkout" shows when the API has a checkout page (`store.checkoutUrl` in the listings). It sends the shopper there
159
+ with the available lines in the address (`checkout-link.ts`); nothing is saved until the shopper places the order.
160
+ Checking out the same lines again reuses the checkout, so placing from an older tab finds the same order; other
161
+ lines get a new one. When the cart loads, comes back with Back, opens, or checks out, it asks whether that checkout
162
+ was placed, and takes its lines out if so. Lines added since stay in the cart.
163
+
164
+ Styling uses the same custom properties as the picker, plus `--benevia-color-drawer` (drawer background, default
165
+ `#fff`). Parts: `button`, `count`, `drawer`, `title`, `close`, `date-group`, `date-heading`, `line`,
166
+ `line-unavailable`, `line-name`, `line-note`, `quantity-input`, `unit-price`, `line-total`, `remove`, `subtotal`, `checkout`,
167
+ `empty`, `status`.
168
+
169
+ ## Preview mode
170
+
171
+ Set `api-url="preview"` and the components answer from the sample store in `fixtures/listings.json` instead of an
172
+ API, with a "Preview data" badge on screen. Its dates move by whole weeks so the first one is next week. "Checkout"
173
+ shows the lines it would send instead of opening the checkout page, so nothing is ordered. Sites use it everywhere
174
+ except their live address, such as on pull request preview links: the API refuses origins the store key doesn't
175
+ list, and preview links are public. The sample data is its own file, loaded only in preview mode.
176
+
177
+ ## Publish
178
+
179
+ `.github/workflows/storefront-publish.yml` publishes the version in `package.json`. Raise the version, merge, then
180
+ push a tag `storefront-v<version>` on that commit (or run the workflow by hand, which is a dry run unless you untick
181
+ it). A published version can't be changed, so a fix is a new version. Sites pin an exact version and move to the new
182
+ one in a pull request.
183
+
184
+ ## Develop
185
+
186
+ ```bash
187
+ npm install
188
+ npm run dev # dev page at http://localhost:5173, served from fixtures/listings.json
189
+ npm test # runs the tests in Tests/storefront
190
+ npm run build # dist/storefront.js
191
+ ```
192
+
193
+ `fixtures/listings.json` is the listings contract the API, these components and the demo site share. Change it first
194
+ and tell the other tracks. `fixtures/api.ts` answers both calls from it the way the API does, for the dev page and the
195
+ tests.
@@ -0,0 +1,149 @@
1
+ var e = {
2
+ store: {
3
+ name: "Demo Hatchery",
4
+ currency: "USD",
5
+ checkoutUrl: "https://checkout.example.com"
6
+ },
7
+ listings: [{
8
+ id: "RH",
9
+ name: "Rhode Island Red",
10
+ description: "Hardy brown egg layers. Calm and good for beginners.",
11
+ category: "Chickens",
12
+ imageUrl: null,
13
+ options: [
14
+ {
15
+ id: "RHF",
16
+ name: "Pullets",
17
+ prices: [{
18
+ minQuantity: 1,
19
+ unitPrice: 4.75
20
+ }, {
21
+ minQuantity: 25,
22
+ unitPrice: 4.25
23
+ }],
24
+ availability: [
25
+ {
26
+ date: "2027-03-02",
27
+ available: 140
28
+ },
29
+ {
30
+ date: "2027-03-09",
31
+ available: 0
32
+ },
33
+ {
34
+ date: "2027-03-16",
35
+ available: 1200
36
+ }
37
+ ]
38
+ },
39
+ {
40
+ id: "RHM",
41
+ name: "Cockerels",
42
+ prices: [{
43
+ minQuantity: 1,
44
+ unitPrice: 1.95
45
+ }],
46
+ availability: [{
47
+ date: "2027-03-02",
48
+ available: 60
49
+ }, {
50
+ date: "2027-03-16",
51
+ available: 300
52
+ }]
53
+ },
54
+ {
55
+ id: "RHS",
56
+ name: "Straight run",
57
+ prices: [{
58
+ minQuantity: 1,
59
+ unitPrice: 3.25
60
+ }, {
61
+ minQuantity: 25,
62
+ unitPrice: 2.95
63
+ }],
64
+ availability: [{
65
+ date: "2027-03-02",
66
+ available: 3
67
+ }, {
68
+ date: "2027-03-09",
69
+ available: 85
70
+ }]
71
+ }
72
+ ]
73
+ }, {
74
+ id: "BR",
75
+ name: "Barred Rock",
76
+ description: "Dependable brown egg layers with black and white barred feathers.",
77
+ category: "Chickens",
78
+ imageUrl: null,
79
+ options: [{
80
+ id: "BRF",
81
+ name: "Pullets",
82
+ prices: [{
83
+ minQuantity: 1,
84
+ unitPrice: 5.25
85
+ }],
86
+ availability: [{
87
+ date: "2027-03-04",
88
+ available: 0
89
+ }, {
90
+ date: "2027-03-11",
91
+ available: 48
92
+ }]
93
+ }, {
94
+ id: "BRS",
95
+ name: "Straight run",
96
+ prices: [{
97
+ minQuantity: 1,
98
+ unitPrice: 3.5
99
+ }],
100
+ availability: [{
101
+ date: "2027-03-04",
102
+ available: 22
103
+ }, {
104
+ date: "2027-03-11",
105
+ available: 90
106
+ }]
107
+ }]
108
+ }]
109
+ };
110
+ // fixtures/api.ts
111
+ function t(t) {
112
+ let n = /^\/api\/storefront\/[^/]+\/listings(?:\/([^/?]+))?\/?(?:\?.*)?$/.exec(t);
113
+ if (!n) return;
114
+ let r = n[1] && decodeURIComponent(n[1]);
115
+ if (!r) {
116
+ let t = e.listings.map((e) => ({
117
+ ...e,
118
+ options: e.options.map((e) => ({
119
+ ...e,
120
+ availability: null
121
+ }))
122
+ }));
123
+ return {
124
+ store: e.store,
125
+ listings: t
126
+ };
127
+ }
128
+ let i = e.listings.find((e) => e.id === r);
129
+ return i ? {
130
+ store: e.store,
131
+ listing: i
132
+ } : null;
133
+ }
134
+ // fixtures/preview.ts
135
+ var n = 864e5;
136
+ function r(e, n = /* @__PURE__ */ new Date()) {
137
+ let r = t(e);
138
+ if (!r) return null;
139
+ let o = i(n);
140
+ return JSON.parse(JSON.stringify(r), (e, t) => e === "date" && typeof t == "string" ? a(t, o) : t);
141
+ }
142
+ function i(t) {
143
+ let r = e.listings.flatMap((e) => e.options.flatMap((e) => e.availability?.map((e) => e.date) ?? [])).reduce((e, t) => t < e ? t : e), i = Date.UTC(t.getFullYear(), t.getMonth(), t.getDate()) + 7 * n;
144
+ return Math.ceil((i - Date.parse(r)) / (7 * n)) * 7;
145
+ }
146
+ function a(e, t) {
147
+ return new Date(Date.parse(e) + t * n).toISOString().slice(0, 10);
148
+ }
149
+ export { r as previewResponse };
@@ -0,0 +1,971 @@
1
+ function e(e, t) {
2
+ let n = [...e].sort((e, t) => e.minQuantity - t.minQuantity);
3
+ return (n.filter((e) => e.minQuantity <= t).at(-1) ?? n[0])?.unitPrice;
4
+ }
5
+ function t(e) {
6
+ if (e.length !== 0) return Math.min(...e.map((e) => e.unitPrice));
7
+ }
8
+ function n(e, t) {
9
+ if (e <= 0) return "Sold out";
10
+ let n = new Intl.NumberFormat(t);
11
+ return e >= 1e3 ? `${n.format(1e3)}+ left` : `${n.format(e)} left`;
12
+ }
13
+ function r(e, t, n = /* @__PURE__ */ new Date()) {
14
+ let r = /* @__PURE__ */ new Date(`${e}T00:00:00Z`), i = r.getUTCFullYear() !== n.getFullYear();
15
+ return new Intl.DateTimeFormat(t, {
16
+ weekday: "short",
17
+ month: "short",
18
+ day: "numeric",
19
+ year: i ? "numeric" : void 0,
20
+ timeZone: "UTC"
21
+ }).format(r);
22
+ }
23
+ function i(e, t, n) {
24
+ return new Intl.NumberFormat(n, {
25
+ style: "currency",
26
+ currency: t
27
+ }).format(e);
28
+ }
29
+ function a(e, t) {
30
+ return Math.min(Math.max(Number.isFinite(e) ? Math.floor(e) : 1, 1), Math.max(t, 1));
31
+ }
32
+ function o(e) {
33
+ return e.find((e) => e.available > 0);
34
+ }
35
+ function s(e) {
36
+ return o(e.availability ?? []) === void 0;
37
+ }
38
+ function c(e) {
39
+ return e === "preview";
40
+ }
41
+ async function l(e) {
42
+ u();
43
+ let { previewResponse: t } = await import("./preview-MEVRl0nS.js");
44
+ return t(e.slice(7));
45
+ }
46
+ function u() {
47
+ if (document.getElementById("benevia-preview-badge")) return;
48
+ let e = document.createElement("div");
49
+ e.id = "benevia-preview-badge", e.textContent = "Preview data", e.title = "This page shows sample data, not the store's live prices and dates.", e.style.cssText = "position: fixed;inset-inline-start: 0.75rem;inset-block-end: 0.75rem;z-index: 2147483647;padding: 0.25rem 0.75rem;border-radius: 999px;background: #7a4b00;color: #fff;font: 600 0.8125rem/1.5 system-ui, sans-serif;pointer-events: none", document.body.append(e);
50
+ }
51
+ // listings.ts
52
+ var d = /* @__PURE__ */ new Map();
53
+ function f(e, t) {
54
+ return _(m(e, t));
55
+ }
56
+ function p(e, t, n) {
57
+ return _(`${m(e, t)}/${encodeURIComponent(n)}`);
58
+ }
59
+ function m(e, t) {
60
+ return `${h(e, t)}/listings`;
61
+ }
62
+ function h(e, t) {
63
+ return `${e.replace(/\/+$/, "")}/api/storefront/${encodeURIComponent(t)}`;
64
+ }
65
+ function g(e, t, n) {
66
+ return `${h(e, t)}/checkouts/${encodeURIComponent(n)}`;
67
+ }
68
+ function _(e) {
69
+ let t = d.get(e);
70
+ if (t && t.expires > Date.now()) return t.request;
71
+ let n = v(e);
72
+ return n.catch(() => {
73
+ d.get(e)?.request === n && d.delete(e);
74
+ }), d.set(e, {
75
+ request: n,
76
+ expires: Date.now() + 3e4
77
+ }), n;
78
+ }
79
+ async function v(e) {
80
+ if (e.startsWith("preview/")) return l(e);
81
+ let t = await fetch(e, { headers: { Accept: "application/json" } });
82
+ if (t.status === 404) return null;
83
+ if (!t.ok) throw Error(`Request failed: ${t.status} ${t.statusText} (${e})`);
84
+ return t.json();
85
+ }
86
+ // dom.ts
87
+ function y(e, t, ...n) {
88
+ let r = document.createElement(e);
89
+ for (let [e, n] of Object.entries(t)) n === !0 ? r.setAttribute(e, "") : n !== !1 && r.setAttribute(e, n);
90
+ return r.append(...b(...n)), r;
91
+ }
92
+ function b(...e) {
93
+ return e.filter((e) => e != null && e !== !1);
94
+ }
95
+ // product-grid.css?inline
96
+ var x = ":host{--_accent:var(--benevia-color-accent,#2f6b3a);--_border:var(--benevia-color-border,#c9c9c2);--_muted:var(--benevia-color-muted,#66665f);--_surface:var(--benevia-color-surface,transparent);--_radius:var(--benevia-radius,6px);--_spacing:var(--benevia-spacing,1rem);--_focus:var(--benevia-color-focus,var(--_accent));font-family:var(--benevia-font-family,inherit);color:var(--benevia-color-text,inherit);display:block}:host([hidden]){display:none}p{margin:0}.status,.empty{color:var(--_muted)}.status.error{color:var(--benevia-color-error,#a3261b)}.list{grid-template-columns:repeat(auto-fill, minmax(min(var(--benevia-card-width,10rem), 100%), 1fr));gap:var(--_spacing);margin:0;padding:0;list-style:none;display:grid}.item{display:flex}.card{padding:calc(var(--_spacing) * .75);color:inherit;border:1px solid var(--_border);border-radius:var(--_radius);background:var(--_surface);flex-direction:column;flex:1;gap:.25em;text-decoration:none;display:flex}.card:hover{border-color:var(--_accent)}.card:hover .name{text-decoration:underline}.card:focus-visible{outline:2px solid var(--_focus);outline-offset:2px}.image{width:100%;aspect-ratio:var(--benevia-image-aspect-ratio,1);object-fit:cover;border-radius:calc(var(--_radius) / 2);background:color-mix(in srgb, var(--_border) 35%, transparent);margin-bottom:.5em;display:block}.skeleton{border-radius:calc(var(--_radius) / 2);background:color-mix(in srgb, var(--_border) 35%, transparent);height:1em;margin:.15em 0;display:block}.placeholders{align-content:start;min-height:100vh}.name-skeleton{width:70%}.price-skeleton{width:45%}.name{font-weight:600;line-height:1.3}.price{color:var(--_muted)}.visually-hidden{clip-path:inset(50%);white-space:nowrap;width:1px;height:1px;margin:-1px;position:absolute;overflow:hidden}", S = 12, C = class extends HTMLElement {
97
+ static observedAttributes = [
98
+ "api-url",
99
+ "store-key",
100
+ "listing-href",
101
+ "category"
102
+ ];
103
+ container = y("div", {
104
+ part: "grid",
105
+ class: "grid"
106
+ });
107
+ catalog;
108
+ loadVersion = 0;
109
+ loadQueued = !1;
110
+ constructor() {
111
+ super();
112
+ let e = this.attachShadow({ mode: "open" }), t = document.createElement("style");
113
+ t.textContent = x, e.append(t, this.container);
114
+ }
115
+ get apiUrl() {
116
+ return this.getAttribute("api-url") ?? "";
117
+ }
118
+ set apiUrl(e) {
119
+ this.setAttribute("api-url", e);
120
+ }
121
+ get storeKey() {
122
+ return this.getAttribute("store-key") ?? "";
123
+ }
124
+ set storeKey(e) {
125
+ this.setAttribute("store-key", e);
126
+ }
127
+ get listingHref() {
128
+ return this.getAttribute("listing-href") ?? "";
129
+ }
130
+ set listingHref(e) {
131
+ this.setAttribute("listing-href", e);
132
+ }
133
+ connectedCallback() {
134
+ this.queueLoad();
135
+ }
136
+ attributeChangedCallback(e, t, n) {
137
+ t !== n && this.isConnected && (e === "listing-href" || e === "category" ? this.render() : this.queueLoad());
138
+ }
139
+ queueLoad() {
140
+ this.loadQueued || (this.loadQueued = !0, queueMicrotask(() => {
141
+ this.loadQueued = !1, this.load();
142
+ }));
143
+ }
144
+ async load() {
145
+ let e = ++this.loadVersion, { apiUrl: t, storeKey: n } = this;
146
+ if (this.catalog = void 0, !t || !n || !this.listingHref) this.showError("Set the api-url, store-key and listing-href attributes.");
147
+ else {
148
+ this.showLoading();
149
+ try {
150
+ let r = await f(t, n);
151
+ if (e !== this.loadVersion) return;
152
+ this.catalog = r, this.render();
153
+ } catch (t) {
154
+ if (e !== this.loadVersion) return;
155
+ console.error("benevia-product-grid: could not load listings", t), this.showError("The catalog could not be loaded. Please try again later.");
156
+ }
157
+ }
158
+ }
159
+ get locale() {
160
+ return this.closest("[lang]")?.getAttribute("lang") || void 0;
161
+ }
162
+ showError(e) {
163
+ this.container.replaceChildren(y("p", {
164
+ part: "status error",
165
+ class: "status error",
166
+ role: "alert"
167
+ }, e));
168
+ }
169
+ showLoading() {
170
+ this.container.replaceChildren(y("p", {
171
+ part: "status loading",
172
+ class: "status loading visually-hidden",
173
+ role: "status"
174
+ }, "Loading…"), y("ul", {
175
+ class: "list placeholders",
176
+ "aria-hidden": "true"
177
+ }, ...Array.from({ length: S }, () => y("li", { class: "item" }, y("span", {
178
+ part: "card card-loading",
179
+ class: "card"
180
+ }, y("span", {
181
+ part: "image image-placeholder",
182
+ class: "image"
183
+ }), y("span", { class: "skeleton name-skeleton" }), y("span", { class: "skeleton price-skeleton" }))))));
184
+ }
185
+ render() {
186
+ let e = this.catalog;
187
+ if (!e) return;
188
+ let t = this.getAttribute("category"), n = t ? e.listings.filter((e) => e.category === t) : e.listings;
189
+ n.length === 0 ? this.container.replaceChildren(y("p", {
190
+ part: "empty",
191
+ class: "empty"
192
+ }, "Nothing is for sale yet.")) : this.container.replaceChildren(y("ul", {
193
+ part: "list",
194
+ class: "list",
195
+ role: "list"
196
+ }, ...n.map((t) => y("li", { class: "item" }, this.renderCard(t, e.store.currency)))));
197
+ }
198
+ renderCard(e, n) {
199
+ let r = t(e.options.flatMap((e) => e.prices));
200
+ return y("a", {
201
+ part: "card",
202
+ class: "card",
203
+ href: ee(this.listingHref, e)
204
+ }, e.imageUrl ? y("img", {
205
+ part: "image",
206
+ class: "image",
207
+ src: e.imageUrl,
208
+ alt: "",
209
+ loading: "lazy",
210
+ decoding: "async"
211
+ }) : y("span", {
212
+ part: "image image-placeholder",
213
+ class: "image"
214
+ }), y("span", {
215
+ part: "name",
216
+ class: "name"
217
+ }, e.name), r !== void 0 && y("span", {
218
+ part: "price",
219
+ class: "price"
220
+ }, `From ${i(r, n, this.locale)} each`));
221
+ }
222
+ };
223
+ function ee(e, t) {
224
+ return e.replaceAll("{id}", encodeURIComponent(t.id)).replaceAll("{slug}", encodeURIComponent(te(t.name)));
225
+ }
226
+ function te(e) {
227
+ return e.normalize("NFKD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
228
+ }
229
+ // checkout-link.ts
230
+ function w(e, { storeKey: t, checkoutId: n, lines: r }) {
231
+ let i = r.map((e) => [
232
+ e.listingId,
233
+ e.optionId,
234
+ e.date,
235
+ e.quantity
236
+ ]);
237
+ return `${e}/${encodeURIComponent(t)}/${encodeURIComponent(n)}#${E(JSON.stringify(i))}`;
238
+ }
239
+ function T(e) {
240
+ let t = e;
241
+ return typeof t == "object" && !!t && typeof t.listingId == "string" && typeof t.optionId == "string" && typeof t.date == "string" && Number.isInteger(t.quantity) && t.quantity > 0;
242
+ }
243
+ function E(e) {
244
+ let t = String.fromCharCode(...new TextEncoder().encode(e));
245
+ return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
246
+ }
247
+ // cart-store.ts
248
+ function D(e) {
249
+ return [...new Set(e.map((e) => e.date))].sort().map((t) => ({
250
+ date: t,
251
+ lines: e.filter((e) => e.date === t)
252
+ }));
253
+ }
254
+ function ne(e) {
255
+ try {
256
+ let t = JSON.parse(e ?? "[]");
257
+ return Array.isArray(t) ? t.filter(T) : [];
258
+ } catch {
259
+ return [];
260
+ }
261
+ }
262
+ var O = "change", k = new EventTarget(), A = /* @__PURE__ */ new Map();
263
+ function j(e) {
264
+ let t = A.get(e);
265
+ return t || (t = q(e), A.set(e, t)), t;
266
+ }
267
+ function re(e, t, n) {
268
+ let r = j(e), i = r.find((e) => H(e, t)), a = Math.min((i?.quantity ?? 0) + t.quantity, n);
269
+ K(e, i ? r.map((e) => e === i ? {
270
+ ...e,
271
+ quantity: a
272
+ } : e) : [...r, {
273
+ ...t,
274
+ quantity: a
275
+ }]);
276
+ }
277
+ function ie(e, t, n) {
278
+ K(e, j(e).map((e) => H(e, t) ? {
279
+ ...e,
280
+ quantity: n
281
+ } : e));
282
+ }
283
+ function M(e, t) {
284
+ K(e, j(e).filter((e) => !H(e, t)));
285
+ }
286
+ function N(e) {
287
+ return j(e).reduce((e, t) => e + t.quantity, 0);
288
+ }
289
+ function P(e) {
290
+ let t = (t) => e(t.detail);
291
+ return k.addEventListener(O, t), () => k.removeEventListener(O, t);
292
+ }
293
+ var F = /* @__PURE__ */ new Map();
294
+ function I(e, t) {
295
+ let n = L(e);
296
+ if (n && U(n.lines, t)) return n;
297
+ let r = {
298
+ id: z(),
299
+ lines: t.map(({ listingId: e, optionId: t, date: n, quantity: r }) => ({
300
+ listingId: e,
301
+ optionId: t,
302
+ date: n,
303
+ quantity: r
304
+ }))
305
+ };
306
+ F.set(e, r);
307
+ try {
308
+ localStorage.setItem(B(e), JSON.stringify(r));
309
+ } catch {}
310
+ return r;
311
+ }
312
+ function L(e) {
313
+ try {
314
+ let t = JSON.parse(localStorage.getItem(B(e)) ?? "null");
315
+ return typeof t?.id == "string" && Array.isArray(t.lines) ? {
316
+ id: t.id,
317
+ lines: t.lines.filter(T)
318
+ } : null;
319
+ } catch {
320
+ return F.get(e) ?? null;
321
+ }
322
+ }
323
+ function R(e, t) {
324
+ let n = L(e);
325
+ if (n?.id === t) {
326
+ F.delete(e);
327
+ try {
328
+ localStorage.removeItem(B(e));
329
+ } catch {}
330
+ K(e, j(e).flatMap((e) => {
331
+ let t = e.quantity - (n.lines.find((t) => H(t, e))?.quantity ?? 0);
332
+ return t > 0 ? [{
333
+ ...e,
334
+ quantity: t
335
+ }] : [];
336
+ }));
337
+ }
338
+ }
339
+ function z() {
340
+ let e = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16));
341
+ e[6] = e[6] & 15 | 64, e[8] = e[8] & 63 | 128;
342
+ let t = [...e].map((e) => e.toString(16).padStart(2, "0")).join("");
343
+ return `${t.slice(0, 8)}-${t.slice(8, 12)}-${t.slice(12, 16)}-${t.slice(16, 20)}-${t.slice(20)}`;
344
+ }
345
+ function B(e) {
346
+ return `benevia-checkout:${e}`;
347
+ }
348
+ function V(t, n) {
349
+ let r = [], i = [];
350
+ for (let a of t) {
351
+ let t = n.find((e) => e.id === a.listingId), o = t?.options.find((e) => e.id === a.optionId), s = o?.availability?.find((e) => e.date === a.date)?.available ?? 0, c = o && e(o.prices, a.quantity);
352
+ !t || !o || s <= 0 || c === void 0 ? i.push({
353
+ ...a,
354
+ listingName: t?.name,
355
+ optionName: o?.name
356
+ }) : r.push({
357
+ ...a,
358
+ listingName: t.name,
359
+ optionName: o.name,
360
+ unitPrice: c,
361
+ total: W(c * a.quantity),
362
+ available: s
363
+ });
364
+ }
365
+ return {
366
+ groups: D(r),
367
+ subtotal: W(r.reduce((e, t) => e + t.total, 0)),
368
+ unavailable: i
369
+ };
370
+ }
371
+ function H(e, t) {
372
+ return e.listingId === t.listingId && e.optionId === t.optionId && e.date === t.date;
373
+ }
374
+ function U(e, t) {
375
+ return e.length === t.length && e.every((e) => t.some((t) => H(e, t) && e.quantity === t.quantity));
376
+ }
377
+ function W(e) {
378
+ return Math.round(e * 100) / 100;
379
+ }
380
+ function G(e) {
381
+ return `benevia-cart:${e}`;
382
+ }
383
+ function K(e, t) {
384
+ A.set(e, t);
385
+ try {
386
+ localStorage.setItem(G(e), JSON.stringify(t));
387
+ } catch {}
388
+ k.dispatchEvent(new CustomEvent(O, { detail: e }));
389
+ }
390
+ function q(e) {
391
+ try {
392
+ return ne(localStorage.getItem(G(e)));
393
+ } catch {
394
+ return [];
395
+ }
396
+ }
397
+ typeof window < "u" && window.addEventListener("storage", (e) => {
398
+ let t = G("");
399
+ if (!e.key?.startsWith(t)) return;
400
+ let n = e.key.slice(t.length);
401
+ A.delete(n), k.dispatchEvent(new CustomEvent(O, { detail: n }));
402
+ });
403
+ // product-picker.css?inline
404
+ var J = ":host{--_accent:var(--benevia-color-accent,#2f6b3a);--_accent-text:var(--benevia-color-accent-text,#fff);--_border:var(--benevia-color-border,#c9c9c2);--_muted:var(--benevia-color-muted,#66665f);--_surface:var(--benevia-color-surface,transparent);--_radius:var(--benevia-radius,6px);--_spacing:var(--benevia-spacing,1rem);--_focus:var(--benevia-color-focus,var(--_accent));font-family:var(--benevia-font-family,inherit);color:var(--benevia-color-text,inherit);display:block}:host([hidden]){display:none}.picker{gap:var(--_spacing);display:grid}p{margin:0}.name{font-size:1.5em;font-weight:700;line-height:1.2}.description,.status,.empty,.price-breaks{color:var(--_muted)}.status.error{color:var(--benevia-color-error,#a3261b)}.choices{gap:calc(var(--_spacing) / 2);border:0;flex-wrap:wrap;margin:0;padding:0;display:flex}legend{width:100%;margin-bottom:calc(var(--_spacing) / 2);padding:0;font-weight:600}.choice{border:1px solid var(--_border);border-radius:var(--_radius);background:var(--_surface);cursor:pointer;gap:.125em;min-width:7.5em;padding:.5em .75em;display:grid;position:relative}.choice:has(input:checked){border-color:var(--_accent);box-shadow:inset 0 0 0 1px var(--_accent)}.quantity-input:focus-visible,.add-button:focus-visible{outline:2px solid var(--_focus);outline-offset:2px}.choice:has(input:focus-visible){outline:2px solid var(--_focus);outline-offset:2px}.choice:has(input:disabled){cursor:not-allowed;color:var(--benevia-color-sold-out,var(--_muted));border-style:dashed}.choice-name{font-weight:600}.choice-detail{color:var(--_muted);font-size:.875em}.option-name{font-weight:600}.quantity{justify-items:start;gap:.25em;display:grid}.quantity label{font-weight:600}.quantity-input{width:6em;font:inherit;color:inherit;border:1px solid var(--_border);border-radius:var(--_radius);background:var(--_surface);padding:.5em}.price{flex-wrap:wrap;align-items:baseline;gap:.25em 1em;display:flex}.unit-price{font-size:1.25em;font-weight:700}.price-breaks{margin:0;padding:0;font-size:.875em;list-style:none}.add-button{font:inherit;color:var(--_accent-text);background:var(--_accent);border-radius:var(--_radius);cursor:pointer;border:0;justify-self:start;padding:.75em 1.5em;font-weight:600}.add-button:disabled{cursor:not-allowed;opacity:.5}.status.added:empty{display:none}.picker:has(>.skeleton-group){align-content:start;min-height:100vh}.skeleton{border-radius:var(--_radius);background:color-mix(in srgb, var(--_border) 35%, transparent);display:block}.name-skeleton{width:60%;height:1.8em}.description-skeleton{width:90%;height:1.2em}.skeleton-group{gap:calc(var(--_spacing) / 2);display:grid}.skeleton-group:before{content:\"\";border-radius:var(--_radius);background:color-mix(in srgb, var(--_border) 35%, transparent);width:6em;height:1.2em}.skeleton-row{gap:calc(var(--_spacing) / 2);flex-wrap:wrap;display:flex}.choice-skeleton{width:7.5em;height:3.4em}.button-skeleton{width:9em;height:2.9em}.visually-hidden{clip-path:inset(50%);white-space:nowrap;width:1px;height:1px;margin:-1px;position:absolute;overflow:hidden}", Y = class extends HTMLElement {
405
+ static observedAttributes = [
406
+ "api-url",
407
+ "store-key",
408
+ "listing",
409
+ "listing-param",
410
+ "option-label",
411
+ "date-label"
412
+ ];
413
+ root;
414
+ container = y("div", {
415
+ part: "picker",
416
+ class: "picker"
417
+ });
418
+ store;
419
+ listingData;
420
+ optionId;
421
+ date;
422
+ quantity = 1;
423
+ loadVersion = 0;
424
+ loadQueued = !1;
425
+ constructor() {
426
+ super(), this.root = this.attachShadow({ mode: "open" });
427
+ let e = document.createElement("style");
428
+ e.textContent = J, this.root.append(e, this.container);
429
+ }
430
+ get apiUrl() {
431
+ return this.getAttribute("api-url") ?? "";
432
+ }
433
+ set apiUrl(e) {
434
+ this.setAttribute("api-url", e);
435
+ }
436
+ get storeKey() {
437
+ return this.getAttribute("store-key") ?? "";
438
+ }
439
+ set storeKey(e) {
440
+ this.setAttribute("store-key", e);
441
+ }
442
+ get listing() {
443
+ return this.getAttribute("listing") ?? "";
444
+ }
445
+ set listing(e) {
446
+ this.setAttribute("listing", e);
447
+ }
448
+ get listingId() {
449
+ let e = this.getAttribute("listing-param");
450
+ return this.listing || e && new URLSearchParams(location.search).get(e) || "";
451
+ }
452
+ connectedCallback() {
453
+ this.queueLoad();
454
+ }
455
+ attributeChangedCallback(e, t, n) {
456
+ t !== n && this.isConnected && (e === "option-label" || e === "date-label" ? this.render() : this.queueLoad());
457
+ }
458
+ queueLoad() {
459
+ this.loadQueued || (this.loadQueued = !0, queueMicrotask(() => {
460
+ this.loadQueued = !1, this.load();
461
+ }));
462
+ }
463
+ async load() {
464
+ let e = ++this.loadVersion, { apiUrl: t, storeKey: n, listingId: r } = this;
465
+ if (!t || !n) this.showError("Set the api-url, store-key and listing attributes.");
466
+ else if (!r) this.showError(this.hasAttribute("listing-param") ? "This item is not available." : "Set the api-url, store-key and listing attributes.");
467
+ else {
468
+ this.showLoading();
469
+ try {
470
+ let i = await p(t, n, r);
471
+ if (e !== this.loadVersion) return;
472
+ if (!i) {
473
+ this.showError("This item is not available.");
474
+ return;
475
+ }
476
+ let a = i.listing;
477
+ this.store = i.store, this.listingData = a;
478
+ let o = a.options.find((e) => !s(e)) ?? a.options[0];
479
+ this.selectOption(o?.id), this.render();
480
+ } catch (t) {
481
+ if (e !== this.loadVersion) return;
482
+ console.error("benevia-product-picker: could not load listings", t), this.showError("Availability could not be loaded. Please try again later.");
483
+ }
484
+ }
485
+ }
486
+ get selectedOption() {
487
+ return this.listingData?.options.find((e) => e.id === this.optionId);
488
+ }
489
+ get availableOnDate() {
490
+ return this.selectedOption?.availability?.find((e) => e.date === this.date)?.available ?? 0;
491
+ }
492
+ get locale() {
493
+ return this.closest("[lang]")?.getAttribute("lang") || void 0;
494
+ }
495
+ selectOption(e) {
496
+ this.optionId = e, this.date = o(this.selectedOption?.availability ?? [])?.date, this.quantity = a(this.quantity, this.availableOnDate);
497
+ }
498
+ showError(e) {
499
+ this.listingData = void 0, this.container.replaceChildren(y("p", {
500
+ part: "status error",
501
+ class: "status error",
502
+ role: "alert"
503
+ }, e));
504
+ }
505
+ showLoading() {
506
+ this.listingData = void 0;
507
+ let e = (e) => y("div", { class: "skeleton-row" }, ...Array.from({ length: 3 }, () => y("span", { class: `skeleton ${e}` })));
508
+ this.container.replaceChildren(y("p", {
509
+ part: "status loading",
510
+ class: "status loading visually-hidden",
511
+ role: "status"
512
+ }, "Loading…"), y("span", {
513
+ part: "name",
514
+ class: "skeleton name-skeleton",
515
+ "aria-hidden": "true"
516
+ }), y("span", {
517
+ part: "description",
518
+ class: "skeleton description-skeleton",
519
+ "aria-hidden": "true"
520
+ }), y("div", {
521
+ class: "skeleton-group",
522
+ "aria-hidden": "true"
523
+ }, e("choice-skeleton")), y("div", {
524
+ class: "skeleton-group",
525
+ "aria-hidden": "true"
526
+ }, e("choice-skeleton")), y("span", {
527
+ class: "skeleton button-skeleton",
528
+ "aria-hidden": "true"
529
+ }));
530
+ }
531
+ render() {
532
+ let e = this.listingData;
533
+ if (!e) return;
534
+ let t = "listing-name";
535
+ this.container.setAttribute("role", "group"), this.container.setAttribute("aria-labelledby", t), this.container.replaceChildren(y("p", {
536
+ part: "name",
537
+ class: "name",
538
+ id: t
539
+ }, e.name), e.description && y("p", {
540
+ part: "description",
541
+ class: "description"
542
+ }, e.description), this.renderOptions(e), y("div", { class: "dates-slot" }), this.renderQuantity(), y("div", { class: "price-slot" }), y("button", {
543
+ type: "button",
544
+ part: "add-button",
545
+ class: "add-button"
546
+ }, "Add to cart"), y("p", {
547
+ part: "status",
548
+ class: "status added",
549
+ role: "status"
550
+ })), this.container.querySelector(".add-button")?.addEventListener("click", () => this.addToCart()), this.renderDates(), this.renderQuantityLimits(), this.renderPrice();
551
+ }
552
+ renderOptions(e) {
553
+ let n = this.getAttribute("option-label") || "Option";
554
+ if (e.options.length === 1) {
555
+ let t = e.options[0];
556
+ return y("p", {
557
+ part: "option-name",
558
+ class: "option-name"
559
+ }, `${n}: ${t.name}`);
560
+ }
561
+ let r = y("fieldset", {
562
+ part: "options",
563
+ class: "choices"
564
+ }, y("legend", {}, n));
565
+ for (let n of e.options) {
566
+ let e = s(n), i = t(n.prices), a = y("input", {
567
+ type: "radio",
568
+ name: "option",
569
+ value: n.id,
570
+ class: "visually-hidden"
571
+ });
572
+ a.checked = n.id === this.optionId, a.addEventListener("change", () => {
573
+ this.selectOption(n.id), this.updateSelectedParts(r, "option"), this.renderDates(), this.renderQuantityLimits(), this.renderPrice();
574
+ }), r.append(y("label", {
575
+ part: X("option", a.checked, e),
576
+ class: "choice"
577
+ }, a, y("span", { class: "choice-name" }, n.name), y("span", { class: "choice-detail" }, e ? "Sold out" : i !== void 0 && this.fromPrice(n, i))));
578
+ }
579
+ return r;
580
+ }
581
+ renderDates() {
582
+ let e = this.container.querySelector(".dates-slot"), t = this.selectedOption;
583
+ if (!e || !t) return;
584
+ let i = y("fieldset", {
585
+ part: "dates",
586
+ class: "choices"
587
+ }, y("legend", {}, this.getAttribute("date-label") || "Date")), o = t.availability ?? [];
588
+ o.length === 0 && i.append(y("p", {
589
+ part: "empty",
590
+ class: "empty"
591
+ }, "No dates are open yet."));
592
+ for (let { date: e, available: t } of o) {
593
+ let o = t <= 0, s = r(e, this.locale), c = y("input", {
594
+ type: "radio",
595
+ name: "date",
596
+ value: e,
597
+ class: "visually-hidden",
598
+ disabled: o
599
+ });
600
+ c.checked = e === this.date, c.addEventListener("change", () => {
601
+ this.date = e, this.quantity = a(this.quantity, t), this.updateSelectedParts(i, "date"), this.renderQuantityLimits(), this.renderPrice();
602
+ }), i.append(y("label", {
603
+ part: X("date", c.checked, o),
604
+ class: "choice"
605
+ }, c, y(o ? "s" : "span", { class: "choice-name" }, s), y("span", {
606
+ part: "count",
607
+ class: "choice-detail"
608
+ }, n(t, this.locale))));
609
+ }
610
+ e.replaceChildren(i);
611
+ }
612
+ renderQuantity() {
613
+ let e = y("input", {
614
+ id: "quantity",
615
+ type: "number",
616
+ part: "quantity-input",
617
+ class: "quantity-input",
618
+ min: "1",
619
+ step: "1",
620
+ inputmode: "numeric"
621
+ }), t = () => {
622
+ this.quantity = a(e.valueAsNumber, this.availableOnDate), this.renderPrice();
623
+ };
624
+ return e.addEventListener("input", t), e.addEventListener("change", () => {
625
+ t(), e.value = String(this.quantity);
626
+ }), y("div", {
627
+ part: "quantity",
628
+ class: "quantity"
629
+ }, y("label", {
630
+ for: "quantity",
631
+ part: "quantity-label"
632
+ }, "Quantity"), e);
633
+ }
634
+ renderQuantityLimits() {
635
+ let e = this.root.querySelector(".quantity-input");
636
+ if (!e) return;
637
+ let t = this.availableOnDate;
638
+ e.max = String(Math.max(t, 1)), e.value = String(this.quantity), e.disabled = t <= 0;
639
+ }
640
+ renderPrice() {
641
+ let t = this.container.querySelector(".price-slot"), n = this.selectedOption;
642
+ if (!t || !n) return;
643
+ let r = e(n.prices, this.quantity), i = [...n.prices].filter((e) => e.minQuantity > 1).sort((e, t) => e.minQuantity - t.minQuantity).map((e) => y("li", {}, `${e.minQuantity} or more: ${this.price(e.unitPrice)} each`));
644
+ t.replaceChildren(...b(r !== void 0 && y("p", {
645
+ part: "price",
646
+ class: "price"
647
+ }, y("span", { class: "unit-price" }, `${this.price(r)} each`), y("span", {
648
+ part: "total",
649
+ class: "total"
650
+ }, `Total ${this.price(r * this.quantity)}`)), i.length > 0 && y("ul", {
651
+ part: "price-breaks",
652
+ class: "price-breaks"
653
+ }, ...i)));
654
+ let a = this.container.querySelector(".add-button");
655
+ a && (a.disabled = this.availableOnDate <= 0 || r === void 0);
656
+ }
657
+ updateSelectedParts(e, t) {
658
+ for (let n of e.querySelectorAll("label")) {
659
+ let e = n.querySelector("input");
660
+ e && n.setAttribute("part", X(t, e.checked, e.disabled));
661
+ }
662
+ }
663
+ addToCart() {
664
+ let t = this.listingData, n = this.selectedOption, i = n && e(n.prices, this.quantity);
665
+ if (!t || !n || !this.date || i === void 0 || !this.store) return;
666
+ let a = {
667
+ listingId: t.id,
668
+ optionId: n.id,
669
+ date: this.date,
670
+ quantity: this.quantity,
671
+ unitPrice: i,
672
+ currency: this.store.currency
673
+ };
674
+ re(this.storeKey, {
675
+ listingId: t.id,
676
+ optionId: n.id,
677
+ date: this.date,
678
+ quantity: this.quantity
679
+ }, this.availableOnDate), this.dispatchEvent(new CustomEvent("benevia-add-to-cart", {
680
+ detail: a,
681
+ bubbles: !0,
682
+ composed: !0
683
+ }));
684
+ let o = this.container.querySelector(".added");
685
+ o && (o.textContent = `Added ${this.quantity} ${n.name} for ${r(this.date, this.locale)} to the cart.`);
686
+ }
687
+ fromPrice(e, t) {
688
+ return new Set(e.prices.map((e) => e.unitPrice)).size > 1 ? `From ${this.price(t)}` : this.price(t);
689
+ }
690
+ price(e) {
691
+ return i(e, this.store?.currency ?? "USD", this.locale);
692
+ }
693
+ };
694
+ function X(e, t, n) {
695
+ return [
696
+ e,
697
+ t && `${e}-selected`,
698
+ n && `${e}-sold-out`
699
+ ].filter(Boolean).join(" ");
700
+ }
701
+ // shopping-cart.css?inline
702
+ var ae = ":host{--_accent:var(--benevia-color-accent,#2f6b3a);--_accent-text:var(--benevia-color-accent-text,#fff);--_border:var(--benevia-color-border,#c9c9c2);--_muted:var(--benevia-color-muted,#66665f);--_surface:var(--benevia-color-surface,transparent);--_drawer:var(--benevia-color-drawer,#fff);--_radius:var(--benevia-radius,6px);--_spacing:var(--benevia-spacing,1rem);--_focus:var(--benevia-color-focus,var(--_accent));font-family:var(--benevia-font-family,inherit);color:var(--benevia-color-text,inherit);display:inline-block}:host([hidden]){display:none}button{font:inherit;color:inherit;cursor:pointer}button:focus-visible,.title:focus-visible,.quantity-input:focus-visible{outline:2px solid var(--_focus);outline-offset:2px}.cart-button{background:var(--_surface);border:1px solid var(--_border);border-radius:var(--_radius);align-items:center;gap:.5em;padding:.5em 1em;font-weight:600;display:inline-flex}.count{text-align:center;min-width:1.5em;color:var(--_accent-text);background:var(--_accent);border-radius:999px;padding:0 .4em;font-size:.875em;line-height:1.5}.count[hidden]{display:none}.drawer{box-sizing:border-box;width:min(28rem,100vw);max-width:100vw;height:100%;max-height:100%;padding:var(--_spacing);color:var(--benevia-color-text,inherit);background:var(--_drawer);border:0;margin:0 0 0 auto;overflow-y:auto}.drawer[open]{align-content:start;gap:var(--_spacing);display:grid}.drawer::backdrop{background:#0006}.head{justify-content:space-between;align-items:center;display:flex}.title{margin:0;font-size:1.5em}.close{border-radius:var(--_radius);background:0 0;border:0;width:2.25em;height:2.25em;font-size:1.25em;line-height:1}.body{gap:var(--_spacing);display:grid}p{margin:0}.empty,.status,.unavailable{color:var(--_muted)}.status.error{color:var(--benevia-color-error,#a3261b)}.date-heading{margin:0 0 calc(var(--_spacing) / 2);font-size:1em}.lines{gap:calc(var(--_spacing) / 2);margin:0;padding:0;list-style:none;display:grid}.line{padding-bottom:calc(var(--_spacing) / 2);border-bottom:1px solid var(--_border);grid-template-columns:1fr auto;align-items:center;gap:.25em 1em;display:grid}.line-name{font-weight:600}.line-detail{flex-wrap:wrap;grid-area:2/1/auto/-1;align-items:center;gap:.5em;display:flex}.quantity{color:var(--_muted)}.quantity-input{width:5em;font:inherit;color:inherit;border:1px solid var(--_border);border-radius:var(--_radius);background:var(--_surface);padding:.25em .5em}.unit-price{color:var(--_muted)}.line-total{margin-left:auto;font-weight:600}.line-note{color:var(--benevia-color-error,#a3261b);grid-column:1/-1}.line-note[hidden]{display:none}.remove{color:var(--_muted);background:0 0;border:0;padding:.25em .5em;font-size:.875em;text-decoration:underline}.subtotal{justify-content:space-between;font-size:1.25em;font-weight:700;display:flex}.checkout{width:100%;font:inherit;color:var(--_accent-text);background:var(--_accent);border-radius:var(--_radius);cursor:pointer;border:0;padding:.75em 1.5em;font-weight:600}.checkout:focus-visible{outline:2px solid var(--_focus);outline-offset:2px}.visually-hidden{clip-path:inset(50%);white-space:nowrap;width:1px;height:1px;margin:-1px;position:absolute;overflow:hidden}.preview-checkout{gap:calc(var(--_spacing) / 2);display:grid}.preview-checkout h3,.preview-checkout p{margin:0}.preview-back{background:var(--_surface);border:1px solid var(--_border);border-radius:var(--_radius);justify-self:start;padding:.5em 1em}", Z = class extends HTMLElement {
703
+ static observedAttributes = [
704
+ "api-url",
705
+ "store-key",
706
+ "date-label"
707
+ ];
708
+ root;
709
+ count = y("span", {
710
+ part: "count",
711
+ class: "count"
712
+ });
713
+ countText = y("span", { class: "visually-hidden" });
714
+ body = y("div", { class: "body" });
715
+ dialog;
716
+ listings;
717
+ store;
718
+ layout = "";
719
+ loadFailed = !1;
720
+ unsubscribe;
721
+ onPageShow = (e) => {
722
+ e.persisted && this.completeIfPlaced();
723
+ };
724
+ constructor() {
725
+ super(), this.root = this.attachShadow({ mode: "open" });
726
+ let e = document.createElement("style");
727
+ e.textContent = ae;
728
+ let t = y("button", {
729
+ type: "button",
730
+ part: "button",
731
+ class: "cart-button",
732
+ "aria-haspopup": "dialog"
733
+ }, y("slot", {}, "Cart"), this.count, this.countText);
734
+ t.addEventListener("click", () => this.open());
735
+ let n = y("button", {
736
+ type: "button",
737
+ part: "close",
738
+ class: "close",
739
+ "aria-label": "Close cart"
740
+ }, "×");
741
+ n.addEventListener("click", () => this.dialog.close()), this.dialog = y("dialog", {
742
+ part: "drawer",
743
+ class: "drawer",
744
+ "aria-labelledby": "cart-title"
745
+ }, y("div", { class: "head" }, y("h2", {
746
+ part: "title",
747
+ class: "title",
748
+ id: "cart-title",
749
+ tabindex: "-1"
750
+ }, "Cart"), n), this.body, y("slot", { name: "footer" })), this.dialog.addEventListener("click", (e) => {
751
+ e.target === this.dialog && this.dialog.close();
752
+ }), this.root.append(e, t, this.dialog);
753
+ }
754
+ get apiUrl() {
755
+ return this.getAttribute("api-url") ?? "";
756
+ }
757
+ set apiUrl(e) {
758
+ this.setAttribute("api-url", e);
759
+ }
760
+ get storeKey() {
761
+ return this.getAttribute("store-key") ?? "";
762
+ }
763
+ set storeKey(e) {
764
+ this.setAttribute("store-key", e);
765
+ }
766
+ connectedCallback() {
767
+ this.unsubscribe = P((e) => {
768
+ e === this.storeKey && this.render();
769
+ }), window.addEventListener("pageshow", this.onPageShow), this.render(), this.completeIfPlaced();
770
+ }
771
+ disconnectedCallback() {
772
+ this.unsubscribe?.(), window.removeEventListener("pageshow", this.onPageShow);
773
+ }
774
+ attributeChangedCallback(e, t) {
775
+ e !== "date-label" && t !== null && (this.listings = void 0), this.isConnected && (this.render(), e !== "date-label" && this.completeIfPlaced());
776
+ }
777
+ async open() {
778
+ this.dialog.open || this.dialog.showModal(), this.render(), await Promise.all([this.load(), this.completeIfPlaced()]);
779
+ }
780
+ async load() {
781
+ let { apiUrl: e, storeKey: t } = this, n = [...new Set(j(t).map((e) => e.listingId))];
782
+ if (e && t && n.length !== 0) {
783
+ try {
784
+ let r = (await Promise.all(n.map((n) => p(e, t, n)))).filter((e) => e !== null);
785
+ this.listings = r.map((e) => e.listing), this.store = r[0]?.store ?? this.store, this.loadFailed = !1, this.layout = "";
786
+ } catch (e) {
787
+ console.error("benevia-cart: could not load listings", e), this.loadFailed = !0;
788
+ }
789
+ this.render();
790
+ }
791
+ }
792
+ async checkout() {
793
+ let { storeKey: e } = this, t = this.store?.checkoutUrl;
794
+ if (!this.listings || !t) return;
795
+ await this.completeIfPlaced();
796
+ let n = V(j(e), this.listings).groups.flatMap((e) => e.lines);
797
+ if (n.length === 0) return;
798
+ if (c(this.apiUrl)) {
799
+ this.showPreviewCheckout(n);
800
+ return;
801
+ }
802
+ let r = I(e, n).id;
803
+ window.location.assign(w(t, {
804
+ storeKey: e,
805
+ checkoutId: r,
806
+ lines: n
807
+ }));
808
+ }
809
+ async completeIfPlaced() {
810
+ let { apiUrl: e, storeKey: t } = this, n = L(t);
811
+ if (e && t && n) {
812
+ if (j(t).length === 0) R(t, n.id);
813
+ else try {
814
+ await v(g(e, t, n.id)) && R(t, n.id);
815
+ } catch (e) {
816
+ console.error("benevia-cart: could not check the checkout", e);
817
+ }
818
+ }
819
+ }
820
+ get locale() {
821
+ return this.closest("[lang]")?.getAttribute("lang") || void 0;
822
+ }
823
+ render() {
824
+ let e = N(this.storeKey);
825
+ if (this.count.textContent = String(e), this.count.hidden = e === 0, this.countText.textContent = `, ${e} ${e === 1 ? "item" : "items"}`, !this.dialog.open) return;
826
+ let t = this.body.contains(this.root.activeElement);
827
+ this.renderBody(), t && !this.body.contains(this.root.activeElement) && this.root.getElementById("cart-title")?.focus();
828
+ }
829
+ renderBody() {
830
+ let e = j(this.storeKey);
831
+ if (e.length !== 0 && this.listings || (this.layout = ""), e.length === 0) {
832
+ this.body.replaceChildren(y("p", {
833
+ part: "empty",
834
+ class: "empty"
835
+ }, "Your cart is empty."));
836
+ return;
837
+ }
838
+ if (!this.listings) {
839
+ this.body.replaceChildren(this.loadFailed ? y("p", {
840
+ part: "status error",
841
+ class: "status error",
842
+ role: "alert"
843
+ }, "The cart could not be loaded. Please try again later.") : y("p", {
844
+ part: "status loading",
845
+ class: "status",
846
+ role: "status"
847
+ }, "Loading…"));
848
+ return;
849
+ }
850
+ let t = V(e, this.listings), n = this.getAttribute("date-label") || "Date", i = [n, ...e.map($)].join("|");
851
+ i === this.layout ? this.updateAmounts(t) : (this.layout = i, this.body.replaceChildren(...b(...t.groups.map((e) => {
852
+ let t = `date-${e.date}`;
853
+ return y("section", {
854
+ part: "date-group",
855
+ class: "date-group",
856
+ "aria-labelledby": t
857
+ }, y("h3", {
858
+ part: "date-heading",
859
+ class: "date-heading",
860
+ id: t
861
+ }, `${n}: ${r(e.date, this.locale)}`), y("ul", { class: "lines" }, ...e.lines.map((e) => this.renderLine(e))));
862
+ }), t.unavailable.length > 0 && y("section", {
863
+ part: "unavailable",
864
+ class: "unavailable"
865
+ }, y("p", {}, "No longer available:"), y("ul", { class: "lines" }, ...t.unavailable.map((e) => this.renderUnavailable(e)))), t.groups.length > 0 && y("p", {
866
+ part: "subtotal",
867
+ class: "subtotal"
868
+ }, y("span", {}, "Subtotal"), y("span", { class: "amount" }, this.price(t.subtotal))), t.groups.length > 0 && !!this.store?.checkoutUrl && this.checkoutButton())));
869
+ }
870
+ updateAmounts(e) {
871
+ for (let t of e.groups.flatMap((e) => e.lines)) {
872
+ let e = this.body.querySelector(`[data-line="${CSS.escape($(t))}"]`), n = e?.querySelector(".quantity-input");
873
+ n && (n.value = String(t.quantity)), e?.querySelector(".unit-price")?.replaceChildren(this.unitPrice(t)), e?.querySelector(".line-total")?.replaceChildren(this.price(t.total));
874
+ let r = e?.querySelector(".line-note");
875
+ r && (r.textContent = Q(t), r.hidden = !r.textContent);
876
+ }
877
+ this.body.querySelector(".subtotal .amount")?.replaceChildren(this.price(e.subtotal));
878
+ }
879
+ renderLine(e) {
880
+ let t = $(e), n = `${e.listingName}, ${e.optionName}`, r = y("input", {
881
+ id: `quantity-${t}`,
882
+ type: "number",
883
+ part: "quantity-input",
884
+ class: "quantity-input",
885
+ min: "1",
886
+ max: String(e.available),
887
+ step: "1",
888
+ inputmode: "numeric"
889
+ });
890
+ return r.value = String(e.quantity), r.addEventListener("change", () => {
891
+ let t = a(r.valueAsNumber, e.available);
892
+ r.value = String(t), ie(this.storeKey, e, t);
893
+ }), y("li", {
894
+ part: "line",
895
+ class: "line",
896
+ "data-line": t
897
+ }, y("p", {
898
+ part: "line-name",
899
+ class: "line-name"
900
+ }, n), y("div", { class: "line-detail" }, y("label", {
901
+ for: `quantity-${t}`,
902
+ class: "quantity"
903
+ }, y("span", { class: "visually-hidden" }, `Quantity of ${n}`), y("span", { "aria-hidden": "true" }, "Qty")), r, y("span", {
904
+ part: "unit-price",
905
+ class: "unit-price"
906
+ }, this.unitPrice(e)), y("span", {
907
+ part: "line-total",
908
+ class: "line-total"
909
+ }, this.price(e.total))), this.removeButton(e, n), y("p", {
910
+ part: "line-note",
911
+ class: "line-note",
912
+ hidden: !Q(e)
913
+ }, Q(e)));
914
+ }
915
+ renderUnavailable(e) {
916
+ let t = `${e.listingName ? [e.listingName, e.optionName].filter(Boolean).join(", ") : "An item no longer sold"}, ${r(e.date, this.locale)}`;
917
+ return y("li", {
918
+ part: "line line-unavailable",
919
+ class: "line"
920
+ }, y("p", { class: "line-name" }, t), this.removeButton(e, t));
921
+ }
922
+ showPreviewCheckout(e) {
923
+ let t = y("button", {
924
+ type: "button",
925
+ part: "preview-back",
926
+ class: "preview-back"
927
+ }, "Back to cart");
928
+ t.addEventListener("click", () => {
929
+ this.layout = "", this.render(), this.root.getElementById("cart-title")?.focus();
930
+ }), this.layout = "", this.body.replaceChildren(y("section", {
931
+ part: "preview-checkout",
932
+ class: "preview-checkout",
933
+ role: "status",
934
+ "aria-labelledby": "preview-checkout-title"
935
+ }, y("h3", {
936
+ id: "preview-checkout-title",
937
+ tabindex: "-1"
938
+ }, "Preview checkout"), y("p", {}, "This is a preview, so nothing is ordered. On the live site, Checkout opens the store's checkout page with these lines:"), y("ul", { class: "lines" }, ...e.map((e) => y("li", {}, `${e.quantity} × ${e.listingName}, ${e.optionName}, ${r(e.date, this.locale)}`))), t)), this.root.getElementById("preview-checkout-title")?.focus();
939
+ }
940
+ checkoutButton() {
941
+ let e = y("button", {
942
+ type: "button",
943
+ part: "checkout",
944
+ class: "checkout"
945
+ }, "Checkout");
946
+ return e.addEventListener("click", () => void this.checkout()), e;
947
+ }
948
+ removeButton(e, t) {
949
+ let n = y("button", {
950
+ type: "button",
951
+ part: "remove",
952
+ class: "remove",
953
+ "aria-label": `Remove ${t}`
954
+ }, "Remove");
955
+ return n.addEventListener("click", () => M(this.storeKey, e)), n;
956
+ }
957
+ unitPrice(e) {
958
+ return `× ${this.price(e.unitPrice)}`;
959
+ }
960
+ price(e) {
961
+ return i(e, this.store?.currency ?? "USD", this.locale);
962
+ }
963
+ };
964
+ function Q(e) {
965
+ return e.quantity > e.available ? `Only ${e.available} left on this date.` : "";
966
+ }
967
+ function $(e) {
968
+ return `${e.listingId}-${e.optionId}-${e.date}`;
969
+ }
970
+ customElements.get("benevia-product-grid") || customElements.define("benevia-product-grid", C), customElements.get("benevia-product-picker") || customElements.define("benevia-product-picker", Y), customElements.get("benevia-cart") || customElements.define("benevia-cart", Z);
971
+ export { C as ProductGrid, Y as ProductPicker, Z as ShoppingCart };
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@beneviasoftware/storefront",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "description": "Web components that sell from a Benevia store's live availability.",
5
+ "license": "SEE LICENSE IN LICENSE.txt",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/beneviasoftware/erp.git",
9
+ "directory": "src/storefront"
10
+ },
11
+ "type": "module",
12
+ "exports": {
13
+ ".": "./dist/storefront.js"
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "dev": "vite",
20
+ "build": "tsc --noEmit && vite build",
21
+ "test": "vitest run",
22
+ "test:watch": "vitest",
23
+ "prepack": "npm run build"
24
+ },
25
+ "devDependencies": {
26
+ "happy-dom": "^21.0.4",
27
+ "typescript": "^6.0.3",
28
+ "vite": "^8.3.8",
29
+ "vitest": "^5.1.1"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public"
33
+ }
34
+ }