@backgold/template-kit 0.0.0-stage → 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 (349) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +12 -2
  3. package/dist/chunk-RJAVFRC6.js +67 -0
  4. package/dist/constants-BAIo_Q5U.d-lQbj1e1-.d.ts +48 -0
  5. package/dist/content-api-Cox1-wz5.d.ts +1096 -0
  6. package/dist/contract/content-api-examples.d.ts +72 -0
  7. package/dist/contract/content-api-examples.js +926 -0
  8. package/dist/contract/content-api.d.ts +2 -0
  9. package/dist/contract/content-api.js +1 -0
  10. package/dist/contract/site-templates.d.ts +253 -0
  11. package/dist/contract/site-templates.js +185 -0
  12. package/package.json +70 -3
  13. package/src/components/EntryCard.astro +35 -0
  14. package/src/components/EventMap.astro +118 -0
  15. package/src/components/EventPage.astro +194 -0
  16. package/src/components/FieldValue.astro +41 -0
  17. package/src/components/LeadingHero.astro +21 -0
  18. package/src/components/NotFound.astro +20 -0
  19. package/src/components/PageSections.astro +47 -0
  20. package/src/components/Prose.astro +18 -0
  21. package/src/components/chrome/Brand.astro +61 -0
  22. package/src/components/chrome/ClosingCall.astro +94 -0
  23. package/src/components/chrome/DonateStrip.astro +61 -0
  24. package/src/components/chrome/FooterColumns.astro +32 -0
  25. package/src/components/chrome/FooterContact.astro +28 -0
  26. package/src/components/chrome/MenuList.astro +45 -0
  27. package/src/components/chrome/ModeToggle.astro +125 -0
  28. package/src/components/chrome/SignedInNotice.astro +53 -0
  29. package/src/components/chrome/SignupBand.astro +12 -0
  30. package/src/components/chrome/TakeoverBanner.astro +56 -0
  31. package/src/components/chrome/VisitorAccount.astro +82 -0
  32. package/src/components/entries/AuthorBox.astro +47 -0
  33. package/src/components/entries/EntryFields.astro +29 -0
  34. package/src/components/entries/EntryHeader.astro +77 -0
  35. package/src/components/entries/ListFrame.astro +126 -0
  36. package/src/components/entries/ListSearch.astro +24 -0
  37. package/src/components/entries/Share.astro +24 -0
  38. package/src/components/entries/course/classroom.astro +26 -0
  39. package/src/components/entries/course/lesson.astro +18 -0
  40. package/src/components/entries/course/section.ts +20 -0
  41. package/src/components/entries/course/syllabus.astro +15 -0
  42. package/src/components/entries/index.ts +77 -0
  43. package/src/components/entries/newsletter/issue.astro +41 -0
  44. package/src/components/entries/newsletter/list.astro +26 -0
  45. package/src/components/entries/podcast/episode.astro +42 -0
  46. package/src/components/entries/podcast/list.astro +36 -0
  47. package/src/components/entries/post/article.astro +31 -0
  48. package/src/components/entries/post/list.astro +85 -0
  49. package/src/components/entries/props.ts +61 -0
  50. package/src/components/entries/video/cards.astro +39 -0
  51. package/src/components/entries/video/grid.astro +15 -0
  52. package/src/components/entries/video/watch.astro +41 -0
  53. package/src/components/live/LivePage.astro +215 -0
  54. package/src/components/live/LocalTime.astro +29 -0
  55. package/src/components/sections/About/books.astro +188 -0
  56. package/src/components/sections/About/credentials.ts +80 -0
  57. package/src/components/sections/About/index.astro +60 -0
  58. package/src/components/sections/About/left.astro +57 -0
  59. package/src/components/sections/About/letter.astro +111 -0
  60. package/src/components/sections/About/portrait.astro +308 -0
  61. package/src/components/sections/Advocacy/compact.astro +14 -0
  62. package/src/components/sections/Advocacy/index.astro +14 -0
  63. package/src/components/sections/Band.astro +39 -0
  64. package/src/components/sections/Blog/feature.astro +176 -0
  65. package/src/components/sections/Blog/index.astro +37 -0
  66. package/src/components/sections/Blog/latest.ts +80 -0
  67. package/src/components/sections/Blog/list.astro +186 -0
  68. package/src/components/sections/Booking/index.astro +139 -0
  69. package/src/components/sections/Booking/list.astro +144 -0
  70. package/src/components/sections/Booking/types.ts +60 -0
  71. package/src/components/sections/Calendar/agenda.astro +14 -0
  72. package/src/components/sections/Calendar/index.astro +14 -0
  73. package/src/components/sections/CandidateRoster/ballot.astro +394 -0
  74. package/src/components/sections/CandidateRoster/candidates.ts +69 -0
  75. package/src/components/sections/CandidateRoster/compact.astro +115 -0
  76. package/src/components/sections/CandidateRoster/index.astro +57 -0
  77. package/src/components/sections/CaseStudies/beforeafter.astro +222 -0
  78. package/src/components/sections/CaseStudies/cases.ts +111 -0
  79. package/src/components/sections/CaseStudies/grid.astro +261 -0
  80. package/src/components/sections/CaseStudies/index.astro +333 -0
  81. package/src/components/sections/Classroom/CourseCard.astro +181 -0
  82. package/src/components/sections/Classroom/Courses.astro +88 -0
  83. package/src/components/sections/Classroom/classroom.ts +141 -0
  84. package/src/components/sections/Classroom/index.astro +20 -0
  85. package/src/components/sections/Classroom/list.astro +15 -0
  86. package/src/components/sections/Collection/compact.astro +7 -0
  87. package/src/components/sections/Collection/entries.ts +62 -0
  88. package/src/components/sections/Collection/feature.astro +180 -0
  89. package/src/components/sections/Collection/index.astro +46 -0
  90. package/src/components/sections/Collection/library.astro +271 -0
  91. package/src/components/sections/Collection/list.astro +7 -0
  92. package/src/components/sections/Collection/outline.astro +134 -0
  93. package/src/components/sections/Collection/shelves.astro +191 -0
  94. package/src/components/sections/Comparison/Unlisted.astro +6 -0
  95. package/src/components/sections/Comparison/cards.astro +171 -0
  96. package/src/components/sections/Comparison/index.astro +191 -0
  97. package/src/components/sections/Comparison/sides.ts +98 -0
  98. package/src/components/sections/Comparison/spectrum.astro +261 -0
  99. package/src/components/sections/ContentPost/banner.astro +152 -0
  100. package/src/components/sections/ContentPost/index.astro +35 -0
  101. package/src/components/sections/ContentPost/lesson.ts +126 -0
  102. package/src/components/sections/ContentPost/player.astro +254 -0
  103. package/src/components/sections/ContentPost/prose.astro +80 -0
  104. package/src/components/sections/ContentPost/theater.astro +329 -0
  105. package/src/components/sections/Countdown/index.astro +53 -0
  106. package/src/components/sections/Course/Bar.astro +46 -0
  107. package/src/components/sections/Course/CourseHead.astro +123 -0
  108. package/src/components/sections/Course/Crumbs.astro +44 -0
  109. package/src/components/sections/Course/Icon.astro +29 -0
  110. package/src/components/sections/Course/Ring.astro +62 -0
  111. package/src/components/sections/Course/Syllabus.astro +146 -0
  112. package/src/components/sections/Course/course.ts +146 -0
  113. package/src/components/sections/Course/index.astro +143 -0
  114. package/src/components/sections/Course/outline.astro +39 -0
  115. package/src/components/sections/Cta/banner.astro +64 -0
  116. package/src/components/sections/Cta/card.astro +88 -0
  117. package/src/components/sections/Cta/index.astro +31 -0
  118. package/src/components/sections/Cta/photo.astro +114 -0
  119. package/src/components/sections/Cta/strip.astro +91 -0
  120. package/src/components/sections/Donate/index.astro +136 -0
  121. package/src/components/sections/Donate/story.astro +7 -0
  122. package/src/components/sections/Event/card.astro +14 -0
  123. package/src/components/sections/Event/index.astro +14 -0
  124. package/src/components/sections/EventsList/AgendaMonths.astro +105 -0
  125. package/src/components/sections/EventsList/CalendarLine.astro +23 -0
  126. package/src/components/sections/EventsList/EventRows.astro +196 -0
  127. package/src/components/sections/EventsList/LiveCounts.astro +75 -0
  128. package/src/components/sections/EventsList/TypeTabs.astro +53 -0
  129. package/src/components/sections/EventsList/agenda.astro +55 -0
  130. package/src/components/sections/EventsList/calendar.astro +392 -0
  131. package/src/components/sections/EventsList/cards.astro +186 -0
  132. package/src/components/sections/EventsList/cohorts.astro +205 -0
  133. package/src/components/sections/EventsList/compact.astro +163 -0
  134. package/src/components/sections/EventsList/events.ts +168 -0
  135. package/src/components/sections/EventsList/index.astro +46 -0
  136. package/src/components/sections/EventsList/map.astro +436 -0
  137. package/src/components/sections/EventsList/shifts.astro +355 -0
  138. package/src/components/sections/EventsList/week.astro +361 -0
  139. package/src/components/sections/Faq/Contact.astro +63 -0
  140. package/src/components/sections/Faq/Questions.astro +98 -0
  141. package/src/components/sections/Faq/cards.astro +74 -0
  142. package/src/components/sections/Faq/faq.ts +101 -0
  143. package/src/components/sections/Faq/index.astro +49 -0
  144. package/src/components/sections/Faq/topics.astro +178 -0
  145. package/src/components/sections/Financials/Foot.astro +38 -0
  146. package/src/components/sections/Financials/Head.astro +47 -0
  147. package/src/components/sections/Financials/donut.astro +197 -0
  148. package/src/components/sections/Financials/financials.ts +52 -0
  149. package/src/components/sections/Financials/index.astro +148 -0
  150. package/src/components/sections/Financials/table.astro +157 -0
  151. package/src/components/sections/FormBlock/index.astro +33 -0
  152. package/src/components/sections/FormBlock/wide.astro +7 -0
  153. package/src/components/sections/Hero/cover.astro +176 -0
  154. package/src/components/sections/Hero/donate.astro +209 -0
  155. package/src/components/sections/Hero/field.astro +390 -0
  156. package/src/components/sections/Hero/index.astro +52 -0
  157. package/src/components/sections/Hero/overlap.astro +151 -0
  158. package/src/components/sections/Hero/rotating.astro +30 -0
  159. package/src/components/sections/Hero/split.astro +99 -0
  160. package/src/components/sections/Hero/statement.astro +55 -0
  161. package/src/components/sections/Hero/video.astro +399 -0
  162. package/src/components/sections/Issues/checklist.astro +204 -0
  163. package/src/components/sections/Issues/drawer.astro +237 -0
  164. package/src/components/sections/Issues/index.astro +115 -0
  165. package/src/components/sections/Issues/issues.ts +37 -0
  166. package/src/components/sections/Issues/numbered.astro +79 -0
  167. package/src/components/sections/Issues/rows.astro +137 -0
  168. package/src/components/sections/Issues/steps.astro +81 -0
  169. package/src/components/sections/Issues/tabs.astro +322 -0
  170. package/src/components/sections/Leaderboard/index.astro +29 -0
  171. package/src/components/sections/Lesson/Door.astro +121 -0
  172. package/src/components/sections/Lesson/LessonBody.astro +416 -0
  173. package/src/components/sections/Lesson/Rail.astro +182 -0
  174. package/src/components/sections/Lesson/Tracker.astro +137 -0
  175. package/src/components/sections/Lesson/index.astro +27 -0
  176. package/src/components/sections/Lesson/lesson.ts +233 -0
  177. package/src/components/sections/Lesson/reading.astro +21 -0
  178. package/src/components/sections/Map/CoverageLine.astro +19 -0
  179. package/src/components/sections/Map/RegionMap.astro +109 -0
  180. package/src/components/sections/Map/bar.astro +160 -0
  181. package/src/components/sections/Map/index.astro +192 -0
  182. package/src/components/sections/Map/map.astro +275 -0
  183. package/src/components/sections/MediaKit/BioCard.astro +108 -0
  184. package/src/components/sections/MediaKit/Downloads.astro +88 -0
  185. package/src/components/sections/MediaKit/index.astro +183 -0
  186. package/src/components/sections/MediaKit/kit.ts +140 -0
  187. package/src/components/sections/MediaKit/press.astro +189 -0
  188. package/src/components/sections/MediaKit/speaker.astro +205 -0
  189. package/src/components/sections/Membership/Benefits.astro +42 -0
  190. package/src/components/sections/Membership/Check.astro +12 -0
  191. package/src/components/sections/Membership/Price.astro +61 -0
  192. package/src/components/sections/Membership/compare.astro +312 -0
  193. package/src/components/sections/Membership/index.astro +281 -0
  194. package/src/components/sections/Membership/offers.ts +169 -0
  195. package/src/components/sections/Membership/tiers.astro +217 -0
  196. package/src/components/sections/MovementMap/index.astro +50 -0
  197. package/src/components/sections/MovementTicker/index.astro +43 -0
  198. package/src/components/sections/Pathways/Doors.astro +147 -0
  199. package/src/components/sections/Pathways/Head.astro +37 -0
  200. package/src/components/sections/Pathways/index.astro +27 -0
  201. package/src/components/sections/Pathways/pathways.ts +100 -0
  202. package/src/components/sections/Pathways/quiz.astro +286 -0
  203. package/src/components/sections/Pathways/tabs.astro +271 -0
  204. package/src/components/sections/PdfEmbed/card.astro +99 -0
  205. package/src/components/sections/PdfEmbed/index.astro +26 -0
  206. package/src/components/sections/PdfEmbed/medium.astro +7 -0
  207. package/src/components/sections/PdfEmbed/tall.astro +7 -0
  208. package/src/components/sections/Petition/coverage.astro +14 -0
  209. package/src/components/sections/Petition/image.astro +14 -0
  210. package/src/components/sections/Petition/index.astro +14 -0
  211. package/src/components/sections/Petition/map.astro +14 -0
  212. package/src/components/sections/PlatformPlanks/anchors.ts +66 -0
  213. package/src/components/sections/PlatformPlanks/columns.astro +171 -0
  214. package/src/components/sections/PlatformPlanks/index.astro +56 -0
  215. package/src/components/sections/PlatformPlanks/longread.astro +250 -0
  216. package/src/components/sections/PollBlock/index.astro +30 -0
  217. package/src/components/sections/Portfolio/featured.astro +343 -0
  218. package/src/components/sections/Portfolio/index.astro +571 -0
  219. package/src/components/sections/Portfolio/strip.astro +173 -0
  220. package/src/components/sections/Portfolio/work.ts +100 -0
  221. package/src/components/sections/Progress/MatchClock.astro +166 -0
  222. package/src/components/sections/Progress/compact.astro +150 -0
  223. package/src/components/sections/Progress/index.astro +32 -0
  224. package/src/components/sections/Progress/match.astro +126 -0
  225. package/src/components/sections/Progress/ring.astro +179 -0
  226. package/src/components/sections/QuickDonate/DonateCard.astro +149 -0
  227. package/src/components/sections/QuickDonate/Picker.astro +95 -0
  228. package/src/components/sections/QuickDonate/band.astro +164 -0
  229. package/src/components/sections/QuickDonate/bar.astro +208 -0
  230. package/src/components/sections/QuickDonate/donate.ts +126 -0
  231. package/src/components/sections/QuickDonate/hero.astro +143 -0
  232. package/src/components/sections/QuickDonate/index.astro +73 -0
  233. package/src/components/sections/QuickDonate/jar.astro +225 -0
  234. package/src/components/sections/QuickDonate/ladder.astro +248 -0
  235. package/src/components/sections/QuoteStrip/carousel.astro +340 -0
  236. package/src/components/sections/QuoteStrip/index.astro +58 -0
  237. package/src/components/sections/QuoteStrip/logos.astro +226 -0
  238. package/src/components/sections/QuoteStrip/quotes.ts +61 -0
  239. package/src/components/sections/QuoteStrip/single.astro +92 -0
  240. package/src/components/sections/QuoteStrip/ticker.astro +319 -0
  241. package/src/components/sections/QuoteStrip/wall.astro +113 -0
  242. package/src/components/sections/Resources/band.astro +93 -0
  243. package/src/components/sections/Resources/featured.astro +239 -0
  244. package/src/components/sections/Resources/index.astro +225 -0
  245. package/src/components/sections/Resources/resources.ts +92 -0
  246. package/src/components/sections/SampleBallot/Position.astro +39 -0
  247. package/src/components/sections/SampleBallot/ballot.ts +92 -0
  248. package/src/components/sections/SampleBallot/cards.astro +299 -0
  249. package/src/components/sections/SampleBallot/index.astro +326 -0
  250. package/src/components/sections/SampleBallot/measures.astro +172 -0
  251. package/src/components/sections/Scorecard/grades.astro +141 -0
  252. package/src/components/sections/Scorecard/index.astro +294 -0
  253. package/src/components/sections/Scorecard/promise.astro +167 -0
  254. package/src/components/sections/Scorecard/votes.ts +83 -0
  255. package/src/components/sections/SectionHead.astro +31 -0
  256. package/src/components/sections/Services/Button.astro +24 -0
  257. package/src/components/sections/Services/Check.astro +12 -0
  258. package/src/components/sections/Services/Includes.astro +42 -0
  259. package/src/components/sections/Services/compare.astro +328 -0
  260. package/src/components/sections/Services/index.astro +187 -0
  261. package/src/components/sections/Services/list.astro +181 -0
  262. package/src/components/sections/Services/services.ts +80 -0
  263. package/src/components/sections/ShareKit/Actions.astro +71 -0
  264. package/src/components/sections/ShareKit/Buttons.astro +62 -0
  265. package/src/components/sections/ShareKit/compact.astro +123 -0
  266. package/src/components/sections/ShareKit/index.astro +160 -0
  267. package/src/components/sections/ShareKit/share.ts +60 -0
  268. package/src/components/sections/ShareKit/strip.astro +173 -0
  269. package/src/components/sections/SignupCapture/band.astro +7 -0
  270. package/src/components/sections/SignupCapture/index.astro +103 -0
  271. package/src/components/sections/SignupCapture/inline.astro +7 -0
  272. package/src/components/sections/SocialFeed/index.astro +34 -0
  273. package/src/components/sections/StatCards/feature.astro +143 -0
  274. package/src/components/sections/StatCards/index.astro +51 -0
  275. package/src/components/sections/StatCards/ribbon.astro +113 -0
  276. package/src/components/sections/StatCards/wall.astro +177 -0
  277. package/src/components/sections/Store/featured.astro +14 -0
  278. package/src/components/sections/Store/index.astro +14 -0
  279. package/src/components/sections/Stories/Status.astro +42 -0
  280. package/src/components/sections/Stories/StoryCards.astro +171 -0
  281. package/src/components/sections/Stories/cards.astro +42 -0
  282. package/src/components/sections/Stories/index.astro +238 -0
  283. package/src/components/sections/Stories/stories.ts +97 -0
  284. package/src/components/sections/Stories/timeline.astro +135 -0
  285. package/src/components/sections/TeamGrid/board.astro +280 -0
  286. package/src/components/sections/TeamGrid/index.astro +71 -0
  287. package/src/components/sections/TeamGrid/list.astro +306 -0
  288. package/src/components/sections/TeamGrid/people.ts +178 -0
  289. package/src/components/sections/VideoEmbed/index.astro +52 -0
  290. package/src/components/sections/VideoEmbed/landscape.astro +7 -0
  291. package/src/components/sections/VideoEmbed/portrait.astro +7 -0
  292. package/src/components/sections/VideoEmbed/square.astro +7 -0
  293. package/src/components/sections/VoterTools/DaysLeft.astro +33 -0
  294. package/src/components/sections/VoterTools/Lookup.astro +43 -0
  295. package/src/components/sections/VoterTools/dates.astro +153 -0
  296. package/src/components/sections/VoterTools/index.astro +231 -0
  297. package/src/components/sections/VoterTools/polling.astro +144 -0
  298. package/src/components/sections/VoterTools/voter-tools.ts +71 -0
  299. package/src/components/sections/index.ts +373 -0
  300. package/src/components/sections/modules/Headed.astro +39 -0
  301. package/src/components/sections/modules/ModuleFrame.astro +181 -0
  302. package/src/components/store/CollectionPage.astro +40 -0
  303. package/src/components/store/ProductCard.astro +32 -0
  304. package/src/components/store/ProductGrid.astro +16 -0
  305. package/src/components/store/ProductPage.astro +146 -0
  306. package/src/components/store/StorePage.astro +137 -0
  307. package/src/components/store/StoreScript.astro +572 -0
  308. package/src/components/volunteer/ShiftLive.astro +90 -0
  309. package/src/components/volunteer/detail.astro +247 -0
  310. package/src/components/volunteer/list.astro +298 -0
  311. package/src/components/volunteer/props.ts +21 -0
  312. package/src/env.d.ts +22 -0
  313. package/src/index.d.ts +10 -0
  314. package/src/index.js +63 -0
  315. package/src/layouts/Site.astro +387 -0
  316. package/src/lib/academy.ts +146 -0
  317. package/src/lib/brand.ts +534 -0
  318. package/src/lib/chrome.ts +121 -0
  319. package/src/lib/donate-frame.ts +104 -0
  320. package/src/lib/entries.ts +190 -0
  321. package/src/lib/env.ts +34 -0
  322. package/src/lib/event-map-draw.ts +91 -0
  323. package/src/lib/events.ts +476 -0
  324. package/src/lib/fonts.ts +116 -0
  325. package/src/lib/footer.ts +24 -0
  326. package/src/lib/format.ts +160 -0
  327. package/src/lib/geo.ts +131 -0
  328. package/src/lib/live.ts +55 -0
  329. package/src/lib/menu.ts +48 -0
  330. package/src/lib/petition-text.ts +29 -0
  331. package/src/lib/reading.ts +17 -0
  332. package/src/lib/regions.ts +215 -0
  333. package/src/lib/section.ts +105 -0
  334. package/src/lib/shifts.ts +187 -0
  335. package/src/lib/store.ts +521 -0
  336. package/src/lib/stream-time.ts +20 -0
  337. package/src/lib/stream.ts +141 -0
  338. package/src/lib/visitor.ts +54 -0
  339. package/src/routes/catch-all.astro +435 -0
  340. package/src/routes/form.astro +30 -0
  341. package/src/routes/live.astro +49 -0
  342. package/src/routes/not-found.astro +18 -0
  343. package/src/routes/preview.astro +60 -0
  344. package/src/routes/setup.astro +62 -0
  345. package/src/routes/volunteer-shift.astro +61 -0
  346. package/src/styles/entries.css +784 -0
  347. package/src/styles/site.css +1910 -0
  348. package/src/styles/store.css +634 -0
  349. package/src/template.ts +182 -0
