@uvalib/web-components 1.1.1 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (252) hide show
  1. package/CHANGELOG.md +140 -0
  2. package/README.md +1310 -80
  3. package/dist/analytics.d.ts +10 -0
  4. package/dist/analytics.js +9 -0
  5. package/dist/analytics.js.map +1 -0
  6. package/dist/base/UvalibElement.js +8 -5
  7. package/dist/base/UvalibElement.js.map +1 -1
  8. package/dist/base/analytics-state.d.ts +7 -0
  9. package/dist/base/analytics-state.js.map +1 -1
  10. package/dist/base/light-dom-styles.d.ts +13 -0
  11. package/dist/base/light-dom-styles.js +26 -0
  12. package/dist/base/light-dom-styles.js.map +1 -1
  13. package/dist/base/search-tracker.d.ts +57 -0
  14. package/dist/base/search-tracker.js +51 -0
  15. package/dist/base/search-tracker.js.map +1 -0
  16. package/dist/base/url-param.d.ts +23 -0
  17. package/dist/base/url-param.js +49 -0
  18. package/dist/base/url-param.js.map +1 -0
  19. package/dist/base.css +562 -2
  20. package/dist/base.d.ts +2 -0
  21. package/dist/base.js +1 -0
  22. package/dist/base.js.map +1 -1
  23. package/dist/components/site-analytics/SiteAnalytics.d.ts +20 -1
  24. package/dist/components/site-analytics/SiteAnalytics.js +93 -12
  25. package/dist/components/site-analytics/SiteAnalytics.js.map +1 -1
  26. package/dist/components/site-page/SitePage.d.ts +23 -0
  27. package/dist/components/site-page/SitePage.js +77 -0
  28. package/dist/components/site-page/SitePage.js.map +1 -1
  29. package/dist/components/uvalib-back-to-top/UvalibBackToTop.d.ts +58 -0
  30. package/dist/components/uvalib-back-to-top/UvalibBackToTop.js +250 -0
  31. package/dist/components/uvalib-back-to-top/UvalibBackToTop.js.map +1 -0
  32. package/dist/components/uvalib-back-to-top/uvalib-back-to-top.d.ts +1 -0
  33. package/dist/components/uvalib-back-to-top/uvalib-back-to-top.js +4 -0
  34. package/dist/components/uvalib-back-to-top/uvalib-back-to-top.js.map +1 -0
  35. package/dist/components/uvalib-breadcrumbs/UvalibBreadcrumbs.d.ts +14 -0
  36. package/dist/components/uvalib-breadcrumbs/UvalibBreadcrumbs.js +56 -4
  37. package/dist/components/uvalib-breadcrumbs/UvalibBreadcrumbs.js.map +1 -1
  38. package/dist/components/uvalib-card/UvalibCard.d.ts +19 -5
  39. package/dist/components/uvalib-card/UvalibCard.js +112 -9
  40. package/dist/components/uvalib-card/UvalibCard.js.map +1 -1
  41. package/dist/components/uvalib-chip-group/UvalibChipGroup.d.ts +178 -0
  42. package/dist/components/uvalib-chip-group/UvalibChipGroup.js +817 -0
  43. package/dist/components/uvalib-chip-group/UvalibChipGroup.js.map +1 -0
  44. package/dist/components/uvalib-chip-group/uvalib-chip-group.d.ts +1 -0
  45. package/dist/components/uvalib-chip-group/uvalib-chip-group.js +4 -0
  46. package/dist/components/uvalib-chip-group/uvalib-chip-group.js.map +1 -0
  47. package/dist/components/uvalib-combobox/UvalibCombobox.d.ts +212 -0
  48. package/dist/components/uvalib-combobox/UvalibCombobox.js +1088 -0
  49. package/dist/components/uvalib-combobox/UvalibCombobox.js.map +1 -0
  50. package/dist/components/uvalib-combobox/uvalib-combobox.d.ts +1 -0
  51. package/dist/components/uvalib-combobox/uvalib-combobox.js +4 -0
  52. package/dist/components/uvalib-combobox/uvalib-combobox.js.map +1 -0
  53. package/dist/components/uvalib-contents/UvalibContents.d.ts +53 -0
  54. package/dist/components/uvalib-contents/UvalibContents.js +202 -3
  55. package/dist/components/uvalib-contents/UvalibContents.js.map +1 -1
  56. package/dist/components/uvalib-date-histogram/UvalibDateHistogram.d.ts +187 -0
  57. package/dist/components/uvalib-date-histogram/UvalibDateHistogram.js +1452 -0
  58. package/dist/components/uvalib-date-histogram/UvalibDateHistogram.js.map +1 -0
  59. package/dist/components/uvalib-date-histogram/uvalib-date-histogram.d.ts +1 -0
  60. package/dist/components/uvalib-date-histogram/uvalib-date-histogram.js +4 -0
  61. package/dist/components/uvalib-date-histogram/uvalib-date-histogram.js.map +1 -0
  62. package/dist/components/uvalib-date-range/UvalibDateRange.d.ts +6 -0
  63. package/dist/components/uvalib-date-range/UvalibDateRange.js +23 -0
  64. package/dist/components/uvalib-date-range/UvalibDateRange.js.map +1 -1
  65. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.d.ts +113 -0
  66. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.js +589 -0
  67. package/dist/components/uvalib-filter-drawer/UvalibFilterDrawer.js.map +1 -0
  68. package/dist/components/uvalib-filter-drawer/uvalib-filter-drawer.d.ts +1 -0
  69. package/dist/components/uvalib-filter-drawer/uvalib-filter-drawer.js +4 -0
  70. package/dist/components/uvalib-filter-drawer/uvalib-filter-drawer.js.map +1 -0
  71. package/dist/components/uvalib-image-regions/UvalibImageRegions.d.ts +130 -0
  72. package/dist/components/uvalib-image-regions/UvalibImageRegions.js +658 -0
  73. package/dist/components/uvalib-image-regions/UvalibImageRegions.js.map +1 -0
  74. package/dist/components/uvalib-image-regions/regions.d.ts +57 -0
  75. package/dist/components/uvalib-image-regions/regions.js +117 -0
  76. package/dist/components/uvalib-image-regions/regions.js.map +1 -0
  77. package/dist/components/uvalib-image-regions/uvalib-image-regions.d.ts +1 -0
  78. package/dist/components/uvalib-image-regions/uvalib-image-regions.js +4 -0
  79. package/dist/components/uvalib-image-regions/uvalib-image-regions.js.map +1 -0
  80. package/dist/components/uvalib-lightbox/UvalibLightbox.d.ts +40 -0
  81. package/dist/components/uvalib-lightbox/UvalibLightbox.js +152 -17
  82. package/dist/components/uvalib-lightbox/UvalibLightbox.js.map +1 -1
  83. package/dist/components/uvalib-lightbox/media.d.ts +1 -18
  84. package/dist/components/uvalib-lightbox/media.js +1 -42
  85. package/dist/components/uvalib-lightbox/media.js.map +1 -1
  86. package/dist/components/uvalib-map/UvalibMap.d.ts +182 -0
  87. package/dist/components/uvalib-map/UvalibMap.js +1001 -0
  88. package/dist/components/uvalib-map/UvalibMap.js.map +1 -0
  89. package/dist/components/uvalib-map/uvalib-map.d.ts +1 -0
  90. package/dist/components/uvalib-map/uvalib-map.js +4 -0
  91. package/dist/components/uvalib-map/uvalib-map.js.map +1 -0
  92. package/dist/components/uvalib-metadata/UvalibMetadata.d.ts +39 -2
  93. package/dist/components/uvalib-metadata/UvalibMetadata.js +214 -8
  94. package/dist/components/uvalib-metadata/UvalibMetadata.js.map +1 -1
  95. package/dist/components/uvalib-pager/UvalibPager.d.ts +77 -4
  96. package/dist/components/uvalib-pager/UvalibPager.js +270 -8
  97. package/dist/components/uvalib-pager/UvalibPager.js.map +1 -1
  98. package/dist/components/uvalib-photo-grid/UvalibPhotoGrid.d.ts +27 -1
  99. package/dist/components/uvalib-photo-grid/UvalibPhotoGrid.js +192 -26
  100. package/dist/components/uvalib-photo-grid/UvalibPhotoGrid.js.map +1 -1
  101. package/dist/components/uvalib-results-count/UvalibResultsCount.d.ts +62 -0
  102. package/dist/components/uvalib-results-count/UvalibResultsCount.js +208 -0
  103. package/dist/components/uvalib-results-count/UvalibResultsCount.js.map +1 -0
  104. package/dist/components/uvalib-results-count/uvalib-results-count.d.ts +1 -0
  105. package/dist/components/uvalib-results-count/uvalib-results-count.js +4 -0
  106. package/dist/components/uvalib-results-count/uvalib-results-count.js.map +1 -0
  107. package/dist/components/uvalib-tabs/UvalibTabs.d.ts +127 -0
  108. package/dist/components/uvalib-tabs/UvalibTabs.js +821 -0
  109. package/dist/components/uvalib-tabs/UvalibTabs.js.map +1 -0
  110. package/dist/components/uvalib-tabs/uvalib-tabs.d.ts +1 -0
  111. package/dist/components/uvalib-tabs/uvalib-tabs.js +4 -0
  112. package/dist/components/uvalib-tabs/uvalib-tabs.js.map +1 -0
  113. package/dist/components/uvalib-tag-list/UvalibTagList.d.ts +89 -0
  114. package/dist/components/uvalib-tag-list/UvalibTagList.js +411 -0
  115. package/dist/components/uvalib-tag-list/UvalibTagList.js.map +1 -0
  116. package/dist/components/uvalib-tag-list/uvalib-tag-list.d.ts +1 -0
  117. package/dist/components/uvalib-tag-list/uvalib-tag-list.js +4 -0
  118. package/dist/components/uvalib-tag-list/uvalib-tag-list.js.map +1 -0
  119. package/dist/custom-elements.json +14007 -3497
  120. package/dist/index.d.ts +16 -0
  121. package/dist/index.js +10 -0
  122. package/dist/index.js.map +1 -1
  123. package/dist/pagefind.css +4 -0
  124. package/dist/styles/base.js +154 -1
  125. package/dist/styles/base.js.map +1 -1
  126. package/dist/styles/color-scheme.js +9 -0
  127. package/dist/styles/color-scheme.js.map +1 -1
  128. package/dist/styles/controls.js +8 -0
  129. package/dist/styles/controls.js.map +1 -1
  130. package/dist/styles/hidden.d.ts +2 -0
  131. package/dist/styles/hidden.js +51 -0
  132. package/dist/styles/hidden.js.map +1 -0
  133. package/dist/styles/message.d.ts +1 -0
  134. package/dist/styles/message.js +82 -0
  135. package/dist/styles/message.js.map +1 -0
  136. package/dist/styles/pagefind.js +4 -0
  137. package/dist/styles/pagefind.js.map +1 -1
  138. package/dist/styles/result-list.d.ts +1 -0
  139. package/dist/styles/result-list.js +111 -0
  140. package/dist/styles/result-list.js.map +1 -0
  141. package/dist/styles/results.d.ts +1 -0
  142. package/dist/styles/results.js +242 -0
  143. package/dist/styles/results.js.map +1 -0
  144. package/dist/testing/index.d.ts +110 -0
  145. package/dist/testing/index.js +100 -0
  146. package/dist/testing/index.js.map +1 -0
  147. package/dist/testing/lighthouse-rules.d.ts +10 -0
  148. package/dist/testing/lighthouse-rules.js +44 -0
  149. package/dist/testing/lighthouse-rules.js.map +1 -0
  150. package/dist/tokens.css +9 -0
  151. package/dist-cdn/analytics.js +32 -0
  152. package/dist-cdn/analytics.js.map +1 -0
  153. package/dist-cdn/base.css +562 -2
  154. package/dist-cdn/bento-box.js +3 -3
  155. package/dist-cdn/chunks/{SiteAnalytics-Cm-FyhYS.js → SiteAnalytics-B9gu5aGO.js} +59 -30
  156. package/dist-cdn/chunks/SiteAnalytics-B9gu5aGO.js.map +1 -0
  157. package/dist-cdn/chunks/{UvalibElement-BnI-eRRR.js → UvalibElement-pGONDAwB.js} +108 -101
  158. package/dist-cdn/chunks/UvalibElement-pGONDAwB.js.map +1 -0
  159. package/dist-cdn/chunks/{accessible-GqhVn5_H.js → accessible-DJv7YOtS.js} +2 -2
  160. package/dist-cdn/chunks/{accessible-GqhVn5_H.js.map → accessible-DJv7YOtS.js.map} +1 -1
  161. package/dist-cdn/chunks/analytics-state-Ce8DKe4F.js.map +1 -1
  162. package/dist-cdn/chunks/base-BI8h0Gf3.js +281 -0
  163. package/dist-cdn/chunks/base-BI8h0Gf3.js.map +1 -0
  164. package/dist-cdn/chunks/inline-copy-BANQSMIR.js +69 -0
  165. package/dist-cdn/chunks/inline-copy-BANQSMIR.js.map +1 -0
  166. package/dist-cdn/chunks/{library-weekly-hours-COE7Vv6V.js → library-weekly-hours-CrV3TlP5.js} +3 -3
  167. package/dist-cdn/chunks/{library-weekly-hours-COE7Vv6V.js.map → library-weekly-hours-CrV3TlP5.js.map} +1 -1
  168. package/dist-cdn/chunks/regions-B8ExwUGP.js +86 -0
  169. package/dist-cdn/chunks/regions-B8ExwUGP.js.map +1 -0
  170. package/dist-cdn/chunks/{repeat-CIFUYkyh.js → repeat-m5Zd_QeP.js} +2 -2
  171. package/dist-cdn/chunks/{repeat-CIFUYkyh.js.map → repeat-m5Zd_QeP.js.map} +1 -1
  172. package/dist-cdn/chunks/{site-header-C9V7Wuw2.js → site-header-DYRMpdBj.js} +13 -4
  173. package/dist-cdn/chunks/site-header-DYRMpdBj.js.map +1 -0
  174. package/dist-cdn/chunks/{site-main-nav-AaxZ9rQf.js → site-main-nav-DURrQMal.js} +3 -3
  175. package/dist-cdn/chunks/{site-main-nav-AaxZ9rQf.js.map → site-main-nav-DURrQMal.js.map} +1 -1
  176. package/dist-cdn/chunks/source-children-BHsDwCvL.js +53 -0
  177. package/dist-cdn/chunks/source-children-BHsDwCvL.js.map +1 -0
  178. package/dist-cdn/chunks/{static-html-1mTAG6nS.js → static-html-C1rhtCHu.js} +2 -2
  179. package/dist-cdn/chunks/{static-html-1mTAG6nS.js.map → static-html-C1rhtCHu.js.map} +1 -1
  180. package/dist-cdn/chunks/url-param-C1sk_F1d.js +28 -0
  181. package/dist-cdn/chunks/url-param-C1sk_F1d.js.map +1 -0
  182. package/dist-cdn/custom-elements.json +14007 -3497
  183. package/dist-cdn/events-section.js +3 -3
  184. package/dist-cdn/library-hours-setup.js +2 -2
  185. package/dist-cdn/library-weekly-hours.js +1 -1
  186. package/dist-cdn/manifest.json +15 -2
  187. package/dist-cdn/pagefind.css +4 -0
  188. package/dist-cdn/site-alerts.js +4 -4
  189. package/dist-cdn/site-analytics.js +2 -2
  190. package/dist-cdn/site-footer.js +2 -2
  191. package/dist-cdn/site-header.js +1 -1
  192. package/dist-cdn/site-hours-section.js +4 -4
  193. package/dist-cdn/site-main-nav.js +1 -1
  194. package/dist-cdn/site-page.js +56 -11
  195. package/dist-cdn/site-page.js.map +1 -1
  196. package/dist-cdn/site-style.js +2 -2
  197. package/dist-cdn/skills/uvalib-web-components/SKILL.md +269 -24
  198. package/dist-cdn/skills/uvalib-web-components/reference/accessibility-testing.md +34 -2
  199. package/dist-cdn/skills/uvalib-web-components/reference/components.md +514 -13
  200. package/dist-cdn/skills/uvalib-web-components/reference/snippets.md +1 -1
  201. package/dist-cdn/tokens.css +9 -0
  202. package/dist-cdn/uvalib-analytics.js +2 -2
  203. package/dist-cdn/uvalib-back-to-top.js +156 -0
  204. package/dist-cdn/uvalib-back-to-top.js.map +1 -0
  205. package/dist-cdn/uvalib-breadcrumbs.js +31 -11
  206. package/dist-cdn/uvalib-breadcrumbs.js.map +1 -1
  207. package/dist-cdn/uvalib-card-grid.js +1 -1
  208. package/dist-cdn/uvalib-card.js +97 -23
  209. package/dist-cdn/uvalib-card.js.map +1 -1
  210. package/dist-cdn/uvalib-chip-group.js +535 -0
  211. package/dist-cdn/uvalib-chip-group.js.map +1 -0
  212. package/dist-cdn/uvalib-combobox.js +667 -0
  213. package/dist-cdn/uvalib-combobox.js.map +1 -0
  214. package/dist-cdn/uvalib-contents.js +102 -23
  215. package/dist-cdn/uvalib-contents.js.map +1 -1
  216. package/dist-cdn/uvalib-date-histogram.js +960 -0
  217. package/dist-cdn/uvalib-date-histogram.js.map +1 -0
  218. package/dist-cdn/uvalib-date-range.js +14 -2
  219. package/dist-cdn/uvalib-date-range.js.map +1 -1
  220. package/dist-cdn/uvalib-filter-drawer.js +355 -0
  221. package/dist-cdn/uvalib-filter-drawer.js.map +1 -0
  222. package/dist-cdn/uvalib-filter.js +3 -3
  223. package/dist-cdn/uvalib-image-regions.js +447 -0
  224. package/dist-cdn/uvalib-image-regions.js.map +1 -0
  225. package/dist-cdn/uvalib-lightbox.js +145 -78
  226. package/dist-cdn/uvalib-lightbox.js.map +1 -1
  227. package/dist-cdn/uvalib-map.js +471 -0
  228. package/dist-cdn/uvalib-map.js.map +1 -0
  229. package/dist-cdn/uvalib-metadata.js +152 -25
  230. package/dist-cdn/uvalib-metadata.js.map +1 -1
  231. package/dist-cdn/uvalib-pager.js +164 -18
  232. package/dist-cdn/uvalib-pager.js.map +1 -1
  233. package/dist-cdn/uvalib-photo-grid.js +123 -21
  234. package/dist-cdn/uvalib-photo-grid.js.map +1 -1
  235. package/dist-cdn/uvalib-results-count.js +101 -0
  236. package/dist-cdn/uvalib-results-count.js.map +1 -0
  237. package/dist-cdn/uvalib-tabs.js +436 -0
  238. package/dist-cdn/uvalib-tabs.js.map +1 -0
  239. package/dist-cdn/uvalib-tag-list.js +267 -0
  240. package/dist-cdn/uvalib-tag-list.js.map +1 -0
  241. package/package.json +66 -3
  242. package/skills/uvalib-web-components/SKILL.md +269 -24
  243. package/skills/uvalib-web-components/reference/accessibility-testing.md +34 -2
  244. package/skills/uvalib-web-components/reference/components.md +514 -13
  245. package/skills/uvalib-web-components/reference/snippets.md +1 -1
  246. package/dist-cdn/chunks/SiteAnalytics-Cm-FyhYS.js.map +0 -1
  247. package/dist-cdn/chunks/UvalibElement-BnI-eRRR.js.map +0 -1
  248. package/dist-cdn/chunks/base-CAFQWnZG.js +0 -128
  249. package/dist-cdn/chunks/base-CAFQWnZG.js.map +0 -1
  250. package/dist-cdn/chunks/site-header-C9V7Wuw2.js.map +0 -1
  251. package/dist-cdn/chunks/source-children-RuAec527.js +0 -119
  252. package/dist-cdn/chunks/source-children-RuAec527.js.map +0 -1
