@backgold/template-kit 0.1.0 → 0.1.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/dist/{chunk-KOB36GSF.js → chunk-RJAVFRC6.js} +9 -4
- package/dist/{constants-DvTNj4JI.d-Batjcj3Z.d.ts → constants-BAIo_Q5U.d-lQbj1e1-.d.ts} +11 -1
- package/dist/{content-api-CYeY0vU8.d.ts → content-api-Cox1-wz5.d.ts} +250 -3
- package/dist/contract/content-api-examples.d.ts +17 -3
- package/dist/contract/content-api-examples.js +146 -3
- package/dist/contract/content-api.d.ts +2 -2
- package/dist/contract/content-api.js +1 -1
- package/dist/contract/site-templates.d.ts +4 -3
- package/dist/contract/site-templates.js +1 -1
- package/package.json +5 -5
- package/src/components/chrome/Brand.astro +23 -16
- package/src/components/sections/About/credentials.ts +0 -10
- package/src/components/sections/About/index.astro +6 -3
- package/src/components/sections/About/left.astro +6 -3
- package/src/components/sections/About/letter.astro +6 -3
- package/src/components/sections/About/portrait.astro +2 -2
- package/src/components/sections/ContentPost/lesson.ts +14 -7
- package/src/components/sections/ContentPost/prose.astro +80 -0
- package/src/components/sections/Hero/cover.astro +9 -3
- package/src/components/sections/Hero/donate.astro +3 -3
- package/src/components/sections/Hero/index.astro +2 -2
- package/src/components/sections/Hero/overlap.astro +3 -3
- package/src/components/sections/Hero/split.astro +9 -6
- package/src/components/sections/Hero/statement.astro +3 -3
- package/src/components/sections/Hero/video.astro +3 -3
- package/src/components/sections/VoterTools/Lookup.astro +43 -0
- package/src/components/sections/VoterTools/dates.astro +9 -5
- package/src/components/sections/VoterTools/index.astro +12 -9
- package/src/components/sections/VoterTools/polling.astro +9 -6
- package/src/components/sections/VoterTools/voter-tools.ts +5 -4
- package/src/components/sections/index.ts +3 -0
- package/src/components/sections/modules/ModuleFrame.astro +4 -2
- package/src/components/store/CollectionPage.astro +40 -0
- package/src/components/store/ProductCard.astro +32 -0
- package/src/components/store/ProductGrid.astro +16 -0
- package/src/components/store/ProductPage.astro +146 -0
- package/src/components/store/StorePage.astro +137 -0
- package/src/components/store/StoreScript.astro +572 -0
- package/src/components/volunteer/props.ts +1 -1
- package/src/index.js +0 -1
- package/src/layouts/Site.astro +19 -3
- package/src/lib/chrome.ts +6 -4
- package/src/lib/donate-frame.ts +44 -4
- package/src/lib/live.ts +6 -5
- package/src/lib/section.ts +11 -0
- package/src/lib/shifts.ts +2 -1
- package/src/lib/store.ts +521 -0
- package/src/routes/catch-all.astro +168 -19
- package/src/styles/site.css +71 -0
- package/src/styles/store.css +634 -0
- package/src/template.ts +1 -1
- package/src/routes/volunteer.astro +0 -37
package/src/lib/chrome.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The site's header and footer as BackGold's operator set them up: GET /site's
|
|
2
|
-
// `chrome` (each part's layout
|
|
2
|
+
// `chrome` (each part's layout, the header's name beside the logo and the
|
|
3
|
+
// footer's own words), against what the
|
|
3
4
|
// template's template.json `chrome` (its config's manifest) says it draws. A
|
|
4
5
|
// layout the site names that the template does not list is drawn as the
|
|
5
6
|
// template's first, exactly as a section's variant falls back; a `/site`
|
|
@@ -28,7 +29,8 @@ export interface ClosingCall {
|
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
export interface SiteChrome {
|
|
31
|
-
|
|
32
|
+
/** `showName`: the name in type beside the organization's logo (off unless the operator turned it on). */
|
|
33
|
+
header: { layout: HeaderLayout; showName: boolean }
|
|
32
34
|
footer: {
|
|
33
35
|
layout: FooterLayout
|
|
34
36
|
blurb: string | null
|
|
@@ -43,7 +45,7 @@ export interface SiteChrome {
|
|
|
43
45
|
/** What `/site` carries, read structurally so an older answer still parses. */
|
|
44
46
|
interface Raw {
|
|
45
47
|
chrome?: {
|
|
46
|
-
header?: { layout?: unknown }
|
|
48
|
+
header?: { layout?: unknown; show_name?: unknown }
|
|
47
49
|
footer?: {
|
|
48
50
|
layout?: unknown
|
|
49
51
|
blurb?: unknown
|
|
@@ -100,7 +102,7 @@ export function chromeOf(site: unknown, manifest: SiteTemplateManifest): SiteChr
|
|
|
100
102
|
}
|
|
101
103
|
: null
|
|
102
104
|
return {
|
|
103
|
-
header: { layout: drawn(manifest.chrome.header, raw.header?.layout) },
|
|
105
|
+
header: { layout: drawn(manifest.chrome.header, raw.header?.layout), showName: raw.header?.show_name === true },
|
|
104
106
|
footer: {
|
|
105
107
|
layout,
|
|
106
108
|
blurb: str(footer.blurb),
|
package/src/lib/donate-frame.ts
CHANGED
|
@@ -54,11 +54,51 @@ export function carriesDonateQuery(page: URLSearchParams): boolean {
|
|
|
54
54
|
return false
|
|
55
55
|
}
|
|
56
56
|
|
|
57
|
-
/** Whether a page with these sections and areas draws a
|
|
58
|
-
|
|
59
|
-
if (sections.some((s) =>
|
|
57
|
+
/** Whether a page with these sections and areas draws a frame of a type `draws` names anywhere. */
|
|
58
|
+
function drawsFrame(sections: Section[], areas: Areas | null, draws: (type: string) => boolean): boolean {
|
|
59
|
+
if (sections.some((s) => draws(s.type))) return true
|
|
60
60
|
for (const items of Object.values(areas ?? {})) {
|
|
61
|
-
for (const item of items) if (item.sections.some((s) =>
|
|
61
|
+
for (const item of items) if (item.sections.some((s) => draws(s.type))) return true
|
|
62
62
|
}
|
|
63
63
|
return false
|
|
64
64
|
}
|
|
65
|
+
|
|
66
|
+
/** Whether a page with these sections and areas draws a Donate frame anywhere. */
|
|
67
|
+
export function drawsDonateFrame(sections: Section[], areas: Areas | null): boolean {
|
|
68
|
+
return drawsFrame(sections, areas, isDonateFrame)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// ── A form frame's share of the page's address ──────────────────────────────
|
|
72
|
+
//
|
|
73
|
+
// A link to a page's form may name the choice it opens on: a site's open
|
|
74
|
+
// roles link to `/volunteer?pick=Phone%20Banker`, and the form's first
|
|
75
|
+
// Choose-one field offering that value takes it (BackGold's FormBlock frame
|
|
76
|
+
// reads `pick` off its own address). The frame copies the page's `pick`
|
|
77
|
+
// as it copies the donate names, and a page that draws a form frame says it
|
|
78
|
+
// reads the name (READS_QUERY_HEADER) the same way.
|
|
79
|
+
|
|
80
|
+
const FORM_FRAME_TYPES = new Set(['FormBlock'])
|
|
81
|
+
const PICK_NAME = 'pick'
|
|
82
|
+
/** The value of the page's READS_QUERY_HEADER when it draws a form frame. */
|
|
83
|
+
export const FORM_READS_QUERY = PICK_NAME
|
|
84
|
+
|
|
85
|
+
/** Whether a frame of this module type takes the page's `pick`. */
|
|
86
|
+
export function isFormFrame(type: string): boolean {
|
|
87
|
+
return FORM_FRAME_TYPES.has(type)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The frame's address with the page's `pick` added, when the page carries one the address does not. */
|
|
91
|
+
export function withPickQuery(frame: URL, page: URLSearchParams): void {
|
|
92
|
+
const pick = page.get(PICK_NAME)
|
|
93
|
+
if (pick && !frame.searchParams.has(PICK_NAME)) frame.searchParams.set(PICK_NAME, pick)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Whether the page's address carries a `pick` with a value. */
|
|
97
|
+
export function carriesPickQuery(page: URLSearchParams): boolean {
|
|
98
|
+
return !!page.get(PICK_NAME)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Whether a page with these sections and areas draws a form frame anywhere. */
|
|
102
|
+
export function drawsFormFrame(sections: Section[], areas: Areas | null): boolean {
|
|
103
|
+
return drawsFrame(sections, areas, isFormFrame)
|
|
104
|
+
}
|
package/src/lib/live.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Where a visitor's browser reads an event's live counts: the Content API's
|
|
2
2
|
// `GET /events/live?ids=`, which answers `{ events: [{ id, going, seats_left }] }`
|
|
3
3
|
// (and a volunteer shift's, `GET /shifts/live?ids=`, `{ shifts: [{ id,
|
|
4
|
-
// signed_up, waitlisted, state }] }`,
|
|
4
|
+
// signed_up, waitlisted, state }] }`, and a store listing's price,
|
|
5
|
+
// availability and questions, `GET /products/live?ids=`, the same way)
|
|
5
6
|
// outside the content version (`Cache-Control: public, max-age=30`). The page
|
|
6
7
|
// around the counts is cached under the content version, so the counts are
|
|
7
8
|
// never part of it: a few lines of script fetch them after the page loads.
|
|
@@ -23,17 +24,17 @@
|
|
|
23
24
|
import { apiOrigin, trimmed, workerVars } from './env'
|
|
24
25
|
|
|
25
26
|
const PUBLISHABLE_KEY = /^bg_site_pk_[A-Za-z0-9]+$/
|
|
26
|
-
/** The live routes: an event's going and seats left, a volunteer shift's signed up and state. */
|
|
27
|
-
const LIVE_PATHS = { events: '/api/content/v1/events/live', shifts: '/api/content/v1/shifts/live' } as const
|
|
27
|
+
/** The live routes: an event's going and seats left, a volunteer shift's signed up and state, a store listing's price and availability. */
|
|
28
|
+
const LIVE_PATHS = { events: '/api/content/v1/events/live', shifts: '/api/content/v1/shifts/live', products: '/api/content/v1/products/live' } as const
|
|
28
29
|
|
|
29
30
|
export interface LiveSource {
|
|
30
|
-
/** The same-origin path (first-party), else `<api origin>/api/content/v1/events/live` (or `/shifts/live`). */
|
|
31
|
+
/** The same-origin path (first-party), else `<api origin>/api/content/v1/events/live` (or `/shifts/live`, `/products/live`). */
|
|
31
32
|
url: string
|
|
32
33
|
/** The publishable key the browser sends; null first-party, where none is sent. */
|
|
33
34
|
key: string | null
|
|
34
35
|
}
|
|
35
36
|
|
|
36
|
-
/** The live route for this site (see above), events' or
|
|
37
|
+
/** The live route for this site (see above), events', shifts' or products'; null when a key-mode site has nothing to ask with. */
|
|
37
38
|
export async function liveSource(firstParty: boolean, feed: keyof typeof LIVE_PATHS = 'events'): Promise<LiveSource | null> {
|
|
38
39
|
const path = LIVE_PATHS[feed]
|
|
39
40
|
if (firstParty) return { url: path, key: null }
|
package/src/lib/section.ts
CHANGED
|
@@ -33,6 +33,17 @@ export function media(section: Section, ...keys: string[]): Media | null {
|
|
|
33
33
|
return null
|
|
34
34
|
}
|
|
35
35
|
|
|
36
|
+
/**
|
|
37
|
+
* A Hero's or an About's photo treatment (`options.photoStyle`), as
|
|
38
|
+
* BackGold's own blocks read it: 'photo' (the default) crops the picture to
|
|
39
|
+
* fill its frame; 'badge' and 'plain' show the whole picture (a logo, an
|
|
40
|
+
* illustration), on the frame's surface or on nothing.
|
|
41
|
+
*/
|
|
42
|
+
export function photoStyleOf(section: Section): 'photo' | 'badge' | 'plain' {
|
|
43
|
+
const style = section.options?.photoStyle
|
|
44
|
+
return style === 'badge' || style === 'plain' ? style : 'photo'
|
|
45
|
+
}
|
|
46
|
+
|
|
36
47
|
/**
|
|
37
48
|
* A Hero's photo: the first of `keys` the section has media for, its alt text
|
|
38
49
|
* the section's `copy.imageAlt` (empty when the section has none).
|
package/src/lib/shifts.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// The organization's volunteer shifts as the kit's volunteer pages draw them
|
|
2
|
-
// (src/routes/
|
|
2
|
+
// (`/volunteer`, the open-shifts list src/routes/catch-all.astro draws when
|
|
3
|
+
// the site has no page of its own at that address, and
|
|
3
4
|
// src/routes/volunteer-shift.astro, `/volunteer/<slug>`), read from the
|
|
4
5
|
// Content API's `GET /shifts`: every open shift, soonest first, each with its
|
|
5
6
|
// counts, its state (`open`, `full`, `waitlist`, `closed`), what it belongs to
|
package/src/lib/store.ts
ADDED
|
@@ -0,0 +1,521 @@
|
|
|
1
|
+
// The storefront the kit draws for every template (board 06 of the store
|
|
2
|
+
// design): static pages built from the Content API's catalog reads, readable
|
|
3
|
+
// with scripts off, and one small live island.
|
|
4
|
+
//
|
|
5
|
+
// /store the shop: the departments rail (each with
|
|
6
|
+
// its published count, only departments with
|
|
7
|
+
// something in them; the api lists only those
|
|
8
|
+
// whose storefront page is on, each under its
|
|
9
|
+
// nearest listed ancestor), the site's collections
|
|
10
|
+
// under it, the grid of listings (each card
|
|
11
|
+
// the link, no buttons) and a collection band
|
|
12
|
+
// carrying the page's one call (GET /products).
|
|
13
|
+
// /store/departments/<slug> the same, narrowed to a department and
|
|
14
|
+
// everything under it (`?department=`); a
|
|
15
|
+
// department the api does not list has none.
|
|
16
|
+
// Its rail carries the filter panel: a
|
|
17
|
+
// group per facet the api sends with
|
|
18
|
+
// `?department=`, each value a link that
|
|
19
|
+
// toggles `?attr=<key>:<value>` (repeatable,
|
|
20
|
+
// keys AND, a key's values OR) in the page's
|
|
21
|
+
// own address, which passes to GET /products.
|
|
22
|
+
// The shop's root has no facets.
|
|
23
|
+
// /store/<slug> one listing (GET /products/<slug>): its
|
|
24
|
+
// gallery, copy, attributes, related listings
|
|
25
|
+
// by collection, and the Product + Offer
|
|
26
|
+
// JSON-LD in the HTML. Its price,
|
|
27
|
+
// availability and Add to cart are the island
|
|
28
|
+
// (components/store/StoreScript.astro), which
|
|
29
|
+
// reads GET /products/live on view.
|
|
30
|
+
// /collections/<slug> one collection (GET /collections/<slug>):
|
|
31
|
+
// its cover, intro, the ordered grid, then one
|
|
32
|
+
// call back to the shop.
|
|
33
|
+
//
|
|
34
|
+
// A grid's later pages ride `?cursor=` as a list's do. Availability is the
|
|
35
|
+
// api's word, never a count. Prices are the build's; the island shows the
|
|
36
|
+
// live one when it differs.
|
|
37
|
+
//
|
|
38
|
+
// The cart belongs to the hosted checkout (`/s/<org>/checkout` on BackGold,
|
|
39
|
+
// on the host of a listing's `buy_url`), a different origin from the site's,
|
|
40
|
+
// so the site keeps its own cart and hands it over. The contract:
|
|
41
|
+
//
|
|
42
|
+
// - The island keeps the lines in localStorage on the site's origin under
|
|
43
|
+
// `gg-cart:<org slug>`, as an array in the checkout cart's own `CartItem`
|
|
44
|
+
// shape (the platform's frontend services/store-cart.ts): `variant_id`,
|
|
45
|
+
// `product_slug`, `product_name`, `variant_name`, `unit_price_cents`,
|
|
46
|
+
// `quantity`, `photo_url`, `needs_shipping`, and `answers` as
|
|
47
|
+
// `{ order?, units? }` keyed by label when the listing asks questions. A
|
|
48
|
+
// second add of the same item adds its quantity to the line, keeps the
|
|
49
|
+
// newer once-per-order answers and appends its units' answers, as the
|
|
50
|
+
// checkout's own add does.
|
|
51
|
+
// - The header's Cart link counts the lines' quantities. It, and the
|
|
52
|
+
// island's Check out after an add, go to
|
|
53
|
+
// `<checkout>#cart=<base64url of the UTF-8 JSON of the CartItem[]>`, in
|
|
54
|
+
// the fragment, never the query, so answers reach no server log. The
|
|
55
|
+
// checkout replaces its cart for the organization with the lines handed
|
|
56
|
+
// over (the site's cart is what the buyer saw), takes at most 50 lines and
|
|
57
|
+
// 64 KB, one line per item, a quantity of 1 to 99, names of at most 255
|
|
58
|
+
// characters, `units` no longer than the quantity and answers that are
|
|
59
|
+
// strings or lists of strings (a line that breaks one is dropped), and
|
|
60
|
+
// clears the fragment; it quotes prices
|
|
61
|
+
// again itself, so a line's `unit_price_cents` is for display only. The
|
|
62
|
+
// site forgets its cart in the click that hands it over (the link's
|
|
63
|
+
// address already carries the lines, so a new tab gets them too): the
|
|
64
|
+
// checkout owns the cart from then on, and an empty site cart's link goes
|
|
65
|
+
// to the checkout as it stands. A later hand-over of new lines replaces
|
|
66
|
+
// the checkout's cart, never adds to it.
|
|
67
|
+
|
|
68
|
+
import type { BackgoldContent, CollectionResponse, ProductDepartment, ProductDetail, ProductFacet, ProductResponse, ProductSummary, ProductsResponse } from '@backgold/content'
|
|
69
|
+
import { BackgoldApiError } from '@backgold/content'
|
|
70
|
+
import { PRODUCT_ATTR_FILTERS_MAX, PRODUCT_ATTR_KEY_PATTERN, PRODUCT_ATTR_VALUE_MAX } from '#contract/content-api'
|
|
71
|
+
|
|
72
|
+
/** The api's availability word: `in_stock`, `low`, `out` or `preorder`. */
|
|
73
|
+
export type ProductAvailability = ProductSummary['availability']
|
|
74
|
+
|
|
75
|
+
export const STORE_PATH = '/store'
|
|
76
|
+
export const COLLECTIONS_PATH = '/collections'
|
|
77
|
+
/** The segment under /store that a department's own page sits under. */
|
|
78
|
+
const DEPARTMENTS_SEGMENT = 'departments'
|
|
79
|
+
/** How many listings a grid page shows. */
|
|
80
|
+
export const STORE_PAGE_SIZE = 24
|
|
81
|
+
|
|
82
|
+
export const productPath = (slug: string): string => `${STORE_PATH}/${encodeURIComponent(slug)}`
|
|
83
|
+
export const collectionPath = (slug: string): string => `${COLLECTIONS_PATH}/${encodeURIComponent(slug)}`
|
|
84
|
+
export const departmentPath = (slug: string): string => `${STORE_PATH}/${DEPARTMENTS_SEGMENT}/${encodeURIComponent(slug)}`
|
|
85
|
+
|
|
86
|
+
/** Which storefront page a path is, or null for any other path. */
|
|
87
|
+
export type StoreRoute =
|
|
88
|
+
| { kind: 'store'; department: null }
|
|
89
|
+
| { kind: 'store'; department: string }
|
|
90
|
+
| { kind: 'product'; slug: string }
|
|
91
|
+
| { kind: 'collection'; slug: string }
|
|
92
|
+
|
|
93
|
+
const decoded = (segment: string): string | null => {
|
|
94
|
+
try {
|
|
95
|
+
const value = decodeURIComponent(segment)
|
|
96
|
+
return value && !value.includes('/') ? value : null
|
|
97
|
+
} catch {
|
|
98
|
+
return null
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function storeRouteOf(pathname: string): StoreRoute | null {
|
|
103
|
+
const segments = pathname.replace(/\/+$/, '').split('/').filter(Boolean)
|
|
104
|
+
if (segments[0] === 'store') {
|
|
105
|
+
if (segments.length === 1) return { kind: 'store', department: null }
|
|
106
|
+
if (segments.length === 2) {
|
|
107
|
+
const slug = decoded(segments[1]!)
|
|
108
|
+
return slug ? { kind: 'product', slug } : null
|
|
109
|
+
}
|
|
110
|
+
if (segments.length === 3 && segments[1] === DEPARTMENTS_SEGMENT) {
|
|
111
|
+
const slug = decoded(segments[2]!)
|
|
112
|
+
return slug ? { kind: 'store', department: slug } : null
|
|
113
|
+
}
|
|
114
|
+
return null
|
|
115
|
+
}
|
|
116
|
+
if (segments[0] === 'collections' && segments.length === 2) {
|
|
117
|
+
const slug = decoded(segments[1]!)
|
|
118
|
+
return slug ? { kind: 'collection', slug } : null
|
|
119
|
+
}
|
|
120
|
+
return null
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A read the api has no answer for: an api older than the catalog (404), or a cursor or slug it refuses (400). */
|
|
124
|
+
const absent = (error: unknown): boolean => error instanceof BackgoldApiError && (error.status === 404 || error.status === 400)
|
|
125
|
+
|
|
126
|
+
/** One page of the shop as the api answered it, and the filters that page is under. */
|
|
127
|
+
export interface Storefront {
|
|
128
|
+
shop: ProductsResponse
|
|
129
|
+
filters: StoreFilters
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* One page of the shop (a department's, with one, under its filters), or
|
|
134
|
+
* null when the api serves no catalog or refuses the page. Filters the api
|
|
135
|
+
* refuses (400 `BAD_ATTR`) are dropped: the page is read again without them,
|
|
136
|
+
* and drawn unfiltered.
|
|
137
|
+
*/
|
|
138
|
+
export async function storefront(
|
|
139
|
+
client: BackgoldContent,
|
|
140
|
+
opts: { department: string | null; cursor: string | null; filters: StoreFilters },
|
|
141
|
+
): Promise<Storefront | null> {
|
|
142
|
+
const read = (filters: StoreFilters) =>
|
|
143
|
+
client.products({
|
|
144
|
+
limit: STORE_PAGE_SIZE,
|
|
145
|
+
...(opts.department ? { department: opts.department } : {}),
|
|
146
|
+
...(filters.length > 0 ? { attr: attrOption(filters) } : {}),
|
|
147
|
+
...(opts.cursor ? { cursor: opts.cursor } : {}),
|
|
148
|
+
})
|
|
149
|
+
try {
|
|
150
|
+
return { shop: await read(opts.filters), filters: opts.filters }
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (opts.filters.length > 0 && error instanceof BackgoldApiError && error.code === 'BAD_ATTR') {
|
|
153
|
+
try {
|
|
154
|
+
return { shop: await read([]), filters: [] }
|
|
155
|
+
} catch (again) {
|
|
156
|
+
if (absent(again)) return null
|
|
157
|
+
throw again
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (absent(error)) return null
|
|
161
|
+
throw error
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// ── The filter panel ─────────────────────────────────────────────────────────
|
|
166
|
+
|
|
167
|
+
/** The query name a department page's filters ride in, as GET /products takes them. */
|
|
168
|
+
export const FILTER_PARAM = 'attr'
|
|
169
|
+
|
|
170
|
+
/** One chosen attribute value. */
|
|
171
|
+
export interface StoreFilter {
|
|
172
|
+
key: string
|
|
173
|
+
value: string
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** The filters a page is under, in the order its address names them. */
|
|
177
|
+
export type StoreFilters = readonly StoreFilter[]
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* The page address's `?attr=<key>:<value>` filters: each split at its first
|
|
181
|
+
* colon, a key the api would refuse, an empty or overlong value, a repeat and
|
|
182
|
+
* any past the api's limit left out, so a hand-typed address never fails the
|
|
183
|
+
* page.
|
|
184
|
+
*/
|
|
185
|
+
export function storeFiltersOf(params: URLSearchParams): StoreFilters {
|
|
186
|
+
const out: StoreFilter[] = []
|
|
187
|
+
for (const raw of params.getAll(FILTER_PARAM)) {
|
|
188
|
+
const colon = raw.indexOf(':')
|
|
189
|
+
if (colon === -1) continue
|
|
190
|
+
const key = raw.slice(0, colon)
|
|
191
|
+
const value = raw.slice(colon + 1)
|
|
192
|
+
if (!PRODUCT_ATTR_KEY_PATTERN.test(key) || value === '' || value.length > PRODUCT_ATTR_VALUE_MAX) continue
|
|
193
|
+
if (out.some((f) => f.key === key && f.value === value)) continue
|
|
194
|
+
out.push({ key, value })
|
|
195
|
+
if (out.length === PRODUCT_ATTR_FILTERS_MAX) break
|
|
196
|
+
}
|
|
197
|
+
return out
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** The filters as `products({ attr })` takes them: a key's values together. */
|
|
201
|
+
function attrOption(filters: StoreFilters): Record<string, string[]> {
|
|
202
|
+
const attr: Record<string, string[]> = {}
|
|
203
|
+
for (const { key, value } of filters) (attr[key] ??= []).push(value)
|
|
204
|
+
return attr
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** A department page's address under these filters, and at a later page with a cursor. */
|
|
208
|
+
export function filteredPath(path: string, filters: StoreFilters, cursor: string | null = null): string {
|
|
209
|
+
const query = [
|
|
210
|
+
...filters.map((f) => `${FILTER_PARAM}=${encodeURIComponent(f.key)}:${encodeURIComponent(f.value)}`),
|
|
211
|
+
...(cursor ? [`cursor=${encodeURIComponent(cursor)}`] : []),
|
|
212
|
+
]
|
|
213
|
+
return query.length > 0 ? `${path}?${query.join('&')}` : path
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export interface FacetLink {
|
|
217
|
+
label: string
|
|
218
|
+
href: string
|
|
219
|
+
count: number
|
|
220
|
+
chosen: boolean
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
export interface FacetGroup {
|
|
224
|
+
key: string
|
|
225
|
+
label: string
|
|
226
|
+
links: FacetLink[]
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** A facet value as the panel names it: the api's text, `true` and `false` as Yes and No. */
|
|
230
|
+
export function facetValueText(facet: Pick<ProductFacet, 'kind'>, value: string): string {
|
|
231
|
+
if (facet.kind === 'boolean' && (value === 'true' || value === 'false')) return value === 'true' ? 'Yes' : 'No'
|
|
232
|
+
return value
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* The filter panel: one group per facet, in the api's order, each value a
|
|
237
|
+
* link to the page with that value toggled (the other chosen values kept,
|
|
238
|
+
* the cursor dropped). A chosen value the api did not list (nothing matches
|
|
239
|
+
* it under the other filters) is kept at the end with a count of 0, so it
|
|
240
|
+
* can still be turned off.
|
|
241
|
+
*/
|
|
242
|
+
export function facetGroups(facets: readonly ProductFacet[], filters: StoreFilters, path: string): FacetGroup[] {
|
|
243
|
+
const isChosen = (key: string, value: string) => filters.some((f) => f.key === key && f.value === value)
|
|
244
|
+
const toggled = (key: string, value: string): StoreFilters =>
|
|
245
|
+
isChosen(key, value) ? filters.filter((f) => !(f.key === key && f.value === value)) : [...filters, { key, value }]
|
|
246
|
+
return facets.map((facet) => {
|
|
247
|
+
const values = [...facet.values]
|
|
248
|
+
for (const f of filters) if (f.key === facet.key && !values.some((v) => v.value === f.value)) values.push({ value: f.value, count: 0 })
|
|
249
|
+
return {
|
|
250
|
+
key: facet.key,
|
|
251
|
+
label: facet.label,
|
|
252
|
+
links: values.map((v) => ({
|
|
253
|
+
label: facetValueText(facet, v.value),
|
|
254
|
+
href: filteredPath(path, toggled(facet.key, v.value)),
|
|
255
|
+
count: v.count,
|
|
256
|
+
chosen: isChosen(facet.key, v.value),
|
|
257
|
+
})),
|
|
258
|
+
}
|
|
259
|
+
})
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** A listing for its page, or null (unknown, unpublished, or an api older than the catalog). */
|
|
263
|
+
export async function productPage(client: BackgoldContent, slug: string): Promise<ProductResponse | null> {
|
|
264
|
+
try {
|
|
265
|
+
return await client.product(slug)
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (absent(error)) return null
|
|
268
|
+
throw error
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** A collection for its page, or null (unknown, unpublished, or an api older than the catalog). */
|
|
273
|
+
export async function collectionPage(client: BackgoldContent, slug: string): Promise<CollectionResponse | null> {
|
|
274
|
+
try {
|
|
275
|
+
return await client.collection(slug)
|
|
276
|
+
} catch (error) {
|
|
277
|
+
if (absent(error)) return null
|
|
278
|
+
throw error
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// ── Words and numbers ────────────────────────────────────────────────────────
|
|
283
|
+
|
|
284
|
+
/** The availability words a card and the island show. */
|
|
285
|
+
export const AVAILABILITY_WORDS: Record<ProductAvailability, string> = {
|
|
286
|
+
in_stock: 'In stock',
|
|
287
|
+
low: 'Only a few left',
|
|
288
|
+
out: 'Sold out',
|
|
289
|
+
preorder: 'Preorder',
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** The chip class an availability word wears: quiet when in stock, the accent when few are left. */
|
|
293
|
+
export const AVAILABILITY_CHIPS: Record<ProductAvailability, string> = {
|
|
294
|
+
in_stock: 'chip-wash',
|
|
295
|
+
low: 'chip-accent',
|
|
296
|
+
out: '',
|
|
297
|
+
preorder: 'chip-wash',
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const WHOLE = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 })
|
|
301
|
+
const CENTS = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: 2 })
|
|
302
|
+
|
|
303
|
+
/** A price from cents: "$30" for whole dollars, "$24.50" otherwise. */
|
|
304
|
+
export function money(cents: number): string {
|
|
305
|
+
return cents % 100 === 0 ? WHOLE.format(cents / 100) : CENTS.format(cents / 100)
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** A listing's price on a card: one price, or "From $X" when its items differ. */
|
|
309
|
+
export function priceLabel(product: Pick<ProductSummary, 'price_from_cents' | 'price_to_cents'>): string {
|
|
310
|
+
return product.price_from_cents === product.price_to_cents ? money(product.price_from_cents) : `From ${money(product.price_from_cents)}`
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// ── The rail ─────────────────────────────────────────────────────────────────
|
|
314
|
+
|
|
315
|
+
export interface RailLink {
|
|
316
|
+
label: string
|
|
317
|
+
href: string
|
|
318
|
+
count: number
|
|
319
|
+
current: boolean
|
|
320
|
+
/** 0 for a top-level department, 1 for one under the department being shown. */
|
|
321
|
+
depth: 0 | 1
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
const byPosition = (a: ProductDepartment, b: ProductDepartment) => a.position - b.position || a.label.localeCompare(b.label)
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* The departments rail: every top-level department with a published listing
|
|
328
|
+
* in it or under it, in the tree's order; on a department's page, its path
|
|
329
|
+
* is current and the departments under it with something in them follow it.
|
|
330
|
+
*/
|
|
331
|
+
export function departmentRail(departments: readonly ProductDepartment[], current: string | null): RailLink[] {
|
|
332
|
+
const live = departments.filter((d) => d.count > 0)
|
|
333
|
+
const bySlug = new Map(live.map((d) => [d.slug, d]))
|
|
334
|
+
const shown = current ? bySlug.get(current) ?? null : null
|
|
335
|
+
// The current department's root, so its top-level row is marked current too.
|
|
336
|
+
const path = new Set<string>()
|
|
337
|
+
for (let node = shown; node; node = node.parent_id ? live.find((d) => d.id === node!.parent_id) ?? null : null) path.add(node.id)
|
|
338
|
+
const link = (d: ProductDepartment, depth: 0 | 1): RailLink => ({ label: d.label, href: departmentPath(d.slug), count: d.count, current: path.has(d.id), depth })
|
|
339
|
+
const out: RailLink[] = []
|
|
340
|
+
for (const root of live.filter((d) => d.parent_id === null).sort(byPosition)) {
|
|
341
|
+
out.push(link(root, 0))
|
|
342
|
+
if (shown && path.has(root.id)) {
|
|
343
|
+
for (const child of live.filter((d) => d.parent_id === shown.id).sort(byPosition)) out.push(link(child, 1))
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
return out
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** The department a page narrows to, by its slug; null when the tree has no such live department. */
|
|
350
|
+
export function departmentOf(departments: readonly ProductDepartment[], slug: string | null): ProductDepartment | null {
|
|
351
|
+
return slug ? departments.find((d) => d.slug === slug && d.count > 0) ?? null : null
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* How many published listings the shop has: the top-level departments'
|
|
356
|
+
* counts, or the page's own count when nothing is classified. GET /products
|
|
357
|
+
* carries no total, so when a top-level department's storefront page is off
|
|
358
|
+
* the api does not list it: its children come up as top-level departments
|
|
359
|
+
* and still count, but the listings filed on it directly are left out of the
|
|
360
|
+
* sum.
|
|
361
|
+
*/
|
|
362
|
+
export function shopCount(response: ProductsResponse): number {
|
|
363
|
+
const roots = response.departments.filter((d) => d.parent_id === null).reduce((n, d) => n + d.count, 0)
|
|
364
|
+
return Math.max(roots, response.products.length)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
// ── The product page ─────────────────────────────────────────────────────────
|
|
368
|
+
|
|
369
|
+
/** An attribute's value as the details table shows it; null leaves the row out. */
|
|
370
|
+
export function attributeText(value: ProductDetail['attributes'][number]['value']): string | null {
|
|
371
|
+
if (value === null) return null
|
|
372
|
+
if (typeof value === 'boolean') return value ? 'Yes' : 'No'
|
|
373
|
+
if (Array.isArray(value)) return value.length > 0 ? value.join(', ') : null
|
|
374
|
+
const trimmed = value.trim()
|
|
375
|
+
return trimmed === '' ? null : trimmed
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
export interface RelatedGroup {
|
|
379
|
+
title: string
|
|
380
|
+
href: string | null
|
|
381
|
+
products: ProductSummary[]
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* The related listings grouped by the collection they share with the
|
|
386
|
+
* listing, in the order of the listing's own collections; one the api names
|
|
387
|
+
* without a shared collection goes under "More from the shop".
|
|
388
|
+
*/
|
|
389
|
+
export function relatedGroups(product: ProductDetail): RelatedGroup[] {
|
|
390
|
+
const groups = new Map<string, RelatedGroup>()
|
|
391
|
+
for (const ref of product.collections) groups.set(ref.slug, { title: ref.title, href: collectionPath(ref.slug), products: [] })
|
|
392
|
+
const loose: ProductSummary[] = []
|
|
393
|
+
for (const other of product.related) {
|
|
394
|
+
const shared = other.collections.find((c) => groups.has(c.slug))
|
|
395
|
+
if (shared) groups.get(shared.slug)!.products.push(other)
|
|
396
|
+
else loose.push(other)
|
|
397
|
+
}
|
|
398
|
+
const out = [...groups.values()].filter((g) => g.products.length > 0)
|
|
399
|
+
if (loose.length > 0) out.push({ title: 'More from the shop', href: null, products: loose })
|
|
400
|
+
return out
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
const SCHEMA_AVAILABILITY: Record<ProductAvailability, string> = {
|
|
404
|
+
in_stock: 'https://schema.org/InStock',
|
|
405
|
+
low: 'https://schema.org/LimitedAvailability',
|
|
406
|
+
out: 'https://schema.org/OutOfStock',
|
|
407
|
+
preorder: 'https://schema.org/PreOrder',
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* The listing as schema.org Product JSON-LD with one Offer per item, from
|
|
412
|
+
* the build: the price in dollars and cents in USD, the availability, the
|
|
413
|
+
* SKU and (with a UPC) the gtin12, each Offer at the listing's page on this
|
|
414
|
+
* site.
|
|
415
|
+
*/
|
|
416
|
+
export function productJsonLd(product: ProductDetail, siteUrl: string): Record<string, unknown> {
|
|
417
|
+
const url = new URL(productPath(product.slug), siteUrl).toString()
|
|
418
|
+
const sku = product.items.find((i) => i.sku)?.sku ?? null
|
|
419
|
+
const description = product.seo.description ?? product.short_description
|
|
420
|
+
return {
|
|
421
|
+
'@context': 'https://schema.org',
|
|
422
|
+
'@type': 'Product',
|
|
423
|
+
name: product.name,
|
|
424
|
+
url,
|
|
425
|
+
...(description ? { description } : {}),
|
|
426
|
+
...(product.photos.length > 0 ? { image: product.photos.map((p) => p.url) } : {}),
|
|
427
|
+
...(sku ? { sku } : {}),
|
|
428
|
+
...(product.manufacturer ? { brand: { '@type': 'Brand', name: product.manufacturer.name } } : {}),
|
|
429
|
+
...(product.department.length > 0 ? { category: product.department.map((d) => d.label).join(' > ') } : {}),
|
|
430
|
+
offers: product.items.map((item) => ({
|
|
431
|
+
'@type': 'Offer',
|
|
432
|
+
...(item.sku ? { sku: item.sku } : {}),
|
|
433
|
+
...(item.upc ? { gtin12: item.upc } : {}),
|
|
434
|
+
name: item.name,
|
|
435
|
+
price: (item.price_cents / 100).toFixed(2),
|
|
436
|
+
priceCurrency: 'USD',
|
|
437
|
+
availability: SCHEMA_AVAILABILITY[item.availability],
|
|
438
|
+
url,
|
|
439
|
+
})),
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Where the order goes, as the one line under the availability word (never
|
|
445
|
+
* a choice): picked up at the store, shipped to a licensed dealer the buyer
|
|
446
|
+
* names at checkout, or shipped to the buyer when there is something to
|
|
447
|
+
* ship; null for a listing with nothing to ship to the buyer.
|
|
448
|
+
*/
|
|
449
|
+
export function shipLine(product: Pick<ProductDetail, 'ship_to' | 'ships'>): string | null {
|
|
450
|
+
if (product.ship_to === 'store') return 'Pick up at the store'
|
|
451
|
+
if (product.ship_to === 'third_party') return 'Ships to a licensed dealer you name at checkout'
|
|
452
|
+
return product.ships ? 'Ships to you' : null
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** The sentence a listing that counts as a political contribution carries before Add to cart (DS §18.1). */
|
|
456
|
+
export const contributionLine = (siteName: string): string => `A purchase is a political contribution to ${siteName}.`
|
|
457
|
+
|
|
458
|
+
// ── The checkout ─────────────────────────────────────────────────────────────
|
|
459
|
+
|
|
460
|
+
export interface Checkout {
|
|
461
|
+
/** The organization's slug on BackGold, the cart's key (`gg-cart:<org>`). */
|
|
462
|
+
org: string
|
|
463
|
+
/** The hosted checkout: `<origin>/s/<org>/checkout`. */
|
|
464
|
+
url: string
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Where a listing's cart checks out, read off its `buy_url` (`<origin>/s/<org>/<slug>`); null when it is not that shape. */
|
|
468
|
+
export function checkoutOf(buyUrl: string): Checkout | null {
|
|
469
|
+
try {
|
|
470
|
+
const url = new URL(buyUrl)
|
|
471
|
+
const m = /^\/s\/([^/]+)\/[^/]+\/?$/.exec(url.pathname)
|
|
472
|
+
if (!m || (url.protocol !== 'https:' && url.protocol !== 'http:')) return null
|
|
473
|
+
const org = decodeURIComponent(m[1]!)
|
|
474
|
+
return { org, url: `${url.origin}/s/${encodeURIComponent(org)}/checkout` }
|
|
475
|
+
} catch {
|
|
476
|
+
return null
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** The checkout of the first listing that names one. */
|
|
481
|
+
export function checkoutFor(products: readonly Pick<ProductSummary, 'buy_url'>[]): Checkout | null {
|
|
482
|
+
for (const p of products) {
|
|
483
|
+
const found = checkoutOf(p.buy_url)
|
|
484
|
+
if (found) return found
|
|
485
|
+
}
|
|
486
|
+
return null
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
/** What the island reads about the listing from the page: the build's view of it. */
|
|
490
|
+
export interface IslandProduct {
|
|
491
|
+
id: string
|
|
492
|
+
slug: string
|
|
493
|
+
name: string
|
|
494
|
+
photo_url: string | null
|
|
495
|
+
ships: boolean
|
|
496
|
+
/** Where the order goes: a pickup at the store ships nothing to the buyer. */
|
|
497
|
+
ship_to: ProductDetail['ship_to']
|
|
498
|
+
buy_url: string
|
|
499
|
+
/** When the build read the listing (its `updated_at`), for "As of the last build". */
|
|
500
|
+
built_at: string
|
|
501
|
+
items: Array<{ id: string; name: string; price_cents: number; compare_at_cents: number | null; availability: ProductAvailability }>
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
export function islandProduct(product: ProductDetail): IslandProduct {
|
|
505
|
+
return {
|
|
506
|
+
id: product.id,
|
|
507
|
+
slug: product.slug,
|
|
508
|
+
name: product.name,
|
|
509
|
+
photo_url: product.photos[0]?.url ?? null,
|
|
510
|
+
ships: product.ships,
|
|
511
|
+
ship_to: product.ship_to,
|
|
512
|
+
buy_url: product.buy_url,
|
|
513
|
+
built_at: product.updated_at,
|
|
514
|
+
items: product.items.map(({ id, name, price_cents, compare_at_cents, availability }) => ({ id, name, price_cents, compare_at_cents, availability })),
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** The item a page opens on: the first one that can be bought, else the first. */
|
|
519
|
+
export function firstBuyable<T extends { availability: ProductAvailability }>(items: readonly T[]): T | null {
|
|
520
|
+
return items.find((i) => i.availability !== 'out') ?? items[0] ?? null
|
|
521
|
+
}
|