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