-
Notifications
You must be signed in to change notification settings - Fork 0
/
charts.mjs
1241 lines (1127 loc) · 45 KB
/
charts.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",
"esri/symbols/support/cimSymbolUtils",
]);
// data urls
var datasets = {
'Tucson Demographics': "35fda63efad14a7b8c2a0a68d77020b7_0",
'NYC bags': "7264acdf886941199f7c01648ba04e6b_0",
'Seattle Bike Facilities': "f4f509fa13504fb7957cef168fad74f0_1",
'Citclops Water': "8581a7460e144ae09ad25d47f8e82af8_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,
highlights: [],
displayField: null,
chart: null,
}
}
var chart, cedarChart, guide;
var matches = [];
// set up symbol types
var geoSymbols = {
'point': 'simple-marker',
'line': 'simple-line',
'polygon': 'simple-fill'
}
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 });
}
//
// CHARTING
//
// add a chart, making a best guess at appropriate style based on fieldType and various properties
async function addChart({event = null, fieldName = null, fieldStats = null}) {
console.log('addChart:', arguments);
let {view, layer, dataset, displayField} = 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);
document.getElementById('chart').style.display = "inline";
view.ui.add('chart', 'bottom-left');
var definition = {
type: "bar",
datasets: [
{
// url: "https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/USA_States_Generalized/FeatureServer/0",
url: dataset.attributes.url,
query: {
// orderByFields: "POPULATION DESC"
orderByFields: fieldName
}
}
],
series: [
{
category: { field: displayField, label: displayField },
value: { field: fieldName, label: fieldName },
}
],
overrides: {
"listeners": [ // listeners must be added here to be passed to AmCharts
{
"event": "init",
"method": e => {
console.log('init', e)
e.chart.graphs[0].fillColorsField = "color";
e.chart.graphs[0].lineColorField = "color"; // either works
state.chart = e.chart;
window.chart = e.chart;
guide = new AmCharts.Guide();
e.chart.categoryAxis.addGuide(guide);
},
},
{
"event": "zoomed",
"method": e => console.log('zoom')
},
{
"event": "clicked",
"method": e => console.log('clicked')
},
{
"event": "clickGraphItem",
"method": e => {
console.log('clickGraphItem', e)
e.item.lineColor = "red";
e.item.fillColors = "red";
e.chart.drawChart(); // drawChart works here but not outside an event
}
},
{
"event": "changed", // cursor position has changed on the chart
"method": async e => {
var xValue = e.chart.categoryAxis.coordinateToValue(e.x);
var yValue = AmCharts.roundTo(e.chart.valueAxes[0].coordinateToValue(e.y), 2);
var feature = e.chart.chartData.filter(i => i.dataContext[displayField] == xValue)[0];
if (!feature) {
feature = e.chart.chartData.filter(i => i.dataContext[displayField] == xValue)[0];
}
let name = feature.category || feature.name;
console.log(`Chart item: ${name}`)
highlightFeature({name});
drawGuides({name});
}
},
],
},
};
cedarChart = new cedar.Chart("chart", definition);
window.cedarchart = cedarChart;
cedarChart.show()
.then(e => {
//
});
}
//
// UTILITY FUNCTIONS
//
// draw whole map from scratch
async function drawMap() {
var {dataset, layer, view, displayField} = 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: [] },
});
view.whenLayerView(layer).then(r => state.layerView = r);
// 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`;
view.on("pointer-move", async function(evt) {
let {layer, layerView, highlights} = state;
var screenPoint = {
x: evt.x,
y: evt.y
};
// the hitTest() checks to see if any graphics in the view
// intersect the given screen x, y coordinates
const options = {
include: state.layer,
}
view.hitTest(screenPoint, options)
.then( function(response) {
if (response.results.length) {
matches.push(response.results[0]);
} else {
view.graphics.removeAll(); // reset
view.popup.close();
}
});
if (matches && matches.length) {
var match = matches.pop();
if (match.graphic?.geometry) {
highlightFeature({response: match});
if (state.chart) drawGuides({response: match});
// position popup behind direction of pointer's travel so it doesn't block the hittests
let alignment = state.direction == "North" ? "bottom-center" :
state.direction == "East" ? "bottom-left" :
state.direction == "South" ? "top-center" :
"top-right";
if (!view.popup.visible ||
(view.popup.visible &&
match.graphic.geometry.centroid.x != view.popup.location.x &&
match.graphic.geometry.centroid.y != view.popup.location.y)) {
// new popup
view.popup.alignment = alignment;
view.popup.open({
location: match.graphic.geometry.centroid,
features: [match.graphic],
});
} // otherwise leave the existing popup alone
}
matches = [];
}
});
// update state
state.view = view;
// bgColor needs state.view to be set first
state.bgColor = await getBgColor();
return view;
}
// color a feature red
async function highlightFeature({response = null, name = null}) {
let {view, layer, displayField, geotype} = state;
var symbol = {
type: geoSymbols[geotype],
color: [255,0,0,0.5],
style: geotype == 'point' ? "circle" : 'solid',
outline: {
color: "red",
width: 2
}
};
var selectionGraphic = {
type: geotype // autocast to new Graphic()
};
if (name) {
var query = layer.createQuery();
query.where = `${displayField} = '${name}'`;
query.returnGeometry = true;
response = await layer.queryFeatures(query).then(response => response);
selectionGraphic.geometry = response.features[0].geometry || response.geometry;
} else {
selectionGraphic = response.graphic;
}
view.graphics.removeAll(); // reset
selectionGraphic.symbol = symbol;
view.graphics.add(selectionGraphic);
}
// draw a red line on a specific category on the chart's "category" x-axis
function drawGuides({response = null, name = null}) {
let {displayField, chart} = state;
// match a graphic to a chart category
if (!name) { // get a name from the response object
var graphic = response.results ? response.results[0].graphic : response.graphic;
var attributes = graphic.attributes;
name = attributes[displayField];
if (!name) { // use any attribute to get a category name
var findByField = Object.keys(attributes)[0]; // grab the first one
let matchValue = attributes[findByField]; // get the value
let matchIndex = chart.dataProvider.findIndex(m => m[findByField] == matchValue); // match by value
let match = chart.dataProvider[matchIndex];
name = match[displayField]; // extract matching category name
}
}
// draw chart guides
// https://docs.amcharts.com/3/javascriptcharts/Guide
guide.category = name; // start guide highlight here
guide.toCategory = name; // end guide highlight here
guide.expand = true;
guide.fillAlpha = 1;
guide.fillColor = "#ff0000";
chart.categoryAxis.draw(); // AH HA - update guides
}
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); }
}
// clear any existing charts
document.getElementById('chart').style.display = "none";
document.getElementById('chart').innerHTML = '';
// choose a field to use as the chart's "category" x-axis - this is the attribute used to identify a given feature to a human. typically this would be "name" etc but many datasets don't include that.
let displayField = dataset.attributes.displayField; // check for a displayField - for more info: https://community.esri.com/t5/arcgis-pro-questions/what-is-the-display-field/m-p/742003
if (displayField == "") displayField = dataset.attributes.fieldNames.find(i => i.toLowerCase().includes("name"))
if (typeof displayField == "undefined") displayField = "NAME"; // ¯\_(ツ)_/¯
// initialize a new layer
const url = dataset.attributes.url;
layer = new FeatureLayer({
renderer: {type: 'simple'},
url,
minScale: 0,
maxScale: 0,
popupTemplate: {
content: `${displayField}: {${displayField}}`,
overwriteActions: true,
}
});
// update state
state = {...state, layer, dataset, displayField};
// clear widgets list
state.widgets = [];
// update attributes lists
updateAttributeList('#chartAttributeList', () => addChart({event}) );
let chartAttributeSearchElement = document.getElementById("chartAttributeSearch")
chartAttributeSearchElement.addEventListener("input", chartAttributeSearchInput);
chartAttributeSearchElement.addEventListener("change", chartAttributeSearchChange); // clear input button
let chartPlaceholderText = `Search ${dataset.attributes.fields.length} Attributes by Name`;
chartAttributeSearchElement.setAttribute('placeholder', chartPlaceholderText);
// 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, displayField} = 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;
state.geotype = geotype;
// 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,
},
};
}
// GET FIELD
// check for fieldName in args, the event object,
if (!fieldName) { fieldName = event?.currentTarget?.getAttribute('data-field'); }
// a displayField specified in the dataset,
if (!fieldName) { fieldName = dataset?.attributes?.displayField; }
// or just set default fieldName to "NAME"
if (!fieldName && dataset.attributes.fieldNames.includes("NAME")) { fieldName = "NAME"; }
// if there's a fieldName then style it by field
fieldStyle: // label this block so we can break out of it when necessary
if (fieldName) {
state.fieldName = fieldName; // used by toggle checkboxes
var field = getDatasetField(fieldName);
// TODO: don't use cached statistics, as they're frequently out-of-date and incomplete
var fieldStats = field.statistics;
if (fieldStats.values.length == 0) { // it happens
console.warn("Couldn't get statistics values for field '"+fieldName+"'.");
break fieldStyle;
}
try {
// sometimes stats have .min and .max, sometimes they have .value and .count
var { categorical, pseudoCategorical } = await datasetFieldCategorical(fieldName);
var numberLike = await datasetFieldIsNumberLike(fieldName);
if (field.simpleType == "string" && numberLike) {
// recast values as numbers and resort
fieldStats.values = fieldStats.values.map(e => Object.assign({...e, value: parseFloat(e.value)}))
.sort((a, b) => a.value !== b.value ? a.value < b.value ? -1 : 1 : 0);
}
var minValue =
typeof fieldStats.values.min !== "undefined" ? fieldStats.values.min :
typeof fieldStats.values.length !== "undefined" ? fieldStats.values[0].value :
null;
var minLabel = minValue;
var maxValue =
typeof fieldStats.values.max !== "undefined" ? fieldStats.values.max :
typeof fieldStats.values.length !== "undefined" ? fieldStats.values[fieldStats.values.length -1].value :
null;
var maxLabel = maxValue;
} catch(e) {
console.warn("Couldn't get statistics for styling field '"+fieldName+"':", e);
break fieldStyle;
}
// clear any existing labelingInfo sent from the server
layer.labelingInfo = [ ];
var uniqueValues = (await getDatasetFieldUniqueValues(fieldName)).values;
var numGoodValues = uniqueValues.filter(i => !isBadValue(i.value)).length;
// STYLING
// reset colors – these will be used as "No value" symbols
symbol = copyAndColor(symbol, strokeColor, fillColor);
let {categoricalMax} = state;
if (categorical || (pseudoCategorical && !numberLike)) {
// your basic categorical field
// GET RAMP
let ramp = colorRamps.byName("Mushroom Soup");
let rampColors = ramp.colors;
var numColors = rampColors.length;
// if the field has only a single unique non-bad value, pick a single color, hashing by fieldName –
// this will be more likely to show a visual change when switching between two fields which both have a single value
if ( (numGoodValues == 1) ||
((fieldStats.values.min && fieldStats.values.max) &&
(fieldStats.values.min === fieldStats.values.max))
) {
var indexOffset = getHash(fieldName) % numColors; // pick an offset
// replace the entire ramp with a single color
rampColors = [rampColors[indexOffset]];
numColors = 1;
}
// sort by values - if only pseudocategorical leave it sorted by the default: prevalence
if (categorical) {
uniqueValues.sort((a, b) => a.value !== b.value ? a.value < b.value ? -1 : 1 : 0);
}
// TODO: sort before assigning color values? currently values are assigned color by frequency
// generate categorical colors for field
var uniqueValueInfos = [];
// pick a limit to the number of legend entries
const numEntries = categorical ? Math.min(uniqueValues.length, categoricalMax) : // the top categories
pseudoCategorical <= categoricalMax ? pseudoCategorical : // the top pseudocategories
5; // just show the top 5
if (numGoodValues == 0 && uniqueValues.length == 1) { // it happens
var defaultSymbol = copyAndColor(symbol, badStrokeColor, badFillColor);
var defaultLabel = "No value";
} else {
for (let x = 0; x < numEntries; x++) {
if (isBadValue(uniqueValues[x].value)) {
// style any bad points as white rings and lines as grey
var strokeColor = badStrokeColor;
var fillColor = badFillColor;
} else {
// rollover calculation
// TODO: interpolate over whole range to prevent duplicate colors
var indexOffset = x % numColors;
var strokeColor = [
// TODO: switch to proportional interpolation
rampColors[indexOffset].r * .5, // same as fillColor but half as bright
rampColors[indexOffset].g * .5,
rampColors[indexOffset].b * .5,
255 //alpha is always opaque
];
// set fillColor
var fillColor = [
rampColors[indexOffset].r,
rampColors[indexOffset].g,
rampColors[indexOffset].b,
255 // alpha is always opaque
];
}
// clone and color symbol
let uniqueSymbol = copyAndColor(symbol, strokeColor, fillColor);
// add symbol to the stack
uniqueValueInfos.push( {
value: uniqueValues[x].value || "",
label: field.simpleType == "date" ? formatDate(uniqueValues[x].value) :
isBadValue(uniqueValues[x].value) ? "No value" :
uniqueValues[x].value,
symbol: uniqueSymbol,
});
}
}
let numOthers = uniqueValues.length - numEntries;
// set defaults
if (numOthers > 0) {
// use the "other" default color for the long tail of categories
var defaultSymbol = copyAndColor(symbol, otherStrokeColor, otherFillColor);
var defaultLabel = (numOthers + " other") + (numOthers > 1 ? "s" : "");
}
// set renderer
renderer = {...renderer,
type: "unique-value",
defaultSymbol,
defaultLabel,
uniqueValueInfos,
};
} else if (numberLike) { // number-like and non-categorical
// SET RAMP
// custom ramp - pink to blue
var rMin = {r:255, g:200, b:221, a:255};
var rMax = bgColor == "dark" ? {r:61, g:79, b:168, a:255} : {r:21, g:39, b:128, a:255};
renderer.visualVariables.push({
type: "color",
field: fieldName,
stops: [{
value: minValue,
color: {r: rMin.r, g: rMin.g, b: rMin.b, a: 1},
label: (field.simpleType == "date") ? formatDate(minValue) : minLabel
},{
value: maxValue,
color: {r: rMax.r, g: rMax.g, b: rMax.b, a: 1},
label: (field.simpleType == "date") ? formatDate(maxValue) : maxLabel
}]
});
if (field.simpleType !== "date") {
// add one more midValue
var midValue = (parseFloat(maxValue)+parseFloat(minValue))/2;
// if min and max are integers, make mid integer too
if (numberLike && (Number.isInteger(parseFloat(maxValue)) && Number.isInteger(parseFloat(maxValue)))) {
midValue = parseInt(midValue+.5);
}
if (midValue != minValue && midValue !== maxValue) {
// ensure accurate placement of midValue along the ramp, in case of integer coersion
let divisor = (midValue-minValue)/(maxValue - minValue);
// color
var rMid = {r: (rMax.r + rMin.r) * divisor, g: (rMax.g + rMin.g) * divisor, b: (rMax.b + rMin.b) * divisor};
renderer.visualVariables[renderer.visualVariables.length-1].stops.push({
value: midValue,
color: {r: rMid.r, g: rMid.g, b: rMid.b, a: 1},
label: midValue,
});
}
}
// set default label
renderer.label = numGoodValues < uniqueValues.length ? "No value" : "Feature";
// if it's neither categorical nor number-like, use default styling but add labels
} else {
layer.labelingInfo = [ addLabels(fieldName) ];
}
} // end if (fieldName)
renderer = {...renderer, symbol, field: fieldName};
// also add labels if the "Labels on" toggle is checked
if (document.querySelector('#labels calcite-checkbox')?.checked && fieldName) {
layer.labelingInfo = [ addLabels(fieldName) ];
}
// SET SCALE
if (geotype == "point") {
renderer.visualVariables.push({
type: "size",
valueExpression: "$view.scale",
// zoom levels and scale values based on layerView.zoom and layerView.scale
stops: [
{
size: 3.5,
value: 36978595.474472 // z3
},
{
size: 4.5,
value: 577790.554289 // z9
},
{
size: 6,
value: 18055.954822 // z15
},
]
});
} else if (geotype == "line") {
renderer.visualVariables.push({
type: "size",
valueExpression: "$view.scale",
stops: [
{
size: .5,
value: 1155581.108577 // z8
},
{
size: 1,
value: 577790.554289 // z9
},
{
size: 2,
value: 144447.638572 // z11
},
]
});
}
// ADD LABELS
// add labels by default to polygons only for now
if (geotype == "polygon") {
if (!bgColor) {
// bgcolor might not be set if the tab wasn't visible when loaded, give it another chance
bgColor = await getBgColor();
}
if (fieldName) {
var expression = "$feature."+fieldName;
// label if field matches a few conditions:
if (
// there's more than one value
uniqueValues.length > 1 &&
(
(simpleFieldType == "string" && !numberLike) || // it's a non-numberlike string, or
(field.statistics.values.count == uniqueValues.length) // every value is unique
)
){
// TODO: don't violate DRY (labels also set above)
const labels = new LabelClass({
labelExpressionInfo: expression ? { expression } : null,
symbol: {
type: "text", // autocasts as new TextSymbol()
color: bgColor == "light" ? "#1e4667" : "black",
haloSize: 1.5,
haloColor: bgColor == "light" ? "white" : "black",
font: {
size: '14px',
}
}
});
layer.labelingInfo = [ labels ];
}
}
}
// ADD LEGEND
var {legend, view} = state;
// if (fieldName) {
// // remove and replace legend entirely rather than updating, to avoid dojo issues
// view.ui.remove(legend);
// legend = await new Legend({
// view,
// })
// legend.layerInfos = [{
// layer,
// }]
// view.ui.add(legend, "bottom-right");
// } else {
// view.ui.remove(legend);
// legend = null;
// }
layer.renderer = renderer; // replace the old renderer
layer.refresh(); // ensure the layer draws
// update state
state = {...state, layer, view, renderer, bgColor, legend}
} // end autoStyle
//
// STYLING UTILITY FUNCTIONS
//
// check for weirdness
function isBadValue(value) {
return (value === null || // null
value === "" || // empty string
(/^\s+$/.test(value))); // all whitespace
}
// copy a symbol and apply colors
function copyAndColor(symbol, strokeColor, fillColor) {
if (symbol.type == 'cim') {
// clone symbol
var newSymbol = symbol.clone();
cimSymbolUtils.applyCIMSymbolColor(newSymbol, fillColor);
newSymbol.data.symbol.symbolLayers[0].markerGraphics[0].symbol.symbolLayers[0].color = strokeColor;
} else {
newSymbol = Object.assign({}, symbol);
newSymbol.color = fillColor;
if (symbol.type !== "simple-line") {
newSymbol.outline.color = strokeColor;
}
}
return newSymbol;
}
// add labels to a layer
function addLabels(fieldName) {
return new LabelClass({
labelExpressionInfo: { expression: "$feature."+fieldName },
symbol: {
type: "text", // autocasts as new TextSymbol()
color: state.bgColor == "light" ? "#1e4667" : "white",
haloSize: 1.5,
haloColor: state.bgColor == "light" ? "white" : "black",
font: {
size: '14px',
}
}
// these ArcGIS label class properties don't exist in the JSAPI ... yet
// removeDuplicates: "all",
// removeDuplicatesDistance: 0,
// repeatLabel: false,
// repeatLabelDistance: 500,
});
}
// get geometrical extent of dataset features
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
};
}
// get a field object from a field name
function getDatasetField (fieldName) {
let lc_fieldName = fieldName.toLowerCase();
const field = state.dataset.attributes.fields.find(f => f.name.toLowerCase() === lc_fieldName);
if (!field) {
throw new Error(`Could not find field "${fieldName}" in dataset.`);
}
const stats = [...Object.entries(state.dataset.attributes.statistics).values()].find(([, fields]) => fields[lc_fieldName]);
// add "simple type" (numeric, date, string) and stats into rest of field definition
return {
...field,
simpleType: stats && stats[0],
statistics: stats && stats[1][lc_fieldName].statistics
}
}
// get the unique values of a field
async function getDatasetFieldUniqueValues (fieldName) {
var {layer} = state;
if (!DATASET_FIELD_UNIQUE_VALUES[fieldName]) {
const field = getDatasetField(fieldName);
let stats;
if (layer) {
const uniqueValueInfos = (await uniqueValues({ layer: state.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
}
}
stats.uniqueCount = stats.values.length;
// 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;
}