@moonbase.sh/react 0.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +127 -16
- package/dist/index.cjs +2002 -0
- package/dist/index.d.cts +910 -0
- package/dist/index.d.ts +910 -0
- package/dist/index.js +2005 -0
- package/package.json +42 -4
package/README.md
CHANGED
|
@@ -31,7 +31,8 @@ createRoot(document.getElementById('root')!).render(
|
|
|
31
31
|
|
|
32
32
|
Make the storefront at module level, not in a component: it reads the address the visitor arrived at, keeps the cart
|
|
33
33
|
in step with other tabs, and coming back from the hosted checkout it reopens the checkout and takes Moonbase's `mb_*`
|
|
34
|
-
parameters off the address. Make it before your router, which reads the address as it is made.
|
|
34
|
+
parameters off the address. Make it before your router, which reads the address as it is made. Where it has to be made
|
|
35
|
+
in a component, such as from a catalog the server fetched, use `getStorefront` (see [Server rendering](#server-rendering)).
|
|
35
36
|
|
|
36
37
|
## Use hooks in components
|
|
37
38
|
|
|
@@ -64,7 +65,8 @@ export function Shop() {
|
|
|
64
65
|
```
|
|
65
66
|
|
|
66
67
|
Hooks return plain values, and a component renders again only when the part of the storefront it reads changes:
|
|
67
|
-
adding to the cart renders the cart's components, not every product card.
|
|
68
|
+
adding to the cart renders the cart's components, not every product card. So a product card prices itself with
|
|
69
|
+
`usePrice` and adds to the cart with `useCartActions`, rather than reading the whole cart with `useCart`. Every function a hook returns keeps its
|
|
68
70
|
identity across renders, so it can go in a dependency list or to a memoized child.
|
|
69
71
|
|
|
70
72
|
## Main hooks
|
|
@@ -79,7 +81,11 @@ identity across renders, so it can go in a dependency list or to a memoized chil
|
|
|
79
81
|
- `usePromotions()` - the sales currently running across the catalog. Already filtered by the API to what is live and
|
|
80
82
|
applies to the current visitor, so render them as they are.
|
|
81
83
|
- `useCart()` - the lines, totals and price breakdown, `soldOutItems`, and `addToCart`, `setQuantity`,
|
|
82
|
-
`removeFromCart` and `checkout`.
|
|
84
|
+
`removeFromCart` and `checkout`. It renders again on every change to the cart.
|
|
85
|
+
- `usePrice(variation)` - a pricing option's `price`, `originalPrice` and `saving` (the last two only with a discount),
|
|
86
|
+
written in the visitor's currency as the checkout writes them, plus `amount` for adding prices up. `useCurrency()` is
|
|
87
|
+
that currency, and `useCartActions()` is `addToCart` and the rest without the cart. None of the three renders again
|
|
88
|
+
when the cart changes, so they suit product cards.
|
|
83
89
|
- `useEligibleOffers()`, `useLockedOffers()`, `useCartOffer()` - the upsells the cart qualifies for, the offers it is
|
|
84
90
|
short of and by how much, and the cart offer it has earned or is working toward.
|
|
85
91
|
- `useCheckout()` - buying straight away without the cart: `const checkout = useCheckout()`, then
|
|
@@ -91,9 +97,13 @@ identity across renders, so it can go in a dependency list or to a memoized chil
|
|
|
91
97
|
- `useInventory()` - owned products, licenses and the computers they're activated on, downloads, and subscriptions:
|
|
92
98
|
cancelling, renewing, changing plan and changing the card they're paid with.
|
|
93
99
|
- `useOrders()` - the signed-in customer's completed orders, newest first, and their receipt PDFs.
|
|
100
|
+
- `useOwnedProducts()`, `useOwnedProduct(id)`, `useProductActivations(id)`, `useProductLicenses(id)`,
|
|
101
|
+
`useOrderHistory()`, `useSubscriptions()`, `useSubscription(id)` - the signed-in customer's account data, loaded for
|
|
102
|
+
you (see [Account pages](#account-pages)).
|
|
94
103
|
- `useVoucher()` - what a voucher code gives, and redeeming it.
|
|
95
|
-
- `useActivationRequest(token)` - activating a product in the browser: the request the app made, granting it a
|
|
96
|
-
or a trial, and waiting for the app to pick it up.
|
|
104
|
+
- `useActivationRequest(token, options)` - activating a product in the browser: the request the app made, granting it a
|
|
105
|
+
license or a trial, and waiting for the app to pick it up. With `{ autoFulfill: true }` it activates with the signed-in
|
|
106
|
+
customer's license as soon as the request says they can, once per request, leaving a failure in `error`.
|
|
97
107
|
- `useGroups()` - join the signed-in customer to a customer list of the store's that has been opened to sign-ups.
|
|
98
108
|
Throws `NotFoundError` for every reason a join can be refused, which the API deliberately does not distinguish.
|
|
99
109
|
- `useReviews()` - product reviews: `enabled` says whether the store takes them, `getReviews` and `getMoreReviews` read
|
|
@@ -102,8 +112,11 @@ identity across renders, so it can go in a dependency list or to a memoized chil
|
|
|
102
112
|
with the catalog, and `hasRating(rating)` says whether there is a score worth showing yet.
|
|
103
113
|
- `useCommunicationPreferences()` - newsletter sign-ups, and the preferences page an email's footer links to.
|
|
104
114
|
- `useVendor()` - who runs the store.
|
|
115
|
+
- `useAttributionConsent()` - what a cookie banner of your own needs: whether the store asks this visitor, their
|
|
116
|
+
remembered answer, and `setAnswer`. See [Attribution and consent](#attribution-and-consent).
|
|
105
117
|
- `useStorefront()` - the storefront itself, and `useStorefrontState(state => ...)` for any part of its state
|
|
106
|
-
(`
|
|
118
|
+
(`attributionConsentAnswer`, `attributionConsentRequired`, `attributionConsentStatus`, `catalog`, `catalogLoaded`,
|
|
119
|
+
`closed`, `order`, `user`, `userLoaded`, `utm`).
|
|
107
120
|
|
|
108
121
|
### Where checkout happens
|
|
109
122
|
|
|
@@ -150,6 +163,45 @@ function CheckoutButton() {
|
|
|
150
163
|
}
|
|
151
164
|
```
|
|
152
165
|
|
|
166
|
+
## Account pages
|
|
167
|
+
|
|
168
|
+
The account data hooks load what they show for whoever is signed in, and load it again when that changes. Each returns
|
|
169
|
+
`{ data, loading, error, reload }`, and the lists, which Moonbase hands out a page at a time, add `hasMore` and
|
|
170
|
+
`loadMore`, with `data` holding every page loaded so far:
|
|
171
|
+
|
|
172
|
+
```tsx
|
|
173
|
+
import { useOrderHistory } from '@moonbase.sh/react'
|
|
174
|
+
|
|
175
|
+
function Purchases() {
|
|
176
|
+
const orders = useOrderHistory()
|
|
177
|
+
|
|
178
|
+
if (orders.error)
|
|
179
|
+
return <p role="alert">{orders.error.message}</p>
|
|
180
|
+
if (!orders.data)
|
|
181
|
+
return <p>Loading…</p>
|
|
182
|
+
|
|
183
|
+
return (
|
|
184
|
+
<>
|
|
185
|
+
{orders.data.length === 0 && <p>No purchases yet.</p>}
|
|
186
|
+
<ul>
|
|
187
|
+
{orders.data.map(order => <li key={order.id}>{order.id}</li>)}
|
|
188
|
+
</ul>
|
|
189
|
+
{orders.hasMore && (
|
|
190
|
+
<button disabled={orders.loading} onClick={orders.loadMore}>Show more</button>
|
|
191
|
+
)}
|
|
192
|
+
</>
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`data` is null while it first loads, with nobody signed in, and for an ID of `null` or `undefined`, which asks for nothing.
|
|
198
|
+
`loading` is true while a request is in flight and until the storefront knows who is signed in, so a page doesn't flash
|
|
199
|
+
"Nothing here" before it does. What a hook loaded is kept for as long as the same customer is signed in: a component
|
|
200
|
+
that mounts again, such as a tab the customer comes back to, shows it at once and asks again in the background.
|
|
201
|
+
Components asking for the same thing at once share one request. After changing something, call `reload`, which goes
|
|
202
|
+
back to a list's first page. `reload` and `loadMore` never reject: a failure lands in `error`, and `data` keeps what was
|
|
203
|
+
there.
|
|
204
|
+
|
|
153
205
|
## Checkout events
|
|
154
206
|
|
|
155
207
|
```tsx
|
|
@@ -183,6 +235,10 @@ your page is not loaded then: subscribe a webhook to `OrderPaymentFailed` to fol
|
|
|
183
235
|
|
|
184
236
|
Outside of React, `storefront.on('checkoutCompleted', order => ...)` does the same and returns the function that stops it.
|
|
185
237
|
|
|
238
|
+
`useStorefrontEvent` starts listening once its component has mounted, so it misses what the storefront reported before
|
|
239
|
+
then, such as the first `catalogUpdated` on a slow phone. Read what a page needs from the start from the state with
|
|
240
|
+
`useStorefrontState`, or subscribe with `storefront.on` where the storefront is made.
|
|
241
|
+
|
|
186
242
|
## Outside of components
|
|
187
243
|
|
|
188
244
|
Nothing in the storefront depends on React, so a router loader, an analytics script or your own store can use it
|
|
@@ -205,13 +261,13 @@ async function loader() {
|
|
|
205
261
|
|
|
206
262
|
The storefront reads the UTM tags, campaign IDs (`utm_id`, `gad_source`, `gad_campaignid`), referrer and ad click IDs
|
|
207
263
|
(`gclid`, `gbraid`, `wbraid`, `fbclid`, `msclkid`, `ttclid`) the visitor arrived with, and sends them with the cart,
|
|
208
|
-
checkout
|
|
209
|
-
it keeps and sends only the platforms they came from (`utm.adClicks`), not the IDs, and records a
|
|
210
|
-
order only with the first thing put in the cart. The campaign IDs name a campaign, not a visitor,
|
|
211
|
-
either way. Until you say whether they agreed, it follows the store's setting in Moonbase (Account
|
|
212
|
-
Storefront > "Features" > "Ad and campaign tracking": always, only outside the EEA, the UK and Switzerland,
|
|
213
|
-
cookie consent), which the catalog reports for this visitor. Pass `attributionConsent` to
|
|
214
|
-
later from your cookie banner, and that wins:
|
|
264
|
+
checkout, sign-up, trials and downloads. A click ID identifies the visitor's click, so without the visitor's consent to
|
|
265
|
+
marketing cookies it keeps and sends only the platforms they came from (`utm.adClicks`), not the IDs, and records a
|
|
266
|
+
tagged arrival on the order only with the first thing put in the cart. The campaign IDs name a campaign, not a visitor,
|
|
267
|
+
so they are kept either way. Until you say whether they agreed, it follows the store's setting in Moonbase (Account
|
|
268
|
+
settings > Storefront > "Features" > "Ad and campaign tracking": always, only outside the EEA, the UK and Switzerland,
|
|
269
|
+
or only with cookie consent), which the catalog reports for this visitor. Pass `attributionConsent` to
|
|
270
|
+
`createStorefront`, or tell it later from your cookie banner, and that wins:
|
|
215
271
|
|
|
216
272
|
```ts
|
|
217
273
|
onMarketingConsent(granted => storefront.setAttributionConsent(granted))
|
|
@@ -226,22 +282,77 @@ onConsentUpdate(({ adUserData, adPersonalization }) => storefront.setAttribution
|
|
|
226
282
|
|
|
227
283
|
The cart, checkout, sign-up, trial, newsletter subscription and download requests also tell Moonbase what your banner
|
|
228
284
|
reported (nothing until it reports) and when and on which page (origin and path only) a tagged visit first landed.
|
|
229
|
-
|
|
285
|
+
Where the store connected Meta or Google Analytics in Moonbase, and the visitor's consent lets click IDs go, they also
|
|
286
|
+
carry the visitor's Meta and Google Analytics browser IDs (read from the `_fbp`, `_fbc`, `_ga` and `_ga_<stream>`
|
|
287
|
+
cookies as each request is made) and the page's origin and path. `storefront.adSignals()` returns what they send, and
|
|
288
|
+
`attributionConsentStatus` in the storefront's state says where the visitor's consent stands (`'granted'`, `'refused'`
|
|
289
|
+
or `'unknown'`). A browser that sends Global Privacy Control counts as refusing for each platform the store has not set
|
|
290
|
+
to ignore it in Moonbase: no browser IDs go for that platform, and `attributionConsentStatusByPlatform` in the state
|
|
291
|
+
says where consent stands for `meta` and `googleAnalytics` each. `attributionConsentStatus` is `'refused'` for it unless
|
|
292
|
+
the store set every platform it connected to ignore it. When your banner reports a refusal for a signed-in customer, or the browser sends Global Privacy Control, the
|
|
293
|
+
storefront tells Moonbase, once per tab.
|
|
294
|
+
|
|
295
|
+
A cookie banner of your own gets what it needs from `useAttributionConsent()`. `required` says whether the store's
|
|
296
|
+
setting asks this visitor at all: `true` or `false` once the browser has loaded the catalog for them, and `undefined`
|
|
297
|
+
until then, since a catalog fetched on a server describes where the server is. `answer` is the visitor's answer, or
|
|
298
|
+
`null` until they give one, and `setAnswer` records it. The storefront remembers the answer in the browser
|
|
299
|
+
(`moonbase_attribution_consent` in local storage) and starts from it on the next visit, unless you pass
|
|
300
|
+
`attributionConsent` to `createStorefront`:
|
|
301
|
+
|
|
302
|
+
```tsx
|
|
303
|
+
function CookieBanner() {
|
|
304
|
+
const { required, answer, setAnswer } = useAttributionConsent()
|
|
305
|
+
|
|
306
|
+
if (!required || answer !== null)
|
|
307
|
+
return null
|
|
308
|
+
|
|
309
|
+
return (
|
|
310
|
+
<div role="dialog">
|
|
311
|
+
<button onClick={() => setAnswer(true)}>Accept</button>
|
|
312
|
+
<button onClick={() => setAnswer(false)}>Decline</button>
|
|
313
|
+
</div>
|
|
314
|
+
)
|
|
315
|
+
}
|
|
316
|
+
```
|
|
317
|
+
|
|
318
|
+
A consent manager that reports on every page keeps calling `storefront.setAttributionConsent` instead, which remembers
|
|
319
|
+
nothing.
|
|
230
320
|
|
|
231
321
|
## Server rendering
|
|
232
322
|
|
|
323
|
+
`fetchCatalog(endpoint, options)` fetches the catalog on a server, as anyone sees it, for the `initialCatalog` a page's
|
|
324
|
+
storefront starts from (below). Its `fetch` option goes to `fetch` with the request, so a Next.js page can cache the
|
|
325
|
+
catalog on its own schedule rather than revalidating the whole route:
|
|
326
|
+
|
|
327
|
+
```ts
|
|
328
|
+
const catalog = await fetchCatalog('https://demo.moonbase.sh', { fetch: { next: { revalidate: 3600 } } })
|
|
329
|
+
```
|
|
330
|
+
|
|
233
331
|
The storefront can be made on a server, where it has no visitor: no cart, nobody signed in, and nothing sent. A
|
|
234
332
|
storefront made at module level in a client module, as above, renders on the server with an empty catalog, so show your
|
|
235
333
|
own fallback prices until it loads, and the browser takes over from there. The browser hydrates against that same
|
|
236
334
|
server state before switching to its own, so a catalog it cached on an earlier visit never causes a hydration mismatch.
|
|
237
335
|
|
|
238
|
-
To have the server render real prices, fetch the catalog there and start the page's storefront from it
|
|
336
|
+
To have the server render real prices, fetch the catalog there and start the page's storefront from it. The storefront
|
|
337
|
+
is then made in a component, so make it with `getStorefront`, which hands back the same storefront every time in a
|
|
338
|
+
browser and a new one for each render on a server:
|
|
239
339
|
|
|
240
340
|
```tsx
|
|
241
341
|
'use client'
|
|
242
342
|
|
|
243
343
|
export function Providers({ catalog, children }: { catalog: Storefront, children: ReactNode }) {
|
|
244
|
-
const
|
|
344
|
+
const storefront = getStorefront('https://demo.moonbase.sh', { initialCatalog: catalog })
|
|
245
345
|
return <StorefrontProvider storefront={storefront}>{children}</StorefrontProvider>
|
|
246
346
|
}
|
|
247
347
|
```
|
|
348
|
+
|
|
349
|
+
Not `createStorefront` in a `useState` initializer: React runs one twice under Strict Mode, and the storefront it throws
|
|
350
|
+
away would go on following the tab. The options only count the first time, when the storefront is made.
|
|
351
|
+
|
|
352
|
+
A router that reads the address before the storefront is made, as Next.js's does, puts the hosted checkout's `mb_*`
|
|
353
|
+
parameters back as the page hydrates. `<StorefrontProvider>` takes them off again once the page has hydrated, and tells
|
|
354
|
+
the router with a `popstate`, so `useSearchParams()` no longer lists them either.
|
|
355
|
+
|
|
356
|
+
`storefront.dispose()` stops a storefront for good: it stops following other tabs and the checkout, stops renewing the
|
|
357
|
+
customer's sign-in, and ignores what its requests still in flight bring back. That is for tests, or a page that swaps one
|
|
358
|
+
storefront for another. After it, `getStorefront` makes a new one.
|