@@ -0,0 +1,1452 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ import { html, nothing, unsafeCSS } from 'lit';
8
+ import { property, state } from 'lit/decorators.js';
9
+ import { repeat } from 'lit/directives/repeat.js';
10
+ import { trackEvent } from '../../base/analytics.js';
11
+ import { installLightDomStyles } from '../../base/light-dom-styles.js';
12
+ import { SourceChildren } from '../../base/source-children.js';
13
+ import { UvalibElement } from '../../base/UvalibElement.js';
14
+ import { accessible } from '../../styles/accessible.js';
15
+ /** The analytics category. */
16
+ const TAG = 'uvalib-date-histogram';
17
+ const MONTHS = [
18
+ 'January',
19
+ 'February',
20
+ 'March',
21
+ 'April',
22
+ 'May',
23
+ 'June',
24
+ 'July',
25
+ 'August',
26
+ 'September',
27
+ 'October',
28
+ 'November',
29
+ 'December',
30
+ ];
31
+ const SHORT_MONTHS = MONTHS.map((m) => m.slice(0, 3));
32
+ /** Element ids share the document id space in light DOM, so each instance gets its own prefix. */
33
+ let instanceCounter = 0;
34
+ const ISO_DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
35
+ /** True for a real calendar date `YYYY-MM-DD`. Parsed in UTC so a time zone cannot shift the year. */
36
+ function isIsoDate(s) {
37
+ const m = typeof s === 'string' ? ISO_DAY.exec(s) : null;
38
+ if (!m)
39
+ return false;
40
+ const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
41
+ const date = new Date(Date.UTC(y, mo - 1, d));
42
+ date.setUTCFullYear(y);
43
+ return date.getUTCFullYear() === y && date.getUTCMonth() === mo - 1 && date.getUTCDate() === d;
44
+ }
45
+ /** Last calendar day of `month` (1–12), as `YYYY-MM-DD`. */
46
+ function lastDay(year, month) {
47
+ const d = new Date(Date.UTC(year, month, 0)).getUTCDate();
48
+ return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
49
+ }
50
+ function monthIndex(token) {
51
+ const t = token.toLowerCase();
52
+ const full = MONTHS.findIndex((m) => m.toLowerCase() === t);
53
+ if (full >= 0)
54
+ return full + 1;
55
+ const brief = SHORT_MONTHS.findIndex((m) => m.toLowerCase() === t);
56
+ if (brief >= 0)
57
+ return brief + 1;
58
+ const n = Number(t);
59
+ return Number.isInteger(n) && n >= 1 && n <= 12 ? n : 0;
60
+ }
61
+ /** A decade key, `1810s`. */
62
+ const DECADE = /^(\d{3}0)s$/;
63
+ const decadeKey = (year) => `${String(Math.floor(year / 10) * 10).padStart(4, '0')}s`;
64
+ /** The `selected` value a decade bar sets: its first and last year (`1810/1819`). */
65
+ function decadeSelection(key) {
66
+ const d = Number(key.slice(0, 4));
67
+ return `${key.slice(0, 4)}/${String(d + 9).padStart(4, '0')}`;
68
+ }
69
+ /**
70
+ * `granularity="auto"`: month bars when every dated count is a month and they span at most
71
+ * 3 years (36 bars), year bars up to 30 years, decades beyond.
72
+ */
73
+ const AUTO_MONTH_YEARS = 3;
74
+ const AUTO_YEAR_YEARS = 30;
75
+ /** `YYYY`, `YYYY-MM` and `YYYYs` (a decade) are buckets. A day, a month name or anything else is an odd date. */
76
+ function parseDate(raw) {
77
+ const s = raw.replace(/\s+/g, ' ').trim();
78
+ if (!s)
79
+ return null;
80
+ if (DECADE.test(s))
81
+ return { key: s, kind: 'decade' };
82
+ if (ISO_DAY.test(s))
83
+ return { key: isIsoDate(s) ? s : s, kind: 'odd' };
84
+ const month = /^(\d{4})-(\d{2})$/.exec(s);
85
+ if (month) {
86
+ const mo = Number(month[2]);
87
+ return mo >= 1 && mo <= 12
88
+ ? { key: `${month[1]}-${month[2]}`, kind: 'month' }
89
+ : { key: s, kind: 'odd' };
90
+ }
91
+ if (/^\d{4}$/.test(s))
92
+ return { key: s, kind: 'year' };
93
+ const named = /^([A-Za-z]+)\s+(\d{4})$/.exec(s) ?? /^(\d{4})\s+([A-Za-z]+)$/.exec(s);
94
+ if (named) {
95
+ const year = /^\d{4}$/.test(named[1]) ? named[1] : named[2];
96
+ const word = year === named[1] ? named[2] : named[1];
97
+ const mo = monthIndex(word);
98
+ if (mo)
99
+ return { key: `${year}-${String(mo).padStart(2, '0')}`, kind: 'month' };
100
+ }
101
+ return { key: s, kind: 'odd' };
102
+ }
103
+ /** Inclusive ISO span of a bucket key, or null when `key` is not a decade, year, month or day. */
104
+ function keyToSpan(key) {
105
+ if (isIsoDate(key))
106
+ return { from: key, to: key };
107
+ const month = /^(\d{4})-(\d{2})$/.exec(key);
108
+ if (month && Number(month[2]) >= 1 && Number(month[2]) <= 12) {
109
+ return { from: `${key}-01`, to: lastDay(Number(month[1]), Number(month[2])) };
110
+ }
111
+ if (/^\d{4}$/.test(key))
112
+ return { from: `${key}-01-01`, to: `${key}-12-31` };
113
+ const decade = DECADE.exec(key);
114
+ if (decade) {
115
+ const last = String(Number(decade[1]) + 9).padStart(4, '0');
116
+ return { from: `${decade[1]}-01-01`, to: `${last}-12-31` };
117
+ }
118
+ return null;
119
+ }
120
+ function splitSelection(raw) {
121
+ return raw
122
+ .trim()
123
+ .split(/\s*(?:\.\.|\/|\u2013|\u2014)\s*/)
124
+ .filter(Boolean);
125
+ }
126
+ /**
127
+ * The inclusive span `selected` covers. A range is split only when every part is a
128
+ * year, month or day. An odd phrase that itself contains `/`, `..` or a dash stays one token.
129
+ */
130
+ function parseSelected(raw) {
131
+ const trimmed = raw.trim();
132
+ if (!trimmed)
133
+ return null;
134
+ const parts = splitSelection(trimmed);
135
+ if (parts.length >= 2 && parts.every((p) => keyToSpan(p) !== null)) {
136
+ const spans = parts.map((p) => keyToSpan(p));
137
+ const from = spans.reduce((a, s) => (s.from < a ? s.from : a), spans[0].from);
138
+ const to = spans.reduce((a, s) => (s.to > a ? s.to : a), spans[0].to);
139
+ return { from, to };
140
+ }
141
+ return keyToSpan(trimmed) ?? { from: trimmed, to: trimmed };
142
+ }
143
+ /** The first year of the half-century a year is in (decade rows are 1800–1849, 1850–1899, …). */
144
+ const halfCentury = (year) => Math.floor(year / 50) * 50;
145
+ /** Years touched by two ISO dates, inclusive. */
146
+ function yearCount(min, max) {
147
+ const a = /^(\d{4})/.exec(min.trim());
148
+ const b = /^(\d{4})/.exec(max.trim());
149
+ if (!a || !b)
150
+ return null;
151
+ return Math.abs(Number(b[1]) - Number(a[1])) + 1;
152
+ }
153
+ function isoToSelected(from, to, grain) {
154
+ if (!isIsoDate(from) || !isIsoDate(to))
155
+ return '';
156
+ const [a, b] = from <= to ? [from, to] : [to, from];
157
+ if (grain === 'year') {
158
+ const ya = a.slice(0, 4);
159
+ const yb = b.slice(0, 4);
160
+ return ya === yb ? ya : `${ya}/${yb}`;
161
+ }
162
+ const ma = a.slice(0, 7);
163
+ const mb = b.slice(0, 7);
164
+ return ma === mb ? ma : `${ma}/${mb}`;
165
+ }
166
+ /** Plural `unit`, with a trailing s dropped for a count of one (`photos` → `photo`). `series` stays. */
167
+ function unitWord(count, unit) {
168
+ const word = unit.trim() || 'items';
169
+ if (count === 1 && /[^s]s$/i.test(word) && !/ies$/i.test(word))
170
+ return word.slice(0, -1);
171
+ return word;
172
+ }
173
+ function bucketName(key, count, unit) {
174
+ const n = count.toLocaleString('en-US');
175
+ const word = unitWord(count, unit);
176
+ const month = /^(\d{4})-(\d{2})$/.exec(key);
177
+ if (month)
178
+ return `${MONTHS[Number(month[2]) - 1]} ${month[1]}: ${n} ${word}`;
179
+ const day = /^(\d{4})-(\d{2})-(\d{2})$/.exec(key);
180
+ if (day && isIsoDate(key))
181
+ return `${Number(day[3])} ${MONTHS[Number(day[2]) - 1]} ${day[1]}: ${n} ${word}`;
182
+ return `${key}: ${n} ${word}`;
183
+ }
184
+ function addOdd(odds, key, count) {
185
+ odds.set(key, (odds.get(key) ?? 0) + count);
186
+ }
187
+ /** Each valid item as a parsed date and a count. */
188
+ function parsedItems(items) {
189
+ const out = [];
190
+ for (const item of items) {
191
+ if (!item || typeof item.date !== 'string')
192
+ continue;
193
+ const count = typeof item.count === 'number' ? item.count : Number(item.count);
194
+ if (!Number.isFinite(count) || count < 0)
195
+ continue;
196
+ const parsed = parseDate(item.date);
197
+ if (parsed)
198
+ out.push({ ...parsed, count });
199
+ }
200
+ return out;
201
+ }
202
+ /** The grain `granularity="auto"` draws. `span` is the years to cover when there are no counts yet. */
203
+ function autoGrain(items, span) {
204
+ const dated = parsedItems(items).filter((p) => p.kind !== 'odd');
205
+ if (!dated.length)
206
+ return span != null && span > AUTO_YEAR_YEARS ? 'decade' : 'year';
207
+ const years = dated.map((p) => Number(p.key.slice(0, 4)));
208
+ const width = Math.max(...years) - Math.min(...years) + 1;
209
+ if (dated.every((p) => p.kind === 'month') && width <= AUTO_MONTH_YEARS)
210
+ return 'month';
211
+ if (dated.some((p) => p.kind === 'decade'))
212
+ return 'decade';
213
+ return width <= AUTO_YEAR_YEARS ? 'year' : 'decade';
214
+ }
215
+ /** Continuous buckets from the earliest date to the latest, with the months, years or decades between filled in. */
216
+ function buildModel(items, grain) {
217
+ const buckets = new Map();
218
+ const odds = new Map();
219
+ for (const parsed of parsedItems(items)) {
220
+ const { count } = parsed;
221
+ if (parsed.kind === 'odd' ||
222
+ (grain === 'month' && parsed.kind === 'year') ||
223
+ (grain !== 'decade' && parsed.kind === 'decade')) {
224
+ addOdd(odds, parsed.key, count);
225
+ continue;
226
+ }
227
+ const key = grain === 'year'
228
+ ? parsed.key.slice(0, 4)
229
+ : grain === 'decade'
230
+ ? decadeKey(Number(parsed.key.slice(0, 4)))
231
+ : parsed.key;
232
+ buckets.set(key, (buckets.get(key) ?? 0) + count);
233
+ }
234
+ const bars = [];
235
+ const keys = [...buckets.keys()].sort();
236
+ if (keys.length) {
237
+ const first = Number(keys[0].slice(0, 4));
238
+ const last = Number(keys[keys.length - 1].slice(0, 4));
239
+ for (let year = first; year <= last; year += grain === 'decade' ? 10 : 1) {
240
+ if (grain === 'decade') {
241
+ const key = decadeKey(year);
242
+ bars.push({ key, count: buckets.get(key) ?? 0, year, month: 0 });
243
+ }
244
+ else if (grain === 'year') {
245
+ const key = String(year);
246
+ bars.push({ key, count: buckets.get(key) ?? 0, year, month: 0 });
247
+ }
248
+ else {
249
+ for (let month = 1; month <= 12; month++) {
250
+ const key = `${year}-${String(month).padStart(2, '0')}`;
251
+ bars.push({ key, count: buckets.get(key) ?? 0, year, month });
252
+ }
253
+ }
254
+ }
255
+ }
256
+ const max = bars.reduce((m, b) => (b.count > m ? b.count : m), 0);
257
+ return {
258
+ bars,
259
+ odds: [...odds.entries()].map(([key, count]) => ({ key, count })),
260
+ max,
261
+ };
262
+ }
263
+ function barPercent(count, max, log) {
264
+ if (count <= 0 || max <= 0)
265
+ return 0;
266
+ if (log)
267
+ return (Math.log1p(count) / Math.log1p(max)) * 100;
268
+ return (count / max) * 100;
269
+ }
270
+ function parseCount(text) {
271
+ if (text == null)
272
+ return null;
273
+ const t = text.replace(/,/g, '').trim();
274
+ if (!t)
275
+ return null;
276
+ // A dash in a count cell is zero, so a boundary year of dashes is still drawn.
277
+ if (t === '\u2014' || t === '-' || t === '\u2013')
278
+ return 0;
279
+ const n = Number(t);
280
+ return Number.isFinite(n) && n >= 0 ? n : null;
281
+ }
282
+ /** A header row has `<th>`, sits in `<thead>`, or its count cell is not a number (a dash is zero, so data). */
283
+ function isHeaderRow(row, countCol) {
284
+ const cells = [...row.cells];
285
+ if (cells.some((c) => c.tagName === 'TH'))
286
+ return true;
287
+ if (row.parentElement?.tagName === 'THEAD')
288
+ return true;
289
+ return parseCount(cells[countCol]?.textContent) == null;
290
+ }
291
+ /** A child `<table>`: two columns (date, count) or a year-by-month grid. */
292
+ function parseTable(table) {
293
+ const rows = [...table.rows];
294
+ if (!rows.length)
295
+ return [];
296
+ const header = [...rows[0].cells].map((c) => (c.textContent ?? '').replace(/\s+/g, ' ').trim());
297
+ const headerMonths = header.map((h) => monthIndex(h));
298
+ // A count of 1–12 in a two-column table is not a month heading. A grid has several columns.
299
+ const matrix = header.length >= 3 && headerMonths.filter((m) => m > 0).length >= 2;
300
+ const items = [];
301
+ if (matrix) {
302
+ for (const row of rows.slice(1)) {
303
+ const cells = [...row.cells];
304
+ const year = (cells[0]?.textContent ?? '').trim();
305
+ if (!/^\d{4}$/.test(year))
306
+ continue;
307
+ headerMonths.forEach((mo, i) => {
308
+ if (!mo)
309
+ return;
310
+ const count = parseCount(cells[i]?.textContent);
311
+ if (count == null)
312
+ return;
313
+ items.push({ date: `${year}-${String(mo).padStart(2, '0')}`, count });
314
+ });
315
+ }
316
+ return items;
317
+ }
318
+ const lower = header.map((h) => h.toLowerCase());
319
+ let dateCol = lower.findIndex((h) => /date|month|year/.test(h));
320
+ let countCol = lower.findIndex((h) => /count|photo|total|number|item/.test(h));
321
+ if (dateCol < 0)
322
+ dateCol = 0;
323
+ if (countCol < 0)
324
+ countCol = dateCol === 0 ? 1 : 0;
325
+ // "undated" matches /date/, so a header is a `<th>` row or a count cell that is not a number.
326
+ const body = isHeaderRow(rows[0], countCol) ? rows.slice(1) : rows;
327
+ for (const row of body) {
328
+ const cells = [...row.cells];
329
+ const date = (cells[dateCol]?.textContent ?? '').replace(/\s+/g, ' ').trim();
330
+ const count = parseCount(cells[countCol]?.textContent);
331
+ if (!date || count == null)
332
+ continue;
333
+ items.push({ date, count });
334
+ }
335
+ return items;
336
+ }
337
+ /**
338
+ * Kept with `no-style`: the bar tracks keep a fixed height (so drawing the bars does not move
339
+ * the page), each bar is at least 24px, a selection is an inset ring rather than a colour,
340
+ * bars keep a border in forced colors, and a wide month row scrolls inside the component.
341
+ * `host` is `:host` or the tag.
342
+ */
343
+ const structuralRules = (host) => {
344
+ const attr = (sel) => (host === ':host' ? `:host(${sel})` : `${host}${sel}`);
345
+ return `
346
+ ${host} { display: block; max-width: 100%; min-width: 0; box-sizing: border-box; }
347
+ ${host} .scroller { overflow-x: auto; max-width: 100%; overscroll-behavior-x: contain; }
348
+ ${host} :is(.by-month, .by-decade) .scroller { scroll-padding-inline-start: 4rem; }
349
+ ${host} .year {
350
+ display: grid;
351
+ grid-template-columns: 3.5rem minmax(0, 1fr);
352
+ column-gap: 0.5rem;
353
+ align-items: end;
354
+ margin: 0 0 0.5rem;
355
+ }
356
+ ${host} .year-label {
357
+ position: sticky;
358
+ inset-inline-start: 0;
359
+ z-index: 1;
360
+ text-align: end;
361
+ font-weight: 600;
362
+ font-variant-numeric: tabular-nums;
363
+ background: var(--uva-color-surface, #fff);
364
+ color: var(--uva-color-text, #2b2b2b);
365
+ }
366
+ ${host} .bars {
367
+ display: grid;
368
+ grid-template-columns: repeat(12, minmax(1.5rem, 1fr));
369
+ gap: 2px;
370
+ block-size: var(--uvalib-date-histogram-bar-size, 8rem);
371
+ min-inline-size: calc(12 * 1.5rem + 11 * 2px);
372
+ }
373
+ ${host} .by-decade .bars {
374
+ grid-template-columns: repeat(5, minmax(1.5rem, 1fr));
375
+ min-inline-size: calc(5 * 1.5rem + 4 * 2px);
376
+ }
377
+ ${host} .bar {
378
+ position: relative;
379
+ box-sizing: border-box;
380
+ display: flex;
381
+ flex-direction: column;
382
+ justify-content: flex-end;
383
+ align-items: stretch;
384
+ min-inline-size: 1.5rem;
385
+ min-block-size: 1.5rem;
386
+ height: 100%;
387
+ margin: 0;
388
+ padding: 0;
389
+ border: 1px solid var(--uva-color-control-border, #808080);
390
+ background: var(--uva-color-track, #e5e7eb);
391
+ font: inherit;
392
+ color: inherit;
393
+ cursor: pointer;
394
+ }
395
+ ${host} .bar::after {
396
+ content: '';
397
+ position: absolute;
398
+ inset: 0;
399
+ z-index: 1;
400
+ pointer-events: none;
401
+ }
402
+ ${host} .fill {
403
+ display: block;
404
+ width: 100%;
405
+ min-height: 0;
406
+ background: var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));
407
+ border: 1px solid var(--uva-color-text, #2b2b2b);
408
+ box-sizing: border-box;
409
+ }
410
+ ${host} .bar.is-empty .fill { background: transparent; border-color: transparent; }
411
+ ${host} .bar[aria-pressed='true']::after {
412
+ box-shadow: inset 0 0 0 3px var(--uva-color-text, #2b2b2b);
413
+ background-image: repeating-linear-gradient(
414
+ -45deg,
415
+ transparent,
416
+ transparent 3px,
417
+ var(--uva-color-on-accent, #fff) 3px,
418
+ var(--uva-color-on-accent, #fff) 4px
419
+ );
420
+ }
421
+ ${host} .by-year .bars {
422
+ display: flex;
423
+ flex-wrap: wrap;
424
+ align-items: flex-end;
425
+ align-content: flex-end;
426
+ min-inline-size: 0;
427
+ block-size: auto;
428
+ min-block-size: var(--uvalib-date-histogram-bar-size, 8rem);
429
+ }
430
+ ${host} .by-year .bar {
431
+ flex: 1 1 1.5rem;
432
+ max-inline-size: 3rem;
433
+ height: auto;
434
+ block-size: var(--uvalib-date-histogram-bar-size, 8rem);
435
+ }
436
+ ${host} .strip {
437
+ display: flex;
438
+ align-items: flex-end;
439
+ gap: 2px;
440
+ block-size: var(--uvalib-date-histogram-strip-size, 1.5rem);
441
+ max-width: 100%;
442
+ }
443
+ ${host} .strip-bar {
444
+ flex: 1 1 0;
445
+ min-inline-size: 0;
446
+ box-sizing: border-box;
447
+ background: var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));
448
+ border: 1px solid var(--uva-color-text, #2b2b2b);
449
+ }
450
+ ${host} .strip-bar.is-empty { background: transparent; }
451
+ ${host} .strip-bar.is-selected {
452
+ box-shadow: inset 0 0 0 2px var(--uva-color-text, #2b2b2b);
453
+ background-image: repeating-linear-gradient(
454
+ -45deg,
455
+ transparent,
456
+ transparent 2px,
457
+ var(--uva-color-on-accent, #fff) 2px,
458
+ var(--uva-color-on-accent, #fff) 3px
459
+ );
460
+ }
461
+ ${host} .outliers { display: flex; flex-wrap: wrap; gap: 0.35rem; margin: 0.5rem 0; }
462
+ ${host} .chip {
463
+ box-sizing: border-box;
464
+ min-block-size: 1.5rem;
465
+ min-inline-size: 1.5rem;
466
+ margin: 0;
467
+ padding: 0.15rem 0.6rem;
468
+ border: 1px solid var(--uva-color-control-border, #808080);
469
+ border-radius: 999px;
470
+ background: var(--uva-color-surface-raised, #fff);
471
+ color: var(--uva-color-text, #2b2b2b);
472
+ font: inherit;
473
+ cursor: pointer;
474
+ }
475
+ ${host} .chip[aria-pressed='true'] {
476
+ box-shadow: inset 0 0 0 2px var(--uva-color-text, #2b2b2b);
477
+ font-weight: 700;
478
+ }
479
+ ${host} .scroll-hint {
480
+ margin: 0 0 0.35rem;
481
+ font-size: 0.875rem;
482
+ color: var(--uva-color-text-muted, #4b5563);
483
+ }
484
+ ${host} .plot { min-block-size: var(--uvalib-date-histogram-bar-size, 8rem); }
485
+ ${host} .empty { margin: 0; color: var(--uva-color-text-muted, #4b5563); }
486
+ ${host} .table-wrap { overflow-x: auto; max-width: 100%; }
487
+ ${host} table { border-collapse: collapse; }
488
+ ${host} th, ${host} td {
489
+ border: 1px solid var(--uva-color-control-border, #808080);
490
+ padding: 0.2rem 0.4rem;
491
+ text-align: end;
492
+ color: var(--uva-color-text, #2b2b2b);
493
+ }
494
+ ${host} th[scope='row'], ${host} caption { text-align: start; }
495
+ ${host} caption { font-weight: 600; }
496
+ ${host} .visually-hidden {
497
+ position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0;
498
+ overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
499
+ }
500
+ ${host} :is(button, summary, [tabindex]):focus-visible {
501
+ outline: 3px solid var(--uva-color-focus, var(--uva-brand-orange, #e57200));
502
+ outline-offset: 2px;
503
+ }
504
+ ${host}[hidden], ${host} [hidden] { display: none !important; }
505
+ ${attr("[variant='strip']")} .chart { min-block-size: var(--uvalib-date-histogram-strip-size, 1.5rem); }
506
+ @media (forced-colors: active) {
507
+ ${host} .bar, ${host} .strip-bar, ${host} .fill, ${host} .chip, ${host} th, ${host} td {
508
+ forced-color-adjust: none;
509
+ border: 1px solid ButtonText;
510
+ background: Canvas;
511
+ color: ButtonText;
512
+ }
513
+ ${host} .fill, ${host} .strip-bar { background: ButtonText; }
514
+ ${host} .bar.is-empty .fill, ${host} .strip-bar.is-empty { background: transparent; }
515
+ ${host} .bar[aria-pressed='true'], ${host} .chip[aria-pressed='true'], ${host} .strip-bar.is-selected {
516
+ outline: 3px solid Highlight;
517
+ outline-offset: -4px;
518
+ }
519
+ ${host} :is(.bar, .chip, summary, [tabindex]):focus-visible {
520
+ outline: 3px solid Highlight;
521
+ outline-offset: 2px;
522
+ }
523
+ }
524
+ `;
525
+ };
526
+ const shadowStructure = unsafeCSS(structuralRules(':host'));
527
+ /** The tag stays on one line so the caption text is the label, not the template's indentation. */
528
+ function tableCaption(text) {
529
+ // prettier-ignore
530
+ return html `<caption>${text}</caption>`;
531
+ }
532
+ /**
533
+ * Monthly, yearly or per-decade counts as bars: a date distribution for a search page, an
534
+ * archive timeline or a card. Give `items` (`{ date, count }`, `date` a `YYYY` or `YYYY-MM`)
535
+ * or a child `<table>` (the no-JS fallback). `granularity="month"` draws twelve bars for every
536
+ * year from the first date to the last, including months with a count of zero. A year-only
537
+ * count in a month chart, a day, or any other date is a chip beside the chart.
538
+ *
539
+ * `granularity="decade"` is for a long span (two centuries of minutes): one bar per decade
540
+ * ("1810s: 22 meetings"), an empty decade a gap, five decades to a row labelled with its
541
+ * first year (1800, 1850, …), the decades lined up in columns. Choosing a decade selects
542
+ * its first to last year (`selected="1810/1819"`, `select` `{ from: '1810-01-01', to:
543
+ * '1819-12-31' }`); up and down arrows move 50 years. `granularity="auto"` draws months
544
+ * when every count is a month within 3 years (at most 36 bars), years up to 30 years, and
545
+ * decades beyond. A year row that scrolls sideways is not offered: 200 years at the 24px
546
+ * minimum bar is over 5,000px, so a sidebar would show ten years at a time and lose the
547
+ * shape that decades show whole.
548
+ *
549
+ * Each bar is a button named like "October 2015: 5,311 photos". Arrow keys move between
550
+ * bars; Enter or Space selects. `selected` is one bucket (`2015-10`, `2015`) or a range
551
+ * (`2015-03/2016-01`, also `..` or an en dash). The selection is `aria-pressed`, an inset
552
+ * ring and a stripe, not colour alone. Choosing a bar fires `select` with `{ from, to }`
553
+ * as ISO dates (a month runs from its first day to its last). Choosing the selected bar
554
+ * again clears it (`from` and `to` are empty strings).
555
+ *
556
+ * `range-for` is the id of a `<uvalib-date-range>`. A bar click sets that element's
557
+ * `value`. Whenever the range's value changes, from its controls or set in script (a Clear
558
+ * button, Back/Forward, a restored URL), this element highlights the buckets that overlap it
559
+ * (it listens for `uvalib-date-range-value`). A value that is exactly the range's own `min`
560
+ * and `max` is no selection. On connect or reconnect, or when the range is added later, the
561
+ * range's value wins when it holds a selection or changed while this element was away;
562
+ * otherwise `selected` is written to it. A range value is never rounded to whole buckets
563
+ * and written back. Setting `selected` here updates the date range.
564
+ *
565
+ * `variant="strip"` is the small per-year row for a card: not interactive, `role="img"`,
566
+ * one bar per year, or per decade with `decade` (or `auto` over more than 30 years).
567
+ *
568
+ * The chart reserves its height before the counts arrive: one bar track, or one track
569
+ * per year (per half-century for decades) when those years are already known from the
570
+ * data, a linked date range or the table (`--uvalib-date-histogram-bar-size`, 8rem, plus
571
+ * the row gap). Filling the bars in does not move the page. On a narrow screen a month row
572
+ * scrolls inside the component; "Scroll sideways to see more." shows while it overflows.
573
+ * Years wrap; a decade row fits 320px.
574
+ *
575
+ * @tagname uvalib-date-histogram
576
+ * @slot - A `<table>` of dates and counts: two columns (date, count) or a year-by-month grid. Without JavaScript it is the fallback. With JavaScript it supplies the counts when `items` is empty. Show as table lists those counts, including odd dates; once `items` is set it lists `items` instead.
577
+ * @fires select - A bar or an odd-date chip was chosen, or the current one chosen again to clear it. `detail` is `{ from, to }` (ISO dates, or the odd token). Empty strings clear the selection. Not fired when `selected` is set in script or when a linked date range changes. Bubbles and is composed.
578
+ * @fires uvalib-analytics-event - For `<site-analytics>`: `['uvalib-date-histogram', 'select', '<from>–<to>']` when both ends are ISO dates, or `'other'` for any other choice. Not fired when the selection is cleared, set in script, or restored from a date range. Bubbles and is composed.
579
+ * @csspart chart - The bar chart (shadow mode).
580
+ * @csspart bar - A bar button, or a strip segment (shadow mode).
581
+ * @csspart table - The generated table in Show as table (shadow mode).
582
+ * @cssprop [--uvalib-date-histogram-bar-size=8rem] - Height of each bar track. The chart reserves one track, or one per known year, before the counts arrive.
583
+ * @cssprop [--uvalib-date-histogram-strip-size=1.5rem] - Height of `variant="strip"`.
584
+ * @cssprop [--uva-brand-blue=#232d4b] - Bar fill.
585
+ * @cssprop [--uva-brand-orange=#e57200] - Focus ring when `--uva-color-focus` is unset.
586
+ * @cssprop [--uva-font-family=inherit] - Font family.
587
+ * @cssprop --uva-color-accent-bg - Dark-mode role token: bar fill (else `--uva-brand-blue`).
588
+ * @cssprop --uva-color-on-accent - Dark-mode role token: the selection stripe (else #fff).
589
+ * @cssprop --uva-color-text - Dark-mode role token: labels and the selection ring (else #2b2b2b).
590
+ * @cssprop --uva-color-text-muted - Dark-mode role token: the scroll hint (else #4b5563).
591
+ * @cssprop --uva-color-track - Dark-mode role token: the empty part of a bar (else #e5e7eb).
592
+ * @cssprop --uva-color-surface - Dark-mode role token: the sticky year label (else #fff).
593
+ * @cssprop --uva-color-surface-raised - Dark-mode role token: odd-date chips (else #fff).
594
+ * @cssprop --uva-color-control-border - Dark-mode role token: bar, chip and table borders (else #808080).
595
+ * @cssprop --uva-color-focus - Dark-mode role token: focus ring (else `--uva-brand-orange`).
596
+ */
597
+ export class UvalibDateHistogram extends UvalibElement {
598
+ static { this.styles = [
599
+ accessible,
600
+ shadowStructure,
601
+ unsafeCSS(`
602
+ :host { font-family: var(--uva-font-family, inherit); }
603
+ .year-label { background: var(--uva-color-surface, #fff); color: var(--uva-color-text, #2b2b2b); }
604
+ .bar {
605
+ border-color: var(--uva-color-control-border, #808080);
606
+ background: var(--uva-color-track, #e5e7eb);
607
+ }
608
+ .fill {
609
+ background: var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b));
610
+ border-color: var(--uva-color-text, #2b2b2b);
611
+ transition: height 0.2s ease;
612
+ }
613
+ .bar[aria-pressed='true']::after {
614
+ box-shadow: inset 0 0 0 3px var(--uva-color-text, #2b2b2b);
615
+ background-image: repeating-linear-gradient(
616
+ -45deg,
617
+ transparent,
618
+ transparent 3px,
619
+ var(--uva-color-on-accent, #fff) 3px,
620
+ var(--uva-color-on-accent, #fff) 4px
621
+ );
622
+ }
623
+ .strip-bar { background: var(--uva-color-accent-bg, var(--uva-brand-blue, #232d4b)); border-color: var(--uva-color-text, #2b2b2b); }
624
+ .strip-bar.is-selected {
625
+ box-shadow: inset 0 0 0 2px var(--uva-color-text, #2b2b2b);
626
+ background-image: repeating-linear-gradient(-45deg, transparent, transparent 2px, var(--uva-color-on-accent, #fff) 2px, var(--uva-color-on-accent, #fff) 3px);
627
+ }
628
+ .chip {
629
+ background: var(--uva-color-surface-raised, #fff);
630
+ color: var(--uva-color-text, #2b2b2b);
631
+ border-color: var(--uva-color-control-border, #808080);
632
+ }
633
+ .chip[aria-pressed='true'] { box-shadow: inset 0 0 0 2px var(--uva-color-text, #2b2b2b); }
634
+ .scroll-hint { color: var(--uva-color-text-muted, #4b5563); }
635
+ .empty { margin: 0; color: var(--uva-color-text-muted, #4b5563); }
636
+ th, td { border-color: var(--uva-color-control-border, #808080); color: var(--uva-color-text, #2b2b2b); }
637
+ caption { color: var(--uva-color-text, #2b2b2b); }
638
+ @media (prefers-reduced-motion: reduce) {
639
+ .fill { transition: none; }
640
+ }
641
+ `),
642
+ ]; }
643
+ constructor() {
644
+ super();
645
+ /** Counts to draw. When non-empty, wins over the child table. Set a new array to update. */
646
+ this.items = [];
647
+ /**
648
+ * `month` (twelve bars per year), `year`, `decade` (one bar per decade, five to a row), or
649
+ * `auto`: months when every count is a month within 3 years, years up to 30 years, else
650
+ * decades. Anything else is month, with one console warning.
651
+ */
652
+ this.granularity = 'month';
653
+ /** `log` scales bar height by log(count + 1). Anything else is linear. */
654
+ this.scale = 'linear';
655
+ /**
656
+ * One bucket (`2015-10` or `2015`) or a range (`2015-03/2016-01`). A linked date range
657
+ * writes a range here. Empty when nothing is selected.
658
+ */
659
+ this.selected = '';
660
+ /** Id of a `<uvalib-date-range>` to keep in step with, both ways. */
661
+ this.rangeFor = '';
662
+ /** `strip`: a non-interactive per-year row (`role="img"`). Anything else is the bar chart. */
663
+ this.variant = '';
664
+ /** Word after the count in each bar's name. Plural; a count of one drops a trailing s. */
665
+ this.unit = 'items';
666
+ /** Accessible name of the bar group, and the start of the strip's summary. */
667
+ this.label = 'Dates';
668
+ this.tableItems = [];
669
+ this.authorTable = false;
670
+ this.overflowing = false;
671
+ this.activeKey = '';
672
+ this.uid = `uvalib-date-histogram-${++instanceCounter}`;
673
+ this.tableKey = '';
674
+ this.warnedGrain = false;
675
+ this.partner = null;
676
+ /** The next update came from the linked date range, so it must not write back. */
677
+ this.echo = false;
678
+ this.seen = false;
679
+ /** True while `choose()` assigns `selected`, so that click keeps the roving tab stop. */
680
+ this.choosing = false;
681
+ this.onPartner = () => {
682
+ this.pullPartner();
683
+ };
684
+ new SourceChildren(this, () => this.lightDom, (nodes) => this.readTable(nodes));
685
+ }
686
+ createRenderRoot() {
687
+ const root = super.createRenderRoot();
688
+ if (root instanceof ShadowRoot && this.noStyle) {
689
+ const sheet = shadowStructure.styleSheet;
690
+ if (sheet)
691
+ root.adoptedStyleSheets = [sheet];
692
+ }
693
+ return root;
694
+ }
695
+ connectedCallback() {
696
+ super.connectedCallback();
697
+ if (this.lightDom && this.noStyle) {
698
+ const node = this.getRootNode();
699
+ installLightDomStyles(`${this.localName}::structure`, unsafeCSS(structuralRules(this.localName)), {
700
+ root: node instanceof ShadowRoot || node instanceof Document ? node : undefined,
701
+ scope: false,
702
+ });
703
+ }
704
+ this.bindPartner();
705
+ // A reconnect schedules no update, so take up the date range here.
706
+ if (this.hasUpdated) {
707
+ this.seen = true;
708
+ this.syncOnBind();
709
+ }
710
+ this.measureOverflow();
711
+ if (!customElements.get('uvalib-date-range')) {
712
+ void customElements.whenDefined('uvalib-date-range').then(() => {
713
+ if (!this.isConnected)
714
+ return;
715
+ this.bindPartner();
716
+ this.syncOnBind();
717
+ });
718
+ }
719
+ }
720
+ disconnectedCallback() {
721
+ super.disconnectedCallback();
722
+ this.unlisten(this.partner);
723
+ this.partner = null;
724
+ this.ro?.disconnect();
725
+ this.ro = undefined;
726
+ this.observed = undefined;
727
+ this.partnerObserver?.disconnect();
728
+ this.partnerObserver = undefined;
729
+ this.seen = false;
730
+ }
731
+ willUpdate(changed) {
732
+ if (!this.warnedGrain &&
733
+ changed.has('granularity') &&
734
+ !['year', 'month', 'decade', 'auto'].includes(this.granularity)) {
735
+ this.warnedGrain = true;
736
+ console.warn(`<${TAG}>: granularity must be "month", "year", "decade" or "auto"; using "month".`);
737
+ }
738
+ if (changed.has('selected') && !this.choosing)
739
+ this.activeKey = '';
740
+ this.choosing = false;
741
+ }
742
+ updated(changed) {
743
+ const echoing = this.echo;
744
+ this.echo = false;
745
+ const before = this.partner;
746
+ this.bindPartner();
747
+ const appeared = this.partner != null && this.partner !== before;
748
+ if (!this.seen || changed.has('rangeFor') || appeared) {
749
+ this.seen = true;
750
+ if (!echoing || this.selected)
751
+ this.syncOnBind();
752
+ }
753
+ else if (changed.has('selected') && !echoing) {
754
+ this.pushPartner();
755
+ }
756
+ // With `auto`, counts arriving can change the grain, so a range read before them is read again.
757
+ const grain = this.grain;
758
+ if (this.drawnGrain && grain !== this.drawnGrain && this.partner)
759
+ this.pullPartner();
760
+ this.drawnGrain = grain;
761
+ this.watchForPartner();
762
+ this.measureOverflow();
763
+ }
764
+ get grain() {
765
+ const g = this.granularity;
766
+ if (g === 'year' || g === 'decade')
767
+ return g;
768
+ if (g === 'auto')
769
+ return autoGrain(this.data, this.partnerSpan());
770
+ return 'month';
771
+ }
772
+ /** The strip is one bar per year, or per decade for `decade` (or `auto` over a long span). */
773
+ get stripGrain() {
774
+ if (this.granularity === 'decade')
775
+ return 'decade';
776
+ if (this.granularity === 'auto')
777
+ return this.grain === 'decade' ? 'decade' : 'year';
778
+ return 'year';
779
+ }
780
+ /** Years from the linked date range's `min` to its `max`, or null. */
781
+ partnerSpan() {
782
+ const partner = this.partner ?? this.findPartner();
783
+ if (!partner)
784
+ return null;
785
+ return yearCount(partner.min || partner.getAttribute('min') || '', partner.max || partner.getAttribute('max') || '');
786
+ }
787
+ get strip() {
788
+ return this.variant === 'strip';
789
+ }
790
+ get log() {
791
+ return this.scale === 'log';
792
+ }
793
+ get labelText() {
794
+ return this.label.trim() || 'Dates';
795
+ }
796
+ get data() {
797
+ return this.items.length ? this.items : this.tableItems;
798
+ }
799
+ readTable(nodes) {
800
+ const tables = nodes.filter((n) => n instanceof HTMLTableElement);
801
+ const items = tables.flatMap((table) => parseTable(table));
802
+ const key = JSON.stringify(items);
803
+ const author = tables.length > 0;
804
+ if (key === this.tableKey && author === this.authorTable)
805
+ return;
806
+ this.tableKey = key;
807
+ this.tableItems = items;
808
+ this.authorTable = author;
809
+ if (this.hasUpdated)
810
+ this.requestUpdate();
811
+ }
812
+ findPartner() {
813
+ const id = this.rangeFor.trim();
814
+ if (!id)
815
+ return null;
816
+ const root = this.getRootNode();
817
+ const found = (root instanceof Document || root instanceof ShadowRoot ? root.getElementById(id) : null) ??
818
+ this.ownerDocument.getElementById(id);
819
+ if (!found || found.localName !== 'uvalib-date-range')
820
+ return null;
821
+ return found;
822
+ }
823
+ bindPartner() {
824
+ const el = this.findPartner();
825
+ if (el === this.partner)
826
+ return;
827
+ this.unlisten(this.partner);
828
+ this.partner = el;
829
+ // `uvalib-date-range-value` also covers a `value` set in script; `date-range-change`
830
+ // is kept for a date range from an older release.
831
+ el?.addEventListener('uvalib-date-range-value', this.onPartner);
832
+ el?.addEventListener('date-range-change', this.onPartner);
833
+ }
834
+ unlisten(el) {
835
+ el?.removeEventListener('uvalib-date-range-value', this.onPartner);
836
+ el?.removeEventListener('date-range-change', this.onPartner);
837
+ }
838
+ /**
839
+ * On connect, or when the date range appears: the range's value wins when it holds a
840
+ * selection or changed while this element was away; otherwise `selected` is written to it.
841
+ */
842
+ syncOnBind() {
843
+ const el = this.partner;
844
+ if (!el)
845
+ return;
846
+ const r = this.partnerRange();
847
+ const changedAway = !!r && this.lastSeenEl === el && this.lastSeen != null && r.join('/') !== this.lastSeen;
848
+ this.lastSeenEl = el;
849
+ if (!this.selected || changedAway || (r && !this.isFullSpan(r[0], r[1])))
850
+ this.pullPartner();
851
+ else
852
+ this.pushPartner();
853
+ }
854
+ /** While the named date range is not in the tree yet, take its value when it appears. */
855
+ watchForPartner() {
856
+ if (!this.isConnected || !this.rangeFor.trim() || this.partner) {
857
+ this.partnerObserver?.disconnect();
858
+ this.partnerObserver = undefined;
859
+ return;
860
+ }
861
+ if (this.partnerObserver)
862
+ return;
863
+ const root = this.getRootNode();
864
+ if (!(root instanceof Document) && !(root instanceof ShadowRoot))
865
+ return;
866
+ this.partnerObserver = new MutationObserver(() => {
867
+ if (!this.isConnected || this.partner)
868
+ return;
869
+ this.bindPartner();
870
+ if (!this.partner)
871
+ return;
872
+ this.partnerObserver?.disconnect();
873
+ this.partnerObserver = undefined;
874
+ this.syncOnBind();
875
+ this.requestUpdate();
876
+ });
877
+ this.partnerObserver.observe(root, { childList: true, subtree: true });
878
+ }
879
+ partnerEnds() {
880
+ const el = this.partner;
881
+ if (!el)
882
+ return null;
883
+ return {
884
+ min: el.min || el.getAttribute('min') || '',
885
+ max: el.max || el.getAttribute('max') || '',
886
+ };
887
+ }
888
+ /** `[min, max]` is the date range's empty state (a cleared selection, or the host's initial value). */
889
+ isFullSpan(from, to) {
890
+ const ends = this.partnerEnds();
891
+ if (!ends?.min || !ends.max)
892
+ return false;
893
+ return from === ends.min && to === ends.max;
894
+ }
895
+ /** The date range's value as it shows it: missing ends are `min` / `max`, both clamped to them. */
896
+ partnerRange() {
897
+ const el = this.partner;
898
+ const ends = this.partnerEnds();
899
+ if (!el || !ends)
900
+ return null;
901
+ const value = Array.isArray(el.value) ? el.value : [];
902
+ const bounded = isIsoDate(ends.min) && isIsoDate(ends.max) && ends.min <= ends.max;
903
+ const clamp = (iso) => !bounded ? iso : iso < ends.min ? ends.min : iso > ends.max ? ends.max : iso;
904
+ const a = isIsoDate(value[0]) ? clamp(value[0]) : bounded ? ends.min : '';
905
+ const b = isIsoDate(value[1]) ? clamp(value[1]) : bounded ? ends.max : '';
906
+ if (!a || !b)
907
+ return null;
908
+ return a <= b ? [a, b] : [b, b];
909
+ }
910
+ /** Show the date range's value. A `selected` that already spans it exactly is kept as written. */
911
+ pullPartner() {
912
+ const r = this.partnerRange();
913
+ if (!r)
914
+ return;
915
+ this.lastSeen = r.join('/');
916
+ const [from, to] = r;
917
+ if (this.isFullSpan(from, to)) {
918
+ if (this.selected) {
919
+ this.echo = true;
920
+ this.selected = '';
921
+ }
922
+ return;
923
+ }
924
+ // Compared as the range shows it, so a decade from before `min` (1810–1819 with a
925
+ // 1817 minimum) stays as chosen.
926
+ const cur = this.selected ? parseSelected(this.selected) : null;
927
+ const ends = this.partnerEnds();
928
+ const clamp = (iso) => ends && isIsoDate(ends.min) && isIsoDate(ends.max)
929
+ ? iso < ends.min
930
+ ? ends.min
931
+ : iso > ends.max
932
+ ? ends.max
933
+ : iso
934
+ : iso;
935
+ if (cur && clamp(cur.from) === from && clamp(cur.to) === to)
936
+ return;
937
+ const next = isoToSelected(from, to, this.grain === 'month' ? 'month' : 'year');
938
+ if (!next || next === this.selected)
939
+ return;
940
+ this.echo = true;
941
+ this.selected = next;
942
+ }
943
+ /**
944
+ * Write `selected` to the date range. A `selected` that is only the range's own value
945
+ * rounded to this chart's buckets is not written back (that would widen the range),
946
+ * unless `force` (a visitor chose that bar again to take the whole bucket).
947
+ */
948
+ pushPartner(force = false) {
949
+ const el = this.partner;
950
+ if (!el)
951
+ return;
952
+ const span = this.selected ? parseSelected(this.selected) : null;
953
+ let next = null;
954
+ if (span && isIsoDate(span.from) && isIsoDate(span.to))
955
+ next = [span.from, span.to];
956
+ else if (!this.selected && isIsoDate(el.min) && isIsoDate(el.max))
957
+ next = [el.min, el.max];
958
+ if (!next)
959
+ return;
960
+ const cur = el.value;
961
+ if (Array.isArray(cur) && cur[0] === next[0] && cur[1] === next[1])
962
+ return;
963
+ const r = this.partnerRange();
964
+ if (!force &&
965
+ r &&
966
+ this.selected &&
967
+ !this.isFullSpan(r[0], r[1]) &&
968
+ isoToSelected(r[0], r[1], this.grain === 'month' ? 'month' : 'year') === this.selected.trim()) {
969
+ this.lastSeen = r.join('/');
970
+ return;
971
+ }
972
+ el.value = next;
973
+ this.lastSeen = next.join('/');
974
+ }
975
+ emit(from, to) {
976
+ this.dispatchEvent(new CustomEvent('select', { detail: { from, to }, bubbles: true, composed: true }));
977
+ if (from && to) {
978
+ const name = isIsoDate(from) && isIsoDate(to) ? `${from}\u2013${to}` : 'other';
979
+ trackEvent(this, [TAG, 'select', name]);
980
+ }
981
+ }
982
+ choose(key) {
983
+ this.activeKey = key;
984
+ const token = this.selected.trim();
985
+ const bucket = keyToSpan(key);
986
+ // A decade selects its first to last year, the form a linked date range writes back.
987
+ const pick = this.grain === 'decade' && DECADE.test(key) ? decadeSelection(key) : key;
988
+ // A second click on the same token clears it. A stored month that only names part
989
+ // of the linked range (October 5–20 shown as 2015-10) expands to the whole bucket
990
+ // instead: assigning the same `selected` string would not run `pushPartner()`.
991
+ if (token === key || token === pick) {
992
+ const value = this.partner?.value;
993
+ const partial = !!bucket &&
994
+ Array.isArray(value) &&
995
+ value.length >= 2 &&
996
+ (value[0] !== bucket.from || value[1] !== bucket.to);
997
+ if (partial && bucket) {
998
+ this.pushPartner(true);
999
+ this.emit(bucket.from, bucket.to);
1000
+ return;
1001
+ }
1002
+ this.choosing = true;
1003
+ this.selected = '';
1004
+ this.emit('', '');
1005
+ return;
1006
+ }
1007
+ this.choosing = true;
1008
+ this.selected = pick;
1009
+ const span = parseSelected(pick);
1010
+ this.emit(span?.from ?? key, span?.to ?? key);
1011
+ }
1012
+ onBarClick(e) {
1013
+ const key = e.currentTarget.dataset.date ?? '';
1014
+ if (key)
1015
+ this.choose(key);
1016
+ }
1017
+ onBarKeydown(e) {
1018
+ const keys = this.flatKeys();
1019
+ const i = keys.indexOf(e.currentTarget.dataset.date ?? '');
1020
+ if (i < 0)
1021
+ return;
1022
+ const grain = this.grain;
1023
+ const step = grain === 'month' ? 12 : 1;
1024
+ // Decade rows are half-centuries that may start part-way, so up and down move 50 years.
1025
+ const row = (dir) => grain === 'decade'
1026
+ ? keys.indexOf(decadeKey(Number(keys[i].slice(0, 4)) + dir * 50))
1027
+ : i + dir * step;
1028
+ let next = -1;
1029
+ switch (e.key) {
1030
+ case 'ArrowRight':
1031
+ next = i + 1;
1032
+ break;
1033
+ case 'ArrowLeft':
1034
+ next = i - 1;
1035
+ break;
1036
+ case 'ArrowDown':
1037
+ next = row(1);
1038
+ break;
1039
+ case 'ArrowUp':
1040
+ next = row(-1);
1041
+ break;
1042
+ case 'Home':
1043
+ next = 0;
1044
+ break;
1045
+ case 'End':
1046
+ next = keys.length - 1;
1047
+ break;
1048
+ default:
1049
+ return;
1050
+ }
1051
+ e.preventDefault();
1052
+ if (next < 0 || next >= keys.length || next === i)
1053
+ return;
1054
+ this.activeKey = keys[next];
1055
+ void this.updateComplete.then(() => this.focusBar(this.activeKey));
1056
+ }
1057
+ flatKeys() {
1058
+ return buildModel(this.data, this.grain).bars.map((b) => b.key);
1059
+ }
1060
+ focusBar(key) {
1061
+ const btn = this.renderRoot.querySelector(`button.bar[data-date="${CSS.escape(key)}"]`);
1062
+ if (!btn)
1063
+ return;
1064
+ btn.focus();
1065
+ const scroller = btn.closest('.scroller');
1066
+ if (!scroller)
1067
+ return;
1068
+ const bar = btn.getBoundingClientRect();
1069
+ const box = scroller.getBoundingClientRect();
1070
+ const labelRight = btn
1071
+ .closest('.year')
1072
+ ?.querySelector('.year-label')
1073
+ ?.getBoundingClientRect().right;
1074
+ // 5px keeps the 3px outline and its 2px offset clear of the sticky year label.
1075
+ const leftEdge = labelRight == null ? box.left : labelRight + 5;
1076
+ if (bar.right > box.right)
1077
+ scroller.scrollLeft += bar.right - box.right;
1078
+ else if (bar.left < leftEdge)
1079
+ scroller.scrollLeft -= leftEdge - bar.left;
1080
+ }
1081
+ measureOverflow() {
1082
+ const scroller = this.renderRoot.querySelector('.scroller');
1083
+ if (!(scroller instanceof HTMLElement)) {
1084
+ if (this.overflowing)
1085
+ this.overflowing = false;
1086
+ return;
1087
+ }
1088
+ if (typeof ResizeObserver !== 'undefined') {
1089
+ this.ro ??= new ResizeObserver(() => this.measureOverflow());
1090
+ if (this.observed !== scroller) {
1091
+ this.ro.disconnect();
1092
+ this.ro.observe(scroller);
1093
+ this.observed = scroller;
1094
+ }
1095
+ }
1096
+ const on = scroller.scrollWidth > scroller.clientWidth + 1;
1097
+ if (on !== this.overflowing)
1098
+ this.overflowing = on;
1099
+ }
1100
+ /**
1101
+ * A lone odd token (a year chip on a month chart, a day, "undated", "c. 1910–1920")
1102
+ * highlights only itself. A bucket at this grain, or a range of dates, highlights overlaps.
1103
+ */
1104
+ selectionHighlights() {
1105
+ const trimmed = this.selected.trim();
1106
+ if (!trimmed)
1107
+ return false;
1108
+ const parts = splitSelection(trimmed);
1109
+ if (parts.length >= 2 && parts.every((p) => keyToSpan(p) !== null))
1110
+ return true;
1111
+ if (parts.length !== 1)
1112
+ return false;
1113
+ const grain = this.grain;
1114
+ if (grain === 'decade')
1115
+ return /^\d{4}$/.test(trimmed) || DECADE.test(trimmed);
1116
+ return grain === 'year' ? /^\d{4}$/.test(trimmed) : /^\d{4}-\d{2}$/.test(trimmed);
1117
+ }
1118
+ overlaps(key, span) {
1119
+ if (!span || !isIsoDate(span.from) || !isIsoDate(span.to))
1120
+ return false;
1121
+ const own = keyToSpan(key);
1122
+ if (!own)
1123
+ return false;
1124
+ return own.from <= span.to && own.to >= span.from;
1125
+ }
1126
+ pressed(key, span) {
1127
+ if (this.selected.trim() === key)
1128
+ return true;
1129
+ if (!this.selectionHighlights())
1130
+ return false;
1131
+ return this.overlaps(key, span);
1132
+ }
1133
+ /** An odd chip matches its own key, or an ISO day inside a multi-bucket range. */
1134
+ chipOn(key, span) {
1135
+ if (this.selected.trim() === key)
1136
+ return true;
1137
+ if (!isIsoDate(key))
1138
+ return false;
1139
+ const parts = splitSelection(this.selected.trim());
1140
+ if (parts.length < 2 || parts.some((p) => keyToSpan(p) === null))
1141
+ return false;
1142
+ return this.overlaps(key, span);
1143
+ }
1144
+ focusKey(bars) {
1145
+ const keys = bars.map((b) => b.key);
1146
+ if (this.activeKey && keys.includes(this.activeKey))
1147
+ return this.activeKey;
1148
+ const span = parseSelected(this.selected);
1149
+ const selected = bars.find((b) => this.pressed(b.key, span));
1150
+ return selected?.key ?? keys[0] ?? '';
1151
+ }
1152
+ barTemplate(bar, tab, span, max, column = 0) {
1153
+ const pct = barPercent(bar.count, max, this.log);
1154
+ const on = this.pressed(bar.key, span);
1155
+ return html `
1156
+ <button
1157
+ type="button"
1158
+ class="bar ${bar.count ? '' : 'is-empty'}"
1159
+ part="bar"
1160
+ style=${column ? `grid-column-start: ${column}` : nothing}
1161
+ data-date=${bar.key}
1162
+ tabindex=${bar.key === tab ? '0' : '-1'}
1163
+ aria-pressed=${on ? 'true' : 'false'}
1164
+ aria-label=${bucketName(bar.key, bar.count, this.unit)}
1165
+ @click=${this.onBarClick}
1166
+ @keydown=${this.onBarKeydown}
1167
+ >
1168
+ <span class="fill" aria-hidden="true" style="height: ${pct}%"></span>
1169
+ </button>
1170
+ `;
1171
+ }
1172
+ renderBars(model, span) {
1173
+ const tab = this.focusKey(model.bars);
1174
+ const grain = this.grain;
1175
+ if (grain === 'decade') {
1176
+ const rows = [...new Set(model.bars.map((b) => halfCentury(b.year)))];
1177
+ return html `
1178
+ <div class="scroller" role="group" aria-label=${this.labelText}>
1179
+ ${rows.map((start) => {
1180
+ const inRow = model.bars.filter((b) => halfCentury(b.year) === start);
1181
+ // The first decade keeps its column, so decades line up from row to row.
1182
+ const column = (inRow[0].year - start) / 10 + 1;
1183
+ return html `
1184
+ <div class="year">
1185
+ <span class="year-label" aria-hidden="true">${start}</span>
1186
+ <div class="bars" role="group" aria-label=${`${start} to ${start + 49}`}>
1187
+ ${repeat(inRow, (b) => b.key, (b, i) => this.barTemplate(b, tab, span, model.max, i === 0 ? column : 0))}
1188
+ </div>
1189
+ </div>
1190
+ `;
1191
+ })}
1192
+ </div>
1193
+ `;
1194
+ }
1195
+ if (grain === 'year') {
1196
+ return html `
1197
+ <div class="scroller" role="group" aria-label=${this.labelText}>
1198
+ <div class="bars">
1199
+ ${repeat(model.bars, (b) => b.key, (b) => this.barTemplate(b, tab, span, model.max))}
1200
+ </div>
1201
+ </div>
1202
+ `;
1203
+ }
1204
+ const years = [...new Set(model.bars.map((b) => b.year))];
1205
+ return html `
1206
+ <div class="scroller" role="group" aria-label=${this.labelText}>
1207
+ ${years.map((year) => html `
1208
+ <div class="year">
1209
+ <span class="year-label" id=${`${this.uid}-${year}`}>${year}</span>
1210
+ <div class="bars" role="group" aria-labelledby=${`${this.uid}-${year}`}>
1211
+ ${repeat(model.bars.filter((b) => b.year === year), (b) => b.key, (b) => this.barTemplate(b, tab, span, model.max))}
1212
+ </div>
1213
+ </div>
1214
+ `)}
1215
+ </div>
1216
+ `;
1217
+ }
1218
+ renderOdds(odds, span) {
1219
+ if (!odds.length)
1220
+ return nothing;
1221
+ return html `
1222
+ <div class="outliers" role="group" aria-label="Other dates">
1223
+ ${odds.map((odd) => {
1224
+ const name = bucketName(odd.key, odd.count, this.unit);
1225
+ const on = this.chipOn(odd.key, span);
1226
+ return html `
1227
+ <button
1228
+ type="button"
1229
+ class="chip"
1230
+ data-date=${odd.key}
1231
+ aria-pressed=${on ? 'true' : 'false'}
1232
+ @click=${this.onBarClick}
1233
+ >
1234
+ ${name}
1235
+ </button>
1236
+ `;
1237
+ })}
1238
+ </div>
1239
+ `;
1240
+ }
1241
+ generatedTable(model) {
1242
+ const caption = this.labelText;
1243
+ if (this.grain === 'month' && model.bars.length) {
1244
+ const years = [...new Set(model.bars.map((b) => b.year))];
1245
+ return html `
1246
+ <table part="table">
1247
+ ${tableCaption(caption)}
1248
+ <thead>
1249
+ <tr>
1250
+ <th scope="col">Year</th>
1251
+ ${SHORT_MONTHS.map((m) => html `<th scope="col">${m}</th>`)}
1252
+ <th scope="col">Total</th>
1253
+ </tr>
1254
+ </thead>
1255
+ <tbody>
1256
+ ${years.map((year) => {
1257
+ const cells = model.bars.filter((b) => b.year === year);
1258
+ const total = cells.reduce((s, b) => s + b.count, 0);
1259
+ return html `
1260
+ <tr>
1261
+ <th scope="row">${year}</th>
1262
+ ${cells.map((b) => html `<td>${b.count.toLocaleString('en-US')}</td>`)}
1263
+ <td>${total.toLocaleString('en-US')}</td>
1264
+ </tr>
1265
+ `;
1266
+ })}
1267
+ </tbody>
1268
+ </table>
1269
+ ${this.oddsTable(model)}
1270
+ `;
1271
+ }
1272
+ return html `
1273
+ <table part="table">
1274
+ ${tableCaption(caption)}
1275
+ <thead>
1276
+ <tr>
1277
+ <th scope="col">${{ year: 'Year', decade: 'Decade', month: 'Date' }[this.grain]}</th>
1278
+ <th scope="col">Count</th>
1279
+ </tr>
1280
+ </thead>
1281
+ <tbody>
1282
+ ${model.bars.map((b) => html `
1283
+ <tr>
1284
+ <th scope="row">${b.key}</th>
1285
+ <td>${b.count.toLocaleString('en-US')}</td>
1286
+ </tr>
1287
+ `)}
1288
+ ${model.odds.map((o) => html `
1289
+ <tr>
1290
+ <th scope="row">${o.key}</th>
1291
+ <td>${o.count.toLocaleString('en-US')}</td>
1292
+ </tr>
1293
+ `)}
1294
+ </tbody>
1295
+ </table>
1296
+ `;
1297
+ }
1298
+ oddsTable(model) {
1299
+ if (!model.odds.length)
1300
+ return nothing;
1301
+ return html `
1302
+ <table part="table">
1303
+ ${tableCaption('Other dates')}
1304
+ <thead>
1305
+ <tr>
1306
+ <th scope="col">Date</th>
1307
+ <th scope="col">Count</th>
1308
+ </tr>
1309
+ </thead>
1310
+ <tbody>
1311
+ ${model.odds.map((o) => html `
1312
+ <tr>
1313
+ <th scope="row">${o.key}</th>
1314
+ <td>${o.count.toLocaleString('en-US')}</td>
1315
+ </tr>
1316
+ `)}
1317
+ </tbody>
1318
+ </table>
1319
+ `;
1320
+ }
1321
+ renderDisclosure(model) {
1322
+ if (!this.authorTable && !model.bars.length && !model.odds.length)
1323
+ return nothing;
1324
+ const generated = this.lightDom || !this.authorTable || this.items.length > 0;
1325
+ return html `
1326
+ <details class="as-table">
1327
+ <summary>Show as table</summary>
1328
+ <div
1329
+ class="table-wrap"
1330
+ role="region"
1331
+ tabindex="0"
1332
+ aria-label="${this.labelText} as a table"
1333
+ >
1334
+ ${generated ? this.generatedTable(model) : nothing}
1335
+ ${generated || this.lightDom ? nothing : html `<slot></slot>`}
1336
+ </div>
1337
+ </details>
1338
+ `;
1339
+ }
1340
+ /** One bar track, or one per year when the span is already known, so late `items` do not shift the page. */
1341
+ reserveStyle() {
1342
+ const size = 'var(--uvalib-date-histogram-bar-size, 8rem)';
1343
+ if (this.grain === 'year')
1344
+ return `min-block-size: ${size}`;
1345
+ return `min-block-size: calc(${this.reservedRows()} * (${size} + 0.5rem))`;
1346
+ }
1347
+ /** Rows: one per year for months, one per half-century for decades. */
1348
+ reservedRows() {
1349
+ const grain = this.grain;
1350
+ const rowOf = (year) => (grain === 'decade' ? halfCentury(year) : year);
1351
+ const model = buildModel(this.data, grain);
1352
+ if (model.bars.length)
1353
+ return new Set(model.bars.map((b) => rowOf(b.year))).size;
1354
+ const partner = this.partner ?? this.findPartner();
1355
+ if (!partner)
1356
+ return 1;
1357
+ const a = /^(\d{4})/.exec((partner.min || partner.getAttribute('min') || '').trim());
1358
+ const b = /^(\d{4})/.exec((partner.max || partner.getAttribute('max') || '').trim());
1359
+ if (!a || !b)
1360
+ return 1;
1361
+ const [lo, hi] = [Number(a[1]), Number(b[1])].sort((x, y) => x - y);
1362
+ return grain === 'decade' ? (rowOf(hi) - rowOf(lo)) / 50 + 1 : hi - lo + 1;
1363
+ }
1364
+ renderStrip(model) {
1365
+ const years = model.bars;
1366
+ const total = years.reduce((s, b) => s + b.count, 0);
1367
+ const span = parseSelected(this.selected);
1368
+ // A year bar's key is the year, a decade bar's is `1810s`.
1369
+ const range = years.length === 0
1370
+ ? ''
1371
+ : years.length === 1
1372
+ ? years[0].key
1373
+ : `${years[0].key} to ${years[years.length - 1].key}`;
1374
+ let name = years.length
1375
+ ? `${this.labelText}: ${range}, ${total.toLocaleString('en-US')} ${unitWord(total, this.unit)}`
1376
+ : `${this.labelText}: no dates`;
1377
+ if (span && years.some((b) => this.pressed(b.key, span))) {
1378
+ const on = years.filter((b) => this.pressed(b.key, span));
1379
+ const a = on[0].key;
1380
+ const b = on[on.length - 1].key;
1381
+ name += a === b ? `. Selected ${a}.` : `. Selected ${a} to ${b}.`;
1382
+ }
1383
+ return html `
1384
+ <div class="strip" part="chart" role="img" aria-label=${name}>
1385
+ ${years.map((bar) => {
1386
+ const pct = barPercent(bar.count, model.max, this.log);
1387
+ const on = this.pressed(bar.key, span);
1388
+ return html `<span
1389
+ class="strip-bar ${bar.count ? '' : 'is-empty'} ${on ? 'is-selected' : ''}"
1390
+ part="bar"
1391
+ style="height: ${pct}%"
1392
+ ></span>`;
1393
+ })}
1394
+ </div>
1395
+ `;
1396
+ }
1397
+ render() {
1398
+ const model = buildModel(this.data, this.strip ? this.stripGrain : this.grain);
1399
+ if (this.strip)
1400
+ return this.renderStrip(model);
1401
+ const span = parseSelected(this.selected);
1402
+ const chartClass = `by-${this.grain}`;
1403
+ return html `
1404
+ <div class="chart ${chartClass}" part="chart">
1405
+ <p class="scroll-hint" ?hidden=${!this.overflowing}>Scroll sideways to see more.</p>
1406
+ <div class="plot" style=${this.reserveStyle()}>
1407
+ ${model.bars.length
1408
+ ? this.renderBars(model, span)
1409
+ : html `<p class="empty">No dates to show.</p>`}
1410
+ </div>
1411
+ </div>
1412
+ ${this.renderOdds(model.odds, span)} ${this.renderDisclosure(model)}
1413
+ `;
1414
+ }
1415
+ }
1416
+ __decorate([
1417
+ property({ type: Array })
1418
+ ], UvalibDateHistogram.prototype, "items", void 0);
1419
+ __decorate([
1420
+ property({ type: String })
1421
+ ], UvalibDateHistogram.prototype, "granularity", void 0);
1422
+ __decorate([
1423
+ property({ type: String })
1424
+ ], UvalibDateHistogram.prototype, "scale", void 0);
1425
+ __decorate([
1426
+ property({ type: String })
1427
+ ], UvalibDateHistogram.prototype, "selected", void 0);
1428
+ __decorate([
1429
+ property({ type: String, attribute: 'range-for' })
1430
+ ], UvalibDateHistogram.prototype, "rangeFor", void 0);
1431
+ __decorate([
1432
+ property({ type: String })
1433
+ ], UvalibDateHistogram.prototype, "variant", void 0);
1434
+ __decorate([
1435
+ property({ type: String })
1436
+ ], UvalibDateHistogram.prototype, "unit", void 0);
1437
+ __decorate([
1438
+ property({ type: String })
1439
+ ], UvalibDateHistogram.prototype, "label", void 0);
1440
+ __decorate([
1441
+ state()
1442
+ ], UvalibDateHistogram.prototype, "tableItems", void 0);
1443
+ __decorate([
1444
+ state()
1445
+ ], UvalibDateHistogram.prototype, "authorTable", void 0);
1446
+ __decorate([
1447
+ state()
1448
+ ], UvalibDateHistogram.prototype, "overflowing", void 0);
1449
+ __decorate([
1450
+ state()
1451
+ ], UvalibDateHistogram.prototype, "activeKey", void 0);
1452
+ //# sourceMappingURL=UvalibDateHistogram.js.map