@@ -0,0 +1,160 @@
1
+ // Dates, money and copy as the components show them. A moment given with a
2
+ // time zone (an event row carries its own IANA `timezone`) is shown in that
3
+ // zone and named by the zone's short name ("CDT"), so an event reads in its
4
+ // own day and time wherever the page is served; `zoneName` spells the zone
5
+ // out ("Mountain Time") for a line that names it once for a whole page, and
6
+ // formatWhen leaves it off the time beside such a line. Without a usable zone a value
7
+ // is shown as written: the calendar day and clock time in the value itself,
8
+ // so a server in another time zone never moves it to another day, and a time
9
+ // written in UTC (ending in `Z`) says "UTC". A date with no time is a
10
+ // calendar day, with no zone.
11
+
12
+ import { sanitizeRichText } from '@backgold/astro/server'
13
+
14
+ const WALL_CLOCK = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/
15
+ // A time that names its offset (`Z` or `±hh:mm`) is one moment, which a zone can show.
16
+ const INSTANT = /[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:z|[+-]\d{2}:?\d{2})$/i
17
+
18
+ const DAY = new Intl.DateTimeFormat('en-US', { year: 'numeric', month: 'long', day: 'numeric', timeZone: 'UTC' })
19
+ const SHORT_DAY = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' })
20
+ const DAY_AND_TIME_PARTS: Intl.DateTimeFormatOptions = {
21
+ weekday: 'long',
22
+ month: 'long',
23
+ day: 'numeric',
24
+ year: 'numeric',
25
+ hour: 'numeric',
26
+ minute: '2-digit',
27
+ }
28
+ const DAY_AND_TIME = new Intl.DateTimeFormat('en-US', { ...DAY_AND_TIME_PARTS, timeZone: 'UTC' })
29
+
30
+ // One formatter per zone and naming, built on first use (building one is the
31
+ // costly part); null for a name Intl does not know.
32
+ const IN_ZONE = new Map<string, Intl.DateTimeFormat | null>()
33
+
34
+ function formatter(zone: string, options: Intl.DateTimeFormatOptions, key: string): Intl.DateTimeFormat | null {
35
+ let format = IN_ZONE.get(`${key}\n${zone}`)
36
+ if (format === undefined) {
37
+ try {
38
+ format = new Intl.DateTimeFormat('en-US', { ...options, timeZone: zone })
39
+ } catch (err) {
40
+ if (!(err instanceof RangeError)) throw err
41
+ format = null
42
+ }
43
+ IN_ZONE.set(`${key}\n${zone}`, format)
44
+ }
45
+ return format
46
+ }
47
+
48
+ function inZone(timeZone: unknown, named: boolean): Intl.DateTimeFormat | null {
49
+ const zone = text(timeZone)?.trim()
50
+ if (!zone) return null
51
+ return named ? formatter(zone, { ...DAY_AND_TIME_PARTS, timeZoneName: 'short' }, 'short') : formatter(zone, DAY_AND_TIME_PARTS, 'none')
52
+ }
53
+
54
+ const zonePart = (format: Intl.DateTimeFormat | null): string | null =>
55
+ format?.formatToParts(new Date()).find((p) => p.type === 'timeZoneName')?.value ?? null
56
+
57
+ /**
58
+ * The zone as a name a reader knows, "Mountain Time" for America/Denver (its
59
+ * generic name, the same in summer and winter); its short name ("UTC") for a
60
+ * zone with no generic name but an offset; null for no zone or one Intl does
61
+ * not know.
62
+ */
63
+ export function zoneName(timeZone: unknown): string | null {
64
+ const zone = text(timeZone)?.trim()
65
+ if (!zone) return null
66
+ const generic = zonePart(formatter(zone, { timeZoneName: 'longGeneric' }, 'generic'))
67
+ return generic && !/^GMT\b/.test(generic) ? generic : zonePart(formatter(zone, { timeZoneName: 'short' }, 'zone'))
68
+ }
69
+
70
+ function wallClock(value: string): { date: Date; hasTime: boolean } | null {
71
+ const m = WALL_CLOCK.exec(value)
72
+ if (!m || Number.isNaN(Date.parse(value.length === 10 ? `${value}T00:00:00Z` : value))) return null
73
+ const [, y, mo, d, h, mi] = m
74
+ const date = new Date(Date.UTC(Number(y), Number(mo) - 1, Number(d), Number(h ?? 0), Number(mi ?? 0)))
75
+ return { date, hasTime: h !== undefined }
76
+ }
77
+
78
+ /** "October 8, 2026", or null when the value is not a date. */
79
+ export function formatDay(value: unknown): string | null {
80
+ if (typeof value !== 'string') return null
81
+ const parsed = wallClock(value)
82
+ return parsed ? DAY.format(parsed.date) : null
83
+ }
84
+
85
+ /** "Oct 8" (board A1's news bylines), or null when the value is not a date. */
86
+ export function formatShortDay(value: unknown): string | null {
87
+ if (typeof value !== 'string') return null
88
+ const parsed = wallClock(value)
89
+ return parsed ? SHORT_DAY.format(parsed.date) : null
90
+ }
91
+
92
+ /**
93
+ * "Saturday, October 10, 2026 at 10:00 AM CDT" for a moment shown in
94
+ * `timeZone` ("… at 10:00 AM" with `named` false, beside a line that names
95
+ * the zone). With no usable zone: "… at 7:00 PM UTC" for a UTC time, the
96
+ * clock time as written for any other. "October 10, 2026" for a date with no
97
+ * time, zone or not. Null when the value is not a date.
98
+ */
99
+ export function formatWhen(value: unknown, timeZone?: unknown, named = true): string | null {
100
+ if (typeof value !== 'string') return null
101
+ const parsed = wallClock(value)
102
+ if (!parsed) return null
103
+ if (!parsed.hasTime) return DAY.format(parsed.date)
104
+ const trimmed = value.trim()
105
+ const zoned = INSTANT.test(trimmed) ? inZone(timeZone, named) : null
106
+ if (zoned) return zoned.format(new Date(trimmed))
107
+ return /z$/i.test(trimmed) ? `${DAY_AND_TIME.format(parsed.date)} UTC` : DAY_AND_TIME.format(parsed.date)
108
+ }
109
+
110
+ const DOLLARS = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD', maximumFractionDigits: 0 })
111
+
112
+ /** Whole dollars from cents: 1240000 → "$12,400". */
113
+ export function formatCents(cents: unknown): string | null {
114
+ return typeof cents === 'number' && Number.isFinite(cents) ? DOLLARS.format(Math.round(cents / 100)) : null
115
+ }
116
+
117
+ /** A file size: 2048 → "2 KB". */
118
+ export function formatBytes(bytes: unknown): string | null {
119
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes < 0) return null
120
+ if (bytes < 1024) return `${bytes} B`
121
+ if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`
122
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
123
+ }
124
+
125
+ /** A non-blank string, or null. */
126
+ export function text(value: unknown): string | null {
127
+ return typeof value === 'string' && value.trim() !== '' ? value : null
128
+ }
129
+
130
+ /**
131
+ * A copy value from BackGold: the editor's restricted HTML when it opens with
132
+ * a prose tag (sanitized), else plain text with a blank line between
133
+ * paragraphs (escaped by Astro when rendered).
134
+ */
135
+ export type Prose = { html: string } | { paragraphs: string[] }
136
+
137
+ const RICH_PROSE = /^\s*<\s*(p|br|strong|em|a)[\s/>]/i
138
+
139
+ export function prose(value: unknown): Prose | null {
140
+ const raw = text(value)
141
+ if (!raw) return null
142
+ if (RICH_PROSE.test(raw)) return { html: sanitizeRichText(raw) }
143
+ const paragraphs = raw.split(/\n{2,}/).map((p) => p.trim()).filter(Boolean)
144
+ return paragraphs.length > 0 ? { paragraphs } : null
145
+ }
146
+
147
+ /** "A", "A and B", "A, B and C". */
148
+ export function listOf(names: string[]): string {
149
+ if (names.length <= 1) return names.join('')
150
+ return `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`
151
+ }
152
+
153
+ /**
154
+ * A stat a hosted BackGold page fills in live (`auto:…`) has no value a
155
+ * server can show; it is left out rather than shown as code.
156
+ */
157
+ export function literalStat(value: unknown): string | null {
158
+ const raw = text(value)
159
+ return raw && !raw.startsWith('auto:') ? raw : null
160
+ }
package/src/lib/geo.ts ADDED
@@ -0,0 +1,131 @@
1
+ // The geography a Map section draws: BackGold's geometry for the section's
2
+ // set of places, at the section's `media.geoUrl` (`/lp-runtime/<hash>.json`
3
+ // on the api, where <hash> is the file's SHA-256). It is already projected
4
+ // to SVG coordinates:
5
+ //
6
+ // { width, height, paths: { key: d }, centroids: { key: [x, y] },
7
+ // labels?: { key: label }, underlay?: [key] }
8
+ //
9
+ // A county set keys each place on its name; a district set keys on a code
10
+ // and names each place in `labels`. `underlay` lists places drawn first,
11
+ // beneath the rest, because they overlap others by design.
12
+ //
13
+ // The address names the file's hash, so its bytes never change. It is read
14
+ // once and kept: in this isolate's memory, and in the BACKGOLD_CACHE KV
15
+ // namespace (when the Worker has one) under `geo:<hash>` for thirty days, so
16
+ // another isolate reads KV instead of BackGold. A relative address is read
17
+ // from BACKGOLD_API_ORIGIN, where the api serves `/lp-runtime`. Anything that
18
+ // is not such a file is never read, and a read that fails or takes longer
19
+ // than GEO_TIMEOUT_MS is not kept: the section draws without its map and the
20
+ // next render asks again.
21
+
22
+ import { apiOrigin, workerVars } from './env'
23
+
24
+ export interface Geo {
25
+ width: number
26
+ height: number
27
+ /** Place key → SVG path `d`, in `0 0 width height`. */
28
+ paths: Record<string, string>
29
+ /** Place key → its centre, in the same space. */
30
+ centroids: Record<string, [number, number]>
31
+ /** Place key → the name to show, for a set keyed on codes. */
32
+ labels: Record<string, string>
33
+ /** Place keys drawn first, beneath every other place. */
34
+ underlay: string[]
35
+ }
36
+
37
+ const GEO_PATH = /^\/lp-runtime\/([0-9a-f]{64})\.json$/
38
+ /** Only path commands and numbers: what BackGold's geometry is made of. */
39
+ const PATH_DATA = /^[MmLlHhVvZz0-9eE.,+\-\s]+$/
40
+ const GEO_TIMEOUT_MS = 4000
41
+ const KV_TTL_SECONDS = 30 * 86400
42
+ /** The most geometries an isolate keeps; past it the oldest is dropped. */
43
+ const MAX_HELD = 8
44
+
45
+ interface KvText {
46
+ get(key: string, type: 'text'): Promise<string | null>
47
+ put(key: string, value: string, options?: { expirationTtl?: number }): Promise<void>
48
+ }
49
+
50
+ const held = new Map<string, Promise<Geo | null>>()
51
+
52
+ const isRecord = (value: unknown): value is Record<string, unknown> => !!value && typeof value === 'object' && !Array.isArray(value)
53
+
54
+ /** The geometry in `payload`, or null when it is not one. */
55
+ function parseGeo(payload: unknown): Geo | null {
56
+ if (!isRecord(payload) || !isRecord(payload.paths)) return null
57
+ const { width, height } = payload
58
+ if (typeof width !== 'number' || typeof height !== 'number' || !(width > 0) || !(height > 0)) return null
59
+ const paths: Record<string, string> = {}
60
+ for (const [key, d] of Object.entries(payload.paths)) if (typeof d === 'string' && d !== '' && PATH_DATA.test(d)) paths[key] = d
61
+ if (Object.keys(paths).length === 0) return null
62
+ const centroids: Record<string, [number, number]> = {}
63
+ for (const [key, c] of Object.entries(isRecord(payload.centroids) ? payload.centroids : {})) {
64
+ if (Array.isArray(c) && c.length === 2 && Number.isFinite(c[0]) && Number.isFinite(c[1])) centroids[key] = [c[0], c[1]]
65
+ }
66
+ const labels: Record<string, string> = {}
67
+ for (const [key, label] of Object.entries(isRecord(payload.labels) ? payload.labels : {})) if (typeof label === 'string' && label.trim() !== '') labels[key] = label
68
+ const underlay = Array.isArray(payload.underlay) ? payload.underlay.filter((key): key is string => typeof key === 'string' && key in paths) : []
69
+ return { width, height, paths, centroids, labels, underlay }
70
+ }
71
+
72
+ function kvOf(env: Record<string, unknown>): KvText | null {
73
+ const kv = env.BACKGOLD_CACHE as Partial<KvText> | undefined
74
+ return kv && typeof kv.get === 'function' && typeof kv.put === 'function' ? (kv as KvText) : null
75
+ }
76
+
77
+ /** The geometry file's address and hash, when `geoUrl` names one; relative addresses on `origin`. */
78
+ function geoFile(geoUrl: string, origin: string | null): { url: string; hash: string } | null {
79
+ let url: URL
80
+ try {
81
+ url = geoUrl.startsWith('/') && !geoUrl.startsWith('//') ? new URL(`${origin ?? ''}${geoUrl}`) : new URL(geoUrl)
82
+ } catch {
83
+ return null
84
+ }
85
+ const hash = GEO_PATH.exec(url.pathname)?.[1]
86
+ if (!hash || (url.protocol !== 'https:' && url.protocol !== 'http:') || url.search || url.hash || url.username || url.password) return null
87
+ return { url: url.href, hash }
88
+ }
89
+
90
+ async function read(file: { url: string; hash: string }, kv: KvText | null, defer: (task: Promise<unknown>) => void): Promise<Geo | null> {
91
+ const key = `geo:${file.hash}`
92
+ const stored = kv ? await kv.get(key, 'text').catch(() => null) : null
93
+ if (stored) {
94
+ try {
95
+ const geo = parseGeo(JSON.parse(stored))
96
+ if (geo) return geo
97
+ } catch {
98
+ // A value that is not the geometry is read again from BackGold.
99
+ }
100
+ }
101
+ const res = await fetch(file.url, { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(GEO_TIMEOUT_MS) })
102
+ if (!res.ok) return null
103
+ const text = await res.text()
104
+ const geo = parseGeo(JSON.parse(text))
105
+ if (geo && kv) defer(kv.put(key, text, { expirationTtl: KV_TTL_SECONDS }).catch(() => undefined))
106
+ return geo
107
+ }
108
+
109
+ /**
110
+ * The geometry at a section's `geoUrl`, or null (no address, not a geometry
111
+ * file, or the read failed). The KV write runs after the response, through
112
+ * the request's `waitUntil` (`locals.cfContext`) where it has one, so the
113
+ * page never waits for it.
114
+ */
115
+ export async function loadGeo(geoUrl: string | null, locals: object): Promise<Geo | null> {
116
+ if (!geoUrl) return null
117
+ const env = await workerVars()
118
+ const file = geoFile(geoUrl, apiOrigin(env))
119
+ if (!file) return null
120
+ let pending = held.get(file.hash)
121
+ if (!pending) {
122
+ const cf = (locals as { cfContext?: { waitUntil(task: Promise<unknown>): void } }).cfContext
123
+ const defer = (task: Promise<unknown>) => (cf ? cf.waitUntil(task) : void task)
124
+ pending = read(file, kvOf(env), defer).catch(() => null)
125
+ held.set(file.hash, pending)
126
+ while (held.size > MAX_HELD) held.delete(held.keys().next().value!)
127
+ }
128
+ const geo = await pending
129
+ if (!geo && held.get(file.hash) === pending) held.delete(file.hash)
130
+ return geo
131
+ }
@@ -0,0 +1,55 @@
1
+ // Where a visitor's browser reads an event's live counts: the Content API's
2
+ // `GET /events/live?ids=`, which answers `{ events: [{ id, going, seats_left }] }`
3
+ // (and a volunteer shift's, `GET /shifts/live?ids=`, `{ shifts: [{ id,
4
+ // signed_up, waitlisted, state }] }`, and a store listing's price,
5
+ // availability and questions, `GET /products/live?ids=`, the same way)
6
+ // outside the content version (`Cache-Control: public, max-age=30`). The page
7
+ // around the counts is cached under the content version, so the counts are
8
+ // never part of it: a few lines of script fetch them after the page loads.
9
+ //
10
+ // Which address the browser asks, by how the site reads BackGold:
11
+ //
12
+ // - First-party (`locals.backgold.firstParty`: `BACKGOLD_SITE_ID` with the
13
+ // `BACKGOLD_API` binding, or BackGold's shared template Worker): the site's
14
+ // host is the api's own, and the api answers `/api/content/v1/events/live`
15
+ // there for that host's site with no key, so the browser asks that
16
+ // same-origin path and sends no Authorization header.
17
+ // - With a site key: the browser sends the publishable key
18
+ // (`BACKGOLD_SITE_KEY`, which only reads what the public site already
19
+ // shows) to `<BACKGOLD_API_ORIGIN>/api/content/v1/events/live`, as any
20
+ // partner's browser code may. Without a publishable key, or with an api
21
+ // origin that is not an http(s) URL, there is nothing to ask and no counts
22
+ // are drawn.
23
+
24
+ import { apiOrigin, trimmed, workerVars } from './env'
25
+
26
+ const PUBLISHABLE_KEY = /^bg_site_pk_[A-Za-z0-9]+$/
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
29
+
30
+ export interface LiveSource {
31
+ /** The same-origin path (first-party), else `<api origin>/api/content/v1/events/live` (or `/shifts/live`, `/products/live`). */
32
+ url: string
33
+ /** The publishable key the browser sends; null first-party, where none is sent. */
34
+ key: string | null
35
+ }
36
+
37
+ /** The live route for this site (see above), events', shifts' or products'; null when a key-mode site has nothing to ask with. */
38
+ export async function liveSource(firstParty: boolean, feed: keyof typeof LIVE_PATHS = 'events'): Promise<LiveSource | null> {
39
+ const path = LIVE_PATHS[feed]
40
+ if (firstParty) return { url: path, key: null }
41
+ const env = await workerVars()
42
+ const key = trimmed(env.BACKGOLD_SITE_KEY)
43
+ if (!PUBLISHABLE_KEY.test(key)) return null
44
+ const origin = apiOrigin(env)
45
+ return origin ? { url: `${origin}${path}`, key } : null
46
+ }
47
+
48
+ const emitted = new WeakSet<Request>()
49
+
50
+ /** True the first time it is asked during one render, so a page carries one copy of the live script. */
51
+ export function firstLiveScript(request: Request): boolean {
52
+ if (emitted.has(request)) return false
53
+ emitted.add(request)
54
+ return true
55
+ }
@@ -0,0 +1,48 @@
1
+ // The header menu as the bar and the phone sheet draw it, from menuOf's
2
+ // nodes: what an organization's menu rows can repeat is drawn once.
3
+ //
4
+ // - The header button is never a plain item too: an item (at any depth)
5
+ // with the button's label (case and spacing aside) is left out, so DONATE
6
+ // reads once, as the button, whatever address each row names. An item
7
+ // with the button's address under another label stays (a drive's "The
8
+ // petition" beside its "Sign the petition" button).
9
+ // - Two siblings with the same label and the same address are one item,
10
+ // the first; a group that opens on its own address does not list that
11
+ // address again among its children (MenuList lists it first).
12
+ // - A group whose links come down to one (its own address and its
13
+ // children, counted once) is a plain item: the group's label, the one
14
+ // link's address, current where that link is. A group left with no link
15
+ // at all (its one link was the button) is left out.
16
+ //
17
+ // The footer is not tidied here: its groups are its columns.
18
+ import type { MenuNode } from '@backgold/astro/server'
19
+
20
+ const sameLabel = (a: string, b: string) => a.trim().replace(/\s+/g, ' ').toLowerCase() === b.trim().replace(/\s+/g, ' ').toLowerCase()
21
+ const sameItem = (a: MenuNode, b: MenuNode) => a.href === b.href && sameLabel(a.label, b.label)
22
+
23
+ const isButton = (node: MenuNode, button: MenuNode | null): boolean => button !== null && sameLabel(node.label, button.label)
24
+
25
+ function tidy(nodes: MenuNode[], button: MenuNode | null): MenuNode[] {
26
+ const out: MenuNode[] = []
27
+ for (const node of nodes) {
28
+ const isGroup = node.children.length > 0
29
+ if (!isGroup && isButton(node, button)) continue
30
+ let children = isGroup ? tidy(node.children, button) : []
31
+ if (node.href) children = children.filter((child) => !(child.children.length === 0 && sameItem(child, { ...node, children: [] })))
32
+ let next: MenuNode = { ...node, children }
33
+ if (isGroup) {
34
+ const links = [...(node.href ? [{ ...node, children: [] }] : []), ...children]
35
+ if (links.length === 0) continue
36
+ const only = links.length === 1 ? links[0]! : null
37
+ if (only && only.children.length === 0) next = { ...only, label: node.label, children: [] }
38
+ }
39
+ if (out.some((kept) => kept.children.length === 0 && next.children.length === 0 && sameItem(kept, next))) continue
40
+ out.push(next)
41
+ }
42
+ return out
43
+ }
44
+
45
+ /** The header menu with repeats drawn once (above); `button` is the header button, when one shows. */
46
+ export function tidyHeaderMenu(nodes: MenuNode[], button: MenuNode | null): MenuNode[] {
47
+ return tidy(nodes, button)
48
+ }
@@ -0,0 +1,29 @@
1
+ // A Petition section's petition text, as the Content API sends it on the
2
+ // section's `data.petition.text_html` (the editor's restricted HTML), sanitized
3
+ // here. Null when BackGold sends no text: the layout then draws nothing more
4
+ // and the frame keeps its text whole. The Unlabeled and nonprofit Petition
5
+ // layouts draw it beside the sheet; the asks are the page's Issues band's and
6
+ // the legal note is the frame's, so neither is read here.
7
+ import type { Section } from '@backgold/content'
8
+ import { sanitizeRichText } from '@backgold/astro/server'
9
+ import { text } from './format'
10
+
11
+ // TODO(the platform MR from backgold branch task/petition-text-left):
12
+ // the vendored contract's SectionData has no `petition` yet; drop this type for
13
+ // the contract's once that MR lands and `contract-pull` brings it here.
14
+ /** The petition a Petition section names, on its `data` (the platform's Content API). */
15
+ interface SectionPetition {
16
+ slug: string
17
+ title: string
18
+ text_html: string | null
19
+ addressed_to: string | null
20
+ signature_count: number
21
+ goal: number | null
22
+ }
23
+
24
+ export function petitionText(section: Section): string | null {
25
+ const petition = (section.data as { petition?: Partial<SectionPetition> } | undefined)?.petition
26
+ const raw = text(petition?.text_html)
27
+ const html = raw ? sanitizeRichText(raw).trim() : ''
28
+ return html || null
29
+ }
@@ -0,0 +1,17 @@
1
+ // The entry a request is drawing, for the sections in its areas: a Blog
2
+ // section in an entry's sidebar ("More from the campaign", board C11) lists
3
+ // the newest posts but the one being read. The route marks it on the
4
+ // request's `Astro.locals` (one object per request, the same in every
5
+ // component it renders); a page, a list or an event marks nothing.
6
+
7
+ const reading = new WeakMap<object, string>()
8
+
9
+ /** Mark `entryId` as the entry this request draws. */
10
+ export function markReading(locals: object, entryId: string): void {
11
+ reading.set(locals, entryId)
12
+ }
13
+
14
+ /** The id of the entry this request draws; null on any other route. */
15
+ export function readingOf(locals: object): string | null {
16
+ return reading.get(locals) ?? null
17
+ }
@@ -0,0 +1,215 @@
1
+ // A Map section's places, matched to its geometry (src/lib/geo.ts) the way
2
+ // BackGold's own Map block matches them (packages/site map-status.ts and
3
+ // runtime/map-choropleth.ts): a row's `region` names a place by its key in
4
+ // the geometry, ignoring case and surrounding spaces, and a later row for
5
+ // the same place wins. Its `status` is 'lit', 'starting', or anything else,
6
+ // which is dark; a place no row names is dark too.
7
+ //
8
+ // A section with `focusRegion` frames that one place (BackGold's
9
+ // focusFrameViewBox): its bounding box padded by FOCUS_PADDING of its larger
10
+ // side, no narrower than FOCUS_MIN_WIDTH of the whole set, shaped to the
11
+ // whole set's proportions and kept inside it. The other places stay, dimmed.
12
+ //
13
+ // The coverage line is a count and a label. Over a map it counts the lit
14
+ // rows against the set's `regionTotal` (else the rows) and names the set's
15
+ // places by its `regionNoun` ("8 of 254 counties" · "Organized"); over the
16
+ // tiles it counts against the rows ("2 of 4" · "Organized"). A framed
17
+ // map names its place and status instead ("Travis county" · "Organized"),
18
+ // as BackGold's block does: the count of the whole set is not that place's
19
+ // story. The label is the section's litLabel as written, never turned into
20
+ // a verb. The numbers behind a map's count are its share (coverageShare):
21
+ // the lit rows, and the set's `regionTotal` when a positive number, else
22
+ // the rows. The 'bar' layout draws that share as one wide bar with no map,
23
+ // under the line a map would carry (coverageOf).
24
+ //
25
+ // Under a map the directory lists the lit and starting places only; the
26
+ // places the map draws dark are one invitation in the coverage line's
27
+ // shape, their count and the section's darkLabel ("239 counties" · "No
28
+ // chapter yet"), which carries the section's charter link (the link whose
29
+ // label is `charterCtaText`) as its button.
30
+
31
+ import type { Section } from '@backgold/content'
32
+ import type { Geo } from './geo'
33
+ import { linkOf, type Link, type Row } from './section'
34
+ import { text } from './format'
35
+
36
+ export type RegionStatus = 'lit' | 'starting' | 'dark'
37
+
38
+ export interface Place {
39
+ /** The row's `region`, as the organization wrote it. */
40
+ name: string
41
+ status: RegionStatus
42
+ link: Link | null
43
+ }
44
+
45
+ export interface DrawnRegion {
46
+ key: string
47
+ /** `labels[key]`, else the key. */
48
+ label: string
49
+ d: string
50
+ status: RegionStatus
51
+ /** A lit place's link, when its row has a safe one. */
52
+ link: Link | null
53
+ focus: boolean
54
+ }
55
+
56
+ export interface DrawnMap {
57
+ viewBox: string
58
+ /** Every place in the geometry: the underlay first, the framed place last. */
59
+ regions: DrawnRegion[]
60
+ /** The framed place, when `focusRegion` names one in the geometry. */
61
+ focus: DrawnRegion | null
62
+ }
63
+
64
+ const FOCUS_PADDING = 0.35
65
+ const FOCUS_MIN_WIDTH = 0.14
66
+
67
+ /** The key BackGold matches a row's place to the geometry by. */
68
+ const regionKey = (name: string): string => name.trim().toLowerCase()
69
+
70
+ /** The section's rows as places: each with a name, its status and its link. */
71
+ export function placesOf(rows: Row[]): Place[] {
72
+ return rows.flatMap((row) => {
73
+ const name = text(row.region)
74
+ if (!name) return []
75
+ const status: RegionStatus = row.status === 'lit' ? 'lit' : row.status === 'starting' ? 'starting' : 'dark'
76
+ return [{ name, status, link: linkOf(row.region, row.url) }]
77
+ })
78
+ }
79
+
80
+ /** The place in `geo` that `name` names: the key as written, else ignoring case. */
81
+ function keyIn(geo: Geo, name: string): string | null {
82
+ if (name in geo.paths) return name
83
+ const wanted = regionKey(name)
84
+ return Object.keys(geo.paths).find((key) => regionKey(key) === wanted) ?? null
85
+ }
86
+
87
+ /** The bounding box of a path made of absolute M and L commands; null for any other. */
88
+ function bbox(d: string): { x: number; y: number; w: number; h: number } | null {
89
+ if (/[^MLZ0-9eE.,\-\s]/.test(d)) return null
90
+ const nums = d.match(/-?\d*\.?\d+(?:e-?\d+)?/gi)
91
+ if (!nums || nums.length < 2) return null
92
+ let [minX, minY, maxX, maxY] = [Infinity, Infinity, -Infinity, -Infinity]
93
+ for (let i = 0; i + 1 < nums.length; i += 2) {
94
+ const x = Number(nums[i])
95
+ const y = Number(nums[i + 1])
96
+ minX = Math.min(minX, x)
97
+ minY = Math.min(minY, y)
98
+ maxX = Math.max(maxX, x)
99
+ maxY = Math.max(maxY, y)
100
+ }
101
+ return Number.isFinite(minX) && Number.isFinite(minY) ? { x: minX, y: minY, w: maxX - minX, h: maxY - minY } : null
102
+ }
103
+
104
+ const round = (n: number): number => Math.round(n * 100) / 100
105
+
106
+ /** The viewBox framing `key`: from its path's box, else a point at its centroid; null with neither. */
107
+ function frame(geo: Geo, key: string): string | null {
108
+ const centroid = geo.centroids[key]
109
+ const box = bbox(geo.paths[key]!) ?? (centroid ? { x: centroid[0], y: centroid[1], w: 0, h: 0 } : null)
110
+ if (!box) return null
111
+ const aspect = geo.width / geo.height
112
+ const pad = Math.max(box.w, box.h) * FOCUS_PADDING
113
+ let w = Math.max(box.w + pad * 2, FOCUS_MIN_WIDTH * geo.width)
114
+ let h = Math.max(box.h + pad * 2, FOCUS_MIN_WIDTH * geo.width)
115
+ if (w / h < aspect) w = h * aspect
116
+ else h = w / aspect
117
+ w = Math.min(w, geo.width)
118
+ h = Math.min(h, geo.height)
119
+ const x = Math.max(0, Math.min(box.x + box.w / 2 - w / 2, geo.width - w))
120
+ const y = Math.max(0, Math.min(box.y + box.h / 2 - h / 2, geo.height - h))
121
+ return `${round(x)} ${round(y)} ${round(w)} ${round(h)}`
122
+ }
123
+
124
+ /** The geometry drawn for these places, framed on `focusRegion` when it names one. */
125
+ export function drawMap(geo: Geo, places: Place[], focusRegion: string | null): DrawnMap {
126
+ const byKey = new Map(places.map((p) => [regionKey(p.name), p]))
127
+ const named = focusRegion ? keyIn(geo, focusRegion) : null
128
+ const framed = named ? frame(geo, named) : null
129
+ const focusKey = framed ? named : null
130
+ const underlay = new Set(geo.underlay)
131
+ const keys = [...geo.underlay, ...Object.keys(geo.paths).filter((key) => !underlay.has(key) && key !== focusKey), ...(focusKey && !underlay.has(focusKey) ? [focusKey] : [])]
132
+ const regions = keys.map((key): DrawnRegion => {
133
+ const place = byKey.get(regionKey(key))
134
+ const status = place?.status ?? 'dark'
135
+ return { key, label: geo.labels[key] ?? key, d: geo.paths[key]!, status, link: status === 'lit' ? (place?.link ?? null) : null, focus: key === focusKey }
136
+ })
137
+ return { viewBox: framed ?? `0 0 ${geo.width} ${geo.height}`, regions, focus: regions.find((r) => r.focus) ?? null }
138
+ }
139
+
140
+ export interface MapLabels {
141
+ lit: string
142
+ starting: string
143
+ dark: string
144
+ }
145
+
146
+ /** The section's words for each status, else the template's. */
147
+ export function mapLabels(section: Section): MapLabels {
148
+ return {
149
+ lit: text(section.copy.litLabel) ?? 'Organized',
150
+ starting: text(section.copy.startingLabel) ?? 'Getting started',
151
+ dark: text(section.copy.darkLabel) ?? 'Still open',
152
+ }
153
+ }
154
+
155
+ /** "county" → "counties", "district" → "districts" (BackGold's pluralizeRegionNoun). */
156
+ function pluralNoun(noun: string): string {
157
+ return /[^aeiou]y$/i.test(noun) ? `${noun.slice(0, -1)}ies` : `${noun}s`
158
+ }
159
+
160
+ /** "county"/"counties" for `n`; "place"/"places" when the section names no noun. */
161
+ export function nounFor(section: Section, n: number): string {
162
+ const noun = text(section.options?.regionNoun)?.trim() ?? 'place'
163
+ return n === 1 ? noun : pluralNoun(noun)
164
+ }
165
+
166
+ export interface Coverage {
167
+ /** "8 of 254 counties", "2 of 4", or a framed map's "Cedar county". */
168
+ count: string
169
+ /** The status label the count is of. */
170
+ label: string
171
+ }
172
+
173
+ /** The lit rows, and the set they are a share of: `regionTotal` when a positive number, else the rows. */
174
+ export function coverageShare(section: Section, places: Place[]): { lit: number; total: number } {
175
+ const lit = places.filter((p) => p.status === 'lit').length
176
+ const regionTotal = section.options?.regionTotal
177
+ const total = typeof regionTotal === 'number' && regionTotal > 0 ? Math.trunc(regionTotal) : places.length
178
+ return { lit, total }
179
+ }
180
+
181
+ /** The coverage line a whole map carries, counted against the set ("8 of 254 counties" · "Organized"). */
182
+ export function coverageOf(section: Section, places: Place[], labels: MapLabels): Coverage {
183
+ const noun = text(section.options?.regionNoun)?.trim() ?? null
184
+ const { lit, total } = coverageShare(section, places)
185
+ return { count: `${lit} of ${total}${noun ? ` ${nounFor(section, total)}` : ''}`, label: labels.lit }
186
+ }
187
+
188
+ /** The coverage line (see above); `drawn` is null over the tiles. */
189
+ export function coverage(section: Section, drawn: DrawnMap | null, places: Place[], labels: MapLabels): Coverage {
190
+ const noun = text(section.options?.regionNoun)?.trim() ?? null
191
+ if (drawn?.focus) return { count: `${drawn.focus.label}${noun ? ` ${noun}` : ''}`, label: labels[drawn.focus.status] }
192
+ if (!drawn) return { count: `${coverageShare(section, places).lit} of ${places.length}`, label: labels.lit }
193
+ return coverageOf(section, places, labels)
194
+ }
195
+
196
+ export interface Invitation {
197
+ /** "239 counties", "1 place". */
198
+ count: string
199
+ /** The section's darkLabel, else the template's ("Still open"). */
200
+ label: string
201
+ /** The section's charter link, drawn as the invitation's button. */
202
+ charter: Link | null
203
+ }
204
+
205
+ /** The invitation the dark places on a map collapse into; null when the map draws none dark. */
206
+ export function invitation(section: Section, drawn: DrawnMap, links: Link[], labels: MapLabels): Invitation | null {
207
+ const dark = drawn.regions.filter((r) => r.status === 'dark').length
208
+ if (dark === 0) return null
209
+ const charterText = text(section.copy.charterCtaText)
210
+ return {
211
+ count: `${dark} ${nounFor(section, dark)}`,
212
+ label: labels.dark,
213
+ charter: (charterText && links.find((link) => link.label === charterText)) || null,
214
+ }
215
+ }