@occluze/tether 0.6.6 → 0.6.8

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 (135) hide show
  1. package/README.md +3 -3
  2. package/dist/esm/astro.js +2 -2
  3. package/dist/esm/chunks/account-C3NP6HFB.js +1 -0
  4. package/dist/esm/chunks/account-pages-WLK374FO.js +1 -0
  5. package/dist/esm/chunks/analytics-G3SAWMNL.js +1 -0
  6. package/dist/esm/chunks/chunk-27PJJZGC.js +1 -0
  7. package/dist/esm/chunks/chunk-2FSXS55U.js +1 -0
  8. package/dist/esm/chunks/chunk-FCSWQDVV.js +1 -0
  9. package/dist/esm/chunks/chunk-FOMSMIAM.js +1 -0
  10. package/dist/esm/chunks/chunk-GZJTCLLW.js +1 -0
  11. package/dist/esm/chunks/chunk-HEQILZVR.js +1 -0
  12. package/dist/esm/chunks/chunk-JOOEXYF3.js +4 -0
  13. package/dist/esm/chunks/chunk-MPTQYLSM.js +1 -0
  14. package/dist/esm/chunks/chunk-NEHZ37TU.js +3 -0
  15. package/dist/esm/chunks/chunk-V74KGEJF.js +1 -0
  16. package/dist/esm/chunks/chunk-VT4CDUJJ.js +1 -0
  17. package/dist/esm/chunks/chunk-YJLWX2HK.js +1 -0
  18. package/dist/esm/chunks/diagnose-6VVGZNTY.js +14 -0
  19. package/dist/esm/chunks/extras-GJVRDFM3.js +1 -0
  20. package/dist/esm/chunks/markets-ui-UNB4PTA7.js +1 -0
  21. package/dist/esm/chunks/search-OU75RNQL.js +1 -0
  22. package/dist/esm/index.js +1 -1
  23. package/dist/esm/server.js +2 -1
  24. package/dist/presets/barba.esm.js +56 -36
  25. package/dist/tether.account-pages.js +776 -432
  26. package/dist/tether.account-pages.min.js +1 -1
  27. package/dist/tether.account.js +655 -321
  28. package/dist/tether.account.min.js +1 -1
  29. package/dist/tether.analytics.js +318 -191
  30. package/dist/tether.analytics.min.js +1 -1
  31. package/dist/tether.diagnose.js +334 -243
  32. package/dist/tether.diagnose.min.js +2 -2
  33. package/dist/tether.extras.js +78 -33
  34. package/dist/tether.extras.min.js +1 -1
  35. package/dist/tether.js +3171 -1998
  36. package/dist/tether.markets.js +231 -126
  37. package/dist/tether.markets.min.js +1 -1
  38. package/dist/tether.min.js +0 -0
  39. package/dist/tether.min.js.map +4 -4
  40. package/dist/tether.search.js +221 -126
  41. package/dist/tether.search.min.js +1 -1
  42. package/package.json +23 -4
  43. package/src/account/addresses-view.js +92 -0
  44. package/src/account/browser-session.js +359 -0
  45. package/src/account/markup.js +48 -0
  46. package/src/account/operations.js +180 -0
  47. package/src/account/order-lines.js +96 -0
  48. package/src/account/order-list.js +91 -0
  49. package/src/account/order-page.js +192 -0
  50. package/src/account/page-events.js +288 -0
  51. package/src/account/server-client.js +172 -0
  52. package/src/account/shared.js +111 -0
  53. package/src/account/shopify-auth.js +150 -0
  54. package/src/account/subscriptions-view.js +158 -0
  55. package/src/account-api.js +118 -0
  56. package/src/account-links.js +35 -0
  57. package/src/account-pages.js +68 -284
  58. package/src/account.js +281 -317
  59. package/src/amounts.js +36 -0
  60. package/src/analytics-shopify.js +241 -0
  61. package/src/analytics.js +304 -184
  62. package/src/api-version.js +75 -25
  63. package/src/astro.js +233 -68
  64. package/src/cart/checkout.js +97 -0
  65. package/src/cart/drawer.js +138 -0
  66. package/src/cart/mutations.js +234 -0
  67. package/src/cart/render.js +294 -0
  68. package/src/cart/store.js +326 -0
  69. package/src/cart.js +322 -481
  70. package/src/client.js +214 -78
  71. package/src/collection.js +126 -57
  72. package/src/config.js +323 -59
  73. package/src/controls/cart-controls.js +155 -0
  74. package/src/controls/discount.js +96 -0
  75. package/src/controls/extras.js +63 -0
  76. package/src/controls/navigation.js +83 -0
  77. package/src/diagnose-markup.js +333 -0
  78. package/src/diagnose.js +251 -202
  79. package/src/dom.js +219 -220
  80. package/src/extras.js +119 -37
  81. package/src/fragments.js +115 -22
  82. package/src/images.js +104 -0
  83. package/src/index.js +245 -285
  84. package/src/initial.js +78 -66
  85. package/src/lazy-iife.js +92 -22
  86. package/src/lazy.js +25 -4
  87. package/src/loader.js +263 -124
  88. package/src/market-codes.js +35 -0
  89. package/src/markets-ui.js +169 -55
  90. package/src/markets.js +286 -85
  91. package/src/markup.js +64 -0
  92. package/src/mounting.js +214 -91
  93. package/src/page-market.js +116 -0
  94. package/src/parts/account-pages.js +4 -1
  95. package/src/parts/account.js +4 -1
  96. package/src/parts/analytics.js +4 -1
  97. package/src/parts/diagnose.js +4 -1
  98. package/src/parts/extras.js +4 -1
  99. package/src/parts/markets.js +4 -1
  100. package/src/parts/search.js +4 -1
  101. package/src/presets/barba.js +120 -30
  102. package/src/product-events.js +130 -0
  103. package/src/product-render.js +257 -0
  104. package/src/product-state.js +318 -0
  105. package/src/product.js +233 -459
  106. package/src/repeaters.js +173 -0
  107. package/src/search.js +277 -107
  108. package/src/selling-plans.js +107 -47
  109. package/src/server.js +168 -205
  110. package/src/shopify-values.js +89 -0
  111. package/src/status.js +99 -39
  112. package/src/store-html.js +0 -0
  113. package/src/storefront/catalog.js +199 -0
  114. package/src/storefront/json-ld.js +167 -0
  115. package/src/variant-render.js +165 -0
  116. package/types/astro.d.ts +13 -2
  117. package/types/index.d.ts +178 -27
  118. package/types/server.d.ts +89 -17
  119. package/dist/esm/chunks/account-QUBHQG3C.js +0 -1
  120. package/dist/esm/chunks/account-pages-VWDHF6WA.js +0 -1
  121. package/dist/esm/chunks/analytics-SLATWPLC.js +0 -1
  122. package/dist/esm/chunks/chunk-64TUD3QR.js +0 -1
  123. package/dist/esm/chunks/chunk-AJLPU2JC.js +0 -4
  124. package/dist/esm/chunks/chunk-FIOZPPC5.js +0 -1
  125. package/dist/esm/chunks/chunk-K2YEQAIH.js +0 -1
  126. package/dist/esm/chunks/chunk-L2TRRKYV.js +0 -1
  127. package/dist/esm/chunks/chunk-RREHGH4A.js +0 -1
  128. package/dist/esm/chunks/chunk-VC46IEJQ.js +0 -1
  129. package/dist/esm/chunks/chunk-VCPI7MJ2.js +0 -1
  130. package/dist/esm/chunks/chunk-VPVJPNB4.js +0 -1
  131. package/dist/esm/chunks/chunk-ZIUIWEON.js +0 -1
  132. package/dist/esm/chunks/diagnose-VXQBSD3A.js +0 -14
  133. package/dist/esm/chunks/extras-R4X34VQL.js +0 -1
  134. package/dist/esm/chunks/markets-ui-F3R5T5EL.js +0 -1
  135. package/dist/esm/chunks/search-NILMGYXG.js +0 -1
