@uvalib/web-components 1.1.1 → 1.2.0

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