@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.
Files changed (52) hide show
  1. package/dist/{chunk-KOB36GSF.js → chunk-RJAVFRC6.js} +9 -4
  2. package/dist/{constants-DvTNj4JI.d-Batjcj3Z.d.ts → constants-BAIo_Q5U.d-lQbj1e1-.d.ts} +11 -1
  3. package/dist/{content-api-CYeY0vU8.d.ts → content-api-Cox1-wz5.d.ts} +250 -3
  4. package/dist/contract/content-api-examples.d.ts +17 -3
  5. package/dist/contract/content-api-examples.js +146 -3
  6. package/dist/contract/content-api.d.ts +2 -2
  7. package/dist/contract/content-api.js +1 -1
  8. package/dist/contract/site-templates.d.ts +4 -3
  9. package/dist/contract/site-templates.js +1 -1
  10. package/package.json +5 -5
  11. package/src/components/chrome/Brand.astro +23 -16
  12. package/src/components/sections/About/credentials.ts +0 -10
  13. package/src/components/sections/About/index.astro +6 -3
  14. package/src/components/sections/About/left.astro +6 -3
  15. package/src/components/sections/About/letter.astro +6 -3
  16. package/src/components/sections/About/portrait.astro +2 -2
  17. package/src/components/sections/ContentPost/lesson.ts +14 -7
  18. package/src/components/sections/ContentPost/prose.astro +80 -0
  19. package/src/components/sections/Hero/cover.astro +9 -3
  20. package/src/components/sections/Hero/donate.astro +3 -3
  21. package/src/components/sections/Hero/index.astro +2 -2
  22. package/src/components/sections/Hero/overlap.astro +3 -3
  23. package/src/components/sections/Hero/split.astro +9 -6
  24. package/src/components/sections/Hero/statement.astro +3 -3
  25. package/src/components/sections/Hero/video.astro +3 -3
  26. package/src/components/sections/VoterTools/Lookup.astro +43 -0
  27. package/src/components/sections/VoterTools/dates.astro +9 -5
  28. package/src/components/sections/VoterTools/index.astro +12 -9
  29. package/src/components/sections/VoterTools/polling.astro +9 -6
  30. package/src/components/sections/VoterTools/voter-tools.ts +5 -4
  31. package/src/components/sections/index.ts +3 -0
  32. package/src/components/sections/modules/ModuleFrame.astro +4 -2
  33. package/src/components/store/CollectionPage.astro +40 -0
  34. package/src/components/store/ProductCard.astro +32 -0
  35. package/src/components/store/ProductGrid.astro +16 -0
  36. package/src/components/store/ProductPage.astro +146 -0
  37. package/src/components/store/StorePage.astro +137 -0
  38. package/src/components/store/StoreScript.astro +572 -0
  39. package/src/components/volunteer/props.ts +1 -1
  40. package/src/index.js +0 -1
  41. package/src/layouts/Site.astro +19 -3
  42. package/src/lib/chrome.ts +6 -4
  43. package/src/lib/donate-frame.ts +44 -4
  44. package/src/lib/live.ts +6 -5
  45. package/src/lib/section.ts +11 -0
  46. package/src/lib/shifts.ts +2 -1
  47. package/src/lib/store.ts +521 -0
  48. package/src/routes/catch-all.astro +168 -19
  49. package/src/styles/site.css +71 -0
  50. package/src/styles/store.css +634 -0
  51. package/src/template.ts +1 -1
  52. package/src/routes/volunteer.astro +0 -37
