@internetarchive/histogram-date-range 1.4.2-alpha-webdev8495.0 → 1.4.2

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.
@@ -1,1189 +1,1189 @@
1
- import '@internetarchive/ia-activity-indicator';
2
- import dayjs from 'dayjs/esm';
3
- import customParseFormat from 'dayjs/esm/plugin/customParseFormat';
4
- import fixFirstCenturyYears from './plugins/fix-first-century-years';
5
- import {
6
- css,
7
- html,
8
- LitElement,
9
- nothing,
10
- PropertyValues,
11
- svg,
12
- SVGTemplateResult,
13
- TemplateResult,
14
- } from 'lit';
15
- import { customElement, property, state, query } from 'lit/decorators.js';
16
- import { live } from 'lit/directives/live.js';
17
- import { classMap } from 'lit/directives/class-map.js';
18
- import { styleMap } from 'lit/directives/style-map.js';
19
-
20
- dayjs.extend(customParseFormat);
21
- dayjs.extend(fixFirstCenturyYears);
22
-
23
- type SliderId = 'slider-min' | 'slider-max';
24
-
25
- export type BinSnappingInterval = 'none' | 'month' | 'year';
26
-
27
- export type BarScalingPreset = 'linear' | 'logarithmic';
28
- export type BarScalingFunction = (binValue: number) => number;
29
- export type BarScalingOption = BarScalingPreset | BarScalingFunction;
30
-
31
- interface HistogramItem {
32
- value: number;
33
- height: number;
34
- binStart: string;
35
- binEnd: string;
36
- tooltip: string;
37
- }
38
-
39
- interface BarDataset extends DOMStringMap {
40
- numItems: string;
41
- binStart: string;
42
- binEnd: string;
43
- }
44
-
45
- // these values can be overridden via the component's HTML (camelCased) attributes
46
- const WIDTH = 180;
47
- const HEIGHT = 40;
48
- const SLIDER_WIDTH = 10;
49
- const TOOLTIP_WIDTH = 125;
50
- const TOOLTIP_HEIGHT = 30;
51
- const DATE_FORMAT = 'YYYY';
52
- const MISSING_DATA = 'no data';
53
- const UPDATE_DEBOUNCE_DELAY_MS = 0;
54
- const TOOLTIP_LABEL = 'item';
55
-
56
- // this constant is not set up to be overridden
57
- const SLIDER_CORNER_SIZE = 4;
58
-
59
- /**
60
- * Map from bar scaling preset options to the corresponding function they represent
61
- */
62
- const BAR_SCALING_PRESET_FNS: Record<BarScalingPreset, BarScalingFunction> = {
63
- linear: (binValue: number) => binValue,
64
- logarithmic: (binValue: number) => Math.log1p(binValue),
65
- };
66
-
67
- // these CSS custom props can be overridden from the HTML that is invoking this component
68
- const sliderColor = css`var(--histogramDateRangeSliderColor, #4B65FE)`;
69
- const selectedRangeColor = css`var(--histogramDateRangeSelectedRangeColor, #DBE0FF)`;
70
- const barIncludedFill = css`var(--histogramDateRangeBarIncludedFill, #2C2C2C)`;
71
- const activityIndicatorColor = css`var(--histogramDateRangeActivityIndicator, #2C2C2C)`;
72
- const barExcludedFill = css`var(--histogramDateRangeBarExcludedFill, #CCCCCC)`;
73
- const inputRowMargin = css`var(--histogramDateRangeInputRowMargin, 0)`;
74
- const inputBorder = css`var(--histogramDateRangeInputBorder, 0.5px solid #2C2C2C)`;
75
- const inputWidth = css`var(--histogramDateRangeInputWidth, 35px)`;
76
- const inputFontSize = css`var(--histogramDateRangeInputFontSize, 1.2rem)`;
77
- const inputFontFamily = css`var(--histogramDateRangeInputFontFamily, sans-serif)`;
78
- const tooltipBackgroundColor = css`var(--histogramDateRangeTooltipBackgroundColor, #2C2C2C)`;
79
- const tooltipTextColor = css`var(--histogramDateRangeTooltipTextColor, #FFFFFF)`;
80
- const tooltipFontSize = css`var(--histogramDateRangeTooltipFontSize, 1.1rem)`;
81
- const tooltipFontFamily = css`var(--histogramDateRangeTooltipFontFamily, sans-serif)`;
82
-
83
- @customElement('histogram-date-range')
84
- export class HistogramDateRange extends LitElement {
85
- /* eslint-disable lines-between-class-members */
86
-
87
- // public reactive properties that can be set via HTML attributes
88
- @property({ type: Number }) width = WIDTH;
89
- @property({ type: Number }) height = HEIGHT;
90
- @property({ type: Number }) sliderWidth = SLIDER_WIDTH;
91
- @property({ type: Number }) tooltipWidth = TOOLTIP_WIDTH;
92
- @property({ type: Number }) tooltipHeight = TOOLTIP_HEIGHT;
93
- @property({ type: Number }) updateDelay = UPDATE_DEBOUNCE_DELAY_MS;
94
- @property({ type: String }) dateFormat = DATE_FORMAT;
95
- @property({ type: String }) missingDataMessage = MISSING_DATA;
96
- @property({ type: String }) minDate = '';
97
- @property({ type: String }) maxDate = '';
98
- @property({ type: Boolean }) disabled = false;
99
- @property({ type: Array }) bins: number[] = [];
100
- /** If true, update events will not be canceled by the date inputs receiving focus */
101
- @property({ type: Boolean }) updateWhileFocused = false;
102
-
103
- /**
104
- * What interval bins should be snapped to for determining their time ranges.
105
- * - `none` (default): Bins should each represent an identical duration of time,
106
- * without regard for the actual dates represented.
107
- * - `month`: Bins should each represent one or more full, non-overlapping months.
108
- * The bin ranges will be "snapped" to the nearest month boundaries, which can
109
- * result in bins that represent different amounts of time, particularly if the
110
- * provided bins do not evenly divide the provided date range, or if the months
111
- * represented are of different lengths.
112
- * - `year`: Same as `month`, but snapping to year boundaries instead of months.
113
- */
114
- @property({ type: String }) binSnapping: BinSnappingInterval = 'none';
115
-
116
- /**
117
- * What label to use on tooltips to identify the type of data being represented.
118
- * Defaults to `'item(s)'`.
119
- */
120
- @property({ type: String }) tooltipLabel = TOOLTIP_LABEL;
121
-
122
- /**
123
- * A function or preset value indicating how the height of each bar relates to its
124
- * corresponding bin value. Current presets available are 'logarithmic' and 'linear',
125
- * but a custom function may be provided instead if other behavior is desired.
126
- *
127
- * The default scaling (`'logarithmic'`) uses the logarithm of each bin value, yielding
128
- * more prominent bars for smaller values. This ensures that even when the difference
129
- * between the min & max values is large, small values are unlikely to completely disappear
130
- * visually. However, the cost is that bars have less noticeable variation among values of
131
- * a similar magnitude, and their heights are not a direct representation of the bin values.
132
- *
133
- * The `'linear'` preset option instead sizes the bars in linear proportion to their bin
134
- * values.
135
- */
136
- @property({ type: String }) barScaling: BarScalingOption = 'logarithmic';
137
-
138
- // internal reactive properties not exposed as attributes
139
- @state() private _tooltipOffsetX = 0;
140
- @state() private _tooltipOffsetY = 0;
141
- @state() private _tooltipContent?: TemplateResult;
142
- @state() private _tooltipDateFormat?: string;
143
- @state() private _isDragging = false;
144
- @state() private _isLoading = false;
145
-
146
- @query('#tooltip') private _tooltip!: HTMLDivElement;
147
-
148
- // non-reactive properties (changes don't auto-trigger re-rendering)
149
- private _minSelectedDate = '';
150
- private _maxSelectedDate = '';
151
- private _minDateMS = 0;
152
- private _maxDateMS = 0;
153
- private _dragOffset = 0;
154
- private _histWidth = 0;
155
- private _binWidth = 0;
156
- private _currentSlider?: SVGRectElement;
157
- private _histData: HistogramItem[] = [];
158
- private _emitUpdatedEventTimer?: ReturnType<typeof setTimeout>;
159
- private _previousDateRange = '';
160
-
161
- /* eslint-enable lines-between-class-members */
162
-
163
- disconnectedCallback(): void {
164
- this.removeListeners();
165
- super.disconnectedCallback();
166
- }
167
-
168
- willUpdate(changedProps: PropertyValues): void {
169
- // check for changes that would affect bin data calculations
170
- if (
171
- changedProps.has('bins') ||
172
- changedProps.has('minDate') ||
173
- changedProps.has('maxDate') ||
174
- changedProps.has('minSelectedDate') ||
175
- changedProps.has('maxSelectedDate') ||
176
- changedProps.has('width') ||
177
- changedProps.has('height') ||
178
- changedProps.has('binSnapping') ||
179
- changedProps.has('barScaling')
180
- ) {
181
- this.handleDataUpdate();
182
- }
183
- }
184
-
185
- /**
186
- * Set private properties that depend on the attribute bin data
187
- *
188
- * We're caching these values and not using getters to avoid recalculating all
189
- * of the hist data every time the user drags a slider or hovers over a bar
190
- * creating a tooltip.
191
- */
192
- private handleDataUpdate(): void {
193
- if (!this.hasBinData) {
194
- return;
195
- }
196
- this._histWidth = this.width - this.sliderWidth * 2;
197
-
198
- this._minDateMS = this.snapTimestamp(this.getMSFromString(this.minDate));
199
- // NB: The max date string, converted as-is to ms, represents the *start* of the
200
- // final date interval; we want the *end*, so we add any snap interval/offset.
201
- this._maxDateMS =
202
- this.snapTimestamp(
203
- this.getMSFromString(this.maxDate) + this.snapInterval
204
- ) + this.snapEndOffset;
205
-
206
- this._binWidth = this._histWidth / this._numBins;
207
- this._histData = this.calculateHistData();
208
- this.minSelectedDate = this.minSelectedDate
209
- ? this.minSelectedDate
210
- : this.minDate;
211
- this.maxSelectedDate = this.maxSelectedDate
212
- ? this.maxSelectedDate
213
- : this.maxDate;
214
- }
215
-
216
- /**
217
- * Rounds the given timestamp to the next full second.
218
- */
219
- private snapToNextSecond(timestamp: number): number {
220
- return Math.ceil(timestamp / 1000) * 1000;
221
- }
222
-
223
- /**
224
- * Rounds the given timestamp to the (approximate) nearest start of a month,
225
- * such that dates up to and including the 15th of the month are rounded down,
226
- * while dates past the 15th are rounded up.
227
- */
228
- private snapToMonth(timestamp: number): number {
229
- const d = dayjs(timestamp);
230
- const monthsToAdd = d.date() < 16 ? 0 : 1;
231
- const snapped = d
232
- .add(monthsToAdd, 'month')
233
- .date(1)
234
- .hour(0)
235
- .minute(0)
236
- .second(0)
237
- .millisecond(0); // First millisecond of the month
238
- return snapped.valueOf();
239
- }
240
-
241
- /**
242
- * Rounds the given timestamp to the (approximate) nearest start of a year,
243
- * such that dates up to the end of June are rounded down, while dates in
244
- * July or later are rounded up.
245
- */
246
- private snapToYear(timestamp: number): number {
247
- const d = dayjs(timestamp);
248
- const yearsToAdd = d.month() < 6 ? 0 : 1;
249
- const snapped = d
250
- .add(yearsToAdd, 'year')
251
- .month(0)
252
- .date(1)
253
- .hour(0)
254
- .minute(0)
255
- .second(0)
256
- .millisecond(0); // First millisecond of the year
257
- return snapped.valueOf();
258
- }
259
-
260
- /**
261
- * Rounds the given timestamp according to the `binSnapping` property.
262
- * Default is simply to snap to the nearest full second.
263
- */
264
- private snapTimestamp(timestamp: number): number {
265
- switch (this.binSnapping) {
266
- case 'year':
267
- return this.snapToYear(timestamp);
268
- case 'month':
269
- return this.snapToMonth(timestamp);
270
- case 'none':
271
- default:
272
- // We still align it to second boundaries to resolve minor discrepancies
273
- return this.snapToNextSecond(timestamp);
274
- }
275
- }
276
-
277
- /**
278
- * Function to scale bin values, whether from a preset or a provided custom function.
279
- */
280
- private get barScalingFunction(): BarScalingFunction {
281
- if (typeof this.barScaling === 'string') {
282
- return BAR_SCALING_PRESET_FNS[this.barScaling];
283
- }
284
-
285
- return this.barScaling;
286
- }
287
-
288
- private calculateHistData(): HistogramItem[] {
289
- const { bins, height, dateRangeMS, _numBins, _minDateMS } = this;
290
- const minValue = Math.min(...this.bins);
291
- const maxValue = Math.max(...this.bins);
292
- // if there is no difference between the min and max values, use a range of
293
- // 1 because log scaling will fail if the range is 0
294
- const valueRange =
295
- minValue === maxValue ? 1 : this.barScalingFunction(maxValue);
296
- const valueScale = height / valueRange;
297
- const dateScale = dateRangeMS / _numBins;
298
-
299
- return bins.map((v: number, i: number) => {
300
- const binStartMS = this.snapTimestamp(i * dateScale + _minDateMS);
301
- const binStart = this.formatDate(binStartMS);
302
-
303
- const binEndMS =
304
- this.snapTimestamp((i + 1) * dateScale + _minDateMS) +
305
- this.snapEndOffset;
306
- const binEnd = this.formatDate(binEndMS);
307
-
308
- const tooltipStart = this.formatDate(binStartMS, this.tooltipDateFormat);
309
- const tooltipEnd = this.formatDate(binEndMS, this.tooltipDateFormat);
310
- // If start/end are the same, just render a single value
311
- const tooltip =
312
- tooltipStart === tooltipEnd
313
- ? tooltipStart
314
- : `${tooltipStart} - ${tooltipEnd}`;
315
-
316
- return {
317
- value: v,
318
- // apply the configured scaling function to the bin value before determining bar height
319
- height: Math.floor(this.barScalingFunction(v) * valueScale),
320
- binStart,
321
- binEnd,
322
- tooltip,
323
- };
324
- });
325
- }
326
-
327
- private get hasBinData(): boolean {
328
- return this._numBins > 0;
329
- }
330
-
331
- private get _numBins(): number {
332
- if (!this.bins || !this.bins.length) {
333
- return 0;
334
- }
335
- return this.bins.length;
336
- }
337
-
338
- private get histogramLeftEdgeX(): number {
339
- return this.sliderWidth;
340
- }
341
-
342
- private get histogramRightEdgeX(): number {
343
- return this.width - this.sliderWidth;
344
- }
345
-
346
- /**
347
- * Approximate size in ms of the interval to which bins are snapped.
348
- */
349
- private get snapInterval(): number {
350
- const yearMS = 31_536_000_000; // A 365-day approximation of ms in a year
351
- const monthMS = 2_592_000_000; // A 30-day approximation of ms in a month
352
- switch (this.binSnapping) {
353
- case 'year':
354
- return yearMS;
355
- case 'month':
356
- return monthMS;
357
- case 'none':
358
- default:
359
- return 0;
360
- }
361
- }
362
-
363
- /**
364
- * Offset added to the end of each bin to ensure disjoint intervals,
365
- * depending on whether snapping is enabled and there are multiple bins.
366
- */
367
- private get snapEndOffset(): number {
368
- return this.binSnapping !== 'none' && this._numBins > 1 ? -1 : 0;
369
- }
370
-
371
- /**
372
- * Optional date format to use for tooltips only.
373
- * Falls back to `dateFormat` if not provided.
374
- */
375
- @property({ type: String }) get tooltipDateFormat(): string {
376
- return this._tooltipDateFormat ?? this.dateFormat;
377
- }
378
-
379
- set tooltipDateFormat(value: string) {
380
- this._tooltipDateFormat = value;
381
- }
382
-
383
- /** component's loading (and disabled) state */
384
- @property({ type: Boolean }) get loading(): boolean {
385
- return this._isLoading;
386
- }
387
-
388
- set loading(value: boolean) {
389
- this.disabled = value;
390
- this._isLoading = value;
391
- }
392
-
393
- /** formatted minimum date of selected date range */
394
- @property() get minSelectedDate(): string {
395
- return this.formatDate(this.getMSFromString(this._minSelectedDate));
396
- }
397
-
398
- /** updates minSelectedDate if new date is valid */
399
- set minSelectedDate(rawDate: string) {
400
- if (!this._minSelectedDate) {
401
- // because the values needed to calculate valid max/min values are not
402
- // available during the lit init when it's populating properties from
403
- // attributes, fall back to just the raw date if nothing is already set
404
- this._minSelectedDate = rawDate;
405
- return;
406
- }
407
- const proposedDateMS = this.getMSFromString(rawDate);
408
- const isValidDate = !Number.isNaN(proposedDateMS);
409
- const isNotTooRecent =
410
- proposedDateMS <= this.getMSFromString(this.maxSelectedDate);
411
- if (isValidDate && isNotTooRecent) {
412
- this._minSelectedDate = this.formatDate(proposedDateMS);
413
- }
414
- this.requestUpdate();
415
- }
416
-
417
- /** formatted maximum date of selected date range */
418
- @property() get maxSelectedDate(): string {
419
- return this.formatDate(this.getMSFromString(this._maxSelectedDate));
420
- }
421
-
422
- /** updates maxSelectedDate if new date is valid */
423
- set maxSelectedDate(rawDate: string) {
424
- if (!this._maxSelectedDate) {
425
- // because the values needed to calculate valid max/min values are not
426
- // available during the lit init when it's populating properties from
427
- // attributes, fall back to just the raw date if nothing is already set
428
- this._maxSelectedDate = rawDate;
429
- return;
430
- }
431
- const proposedDateMS = this.getMSFromString(rawDate);
432
- const isValidDate = !Number.isNaN(proposedDateMS);
433
- const isNotTooOld =
434
- proposedDateMS >= this.getMSFromString(this.minSelectedDate);
435
- if (isValidDate && isNotTooOld) {
436
- this._maxSelectedDate = this.formatDate(proposedDateMS);
437
- }
438
- this.requestUpdate();
439
- }
440
-
441
- /** horizontal position of min date slider */
442
- get minSliderX(): number {
443
- const x = this.translateDateToPosition(this.minSelectedDate);
444
- return this.validMinSliderX(x);
445
- }
446
-
447
- /** horizontal position of max date slider */
448
- get maxSliderX(): number {
449
- const maxSelectedDateMS = this.snapTimestamp(
450
- this.getMSFromString(this.maxSelectedDate) + this.snapInterval
451
- );
452
- const x = this.translateDateToPosition(this.formatDate(maxSelectedDateMS));
453
- return this.validMaxSliderX(x);
454
- }
455
-
456
- private get dateRangeMS(): number {
457
- return this._maxDateMS - this._minDateMS;
458
- }
459
-
460
- private showTooltip(e: PointerEvent): void {
461
- if (this._isDragging || this.disabled) {
462
- return;
463
- }
464
-
465
- const target = e.currentTarget as SVGRectElement;
466
- const x = target.x.baseVal.value + this.sliderWidth / 2;
467
- const dataset = target.dataset as BarDataset;
468
- const itemsText = `${this.tooltipLabel}${
469
- dataset.numItems !== '1' ? 's' : ''
470
- }`;
471
- const formattedNumItems = Number(dataset.numItems).toLocaleString();
472
-
473
- const tooltipPadding = 2;
474
- const bufferHeight = 9;
475
- const heightAboveHistogram = bufferHeight + this.tooltipHeight;
476
- const histogramBounds = this.getBoundingClientRect();
477
- const barX = histogramBounds.x + x;
478
- const histogramY = histogramBounds.y;
479
-
480
- // Center the tooltip horizontally along the bar
481
- this._tooltipOffsetX =
482
- barX -
483
- tooltipPadding +
484
- (this._binWidth - this.sliderWidth - this.tooltipWidth) / 2 +
485
- window.scrollX;
486
- // Place the tooltip (with arrow) just above the top of the histogram bars
487
- this._tooltipOffsetY = histogramY - heightAboveHistogram + window.scrollY;
488
-
489
- this._tooltipContent = html`
490
- ${formattedNumItems} ${itemsText}<br />
491
- ${dataset.tooltip}
492
- `;
493
- this._tooltip.showPopover?.();
494
- }
495
-
496
- private hideTooltip(): void {
497
- this._tooltipContent = undefined;
498
- this._tooltip.hidePopover?.();
499
- }
500
-
501
- // use arrow functions (rather than standard JS class instance methods) so
502
- // that `this` is bound to the histogramDateRange object and not the event
503
- // target. for more info see
504
- // https://lit-element.polymer-project.org/guide/events#using-this-in-event-listeners
505
- private drag = (e: PointerEvent): void => {
506
- // prevent selecting text or other ranges while dragging, especially in Safari
507
- e.preventDefault();
508
- if (this.disabled) {
509
- return;
510
- }
511
- this.setDragOffset(e);
512
- this._isDragging = true;
513
- this.addListeners();
514
- this.cancelPendingUpdateEvent();
515
- };
516
-
517
- private drop = (): void => {
518
- if (this._isDragging) {
519
- this.removeListeners();
520
- this.beginEmitUpdateProcess();
521
- }
522
- this._isDragging = false;
523
- };
524
-
525
- /**
526
- * Adjust the date range based on slider movement
527
- *
528
- * @param e PointerEvent from the slider being moved
529
- */
530
- private move = (e: PointerEvent): void => {
531
- const histogramClientX = this.getBoundingClientRect().x;
532
- const newX = e.clientX - histogramClientX - this._dragOffset;
533
- const slider = this._currentSlider as SVGRectElement;
534
- if ((slider.id as SliderId) === 'slider-min') {
535
- this.minSelectedDate = this.translatePositionToDate(
536
- this.validMinSliderX(newX)
537
- );
538
- } else {
539
- this.maxSelectedDate = this.translatePositionToDate(
540
- this.validMaxSliderX(newX)
541
- );
542
- if (this.getMSFromString(this.maxSelectedDate) > this._maxDateMS) {
543
- this.maxSelectedDate = this.maxDate;
544
- }
545
- }
546
- };
547
-
548
- /**
549
- * Constrain a proposed value for the minimum (left) slider
550
- *
551
- * If the value is less than the leftmost valid position, then set it to the
552
- * left edge of the histogram (ie the slider width). If the value is greater
553
- * than the rightmost valid position (the position of the max slider), then
554
- * set it to the position of the max slider
555
- */
556
- private validMinSliderX(newX: number): number {
557
- // allow the left slider to go right only to the right slider, even if the
558
- // max selected date is out of range
559
- const rightLimit = Math.min(
560
- this.translateDateToPosition(this.maxSelectedDate),
561
- this.histogramRightEdgeX
562
- );
563
- newX = this.clamp(newX, this.histogramLeftEdgeX, rightLimit);
564
- const isInvalid =
565
- Number.isNaN(newX) || rightLimit < this.histogramLeftEdgeX;
566
- return isInvalid ? this.histogramLeftEdgeX : newX;
567
- }
568
-
569
- /**
570
- * Constrain a proposed value for the maximum (right) slider
571
- *
572
- * If the value is greater than the rightmost valid position, then set it to
573
- * the right edge of the histogram (ie histogram width - slider width). If the
574
- * value is less than the leftmost valid position (the position of the min
575
- * slider), then set it to the position of the min slider
576
- */
577
- private validMaxSliderX(newX: number): number {
578
- // allow the right slider to go left only to the left slider, even if the
579
- // min selected date is out of range
580
- const leftLimit = Math.max(
581
- this.histogramLeftEdgeX,
582
- this.translateDateToPosition(this.minSelectedDate)
583
- );
584
- newX = this.clamp(newX, leftLimit, this.histogramRightEdgeX);
585
- const isInvalid =
586
- Number.isNaN(newX) || leftLimit > this.histogramRightEdgeX;
587
- return isInvalid ? this.histogramRightEdgeX : newX;
588
- }
589
-
590
- private addListeners(): void {
591
- window.addEventListener('pointermove', this.move);
592
- window.addEventListener('pointerup', this.drop);
593
- window.addEventListener('pointercancel', this.drop);
594
- }
595
-
596
- private removeListeners(): void {
597
- window.removeEventListener('pointermove', this.move);
598
- window.removeEventListener('pointerup', this.drop);
599
- window.removeEventListener('pointercancel', this.drop);
600
- }
601
-
602
- /**
603
- * start a timer to emit an update event. this timer can be canceled (and the
604
- * event not emitted) if user drags a slider or focuses a date input within
605
- * the update delay
606
- */
607
- private beginEmitUpdateProcess(): void {
608
- this.cancelPendingUpdateEvent();
609
- this._emitUpdatedEventTimer = setTimeout(() => {
610
- if (this.currentDateRangeString === this._previousDateRange) {
611
- // don't emit duplicate event if no change since last emitted event
612
- return;
613
- }
614
- this._previousDateRange = this.currentDateRangeString;
615
- const options = {
616
- detail: {
617
- minDate: this.minSelectedDate,
618
- maxDate: this.maxSelectedDate,
619
- },
620
- bubbles: true,
621
- composed: true,
622
- };
623
- this.dispatchEvent(new CustomEvent('histogramDateRangeUpdated', options));
624
- }, this.updateDelay);
625
- }
626
-
627
- private cancelPendingUpdateEvent(): void {
628
- if (this._emitUpdatedEventTimer === undefined) {
629
- return;
630
- }
631
- clearTimeout(this._emitUpdatedEventTimer);
632
- this._emitUpdatedEventTimer = undefined;
633
- }
634
-
635
- /**
636
- * find position of pointer in relation to the current slider
637
- */
638
- private setDragOffset(e: PointerEvent): void {
639
- this._currentSlider = e.currentTarget as SVGRectElement;
640
- const sliderX =
641
- (this._currentSlider.id as SliderId) === 'slider-min'
642
- ? this.minSliderX
643
- : this.maxSliderX;
644
- const histogramClientX = this.getBoundingClientRect().x;
645
- this._dragOffset = e.clientX - histogramClientX - sliderX;
646
- }
647
-
648
- /**
649
- * @param x horizontal position of slider
650
- * @returns string representation of date
651
- */
652
- private translatePositionToDate(x: number): string {
653
- // Snap to the nearest second, fixing the case where input like 1/1/2010
654
- // would get translated to 12/31/2009 due to slight discrepancies from
655
- // pixel boundaries and floating point error.
656
- const milliseconds = this.snapToNextSecond(
657
- ((x - this.sliderWidth) * this.dateRangeMS) / this._histWidth
658
- );
659
- return this.formatDate(this._minDateMS + milliseconds);
660
- }
661
-
662
- /**
663
- * Returns slider x-position corresponding to given date
664
- *
665
- * @param date
666
- * @returns x-position of slider
667
- */
668
- private translateDateToPosition(date: string): number {
669
- const milliseconds = this.getMSFromString(date);
670
- return (
671
- this.sliderWidth +
672
- ((milliseconds - this._minDateMS) * this._histWidth) / this.dateRangeMS
673
- );
674
- }
675
-
676
- /** ensure that the returned value is between minValue and maxValue */
677
- private clamp(x: number, minValue: number, maxValue: number): number {
678
- return Math.min(Math.max(x, minValue), maxValue);
679
- }
680
-
681
- private handleInputFocus(): void {
682
- if (!this.updateWhileFocused) {
683
- this.cancelPendingUpdateEvent();
684
- }
685
- }
686
-
687
- private handleMinDateInput(e: Event): void {
688
- const target = e.currentTarget as HTMLInputElement;
689
- if (target.value !== this.minSelectedDate) {
690
- this.minSelectedDate = target.value;
691
- this.beginEmitUpdateProcess();
692
- }
693
- }
694
-
695
- private handleMaxDateInput(e: Event): void {
696
- const target = e.currentTarget as HTMLInputElement;
697
- if (target.value !== this.maxSelectedDate) {
698
- this.maxSelectedDate = target.value;
699
- this.beginEmitUpdateProcess();
700
- }
701
- }
702
-
703
- private handleKeyUp(e: KeyboardEvent): void {
704
- if (e.key === 'Enter') {
705
- const target = e.currentTarget as HTMLInputElement;
706
- target.blur();
707
- if (target.id === 'date-min') {
708
- this.handleMinDateInput(e);
709
- } else if (target.id === 'date-max') {
710
- this.handleMaxDateInput(e);
711
- }
712
- }
713
- }
714
-
715
- private get currentDateRangeString(): string {
716
- return `${this.minSelectedDate}:${this.maxSelectedDate}`;
717
- }
718
-
719
- private getMSFromString(date: unknown): number {
720
- // It's possible that `date` is not a string in certain situations.
721
- // For instance if you use LitElement bindings and the date is `2000`,
722
- // it will be treated as a number instead of a string. This just makes sure
723
- // we're dealing with a string.
724
- const stringified = typeof date === 'string' ? date : String(date);
725
- const digitGroupCount = (stringified.split(/(\d+)/).length - 1) / 2;
726
- if (digitGroupCount === 1) {
727
- // if there's just a single set of digits, assume it's a year
728
- const dateObj = new Date(0, 0); // start at January 1, 1900
729
- dateObj.setFullYear(Number(stringified)); // override year
730
- return dateObj.getTime(); // get time in milliseconds
731
- }
732
- return dayjs(stringified, [this.dateFormat, DATE_FORMAT]).valueOf();
733
- }
734
-
735
- /**
736
- * expand or narrow the selected range by moving the slider nearest the
737
- * clicked bar to the outer edge of the clicked bar
738
- *
739
- * @param e Event click event from a histogram bar
740
- */
741
- private handleBarClick(e: Event): void {
742
- const dataset = (e.currentTarget as SVGRectElement).dataset as BarDataset;
743
- // use the midpoint of the width of the clicked bar to determine which is
744
- // the nearest slider
745
- const clickPosition =
746
- (this.getMSFromString(dataset.binStart) +
747
- this.getMSFromString(dataset.binEnd)) /
748
- 2;
749
- const distanceFromMinSlider = Math.abs(
750
- clickPosition - this.getMSFromString(this.minSelectedDate)
751
- );
752
- const distanceFromMaxSlider = Math.abs(
753
- clickPosition - this.getMSFromString(this.maxSelectedDate)
754
- );
755
- // update the selected range by moving the nearer slider
756
- if (distanceFromMinSlider < distanceFromMaxSlider) {
757
- this.minSelectedDate = dataset.binStart;
758
- } else {
759
- this.maxSelectedDate = dataset.binEnd;
760
- }
761
- this.beginEmitUpdateProcess();
762
- }
763
-
764
- private get minSliderTemplate(): SVGTemplateResult {
765
- // width/height in pixels of curved part of the sliders (like
766
- // border-radius); used as part of a SVG quadratic curve. see
767
- // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#curve_commands
768
- const cs = SLIDER_CORNER_SIZE;
769
-
770
- const sliderShape = `
771
- M${this.minSliderX},0
772
- h-${this.sliderWidth - cs}
773
- q-${cs},0 -${cs},${cs}
774
- v${this.height - cs * 2}
775
- q0,${cs} ${cs},${cs}
776
- h${this.sliderWidth - cs}
777
- `;
778
- return this.generateSliderSVG(this.minSliderX, 'slider-min', sliderShape);
779
- }
780
-
781
- private get maxSliderTemplate(): SVGTemplateResult {
782
- const cs = SLIDER_CORNER_SIZE;
783
- const sliderShape = `
784
- M${this.maxSliderX},0
785
- h${this.sliderWidth - cs}
786
- q${cs},0 ${cs},${cs}
787
- v${this.height - cs * 2}
788
- q0,${cs} -${cs},${cs}
789
- h-${this.sliderWidth - cs}
790
- `;
791
- return this.generateSliderSVG(this.maxSliderX, 'slider-max', sliderShape);
792
- }
793
-
794
- private generateSliderSVG(
795
- sliderPositionX: number,
796
- id: SliderId,
797
- sliderShape: string
798
- ): SVGTemplateResult {
799
- // whether the curved part of the slider is facing towards the left (1), ie
800
- // minimum, or facing towards the right (-1), ie maximum
801
- const k = id === 'slider-min' ? 1 : -1;
802
-
803
- const sliderClasses = classMap({
804
- slider: true,
805
- draggable: !this.disabled,
806
- dragging: this._isDragging,
807
- });
808
-
809
- return svg`
810
- <svg
811
- id=${id}
812
- class=${sliderClasses}
813
- @pointerdown=${this.drag}
814
- >
815
- <path d="${sliderShape} z" fill="${sliderColor}" />
816
- <rect
817
- x="${
818
- sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.4 * k
819
- }"
820
- y="${this.height / 3}"
821
- width="1"
822
- height="${this.height / 3}"
823
- fill="white"
824
- />
825
- <rect
826
- x="${
827
- sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.6 * k
828
- }"
829
- y="${this.height / 3}"
830
- width="1"
831
- height="${this.height / 3}"
832
- fill="white"
833
- />
834
- </svg>
835
- `;
836
- }
837
-
838
- get selectedRangeTemplate(): SVGTemplateResult {
839
- return svg`
840
- <rect
841
- x="${this.minSliderX}"
842
- y="0"
843
- width="${this.maxSliderX - this.minSliderX}"
844
- height="${this.height}"
845
- fill="${selectedRangeColor}"
846
- />`;
847
- }
848
-
849
- get histogramTemplate(): SVGTemplateResult[] {
850
- const xScale = this._histWidth / this._numBins;
851
- const barWidth = xScale - 1;
852
- let x = this.sliderWidth; // start at the left edge of the histogram
853
-
854
- return this._histData.map(data => {
855
- const { minSelectedDate, maxSelectedDate } = this;
856
- const barHeight = data.height;
857
-
858
- const binIsBeforeMin = this.isBefore(data.binEnd, minSelectedDate);
859
- const binIsAfterMax = this.isAfter(data.binStart, maxSelectedDate);
860
- const barFill =
861
- binIsBeforeMin || binIsAfterMax ? barExcludedFill : barIncludedFill;
862
-
863
- // the stroke-dasharray style below creates a transparent border around the
864
- // right edge of the bar, which prevents user from encountering a gap
865
- // between adjacent bars (eg when viewing the tooltips or when trying to
866
- // extend the range by clicking on a bar)
867
- const barStyle = `stroke-dasharray: 0 ${barWidth} ${barHeight} ${barWidth} 0 ${barHeight}`;
868
-
869
- const bar = svg`
870
- <rect
871
- class="bar-pointer-target"
872
- x=${x}
873
- y="0"
874
- width=${barWidth}
875
- height=${this.height}
876
- @pointerenter=${this.showTooltip}
877
- @pointerleave=${this.hideTooltip}
878
- @click=${this.handleBarClick}
879
- fill="transparent"
880
- data-num-items=${data.value}
881
- data-bin-start=${data.binStart}
882
- data-bin-end=${data.binEnd}
883
- data-tooltip=${data.tooltip}
884
- />
885
- <rect
886
- class="bar"
887
- style=${barStyle}
888
- x=${x}
889
- y=${this.height - barHeight}
890
- width=${barWidth}
891
- height=${barHeight}
892
- fill=${barFill}
893
- />`;
894
- x += xScale;
895
- return bar;
896
- });
897
- }
898
-
899
- /** Whether the first arg represents a date strictly before the second arg */
900
- private isBefore(date1: string, date2: string): boolean {
901
- const date1MS = this.getMSFromString(date1);
902
- const date2MS = this.getMSFromString(date2);
903
- return date1MS < date2MS;
904
- }
905
-
906
- /** Whether the first arg represents a date strictly after the second arg */
907
- private isAfter(date1: string, date2: string): boolean {
908
- const date1MS = this.getMSFromString(date1);
909
- const date2MS = this.getMSFromString(date2);
910
- return date1MS > date2MS;
911
- }
912
-
913
- private formatDate(dateMS: number, format: string = this.dateFormat): string {
914
- if (Number.isNaN(dateMS)) {
915
- return '';
916
- }
917
- const date = dayjs(dateMS);
918
- if (date.year() < 1000) {
919
- // years before 1000 don't play well with dayjs custom formatting, so work around dayjs
920
- // by setting the year to a sentinel value and then replacing it instead.
921
- // this is a bit hacky but it does the trick for essentially all reasonable cases
922
- // until such time as we replace dayjs.
923
- const tmpDate = date.year(199999);
924
- return tmpDate.format(format).replace(/199999/g, date.year().toString());
925
- }
926
- return date.format(format);
927
- }
928
-
929
- /**
930
- * NOTE: we are relying on the lit `live` directive in the template to
931
- * ensure that the change to minSelectedDate is noticed and the input value
932
- * gets properly re-rendered. see
933
- * https://lit.dev/docs/templates/directives/#live
934
- */
935
- get minInputTemplate(): TemplateResult {
936
- return html`
937
- <input
938
- id="date-min"
939
- placeholder=${this.dateFormat}
940
- type="text"
941
- @focus=${this.handleInputFocus}
942
- @blur=${this.handleMinDateInput}
943
- @keyup=${this.handleKeyUp}
944
- .value=${live(this.minSelectedDate)}
945
- ?disabled=${this.disabled}
946
- />
947
- `;
948
- }
949
-
950
- get maxInputTemplate(): TemplateResult {
951
- return html`
952
- <input
953
- id="date-max"
954
- placeholder=${this.dateFormat}
955
- type="text"
956
- @focus=${this.handleInputFocus}
957
- @blur=${this.handleMaxDateInput}
958
- @keyup=${this.handleKeyUp}
959
- .value=${live(this.maxSelectedDate)}
960
- ?disabled=${this.disabled}
961
- />
962
- `;
963
- }
964
-
965
- get minLabelTemplate(): TemplateResult {
966
- return html`<label for="date-min" class="sr-only">Minimum date:</label>`;
967
- }
968
-
969
- get maxLabelTemplate(): TemplateResult {
970
- return html`<label for="date-max" class="sr-only">Maximum date:</label>`;
971
- }
972
-
973
- get tooltipTemplate(): TemplateResult {
974
- const styles = styleMap({
975
- width: `${this.tooltipWidth}px`,
976
- height: `${this.tooltipHeight}px`,
977
- top: `${this._tooltipOffsetY}px`,
978
- left: `${this._tooltipOffsetX}px`,
979
- });
980
-
981
- return html`
982
- <div id="tooltip" style=${styles} popover>${this._tooltipContent}</div>
983
- `;
984
- }
985
-
986
- private get histogramAccessibilityTemplate(): TemplateResult {
987
- let rangeText: string = '';
988
- if (this.minSelectedDate && this.maxSelectedDate) {
989
- rangeText = ` from ${this.minSelectedDate} to ${this.maxSelectedDate}`;
990
- } else if (this.minSelectedDate) {
991
- rangeText = ` from ${this.minSelectedDate}`;
992
- } else if (this.maxSelectedDate) {
993
- rangeText = ` up to ${this.maxSelectedDate}`;
994
- }
995
-
996
- const titleText = `Filter results for dates${rangeText}`;
997
- const descText = `This histogram shows the distribution of dates${rangeText}`;
998
-
999
- return html`<title id="histogram-title">${titleText}</title
1000
- ><desc id="histogram-desc">${descText}</desc>`;
1001
- }
1002
-
1003
- private get noDataTemplate(): TemplateResult {
1004
- return html`
1005
- <div class="missing-data-message">${this.missingDataMessage}</div>
1006
- `;
1007
- }
1008
-
1009
- private get activityIndicatorTemplate(): TemplateResult | typeof nothing {
1010
- if (!this.loading) {
1011
- return nothing;
1012
- }
1013
- return html`
1014
- <ia-activity-indicator mode="processing"> </ia-activity-indicator>
1015
- `;
1016
- }
1017
-
1018
- static styles = css`
1019
- .missing-data-message {
1020
- text-align: center;
1021
- }
1022
- #container {
1023
- margin: 0;
1024
- touch-action: none;
1025
- position: relative;
1026
- }
1027
- .disabled {
1028
- opacity: 0.3;
1029
- }
1030
- ia-activity-indicator {
1031
- position: absolute;
1032
- left: calc(50% - 10px);
1033
- top: 10px;
1034
- width: 20px;
1035
- height: 20px;
1036
- --activityIndicatorLoadingDotColor: rgba(0, 0, 0, 0);
1037
- --activityIndicatorLoadingRingColor: ${activityIndicatorColor};
1038
- }
1039
-
1040
- /* prevent selection from interfering with tooltip, especially on mobile */
1041
- /* https://stackoverflow.com/a/4407335/1163042 */
1042
- .noselect {
1043
- -webkit-touch-callout: none; /* iOS Safari */
1044
- -webkit-user-select: none; /* Safari */
1045
- -moz-user-select: none; /* Old versions of Firefox */
1046
- -ms-user-select: none; /* Internet Explorer/Edge */
1047
- user-select: none; /* current Chrome, Edge, Opera and Firefox */
1048
- }
1049
- .bar,
1050
- .bar-pointer-target {
1051
- /* create a transparent border around the hist bars to prevent "gaps" and
1052
- flickering when moving around between bars. this also helps with handling
1053
- clicks on the bars, preventing users from being able to click in between
1054
- bars */
1055
- stroke: rgba(0, 0, 0, 0);
1056
- /* ensure transparent stroke wide enough to cover gap between bars */
1057
- stroke-width: 2px;
1058
- }
1059
- .bar {
1060
- /* ensure the bar's pointer target receives events, not the bar itself */
1061
- pointer-events: none;
1062
- }
1063
- .bar-pointer-target:hover + .bar {
1064
- /* highlight currently hovered bar */
1065
- fill-opacity: 0.7;
1066
- }
1067
- .disabled .bar-pointer-target:hover + .bar {
1068
- /* ensure no visual hover interaction when disabled */
1069
- fill-opacity: 1;
1070
- }
1071
- /****** histogram ********/
1072
- #tooltip {
1073
- position: absolute;
1074
- background: ${tooltipBackgroundColor};
1075
- margin: 0;
1076
- border: 0;
1077
- color: ${tooltipTextColor};
1078
- text-align: center;
1079
- border-radius: 3px;
1080
- padding: 2px;
1081
- font-size: ${tooltipFontSize};
1082
- font-family: ${tooltipFontFamily};
1083
- touch-action: none;
1084
- pointer-events: none;
1085
- overflow: visible;
1086
- }
1087
- #tooltip:after {
1088
- content: '';
1089
- position: absolute;
1090
- margin-left: -5px;
1091
- top: 100%;
1092
- left: 50%;
1093
- /* arrow */
1094
- border: 5px solid ${tooltipTextColor};
1095
- border-color: ${tooltipBackgroundColor} transparent transparent
1096
- transparent;
1097
- }
1098
- /****** slider ********/
1099
- .slider {
1100
- shape-rendering: crispEdges; /* So the slider doesn't get blurry if dragged between pixels */
1101
- }
1102
- .draggable:hover {
1103
- cursor: grab;
1104
- }
1105
- .dragging {
1106
- cursor: grabbing !important;
1107
- }
1108
- /****** inputs ********/
1109
- #inputs {
1110
- display: flex;
1111
- justify-content: center;
1112
- margin: ${inputRowMargin};
1113
- }
1114
- #inputs .dash {
1115
- position: relative;
1116
- bottom: -1px;
1117
- align-self: center; /* Otherwise the dash sticks to the top while the inputs grow */
1118
- }
1119
- input {
1120
- width: ${inputWidth};
1121
- margin: 0 3px;
1122
- border: ${inputBorder};
1123
- border-radius: 2px !important;
1124
- text-align: center;
1125
- font-size: ${inputFontSize};
1126
- font-family: ${inputFontFamily};
1127
- }
1128
- .sr-only {
1129
- position: absolute !important;
1130
- width: 1px !important;
1131
- height: 1px !important;
1132
- margin: 0 !important;
1133
- padding: 0 !important;
1134
- border: 0 !important;
1135
- overflow: hidden !important;
1136
- white-space: nowrap !important;
1137
- clip: rect(1px, 1px, 1px, 1px) !important;
1138
- -webkit-clip-path: inset(50%) !important;
1139
- clip-path: inset(50%) !important;
1140
- }
1141
- `;
1142
-
1143
- render(): TemplateResult {
1144
- if (!this.hasBinData) {
1145
- return this.noDataTemplate;
1146
- }
1147
- return html`
1148
- <div
1149
- id="container"
1150
- class="
1151
- noselect
1152
- ${this._isDragging ? 'dragging' : ''}
1153
- "
1154
- style="width: ${this.width}px"
1155
- >
1156
- ${this.activityIndicatorTemplate} ${this.tooltipTemplate}
1157
- <div
1158
- class="inner-container
1159
- ${this.disabled ? 'disabled' : ''}"
1160
- >
1161
- <svg
1162
- width="${this.width}"
1163
- height="${this.height}"
1164
- aria-labelledby="histogram-title histogram-desc"
1165
- @pointerleave="${this.drop}"
1166
- >
1167
- ${this.histogramAccessibilityTemplate} ${this.selectedRangeTemplate}
1168
- <svg id="histogram">${this.histogramTemplate}</svg>
1169
- ${this.minSliderTemplate} ${this.maxSliderTemplate}
1170
- </svg>
1171
- <div id="inputs">
1172
- ${this.minLabelTemplate} ${this.minInputTemplate}
1173
- <div class="dash">-</div>
1174
- ${this.maxLabelTemplate} ${this.maxInputTemplate}
1175
- <slot name="inputs-right-side"></slot>
1176
- </div>
1177
- </div>
1178
- </div>
1179
- `;
1180
- }
1181
- }
1182
-
1183
- // help TypeScript provide strong typing when interacting with DOM APIs
1184
- // https://stackoverflow.com/questions/65148695/lit-element-typescript-project-global-interface-declaration-necessary
1185
- declare global {
1186
- interface HTMLElementTagNameMap {
1187
- 'histogram-date-range': HistogramDateRange;
1188
- }
1189
- }
1
+ import '@internetarchive/ia-activity-indicator';
2
+ import dayjs from 'dayjs/esm';
3
+ import customParseFormat from 'dayjs/esm/plugin/customParseFormat';
4
+ import fixFirstCenturyYears from './plugins/fix-first-century-years';
5
+ import {
6
+ css,
7
+ html,
8
+ LitElement,
9
+ nothing,
10
+ PropertyValues,
11
+ svg,
12
+ SVGTemplateResult,
13
+ TemplateResult,
14
+ } from 'lit';
15
+ import { customElement, property, state, query } from 'lit/decorators.js';
16
+ import { live } from 'lit/directives/live.js';
17
+ import { classMap } from 'lit/directives/class-map.js';
18
+ import { styleMap } from 'lit/directives/style-map.js';
19
+
20
+ dayjs.extend(customParseFormat);
21
+ dayjs.extend(fixFirstCenturyYears);
22
+
23
+ type SliderId = 'slider-min' | 'slider-max';
24
+
25
+ export type BinSnappingInterval = 'none' | 'month' | 'year';
26
+
27
+ export type BarScalingPreset = 'linear' | 'logarithmic';
28
+ export type BarScalingFunction = (binValue: number) => number;
29
+ export type BarScalingOption = BarScalingPreset | BarScalingFunction;
30
+
31
+ interface HistogramItem {
32
+ value: number;
33
+ height: number;
34
+ binStart: string;
35
+ binEnd: string;
36
+ tooltip: string;
37
+ }
38
+
39
+ interface BarDataset extends DOMStringMap {
40
+ numItems: string;
41
+ binStart: string;
42
+ binEnd: string;
43
+ }
44
+
45
+ // these values can be overridden via the component's HTML (camelCased) attributes
46
+ const WIDTH = 180;
47
+ const HEIGHT = 40;
48
+ const SLIDER_WIDTH = 10;
49
+ const TOOLTIP_WIDTH = 125;
50
+ const TOOLTIP_HEIGHT = 30;
51
+ const DATE_FORMAT = 'YYYY';
52
+ const MISSING_DATA = 'no data';
53
+ const UPDATE_DEBOUNCE_DELAY_MS = 0;
54
+ const TOOLTIP_LABEL = 'item';
55
+
56
+ // this constant is not set up to be overridden
57
+ const SLIDER_CORNER_SIZE = 4;
58
+
59
+ /**
60
+ * Map from bar scaling preset options to the corresponding function they represent
61
+ */
62
+ const BAR_SCALING_PRESET_FNS: Record<BarScalingPreset, BarScalingFunction> = {
63
+ linear: (binValue: number) => binValue,
64
+ logarithmic: (binValue: number) => Math.log1p(binValue),
65
+ };
66
+
67
+ // these CSS custom props can be overridden from the HTML that is invoking this component
68
+ const sliderColor = css`var(--histogramDateRangeSliderColor, #4B65FE)`;
69
+ const selectedRangeColor = css`var(--histogramDateRangeSelectedRangeColor, #DBE0FF)`;
70
+ const barIncludedFill = css`var(--histogramDateRangeBarIncludedFill, #2C2C2C)`;
71
+ const activityIndicatorColor = css`var(--histogramDateRangeActivityIndicator, #2C2C2C)`;
72
+ const barExcludedFill = css`var(--histogramDateRangeBarExcludedFill, #CCCCCC)`;
73
+ const inputRowMargin = css`var(--histogramDateRangeInputRowMargin, 0)`;
74
+ const inputBorder = css`var(--histogramDateRangeInputBorder, 0.5px solid #2C2C2C)`;
75
+ const inputWidth = css`var(--histogramDateRangeInputWidth, 35px)`;
76
+ const inputFontSize = css`var(--histogramDateRangeInputFontSize, 1.2rem)`;
77
+ const inputFontFamily = css`var(--histogramDateRangeInputFontFamily, sans-serif)`;
78
+ const tooltipBackgroundColor = css`var(--histogramDateRangeTooltipBackgroundColor, #2C2C2C)`;
79
+ const tooltipTextColor = css`var(--histogramDateRangeTooltipTextColor, #FFFFFF)`;
80
+ const tooltipFontSize = css`var(--histogramDateRangeTooltipFontSize, 1.1rem)`;
81
+ const tooltipFontFamily = css`var(--histogramDateRangeTooltipFontFamily, sans-serif)`;
82
+
83
+ @customElement('histogram-date-range')
84
+ export class HistogramDateRange extends LitElement {
85
+ /* eslint-disable lines-between-class-members */
86
+
87
+ // public reactive properties that can be set via HTML attributes
88
+ @property({ type: Number }) width = WIDTH;
89
+ @property({ type: Number }) height = HEIGHT;
90
+ @property({ type: Number }) sliderWidth = SLIDER_WIDTH;
91
+ @property({ type: Number }) tooltipWidth = TOOLTIP_WIDTH;
92
+ @property({ type: Number }) tooltipHeight = TOOLTIP_HEIGHT;
93
+ @property({ type: Number }) updateDelay = UPDATE_DEBOUNCE_DELAY_MS;
94
+ @property({ type: String }) dateFormat = DATE_FORMAT;
95
+ @property({ type: String }) missingDataMessage = MISSING_DATA;
96
+ @property({ type: String }) minDate = '';
97
+ @property({ type: String }) maxDate = '';
98
+ @property({ type: Boolean }) disabled = false;
99
+ @property({ type: Array }) bins: number[] = [];
100
+ /** If true, update events will not be canceled by the date inputs receiving focus */
101
+ @property({ type: Boolean }) updateWhileFocused = false;
102
+
103
+ /**
104
+ * What interval bins should be snapped to for determining their time ranges.
105
+ * - `none` (default): Bins should each represent an identical duration of time,
106
+ * without regard for the actual dates represented.
107
+ * - `month`: Bins should each represent one or more full, non-overlapping months.
108
+ * The bin ranges will be "snapped" to the nearest month boundaries, which can
109
+ * result in bins that represent different amounts of time, particularly if the
110
+ * provided bins do not evenly divide the provided date range, or if the months
111
+ * represented are of different lengths.
112
+ * - `year`: Same as `month`, but snapping to year boundaries instead of months.
113
+ */
114
+ @property({ type: String }) binSnapping: BinSnappingInterval = 'none';
115
+
116
+ /**
117
+ * What label to use on tooltips to identify the type of data being represented.
118
+ * Defaults to `'item(s)'`.
119
+ */
120
+ @property({ type: String }) tooltipLabel = TOOLTIP_LABEL;
121
+
122
+ /**
123
+ * A function or preset value indicating how the height of each bar relates to its
124
+ * corresponding bin value. Current presets available are 'logarithmic' and 'linear',
125
+ * but a custom function may be provided instead if other behavior is desired.
126
+ *
127
+ * The default scaling (`'logarithmic'`) uses the logarithm of each bin value, yielding
128
+ * more prominent bars for smaller values. This ensures that even when the difference
129
+ * between the min & max values is large, small values are unlikely to completely disappear
130
+ * visually. However, the cost is that bars have less noticeable variation among values of
131
+ * a similar magnitude, and their heights are not a direct representation of the bin values.
132
+ *
133
+ * The `'linear'` preset option instead sizes the bars in linear proportion to their bin
134
+ * values.
135
+ */
136
+ @property({ type: String }) barScaling: BarScalingOption = 'logarithmic';
137
+
138
+ // internal reactive properties not exposed as attributes
139
+ @state() private _tooltipOffsetX = 0;
140
+ @state() private _tooltipOffsetY = 0;
141
+ @state() private _tooltipContent?: TemplateResult;
142
+ @state() private _tooltipDateFormat?: string;
143
+ @state() private _isDragging = false;
144
+ @state() private _isLoading = false;
145
+
146
+ @query('#tooltip') private _tooltip!: HTMLDivElement;
147
+
148
+ // non-reactive properties (changes don't auto-trigger re-rendering)
149
+ private _minSelectedDate = '';
150
+ private _maxSelectedDate = '';
151
+ private _minDateMS = 0;
152
+ private _maxDateMS = 0;
153
+ private _dragOffset = 0;
154
+ private _histWidth = 0;
155
+ private _binWidth = 0;
156
+ private _currentSlider?: SVGRectElement;
157
+ private _histData: HistogramItem[] = [];
158
+ private _emitUpdatedEventTimer?: ReturnType<typeof setTimeout>;
159
+ private _previousDateRange = '';
160
+
161
+ /* eslint-enable lines-between-class-members */
162
+
163
+ disconnectedCallback(): void {
164
+ this.removeListeners();
165
+ super.disconnectedCallback();
166
+ }
167
+
168
+ willUpdate(changedProps: PropertyValues): void {
169
+ // check for changes that would affect bin data calculations
170
+ if (
171
+ changedProps.has('bins') ||
172
+ changedProps.has('minDate') ||
173
+ changedProps.has('maxDate') ||
174
+ changedProps.has('minSelectedDate') ||
175
+ changedProps.has('maxSelectedDate') ||
176
+ changedProps.has('width') ||
177
+ changedProps.has('height') ||
178
+ changedProps.has('binSnapping') ||
179
+ changedProps.has('barScaling')
180
+ ) {
181
+ this.handleDataUpdate();
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Set private properties that depend on the attribute bin data
187
+ *
188
+ * We're caching these values and not using getters to avoid recalculating all
189
+ * of the hist data every time the user drags a slider or hovers over a bar
190
+ * creating a tooltip.
191
+ */
192
+ private handleDataUpdate(): void {
193
+ if (!this.hasBinData) {
194
+ return;
195
+ }
196
+ this._histWidth = this.width - this.sliderWidth * 2;
197
+
198
+ this._minDateMS = this.snapTimestamp(this.getMSFromString(this.minDate));
199
+ // NB: The max date string, converted as-is to ms, represents the *start* of the
200
+ // final date interval; we want the *end*, so we add any snap interval/offset.
201
+ this._maxDateMS =
202
+ this.snapTimestamp(
203
+ this.getMSFromString(this.maxDate) + this.snapInterval
204
+ ) + this.snapEndOffset;
205
+
206
+ this._binWidth = this._histWidth / this._numBins;
207
+ this._histData = this.calculateHistData();
208
+ this.minSelectedDate = this.minSelectedDate
209
+ ? this.minSelectedDate
210
+ : this.minDate;
211
+ this.maxSelectedDate = this.maxSelectedDate
212
+ ? this.maxSelectedDate
213
+ : this.maxDate;
214
+ }
215
+
216
+ /**
217
+ * Rounds the given timestamp to the next full second.
218
+ */
219
+ private snapToNextSecond(timestamp: number): number {
220
+ return Math.ceil(timestamp / 1000) * 1000;
221
+ }
222
+
223
+ /**
224
+ * Rounds the given timestamp to the (approximate) nearest start of a month,
225
+ * such that dates up to and including the 15th of the month are rounded down,
226
+ * while dates past the 15th are rounded up.
227
+ */
228
+ private snapToMonth(timestamp: number): number {
229
+ const d = dayjs(timestamp);
230
+ const monthsToAdd = d.date() < 16 ? 0 : 1;
231
+ const snapped = d
232
+ .add(monthsToAdd, 'month')
233
+ .date(1)
234
+ .hour(0)
235
+ .minute(0)
236
+ .second(0)
237
+ .millisecond(0); // First millisecond of the month
238
+ return snapped.valueOf();
239
+ }
240
+
241
+ /**
242
+ * Rounds the given timestamp to the (approximate) nearest start of a year,
243
+ * such that dates up to the end of June are rounded down, while dates in
244
+ * July or later are rounded up.
245
+ */
246
+ private snapToYear(timestamp: number): number {
247
+ const d = dayjs(timestamp);
248
+ const yearsToAdd = d.month() < 6 ? 0 : 1;
249
+ const snapped = d
250
+ .add(yearsToAdd, 'year')
251
+ .month(0)
252
+ .date(1)
253
+ .hour(0)
254
+ .minute(0)
255
+ .second(0)
256
+ .millisecond(0); // First millisecond of the year
257
+ return snapped.valueOf();
258
+ }
259
+
260
+ /**
261
+ * Rounds the given timestamp according to the `binSnapping` property.
262
+ * Default is simply to snap to the nearest full second.
263
+ */
264
+ private snapTimestamp(timestamp: number): number {
265
+ switch (this.binSnapping) {
266
+ case 'year':
267
+ return this.snapToYear(timestamp);
268
+ case 'month':
269
+ return this.snapToMonth(timestamp);
270
+ case 'none':
271
+ default:
272
+ // We still align it to second boundaries to resolve minor discrepancies
273
+ return this.snapToNextSecond(timestamp);
274
+ }
275
+ }
276
+
277
+ /**
278
+ * Function to scale bin values, whether from a preset or a provided custom function.
279
+ */
280
+ private get barScalingFunction(): BarScalingFunction {
281
+ if (typeof this.barScaling === 'string') {
282
+ return BAR_SCALING_PRESET_FNS[this.barScaling];
283
+ }
284
+
285
+ return this.barScaling;
286
+ }
287
+
288
+ private calculateHistData(): HistogramItem[] {
289
+ const { bins, height, dateRangeMS, _numBins, _minDateMS } = this;
290
+ const minValue = Math.min(...this.bins);
291
+ const maxValue = Math.max(...this.bins);
292
+ // if there is no difference between the min and max values, use a range of
293
+ // 1 because log scaling will fail if the range is 0
294
+ const valueRange =
295
+ minValue === maxValue ? 1 : this.barScalingFunction(maxValue);
296
+ const valueScale = height / valueRange;
297
+ const dateScale = dateRangeMS / _numBins;
298
+
299
+ return bins.map((v: number, i: number) => {
300
+ const binStartMS = this.snapTimestamp(i * dateScale + _minDateMS);
301
+ const binStart = this.formatDate(binStartMS);
302
+
303
+ const binEndMS =
304
+ this.snapTimestamp((i + 1) * dateScale + _minDateMS) +
305
+ this.snapEndOffset;
306
+ const binEnd = this.formatDate(binEndMS);
307
+
308
+ const tooltipStart = this.formatDate(binStartMS, this.tooltipDateFormat);
309
+ const tooltipEnd = this.formatDate(binEndMS, this.tooltipDateFormat);
310
+ // If start/end are the same, just render a single value
311
+ const tooltip =
312
+ tooltipStart === tooltipEnd
313
+ ? tooltipStart
314
+ : `${tooltipStart} - ${tooltipEnd}`;
315
+
316
+ return {
317
+ value: v,
318
+ // apply the configured scaling function to the bin value before determining bar height
319
+ height: Math.floor(this.barScalingFunction(v) * valueScale),
320
+ binStart,
321
+ binEnd,
322
+ tooltip,
323
+ };
324
+ });
325
+ }
326
+
327
+ private get hasBinData(): boolean {
328
+ return this._numBins > 0;
329
+ }
330
+
331
+ private get _numBins(): number {
332
+ if (!this.bins || !this.bins.length) {
333
+ return 0;
334
+ }
335
+ return this.bins.length;
336
+ }
337
+
338
+ private get histogramLeftEdgeX(): number {
339
+ return this.sliderWidth;
340
+ }
341
+
342
+ private get histogramRightEdgeX(): number {
343
+ return this.width - this.sliderWidth;
344
+ }
345
+
346
+ /**
347
+ * Approximate size in ms of the interval to which bins are snapped.
348
+ */
349
+ private get snapInterval(): number {
350
+ const yearMS = 31_536_000_000; // A 365-day approximation of ms in a year
351
+ const monthMS = 2_592_000_000; // A 30-day approximation of ms in a month
352
+ switch (this.binSnapping) {
353
+ case 'year':
354
+ return yearMS;
355
+ case 'month':
356
+ return monthMS;
357
+ case 'none':
358
+ default:
359
+ return 0;
360
+ }
361
+ }
362
+
363
+ /**
364
+ * Offset added to the end of each bin to ensure disjoint intervals,
365
+ * depending on whether snapping is enabled and there are multiple bins.
366
+ */
367
+ private get snapEndOffset(): number {
368
+ return this.binSnapping !== 'none' && this._numBins > 1 ? -1 : 0;
369
+ }
370
+
371
+ /**
372
+ * Optional date format to use for tooltips only.
373
+ * Falls back to `dateFormat` if not provided.
374
+ */
375
+ @property({ type: String }) get tooltipDateFormat(): string {
376
+ return this._tooltipDateFormat ?? this.dateFormat;
377
+ }
378
+
379
+ set tooltipDateFormat(value: string) {
380
+ this._tooltipDateFormat = value;
381
+ }
382
+
383
+ /** component's loading (and disabled) state */
384
+ @property({ type: Boolean }) get loading(): boolean {
385
+ return this._isLoading;
386
+ }
387
+
388
+ set loading(value: boolean) {
389
+ this.disabled = value;
390
+ this._isLoading = value;
391
+ }
392
+
393
+ /** formatted minimum date of selected date range */
394
+ @property() get minSelectedDate(): string {
395
+ return this.formatDate(this.getMSFromString(this._minSelectedDate));
396
+ }
397
+
398
+ /** updates minSelectedDate if new date is valid */
399
+ set minSelectedDate(rawDate: string) {
400
+ if (!this._minSelectedDate) {
401
+ // because the values needed to calculate valid max/min values are not
402
+ // available during the lit init when it's populating properties from
403
+ // attributes, fall back to just the raw date if nothing is already set
404
+ this._minSelectedDate = rawDate;
405
+ return;
406
+ }
407
+ const proposedDateMS = this.getMSFromString(rawDate);
408
+ const isValidDate = !Number.isNaN(proposedDateMS);
409
+ const isNotTooRecent =
410
+ proposedDateMS <= this.getMSFromString(this.maxSelectedDate);
411
+ if (isValidDate && isNotTooRecent) {
412
+ this._minSelectedDate = this.formatDate(proposedDateMS);
413
+ }
414
+ this.requestUpdate();
415
+ }
416
+
417
+ /** formatted maximum date of selected date range */
418
+ @property() get maxSelectedDate(): string {
419
+ return this.formatDate(this.getMSFromString(this._maxSelectedDate));
420
+ }
421
+
422
+ /** updates maxSelectedDate if new date is valid */
423
+ set maxSelectedDate(rawDate: string) {
424
+ if (!this._maxSelectedDate) {
425
+ // because the values needed to calculate valid max/min values are not
426
+ // available during the lit init when it's populating properties from
427
+ // attributes, fall back to just the raw date if nothing is already set
428
+ this._maxSelectedDate = rawDate;
429
+ return;
430
+ }
431
+ const proposedDateMS = this.getMSFromString(rawDate);
432
+ const isValidDate = !Number.isNaN(proposedDateMS);
433
+ const isNotTooOld =
434
+ proposedDateMS >= this.getMSFromString(this.minSelectedDate);
435
+ if (isValidDate && isNotTooOld) {
436
+ this._maxSelectedDate = this.formatDate(proposedDateMS);
437
+ }
438
+ this.requestUpdate();
439
+ }
440
+
441
+ /** horizontal position of min date slider */
442
+ get minSliderX(): number {
443
+ const x = this.translateDateToPosition(this.minSelectedDate);
444
+ return this.validMinSliderX(x);
445
+ }
446
+
447
+ /** horizontal position of max date slider */
448
+ get maxSliderX(): number {
449
+ const maxSelectedDateMS = this.snapTimestamp(
450
+ this.getMSFromString(this.maxSelectedDate) + this.snapInterval
451
+ );
452
+ const x = this.translateDateToPosition(this.formatDate(maxSelectedDateMS));
453
+ return this.validMaxSliderX(x);
454
+ }
455
+
456
+ private get dateRangeMS(): number {
457
+ return this._maxDateMS - this._minDateMS;
458
+ }
459
+
460
+ private showTooltip(e: PointerEvent): void {
461
+ if (this._isDragging || this.disabled) {
462
+ return;
463
+ }
464
+
465
+ const target = e.currentTarget as SVGRectElement;
466
+ const x = target.x.baseVal.value + this.sliderWidth / 2;
467
+ const dataset = target.dataset as BarDataset;
468
+ const itemsText = `${this.tooltipLabel}${
469
+ dataset.numItems !== '1' ? 's' : ''
470
+ }`;
471
+ const formattedNumItems = Number(dataset.numItems).toLocaleString();
472
+
473
+ const tooltipPadding = 2;
474
+ const bufferHeight = 9;
475
+ const heightAboveHistogram = bufferHeight + this.tooltipHeight;
476
+ const histogramBounds = this.getBoundingClientRect();
477
+ const barX = histogramBounds.x + x;
478
+ const histogramY = histogramBounds.y;
479
+
480
+ // Center the tooltip horizontally along the bar
481
+ this._tooltipOffsetX =
482
+ barX -
483
+ tooltipPadding +
484
+ (this._binWidth - this.sliderWidth - this.tooltipWidth) / 2 +
485
+ window.scrollX;
486
+ // Place the tooltip (with arrow) just above the top of the histogram bars
487
+ this._tooltipOffsetY = histogramY - heightAboveHistogram + window.scrollY;
488
+
489
+ this._tooltipContent = html`
490
+ ${formattedNumItems} ${itemsText}<br />
491
+ ${dataset.tooltip}
492
+ `;
493
+ this._tooltip.showPopover?.();
494
+ }
495
+
496
+ private hideTooltip(): void {
497
+ this._tooltipContent = undefined;
498
+ this._tooltip.hidePopover?.();
499
+ }
500
+
501
+ // use arrow functions (rather than standard JS class instance methods) so
502
+ // that `this` is bound to the histogramDateRange object and not the event
503
+ // target. for more info see
504
+ // https://lit-element.polymer-project.org/guide/events#using-this-in-event-listeners
505
+ private drag = (e: PointerEvent): void => {
506
+ // prevent selecting text or other ranges while dragging, especially in Safari
507
+ e.preventDefault();
508
+ if (this.disabled) {
509
+ return;
510
+ }
511
+ this.setDragOffset(e);
512
+ this._isDragging = true;
513
+ this.addListeners();
514
+ this.cancelPendingUpdateEvent();
515
+ };
516
+
517
+ private drop = (): void => {
518
+ if (this._isDragging) {
519
+ this.removeListeners();
520
+ this.beginEmitUpdateProcess();
521
+ }
522
+ this._isDragging = false;
523
+ };
524
+
525
+ /**
526
+ * Adjust the date range based on slider movement
527
+ *
528
+ * @param e PointerEvent from the slider being moved
529
+ */
530
+ private move = (e: PointerEvent): void => {
531
+ const histogramClientX = this.getBoundingClientRect().x;
532
+ const newX = e.clientX - histogramClientX - this._dragOffset;
533
+ const slider = this._currentSlider as SVGRectElement;
534
+ if ((slider.id as SliderId) === 'slider-min') {
535
+ this.minSelectedDate = this.translatePositionToDate(
536
+ this.validMinSliderX(newX)
537
+ );
538
+ } else {
539
+ this.maxSelectedDate = this.translatePositionToDate(
540
+ this.validMaxSliderX(newX)
541
+ );
542
+ if (this.getMSFromString(this.maxSelectedDate) > this._maxDateMS) {
543
+ this.maxSelectedDate = this.maxDate;
544
+ }
545
+ }
546
+ };
547
+
548
+ /**
549
+ * Constrain a proposed value for the minimum (left) slider
550
+ *
551
+ * If the value is less than the leftmost valid position, then set it to the
552
+ * left edge of the histogram (ie the slider width). If the value is greater
553
+ * than the rightmost valid position (the position of the max slider), then
554
+ * set it to the position of the max slider
555
+ */
556
+ private validMinSliderX(newX: number): number {
557
+ // allow the left slider to go right only to the right slider, even if the
558
+ // max selected date is out of range
559
+ const rightLimit = Math.min(
560
+ this.translateDateToPosition(this.maxSelectedDate),
561
+ this.histogramRightEdgeX
562
+ );
563
+ newX = this.clamp(newX, this.histogramLeftEdgeX, rightLimit);
564
+ const isInvalid =
565
+ Number.isNaN(newX) || rightLimit < this.histogramLeftEdgeX;
566
+ return isInvalid ? this.histogramLeftEdgeX : newX;
567
+ }
568
+
569
+ /**
570
+ * Constrain a proposed value for the maximum (right) slider
571
+ *
572
+ * If the value is greater than the rightmost valid position, then set it to
573
+ * the right edge of the histogram (ie histogram width - slider width). If the
574
+ * value is less than the leftmost valid position (the position of the min
575
+ * slider), then set it to the position of the min slider
576
+ */
577
+ private validMaxSliderX(newX: number): number {
578
+ // allow the right slider to go left only to the left slider, even if the
579
+ // min selected date is out of range
580
+ const leftLimit = Math.max(
581
+ this.histogramLeftEdgeX,
582
+ this.translateDateToPosition(this.minSelectedDate)
583
+ );
584
+ newX = this.clamp(newX, leftLimit, this.histogramRightEdgeX);
585
+ const isInvalid =
586
+ Number.isNaN(newX) || leftLimit > this.histogramRightEdgeX;
587
+ return isInvalid ? this.histogramRightEdgeX : newX;
588
+ }
589
+
590
+ private addListeners(): void {
591
+ window.addEventListener('pointermove', this.move);
592
+ window.addEventListener('pointerup', this.drop);
593
+ window.addEventListener('pointercancel', this.drop);
594
+ }
595
+
596
+ private removeListeners(): void {
597
+ window.removeEventListener('pointermove', this.move);
598
+ window.removeEventListener('pointerup', this.drop);
599
+ window.removeEventListener('pointercancel', this.drop);
600
+ }
601
+
602
+ /**
603
+ * start a timer to emit an update event. this timer can be canceled (and the
604
+ * event not emitted) if user drags a slider or focuses a date input within
605
+ * the update delay
606
+ */
607
+ private beginEmitUpdateProcess(): void {
608
+ this.cancelPendingUpdateEvent();
609
+ this._emitUpdatedEventTimer = setTimeout(() => {
610
+ if (this.currentDateRangeString === this._previousDateRange) {
611
+ // don't emit duplicate event if no change since last emitted event
612
+ return;
613
+ }
614
+ this._previousDateRange = this.currentDateRangeString;
615
+ const options = {
616
+ detail: {
617
+ minDate: this.minSelectedDate,
618
+ maxDate: this.maxSelectedDate,
619
+ },
620
+ bubbles: true,
621
+ composed: true,
622
+ };
623
+ this.dispatchEvent(new CustomEvent('histogramDateRangeUpdated', options));
624
+ }, this.updateDelay);
625
+ }
626
+
627
+ private cancelPendingUpdateEvent(): void {
628
+ if (this._emitUpdatedEventTimer === undefined) {
629
+ return;
630
+ }
631
+ clearTimeout(this._emitUpdatedEventTimer);
632
+ this._emitUpdatedEventTimer = undefined;
633
+ }
634
+
635
+ /**
636
+ * find position of pointer in relation to the current slider
637
+ */
638
+ private setDragOffset(e: PointerEvent): void {
639
+ this._currentSlider = e.currentTarget as SVGRectElement;
640
+ const sliderX =
641
+ (this._currentSlider.id as SliderId) === 'slider-min'
642
+ ? this.minSliderX
643
+ : this.maxSliderX;
644
+ const histogramClientX = this.getBoundingClientRect().x;
645
+ this._dragOffset = e.clientX - histogramClientX - sliderX;
646
+ }
647
+
648
+ /**
649
+ * @param x horizontal position of slider
650
+ * @returns string representation of date
651
+ */
652
+ private translatePositionToDate(x: number): string {
653
+ // Snap to the nearest second, fixing the case where input like 1/1/2010
654
+ // would get translated to 12/31/2009 due to slight discrepancies from
655
+ // pixel boundaries and floating point error.
656
+ const milliseconds = this.snapToNextSecond(
657
+ ((x - this.sliderWidth) * this.dateRangeMS) / this._histWidth
658
+ );
659
+ return this.formatDate(this._minDateMS + milliseconds);
660
+ }
661
+
662
+ /**
663
+ * Returns slider x-position corresponding to given date
664
+ *
665
+ * @param date
666
+ * @returns x-position of slider
667
+ */
668
+ private translateDateToPosition(date: string): number {
669
+ const milliseconds = this.getMSFromString(date);
670
+ return (
671
+ this.sliderWidth +
672
+ ((milliseconds - this._minDateMS) * this._histWidth) / this.dateRangeMS
673
+ );
674
+ }
675
+
676
+ /** ensure that the returned value is between minValue and maxValue */
677
+ private clamp(x: number, minValue: number, maxValue: number): number {
678
+ return Math.min(Math.max(x, minValue), maxValue);
679
+ }
680
+
681
+ private handleInputFocus(): void {
682
+ if (!this.updateWhileFocused) {
683
+ this.cancelPendingUpdateEvent();
684
+ }
685
+ }
686
+
687
+ private handleMinDateInput(e: Event): void {
688
+ const target = e.currentTarget as HTMLInputElement;
689
+ if (target.value !== this.minSelectedDate) {
690
+ this.minSelectedDate = target.value;
691
+ this.beginEmitUpdateProcess();
692
+ }
693
+ }
694
+
695
+ private handleMaxDateInput(e: Event): void {
696
+ const target = e.currentTarget as HTMLInputElement;
697
+ if (target.value !== this.maxSelectedDate) {
698
+ this.maxSelectedDate = target.value;
699
+ this.beginEmitUpdateProcess();
700
+ }
701
+ }
702
+
703
+ private handleKeyUp(e: KeyboardEvent): void {
704
+ if (e.key === 'Enter') {
705
+ const target = e.currentTarget as HTMLInputElement;
706
+ target.blur();
707
+ if (target.id === 'date-min') {
708
+ this.handleMinDateInput(e);
709
+ } else if (target.id === 'date-max') {
710
+ this.handleMaxDateInput(e);
711
+ }
712
+ }
713
+ }
714
+
715
+ private get currentDateRangeString(): string {
716
+ return `${this.minSelectedDate}:${this.maxSelectedDate}`;
717
+ }
718
+
719
+ private getMSFromString(date: unknown): number {
720
+ // It's possible that `date` is not a string in certain situations.
721
+ // For instance if you use LitElement bindings and the date is `2000`,
722
+ // it will be treated as a number instead of a string. This just makes sure
723
+ // we're dealing with a string.
724
+ const stringified = typeof date === 'string' ? date : String(date);
725
+ const digitGroupCount = (stringified.split(/(\d+)/).length - 1) / 2;
726
+ if (digitGroupCount === 1) {
727
+ // if there's just a single set of digits, assume it's a year
728
+ const dateObj = new Date(0, 0); // start at January 1, 1900
729
+ dateObj.setFullYear(Number(stringified)); // override year
730
+ return dateObj.getTime(); // get time in milliseconds
731
+ }
732
+ return dayjs(stringified, [this.dateFormat, DATE_FORMAT]).valueOf();
733
+ }
734
+
735
+ /**
736
+ * expand or narrow the selected range by moving the slider nearest the
737
+ * clicked bar to the outer edge of the clicked bar
738
+ *
739
+ * @param e Event click event from a histogram bar
740
+ */
741
+ private handleBarClick(e: Event): void {
742
+ const dataset = (e.currentTarget as SVGRectElement).dataset as BarDataset;
743
+ // use the midpoint of the width of the clicked bar to determine which is
744
+ // the nearest slider
745
+ const clickPosition =
746
+ (this.getMSFromString(dataset.binStart) +
747
+ this.getMSFromString(dataset.binEnd)) /
748
+ 2;
749
+ const distanceFromMinSlider = Math.abs(
750
+ clickPosition - this.getMSFromString(this.minSelectedDate)
751
+ );
752
+ const distanceFromMaxSlider = Math.abs(
753
+ clickPosition - this.getMSFromString(this.maxSelectedDate)
754
+ );
755
+ // update the selected range by moving the nearer slider
756
+ if (distanceFromMinSlider < distanceFromMaxSlider) {
757
+ this.minSelectedDate = dataset.binStart;
758
+ } else {
759
+ this.maxSelectedDate = dataset.binEnd;
760
+ }
761
+ this.beginEmitUpdateProcess();
762
+ }
763
+
764
+ private get minSliderTemplate(): SVGTemplateResult {
765
+ // width/height in pixels of curved part of the sliders (like
766
+ // border-radius); used as part of a SVG quadratic curve. see
767
+ // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#curve_commands
768
+ const cs = SLIDER_CORNER_SIZE;
769
+
770
+ const sliderShape = `
771
+ M${this.minSliderX},0
772
+ h-${this.sliderWidth - cs}
773
+ q-${cs},0 -${cs},${cs}
774
+ v${this.height - cs * 2}
775
+ q0,${cs} ${cs},${cs}
776
+ h${this.sliderWidth - cs}
777
+ `;
778
+ return this.generateSliderSVG(this.minSliderX, 'slider-min', sliderShape);
779
+ }
780
+
781
+ private get maxSliderTemplate(): SVGTemplateResult {
782
+ const cs = SLIDER_CORNER_SIZE;
783
+ const sliderShape = `
784
+ M${this.maxSliderX},0
785
+ h${this.sliderWidth - cs}
786
+ q${cs},0 ${cs},${cs}
787
+ v${this.height - cs * 2}
788
+ q0,${cs} -${cs},${cs}
789
+ h-${this.sliderWidth - cs}
790
+ `;
791
+ return this.generateSliderSVG(this.maxSliderX, 'slider-max', sliderShape);
792
+ }
793
+
794
+ private generateSliderSVG(
795
+ sliderPositionX: number,
796
+ id: SliderId,
797
+ sliderShape: string
798
+ ): SVGTemplateResult {
799
+ // whether the curved part of the slider is facing towards the left (1), ie
800
+ // minimum, or facing towards the right (-1), ie maximum
801
+ const k = id === 'slider-min' ? 1 : -1;
802
+
803
+ const sliderClasses = classMap({
804
+ slider: true,
805
+ draggable: !this.disabled,
806
+ dragging: this._isDragging,
807
+ });
808
+
809
+ return svg`
810
+ <svg
811
+ id=${id}
812
+ class=${sliderClasses}
813
+ @pointerdown=${this.drag}
814
+ >
815
+ <path d="${sliderShape} z" fill="${sliderColor}" />
816
+ <rect
817
+ x="${
818
+ sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.4 * k
819
+ }"
820
+ y="${this.height / 3}"
821
+ width="1"
822
+ height="${this.height / 3}"
823
+ fill="white"
824
+ />
825
+ <rect
826
+ x="${
827
+ sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.6 * k
828
+ }"
829
+ y="${this.height / 3}"
830
+ width="1"
831
+ height="${this.height / 3}"
832
+ fill="white"
833
+ />
834
+ </svg>
835
+ `;
836
+ }
837
+
838
+ get selectedRangeTemplate(): SVGTemplateResult {
839
+ return svg`
840
+ <rect
841
+ x="${this.minSliderX}"
842
+ y="0"
843
+ width="${this.maxSliderX - this.minSliderX}"
844
+ height="${this.height}"
845
+ fill="${selectedRangeColor}"
846
+ />`;
847
+ }
848
+
849
+ get histogramTemplate(): SVGTemplateResult[] {
850
+ const xScale = this._histWidth / this._numBins;
851
+ const barWidth = xScale - 1;
852
+ let x = this.sliderWidth; // start at the left edge of the histogram
853
+
854
+ return this._histData.map(data => {
855
+ const { minSelectedDate, maxSelectedDate } = this;
856
+ const barHeight = data.height;
857
+
858
+ const binIsBeforeMin = this.isBefore(data.binEnd, minSelectedDate);
859
+ const binIsAfterMax = this.isAfter(data.binStart, maxSelectedDate);
860
+ const barFill =
861
+ binIsBeforeMin || binIsAfterMax ? barExcludedFill : barIncludedFill;
862
+
863
+ // the stroke-dasharray style below creates a transparent border around the
864
+ // right edge of the bar, which prevents user from encountering a gap
865
+ // between adjacent bars (eg when viewing the tooltips or when trying to
866
+ // extend the range by clicking on a bar)
867
+ const barStyle = `stroke-dasharray: 0 ${barWidth} ${barHeight} ${barWidth} 0 ${barHeight}`;
868
+
869
+ const bar = svg`
870
+ <rect
871
+ class="bar-pointer-target"
872
+ x=${x}
873
+ y="0"
874
+ width=${barWidth}
875
+ height=${this.height}
876
+ @pointerenter=${this.showTooltip}
877
+ @pointerleave=${this.hideTooltip}
878
+ @click=${this.handleBarClick}
879
+ fill="transparent"
880
+ data-num-items=${data.value}
881
+ data-bin-start=${data.binStart}
882
+ data-bin-end=${data.binEnd}
883
+ data-tooltip=${data.tooltip}
884
+ />
885
+ <rect
886
+ class="bar"
887
+ style=${barStyle}
888
+ x=${x}
889
+ y=${this.height - barHeight}
890
+ width=${barWidth}
891
+ height=${barHeight}
892
+ fill=${barFill}
893
+ />`;
894
+ x += xScale;
895
+ return bar;
896
+ });
897
+ }
898
+
899
+ /** Whether the first arg represents a date strictly before the second arg */
900
+ private isBefore(date1: string, date2: string): boolean {
901
+ const date1MS = this.getMSFromString(date1);
902
+ const date2MS = this.getMSFromString(date2);
903
+ return date1MS < date2MS;
904
+ }
905
+
906
+ /** Whether the first arg represents a date strictly after the second arg */
907
+ private isAfter(date1: string, date2: string): boolean {
908
+ const date1MS = this.getMSFromString(date1);
909
+ const date2MS = this.getMSFromString(date2);
910
+ return date1MS > date2MS;
911
+ }
912
+
913
+ private formatDate(dateMS: number, format: string = this.dateFormat): string {
914
+ if (Number.isNaN(dateMS)) {
915
+ return '';
916
+ }
917
+ const date = dayjs(dateMS);
918
+ if (date.year() < 1000) {
919
+ // years before 1000 don't play well with dayjs custom formatting, so work around dayjs
920
+ // by setting the year to a sentinel value and then replacing it instead.
921
+ // this is a bit hacky but it does the trick for essentially all reasonable cases
922
+ // until such time as we replace dayjs.
923
+ const tmpDate = date.year(199999);
924
+ return tmpDate.format(format).replace(/199999/g, date.year().toString());
925
+ }
926
+ return date.format(format);
927
+ }
928
+
929
+ /**
930
+ * NOTE: we are relying on the lit `live` directive in the template to
931
+ * ensure that the change to minSelectedDate is noticed and the input value
932
+ * gets properly re-rendered. see
933
+ * https://lit.dev/docs/templates/directives/#live
934
+ */
935
+ get minInputTemplate(): TemplateResult {
936
+ return html`
937
+ <input
938
+ id="date-min"
939
+ placeholder=${this.dateFormat}
940
+ type="text"
941
+ @focus=${this.handleInputFocus}
942
+ @blur=${this.handleMinDateInput}
943
+ @keyup=${this.handleKeyUp}
944
+ .value=${live(this.minSelectedDate)}
945
+ ?disabled=${this.disabled}
946
+ />
947
+ `;
948
+ }
949
+
950
+ get maxInputTemplate(): TemplateResult {
951
+ return html`
952
+ <input
953
+ id="date-max"
954
+ placeholder=${this.dateFormat}
955
+ type="text"
956
+ @focus=${this.handleInputFocus}
957
+ @blur=${this.handleMaxDateInput}
958
+ @keyup=${this.handleKeyUp}
959
+ .value=${live(this.maxSelectedDate)}
960
+ ?disabled=${this.disabled}
961
+ />
962
+ `;
963
+ }
964
+
965
+ get minLabelTemplate(): TemplateResult {
966
+ return html`<label for="date-min" class="sr-only">Minimum date:</label>`;
967
+ }
968
+
969
+ get maxLabelTemplate(): TemplateResult {
970
+ return html`<label for="date-max" class="sr-only">Maximum date:</label>`;
971
+ }
972
+
973
+ get tooltipTemplate(): TemplateResult {
974
+ const styles = styleMap({
975
+ width: `${this.tooltipWidth}px`,
976
+ height: `${this.tooltipHeight}px`,
977
+ top: `${this._tooltipOffsetY}px`,
978
+ left: `${this._tooltipOffsetX}px`,
979
+ });
980
+
981
+ return html`
982
+ <div id="tooltip" style=${styles} popover>${this._tooltipContent}</div>
983
+ `;
984
+ }
985
+
986
+ private get histogramAccessibilityTemplate(): TemplateResult {
987
+ let rangeText: string = '';
988
+ if (this.minSelectedDate && this.maxSelectedDate) {
989
+ rangeText = ` from ${this.minSelectedDate} to ${this.maxSelectedDate}`;
990
+ } else if (this.minSelectedDate) {
991
+ rangeText = ` from ${this.minSelectedDate}`;
992
+ } else if (this.maxSelectedDate) {
993
+ rangeText = ` up to ${this.maxSelectedDate}`;
994
+ }
995
+
996
+ const titleText = `Filter results for dates${rangeText}`;
997
+ const descText = `This histogram shows the distribution of dates${rangeText}`;
998
+
999
+ return html`<title id="histogram-title">${titleText}</title
1000
+ ><desc id="histogram-desc">${descText}</desc>`;
1001
+ }
1002
+
1003
+ private get noDataTemplate(): TemplateResult {
1004
+ return html`
1005
+ <div class="missing-data-message">${this.missingDataMessage}</div>
1006
+ `;
1007
+ }
1008
+
1009
+ private get activityIndicatorTemplate(): TemplateResult | typeof nothing {
1010
+ if (!this.loading) {
1011
+ return nothing;
1012
+ }
1013
+ return html`
1014
+ <ia-activity-indicator mode="processing"> </ia-activity-indicator>
1015
+ `;
1016
+ }
1017
+
1018
+ static styles = css`
1019
+ .missing-data-message {
1020
+ text-align: center;
1021
+ }
1022
+ #container {
1023
+ margin: 0;
1024
+ touch-action: none;
1025
+ position: relative;
1026
+ }
1027
+ .disabled {
1028
+ opacity: 0.3;
1029
+ }
1030
+ ia-activity-indicator {
1031
+ position: absolute;
1032
+ left: calc(50% - 10px);
1033
+ top: 10px;
1034
+ width: 20px;
1035
+ height: 20px;
1036
+ --activityIndicatorLoadingDotColor: rgba(0, 0, 0, 0);
1037
+ --activityIndicatorLoadingRingColor: ${activityIndicatorColor};
1038
+ }
1039
+
1040
+ /* prevent selection from interfering with tooltip, especially on mobile */
1041
+ /* https://stackoverflow.com/a/4407335/1163042 */
1042
+ .noselect {
1043
+ -webkit-touch-callout: none; /* iOS Safari */
1044
+ -webkit-user-select: none; /* Safari */
1045
+ -moz-user-select: none; /* Old versions of Firefox */
1046
+ -ms-user-select: none; /* Internet Explorer/Edge */
1047
+ user-select: none; /* current Chrome, Edge, Opera and Firefox */
1048
+ }
1049
+ .bar,
1050
+ .bar-pointer-target {
1051
+ /* create a transparent border around the hist bars to prevent "gaps" and
1052
+ flickering when moving around between bars. this also helps with handling
1053
+ clicks on the bars, preventing users from being able to click in between
1054
+ bars */
1055
+ stroke: rgba(0, 0, 0, 0);
1056
+ /* ensure transparent stroke wide enough to cover gap between bars */
1057
+ stroke-width: 2px;
1058
+ }
1059
+ .bar {
1060
+ /* ensure the bar's pointer target receives events, not the bar itself */
1061
+ pointer-events: none;
1062
+ }
1063
+ .bar-pointer-target:hover + .bar {
1064
+ /* highlight currently hovered bar */
1065
+ fill-opacity: 0.7;
1066
+ }
1067
+ .disabled .bar-pointer-target:hover + .bar {
1068
+ /* ensure no visual hover interaction when disabled */
1069
+ fill-opacity: 1;
1070
+ }
1071
+ /****** histogram ********/
1072
+ #tooltip {
1073
+ position: absolute;
1074
+ background: ${tooltipBackgroundColor};
1075
+ margin: 0;
1076
+ border: 0;
1077
+ color: ${tooltipTextColor};
1078
+ text-align: center;
1079
+ border-radius: 3px;
1080
+ padding: 2px;
1081
+ font-size: ${tooltipFontSize};
1082
+ font-family: ${tooltipFontFamily};
1083
+ touch-action: none;
1084
+ pointer-events: none;
1085
+ overflow: visible;
1086
+ }
1087
+ #tooltip:after {
1088
+ content: '';
1089
+ position: absolute;
1090
+ margin-left: -5px;
1091
+ top: 100%;
1092
+ left: 50%;
1093
+ /* arrow */
1094
+ border: 5px solid ${tooltipTextColor};
1095
+ border-color: ${tooltipBackgroundColor} transparent transparent
1096
+ transparent;
1097
+ }
1098
+ /****** slider ********/
1099
+ .slider {
1100
+ shape-rendering: crispEdges; /* So the slider doesn't get blurry if dragged between pixels */
1101
+ }
1102
+ .draggable:hover {
1103
+ cursor: grab;
1104
+ }
1105
+ .dragging {
1106
+ cursor: grabbing !important;
1107
+ }
1108
+ /****** inputs ********/
1109
+ #inputs {
1110
+ display: flex;
1111
+ justify-content: center;
1112
+ margin: ${inputRowMargin};
1113
+ }
1114
+ #inputs .dash {
1115
+ position: relative;
1116
+ bottom: -1px;
1117
+ align-self: center; /* Otherwise the dash sticks to the top while the inputs grow */
1118
+ }
1119
+ input {
1120
+ width: ${inputWidth};
1121
+ margin: 0 3px;
1122
+ border: ${inputBorder};
1123
+ border-radius: 2px !important;
1124
+ text-align: center;
1125
+ font-size: ${inputFontSize};
1126
+ font-family: ${inputFontFamily};
1127
+ }
1128
+ .sr-only {
1129
+ position: absolute !important;
1130
+ width: 1px !important;
1131
+ height: 1px !important;
1132
+ margin: 0 !important;
1133
+ padding: 0 !important;
1134
+ border: 0 !important;
1135
+ overflow: hidden !important;
1136
+ white-space: nowrap !important;
1137
+ clip: rect(1px, 1px, 1px, 1px) !important;
1138
+ -webkit-clip-path: inset(50%) !important;
1139
+ clip-path: inset(50%) !important;
1140
+ }
1141
+ `;
1142
+
1143
+ render(): TemplateResult {
1144
+ if (!this.hasBinData) {
1145
+ return this.noDataTemplate;
1146
+ }
1147
+ return html`
1148
+ <div
1149
+ id="container"
1150
+ class="
1151
+ noselect
1152
+ ${this._isDragging ? 'dragging' : ''}
1153
+ "
1154
+ style="width: ${this.width}px"
1155
+ >
1156
+ ${this.activityIndicatorTemplate} ${this.tooltipTemplate}
1157
+ <div
1158
+ class="inner-container
1159
+ ${this.disabled ? 'disabled' : ''}"
1160
+ >
1161
+ <svg
1162
+ width="${this.width}"
1163
+ height="${this.height}"
1164
+ aria-labelledby="histogram-title histogram-desc"
1165
+ @pointerleave="${this.drop}"
1166
+ >
1167
+ ${this.histogramAccessibilityTemplate} ${this.selectedRangeTemplate}
1168
+ <svg id="histogram">${this.histogramTemplate}</svg>
1169
+ ${this.minSliderTemplate} ${this.maxSliderTemplate}
1170
+ </svg>
1171
+ <div id="inputs">
1172
+ ${this.minLabelTemplate} ${this.minInputTemplate}
1173
+ <div class="dash">-</div>
1174
+ ${this.maxLabelTemplate} ${this.maxInputTemplate}
1175
+ <slot name="inputs-right-side"></slot>
1176
+ </div>
1177
+ </div>
1178
+ </div>
1179
+ `;
1180
+ }
1181
+ }
1182
+
1183
+ // help TypeScript provide strong typing when interacting with DOM APIs
1184
+ // https://stackoverflow.com/questions/65148695/lit-element-typescript-project-global-interface-declaration-necessary
1185
+ declare global {
1186
+ interface HTMLElementTagNameMap {
1187
+ 'histogram-date-range': HistogramDateRange;
1188
+ }
1189
+ }