@@ -0,0 +1,318 @@
1
+ /**
2
+ * What a product scope shows for the visitor's choice: the variant, the purchase it is bought as, its prices, the
3
+ * text of every `tether-bind` and every `tether-show` condition. Pure, no DOM and no config: the browser scope
4
+ * (`product.js`) and the server's `initialState()` (`initial.js`) derive their view here, so a server-rendered page
5
+ * shows what the script shows when it takes over.
6
+ */
7
+ import {
8
+ GID,
9
+ allPlans,
10
+ allocationFor,
11
+ findPlan,
12
+ planAdjustment,
13
+ planCheckoutCharge,
14
+ planPrice,
15
+ planSavings,
16
+ } from './selling-plans.js';
17
+ /** @import { Money } from './shopify-values.js' */
18
+ /** @import { Product, ProductVariant } from './fragments.js' */
19
+ /** @import { PlanInGroup } from './selling-plans.js' */
20
+
21
+ /** @typedef {Record<string, string>} Selection Option name → chosen value. */
22
+ /**
23
+ * How the visitor buys. Buying once still names the product's plan when it has plans: the plan the subscription
24
+ * binds (`subscription-price`, `plan-name`) offer next to the one-time price, and the one subscribing switches to.
25
+ *
26
+ * @typedef {{ kind: 'one-time', planId: string | null } | { kind: 'subscription', planId: string }} Purchase
27
+ */
28
+ /**
29
+ * @typedef {object} ProductChoice What the visitor chose, before it is checked against the product.
30
+ * @property {Selection} selected
31
+ * @property {Purchase} purchase
32
+ * @property {number} quantity
33
+ */
34
+ /**
35
+ * @typedef {'in-stock' | 'out-of-stock' | 'backorder' | 'on-sale' | 'not-on-sale' | 'has-variants' | 'single-variant'
36
+ * | 'low-stock' | 'plenty-in-stock' | 'subscription-available' | 'subscription-unavailable' | 'subscription-only'
37
+ * | 'one-time-available' | 'subscription-selected' | 'one-time-selected' | 'has-savings'} ShowCondition
38
+ */
39
+ /**
40
+ * @typedef {object} ProductView
41
+ * @property {ProductVariant} variant
42
+ * @property {Selection} selected The selection, matching `variant`.
43
+ * @property {Purchase} purchase The choice, made valid for the product and `variant`.
44
+ * @property {PlanInGroup | null} plan The purchase's plan, offered or chosen.
45
+ * @property {boolean} isSubscription The line is bought on `plan`: subscription chosen and the variant is on it.
46
+ * @property {boolean} subscriptionAvailable The variant is on at least one plan.
47
+ * @property {number} quantity
48
+ * @property {Money} price What one item costs as bought.
49
+ * @property {Money | null} compareAtPrice Only when on sale.
50
+ * @property {{ amount: Money | null, percentage: number }} savings What `plan` saves on the one-time price.
51
+ * @property {Record<ShowCondition, boolean>} show
52
+ */
53
+ /**
54
+ * @typedef {object} Formatters How the caller writes values as text.
55
+ * @property {(money: Money | null) => string} money
56
+ * @property {(percentage: number) => string} percent
57
+ */
58
+ /** @typedef {string | number | null | undefined} BindText What a bind writes; `null` and `undefined` clear it. */
59
+
60
+ /** Money arithmetic works in hundredths, the precision Tether shows Shopify's amounts in. */
61
+ const MINOR_UNITS_PER_UNIT = 100;
62
+ const PERCENT = 100;
63
+
64
+ /** @param {Money} money */
65
+ const toMinorUnits = (money) => Math.round(parseFloat(money.amount) * MINOR_UNITS_PER_UNIT);
66
+
67
+ /**
68
+ * @param {number} minorUnits
69
+ * @param {string} currencyCode
70
+ * @returns {Money}
71
+ */
72
+ const fromMinorUnits = (minorUnits, currencyCode) => ({
73
+ amount: (minorUnits / MINOR_UNITS_PER_UNIT).toFixed(2),
74
+ currencyCode,
75
+ });
76
+
77
+ /**
78
+ * @param {Money} money
79
+ * @param {number} quantity
80
+ */
81
+ const timesQuantity = (money, quantity) => fromMinorUnits(toMinorUnits(money) * quantity, money.currencyCode);
82
+
83
+ /**
84
+ * @param {ProductVariant} variant
85
+ * @returns {Selection}
86
+ */
87
+ export const selectionOf = (variant) =>
88
+ Object.fromEntries(variant.selectedOptions.map((option) => [option.name, option.value]));
89
+
90
+ /**
91
+ * @param {Product} product
92
+ * @param {Selection} selected
93
+ * @returns {ProductVariant | null} The variant with exactly these option values.
94
+ */
95
+ function findVariant(product, selected) {
96
+ return (
97
+ product.variants.nodes.find((variant) =>
98
+ variant.selectedOptions.every((option) => selected[option.name] === option.value),
99
+ ) ?? null
100
+ );
101
+ }
102
+
103
+ /**
104
+ * @param {Product} product
105
+ * @param {Selection} selected
106
+ * @param {string} name An option name.
107
+ * @param {string} value
108
+ * @returns {boolean} True when a variant for sale has this value and the other selected values.
109
+ */
110
+ export function isValueAvailable(product, selected, name, value) {
111
+ return product.variants.nodes.some(
112
+ (variant) =>
113
+ variant.availableForSale &&
114
+ variant.selectedOptions.every((option) =>
115
+ option.name === name ? option.value === value : selected[option.name] === option.value,
116
+ ),
117
+ );
118
+ }
119
+
120
+ /**
121
+ * The purchase made valid for the product and variant: one-time without plans, a subscription when the product
122
+ * requires one, and a plan the variant is on when it is on any (else a plan of the product, for the binds to offer).
123
+ *
124
+ * @param {Product} product
125
+ * @param {ProductVariant | null} variant
126
+ * @param {{ kind: Purchase['kind'], planId: string | null }} wanted
127
+ * @returns {Purchase}
128
+ */
129
+ export function normalisePurchase(product, variant, wanted) {
130
+ const plans = allPlans(product);
131
+ const known = plans.find((plan) => plan.id === wanted.planId) ?? plans[0];
132
+ if (!known) return { kind: 'one-time', planId: null };
133
+ const onVariant = allocationFor(variant, known.id)
134
+ ? known
135
+ : (plans.find((plan) => allocationFor(variant, plan.id)) ?? known);
136
+ if (product.requiresSellingPlan || wanted.kind === 'subscription')
137
+ return { kind: 'subscription', planId: onVariant.id };
138
+ return { kind: 'one-time', planId: onVariant.id };
139
+ }
140
+
141
+ /**
142
+ * @typedef {object} InitialChoiceOptions
143
+ * @property {string | null | undefined} [variant] A variant id or gid (`?variant=`); the first variant for sale without.
144
+ * @property {string | null | undefined} [sellingPlan] A plan to subscribe on (`?selling_plan=`).
145
+ * @property {string | null | undefined} [defaultPlan] The plan offered first, by id, name or option value.
146
+ * @property {string | null | undefined} [defaultPurchase] `subscription` subscribes; anything else buys once.
147
+ */
148
+
149
+ /**
150
+ * What a product starts with before the visitor chooses anything.
151
+ *
152
+ * @param {Product} product
153
+ * @param {InitialChoiceOptions} options
154
+ * @returns {Omit<ProductChoice, 'quantity'>}
155
+ */
156
+ export function initialChoice(product, { variant, sellingPlan, defaultPlan, defaultPurchase }) {
157
+ const variants = product.variants.nodes;
158
+ const wantedId = GID.variant(variant);
159
+ const start =
160
+ variants.find((candidate) => candidate.id === wantedId) ??
161
+ variants.find((candidate) => candidate.availableForSale) ??
162
+ variants[0] ??
163
+ null;
164
+ const fromUrl = findPlan(product, sellingPlan);
165
+ const offered = fromUrl ?? findPlan(product, defaultPlan);
166
+ const kind = fromUrl || defaultPurchase === 'subscription' ? 'subscription' : 'one-time';
167
+ return {
168
+ selected: start ? selectionOf(start) : {},
169
+ purchase: normalisePurchase(product, start, { kind, planId: offered?.id ?? null }),
170
+ };
171
+ }
172
+
173
+ /**
174
+ * @param {ProductVariant} variant
175
+ * @param {number} lowStock
176
+ * @param {number} variantCount
177
+ * @param {Pick<ProductView, 'isSubscription' | 'subscriptionAvailable' | 'compareAtPrice' | 'savings'>} sale
178
+ * @param {boolean} requiresSellingPlan
179
+ * @returns {Record<ShowCondition, boolean>}
180
+ */
181
+ function showConditions(variant, lowStock, variantCount, sale, requiresSellingPlan) {
182
+ const stock = variant.quantityAvailable;
183
+ const low = stock != null && stock > 0 && stock <= lowStock;
184
+ const onSale = sale.compareAtPrice !== null;
185
+ return {
186
+ 'in-stock': variant.availableForSale,
187
+ 'out-of-stock': !variant.availableForSale,
188
+ backorder: variant.availableForSale && variant.currentlyNotInStock,
189
+ 'on-sale': onSale,
190
+ 'not-on-sale': !onSale,
191
+ 'has-variants': variantCount > 1,
192
+ 'single-variant': variantCount === 1,
193
+ 'low-stock': low,
194
+ 'plenty-in-stock': variant.availableForSale && !low,
195
+ 'subscription-available': sale.subscriptionAvailable,
196
+ 'subscription-unavailable': !sale.subscriptionAvailable,
197
+ 'subscription-only': requiresSellingPlan,
198
+ 'one-time-available': !requiresSellingPlan,
199
+ 'subscription-selected': sale.isSubscription,
200
+ 'one-time-selected': !sale.isSubscription,
201
+ 'has-savings': sale.isSubscription ? sale.savings.percentage > 0 : onSale,
202
+ };
203
+ }
204
+
205
+ /**
206
+ * The view for the visitor's choice. A selection no variant has falls back to the first variant.
207
+ *
208
+ * @param {Product} product
209
+ * @param {ProductChoice} choice
210
+ * @param {number} lowStock `low-stock` at this many or fewer.
211
+ * @returns {ProductView | null} `null` for a product without variants.
212
+ */
213
+ export function productView(product, choice, lowStock) {
214
+ const exact = findVariant(product, choice.selected);
215
+ const variant = exact ?? product.variants.nodes[0];
216
+ if (!variant) return null;
217
+ const purchase = normalisePurchase(product, variant, choice.purchase);
218
+ const { planId } = purchase;
219
+ const plans = allPlans(product);
220
+ const allocation = purchase.kind === 'subscription' ? allocationFor(variant, planId) : null;
221
+ // The plan helpers fall back to the one-time price only without a variant, which `variant` rules out.
222
+ const price = allocation ? (planPrice(variant, planId) ?? variant.price) : variant.price;
223
+ const compareAt = allocation?.priceAdjustments[0]?.compareAtPrice ?? variant.compareAtPrice;
224
+ const sale = {
225
+ isSubscription: allocation !== null,
226
+ subscriptionAvailable: plans.some((plan) => allocationFor(variant, plan.id)),
227
+ compareAtPrice: compareAt && parseFloat(compareAt.amount) > parseFloat(price.amount) ? compareAt : null,
228
+ savings: planSavings(variant, planId),
229
+ };
230
+ return {
231
+ ...sale,
232
+ variant,
233
+ selected: exact ? choice.selected : selectionOf(variant),
234
+ purchase,
235
+ plan: plans.find((plan) => plan.id === planId) ?? null,
236
+ quantity: choice.quantity,
237
+ price,
238
+ show: showConditions(variant, lowStock, product.variants.nodes.length, sale, product.requiresSellingPlan),
239
+ };
240
+ }
241
+
242
+ /**
243
+ * The `tether-bind` values that follow the variant and purchase. Thunks, so only the binds on the page are computed.
244
+ *
245
+ * @param {ProductView} view
246
+ * @param {Formatters} format
247
+ * @returns {Map<string, () => BindText>}
248
+ */
249
+ export function variantBindTexts(view, format) {
250
+ const { variant, plan, price, compareAtPrice, quantity } = view;
251
+ const planId = view.purchase.planId;
252
+ // Prices for the quantity count one item when it is 0 (an optional bundle item).
253
+ const forQuantity = (/** @type {Money} */ money) => timesQuantity(money, Math.max(1, quantity));
254
+ const checkoutCharge = () => {
255
+ const charge = view.isSubscription ? (planCheckoutCharge(variant, planId) ?? price) : price;
256
+ return format.money(forQuantity(charge));
257
+ };
258
+ const discountPercentage = () => {
259
+ if (!compareAtPrice) return '0%';
260
+ return `${Math.round((1 - parseFloat(price.amount) / parseFloat(compareAtPrice.amount)) * PERCENT)}%`;
261
+ };
262
+ const discountAmount = () => {
263
+ if (!compareAtPrice) return '';
264
+ return format.money(fromMinorUnits(toMinorUnits(compareAtPrice) - toMinorUnits(price), price.currencyCode));
265
+ };
266
+ /** @type {Record<string, () => BindText>} */
267
+ const texts = {
268
+ price: () => format.money(price),
269
+ 'total-price': () => format.money(forQuantity(price)),
270
+ 'one-time-price': () => format.money(variant.price),
271
+ 'subscription-price': () => format.money(planId ? planPrice(variant, planId) : null),
272
+ 'subscription-savings': () => format.percent(view.savings.percentage),
273
+ 'subscription-savings-amount': () => format.money(view.savings.amount),
274
+ 'checkout-charge': checkoutCharge,
275
+ 'plan-name': () => plan?.name,
276
+ 'plan-description': () => plan?.description,
277
+ 'plan-group': () => plan?.group.name,
278
+ 'compare-at-price': () => format.money(compareAtPrice),
279
+ 'unit-price': () => format.money(variant.unitPrice),
280
+ 'discount-percentage': discountPercentage,
281
+ 'discount-amount': discountAmount,
282
+ 'variant-title': () => variant.title,
283
+ 'variant-id': () => variant.id,
284
+ sku: () => variant.sku,
285
+ barcode: () => variant.barcode,
286
+ stock: () => variant.quantityAvailable,
287
+ quantity: () => quantity,
288
+ };
289
+ return new Map(Object.entries(texts));
290
+ }
291
+ /**
292
+ * The `tether-plan-bind` values of one plan in a plan list, for the variant.
293
+ *
294
+ * @param {ProductVariant} variant
295
+ * @param {string} planId The list item's `tether-plan-value`.
296
+ * @param {PlanInGroup | undefined} plan The product's plan with that id.
297
+ * @param {Formatters} format
298
+ * @returns {Map<string, () => BindText>}
299
+ */
300
+ export function planBindTexts(variant, planId, plan, format) {
301
+ const adjustmentText = () => {
302
+ const adjustment = planAdjustment(plan);
303
+ if (!adjustment) return '';
304
+ return adjustment.type === 'percentage' ? `${adjustment.value}%` : format.money(adjustment.value);
305
+ };
306
+ /** @type {Record<string, () => BindText>} */
307
+ const texts = {
308
+ name: () => plan?.name,
309
+ // The option values alone ("1 month"), without the price text a store may put in the plan name.
310
+ option: () => (plan?.options ?? []).map((option) => option.value).join(', '),
311
+ description: () => plan?.description,
312
+ price: () => format.money(planPrice(variant, planId)),
313
+ savings: () => format.percent(planSavings(variant, planId).percentage),
314
+ 'savings-amount': () => format.money(planSavings(variant, planId).amount),
315
+ adjustment: adjustmentText,
316
+ };
317
+ return new Map(Object.entries(texts));
318
+ }