@@ -0,0 +1,572 @@
1
+ ---
2
+ // The storefront's live parts, one script per store page, no framework:
3
+ //
4
+ // - The header's Cart link (`[data-bg-cart]`, Site.astro's `cart`): the lines
5
+ // this site keeps under `gg-cart:<org>` in localStorage, counted; hidden
6
+ // while there are none. Its address, and the island's Check out's, carry
7
+ // them to the hosted checkout in the fragment (`#cart=<base64url JSON>`,
8
+ // never the query, so the answers reach no server log), kept current as
9
+ // the cart changes so a new tab gets them too; with no lines it is the
10
+ // checkout's own address (the checkout keeps its own cart). Followed (a
11
+ // click, a modified click or a middle click), the link forgets them here
12
+ // in the same click: the checkout's cart holds them from then on.
13
+ // - The product page's island (`[data-bg-island]`, ProductPage.astro): on
14
+ // view it reads GET /products/live?ids=<the listing> (lib/live.ts: the
15
+ // same-origin path first-party, else the api's address with the
16
+ // publishable key; with neither, the island stays as built) and draws one
17
+ // of five states: in stock, few left, sold out (Add to cart says so and
18
+ // does nothing), the price moved since the build (the built price struck,
19
+ // the live one charged, and a sentence that says so), or the read failed
20
+ // (the built price "as of the last build", Add to cart says it cannot, and
21
+ // Try again reads again). It draws the questions the line asks: the
22
+ // once-per-order ones once, each per-unit one once per unit, so a quantity
23
+ // of 2 asks it twice. Add to cart puts the line in the cart in the hosted
24
+ // checkout's line shape (variant_id, product_slug, product_name,
25
+ // variant_name, unit_price_cents at the live price, quantity, photo_url,
26
+ // needs_shipping, and `answers` as { order, units } keyed by label, the
27
+ // way the checkout's own add does it: a second add of the same item adds
28
+ // its quantity and its units' answers to the line).
29
+ // - The gallery's thumbnails swap the large photo.
30
+ import { liveSource } from '../../lib/live'
31
+ import { AVAILABILITY_CHIPS, AVAILABILITY_WORDS } from '../../lib/store'
32
+
33
+ const bg = Astro.locals.backgold
34
+ const source = await liveSource(bg.setup === null && bg.firstParty, 'products')
35
+ const words = JSON.stringify({ words: AVAILABILITY_WORDS, chips: AVAILABILITY_CHIPS })
36
+ ---
37
+ <script is:inline data-bg-store-api={source?.url ?? ''} data-bg-store-key={source?.key ?? undefined} data-bg-store-words={words}>
38
+ ;(function (script) {
39
+ var api = script.getAttribute('data-bg-store-api')
40
+ var key = script.getAttribute('data-bg-store-key')
41
+ var vocab = JSON.parse(script.getAttribute('data-bg-store-words') || '{}')
42
+ var PREFIX = 'gg-cart:'
43
+ /** The checkout's bounds for a hand-over: lines, a line's quantity, the JSON's size, a name's length. */
44
+ var MOST_LINES = 50
45
+ var MOST_QUANTITY = 99
46
+ var MOST_BYTES = 64 * 1024
47
+ var MOST_TEXT = 255
48
+
49
+ // ── The cart ──
50
+ function readCart(org) {
51
+ try {
52
+ var raw = window.localStorage.getItem(PREFIX + org)
53
+ var lines = raw ? JSON.parse(raw) : []
54
+ return Array.isArray(lines) ? lines : []
55
+ } catch (e) {
56
+ return []
57
+ }
58
+ }
59
+ function writeCart(org, lines) {
60
+ try {
61
+ if (lines.length === 0) window.localStorage.removeItem(PREFIX + org)
62
+ else window.localStorage.setItem(PREFIX + org, JSON.stringify(lines))
63
+ } catch (e) {}
64
+ document.dispatchEvent(new CustomEvent('bg-cart'))
65
+ }
66
+ function mergeAnswers(had, added) {
67
+ if (!had && !added) return undefined
68
+ var order = (added && added.order) || (had && had.order)
69
+ var units = ((had && had.units) || []).concat((added && added.units) || [])
70
+ var out = {}
71
+ if (order) out.order = order
72
+ if (units.length > 0) out.units = units
73
+ return out
74
+ }
75
+ /**
76
+ * Adds the line, merged into the item's own line when it has one (the
77
+ * checkout keeps one line per item). False, and nothing written, when
78
+ * the cart would break the checkout's bounds for a hand-over: at most
79
+ * MOST_LINES lines, a quantity of at most MOST_QUANTITY per line, and
80
+ * at most MOST_BYTES of JSON.
81
+ */
82
+ function addLine(org, line) {
83
+ var lines = readCart(org).slice()
84
+ var at = -1
85
+ for (var i = 0; i < lines.length; i++) if (lines[i] && lines[i].variant_id === line.variant_id) at = i
86
+ if (at >= 0) {
87
+ var merged = Object.assign({}, lines[at], { quantity: lines[at].quantity + line.quantity })
88
+ if (lines[at].answers || line.answers) merged.answers = mergeAnswers(lines[at].answers, line.answers)
89
+ if (merged.quantity > MOST_QUANTITY) return false
90
+ lines[at] = merged
91
+ } else {
92
+ if (lines.length >= MOST_LINES) return false
93
+ lines.push(line)
94
+ }
95
+ if (new TextEncoder().encode(JSON.stringify(lines)).length > MOST_BYTES) return false
96
+ writeCart(org, lines)
97
+ return true
98
+ }
99
+ function base64url(text) {
100
+ var bytes = new TextEncoder().encode(text)
101
+ var binary = ''
102
+ for (var i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i])
103
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
104
+ }
105
+ function count(org) {
106
+ return readCart(org).reduce(function (n, line) {
107
+ return n + (line && typeof line.quantity === 'number' ? line.quantity : 0)
108
+ }, 0)
109
+ }
110
+ /** The checkout's address with this site's lines in its fragment. */
111
+ function checkoutHref(link) {
112
+ var org = link.getAttribute('data-bg-cart')
113
+ var base = link.getAttribute('data-bg-checkout')
114
+ var lines = readCart(org)
115
+ return lines.length > 0 ? base + '#cart=' + base64url(JSON.stringify(lines)) : base
116
+ }
117
+ function drawCart() {
118
+ var links = document.querySelectorAll('[data-bg-cart]')
119
+ for (var i = 0; i < links.length; i++) {
120
+ var n = count(links[i].getAttribute('data-bg-cart'))
121
+ var shown = links[i].querySelector('[data-bg-cart-count]')
122
+ if (shown) shown.textContent = String(n)
123
+ links[i].setAttribute('aria-label', 'Cart, ' + n + (n === 1 ? ' item' : ' items'))
124
+ links[i].setAttribute('href', checkoutHref(links[i]))
125
+ links[i].hidden = n === 0
126
+ }
127
+ var cart = links[0]
128
+ var now = document.querySelectorAll('[data-bg-checkout-now]')
129
+ for (var j = 0; cart && j < now.length; j++) now[j].setAttribute('href', checkoutHref(cart))
130
+ }
131
+ /**
132
+ * The hand-over: the followed link's address is set with the lines
133
+ * first, then the cart is forgotten here. The count is redrawn after the
134
+ * click, once the browser has taken the address.
135
+ */
136
+ function handOver(event) {
137
+ var link = event.target instanceof Element ? event.target.closest('[data-bg-cart], [data-bg-checkout-now]') : null
138
+ var cart = document.querySelector('[data-bg-cart]')
139
+ if (!link || !cart) return
140
+ link.setAttribute('href', checkoutHref(cart))
141
+ try {
142
+ window.localStorage.removeItem(PREFIX + cart.getAttribute('data-bg-cart'))
143
+ } catch (e) {}
144
+ setTimeout(function () {
145
+ document.dispatchEvent(new CustomEvent('bg-cart'))
146
+ }, 0)
147
+ }
148
+ document.addEventListener('click', function (event) {
149
+ if (event.button === 0) handOver(event)
150
+ })
151
+ document.addEventListener('auxclick', function (event) {
152
+ if (event.button === 1) handOver(event)
153
+ })
154
+ document.addEventListener('bg-cart', drawCart)
155
+ window.addEventListener('storage', drawCart)
156
+ window.addEventListener('pageshow', drawCart)
157
+ drawCart()
158
+
159
+ // ── The gallery ──
160
+ var main = document.querySelector('[data-bg-gallery-main]')
161
+ var thumbs = document.querySelectorAll('[data-bg-gallery-thumb]')
162
+ for (var t = 0; t < thumbs.length; t++) {
163
+ thumbs[t].addEventListener('click', function (event) {
164
+ if (!main) return
165
+ event.preventDefault()
166
+ main.setAttribute('src', this.getAttribute('href'))
167
+ for (var u = 0; u < thumbs.length; u++) thumbs[u].removeAttribute('aria-current')
168
+ this.setAttribute('aria-current', 'true')
169
+ })
170
+ }
171
+
172
+ // ── The island ──
173
+ var island = document.querySelector('[data-bg-island]')
174
+ var data = document.querySelector('[data-bg-island-product]')
175
+ var cartLink = document.querySelector('[data-bg-cart]')
176
+ if (!island || !data || !api || !cartLink) return
177
+ var product = JSON.parse(data.textContent || '{}')
178
+ var org = cartLink.getAttribute('data-bg-cart')
179
+ var form = island.querySelector('[data-bg-form]')
180
+ var priceEl = island.querySelector('[data-bg-price]')
181
+ var wasEl = island.querySelector('[data-bg-was]')
182
+ var lineEl = island.querySelector('[data-bg-line]')
183
+ var wordEl = island.querySelector('[data-bg-word]')
184
+ var qtyEl = island.querySelector('[data-bg-qty]')
185
+ var addEl = island.querySelector('[data-bg-add]')
186
+ var retryEl = island.querySelector('[data-bg-retry]')
187
+ var statusEl = island.querySelector('[data-bg-status]')
188
+ var questionsEl = island.querySelector('[data-bg-questions]')
189
+ var unitNote = island.querySelector('[data-bg-unit-note]')
190
+ var fallback = island.querySelector('[data-bg-fallback]')
191
+ var radios = island.querySelectorAll('[data-bg-item]')
192
+ var built = product.built_at ? new Date(product.built_at) : null
193
+ var builtDay = built && !isNaN(built.getTime()) ? built.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) : null
194
+ var live = null
195
+ var failed = false
196
+
197
+ if (fallback) fallback.hidden = true
198
+ form.hidden = false
199
+ var contribution = island.querySelector('[data-bg-contribution]')
200
+ if (contribution) addEl.parentNode.insertBefore(contribution, addEl)
201
+ for (var r = 0; r < radios.length; r++) radios[r].disabled = false
202
+
203
+ function money(cents) {
204
+ var whole = cents % 100 === 0
205
+ return new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', minimumFractionDigits: whole ? 0 : 2, maximumFractionDigits: whole ? 0 : 2 }).format(cents / 100)
206
+ }
207
+ function quantity() {
208
+ var n = Math.floor(Number(qtyEl.value))
209
+ return isFinite(n) && n >= 1 ? Math.min(n, 99) : 1
210
+ }
211
+ function selected() {
212
+ var id = null
213
+ for (var i = 0; i < radios.length; i++) if (radios[i].checked) id = radios[i].value
214
+ var items = product.items || []
215
+ for (var j = 0; j < items.length; j++) if (items[j].id === id) return items[j]
216
+ return items[0] || null
217
+ }
218
+ function liveItem(item) {
219
+ if (!live || !item) return null
220
+ for (var i = 0; i < live.items.length; i++) if (live.items[i].id === item.id) return live.items[i]
221
+ return null
222
+ }
223
+ function setWord(availability) {
224
+ if (!wordEl) return
225
+ wordEl.hidden = !availability
226
+ if (!availability) return
227
+ wordEl.textContent = vocab.words[availability] || ''
228
+ wordEl.className = 'chip' + (vocab.chips[availability] ? ' ' + vocab.chips[availability] : '')
229
+ }
230
+
231
+ // The answers' keys, as the checkout keys them: each question's label, a
232
+ // repeated label numbered " (2)", " (3)" within its scope.
233
+ function keysOf(questions) {
234
+ var used = []
235
+ return questions.map(function (q, i) {
236
+ var raw = q.label || 'Question ' + (i + 1)
237
+ var k = raw
238
+ for (var n = 2; used.indexOf(k) >= 0; n++) k = raw + ' (' + n + ')'
239
+ used.push(k)
240
+ return k
241
+ })
242
+ }
243
+ function scoped(scope) {
244
+ return ((live && live.questions) || []).filter(function (q) {
245
+ return q.scope === scope
246
+ })
247
+ }
248
+ /** True when a list holds a question that takes an answer (a note takes none). */
249
+ function asks(questions) {
250
+ return questions.some(function (q) {
251
+ return q.type !== 'note'
252
+ })
253
+ }
254
+ /** The value a choice's "Other" carries until the typed text replaces it. */
255
+ var OTHER = '__other__'
256
+ function otherBox(name, keep) {
257
+ var other = document.createElement('input')
258
+ other.type = 'text'
259
+ other.name = name + '#other'
260
+ other.className = 'island-other'
261
+ other.setAttribute('aria-label', 'Other')
262
+ other.placeholder = 'Other'
263
+ if (typeof keep[name + '#other'] === 'string') other.value = keep[name + '#other']
264
+ return other
265
+ }
266
+ /** Shows a choice's "Other" text field while Other is chosen, and asks for it then. */
267
+ function syncOther(wrap) {
268
+ var other = wrap.querySelector('.island-other')
269
+ if (!other) return
270
+ var select = wrap.querySelector('select')
271
+ var tick = wrap.querySelector('input[type="checkbox"][value="' + OTHER + '"]')
272
+ var on = select ? select.value === OTHER : !!(tick && tick.checked)
273
+ other.hidden = !on
274
+ other.required = on
275
+ }
276
+ var AGREE = ['checkbox', 'sms_consent', 'email_consent']
277
+ var INPUTS = { text: 'text', email: 'email', phone: 'tel', date: 'date' }
278
+ function field(q, name, label, keep) {
279
+ var wrap = document.createElement('div')
280
+ wrap.className = 'island-field'
281
+ if (q.type === 'note') {
282
+ String(q.body || '')
283
+ .split(/\n{2,}/)
284
+ .map(function (para) {
285
+ return para.trim()
286
+ })
287
+ .filter(Boolean)
288
+ .forEach(function (para) {
289
+ var p = document.createElement('p')
290
+ p.className = 'island-note-text'
291
+ p.textContent = para
292
+ wrap.appendChild(p)
293
+ })
294
+ return wrap
295
+ }
296
+ var id = 'bg-q-' + name.replace(/[^a-z0-9]+/gi, '-')
297
+ if (AGREE.indexOf(q.type) >= 0) {
298
+ var box = document.createElement('label')
299
+ box.className = 'island-agree'
300
+ var input = document.createElement('input')
301
+ input.type = 'checkbox'
302
+ input.name = name
303
+ input.checked = keep[name] === 'Yes'
304
+ box.appendChild(input)
305
+ box.appendChild(document.createTextNode(' ' + label))
306
+ wrap.appendChild(box)
307
+ } else if (q.type === 'checkboxes') {
308
+ var set = document.createElement('fieldset')
309
+ var legend = document.createElement('legend')
310
+ legend.textContent = label + (q.required ? ' *' : '')
311
+ set.appendChild(legend)
312
+ ;(q.options || []).forEach(function (option) {
313
+ var row = document.createElement('label')
314
+ row.className = 'island-agree'
315
+ var tick = document.createElement('input')
316
+ tick.type = 'checkbox'
317
+ tick.setAttribute('data-multi', '')
318
+ tick.name = name
319
+ tick.value = option
320
+ tick.checked = Array.isArray(keep[name]) && keep[name].indexOf(option) >= 0
321
+ row.appendChild(tick)
322
+ row.appendChild(document.createTextNode(' ' + option))
323
+ set.appendChild(row)
324
+ })
325
+ if (q.allow_other) {
326
+ var otherRow = document.createElement('label')
327
+ otherRow.className = 'island-agree'
328
+ var otherTick = document.createElement('input')
329
+ otherTick.type = 'checkbox'
330
+ otherTick.setAttribute('data-multi', '')
331
+ otherTick.name = name
332
+ otherTick.value = OTHER
333
+ otherTick.checked = Array.isArray(keep[name]) && keep[name].indexOf(OTHER) >= 0
334
+ otherRow.appendChild(otherTick)
335
+ otherRow.appendChild(document.createTextNode(' Other'))
336
+ set.appendChild(otherRow)
337
+ set.appendChild(otherBox(name, keep))
338
+ }
339
+ wrap.appendChild(set)
340
+ } else {
341
+ var lab = document.createElement('label')
342
+ lab.setAttribute('for', id)
343
+ lab.textContent = label + (q.required ? ' *' : '')
344
+ wrap.appendChild(lab)
345
+ var control
346
+ if (q.type === 'textarea') {
347
+ control = document.createElement('textarea')
348
+ control.rows = 3
349
+ } else if (q.type === 'select' || q.type === 'radio') {
350
+ control = document.createElement('select')
351
+ var blank = document.createElement('option')
352
+ blank.value = ''
353
+ blank.textContent = 'Choose one'
354
+ control.appendChild(blank)
355
+ ;(q.options || []).forEach(function (option) {
356
+ var o = document.createElement('option')
357
+ o.value = option
358
+ o.textContent = option
359
+ control.appendChild(o)
360
+ })
361
+ if (q.allow_other) {
362
+ var o2 = document.createElement('option')
363
+ o2.value = OTHER
364
+ o2.textContent = 'Other'
365
+ control.appendChild(o2)
366
+ }
367
+ } else {
368
+ control = document.createElement('input')
369
+ control.type = INPUTS[q.type] || 'text'
370
+ }
371
+ control.id = id
372
+ control.name = name
373
+ if (q.required) control.required = true
374
+ if (q.placeholder && control.tagName !== 'SELECT') control.placeholder = q.placeholder
375
+ if (typeof keep[name] === 'string') control.value = keep[name]
376
+ wrap.appendChild(control)
377
+ if (q.allow_other && control.tagName === 'SELECT') wrap.appendChild(otherBox(name, keep))
378
+ }
379
+ if (q.help) {
380
+ var help = document.createElement('p')
381
+ help.className = 'island-help'
382
+ help.textContent = q.help
383
+ wrap.appendChild(help)
384
+ }
385
+ syncOther(wrap)
386
+ return wrap
387
+ }
388
+ /** What every drawn field holds now, by name, so a redraw keeps it. */
389
+ function held() {
390
+ var out = {}
391
+ var controls = questionsEl.querySelectorAll('input, select, textarea')
392
+ for (var i = 0; i < controls.length; i++) {
393
+ var c = controls[i]
394
+ if (c.type === 'checkbox' && c.hasAttribute('data-multi')) {
395
+ out[c.name] = out[c.name] || []
396
+ if (c.checked) out[c.name].push(c.value)
397
+ } else if (c.type === 'checkbox') {
398
+ out[c.name] = c.checked ? 'Yes' : 'No'
399
+ } else {
400
+ out[c.name] = c.value
401
+ }
402
+ }
403
+ return out
404
+ }
405
+ function drawQuestions() {
406
+ var keep = held()
407
+ questionsEl.textContent = ''
408
+ var order = scoped('order')
409
+ var unit = scoped('unit')
410
+ var n = quantity()
411
+ order.forEach(function (q, i) {
412
+ questionsEl.appendChild(field(q, 'o:' + i, q.label, keep))
413
+ })
414
+ for (var u = 0; u < (asks(unit) ? n : 0); u++) {
415
+ unit.forEach(function (q, i) {
416
+ questionsEl.appendChild(field(q, 'u:' + u + ':' + i, n > 1 ? q.label + ' · unit ' + (u + 1) : q.label, keep))
417
+ })
418
+ }
419
+ unitNote.hidden = !(asks(unit) && n > 1)
420
+ }
421
+ questionsEl.addEventListener('change', function (event) {
422
+ var wrap = event.target instanceof Element ? event.target.closest('.island-field') : null
423
+ if (wrap) syncOther(wrap)
424
+ })
425
+ function answersOf(prefix, questions) {
426
+ var keys = keysOf(questions)
427
+ var out = {}
428
+ var now = held()
429
+ questions.forEach(function (q, i) {
430
+ if (q.type === 'note') return
431
+ var value = now[prefix + i]
432
+ if (value === undefined) return
433
+ // "Other" is answered by the text typed beside it.
434
+ var typed = String(now[prefix + i + '#other'] || '').trim()
435
+ if (value === OTHER) value = typed
436
+ if (Array.isArray(value)) {
437
+ value = value
438
+ .map(function (v) {
439
+ return v === OTHER ? typed : v
440
+ })
441
+ .filter(Boolean)
442
+ if (value.length > 0) out[keys[i]] = value
443
+ } else if (value !== '') out[keys[i]] = value
444
+ })
445
+ return out
446
+ }
447
+
448
+ function draw() {
449
+ var item = selected()
450
+ if (!item) return
451
+ var n = quantity()
452
+ var now = liveItem(item)
453
+ statusEl.textContent = ''
454
+ retryEl.hidden = !failed
455
+ if (failed || !now) {
456
+ priceEl.textContent = money(item.price_cents * n)
457
+ wasEl.hidden = true
458
+ lineEl.textContent = (builtDay ? 'As of the last build, ' + builtDay + '. ' : 'As of the last build. ') + (failed ? 'We could not reach the shop for the live price.' : 'This item is not on sale right now.')
459
+ setWord(null)
460
+ addEl.disabled = true
461
+ addEl.textContent = failed ? 'Can’t add to cart right now' : 'Not available'
462
+ return
463
+ }
464
+ priceEl.textContent = money(now.price_cents * n)
465
+ var moved = now.price_cents !== item.price_cents
466
+ // The live compare-at price when the read carries one, else the build's.
467
+ var compareAt = typeof now.compare_at_cents === 'number' || now.compare_at_cents === null ? now.compare_at_cents : item.compare_at_cents
468
+ var compare = !moved && compareAt !== null && compareAt > now.price_cents ? compareAt : null
469
+ wasEl.hidden = !(moved || compare !== null)
470
+ wasEl.textContent = moved ? money(item.price_cents * n) : compare !== null ? money(compare * n) : ''
471
+ var each = n > 1 ? n + ' × ' + money(now.price_cents) + ' · ' : ''
472
+ lineEl.textContent = moved
473
+ ? each + 'Price changed since this page was built. The live price is the one you pay.'
474
+ : n > 1
475
+ ? each + 'updated just now.'
476
+ : 'Price updated just now.'
477
+ setWord(now.availability)
478
+ var out = now.availability === 'out'
479
+ addEl.disabled = out
480
+ addEl.textContent = out ? 'Sold out' : n > 1 ? 'Add ' + n + ' to cart' : 'Add to cart'
481
+ if (out) lineEl.textContent += ' Nothing to add right now.'
482
+ }
483
+
484
+ function read() {
485
+ failed = false
486
+ addEl.disabled = true
487
+ addEl.textContent = 'Checking the price…'
488
+ retryEl.hidden = true
489
+ var headers = { Accept: 'application/json' }
490
+ if (key) headers.Authorization = 'Bearer ' + key
491
+ var controller = typeof AbortController === 'function' ? new AbortController() : null
492
+ var timer = controller ? setTimeout(function () { controller.abort() }, 8000) : null
493
+ fetch(api + '?ids=' + encodeURIComponent(product.id), { headers: headers, signal: controller ? controller.signal : undefined })
494
+ .then(function (res) {
495
+ return res.ok ? res.json() : null
496
+ })
497
+ .then(function (body) {
498
+ var found = body && Array.isArray(body.products) ? body.products.filter(function (p) { return p && p.id === product.id })[0] : null
499
+ if (found && Array.isArray(found.items)) live = { items: found.items, questions: Array.isArray(found.questions) ? found.questions : [] }
500
+ else if (body && Array.isArray(body.products)) live = { items: [], questions: [] }
501
+ else failed = true
502
+ })
503
+ .catch(function () {
504
+ failed = true
505
+ })
506
+ .then(function () {
507
+ if (timer) clearTimeout(timer)
508
+ drawQuestions()
509
+ draw()
510
+ })
511
+ }
512
+
513
+ qtyEl.addEventListener('input', function () {
514
+ drawQuestions()
515
+ draw()
516
+ })
517
+ island.addEventListener('click', function (event) {
518
+ var step = event.target instanceof Element ? event.target.closest('[data-bg-step]') : null
519
+ if (!step) return
520
+ qtyEl.value = String(Math.max(1, Math.min(99, quantity() + Number(step.getAttribute('data-bg-step')))))
521
+ drawQuestions()
522
+ draw()
523
+ })
524
+ for (var k = 0; k < radios.length; k++) radios[k].addEventListener('change', draw)
525
+ retryEl.addEventListener('click', read)
526
+ form.addEventListener('submit', function (event) {
527
+ event.preventDefault()
528
+ var item = selected()
529
+ var now = liveItem(item)
530
+ if (!item || !now || now.availability === 'out') return
531
+ if (!form.reportValidity()) return
532
+ var n = quantity()
533
+ var order = scoped('order')
534
+ var unit = scoped('unit')
535
+ var line = {
536
+ variant_id: item.id,
537
+ product_slug: product.slug,
538
+ product_name: String(product.name).slice(0, MOST_TEXT),
539
+ variant_name: String(item.name || product.name).slice(0, MOST_TEXT),
540
+ unit_price_cents: now.price_cents,
541
+ quantity: n,
542
+ photo_url: product.photo_url,
543
+ needs_shipping: product.ships && product.ship_to !== 'store',
544
+ }
545
+ if (asks(order) || asks(unit)) {
546
+ var answers = {}
547
+ if (asks(order)) answers.order = answersOf('o:', order)
548
+ if (asks(unit)) {
549
+ answers.units = []
550
+ for (var u = 0; u < n; u++) answers.units.push(answersOf('u:' + u + ':', unit))
551
+ }
552
+ line.answers = answers
553
+ }
554
+ if (!addLine(org, line)) {
555
+ statusEl.textContent = 'That is more than one cart can hold. Check out what is in it, then come back for more.'
556
+ return
557
+ }
558
+ questionsEl.textContent = ''
559
+ qtyEl.value = '1'
560
+ drawQuestions()
561
+ draw()
562
+ statusEl.textContent = n > 1 ? n + ' added to your cart. ' : 'Added to your cart. '
563
+ var go = document.createElement('a')
564
+ go.className = 'text-link'
565
+ go.setAttribute('data-bg-checkout-now', '')
566
+ go.href = checkoutHref(cartLink)
567
+ go.textContent = 'Check out'
568
+ statusEl.appendChild(go)
569
+ })
570
+ read()
571
+ })(document.currentScript)
572
+ </script>
@@ -1,4 +1,4 @@
1
- // What the volunteer layouts are given, by src/routes/volunteer.astro and
1
+ // What the volunteer layouts are given, by src/routes/catch-all.astro (the list) and
2
2
  // src/routes/volunteer-shift.astro. A template registers its own as
