-
Notifications
You must be signed in to change notification settings - Fork 0
/
tabnav.mjs
1815 lines (1629 loc) · 66.8 KB
/
tabnav.mjs
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
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',
// url: 'http://jscore.esri.com/debug/4.16/dojo/dojo.js',
// version: 'next',
});
const [
Map,
MapView,
FeatureLayer,
generateHistogram,
HistogramRangeSlider,
Histogram,
uniqueValues,
Legend,
colorRamps,
Color,
viewColorUtils,
LabelClass,
CIMSymbol,
cimSymbolUtils,
] = await loadModules([
"esri/Map",
"esri/views/MapView",
"esri/layers/FeatureLayer",
"esri/smartMapping/statistics/histogram",
"esri/widgets/HistogramRangeSlider",
"esri/widgets/Histogram",
"esri/smartMapping/statistics/uniqueValues",
"esri/widgets/Legend",
"esri/smartMapping/symbology/support/colorRamps",
"esri/smartMapping/symbology/color",
"esri/views/support/colorUtils",
"esri/layers/support/LabelClass",
"esri/symbols/CIMSymbol",
]);
// data urls
var datasets = {
'Tucson Demographics': "35fda63efad14a7b8c2a0a68d77020b7_0",
'Citclops Water': "8581a7460e144ae09ad25d47f8e82af8_0",
'Seattle Bike Facilities': "f4f509fa13504fb7957cef168fad74f0_1",
'NYC bags': "7264acdf886941199f7c01648ba04e6b_0",
'Black Rat Range': "28b0a8a0727d4cc5a2b9703cf6ca4425_0",
'Traffic Circles': "717b10434d4945658355eba78b66971a_6",
'King County Photos': "383878300c4c4f8c940272ba5bfcce34_1036",
}
// dataset switcher
var datasetList = document.getElementById('datasetList');
// populate dropdown with all attributes
for (let [key, value] of Object.entries(datasets)) {
// create new option element and add it to the dropdown
var opt = document.createElement('option');
opt.text = key;
opt.value = value;
datasetList.appendChild(opt);
}
datasetList.addEventListener('change', async event => {
await loadDataset({ datasetId: event.target.value, env: 'prod' });
});
// track state
var state = {};
function initState() {
state = {
dataset: null,
layer: null,
view: null,
widgets: [],
bgColor: null,
legend: null,
categoricalMax: 7,
fieldName: null,
}
}
const DATASET_FIELD_UNIQUE_VALUES = {}; // cache by field name
// URL params
const params = new URLSearchParams(window.location.search);
var env = 'prod';
if (Array.from(params).length != 0) {
var datasetId = params.get('dataset');
const datasetSlug = params.get('slug');
env = params.get('env');
await loadDataset({ datasetId, datasetSlug, env });
} else {
var datasetId = datasetList.options[datasetList.selectedIndex].value;
await loadDataset({ datasetId, env });
}
//
// FILTERING
//
// add a filter, choosing the appropriate widget based on fieldType and various properties
async function addFilter({event = null, fieldName = null, fieldStats = null}) {
let {view, layer} = state;
// if no fieldName is passed directly, get it from the attribute selection event
if (fieldName == null) fieldName = event.currentTarget.dataset.field;
const field = await getDatasetField(fieldName);
let filter = document.createElement('div');
filter.classList.add('filterDiv');
fieldStats = fieldStats ? fieldStats : field.statistics;
filter.innerHTML = await generateLabel(field, fieldStats);
// actions
let icons = document.createElement('span');
icons.innerHTML = " 🅧 ";
icons.onclick = removeFilter;
icons.classList.add('filterIcons');
let tooltip = document.createElement('span');
tooltip.classList.add('tooltip')
tooltip.innerText = "Delete filter";
filter.appendChild(icons);
icons.insertBefore(tooltip, icons.firstChild)
let filtersList = document.getElementById('filtersList');
filtersList.appendChild(filter);
document.getElementById('filtersCount').innerHTML = `Applying ${filtersList.children.length} filters`;
let container = document.createElement('div');
filter.appendChild(container);
const numberLike = await datasetFieldIsNumberLike(fieldName);
// (pseudo-)categorical - most records are covered by a limited # of unique values
// or all other string values
if ((field.simpleType === 'string' && !numberLike)) {
// value list
var widget = await makeStringWidget({ fieldName, container, slider: true });
}
// numerics and dates
else {
widget = await makeHistogramWidget({ fieldName, container, slider: true });
container.classList.add('histogramWidget');
// set whereClause attribute
let whereClause = widget.generateWhereClause(fieldName);
// whereClause = whereClause.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
widget.container.setAttribute('whereClause', whereClause);
}
// if (field.simpleType === 'date') {
// // Time slider
// widget = await makeTimeSliderWidget({ fieldName, container, slider: true });
// }
// scroll the sidebar down to show the most recent filter and keep the attribute search visible
let sidebar = document.getElementById('sidebar')
sidebar.scrollTop = sidebar.scrollHeight;
widget.container.setAttribute('fieldName', fieldName);
widget.container.setAttribute('numberLike', numberLike);
state = {...state, view, layer};
}
//
// WIDGETS
//
// create a histogram
async function makeHistogram ({fieldName, container, slider = false, where = null, features = null }) {
// wrap in another container to handle height without fighting w/JSAPI and rest of sidebar
const parentContainer = container;
let newcontainer = document.createElement('div');
parentContainer.appendChild(newcontainer);
const numberLike = await datasetFieldIsNumberLike(fieldName);
if (!where) {
where = "1=1";
}
if (numberLike) {
where = where.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
try {
let params = {
layer: state.layer,
field: fieldName,
numBins: 30,
where, // optional where clause
features // optional existing set of features
};
let values, 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.warn('Histogram generation failed with automated server call, try using features from server query\n', e);
// params.features = (await layer.queryFeatures()).features;
// const featureCount = await layer.queryFeatureCount();
// if (params.features.length != featureCount) throw new Error('params.features.length != featureCount');
const { features, exceededTransferLimit } = await state.layer.queryFeatures();
if (exceededTransferLimit) throw new Error('Exceeded server limit querying features');
params.features = features;
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.warn('Histogram generation failed with server query, try reconstructing from unique values\n', e);
try {
let uniqueValues = (await getDatasetFieldUniqueValues(fieldName)).values;
let domain = [Math.min(...uniqueValues.map(a => a.value)),
Math.max(...uniqueValues.map(a => a.value))]
// manually reconstruct a feature values array from the unique values and their counts -
let arr = reconstructDataset(uniqueValues);
// use d3 to bin histograms
let d3bins = d3.histogram() // create layout object
.domain([Math.min(...uniqueValues.map(a => a.value)),
Math.max(...uniqueValues.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
var 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(...uniqueValues.map(a => a.value)),
'maxValue': Math.max(...uniqueValues.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.warn('Histogram generation failed with unique values, try using features in layer view\n', e);
let layerView = await view.whenLayerView(layer);
params.features = (await layerView.queryFeatures()).features;
// const featureCount = await layer.queryFeatureCount();
values = await generateHistogram(params);
source = 'layerView';
}
}
}
// Determine if field is an integer
const field = getDatasetField(fieldName);
const integer = await datasetFieldIsInteger(fieldName);
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 histogram
async function makeHistogramWidget({ fieldName, container = null, slider = true }) {
var {widgets, layer} = state;
const wrapper = document.createElement('div');
wrapper.classList.add('histogramWidget');
container = container ? container : document.getElementById('filters');
container.appendChild(wrapper);
// filter by existing widgets on creation
let features;
if (widgets.length > 0) {
const where = concatWheres({ server: true });
// query layer for all features in the other layers, filtered by the state of current layer
features = (await layer.queryFeatures( { where, outFields: [fieldName] })).features;
}
const histogram = await makeHistogram({ fieldName, features, container: wrapper, slider: true });
if (histogram.widget) {
wrapper.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(fieldName, histogram.widget);
updateWidgets(fieldName, histogram.widget);
});
// register widget
state.widgets.push(histogram.widget);
}
return histogram.widget;
}
// create a value list of checkboxes
async function createValueList ({ fieldName, container, onUpdateValues }) {
var {dataset, layer} = state;
container.classList.add('filter');
const list = document.createElement('div');
const header = document.createElement('div');
// header.innerText = 'Values';
header.classList.add('sidebarItemHeader');
list.appendChild(header);
const checkboxList = document.createElement('div');
list.appendChild(checkboxList);
const field = getDatasetField(fieldName);
const stats = await getDatasetFieldUniqueValues(fieldName, layer);
// if (!stats.topValues || stats.topValues.length === 0) {
// return {};
// }
let checkboxListenerDisabled = false;
function addValueListCheckbox (value, checkboxes) {
const checkbox = document.createElement('calcite-checkbox');
checkbox.value = JSON.stringify(value);
// const labelText = document.createTextNode(`${value.value} (${(value.pct * 100).toFixed(2)}% of records)`);
const labelText = document.createElement('span');
// handle null-ish, date, and other field formatting
if (value.value == null || (typeof value.value === 'string' && value.value.trim() === '')) {
labelText.innerHTML = '<span style="color: gray">No value</span>';
} else if (field.simpleType === 'date') {
labelText.innerHTML = formatDate(value.value);
} else {
labelText.innerHTML = value.value;
}
const labelSubText = document.createElement('span');
labelSubText.classList.add('subText');
labelSubText.innerText = value.pct != null ? `${(value.pct * 100).toFixed(2)}%` : '';
const onlyLink = document.createElement('a');
onlyLink.classList.add('valueListSideLink');
onlyLink.href = '#';
onlyLink.innerText = 'only';
const label = document.createElement('label');
label.classList.add('valueListCheckbox');
label.appendChild(checkbox);
label.appendChild(labelText);
label.appendChild(labelSubText);
label.appendChild(onlyLink);
checkbox.addEventListener('calciteCheckboxChange', (event) => {
if (!checkboxListenerDisabled) {
onUpdateValues({ checkboxes, event });
}
});
onlyLink.addEventListener('click', event => {
// disable change listener to keep it from firing as all checkboxes are updated
checkboxListenerDisabled = true;
// check selected box and un-check all others
checkboxes.forEach(c => {
c.checked = c === checkbox ? true : false;
});
// re-enable listener and invoke update handler just once
checkboxListenerDisabled = false;
onUpdateValues({ checkboxes, event });
});
checkboxList.appendChild(label);
return checkbox;
}
// clear all link
const clearLink = document.createElement('a');
clearLink.classList.add('valueListSideLink');
clearLink.href = '#';
clearLink.innerText = 'clear';
header.appendChild(clearLink);
clearLink.addEventListener('click', event => {
// disable change listener to keep it from firing as all checkboxes are updated
checkboxListenerDisabled = true;
// un-check all checkboxes
checkboxes.forEach(c => c.checked = false);
// re-enable listener and invoke update handler just once
checkboxListenerDisabled = false;
onUpdateValues({ checkboxes, event });
});
const checkboxes = [];
checkboxes.push(...stats.topValues.map(value => addValueListCheckbox(value, checkboxes)));
container.appendChild(list);
// search box
if (stats.uniqueCount > stats.topValues.length) {
const searchBox = document.createElement('input');
searchBox.classList.add('valueListSearchBox');
searchBox.type = 'text';
searchBox.placeholder = `Search ${stats.uniqueCount} ${fieldName} values...`;
const wrapper = document.createElement('div');
wrapper.classList.add('valueListSearchBoxWrapper');
list.appendChild(searchBox);
function searchSource(params) {
return async function doSearch(query, callback) {
const where = field.simpleType === 'date' ?
`CAST(${fieldName} AS VARCHAR(256)) LIKE lower('%${query}%')` : // convert dates to strings
`lower(${fieldName}) LIKE lower('%${query}%')`
const { features } = await layer.queryFeatures({
// where: `lower(${fieldName}) LIKE lower('%${query}%')`,
// where: `CAST(${fieldName} AS VARCHAR(256)) LIKE lower('%${query}%')`,
where,
orderByFields: [fieldName],
outFields: [fieldName],
returnDistinctValues: true,
num: 10
});
// de-dupe results (by turning into set)
const vals = new Set(features
.map(f => f.attributes[fieldName])
.map(v => typeof v === 'string' ? v.trim() : v)
.filter(value => {
// exclude any results already selected in checkboxes
return !checkboxes
.filter(c => c.checked)
.map(c => JSON.parse(c.value))
.map(v => v.value)
.includes(value);
})
);
// return values
callback([...vals].map(value => ({
value,
label: field.simpleType === 'date' ? formatDate(value) : value
})));
};
}
autocomplete(searchBox, { hint: false, clearOnSelected: false, }, [{
source: searchSource({ hitsPerPage: 5 }),
displayKey: 'label',
templates: {
suggestion: function(suggestion) {
return suggestion.label;
}
}
}]).on('autocomplete:selected', function(event, suggestion, context) {
let checkbox = checkboxes
.filter(c => !c.checked)
.find(c => JSON.parse(c.value).value === suggestion.value);
if (!checkbox) {
checkbox = addValueListCheckbox(suggestion, checkboxes);
checkboxes.push(checkbox);
}
checkbox.checked = true;
// TODO: why is this necessary? calcite event listener doesn't fire when checkbox added and set to checked in this flow
onUpdateValues({ checkboxes });
});
}
return { checkboxes, fieldStats: stats };
}
// make and place a value list of checkboxes
async function makeStringWidget({ fieldName, container = null, slider = true }) {
container.classList.add('valueListWidget');
const field = getDatasetField(fieldName);
// Build filter/where clause and update layer
const onCheckboxChange = ({ checkboxes }) => {
let checked = checkboxes.filter(c => c.checked).map(c => JSON.parse(c.value));
let whereClause = '1=1';
if (checked.length > 0) {
const hasNull = checked.find(c => c.value == null) ? true : false;
checked = checked.filter(c => c.value != null);
let whereVals;
if (field.simpleType === 'date') {
whereVals = checked.map(c => +new Date(c.value));
whereClause = whereVals.map(v => `${fieldName} = ${v}`).join(' OR ');
} else {
whereVals = checked.map(c => {
if (typeof c.value === 'string') {
return `'${c.value}'`
} else {
return c.value;
}
});
whereClause = `${fieldName} IN (${whereVals.join(', ')})`;
}
if (hasNull) {
whereClause = whereVals ? `${whereClause} OR ` : '';
whereClause = `${fieldName} IS NULL`; // need special SQL handling for null vales
}
}
container.setAttribute('whereClause', whereClause);
const where = concatWheres({ server: false });
updateLayerViewEffect({ where });
};
const { fieldStats } = await createValueList({ fieldName, container, onUpdateValues: onCheckboxChange });
fieldStats.container = container;
// register widget
state.widgets.push(fieldStats)
return fieldStats;
}
//
// UDPATE THINGS
//
// update layerview filter based on widget, throttled
const updateLayerView = _.throttle(
async (fieldName, widget, value = null) => {
let whereClause;
if (widget.label === "Histogram Range Slider") {
whereClause = widget.generateWhereClause(fieldName);
// whereClause = whereClause.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
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({ server: false });
await updateLayerViewEffect({ where });
},
100,
{trailing: false}
);
// update the bins of all histograms except the current widget, throttled
const updateWidgets = _.throttle(
async (fieldName, currentWidget) => {
let widgets = Array.from(listWidgetElements());
// if there's only one widget, skip this
if (widgets.length === 1) return
// collect other widgets' fieldNames, skipping the current widget (handles nested widgets too)
let otherWidgets = widgets.filter(w => w.getAttribute('fieldname') != fieldName);
let fieldNames = otherWidgets.map(w => w.getAttribute('fieldname'));
// convert to a set to remove any duplicates (nested widgets), then back to array
fieldNames = [...new Set(fieldNames)];
if (fieldNames.length == 0) return;
let whereClause = currentWidget.container.getAttribute('whereClause');
const numberLike = currentWidget.container.getAttribute('numberLike') === "true";
if (numberLike) {
whereClause = whereClause.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
try {
// query layer for all features in the other layers, filtered by the state of current layer
var { features } = await state.layer.queryFeatures( { where: whereClause, outFields: fieldNames });
} catch(e) {
throw new Error(`Failed to query layer for ${fieldName}: ${e}`)
}
try {
// update other widgets, passing in the filtered feature set
throttledUpdateOthers(otherWidgets, 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, fieldName, features, { numberLike } = {}) {
var {layer, view} = state;
let values;
if (features) {
let valueExpression;
let sqlExpression;
if (numberLike) {
// copy features and cast string field to number
// features = features.map(f => {
// const clone = f.clone();
// const value = Number(clone.getAttribute(fieldName));
// clone.setAttribute(fieldName, value);
// // clone.sourceLayer = null;
// return clone;
// });
valueExpression = `Number($feature.${fieldName})`;
sqlExpression = `CAST(${fieldName} AS FLOAT})`;
}
let params = {
layer,
view,
features,
field: valueExpression ? null : fieldName,
valueExpression,
// field: fieldName,
// sqlExpression,
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)
}
}
}
function updateOthers(otherWidgets, features) {
for (const widget of otherWidgets) {
// can't update TimeSliders
if (widget.label == "TimeSlider") continue;
const numberLike = widget.getAttribute('numberLike') === "true";
updateHistogram(widget.widget, widget.getAttribute('fieldName'), features, { numberLike });
}
}
const throttledUpdateOthers = _.throttle(updateOthers, 100, {trailing: false});
//
// UTILITY FUNCTIONS
//
// list all known widget DOM elements
function listWidgetElements() {
return [...document.getElementById('filtersList').querySelectorAll('[whereClause]')];
}
// concatenate all the where clauses from all the widgets
function concatWheres( { server = false } = {}) {
let whereClause = '';
let widgets = listWidgetElements();
// generate master here clause with simple string concatenation
for (const [x, widget] of widgets.entries()) {
if (x > 0) whereClause += ' AND ';
let widgetWhere = widget.getAttribute('whereClause');
// explicit cast for number-likes, for feature layer (server-side) queries ONLY
// skip for feature layer view (client-side) queries, which work *without* the cast (but fail with it)
const numberLike = widget.getAttribute('numberLike') === "true";
if (server && numberLike) {
const fieldName = widget.getAttribute('fieldName');
widgetWhere = widgetWhere.replace(fieldName, `CAST(${fieldName} AS FLOAT)`); // for number-like fields
}
whereClause += '(' + widgetWhere + ')';
// whereClause += '(' + widget.getAttribute('whereClause') + ')';
}
return whereClause;
}
async function removeFilter(event, fieldName = null) {
fieldName = fieldName ? fieldName : event.currentTarget.dataset.field;
let filter = event.currentTarget.parentElement;
let filtersList = filter.parentElement;
filter.remove();
document.getElementById('filtersCount').innerHTML = `Applying ${filtersList.children.length} filters`;
updateLayerViewEffect();
}
// draw whole map from scratch
async function drawMap() {
var {dataset, layer, view} = state;
const darkModeCheckbox = document.querySelector('#darkMode calcite-checkbox');
const map = new Map({
// choose a light or dark background theme as default
basemap: darkModeCheckbox?.checked ? "dark-gray-vector" : "gray-vector",
layers: layer,
});
if (view) {
// update existing view, then exit
view.map = map;
state = {...state, view}
// explicitly wait for bgColor to be updated, then update the layerView
await getBgColor().then(color => {
state.bgColor = color;
updateLayerViewEffect();
});
return view;
}
var view = new MapView({
container: "viewDiv",
map: map,
extent: getDatasetExtent(dataset),
ui: { components: [] }
});
// add toggle checkboxes
view.ui.add('zoomToData', 'top-right');
const zoomToDataCheckbox = document.querySelector('#zoomToData calcite-checkbox');
zoomToDataCheckbox.addEventListener('calciteCheckboxChange', () => {
updateLayerViewEffect();
});
view.ui.add('darkMode', 'top-right');
darkModeCheckbox.addEventListener('calciteCheckboxChange', async () => {
state.view = await drawMap();
autoStyle({fieldName: state.fieldName})
});
view.ui.add('labels', 'top-right');
const labelsCheckbox = document.querySelector('#labels calcite-checkbox');
labelsCheckbox.addEventListener('calciteCheckboxChange', () => {
autoStyle({fieldName: state.fieldName})
});
// put vars on window for debugging
Object.assign(window, { state, map, getDatasetField, getDatasetFieldUniqueValues, /*histogram, histogramValues,*/ generateHistogram, HistogramRangeSlider, uniqueValues });
// Dataset info
document.querySelector('#datasetName').innerHTML = dataset.attributes.name;
document.querySelector('#orgName').innerHTML = dataset.attributes.orgName || '';
document.querySelector('#recordCount').innerHTML = `${dataset.attributes.recordCount} records`;
// update state
state.view = view;
// bgColor needs state.view to be set first
state.bgColor = await getBgColor();
return view;
}
// update layerview filter based on histogram widget, throttled
const updateLayerViewWithHistogram = _.throttle(
async (where) => {
await updateLayerViewEffect({ where });
},
50
);
async function loadDataset (args) {
// reset state
initState();
var dataset, layer;
if (args.url) { // dataset url provided directly
const datasetURL = args.url;
try {
// dataset = (await fetch(datasetURL).then(r => r.json()));
dataset = {attributes: {url: args.url}}
} catch(e) { console.log('failed to load dataset from url:', args.url, e); }
} else if (args.datasetId) { // dataset id provided directly
// https://opendataqa.arcgis.com/api/v3/datasets/97a641ac39904f349fb5fc25b94207f6
const datasetURL = `https://opendata${args.env === 'qa' ? 'qa' : ''}.arcgis.com/api/v3/datasets/${args.datasetId}`;
try {
dataset = (await fetch(datasetURL).then(r => r.json())).data;
} catch(e) { console.log('failed to load dataset from id', args.datasetId, e); }
} else if (args.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(args.datasetSlug)}`
const datasetURL = `https://opendata${args.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', args.datasetSlug, e); }
}
// initialize a new layer
const url = dataset.attributes.url;
layer = new FeatureLayer({
renderer: {type: 'simple'},
url,
minScale: 0,
maxScale: 0,
});
// update state
state = {...state, layer, dataset};
// clear filters list
clearFilters();
// clear widgets list
state.widgets = [];
// update attributes lists
updateAttributeList('#filterAttributeList', () => addFilter({event}) );
updateAttributeList('#styleAttributeList', () => autoStyle({event}) );
let filterAttributeSearchElement = document.getElementById("filterAttributeSearch")
filterAttributeSearchElement.addEventListener("input", filterAttributeSearchInput);
filterAttributeSearchElement.addEventListener("change", filterAttributeSearchChange); // clear input button
let filterPlaceholderText = `Search ${dataset.attributes.fields.length} Attributes by Name`;
filterAttributeSearchElement.setAttribute('placeholder', filterPlaceholderText);
let styleAttributeSearchElement = document.getElementById("styleAttributeSearch")
styleAttributeSearchElement.addEventListener("input", styleAttributeSearchInput);
styleAttributeSearchElement.addEventListener("change", styleAttributeSearchChange); // clear input button
let stylePlaceholderText = `Search ${dataset.attributes.fields.length} Attributes by Name`;
styleAttributeSearchElement.setAttribute('placeholder', stylePlaceholderText);
state.usePredefinedStyle = false; // disable for now
// draw map once before autoStyling because getBgColor() requires an initialized layerView object
state.view = await drawMap();
autoStyle({}); // guess at a style for this field
}
// manually reconstruct a feature values array from unique values and their counts
function reconstructDataset(values) {
// normalize array length to 1000, as precision isn't as important as speed here
const divisor = state.dataset.attributes.recordCount / 1000;
// const divisor = 1; // alternately, use the whole set
let arr = [];
for (let x = 0; x < values.length; x++) {
for (let y = 0; y < Math.ceil(values[x].count/divisor); y++) {
arr.push(values[x].value);
};
}
return arr;
}
// https://stackoverflow.com/questions/6122571/simple-non-secure-hash-function-for-javascript
function getHash(s) {
var hash = 0;
if (s.length == 0) {
return hash;
}
for (var i = 0; i < s.length; i++) {
var char = s.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return Math.abs(hash);
}
//
// STYLING
//
// determine whether the map background is dark or light
async function getBgColor() {
const {view, layer} = state;
try {
// make sure there's a layerView, then
var bgColor = view.whenLayerView(layer).then(
// get and return the theme
async () => await viewColorUtils.getBackgroundColorTheme(view).then(theme => theme));
} catch(e) {
console.warn(`Couldn't detect basemap color theme - tab must be in foreground. Choosing "light."\n`, e)
bgColor = "light"; // set default bgColor
}
return bgColor;
}
// Choose symbology based on various dataset and theme attributes
async function autoStyle ({event = null, fieldName = null}) {
var {dataset, layer, view, usePredefinedStyle} = state;
// SET COLORS
// get basemap color theme: "light" or "dark"
var bgColor = await getBgColor();
state.bgColor = bgColor;
// choose default colors based on background theme – dark on light, light on dark
// use rgb values because CIMSymbols don't understand web color names
var fillColor = bgColor == "dark" ? [0,196,210,255] : [173,216,230,255]; // lightblue and steelblue
var strokeColor = bgColor == "dark" ? [70,130,180,255] : [70,130,180,255]; // steelblue and white
// set bad-value colors
const badStrokeColor = geotype == "line" ? bgColor == "dark" ? [128,128,128,255] : [64,64,64,255] : [128,128,128,255]; // grey outlines
const badFillColor = [255,255,255,255]; // white fills
// set "other" colors for unique-value renderers
const otherStrokeColor = [128,128,128,255]; // grey
const otherFillColor = [192,192,192,255]; // light grey
var symbol;
var renderer = {
type: "simple", // autocasts as new SimpleRenderer()
visualVariables: [],
};
// declare shorthand geometry types
const geometryType = dataset.attributes.geometryType;
var geotype = (geometryType == 'esriGeometryPoint') ? 'point'
: (geometryType == 'esriGeometryMultiPoint') ? 'point'
: (geometryType == 'esriGeometryPolygon') ? 'polygon'
: (geometryType == 'esriGeometryLine') ? 'line'
: (geometryType == 'esriGeometryPolyline') ? 'line'
: geometryType;
// SET GEOMETRY
if (geotype === 'point') {
// use CIMSymbol so we can have sub-pixel outline widths
var cimsymbol = new CIMSymbol({
data: {
type: "CIMSymbolReference",
symbol: {
type: "CIMPointSymbol",
symbolLayers: [{
type: "CIMVectorMarker",
enable: true,
size: 16,
frame: {
xmin: 0,
ymin: 0,
xmax: 14,
ymax: 14
},
markerGraphics: [{
type: "CIMMarkerGraphic",
geometry: {
// circle geo taken from https://developers.arcgis.com/javascript/latest/sample-code/sandbox/index.html?sample=cim-primitive-overrides
rings: [
[
[8.5, 0.2],[7.06, 0.33],[5.66, 0.7],[4.35, 1.31],[3.16, 2.14],[2.14, 3.16],[1.31, 4.35],[0.7, 5.66],[0.33, 7.06],[0.2, 8.5],[0.33, 9.94],[0.7, 11.34],[1.31, 12.65],[2.14, 13.84],[3.16, 14.86],[4.35, 15.69],[5.66, 16.3],[7.06, 16.67],[8.5, 16.8],[9.94, 16.67],[11.34, 16.3],[12.65, 15.69],[13.84, 14.86],[14.86, 13.84],[15.69, 12.65],[16.3, 11.34],[16.67, 9.94],[16.8, 8.5],[16.67, 7.06],[16.3, 5.66],[15.69, 4.35],[14.86, 3.16],[13.84, 2.14],[12.65, 1.31],[11.34, 0.7],[9.94, 0.33],[8.5, 0.2]
]
]},
symbol: {
type: "CIMPolygonSymbol",
symbolLayers: [
{
type: "CIMSolidStroke",
width: .45,
color: strokeColor,
},
{
type: "CIMSolidFill",
color: fillColor,
},
]
}
}]
}]
}
}
});
symbol = cimsymbol;
} else if (geotype === 'line') {
symbol = {
type: 'simple-line',
width: '2px',
color: strokeColor,
};
} else if (geotype === 'polygon') {
symbol = {
type: 'simple-fill',
color: fillColor,
outline: {
color: strokeColor,
width: 0.5,
},
};
}