Repository navigation
Expand file tree
/
Copy pathstats.html
More file actions
1062 lines (923 loc) · 37.9 KB
/
Copy pathstats.html
File metadata and controls
1062 lines (923 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!--
This page is an experiment in auto-styling based on a selected attribute.
Sample dataset URL:
http://localhost:8080/widget-coordination.html?dataset=8581a7460e144ae09ad25d47f8e82af8_0
-->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta
name="viewport"
content="initial-scale=1,maximum-scale=1,user-scalable=no"
/>
<title>Filters</title>
<link href="widget-coordination.css" rel="stylesheet">
<script src="https://unpkg.com/lodash@4.17.15/lodash.js"></script>
<script src="https://cdn.jsdelivr.net/autocomplete.js/0/autocomplete.min.js"></script>
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.js"></script>
<!-- Load jStat -->
<script src="https://cdn.jsdelivr.net/npm/jstat@latest/dist/jstat.min.js"></script>
<!-- calcite components -->
<script
type="module"
src="https://unpkg.com/@esri/calcite-components@1.0.0-beta.24/dist/calcite/calcite.esm.js"
></script>
<link
rel="stylesheet"
type="text/css"
href="https://unpkg.com/@esri/calcite-components@1.0.0-beta.24/dist/calcite/calcite.css"
/>
<script type="module">
import { loadModules, setDefaultOptions } from 'https://unpkg.com/esri-loader/dist/esm/esri-loader.js';
(async () => {
setDefaultOptions({
css: true,
// url: 'http://localhost:8000/buildOutput/init.js',
// version: 'next',
});
const [
Map,
MapView,
FeatureLayer,
generateHistogram,
Histogram,
HistogramRangeSlider,
TimeSlider,
uniqueValues,
webMercatorUtils
] = await loadModules([
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer",
"esri/renderers/smartMapping/statistics/histogram",
"esri/widgets/Histogram",
"esri/widgets/HistogramRangeSlider",
"esri/widgets/TimeSlider",
"esri/renderers/smartMapping/statistics/uniqueValues",
"esri/geometry/support/webMercatorUtils"
]);
// SCENE SETUP
//
// parse URL params
const params = new URLSearchParams(window.location.search);
const datasetId = params.get('dataset');
const datasetSlug = params.get('slug');
const env = params.get('env') || 'prod';
// load dataset
const { layer, dataset } = await loadDataset({ datasetId, datasetSlug, env });
// display dataset info
document.querySelector('#datasetName').innerHTML = dataset.attributes.name;
document.querySelector('#orgName').innerHTML = dataset.attributes.orgName || '';
document.querySelector('#recordCount').innerHTML = `${dataset.attributes.recordCount} records`;
// MAP SETUP
//
// load map and setup global variables
const map = new Map({
basemap: "dark-gray-vector",
layers: [layer]
});
const view = new MapView({
container: "viewDiv",
map: map,
extent: getDatasetExtent(dataset)
});
const layerView = await view.whenLayerView(layer);
const attributeList = updateAttributeList(dataset);
// put vars on window for debugging
Object.assign(window, { view, map, dataset, layer, layerView, getDatasetField, getDatasetFieldUniqueValues, /*histogram, histogramValues,*/ generateHistogram, HistogramRangeSlider, uniqueValues });
// DATA FUNCTIONS
//
// load a dataset
async function loadDataset ({ datasetId, datasetSlug, env }) {
let dataset = {};
if (datasetId) { // dataset id provided directly
// https://opendataqa.arcgis.com/api/v3/datasets/97a641ac39904f349fb5fc25b94207f6
const datasetURL = `https://opendata${env === 'qa' ? 'qa' : ''}.arcgis.com/api/v3/datasets/${datasetId}`;
try {
dataset = (await fetch(datasetURL).then(r => r.json())).data;
} catch(e) { console.log('failed to load dataset from id', datasetId, e); }
} else if (datasetSlug) { // dataset slug provided as alternate
// https://opendata.arcgis.com/api/v3/datasets?filter%5Bslug%5D=kingcounty%3A%3Aphoto-centers-for-2010-king-county-orthoimagery-project-ortho-image10-point
const filter = `${encodeURIComponent('filter[slug]')}=${encodeURIComponent(datasetSlug)}`
const datasetURL = `https://opendata${env === 'qa' ? 'qa' : ''}.arcgis.com/api/v3/datasets?${filter}`;
try {
dataset = (await fetch(datasetURL).then(r => r.json())).data[0];
} catch(e) { console.log('failed to load dataset from slug', datasetSlug, e); }
}
// set default renderer
let symbol = {
type: 'simple-marker', size: '5px',
color: [51, 51, 204, 0.0],
outline: {
color: [256, 256, 256, 1],
width: 0.5
},
}
// if (geometryType === 'point') {
// symbol = { ...symbol, type: 'simple-marker', size: '8px' };
// }
// else if (geometryType === 'polyline') {
// symbol = { ...symbol, type: 'simple-line', width: '4px' };
// }
// else if (geometryType === 'polygon') {
// symbol = { ...symbol, type: 'simple-fill' };
// }
const layer = new FeatureLayer({
// renderer: { type: 'simple', symbol },
url: dataset.attributes.url
});
layer.minScale = 0; // draw at all scales
layer.outFields = ["*"]; // get all fields (easier for prototyping, optimize by managing for necessary fields)
return { dataset, layer };
}
function getDatasetExtent (dataset) {
const extent = dataset.attributes.extent;
return {
xmin: extent.coordinates[0][0],
ymin: extent.coordinates[0][1],
xmax: extent.coordinates[1][0],
ymax: extent.coordinates[1][1],
spatialReference: extent.spatialReference
};
}
function getDatasetField (dataset, fieldName) {
fieldName = fieldName.toLowerCase();
const field = dataset.attributes.fields.find(f => f.name.toLowerCase() === fieldName);
const stats = [...Object.entries(dataset.attributes.statistics).values()].find(([, fields]) => fields[fieldName]);
// add "simple type" (numeric, date, string) and stats into rest of field definition
return {
...field,
simpleType: stats && stats[0],
statistics: stats && stats[1][fieldName].statistics
}
}
const DATASET_FIELD_UNIQUE_VALUES = {}; // cache by field name
async function getDatasetFieldUniqueValues (dataset, fieldName, layer) {
if (!DATASET_FIELD_UNIQUE_VALUES[fieldName]) {
const field = getDatasetField(dataset, fieldName);
let stats;
if (field.statistics && field.statistics.uniqueCount) {
stats = { ...field.statistics };
} else {
const uniqueValueInfos = (await uniqueValues({ layer, field: fieldName }))
.uniqueValueInfos
.sort((a, b) => a.count > b.count ? -1 : 1);
const count = uniqueValueInfos.reduce((count, f) => count + f.count, 0);
stats = {
count,
uniqueCount: uniqueValueInfos.length,
values: uniqueValueInfos
}
}
// add percent of records
stats.values = stats.values
// .filter(v => v.value != null && (typeof v.value !== 'string' || v.value.trim() !== ''))
.map(v => ({ ...v, pct: v.count / stats.count }));
// get top values
const maxTopValCount = 12;
// stats.topValues = stats.values.slice(0, maxTopValCount);
stats.topValues = [];
if (stats.uniqueCount < maxTopValCount) {
stats.topValues = stats.values;
} else {
let coverage = 0;
for (let i=0, coverage=0; i < stats.values.length; i++) {
// let stat = { ...stats.values[i], pct: stats.values[i].count / recordCount };
const stat = stats.values[i];
// if (coverage >= 0.80 && stat.pct < 0.05 && stats.topValues.length >= maxTopValCount) break;
if (stat.pct < 0.015 || stats.topValues.length >= maxTopValCount) break;
stats.topValues.push(stat);
coverage += stat.pct;
}
}
DATASET_FIELD_UNIQUE_VALUES[fieldName] = stats;
}
return DATASET_FIELD_UNIQUE_VALUES[fieldName];
}
// Add an entry to the attribute dropdown
function updateAttributeList (dataset) {
// create <calcite-dropdown-item> for each attribute
const attributeList = document.querySelector('#attributeList > calcite-dropdown-group');
const attributes = [
...Object.entries(dataset.attributes.statistics.numeric || {}),
...Object.entries(dataset.attributes.statistics.date || {}),
...Object.entries(dataset.attributes.statistics.string || {})
];
attributes
.map(([fieldName, { statistics: fieldStats }]) => [fieldName, fieldStats]) // grab stats
.filter(([fieldName, fieldStats]) => { // exclude fields with one value
return !fieldStats ||
!fieldStats.values ||
fieldStats.uniqueCount > 1 || // unique count reported as 0 for sampled data
fieldStats.values.min !== fieldStats.values.max
})
.forEach(([fieldName, fieldStats]) => {
// dataset.attributes.fieldNames
// .map(fieldName => [fieldName, getDatasetField(dataset, fieldName)])
// .filter(([fieldName, field]) => !field.statistics || field.statistics.values.min !== field.statistics.values.max)
// .forEach(([fieldName, field]) => {
const field = getDatasetField(dataset, fieldName);
// const fieldStats = field.statistics.values;
const item = document.createElement('calcite-dropdown-item');
item.innerHTML = `${field.alias || fieldName}`;
if (fieldStats && fieldStats.values && fieldStats.values.min != null && fieldStats.values.max != null) {
if (field.simpleType === 'numeric') {
// TODO: vary precision based on value range
item.innerHTML += `<br><small>(${fieldStats.values.min.toFixed(2)} to ${fieldStats.values.max.toFixed(2)})</small>`;
} else if (field.simpleType === 'date') {
item.innerHTML += ` (${formatDate(fieldStats.values.min)} to ${formatDate(fieldStats.values.max)})`;
}
} else if (fieldStats && fieldStats.uniqueCount && field.simpleType === 'string') {
item.innerHTML += ` (${fieldStats.uniqueCount} values)`;
}
// add icon for field type
if (field.simpleType === 'numeric') {
item.iconEnd = 'number';
} else if (field.simpleType === 'string') {
item.iconEnd = 'description';
} else if (field.simpleType === 'date') {
item.iconEnd = 'calendar';
}
item.setAttribute('data-field', field.name);
attributeList.appendChild(item);
});
return attributeList;
}
// add event listener to dropdown, to create visualizations
attributeList.addEventListener('calciteDropdownItemSelected', makeWidget);
// WIDGET HELPERS
//
function updateOthers(otherWidgets, layerView, whereClause, features) {
for (var x = 0; x < otherWidgets.length; x++) {
// can't update TimeSliders
if (otherWidgets[x].label == "TimeSlider") continue;
updateHistogram(otherWidgets[x], layerView, otherWidgets[x].fieldName, whereClause, features);
}
}
const throttledUpdateOthers = _.throttle(updateOthers, 100, {trailing: false});
// list all known widget DOM elements
function listWidgetElements() {
return document.getElementById('widgets').querySelectorAll('[whereClause]')
}
// concatenate all the where clauses from all the widgets
function concatWheres() {
let whereClause = '';
let widgets = listWidgetElements();
// generate master here clause with simple string concatenation
for (var x = 0; x < widgets.length; x++) {
if (x > 0) whereClause += ' AND ';
whereClause += '(' + widgets[x].getAttribute('whereClause') + ')';
}
return whereClause;
}
// STYLING FUNCTIONS
//
// add item to styling attribute dropdown
function updateStylingAttributeList (widget) {
const list = document.querySelector('#stylingAttributeList > calcite-dropdown-group');
const item = document.createElement('calcite-dropdown-item');
item.innerHTML = widget.fieldName;
item.setAttribute('data-field', widget.fieldName);
list.appendChild(item);
}
// add event listener to dropdown, to create visualizations
stylingAttributeList.addEventListener('calciteDropdownItemSelected', updateStyle);
// from is-numeric-field-type.js
function isNumericFieldType (type) {
// NOTE: type can be one of the following:
// "esriFieldTypeSmallInteger", "esriFieldTypeInteger", "esriFieldTypeSingle", "esriFieldTypeDouble",
// "esriFieldTypeString",
// "esriFieldTypeDate",
// "esriFieldTypeOID", "esriFieldTypeGlobalID",
// "esriFieldTypeGeometry", "esriFieldTypeBlob", "esriFieldTypeRaster", "esriFieldTypeGUID", "esriFieldTypeXML"
const numericTypes = ['esriFieldTypeSmallInteger', 'esriFieldTypeInteger', 'esriFieldTypeSingle', 'esriFieldTypeDouble', 'esriFieldTypeFloat'];
return numericTypes.indexOf(type) > -1;
}
function isSmappable(dataset, field) {
const fieldType = field.type;
if (dataset.attributes.content !== 'Feature Service') {
return false;
}
if (fieldType !== 'esriFieldTypeString' && !isNumericFieldType(fieldType) && fieldType !== 'esriFieldTypeDate') {
// if it is NOT a string or a number or a date we can't smap it
return false;
}
const stats = dataset.attributes.statistics;
if (!stats || (!!stats.duration && stats.duration === 0)) {
return false;
}
return true;
}
function updateStyle(event) {
const fieldName = event.target.getAttribute('data-field');
const index = dataset.attributes.fieldNames.indexOf(fieldName);
const field = dataset.attributes.fields[index];
const fieldType = field.type;
// from opendata-ui is-field-smappable.js
if (isSmappable(dataset, field)) {
applySmartMapRender(field);
} else {
_applyDefaultRenderer();
}
return;
let symbol = {
type: 'simple-marker', size: '5px',
color: [51, 51, 204, 0.0],
outline: {
color: [256, 256, 256, 1],
width: 0.5
},
}
if (fieldType === 'esriFieldTypeDate') {
symbol = { ...symbol, type: 'simple-marker', size: '8px' };
}
// else if (fieldType === 'esriFieldTypeString') {
// symbol = { ...symbol, type: 'simple-line', width: '4px' };
// }
// else if (fieldType === 'esriFieldTypeDouble') {
// symbol = { ...symbol, type: 'simple-fill' };
// }
// else if (fieldType === 'esriFieldTypeInteger') {
// symbol = { ...symbol, type: 'simple-fill' };
// }
// if (geometryType === 'point') {
// symbol = { ...symbol, type: 'simple-marker', size: '8px' };
// }
// else if (geometryType === 'polyline') {
// symbol = { ...symbol, type: 'simple-line', width: '4px' };
// }
// else if (geometryType === 'polygon') {
// symbol = { ...symbol, type: 'simple-fill' };
// }
layer.renderer = { type: 'simple', symbol };
}
// update the map view with a new where clause
async function updateLayerViewEffect(layerView, { where = null, updateExtent = false } = {}) {
layerView.filter = null;
if (where) {
layerView.effect = {
filter: {
where,
// geometry: layerView.view.extent.clone().expand(0.5) // testing limiting query by geom/viewport
},
excludedEffect: 'grayscale(100%) brightness(0%) opacity(25%)'
};
}
// adjust view extent (in or out) to fit all filtered data
if (updateExtent && layerView.effect && layerView.effect.filter) {
try {
const featureExtent = await layer.queryExtent({
where: layerView.effect.filter.where,
outSpatialReference: layerView.view.spatialReference
});
if (featureExtent.count > 0) {
const extent = featureExtent.extent;
// const extent = webMercatorUtils.project(featureExtent.extent, layerView.view.spatialReference);
const expanded = extent.expand(1.10);
// view.extent =
if (!layerView.view.extent.contains(expanded) ||
(expanded.width * expanded.height) / (layerView.view.extent.width * layerView.view.extent.height) < 0.20) {
layerView.view.goTo(expanded, { duration: 350 });
}
}
} catch(e) {
console.log('could not query or project feature extent to update viewport', e);
}
}
}
// make an appropriate widget for a field's data type - fieldName may be passed in directly for testing
async function makeWidget (event, fieldName = null) {
// fieldName is normally the current value of the fields dropdown
fieldName = (fieldName === null) ? event.target.getAttribute('data-field') : fieldName;
const field = getDatasetField(dataset, fieldName);
// document.querySelector('#attributeListButton').innerHTML = fieldName;
// stop any timeSlider playback
stopTimePlayback();
// clear previous filters
updateLayerViewEffect(layerView, { updateExtent: true });
let widget;
console.log('makeWidget() fieldType:', field.simpleType);
const query = layerView.layer.createQuery();
const statquery = layerView.layer.createQuery();
query.outFields = [fieldName];
statquery.outFields = [fieldName];
let attstats = dataset.attributes.statistics;
// get a test stat
statquery.outStatistics = {
onStatisticField: fieldName,
outStatisticFieldName: fieldName + "_stddev",
statisticType: "stddev"
};
// query features from the server, returns max 2000 features
// let stats = layer.queryFeatures(query).then(function(response) {
// query within the view's extent on the client once everything's loaded
let stats = layerView.queryFeatures(query).then(async function(response) {
console.log('response features:', response.features.length)
try {
// debugger
const stats = response.features[0].attributes;
console.log('stats:', stats)
return stats
} catch(e) {
return new Error('e:', e)
}
});
if (field.simpleType === 'numeric') {
// Histogram
widget = await makeHistogramWidget({ dataset, fieldName, layer, layerView, slider: true })
}
if (field.simpleType === 'date') {
// Time slider
widget = await makeTimeSliderWidget({ dataset, fieldName, layer, layerView, slider: true });
}
if (field.simpleType === 'string') {
// TODO: TBD
return false
// widget = await makeTimeSliderWidget({ dataset, fieldName, layer, layerView, slider: true });
}
widget.fieldName = fieldName;
widget.container.classList.add('widget');
// label widget
const label = document.createElement('div');
label.classList.add('widgetLabel');
label.innerHTML = fieldName;
widget.container.before(label);
// update styling attribute dropdown
updateStylingAttributeList(widget);
};
let widgetsList = [];
async function makeTimeSlider ({ dataset, fieldName, layerView, container }) {
try {
const field = getDatasetField(dataset, fieldName);
// let {min: startDate, max: endDate } = dataset.attributes.statistics.date[fieldname.toLowerCase()].statistics.values;
const startDate = new Date(field.statistics.values.min);
const endDate = new Date(field.statistics.values.max);
const widget = new TimeSlider({
container: container,
// view: view,
mode: "time-window",
fullTimeExtent: {
start: startDate,
end: endDate,
},
values: [
startDate,
endDate
],
// track timeSlider selection state
selectionWasFullExtent: false
});
return { widget };
}
catch(e) {
throw new Error(e);
return {};
}
}
// make and place a histogram
async function makeHistogramWidget({ dataset, fieldName, layer, layerView, slider = true }) {
const container = document.createElement('div');
container.classList.add('histogramWidget');
document.getElementById('widgets').appendChild(container);
const histogram = await makeHistogram({ dataset, fieldName, layer, layerView, container, slider: true });
if (histogram.widget) {
container.widget = histogram.widget;
// set event handler to update map filter and histograms when handles are dragged
histogram.widget.on(["thumb-change", "thumb-drag", "segment-drag"], event => {
updateLayerView(layerView, fieldName, histogram.widget);
updateWidgets(layerView, fieldName, histogram.widget)
});
// register widget
widgetsList.push(histogram.widget)
}
return histogram.widget;
}
// update layerview filter based on widget, throttled
const updateLayerView = _.throttle(
async (layerView, fieldName, widget, value = null) => {
let whereClause;
if (widget.label === "Histogram Range Slider") {
whereClause = widget.generateWhereClause(fieldName);
}
if (widget.label === "TimeSlider") {
// instead of unix timestamps, use SQL date formatting, as expected by layer.queryFeatures()
whereClause = `${fieldName} BETWEEN DATE ${formatSQLDate(value.start)} AND DATE ${formatSQLDate(value.end)}`;
}
// set whereClause attribute
widget.container.setAttribute('whereClause', whereClause);
const where = concatWheres();
await updateLayerViewEffect(layerView, {where: where, updateExtent: false });
},
10,
{trailing: false}
);
// update the bins of all histograms except the current widget, throttled
const updateWidgets = _.throttle(
async (layerView, fieldName, currentWidget) => {
// if there's only one widget, skip this
if (widgetsList.length === 1) return
// collect other widgets' fieldNames, skipping the current widget (handles nested widgets too)
let otherWidgets = widgetsList.filter(w => w.fieldName != fieldName);
let fieldNames = otherWidgets.map(w => w.fieldName);
// convert to a set to remove any duplicates (nested widgets), then back to array
fieldNames = [...new Set(fieldNames)];
const whereClause = currentWidget.container.getAttribute('whereClause');
try {
let { features } = await layer.queryFeatures( { where: whereClause, outFields: fieldNames });
// update other widgets, passing in the filtered feature set
throttledUpdateOthers(otherWidgets, layerView, concatWheres(), features);
} catch(e) {
throw new Error('Tried to update other widgets: '+e)
}
},
100,
{trailing: false}
);
// update the bins of a histogram
async function updateHistogram(widget, layerView, fieldName, where, features) {
let values;
if (features) {
let params = {
layer,
features,
field: fieldName,
numBins: 30,
// minValue: widget.min,
// maxValue: widget.max,
// values: [widget.values[0], widget.values[1]]
// values: [widget.min, widget.max]
// sqlWhere: concatWheres()
// sqlWhere: where
};
try {
values = await generateHistogram(params);
if (values.bins) {
widget.bins = values.bins;
}
} catch(e) {
console.log('e:', e)
}
}
}
// create a histogram
async function makeHistogram ({dataset, fieldName, layer, layerView, container, slider = false, where = null }) {
// wrap in another container to handle height without fighting w/JSAPI and rest of sidebar
const parentContainer = container;
container = document.createElement('div');
parentContainer.appendChild(container);
try {
let params = {
layer: layer,
field: fieldName,
numBins: 30,
};
if (where) params.where = where;
let values, bins, source, coverage;
try {
values = await generateHistogram(params);
source = 'widgets';
coverage = 1;
} catch(e) {
try {
// histogram generation failed with automated server call, try using features from server query
console.log('histogram generation failed with automated server call, try using features from server query', e);
params.features = (await layer.queryFeatures()).features;
const featureCount = await layer.queryFeatureCount();
if (params.features.length != featureCount) throw new Error('params.features.length != featureCount');
values = await generateHistogram(params);
source = 'layerQuery';
coverage = params.features.length / featureCount;
} catch(e) {
// histogram generation failed with automated server call, try using features from server query
console.log('histogram generation failed with automated server call, try reconstructing from unique values', e);
try {
let uniqueValues = (await getDatasetFieldUniqueValues(dataset, fieldName, layer)).values;
let domain = [Math.min(...uniqueValues.map(a => a.value)),
Math.max(...uniqueValues.map(a => a.value))]
// remove nulls
var filtered = uniqueValues.filter(a => a.value != null);
// manually reconstruct a feature values array from the unique values and their counts -
// normalize array length to 1000, as precision isn't as important as speed here
const divisor = dataset.attributes.recordCount / 1000;
let arr = [];
for (let x = 0; x < filtered.length; x++) {
for (let y = 0; y < Math.ceil(filtered[x].count/divisor); y++) {
arr.push(filtered[x].value);
};
}
// use d3 to bin histograms
let d3bins = d3.histogram() // create layout object
.domain([Math.min(...filtered.map(a => a.value)),
Math.max(...filtered.map(a => a.value))]) // to cover range
.thresholds(29) // separated into 30 bins
(arr); // pass the array
// convert the d3 bins array to a bins object
bins = [];
for (let x = 0; x < d3bins.length; x++) {
bins.push({
minValue: d3bins[x]['x0'],
maxValue: d3bins[x]['x1'],
count: d3bins[x].length,
});
}
// put the bins in the params object
values = {
'bins': bins,
'minValue': Math.min(...filtered.map(a => a.value)),
'maxValue': Math.max(...filtered.map(a => a.value)),
}
const featureCount = arr.length;
source = 'layerQuery';
coverage = 1;
} catch(e) {
// histogram generation failed with unique values, try using features in layer view
console.log('histogram generation failed with unique values, try using features in layer view', e);
params.features = (await layerView.queryFeatures()).features;
const featureCount = await layer.queryFeatureCount();
values = await generateHistogram(params);
source = 'layerView';
coverage = params.features.length / featureCount;
}
}
}
// Determine if field is an integer
const field = getDatasetField(dataset, fieldName);
const integer = await datasetFieldIsInteger(field);
const widget =
slider ?
// Histogram range slider widget
new HistogramRangeSlider({
bins: values.bins,
min: values.minValue,
max: values.maxValue,
values: [values.minValue, values.maxValue],
precision: integer ? 0 : 2,
container: container,
excludedBarColor: "#dddddd",
rangeType: "between",
labelFormatFunction: (value, type) => {
// apply date formatting to histogram
if (field.simpleType == 'date') {
return formatDate(value);
}
return value;
}
})
:
// plain histogram, for miniHistogram nested in timeSlider
new Histogram({
bins: values.bins,
min: values.minValue,
max: values.maxValue,
container: container,
rangeType: "between",
})
;
return { widget, values, source, coverage };
}
catch(e) {
console.log('histogram generation failed', e);
return {};
}
}
// make and place a time slider
async function makeTimeSliderWidget({ dataset, fieldName, layer, layerView, slider = true }) {
const container = document.createElement('div');
container.classList.add('timesliderWidget');
document.getElementById('widgets').appendChild(container);
let timeSlider = await makeTimeSlider({ dataset, fieldName, layerView, container });
// set widget state
if (timeSlider.widget) {
try {
// add a nested histogram
const histogramContainer = document.createElement('div');
histogramContainer.classList.add('miniHistogramWidget');
container.getElementsByClassName("esri-slider__track")[0].after(histogramContainer);
const miniHistogram = await makeHistogram ({ dataset, fieldName, layer, layerView, container: histogramContainer });
miniHistogram.widget.fieldName = fieldName;
// register miniHistogram
widgetsList.push(miniHistogram.widget)
const { widget } = timeSlider;
// set event handler to update map filter when time handles are dragged
widget.watch("timeExtent", function(value) {
updateLayerView(layerView, fieldName, widget, value);
updateWidgets(layerView, fieldName, widget);
});
// handle situation where if the whole time extent is selected, the play button does nothing –
// modify this: select a smaller range, so the play button has room to move the selection
// first: watch when the widget state changes
widget.watch('viewModel.state', function(state){
if (state == "playing") {
// check values (date selection) against fullTimeExtent -
// convert to numeric values with unary + operator to check equivalence (with a 10% tolerance)
if ( +this.values[0] == +this.fullTimeExtent.start &&
Math.abs(+this.values[1] - +this.fullTimeExtent.end) <
(+new Date(this.fullTimeExtent.end) - +new Date(this.fullTimeExtent.start))/ 10 ) {
// update selection state
this.selectionWasFullExtent = true;
// set new selection end to 10% through the date range
this.values[1] = new Date(+new Date(this.fullTimeExtent.start) + (+new Date(this.fullTimeExtent.end) - +new Date(this.fullTimeExtent.start)) / 10);
}
}
else if (state == "ready" && this.selectionWasFullExtent) {
// reset selection state
this.selectionWasFullExtent = false;
// reset selection range to full extent
this.values = [this.fullTimeExtent.start, this.fullTimeExtent.end];
}
});
} catch(e) {
throw new Error(e);
}
// register widget
widgetsList.push(timeSlider.widget)
}
return timeSlider.widget;
}
// Determine if field is an integer
async function datasetFieldIsInteger (field) {
if (field.type.toLowerCase().includes('integer')) { // explicit integer type
return true;
} else { // or check the known values to see if they're all integers
const stats = await getDatasetFieldUniqueValues(dataset, field.name, layer);
return stats.values.every(v => v.value == null || Number.isInteger(v.value));
}
}
// stop all timeSlider playback
function stopTimePlayback() {
for (let i in widgetsList) {
if (widgetsList[i].label && widgetsList[i].label == "TimeSlider") {
widgetsList[i].stop();
}
}
}
function formatDate (timestamp) {
const date = new Date(timestamp);
return `${date.getMonth()+1}/${date.getDate()}/${date.getFullYear()}`;
// => 5/15/2020
}
function formatSQLDate (timestamp) {
const date = new Date(timestamp);
return `'${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}'`;
// => 2020-05-15
}
function makeStylingWidget() {
const container = document.createElement('div');
container.classList.add('stylingWidget');
document.getElementById('widgets').appendChild(container);
}
window.getDefaultRenderer = getDefaultRenderer;
function getDefaultRenderer (geometryType) {
switch (geometryType) {
case 'polygon':
return POLYGON_RENDERER;
case 'point':
case 'multipoint':
return POINT_RENDERER;
case 'polyline':
return LINE_RENDERER;
case 'line':
return LINE_RENDERER;
default:
console.error(`Unknown geometry type (${geometryType})`);
}
}
function simpleFieldType (fieldType) {
const fieldTypes = {
esriFieldTypeGlobalID: 'text',
esriFieldTypeGUID: 'text',
esriFieldTypeDate: 'date-time',
esriFieldTypeString: 'string',
esriFieldTypeSingle: 'number',
esriFieldTypeFloat: 'number',
esriFieldTypeDouble: 'number',
esriFieldTypeInteger: 'number',
esriFieldTypeSmallInteger: 'number',
esriFieldTypeOID: 'number',
};
return fieldTypes[fieldType] || '';
}
async function applySmartMapRender (field) {
// const layerView = this.getLayerView();
const layer = layerView && layerView.layer;
const view = layerView.view;
try {
// apply a smart map renderer for the selected field
const renderer = await createSmartMapRenderer(layer, field, view);
layer.renderer = renderer;
// tryInvoke(this, 'onRendererChange', [layer.renderer]);
} catch (e) {
console.log('and i', e)
// if (this.isDestroying || this.isDestroyed) {
// return;
// }
// reset renderer to default
this._applyDefaultRenderer();
// relay error
tryInvoke(this, 'onSmartMapError', [e]);
}
}
function createSmartMapRenderer (layer, field, view) {
// Some smart mapping renderers support passing cached statistics, which saves an extra server call.
// Currently, our uses of `createRenderer` and `createContinuousRenderer` benefit from this.
// `createClassBreaksRenderer` does not support this parameter but will ignore it.
const statistics = (field.statistics && field.statistics.duration > 0) ? field.statistics : null;
const props = {
layer,
field: field.name,
statistics,
view
};
// TOOD: should this use simpleGeomType() to be consistent w/ component's geometryClass?
const geomType = layer.geometryType;
const fieldType = simpleFieldType(field.type);
switch (fieldType) {
case 'string':
props.numTypes = 12;
if (props.statistics) {
// reformat stats to match `UniqueValuesResult` structure expected by `type` renderers
props.statistics = { uniqueValueInfos: props.statistics.values };
}
return loadRenderer('type', props);
case 'number':
if (geomType === 'polygon') {
return loadRenderer('color', props);
}
if (geomType === 'point' || geomType === 'multipoint' || geomType === 'polyline') {
return loadRenderer('size', props);
}
// return reject('Field/geometry type not supported.');
case 'date-time':
return loadRenderer('color', props);
default:
// return reject('Field type not supported.');
}
}
function loadRenderer (type, props) {
return loadModules(
[`esri/renderers/smartMapping/creators/${type}`]
).then(([rendererCreator]) => {
const creatorFn = type === 'color'
? 'createContinuousRenderer'
: type === 'size'
? 'createContinuousRenderer' // 'createClassBreaksRenderer'
: 'createRenderer';
return rendererCreator[creatorFn](props)
.then(response => response.renderer);
});
}
// TESTS
//