3
3
  // 'volunteer:list' and 'volunteer:detail' in its `entries`
4
4
  // (components/entries/index.ts volunteerLayoutFor).
package/src/index.js CHANGED
@@ -51,7 +51,6 @@ export function templateKit(options) {
51
51
  injectRoute({ pattern: '/preview', entrypoint: route('preview.astro'), prerender: false })
52
52
  injectRoute({ pattern: '/backgold-setup', entrypoint: route('setup.astro'), prerender: false })
53
53
  injectRoute({ pattern: '/404', entrypoint: route('not-found.astro'), prerender: false })
54
- injectRoute({ pattern: '/volunteer', entrypoint: route('volunteer.astro'), prerender: false })
55
54
  injectRoute({ pattern: '/volunteer/[slug]', entrypoint: route('volunteer-shift.astro'), prerender: false })
56
55
  injectRoute({ pattern: '/live', entrypoint: route('live.astro'), prerender: false })
57
56
  injectRoute({ pattern: '/form/[slug]', entrypoint: route('form.astro'), prerender: false })
@@ -7,7 +7,8 @@
7
7
  // a TakeoverBanner fills the first screen.
8
8
  // the header the layout the site chose in BackGold (`/site`
9
9
  // chrome.header, one of template.json's `chrome.header`;
10
- // src/lib/chrome.ts). `bar`: the brand (the logo, else the
10
+ // src/lib/chrome.ts). `bar`: the brand (the logo, with the
11
+ // name beside it when the site asks (`showName`), else the
11
12
  // template's mark and the name as a two-line wordmark) at
12
13
  // the left; the header menu, each group a dropdown, its
13
14
  // repeats drawn once (src/lib/menu.ts); the
@@ -30,6 +31,11 @@
30
31
  // the page's lesson or course to the portal's door
31
32
  // (`signInTitle`); only on a first-party site, where the
32
33
  // sign-in routes answer.
34
+ // On a store page (`cart`, src/lib/store.ts) the Cart
35
+ // link sits before the switch, its count of what this
36
+ // site's cart holds drawn by the store's script and the
37
+ // link hidden while it holds nothing (and with scripts
38
+ // off); it goes to the hosted checkout.
33
39
  // After a sign-in, the notice "You are signed in as …"
34
40
  // under the header (SignedInNotice, board D4).
35
41
  // While the organization's YouTube stream is live (GET
@@ -110,6 +116,7 @@ import { footerColumnsOf } from '../lib/footer'
110
116
  import { tidyHeaderMenu } from '../lib/menu'
111
117
  import { liveStream, withWatchLive } from '../lib/stream'
112
118
  import type { TemplateConfig } from '../template'
119
+ import type { Checkout } from '../lib/store'
113
120
  import '../styles/site.css'
114
121
 
115
122
  interface Props {
@@ -124,6 +131,8 @@ interface Props {
124
131
  areas?: Areas | null
125
132
  /** What the portal's sign-in door names for this page (a lesson's "Lesson 3: Read a budget, in Foundations", a course's title); none elsewhere. */
126
133
  signInTitle?: string | null
134
+ /** A store page's cart: the header's Cart link to this checkout; none elsewhere. */
135
+ cart?: Checkout | null
127
136
  }
128
137
 
129
138
  /** The areas this layout (and the routes, for the Sidebar) place by name. */
@@ -133,7 +142,7 @@ const bg = Astro.locals.backgold
133
142
  if (bg.setup !== null) throw new Error('The site key is not configured; the setup page renders instead of this layout.')
134
143
 
135
144
  const { site, legal, client } = bg
136
- const { template, page, areas = null, signInTitle = null, ...head } = Astro.props
145
+ const { template, page, areas = null, signInTitle = null, cart = null, ...head } = Astro.props
137
146
  const { sections } = template
138
147
  const [primary, footer, utility, stream] = await Promise.all([client.menu('primary'), client.menu('footer'), client.menu('utility'), liveStream(bg)])
139
148
  const pathname = Astro.url.pathname
@@ -275,7 +284,7 @@ const fonts = siteFonts(site.theme, bg.firstParty, template.fonts)
275
284
  <Area name="top_banner" areas={areas} components={sections} />
276
285
  <header class="site-header" data-layout={chrome.header.layout}>
277
286
  <div class="site-header-inner">
278
- <HeaderBrand name={name} logoUrl={site.brand.logo_url} />
287
+ <HeaderBrand name={name} logoUrl={site.brand.logo_url} showName={chrome.header.showName} />
279
288
  {headerNodes.length > 0 && (
280
289
  <>
281
290
  <nav class="header-bar-menu" aria-label="Header menu">
@@ -300,6 +309,13 @@ const fonts = siteFonts(site.theme, bg.firstParty, template.fonts)
300
309
  </>
301
310
  )}
302
311
  {account && <VisitorAccount visitor={visitor} mode="bar" signInTitle={signInTitle} />}
312
+ {cart && (
313
+ <a class="cart-link" href={cart.url} data-bg-cart={cart.org} data-bg-checkout={cart.url} hidden>
314
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 4h2l2.5 11h11L21 8H6.5" /><circle cx="9" cy="19" r="1.5" /><circle cx="17" cy="19" r="1.5" /></svg>
315
+ <span>Cart</span>
316
+ <span class="cart-count" data-bg-cart-count>0</span>
317
+ </a>
318
+ )}
303
319
  {appearance === 'auto' && <ModeToggle />}
304
320
  <MenuButton items={headerItems} page={page} class="button button-small header-button" />
305
321
  </div>