@internetarchive/histogram-date-range 1.0.0 → 1.0.1-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,920 +1,922 @@
1
- import {
2
- css,
3
- html,
4
- nothing,
5
- LitElement,
6
- PropertyValues,
7
- svg,
8
- SVGTemplateResult,
9
- TemplateResult,
10
- } from 'lit';
11
- import { property, state, customElement } from 'lit/decorators.js';
12
- import { live } from 'lit/directives/live.js';
13
- import '@internetarchive/ia-activity-indicator/ia-activity-indicator';
14
-
15
- /* eslint-disable-next-line */
16
- /* @ts-ignore Import module -- JS, so no types */
17
- import dayjs from 'https://esm.archive.org/dayjs@^1.10.7';
18
- /* eslint-disable-next-line */
19
- /* @ts-ignore Import module -- JS, so no types */
20
- import customParseFormat from 'https://esm.archive.org/dayjs@1.9.4/esm/plugin/customParseFormat';
21
- // NOTE: using a specific *earlier* pegged commit for the plugin ^, because esm.archive.org has a
22
- // problem creating later versions where the `export` of an included `utils.js` gets mangled. Eg:
23
- // https://github.com/internetarchive/esbuild_es5/commit/ce19e8b841282c0e94d2b8e6830fd7744b2216c2#diff-4b2ed47327851d566740a30ce5f60271c059ae67eff2006bc07bb7c4fcee8b50L296
24
-
25
- dayjs.extend(customParseFormat);
26
-
27
- // these values can be overridden via the component's HTML (camelCased) attributes
28
- const WIDTH = 180;
29
- const HEIGHT = 40;
30
- const SLIDER_WIDTH = 10;
31
- const TOOLTIP_WIDTH = 125;
32
- const TOOLTIP_HEIGHT = 30;
33
- const DATE_FORMAT = 'YYYY';
34
- const MISSING_DATA = 'no data';
35
- const UPDATE_DEBOUNCE_DELAY_MS = 0;
36
-
37
- // this constant is not set up to be overridden
38
- const SLIDER_CORNER_SIZE = 4;
39
-
40
- // these CSS custom props can be overridden from the HTML that is invoking this component
41
- const sliderColor = css`var(--histogramDateRangeSliderColor, #4B65FE)`;
42
- const selectedRangeColor = css`var(--histogramDateRangeSelectedRangeColor, #DBE0FF)`;
43
- const barIncludedFill = css`var(--histogramDateRangeBarIncludedFill, #2C2C2C)`;
44
- const activityIndicatorColor = css`var(--histogramDateRangeActivityIndicator, #2C2C2C)`;
45
- const barExcludedFill = css`var(--histogramDateRangeBarExcludedFill, #CCCCCC)`;
46
- const inputRowMargin = css`var(--histogramDateRangeInputRowMargin, 0)`;
47
- const inputBorder = css`var(--histogramDateRangeInputBorder, 0.5px solid #2C2C2C)`;
48
- const inputWidth = css`var(--histogramDateRangeInputWidth, 35px)`;
49
- const inputFontSize = css`var(--histogramDateRangeInputFontSize, 1.2rem)`;
50
- const inputFontFamily = css`var(--histogramDateRangeInputFontFamily, sans-serif)`;
51
- const tooltipBackgroundColor = css`var(--histogramDateRangeTooltipBackgroundColor, #2C2C2C)`;
52
- const tooltipTextColor = css`var(--histogramDateRangeTooltipTextColor, #FFFFFF)`;
53
- const tooltipFontSize = css`var(--histogramDateRangeTooltipFontSize, 1.1rem)`;
54
- const tooltipFontFamily = css`var(--histogramDateRangeTooltipFontFamily, sans-serif)`;
55
-
56
- type SliderId = 'slider-min' | 'slider-max';
57
-
58
- interface HistogramItem {
59
- value: number;
60
- height: number;
61
- binStart: string;
62
- binEnd: string;
63
- }
64
-
65
- interface BarDataset extends DOMStringMap {
66
- numItems: string;
67
- binStart: string;
68
- binEnd: string;
69
- }
70
-
71
- @customElement('histogram-date-range')
72
- export class HistogramDateRange extends LitElement {
73
- /* eslint-disable lines-between-class-members */
74
-
75
- // public reactive properties that can be set via HTML attributes
76
- @property({ type: Number }) width = WIDTH;
77
- @property({ type: Number }) height = HEIGHT;
78
- @property({ type: Number }) sliderWidth = SLIDER_WIDTH;
79
- @property({ type: Number }) tooltipWidth = TOOLTIP_WIDTH;
80
- @property({ type: Number }) tooltipHeight = TOOLTIP_HEIGHT;
81
- @property({ type: Number }) updateDelay = UPDATE_DEBOUNCE_DELAY_MS;
82
- @property({ type: String }) dateFormat = DATE_FORMAT;
83
- @property({ type: String }) missingDataMessage = MISSING_DATA;
84
- @property({ type: String }) minDate = '';
85
- @property({ type: String }) maxDate = '';
86
- @property({ type: Boolean }) disabled = false;
87
- @property({ type: Object }) bins: number[] = [];
88
- /** If true, update events will not be canceled by the date inputs receiving focus */
89
- @property({ type: Boolean }) updateWhileFocused = false;
90
-
91
- // internal reactive properties not exposed as attributes
92
- @state() private _tooltipOffset = 0;
93
- @state() private _tooltipContent?: TemplateResult;
94
- @state() private _tooltipVisible = false;
95
- @state() private _isDragging = false;
96
- @state() private _isLoading = false;
97
-
98
- // non-reactive properties (changes don't auto-trigger re-rendering)
99
- private _minSelectedDate = '';
100
- private _maxSelectedDate = '';
101
- private _minDateMS = 0;
102
- private _maxDateMS = 0;
103
- private _dragOffset = 0;
104
- private _histWidth = 0;
105
- private _binWidth = 0;
106
- private _currentSlider?: SVGRectElement;
107
- private _histData: HistogramItem[] = [];
108
- private _emitUpdatedEventTimer?: ReturnType<typeof setTimeout>;
109
- private _previousDateRange = '';
110
-
111
- /* eslint-enable lines-between-class-members */
112
-
113
- disconnectedCallback(): void {
114
- this.removeListeners();
115
- super.disconnectedCallback();
116
- }
117
-
118
- updated(changedProps: PropertyValues): void {
119
- // check for changes that would affect bin data calculations
120
- if (
121
- changedProps.has('bins') ||
122
- changedProps.has('minDate') ||
123
- changedProps.has('maxDate') ||
124
- changedProps.has('minSelectedDate') ||
125
- changedProps.has('maxSelectedDate')
126
- ) {
127
- this.handleDataUpdate();
128
- }
129
- }
130
-
131
- /**
132
- * Set private properties that depend on the attribute bin data
133
- *
134
- * We're caching these values and not using getters to avoid recalculating all
135
- * of the hist data every time the user drags a slider or hovers over a bar
136
- * creating a tooltip.
137
- */
138
- private handleDataUpdate(): void {
139
- if (!this.hasBinData) {
140
- return;
141
- }
142
- this._histWidth = this.width - this.sliderWidth * 2;
143
- this._minDateMS = this.getMSFromString(this.minDate);
144
- this._maxDateMS = this.getMSFromString(this.maxDate);
145
- this._binWidth = this._histWidth / this._numBins;
146
- this._previousDateRange = this.currentDateRangeString;
147
- this._histData = this.calculateHistData();
148
- this.minSelectedDate = this.minSelectedDate
149
- ? this.minSelectedDate
150
- : this.minDate;
151
- this.maxSelectedDate = this.maxSelectedDate
152
- ? this.maxSelectedDate
153
- : this.maxDate;
154
- this.requestUpdate();
155
- }
156
-
157
- private calculateHistData(): HistogramItem[] {
158
- const minValue = Math.min(...this.bins);
159
- const maxValue = Math.max(...this.bins);
160
- // if there is no difference between the min and max values, use a range of
161
- // 1 because log scaling will fail if the range is 0
162
- const valueRange = minValue === maxValue ? 1 : Math.log1p(maxValue);
163
- const valueScale = this.height / valueRange;
164
- const dateScale = this.dateRangeMS / this._numBins;
165
- return this.bins.map((v: number, i: number) => {
166
- return {
167
- value: v,
168
- // use log scaling for the height of the bar to prevent tall bars from
169
- // making the smaller ones too small to see
170
- height: Math.floor(Math.log1p(v) * valueScale),
171
- binStart: `${this.formatDate(i * dateScale + this._minDateMS)}`,
172
- binEnd: `${this.formatDate((i + 1) * dateScale + this._minDateMS)}`,
173
- };
174
- });
175
- }
176
-
177
- private get hasBinData(): boolean {
178
- return this._numBins > 0;
179
- }
180
-
181
- private get _numBins(): number {
182
- if (!this.bins || !this.bins.length) {
183
- return 0;
184
- }
185
- return this.bins.length;
186
- }
187
-
188
- private get histogramLeftEdgeX(): number {
189
- return this.sliderWidth;
190
- }
191
-
192
- private get histogramRightEdgeX(): number {
193
- return this.width - this.sliderWidth;
194
- }
195
-
196
- /** component's loading (and disabled) state */
197
- @property({ type: Boolean }) get loading(): boolean {
198
- return this._isLoading;
199
- }
200
-
201
- set loading(value: boolean) {
202
- this.disabled = value;
203
- this._isLoading = value;
204
- }
205
-
206
- /** formatted minimum date of selected date range */
207
- @property() get minSelectedDate(): string {
208
- return this.formatDate(this.getMSFromString(this._minSelectedDate));
209
- }
210
-
211
- /** updates minSelectedDate if new date is valid */
212
- set minSelectedDate(rawDate: string) {
213
- if (!this._minSelectedDate) {
214
- // because the values needed to calculate valid max/min values are not
215
- // available during the lit init when it's populating properties from
216
- // attributes, fall back to just the raw date if nothing is already set
217
- this._minSelectedDate = rawDate;
218
- return;
219
- }
220
- const proposedDateMS = this.getMSFromString(rawDate);
221
- const isValidDate = !Number.isNaN(proposedDateMS);
222
- const isNotTooRecent =
223
- proposedDateMS <= this.getMSFromString(this.maxSelectedDate);
224
- if (isValidDate && isNotTooRecent) {
225
- this._minSelectedDate = this.formatDate(proposedDateMS);
226
- }
227
- this.requestUpdate();
228
- }
229
-
230
- /** formatted maximum date of selected date range */
231
- @property() get maxSelectedDate(): string {
232
- return this.formatDate(this.getMSFromString(this._maxSelectedDate));
233
- }
234
-
235
- /** updates maxSelectedDate if new date is valid */
236
- set maxSelectedDate(rawDate: string) {
237
- if (!this._maxSelectedDate) {
238
- // because the values needed to calculate valid max/min values are not
239
- // available during the lit init when it's populating properties from
240
- // attributes, fall back to just the raw date if nothing is already set
241
- this._maxSelectedDate = rawDate;
242
- return;
243
- }
244
- const proposedDateMS = this.getMSFromString(rawDate);
245
- const isValidDate = !Number.isNaN(proposedDateMS);
246
- const isNotTooOld =
247
- proposedDateMS >= this.getMSFromString(this.minSelectedDate);
248
- if (isValidDate && isNotTooOld) {
249
- this._maxSelectedDate = this.formatDate(proposedDateMS);
250
- }
251
- this.requestUpdate();
252
- }
253
-
254
- /** horizontal position of min date slider */
255
- get minSliderX(): number {
256
- const x = this.translateDateToPosition(this.minSelectedDate);
257
- return this.validMinSliderX(x);
258
- }
259
-
260
- /** horizontal position of max date slider */
261
- get maxSliderX(): number {
262
- const x = this.translateDateToPosition(this.maxSelectedDate);
263
- return this.validMaxSliderX(x);
264
- }
265
-
266
- private get dateRangeMS(): number {
267
- return this._maxDateMS - this._minDateMS;
268
- }
269
-
270
- private showTooltip(e: PointerEvent): void {
271
- if (this._isDragging || this.disabled) {
272
- return;
273
- }
274
- const target = e.currentTarget as SVGRectElement;
275
- const x = target.x.baseVal.value + this.sliderWidth / 2;
276
- const dataset = target.dataset as BarDataset;
277
- const itemsText = `item${dataset.numItems !== '1' ? 's' : ''}`;
278
- const formattedNumItems = Number(dataset.numItems).toLocaleString();
279
-
280
- this._tooltipOffset =
281
- x + (this._binWidth - this.sliderWidth - this.tooltipWidth) / 2;
282
-
283
- this._tooltipContent = html`
284
- ${formattedNumItems} ${itemsText}<br />
285
- ${dataset.binStart} - ${dataset.binEnd}
286
- `;
287
- this._tooltipVisible = true;
288
- }
289
-
290
- private hideTooltip(): void {
291
- this._tooltipContent = undefined;
292
- this._tooltipVisible = false;
293
- }
294
-
295
- // use arrow functions (rather than standard JS class instance methods) so
296
- // that `this` is bound to the histogramDateRange object and not the event
297
- // target. for more info see
298
- // https://lit-element.polymer-project.org/guide/events#using-this-in-event-listeners
299
- private drag = (e: PointerEvent): void => {
300
- // prevent selecting text or other ranges while dragging, especially in Safari
301
- e.preventDefault();
302
- if (this.disabled) {
303
- return;
304
- }
305
- this.setDragOffset(e);
306
- this._isDragging = true;
307
- this.addListeners();
308
- this.cancelPendingUpdateEvent();
309
- };
310
-
311
- private drop = (): void => {
312
- if (this._isDragging) {
313
- this.removeListeners();
314
- this.beginEmitUpdateProcess();
315
- }
316
- this._isDragging = false;
317
- };
318
-
319
- /**
320
- * Adjust the date range based on slider movement
321
- *
322
- * @param e PointerEvent from the slider being moved
323
- */
324
- private move = (e: PointerEvent): void => {
325
- const histogramClientX = this.getBoundingClientRect().x;
326
- const newX = e.clientX - histogramClientX - this._dragOffset;
327
- const slider = this._currentSlider as SVGRectElement;
328
- if ((slider.id as SliderId) === 'slider-min') {
329
- this.minSelectedDate = this.translatePositionToDate(
330
- this.validMinSliderX(newX)
331
- );
332
- } else {
333
- this.maxSelectedDate = this.translatePositionToDate(
334
- this.validMaxSliderX(newX)
335
- );
336
- }
337
- };
338
-
339
- /**
340
- * Constrain a proposed value for the minimum (left) slider
341
- *
342
- * If the value is less than the leftmost valid position, then set it to the
343
- * left edge of the histogram (ie the slider width). If the value is greater
344
- * than the rightmost valid position (the position of the max slider), then
345
- * set it to the position of the max slider
346
- */
347
- private validMinSliderX(newX: number): number {
348
- // allow the left slider to go right only to the right slider, even if the
349
- // max selected date is out of range
350
- const rightLimit = Math.min(
351
- this.translateDateToPosition(this.maxSelectedDate),
352
- this.histogramRightEdgeX
353
- );
354
- newX = this.clamp(newX, this.histogramLeftEdgeX, rightLimit);
355
- const isInvalid =
356
- Number.isNaN(newX) || rightLimit < this.histogramLeftEdgeX;
357
- return isInvalid ? this.histogramLeftEdgeX : newX;
358
- }
359
-
360
- /**
361
- * Constrain a proposed value for the maximum (right) slider
362
- *
363
- * If the value is greater than the rightmost valid position, then set it to
364
- * the right edge of the histogram (ie histogram width - slider width). If the
365
- * value is less than the leftmost valid position (the position of the min
366
- * slider), then set it to the position of the min slider
367
- */
368
- private validMaxSliderX(newX: number): number {
369
- // allow the right slider to go left only to the left slider, even if the
370
- // min selected date is out of range
371
- const leftLimit = Math.max(
372
- this.histogramLeftEdgeX,
373
- this.translateDateToPosition(this.minSelectedDate)
374
- );
375
- newX = this.clamp(newX, leftLimit, this.histogramRightEdgeX);
376
- const isInvalid =
377
- Number.isNaN(newX) || leftLimit > this.histogramRightEdgeX;
378
- return isInvalid ? this.histogramRightEdgeX : newX;
379
- }
380
-
381
- private addListeners(): void {
382
- window.addEventListener('pointermove', this.move);
383
- window.addEventListener('pointerup', this.drop);
384
- window.addEventListener('pointercancel', this.drop);
385
- }
386
-
387
- private removeListeners(): void {
388
- window.removeEventListener('pointermove', this.move);
389
- window.removeEventListener('pointerup', this.drop);
390
- window.removeEventListener('pointercancel', this.drop);
391
- }
392
-
393
- /**
394
- * start a timer to emit an update event. this timer can be canceled (and the
395
- * event not emitted) if user drags a slider or focuses a date input within
396
- * the update delay
397
- */
398
- private beginEmitUpdateProcess(): void {
399
- this.cancelPendingUpdateEvent();
400
- this._emitUpdatedEventTimer = setTimeout(() => {
401
- if (this.currentDateRangeString === this._previousDateRange) {
402
- // don't emit duplicate event if no change since last emitted event
403
- return;
404
- }
405
- this._previousDateRange = this.currentDateRangeString;
406
- const options = {
407
- detail: {
408
- minDate: this.minSelectedDate,
409
- maxDate: this.maxSelectedDate,
410
- },
411
- bubbles: true,
412
- composed: true,
413
- };
414
- this.dispatchEvent(new CustomEvent('histogramDateRangeUpdated', options));
415
- }, this.updateDelay);
416
- }
417
-
418
- private cancelPendingUpdateEvent(): void {
419
- if (this._emitUpdatedEventTimer === undefined) {
420
- return;
421
- }
422
- clearTimeout(this._emitUpdatedEventTimer);
423
- this._emitUpdatedEventTimer = undefined;
424
- }
425
-
426
- /**
427
- * find position of pointer in relation to the current slider
428
- */
429
- private setDragOffset(e: PointerEvent): void {
430
- this._currentSlider = e.currentTarget as SVGRectElement;
431
- const sliderX =
432
- (this._currentSlider.id as SliderId) === 'slider-min'
433
- ? this.minSliderX
434
- : this.maxSliderX;
435
- const histogramClientX = this.getBoundingClientRect().x;
436
- this._dragOffset = e.clientX - histogramClientX - sliderX;
437
- }
438
-
439
- /**
440
- * @param x horizontal position of slider
441
- * @returns string representation of date
442
- */
443
- private translatePositionToDate(x: number): string {
444
- // use Math.ceil to round up to fix case where input like 1/1/2010 would get
445
- // translated to 12/31/2009
446
- const milliseconds = Math.ceil(
447
- ((x - this.sliderWidth) * this.dateRangeMS) / this._histWidth
448
- );
449
- return this.formatDate(this._minDateMS + milliseconds);
450
- }
451
-
452
- /**
453
- * Returns slider x-position corresponding to given date
454
- *
455
- * @param date
456
- * @returns x-position of slider
457
- */
458
- private translateDateToPosition(date: string): number {
459
- const milliseconds = this.getMSFromString(date);
460
- return (
461
- this.sliderWidth +
462
- ((milliseconds - this._minDateMS) * this._histWidth) / this.dateRangeMS
463
- );
464
- }
465
-
466
- /** ensure that the returned value is between minValue and maxValue */
467
- private clamp(x: number, minValue: number, maxValue: number): number {
468
- return Math.min(Math.max(x, minValue), maxValue);
469
- }
470
-
471
- private handleInputFocus(): void {
472
- if (!this.updateWhileFocused) {
473
- this.cancelPendingUpdateEvent();
474
- }
475
- }
476
-
477
- private handleMinDateInput(e: Event): void {
478
- const target = e.currentTarget as HTMLInputElement;
479
- if (target.value !== this.minSelectedDate) {
480
- this.minSelectedDate = target.value;
481
- this.beginEmitUpdateProcess();
482
- }
483
- }
484
-
485
- private handleMaxDateInput(e: Event): void {
486
- const target = e.currentTarget as HTMLInputElement;
487
- if (target.value !== this.maxSelectedDate) {
488
- this.maxSelectedDate = target.value;
489
- this.beginEmitUpdateProcess();
490
- }
491
- }
492
-
493
- private handleKeyUp(e: KeyboardEvent): void {
494
- if (e.key === 'Enter') {
495
- const target = e.currentTarget as HTMLInputElement;
496
- target.blur();
497
- if (target.id === 'date-min') {
498
- this.handleMinDateInput(e);
499
- } else if (target.id === 'date-max') {
500
- this.handleMaxDateInput(e);
501
- }
502
- }
503
- }
504
-
505
- private get currentDateRangeString(): string {
506
- return `${this.minSelectedDate}:${this.maxSelectedDate}`;
507
- }
508
-
509
- private getMSFromString(date: unknown): number {
510
- // It's possible that `date` is not a string in certain situations.
511
- // For instance if you use LitElement bindings and the date is `2000`,
512
- // it will be treated as a number instead of a string. This just makes sure
513
- // we're dealing with a string.
514
- const stringified = typeof date === 'string' ? date : String(date);
515
- const digitGroupCount = (stringified.split(/(\d+)/).length - 1) / 2;
516
- if (digitGroupCount === 1) {
517
- // if there's just a single set of digits, assume it's a year
518
- const dateObj = new Date(0, 0); // start at January 1, 1900
519
- dateObj.setFullYear(Number(stringified)); // override year
520
- return dateObj.getTime(); // get time in milliseconds
521
- }
522
- return dayjs(stringified, [this.dateFormat, DATE_FORMAT]).valueOf();
523
- }
524
-
525
- /**
526
- * expand or narrow the selected range by moving the slider nearest the
527
- * clicked bar to the outer edge of the clicked bar
528
- *
529
- * @param e Event click event from a histogram bar
530
- */
531
- private handleBarClick(e: Event): void {
532
- const dataset = (e.currentTarget as SVGRectElement).dataset as BarDataset;
533
- // use the midpoint of the width of the clicked bar to determine which is
534
- // the nearest slider
535
- const clickPosition =
536
- (this.getMSFromString(dataset.binStart) +
537
- this.getMSFromString(dataset.binEnd)) /
538
- 2;
539
- const distanceFromMinSlider = Math.abs(
540
- clickPosition - this.getMSFromString(this.minSelectedDate)
541
- );
542
- const distanceFromMaxSlider = Math.abs(
543
- clickPosition - this.getMSFromString(this.maxSelectedDate)
544
- );
545
- // update the selected range by moving the nearer slider
546
- if (distanceFromMinSlider < distanceFromMaxSlider) {
547
- this.minSelectedDate = dataset.binStart;
548
- } else {
549
- this.maxSelectedDate = dataset.binEnd;
550
- }
551
- this.beginEmitUpdateProcess();
552
- }
553
-
554
- private get minSliderTemplate(): SVGTemplateResult {
555
- // width/height in pixels of curved part of the sliders (like
556
- // border-radius); used as part of a SVG quadratic curve. see
557
- // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#curve_commands
558
- const cs = SLIDER_CORNER_SIZE;
559
-
560
- const sliderShape = `
561
- M${this.minSliderX},0
562
- h-${this.sliderWidth - cs}
563
- q-${cs},0 -${cs},${cs}
564
- v${this.height - cs * 2}
565
- q0,${cs} ${cs},${cs}
566
- h${this.sliderWidth - cs}
567
- `;
568
- return this.generateSliderSVG(this.minSliderX, 'slider-min', sliderShape);
569
- }
570
-
571
- private get maxSliderTemplate(): SVGTemplateResult {
572
- const cs = SLIDER_CORNER_SIZE;
573
- const sliderShape = `
574
- M${this.maxSliderX},0
575
- h${this.sliderWidth - cs}
576
- q${cs},0 ${cs},${cs}
577
- v${this.height - cs * 2}
578
- q0,${cs} -${cs},${cs}
579
- h-${this.sliderWidth - cs}
580
- `;
581
- return this.generateSliderSVG(this.maxSliderX, 'slider-max', sliderShape);
582
- }
583
-
584
- private generateSliderSVG(
585
- sliderPositionX: number,
586
- id: SliderId,
587
- sliderShape: string
588
- ): SVGTemplateResult {
589
- // whether the curved part of the slider is facing towards the left (1), ie
590
- // minimum, or facing towards the right (-1), ie maximum
591
- const k = id === 'slider-min' ? 1 : -1;
592
-
593
- return svg`
594
- <svg
595
- id="${id}"
596
- class="
597
- ${this.disabled ? '' : 'draggable'}
598
- ${this._isDragging ? 'dragging' : ''}"
599
- @pointerdown="${this.drag}"
600
- >
601
- <path d="${sliderShape} z" fill="${sliderColor}" />
602
- <rect
603
- x="${
604
- sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.4 * k
605
- }"
606
- y="${this.height / 3}"
607
- width="1"
608
- height="${this.height / 3}"
609
- fill="white"
610
- />
611
- <rect
612
- x="${
613
- sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.6 * k
614
- }"
615
- y="${this.height / 3}"
616
- width="1"
617
- height="${this.height / 3}"
618
- fill="white"
619
- />
620
- </svg>
621
- `;
622
- }
623
-
624
- get selectedRangeTemplate(): SVGTemplateResult {
625
- return svg`
626
- <rect
627
- x="${this.minSliderX}"
628
- y="0"
629
- width="${this.maxSliderX - this.minSliderX}"
630
- height="${this.height}"
631
- fill="${selectedRangeColor}"
632
- />`;
633
- }
634
-
635
- get histogramTemplate(): SVGTemplateResult[] {
636
- const xScale = this._histWidth / this._numBins;
637
- const barWidth = xScale - 1;
638
- let x = this.sliderWidth; // start at the left edge of the histogram
639
-
640
- // the stroke-dasharray style below creates a transparent border around the
641
- // right edge of the bar, which prevents user from encountering a gap
642
- // between adjacent bars (eg when viewing the tooltips or when trying to
643
- // extend the range by clicking on a bar)
644
- return this._histData.map(data => {
645
- const bar = svg`
646
- <rect
647
- class="bar"
648
- style='stroke-dasharray: 0 ${barWidth} ${data.height} ${barWidth} 0 ${
649
- data.height
650
- };'
651
- x="${x}"
652
- y="${this.height - data.height}"
653
- width="${barWidth}"
654
- height="${data.height}"
655
- @pointerenter="${this.showTooltip}"
656
- @pointerleave="${this.hideTooltip}"
657
- @click="${this.handleBarClick}"
658
- fill="${
659
- x + barWidth >= this.minSliderX && x <= this.maxSliderX
660
- ? barIncludedFill
661
- : barExcludedFill
662
- }"
663
- data-num-items="${data.value}"
664
- data-bin-start="${data.binStart}"
665
- data-bin-end="${data.binEnd}"
666
- />`;
667
- x += xScale;
668
- return bar;
669
- });
670
- }
671
-
672
- private formatDate(dateMS: number): string {
673
- if (Number.isNaN(dateMS)) {
674
- return '';
675
- }
676
- const date = dayjs(dateMS);
677
- if (date.year() < 1000) {
678
- // years before 1000 don't play well with dayjs custom formatting, so fall
679
- // back to displaying only the year
680
- return String(date.year());
681
- }
682
- return date.format(this.dateFormat);
683
- }
684
-
685
- /**
686
- * NOTE: we are relying on the lit `live` directive in the template to
687
- * ensure that the change to minSelectedDate is noticed and the input value
688
- * gets properly re-rendered. see
689
- * https://lit.dev/docs/templates/directives/#live
690
- */
691
- get minInputTemplate(): TemplateResult {
692
- return html`
693
- <input
694
- id="date-min"
695
- placeholder="${this.dateFormat}"
696
- type="text"
697
- @focus="${this.handleInputFocus}"
698
- @blur="${this.handleMinDateInput}"
699
- @keyup="${this.handleKeyUp}"
700
- .value="${live(this.minSelectedDate)}"
701
- ?disabled="${this.disabled}"
702
- />
703
- `;
704
- }
705
-
706
- get maxInputTemplate(): TemplateResult {
707
- return html`
708
- <input
709
- id="date-max"
710
- placeholder="${this.dateFormat}"
711
- type="text"
712
- @focus="${this.handleInputFocus}"
713
- @blur="${this.handleMaxDateInput}"
714
- @keyup="${this.handleKeyUp}"
715
- .value="${live(this.maxSelectedDate)}"
716
- ?disabled="${this.disabled}"
717
- />
718
- `;
719
- }
720
-
721
- get minLabelTemplate(): TemplateResult {
722
- return html`<label for="date-min" class="sr-only">Minimum date:</label>`;
723
- }
724
-
725
- get maxLabelTemplate(): TemplateResult {
726
- return html`<label for="date-max" class="sr-only">Maximum date:</label>`;
727
- }
728
-
729
- get tooltipTemplate(): TemplateResult {
730
- return html`
731
- <style>
732
- #tooltip {
733
- width: ${this.tooltipWidth}px;
734
- height: ${this.tooltipHeight}px;
735
- top: ${-9 - this.tooltipHeight}px;
736
- left: ${this._tooltipOffset}px;
737
- display: ${this._tooltipVisible ? 'block' : 'none'};
738
- }
739
- #tooltip:after {
740
- left: ${this.tooltipWidth / 2}px;
741
- }
742
- </style>
743
- <div id="tooltip">${this._tooltipContent}</div>
744
- `;
745
- }
746
-
747
- private get noDataTemplate(): TemplateResult {
748
- return html`
749
- <div class="missing-data-message">${this.missingDataMessage}</div>
750
- `;
751
- }
752
-
753
- private get activityIndicatorTemplate(): TemplateResult | typeof nothing {
754
- if (!this.loading) {
755
- return nothing;
756
- }
757
- return html`
758
- <ia-activity-indicator mode="processing"> </ia-activity-indicator>
759
- `;
760
- }
761
-
762
- static styles = css`
763
- .missing-data-message {
764
- text-align: center;
765
- }
766
- #container {
767
- margin: 0;
768
- touch-action: none;
769
- position: relative;
770
- }
771
- .disabled {
772
- opacity: 0.3;
773
- }
774
- ia-activity-indicator {
775
- position: absolute;
776
- left: calc(50% - 10px);
777
- top: 10px;
778
- width: 20px;
779
- height: 20px;
780
- --activityIndicatorLoadingDotColor: rgba(0, 0, 0, 0);
781
- --activityIndicatorLoadingRingColor: ${activityIndicatorColor};
782
- }
783
-
784
- /* prevent selection from interfering with tooltip, especially on mobile */
785
- /* https://stackoverflow.com/a/4407335/1163042 */
786
- .noselect {
787
- -webkit-touch-callout: none; /* iOS Safari */
788
- -webkit-user-select: none; /* Safari */
789
- -moz-user-select: none; /* Old versions of Firefox */
790
- -ms-user-select: none; /* Internet Explorer/Edge */
791
- user-select: none; /* current Chrome, Edge, Opera and Firefox */
792
- }
793
- .bar {
794
- /* create a transparent border around the hist bars to prevent "gaps" and
795
- flickering when moving around between bars. this also helps with handling
796
- clicks on the bars, preventing users from being able to click in between
797
- bars */
798
- stroke: rgba(0, 0, 0, 0);
799
- /* ensure transparent stroke wide enough to cover gap between bars */
800
- stroke-width: 2px;
801
- }
802
- .bar:hover {
803
- /* highlight currently hovered bar */
804
- fill-opacity: 0.7;
805
- }
806
- .disabled .bar:hover {
807
- /* ensure no visual hover interaction when disabled */
808
- fill-opacity: 1;
809
- }
810
- /****** histogram ********/
811
- #tooltip {
812
- position: absolute;
813
- background: ${tooltipBackgroundColor};
814
- color: ${tooltipTextColor};
815
- text-align: center;
816
- border-radius: 3px;
817
- padding: 2px;
818
- font-size: ${tooltipFontSize};
819
- font-family: ${tooltipFontFamily};
820
- touch-action: none;
821
- pointer-events: none;
822
- }
823
- #tooltip:after {
824
- content: '';
825
- position: absolute;
826
- margin-left: -5px;
827
- top: 100%;
828
- /* arrow */
829
- border: 5px solid ${tooltipTextColor};
830
- border-color: ${tooltipBackgroundColor} transparent transparent
831
- transparent;
832
- }
833
- /****** slider ********/
834
- .draggable:hover {
835
- cursor: grab;
836
- }
837
- .dragging {
838
- cursor: grabbing !important;
839
- }
840
- /****** inputs ********/
841
- #inputs {
842
- display: flex;
843
- justify-content: center;
844
- margin: ${inputRowMargin};
845
- }
846
- #inputs .dash {
847
- position: relative;
848
- bottom: -1px;
849
- align-self: center; /* Otherwise the dash sticks to the top while the inputs grow */
850
- }
851
- input {
852
- width: ${inputWidth};
853
- margin: 0 3px;
854
- border: ${inputBorder};
855
- border-radius: 2px !important;
856
- text-align: center;
857
- font-size: ${inputFontSize};
858
- font-family: ${inputFontFamily};
859
- }
860
- .sr-only {
861
- position: absolute !important;
862
- width: 1px !important;
863
- height: 1px !important;
864
- margin: 0 !important;
865
- padding: 0 !important;
866
- border: 0 !important;
867
- overflow: hidden !important;
868
- white-space: nowrap !important;
869
- clip: rect(1px, 1px, 1px, 1px) !important;
870
- -webkit-clip-path: inset(50%) !important;
871
- clip-path: inset(50%) !important;
872
- }
873
- `;
874
-
875
- render(): TemplateResult {
876
- if (!this.hasBinData) {
877
- return this.noDataTemplate;
878
- }
879
- return html`
880
- <div
881
- id="container"
882
- class="
883
- noselect
884
- ${this._isDragging ? 'dragging' : ''}
885
- "
886
- style="width: ${this.width}px"
887
- >
888
- ${this.activityIndicatorTemplate} ${this.tooltipTemplate}
889
- <div
890
- class="inner-container
891
- ${this.disabled ? 'disabled' : ''}"
892
- >
893
- <svg
894
- width="${this.width}"
895
- height="${this.height}"
896
- @pointerleave="${this.drop}"
897
- >
898
- ${this.selectedRangeTemplate}
899
- <svg id="histogram">${this.histogramTemplate}</svg>
900
- ${this.minSliderTemplate} ${this.maxSliderTemplate}
901
- </svg>
902
- <div id="inputs">
903
- ${this.minLabelTemplate} ${this.minInputTemplate}
904
- <div class="dash">-</div>
905
- ${this.maxLabelTemplate} ${this.maxInputTemplate}
906
- <slot name="inputs-right-side"></slot>
907
- </div>
908
- </div>
909
- </div>
910
- `;
911
- }
912
- }
913
-
914
- // help TypeScript provide strong typing when interacting with DOM APIs
915
- // https://stackoverflow.com/questions/65148695/lit-element-typescript-project-global-interface-declaration-necessary
916
- declare global {
917
- interface HTMLElementTagNameMap {
918
- 'histogram-date-range': HistogramDateRange;
919
- }
920
- }
1
+ import {
2
+ css,
3
+ html,
4
+ nothing,
5
+ LitElement,
6
+ PropertyValues,
7
+ svg,
8
+ SVGTemplateResult,
9
+ TemplateResult,
10
+ } from 'lit';
11
+ import { property, state, customElement } from 'lit/decorators.js';
12
+ import { live } from 'lit/directives/live.js';
13
+ import '@internetarchive/ia-activity-indicator/ia-activity-indicator';
14
+
15
+ /* eslint-disable-next-line */
16
+ /* @ts-ignore Import module -- JS, so no types */
17
+ import dayjs from 'https://esm.archive.org/dayjs@^1.10.7';
18
+ /* eslint-disable-next-line */
19
+ /* @ts-ignore Import module -- JS, so no types */
20
+ import customParseFormat from 'https://esm.archive.org/dayjs@1.9.4/esm/plugin/customParseFormat';
21
+ // NOTE: using a specific *earlier* pegged commit for the plugin ^, because esm.archive.org has a
22
+ // problem creating later versions where the `export` of an included `utils.js` gets mangled. Eg:
23
+ // https://github.com/internetarchive/esbuild_es5/commit/ce19e8b841282c0e94d2b8e6830fd7744b2216c2#diff-4b2ed47327851d566740a30ce5f60271c059ae67eff2006bc07bb7c4fcee8b50L296
24
+
25
+ dayjs.extend(customParseFormat);
26
+
27
+ // these values can be overridden via the component's HTML (camelCased) attributes
28
+ const WIDTH = 180;
29
+ const HEIGHT = 40;
30
+ const SLIDER_WIDTH = 10;
31
+ const TOOLTIP_WIDTH = 125;
32
+ const TOOLTIP_HEIGHT = 30;
33
+ const DATE_FORMAT = 'YYYY';
34
+ const MISSING_DATA = 'no data';
35
+ const UPDATE_DEBOUNCE_DELAY_MS = 0;
36
+
37
+ // this constant is not set up to be overridden
38
+ const SLIDER_CORNER_SIZE = 4;
39
+
40
+ // these CSS custom props can be overridden from the HTML that is invoking this component
41
+ const sliderColor = css`var(--histogramDateRangeSliderColor, #4B65FE)`;
42
+ const selectedRangeColor = css`var(--histogramDateRangeSelectedRangeColor, #DBE0FF)`;
43
+ const barIncludedFill = css`var(--histogramDateRangeBarIncludedFill, #2C2C2C)`;
44
+ const activityIndicatorColor = css`var(--histogramDateRangeActivityIndicator, #2C2C2C)`;
45
+ const barExcludedFill = css`var(--histogramDateRangeBarExcludedFill, #CCCCCC)`;
46
+ const inputRowMargin = css`var(--histogramDateRangeInputRowMargin, 0)`;
47
+ const inputBorder = css`var(--histogramDateRangeInputBorder, 0.5px solid #2C2C2C)`;
48
+ const inputWidth = css`var(--histogramDateRangeInputWidth, 35px)`;
49
+ const inputFontSize = css`var(--histogramDateRangeInputFontSize, 1.2rem)`;
50
+ const inputFontFamily = css`var(--histogramDateRangeInputFontFamily, sans-serif)`;
51
+ const tooltipBackgroundColor = css`var(--histogramDateRangeTooltipBackgroundColor, #2C2C2C)`;
52
+ const tooltipTextColor = css`var(--histogramDateRangeTooltipTextColor, #FFFFFF)`;
53
+ const tooltipFontSize = css`var(--histogramDateRangeTooltipFontSize, 1.1rem)`;
54
+ const tooltipFontFamily = css`var(--histogramDateRangeTooltipFontFamily, sans-serif)`;
55
+
56
+ type SliderId = 'slider-min' | 'slider-max';
57
+
58
+ interface HistogramItem {
59
+ value: number;
60
+ height: number;
61
+ binStart: string;
62
+ binEnd: string;
63
+ }
64
+
65
+ interface BarDataset extends DOMStringMap {
66
+ numItems: string;
67
+ binStart: string;
68
+ binEnd: string;
69
+ }
70
+
71
+ @customElement('histogram-date-range')
72
+ export class HistogramDateRange extends LitElement {
73
+ /* eslint-disable lines-between-class-members */
74
+
75
+ // public reactive properties that can be set via HTML attributes
76
+ @property({ type: Number }) width = WIDTH;
77
+ @property({ type: Number }) height = HEIGHT;
78
+ @property({ type: Number }) sliderWidth = SLIDER_WIDTH;
79
+ @property({ type: Number }) tooltipWidth = TOOLTIP_WIDTH;
80
+ @property({ type: Number }) tooltipHeight = TOOLTIP_HEIGHT;
81
+ @property({ type: Number }) updateDelay = UPDATE_DEBOUNCE_DELAY_MS;
82
+ @property({ type: String }) dateFormat = DATE_FORMAT;
83
+ @property({ type: String }) missingDataMessage = MISSING_DATA;
84
+ @property({ type: String }) minDate = '';
85
+ @property({ type: String }) maxDate = '';
86
+ @property({ type: Boolean }) disabled = false;
87
+ @property({ type: Object }) bins: number[] = [];
88
+ /** If true, update events will not be canceled by the date inputs receiving focus */
89
+ @property({ type: Boolean }) updateWhileFocused = false;
90
+
91
+ // internal reactive properties not exposed as attributes
92
+ @state() private _tooltipOffset = 0;
93
+ @state() private _tooltipContent?: TemplateResult;
94
+ @state() private _tooltipVisible = false;
95
+ @state() private _isDragging = false;
96
+ @state() private _isLoading = false;
97
+
98
+ // non-reactive properties (changes don't auto-trigger re-rendering)
99
+ private _minSelectedDate = '';
100
+ private _maxSelectedDate = '';
101
+ private _minDateMS = 0;
102
+ private _maxDateMS = 0;
103
+ private _dragOffset = 0;
104
+ private _histWidth = 0;
105
+ private _binWidth = 0;
106
+ private _currentSlider?: SVGRectElement;
107
+ private _histData: HistogramItem[] = [];
108
+ private _emitUpdatedEventTimer?: ReturnType<typeof setTimeout>;
109
+ private _previousDateRange = '';
110
+
111
+ /* eslint-enable lines-between-class-members */
112
+
113
+ disconnectedCallback(): void {
114
+ this.removeListeners();
115
+ super.disconnectedCallback();
116
+ }
117
+
118
+ updated(changedProps: PropertyValues): void {
119
+ // check for changes that would affect bin data calculations
120
+ if (
121
+ changedProps.has('bins') ||
122
+ changedProps.has('minDate') ||
123
+ changedProps.has('maxDate') ||
124
+ changedProps.has('minSelectedDate') ||
125
+ changedProps.has('maxSelectedDate') ||
126
+ changedProps.has('width') ||
127
+ changedProps.has('height')
128
+ ) {
129
+ this.handleDataUpdate();
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Set private properties that depend on the attribute bin data
135
+ *
136
+ * We're caching these values and not using getters to avoid recalculating all
137
+ * of the hist data every time the user drags a slider or hovers over a bar
138
+ * creating a tooltip.
139
+ */
140
+ private handleDataUpdate(): void {
141
+ if (!this.hasBinData) {
142
+ return;
143
+ }
144
+ this._histWidth = this.width - this.sliderWidth * 2;
145
+ this._minDateMS = this.getMSFromString(this.minDate);
146
+ this._maxDateMS = this.getMSFromString(this.maxDate);
147
+ this._binWidth = this._histWidth / this._numBins;
148
+ this._previousDateRange = this.currentDateRangeString;
149
+ this._histData = this.calculateHistData();
150
+ this.minSelectedDate = this.minSelectedDate
151
+ ? this.minSelectedDate
152
+ : this.minDate;
153
+ this.maxSelectedDate = this.maxSelectedDate
154
+ ? this.maxSelectedDate
155
+ : this.maxDate;
156
+ this.requestUpdate();
157
+ }
158
+
159
+ private calculateHistData(): HistogramItem[] {
160
+ const minValue = Math.min(...this.bins);
161
+ const maxValue = Math.max(...this.bins);
162
+ // if there is no difference between the min and max values, use a range of
163
+ // 1 because log scaling will fail if the range is 0
164
+ const valueRange = minValue === maxValue ? 1 : Math.log1p(maxValue);
165
+ const valueScale = this.height / valueRange;
166
+ const dateScale = this.dateRangeMS / this._numBins;
167
+ return this.bins.map((v: number, i: number) => {
168
+ return {
169
+ value: v,
170
+ // use log scaling for the height of the bar to prevent tall bars from
171
+ // making the smaller ones too small to see
172
+ height: Math.floor(Math.log1p(v) * valueScale),
173
+ binStart: `${this.formatDate(i * dateScale + this._minDateMS)}`,
174
+ binEnd: `${this.formatDate((i + 1) * dateScale + this._minDateMS)}`,
175
+ };
176
+ });
177
+ }
178
+
179
+ private get hasBinData(): boolean {
180
+ return this._numBins > 0;
181
+ }
182
+
183
+ private get _numBins(): number {
184
+ if (!this.bins || !this.bins.length) {
185
+ return 0;
186
+ }
187
+ return this.bins.length;
188
+ }
189
+
190
+ private get histogramLeftEdgeX(): number {
191
+ return this.sliderWidth;
192
+ }
193
+
194
+ private get histogramRightEdgeX(): number {
195
+ return this.width - this.sliderWidth;
196
+ }
197
+
198
+ /** component's loading (and disabled) state */
199
+ @property({ type: Boolean }) get loading(): boolean {
200
+ return this._isLoading;
201
+ }
202
+
203
+ set loading(value: boolean) {
204
+ this.disabled = value;
205
+ this._isLoading = value;
206
+ }
207
+
208
+ /** formatted minimum date of selected date range */
209
+ @property() get minSelectedDate(): string {
210
+ return this.formatDate(this.getMSFromString(this._minSelectedDate));
211
+ }
212
+
213
+ /** updates minSelectedDate if new date is valid */
214
+ set minSelectedDate(rawDate: string) {
215
+ if (!this._minSelectedDate) {
216
+ // because the values needed to calculate valid max/min values are not
217
+ // available during the lit init when it's populating properties from
218
+ // attributes, fall back to just the raw date if nothing is already set
219
+ this._minSelectedDate = rawDate;
220
+ return;
221
+ }
222
+ const proposedDateMS = this.getMSFromString(rawDate);
223
+ const isValidDate = !Number.isNaN(proposedDateMS);
224
+ const isNotTooRecent =
225
+ proposedDateMS <= this.getMSFromString(this.maxSelectedDate);
226
+ if (isValidDate && isNotTooRecent) {
227
+ this._minSelectedDate = this.formatDate(proposedDateMS);
228
+ }
229
+ this.requestUpdate();
230
+ }
231
+
232
+ /** formatted maximum date of selected date range */
233
+ @property() get maxSelectedDate(): string {
234
+ return this.formatDate(this.getMSFromString(this._maxSelectedDate));
235
+ }
236
+
237
+ /** updates maxSelectedDate if new date is valid */
238
+ set maxSelectedDate(rawDate: string) {
239
+ if (!this._maxSelectedDate) {
240
+ // because the values needed to calculate valid max/min values are not
241
+ // available during the lit init when it's populating properties from
242
+ // attributes, fall back to just the raw date if nothing is already set
243
+ this._maxSelectedDate = rawDate;
244
+ return;
245
+ }
246
+ const proposedDateMS = this.getMSFromString(rawDate);
247
+ const isValidDate = !Number.isNaN(proposedDateMS);
248
+ const isNotTooOld =
249
+ proposedDateMS >= this.getMSFromString(this.minSelectedDate);
250
+ if (isValidDate && isNotTooOld) {
251
+ this._maxSelectedDate = this.formatDate(proposedDateMS);
252
+ }
253
+ this.requestUpdate();
254
+ }
255
+
256
+ /** horizontal position of min date slider */
257
+ get minSliderX(): number {
258
+ const x = this.translateDateToPosition(this.minSelectedDate);
259
+ return this.validMinSliderX(x);
260
+ }
261
+
262
+ /** horizontal position of max date slider */
263
+ get maxSliderX(): number {
264
+ const x = this.translateDateToPosition(this.maxSelectedDate);
265
+ return this.validMaxSliderX(x);
266
+ }
267
+
268
+ private get dateRangeMS(): number {
269
+ return this._maxDateMS - this._minDateMS;
270
+ }
271
+
272
+ private showTooltip(e: PointerEvent): void {
273
+ if (this._isDragging || this.disabled) {
274
+ return;
275
+ }
276
+ const target = e.currentTarget as SVGRectElement;
277
+ const x = target.x.baseVal.value + this.sliderWidth / 2;
278
+ const dataset = target.dataset as BarDataset;
279
+ const itemsText = `item${dataset.numItems !== '1' ? 's' : ''}`;
280
+ const formattedNumItems = Number(dataset.numItems).toLocaleString();
281
+
282
+ this._tooltipOffset =
283
+ x + (this._binWidth - this.sliderWidth - this.tooltipWidth) / 2;
284
+
285
+ this._tooltipContent = html`
286
+ ${formattedNumItems} ${itemsText}<br />
287
+ ${dataset.binStart} - ${dataset.binEnd}
288
+ `;
289
+ this._tooltipVisible = true;
290
+ }
291
+
292
+ private hideTooltip(): void {
293
+ this._tooltipContent = undefined;
294
+ this._tooltipVisible = false;
295
+ }
296
+
297
+ // use arrow functions (rather than standard JS class instance methods) so
298
+ // that `this` is bound to the histogramDateRange object and not the event
299
+ // target. for more info see
300
+ // https://lit-element.polymer-project.org/guide/events#using-this-in-event-listeners
301
+ private drag = (e: PointerEvent): void => {
302
+ // prevent selecting text or other ranges while dragging, especially in Safari
303
+ e.preventDefault();
304
+ if (this.disabled) {
305
+ return;
306
+ }
307
+ this.setDragOffset(e);
308
+ this._isDragging = true;
309
+ this.addListeners();
310
+ this.cancelPendingUpdateEvent();
311
+ };
312
+
313
+ private drop = (): void => {
314
+ if (this._isDragging) {
315
+ this.removeListeners();
316
+ this.beginEmitUpdateProcess();
317
+ }
318
+ this._isDragging = false;
319
+ };
320
+
321
+ /**
322
+ * Adjust the date range based on slider movement
323
+ *
324
+ * @param e PointerEvent from the slider being moved
325
+ */
326
+ private move = (e: PointerEvent): void => {
327
+ const histogramClientX = this.getBoundingClientRect().x;
328
+ const newX = e.clientX - histogramClientX - this._dragOffset;
329
+ const slider = this._currentSlider as SVGRectElement;
330
+ if ((slider.id as SliderId) === 'slider-min') {
331
+ this.minSelectedDate = this.translatePositionToDate(
332
+ this.validMinSliderX(newX)
333
+ );
334
+ } else {
335
+ this.maxSelectedDate = this.translatePositionToDate(
336
+ this.validMaxSliderX(newX)
337
+ );
338
+ }
339
+ };
340
+
341
+ /**
342
+ * Constrain a proposed value for the minimum (left) slider
343
+ *
344
+ * If the value is less than the leftmost valid position, then set it to the
345
+ * left edge of the histogram (ie the slider width). If the value is greater
346
+ * than the rightmost valid position (the position of the max slider), then
347
+ * set it to the position of the max slider
348
+ */
349
+ private validMinSliderX(newX: number): number {
350
+ // allow the left slider to go right only to the right slider, even if the
351
+ // max selected date is out of range
352
+ const rightLimit = Math.min(
353
+ this.translateDateToPosition(this.maxSelectedDate),
354
+ this.histogramRightEdgeX
355
+ );
356
+ newX = this.clamp(newX, this.histogramLeftEdgeX, rightLimit);
357
+ const isInvalid =
358
+ Number.isNaN(newX) || rightLimit < this.histogramLeftEdgeX;
359
+ return isInvalid ? this.histogramLeftEdgeX : newX;
360
+ }
361
+
362
+ /**
363
+ * Constrain a proposed value for the maximum (right) slider
364
+ *
365
+ * If the value is greater than the rightmost valid position, then set it to
366
+ * the right edge of the histogram (ie histogram width - slider width). If the
367
+ * value is less than the leftmost valid position (the position of the min
368
+ * slider), then set it to the position of the min slider
369
+ */
370
+ private validMaxSliderX(newX: number): number {
371
+ // allow the right slider to go left only to the left slider, even if the
372
+ // min selected date is out of range
373
+ const leftLimit = Math.max(
374
+ this.histogramLeftEdgeX,
375
+ this.translateDateToPosition(this.minSelectedDate)
376
+ );
377
+ newX = this.clamp(newX, leftLimit, this.histogramRightEdgeX);
378
+ const isInvalid =
379
+ Number.isNaN(newX) || leftLimit > this.histogramRightEdgeX;
380
+ return isInvalid ? this.histogramRightEdgeX : newX;
381
+ }
382
+
383
+ private addListeners(): void {
384
+ window.addEventListener('pointermove', this.move);
385
+ window.addEventListener('pointerup', this.drop);
386
+ window.addEventListener('pointercancel', this.drop);
387
+ }
388
+
389
+ private removeListeners(): void {
390
+ window.removeEventListener('pointermove', this.move);
391
+ window.removeEventListener('pointerup', this.drop);
392
+ window.removeEventListener('pointercancel', this.drop);
393
+ }
394
+
395
+ /**
396
+ * start a timer to emit an update event. this timer can be canceled (and the
397
+ * event not emitted) if user drags a slider or focuses a date input within
398
+ * the update delay
399
+ */
400
+ private beginEmitUpdateProcess(): void {
401
+ this.cancelPendingUpdateEvent();
402
+ this._emitUpdatedEventTimer = setTimeout(() => {
403
+ if (this.currentDateRangeString === this._previousDateRange) {
404
+ // don't emit duplicate event if no change since last emitted event
405
+ return;
406
+ }
407
+ this._previousDateRange = this.currentDateRangeString;
408
+ const options = {
409
+ detail: {
410
+ minDate: this.minSelectedDate,
411
+ maxDate: this.maxSelectedDate,
412
+ },
413
+ bubbles: true,
414
+ composed: true,
415
+ };
416
+ this.dispatchEvent(new CustomEvent('histogramDateRangeUpdated', options));
417
+ }, this.updateDelay);
418
+ }
419
+
420
+ private cancelPendingUpdateEvent(): void {
421
+ if (this._emitUpdatedEventTimer === undefined) {
422
+ return;
423
+ }
424
+ clearTimeout(this._emitUpdatedEventTimer);
425
+ this._emitUpdatedEventTimer = undefined;
426
+ }
427
+
428
+ /**
429
+ * find position of pointer in relation to the current slider
430
+ */
431
+ private setDragOffset(e: PointerEvent): void {
432
+ this._currentSlider = e.currentTarget as SVGRectElement;
433
+ const sliderX =
434
+ (this._currentSlider.id as SliderId) === 'slider-min'
435
+ ? this.minSliderX
436
+ : this.maxSliderX;
437
+ const histogramClientX = this.getBoundingClientRect().x;
438
+ this._dragOffset = e.clientX - histogramClientX - sliderX;
439
+ }
440
+
441
+ /**
442
+ * @param x horizontal position of slider
443
+ * @returns string representation of date
444
+ */
445
+ private translatePositionToDate(x: number): string {
446
+ // use Math.ceil to round up to fix case where input like 1/1/2010 would get
447
+ // translated to 12/31/2009
448
+ const milliseconds = Math.ceil(
449
+ ((x - this.sliderWidth) * this.dateRangeMS) / this._histWidth
450
+ );
451
+ return this.formatDate(this._minDateMS + milliseconds);
452
+ }
453
+
454
+ /**
455
+ * Returns slider x-position corresponding to given date
456
+ *
457
+ * @param date
458
+ * @returns x-position of slider
459
+ */
460
+ private translateDateToPosition(date: string): number {
461
+ const milliseconds = this.getMSFromString(date);
462
+ return (
463
+ this.sliderWidth +
464
+ ((milliseconds - this._minDateMS) * this._histWidth) / this.dateRangeMS
465
+ );
466
+ }
467
+
468
+ /** ensure that the returned value is between minValue and maxValue */
469
+ private clamp(x: number, minValue: number, maxValue: number): number {
470
+ return Math.min(Math.max(x, minValue), maxValue);
471
+ }
472
+
473
+ private handleInputFocus(): void {
474
+ if (!this.updateWhileFocused) {
475
+ this.cancelPendingUpdateEvent();
476
+ }
477
+ }
478
+
479
+ private handleMinDateInput(e: Event): void {
480
+ const target = e.currentTarget as HTMLInputElement;
481
+ if (target.value !== this.minSelectedDate) {
482
+ this.minSelectedDate = target.value;
483
+ this.beginEmitUpdateProcess();
484
+ }
485
+ }
486
+
487
+ private handleMaxDateInput(e: Event): void {
488
+ const target = e.currentTarget as HTMLInputElement;
489
+ if (target.value !== this.maxSelectedDate) {
490
+ this.maxSelectedDate = target.value;
491
+ this.beginEmitUpdateProcess();
492
+ }
493
+ }
494
+
495
+ private handleKeyUp(e: KeyboardEvent): void {
496
+ if (e.key === 'Enter') {
497
+ const target = e.currentTarget as HTMLInputElement;
498
+ target.blur();
499
+ if (target.id === 'date-min') {
500
+ this.handleMinDateInput(e);
501
+ } else if (target.id === 'date-max') {
502
+ this.handleMaxDateInput(e);
503
+ }
504
+ }
505
+ }
506
+
507
+ private get currentDateRangeString(): string {
508
+ return `${this.minSelectedDate}:${this.maxSelectedDate}`;
509
+ }
510
+
511
+ private getMSFromString(date: unknown): number {
512
+ // It's possible that `date` is not a string in certain situations.
513
+ // For instance if you use LitElement bindings and the date is `2000`,
514
+ // it will be treated as a number instead of a string. This just makes sure
515
+ // we're dealing with a string.
516
+ const stringified = typeof date === 'string' ? date : String(date);
517
+ const digitGroupCount = (stringified.split(/(\d+)/).length - 1) / 2;
518
+ if (digitGroupCount === 1) {
519
+ // if there's just a single set of digits, assume it's a year
520
+ const dateObj = new Date(0, 0); // start at January 1, 1900
521
+ dateObj.setFullYear(Number(stringified)); // override year
522
+ return dateObj.getTime(); // get time in milliseconds
523
+ }
524
+ return dayjs(stringified, [this.dateFormat, DATE_FORMAT]).valueOf();
525
+ }
526
+
527
+ /**
528
+ * expand or narrow the selected range by moving the slider nearest the
529
+ * clicked bar to the outer edge of the clicked bar
530
+ *
531
+ * @param e Event click event from a histogram bar
532
+ */
533
+ private handleBarClick(e: Event): void {
534
+ const dataset = (e.currentTarget as SVGRectElement).dataset as BarDataset;
535
+ // use the midpoint of the width of the clicked bar to determine which is
536
+ // the nearest slider
537
+ const clickPosition =
538
+ (this.getMSFromString(dataset.binStart) +
539
+ this.getMSFromString(dataset.binEnd)) /
540
+ 2;
541
+ const distanceFromMinSlider = Math.abs(
542
+ clickPosition - this.getMSFromString(this.minSelectedDate)
543
+ );
544
+ const distanceFromMaxSlider = Math.abs(
545
+ clickPosition - this.getMSFromString(this.maxSelectedDate)
546
+ );
547
+ // update the selected range by moving the nearer slider
548
+ if (distanceFromMinSlider < distanceFromMaxSlider) {
549
+ this.minSelectedDate = dataset.binStart;
550
+ } else {
551
+ this.maxSelectedDate = dataset.binEnd;
552
+ }
553
+ this.beginEmitUpdateProcess();
554
+ }
555
+
556
+ private get minSliderTemplate(): SVGTemplateResult {
557
+ // width/height in pixels of curved part of the sliders (like
558
+ // border-radius); used as part of a SVG quadratic curve. see
559
+ // https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths#curve_commands
560
+ const cs = SLIDER_CORNER_SIZE;
561
+
562
+ const sliderShape = `
563
+ M${this.minSliderX},0
564
+ h-${this.sliderWidth - cs}
565
+ q-${cs},0 -${cs},${cs}
566
+ v${this.height - cs * 2}
567
+ q0,${cs} ${cs},${cs}
568
+ h${this.sliderWidth - cs}
569
+ `;
570
+ return this.generateSliderSVG(this.minSliderX, 'slider-min', sliderShape);
571
+ }
572
+
573
+ private get maxSliderTemplate(): SVGTemplateResult {
574
+ const cs = SLIDER_CORNER_SIZE;
575
+ const sliderShape = `
576
+ M${this.maxSliderX},0
577
+ h${this.sliderWidth - cs}
578
+ q${cs},0 ${cs},${cs}
579
+ v${this.height - cs * 2}
580
+ q0,${cs} -${cs},${cs}
581
+ h-${this.sliderWidth - cs}
582
+ `;
583
+ return this.generateSliderSVG(this.maxSliderX, 'slider-max', sliderShape);
584
+ }
585
+
586
+ private generateSliderSVG(
587
+ sliderPositionX: number,
588
+ id: SliderId,
589
+ sliderShape: string
590
+ ): SVGTemplateResult {
591
+ // whether the curved part of the slider is facing towards the left (1), ie
592
+ // minimum, or facing towards the right (-1), ie maximum
593
+ const k = id === 'slider-min' ? 1 : -1;
594
+
595
+ return svg`
596
+ <svg
597
+ id="${id}"
598
+ class="
599
+ ${this.disabled ? '' : 'draggable'}
600
+ ${this._isDragging ? 'dragging' : ''}"
601
+ @pointerdown="${this.drag}"
602
+ >
603
+ <path d="${sliderShape} z" fill="${sliderColor}" />
604
+ <rect
605
+ x="${
606
+ sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.4 * k
607
+ }"
608
+ y="${this.height / 3}"
609
+ width="1"
610
+ height="${this.height / 3}"
611
+ fill="white"
612
+ />
613
+ <rect
614
+ x="${
615
+ sliderPositionX - this.sliderWidth * k + this.sliderWidth * 0.6 * k
616
+ }"
617
+ y="${this.height / 3}"
618
+ width="1"
619
+ height="${this.height / 3}"
620
+ fill="white"
621
+ />
622
+ </svg>
623
+ `;
624
+ }
625
+
626
+ get selectedRangeTemplate(): SVGTemplateResult {
627
+ return svg`
628
+ <rect
629
+ x="${this.minSliderX}"
630
+ y="0"
631
+ width="${this.maxSliderX - this.minSliderX}"
632
+ height="${this.height}"
633
+ fill="${selectedRangeColor}"
634
+ />`;
635
+ }
636
+
637
+ get histogramTemplate(): SVGTemplateResult[] {
638
+ const xScale = this._histWidth / this._numBins;
639
+ const barWidth = xScale - 1;
640
+ let x = this.sliderWidth; // start at the left edge of the histogram
641
+
642
+ // the stroke-dasharray style below creates a transparent border around the
643
+ // right edge of the bar, which prevents user from encountering a gap
644
+ // between adjacent bars (eg when viewing the tooltips or when trying to
645
+ // extend the range by clicking on a bar)
646
+ return this._histData.map(data => {
647
+ const bar = svg`
648
+ <rect
649
+ class="bar"
650
+ style='stroke-dasharray: 0 ${barWidth} ${data.height} ${barWidth} 0 ${
651
+ data.height
652
+ };'
653
+ x="${x}"
654
+ y="${this.height - data.height}"
655
+ width="${barWidth}"
656
+ height="${data.height}"
657
+ @pointerenter="${this.showTooltip}"
658
+ @pointerleave="${this.hideTooltip}"
659
+ @click="${this.handleBarClick}"
660
+ fill="${
661
+ x + barWidth >= this.minSliderX && x <= this.maxSliderX
662
+ ? barIncludedFill
663
+ : barExcludedFill
664
+ }"
665
+ data-num-items="${data.value}"
666
+ data-bin-start="${data.binStart}"
667
+ data-bin-end="${data.binEnd}"
668
+ />`;
669
+ x += xScale;
670
+ return bar;
671
+ });
672
+ }
673
+
674
+ private formatDate(dateMS: number): string {
675
+ if (Number.isNaN(dateMS)) {
676
+ return '';
677
+ }
678
+ const date = dayjs(dateMS);
679
+ if (date.year() < 1000) {
680
+ // years before 1000 don't play well with dayjs custom formatting, so fall
681
+ // back to displaying only the year
682
+ return String(date.year());
683
+ }
684
+ return date.format(this.dateFormat);
685
+ }
686
+
687
+ /**
688
+ * NOTE: we are relying on the lit `live` directive in the template to
689
+ * ensure that the change to minSelectedDate is noticed and the input value
690
+ * gets properly re-rendered. see
691
+ * https://lit.dev/docs/templates/directives/#live
692
+ */
693
+ get minInputTemplate(): TemplateResult {
694
+ return html`
695
+ <input
696
+ id="date-min"
697
+ placeholder="${this.dateFormat}"
698
+ type="text"
699
+ @focus="${this.handleInputFocus}"
700
+ @blur="${this.handleMinDateInput}"
701
+ @keyup="${this.handleKeyUp}"
702
+ .value="${live(this.minSelectedDate)}"
703
+ ?disabled="${this.disabled}"
704
+ />
705
+ `;
706
+ }
707
+
708
+ get maxInputTemplate(): TemplateResult {
709
+ return html`
710
+ <input
711
+ id="date-max"
712
+ placeholder="${this.dateFormat}"
713
+ type="text"
714
+ @focus="${this.handleInputFocus}"
715
+ @blur="${this.handleMaxDateInput}"
716
+ @keyup="${this.handleKeyUp}"
717
+ .value="${live(this.maxSelectedDate)}"
718
+ ?disabled="${this.disabled}"
719
+ />
720
+ `;
721
+ }
722
+
723
+ get minLabelTemplate(): TemplateResult {
724
+ return html`<label for="date-min" class="sr-only">Minimum date:</label>`;
725
+ }
726
+
727
+ get maxLabelTemplate(): TemplateResult {
728
+ return html`<label for="date-max" class="sr-only">Maximum date:</label>`;
729
+ }
730
+
731
+ get tooltipTemplate(): TemplateResult {
732
+ return html`
733
+ <style>
734
+ #tooltip {
735
+ width: ${this.tooltipWidth}px;
736
+ height: ${this.tooltipHeight}px;
737
+ top: ${-9 - this.tooltipHeight}px;
738
+ left: ${this._tooltipOffset}px;
739
+ display: ${this._tooltipVisible ? 'block' : 'none'};
740
+ }
741
+ #tooltip:after {
742
+ left: ${this.tooltipWidth / 2}px;
743
+ }
744
+ </style>
745
+ <div id="tooltip">${this._tooltipContent}</div>
746
+ `;
747
+ }
748
+
749
+ private get noDataTemplate(): TemplateResult {
750
+ return html`
751
+ <div class="missing-data-message">${this.missingDataMessage}</div>
752
+ `;
753
+ }
754
+
755
+ private get activityIndicatorTemplate(): TemplateResult | typeof nothing {
756
+ if (!this.loading) {
757
+ return nothing;
758
+ }
759
+ return html`
760
+ <ia-activity-indicator mode="processing"> </ia-activity-indicator>
761
+ `;
762
+ }
763
+
764
+ static styles = css`
765
+ .missing-data-message {
766
+ text-align: center;
767
+ }
768
+ #container {
769
+ margin: 0;
770
+ touch-action: none;
771
+ position: relative;
772
+ }
773
+ .disabled {
774
+ opacity: 0.3;
775
+ }
776
+ ia-activity-indicator {
777
+ position: absolute;
778
+ left: calc(50% - 10px);
779
+ top: 10px;
780
+ width: 20px;
781
+ height: 20px;
782
+ --activityIndicatorLoadingDotColor: rgba(0, 0, 0, 0);
783
+ --activityIndicatorLoadingRingColor: ${activityIndicatorColor};
784
+ }
785
+
786
+ /* prevent selection from interfering with tooltip, especially on mobile */
787
+ /* https://stackoverflow.com/a/4407335/1163042 */
788
+ .noselect {
789
+ -webkit-touch-callout: none; /* iOS Safari */
790
+ -webkit-user-select: none; /* Safari */
791
+ -moz-user-select: none; /* Old versions of Firefox */
792
+ -ms-user-select: none; /* Internet Explorer/Edge */
793
+ user-select: none; /* current Chrome, Edge, Opera and Firefox */
794
+ }
795
+ .bar {
796
+ /* create a transparent border around the hist bars to prevent "gaps" and
797
+ flickering when moving around between bars. this also helps with handling
798
+ clicks on the bars, preventing users from being able to click in between
799
+ bars */
800
+ stroke: rgba(0, 0, 0, 0);
801
+ /* ensure transparent stroke wide enough to cover gap between bars */
802
+ stroke-width: 2px;
803
+ }
804
+ .bar:hover {
805
+ /* highlight currently hovered bar */
806
+ fill-opacity: 0.7;
807
+ }
808
+ .disabled .bar:hover {
809
+ /* ensure no visual hover interaction when disabled */
810
+ fill-opacity: 1;
811
+ }
812
+ /****** histogram ********/
813
+ #tooltip {
814
+ position: absolute;
815
+ background: ${tooltipBackgroundColor};
816
+ color: ${tooltipTextColor};
817
+ text-align: center;
818
+ border-radius: 3px;
819
+ padding: 2px;
820
+ font-size: ${tooltipFontSize};
821
+ font-family: ${tooltipFontFamily};
822
+ touch-action: none;
823
+ pointer-events: none;
824
+ }
825
+ #tooltip:after {
826
+ content: '';
827
+ position: absolute;
828
+ margin-left: -5px;
829
+ top: 100%;
830
+ /* arrow */
831
+ border: 5px solid ${tooltipTextColor};
832
+ border-color: ${tooltipBackgroundColor} transparent transparent
833
+ transparent;
834
+ }
835
+ /****** slider ********/
836
+ .draggable:hover {
837
+ cursor: grab;
838
+ }
839
+ .dragging {
840
+ cursor: grabbing !important;
841
+ }
842
+ /****** inputs ********/
843
+ #inputs {
844
+ display: flex;
845
+ justify-content: center;
846
+ margin: ${inputRowMargin};
847
+ }
848
+ #inputs .dash {
849
+ position: relative;
850
+ bottom: -1px;
851
+ align-self: center; /* Otherwise the dash sticks to the top while the inputs grow */
852
+ }
853
+ input {
854
+ width: ${inputWidth};
855
+ margin: 0 3px;
856
+ border: ${inputBorder};
857
+ border-radius: 2px !important;
858
+ text-align: center;
859
+ font-size: ${inputFontSize};
860
+ font-family: ${inputFontFamily};
861
+ }
862
+ .sr-only {
863
+ position: absolute !important;
864
+ width: 1px !important;
865
+ height: 1px !important;
866
+ margin: 0 !important;
867
+ padding: 0 !important;
868
+ border: 0 !important;
869
+ overflow: hidden !important;
870
+ white-space: nowrap !important;
871
+ clip: rect(1px, 1px, 1px, 1px) !important;
872
+ -webkit-clip-path: inset(50%) !important;
873
+ clip-path: inset(50%) !important;
874
+ }
875
+ `;
876
+
877
+ render(): TemplateResult {
878
+ if (!this.hasBinData) {
879
+ return this.noDataTemplate;
880
+ }
881
+ return html`
882
+ <div
883
+ id="container"
884
+ class="
885
+ noselect
886
+ ${this._isDragging ? 'dragging' : ''}
887
+ "
888
+ style="width: ${this.width}px"
889
+ >
890
+ ${this.activityIndicatorTemplate} ${this.tooltipTemplate}
891
+ <div
892
+ class="inner-container
893
+ ${this.disabled ? 'disabled' : ''}"
894
+ >
895
+ <svg
896
+ width="${this.width}"
897
+ height="${this.height}"
898
+ @pointerleave="${this.drop}"
899
+ >
900
+ ${this.selectedRangeTemplate}
901
+ <svg id="histogram">${this.histogramTemplate}</svg>
902
+ ${this.minSliderTemplate} ${this.maxSliderTemplate}
903
+ </svg>
904
+ <div id="inputs">
905
+ ${this.minLabelTemplate} ${this.minInputTemplate}
906
+ <div class="dash">-</div>
907
+ ${this.maxLabelTemplate} ${this.maxInputTemplate}
908
+ <slot name="inputs-right-side"></slot>
909
+ </div>
910
+ </div>
911
+ </div>
912
+ `;
913
+ }
914
+ }
915
+
916
+ // help TypeScript provide strong typing when interacting with DOM APIs
917
+ // https://stackoverflow.com/questions/65148695/lit-element-typescript-project-global-interface-declaration-necessary
918
+ declare global {
919
+ interface HTMLElementTagNameMap {
920
+ 'histogram-date-range': HistogramDateRange;
921
+ }
922
+ }