-
Notifications
You must be signed in to change notification settings - Fork 20
/
sldreader.js
2940 lines (2638 loc) · 97.1 KB
/
sldreader.js
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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('ol/style'), require('ol/render'), require('ol/geom'), require('ol/extent'), require('ol/has')) :
typeof define === 'function' && define.amd ? define(['exports', 'ol/style', 'ol/render', 'ol/geom', 'ol/extent', 'ol/has'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.SLDReader = {}, global.ol.style, global.ol.render, global.ol.geom, global.ol.extent, global.ol.has));
})(this, (function (exports, style, render, geom, extent, has) { 'use strict';
/**
* Factory methods for filterelements
* @see http://schemas.opengis.net/filter/1.0.0/filter.xsd
*
* @module
*/
var TYPE_COMPARISON = 'comparison';
/**
* @var string[] element names of binary comparison
* @private
*/
var BINARY_COMPARISON_NAMES = [
'PropertyIsEqualTo',
'PropertyIsNotEqualTo',
'PropertyIsLessThan',
'PropertyIsLessThanOrEqualTo',
'PropertyIsGreaterThan',
'PropertyIsGreaterThanOrEqualTo' ];
var COMPARISON_NAMES = BINARY_COMPARISON_NAMES.concat([
'PropertyIsLike',
'PropertyIsNull',
'PropertyIsBetween' ]);
/**
* @private
* @param {string} localName
*
* @return null|string
*/
function getChildTextContent(node, localName) {
var propertyNameElement = node
.getElementsByTagNameNS(node.namespaceURI, localName)
.item(0);
if (!propertyNameElement) {
return null;
}
if (propertyNameElement.parentNode !== node) {
throw new Error('Expected direct descant');
}
return propertyNameElement ? propertyNameElement.textContent.trim() : null;
}
function isComparison(element) {
return COMPARISON_NAMES.includes(element.localName);
}
function isBinary(element) {
return ['or', 'and'].includes(element.localName.toLowerCase());
}
/**
* factory for comparisonOps
* @private
* @param {Element} element
*
* @return {object}
*/
function createComparison(element) {
if (BINARY_COMPARISON_NAMES.includes(element.localName)) {
return createBinaryFilterComparison(element);
}
if (element.localName === 'PropertyIsBetween') {
return createIsBetweenComparison(element);
}
if (element.localName === 'PropertyIsNull') {
return createIsNullComparison(element);
}
if (element.localName === 'PropertyIsLike') {
return createIsLikeComparison(element);
}
throw new Error(("Unknown comparison element " + (element.localName)));
}
/**
* factory for element type BinaryComparisonOpType
* @private
* @param {Element} element
*
* @return {object}
*/
function createBinaryFilterComparison(element) {
var propertyname = getChildTextContent(element, 'PropertyName');
var literal = getChildTextContent(element, 'Literal');
return {
type: TYPE_COMPARISON,
operator: element.localName.toLowerCase(),
propertyname: propertyname,
literal: literal,
// Match case attribute is true by default, so only make it false if the attribute value equals 'false'.
matchcase: element.getAttribute('matchCase') !== 'false',
};
}
/**
* factory for element type PropertyIsLikeType
* @private
* @param {Element} element
*
* @return {object}
*/
function createIsLikeComparison(element) {
var propertyname = getChildTextContent(element, 'PropertyName');
var literal = getChildTextContent(element, 'Literal');
return {
type: TYPE_COMPARISON,
operator: element.localName.toLowerCase(),
propertyname: propertyname,
literal: literal,
wildcard: element.getAttribute('wildCard'),
singlechar: element.getAttribute('singleChar'),
escapechar: element.getAttribute('escapeChar'),
// Match case attribute is true by default, so only make it false if the attribute value equals 'false'.
matchcase: element.getAttribute('matchCase') !== 'false',
};
}
/**
* factory for element type PropertyIsNullType
* @private
* @param {Element} element
*
* @return {object}
*/
function createIsNullComparison(element) {
var propertyname = getChildTextContent(element, 'PropertyName');
return {
type: TYPE_COMPARISON,
operator: element.localName.toLowerCase(),
propertyname: propertyname,
};
}
/**
* factory for element type PropertyIsBetweenType
* @private
* @param {Element} element
*
* @return {object}
*/
function createIsBetweenComparison(element) {
var propertyname = getChildTextContent(element, 'PropertyName');
var lowerboundary = getChildTextContent(element, 'LowerBoundary');
var upperboundary = getChildTextContent(element, 'UpperBoundary');
return {
type: TYPE_COMPARISON,
operator: element.localName.toLowerCase(),
lowerboundary: lowerboundary,
upperboundary: upperboundary,
propertyname: propertyname,
// Match case attribute is true by default, so only make it false if the attribute value equals 'false'.
matchcase: element.getAttribute('matchCase') !== 'false',
};
}
/**
* Factory for and/or filter
* @private
* @param {Element} element
*
* @return {object}
*/
function createBinaryLogic(element) {
var predicates = [];
for (var n = element.firstElementChild; n; n = n.nextElementSibling) {
if (isComparison(n)) {
predicates.push(createComparison(n));
}
}
return {
type: element.localName.toLowerCase(),
predicates: predicates,
};
}
/**
* Factory for not filter
* @private
* @param {Element} element
*
* @return {object}
*/
function createUnaryLogic(element) {
var predicate = null;
var childElement = element.firstElementChild;
if (childElement && isComparison(childElement)) {
predicate = createComparison(childElement);
}
if (childElement && isBinary(childElement)) {
predicate = createBinaryLogic(childElement);
}
return {
type: element.localName.toLowerCase(),
predicate: predicate,
};
}
/**
* Factory root filter element
* @param {Element} element
*
* @return {Filter}
*/
function createFilter(element) {
var filter = {};
for (var n = element.firstElementChild; n; n = n.nextElementSibling) {
if (isComparison(n)) {
filter = createComparison(n);
}
if (isBinary(n)) {
filter = createBinaryLogic(n);
}
if (n.localName.toLowerCase() === 'not') {
filter = createUnaryLogic(n);
}
if (n.localName.toLowerCase() === 'featureid') {
filter.type = 'featureid';
filter.fids = filter.fids || [];
filter.fids.push(n.getAttribute('fid'));
}
}
return filter;
}
/**
* A filter predicate.
* @typedef Filter
* @name Filter
* @description [filter operators](http://schemas.opengis.net/filter/1.1.0/filter.xsd), see also
* [geoserver](http://docs.geoserver.org/stable/en/user/styling/sld/reference/filters.html)
* @property {string} type Can be 'comparison', 'and', 'or', 'not', or 'featureid'.
* @property {Array<string>} [fids] An array of feature id's. Required for type='featureid'.
* @property {string} [operator] Required for type='comparison'. Can be one of
* 'propertyisequalto',
* 'propertyisnotequalto',
* 'propertyislessthan',
* 'propertyislessthanorequalto',
* 'propertyisgreaterthan',
* 'propertyisgreaterthanorequalto',
* 'propertyislike',
* 'propertyisbetween'
* @property {Filter[]} [predicates] Required for type='and' or type='or'.
* An array of filter predicates that must all evaluate to true for 'and', or
* for which at least one must evaluate to true for 'or'.
* @property {Filter} [predicate] Required for type='not'. A single predicate to negate.
* @property {string} [propertyname] Required for type='comparison'.
* @property {string} [literal] A literal value to use in a comparison,
* required for type='comparison'.
* @property {string} [lowerboundary] Lower boundary, required for operator='propertyisbetween'.
* @property {string} [upperboundary] Upper boundary, required for operator='propertyisbetween'.
* @property {string} [wildcard] Required wildcard character for operator='propertyislike'.
* @property {string} [singlechar] Required single char match character,
* required for operator='propertyislike'.
* @property {string} [escapechar] Required escape character for operator='propertyislike'.
*/
/**
* @module
*/
/**
* Generic parser for elements with maxOccurs > 1
* it pushes result of readNode(node) to array on obj[prop]
* @private
* @param {Element} node the xml element to parse
* @param {object} obj the object to modify
* @param {string} prop key on obj to hold array
*/
function addPropArray(node, obj, prop) {
var property = prop.toLowerCase();
obj[property] = obj[property] || [];
var item = {};
readNode(node, item);
obj[property].push(item);
}
/**
* Generic parser for elements that can be arrays
* @private
* @param {Element} node the xml element to parse
* @param {object|Array} obj the object or array to modify
* @param {string} prop key on obj to hold array
*/
function addPropOrArray(node, obj, prop) {
var property = prop.toLowerCase();
var item = {};
readNode(node, item);
if (!(property in obj)) {
obj[property] = item;
} else if (Array.isArray(obj[property])) {
obj[property].push(item);
} else {
obj[property] = [obj[property], item];
}
}
/**
* Generic parser for maxOccurs = 1 (the xsd default)
* it sets result of readNode(node) to array on obj[prop]
* @private
* @param {Element} node the xml element to parse
* @param {object} obj the object to modify
* @param {string} prop key on obj to hold empty object
*/
function addProp(node, obj, prop) {
var property = prop.toLowerCase();
obj[property] = {};
readNode(node, obj[property]);
}
/**
* Assigns textcontent to obj.prop
* @private
* @param {Element} node [description]
* @param {object} obj [description]
* @param {string} prop [description]
* @param {bool} [trimText] Trim whitespace from text content (default false).
*/
function addPropWithTextContent(node, obj, prop, trimText) {
if ( trimText === void 0 ) trimText = false;
var property = prop.toLowerCase();
if (trimText) {
obj[property] = node.textContent.trim();
} else {
obj[property] = node.textContent;
}
}
/**
* Assigns numeric value of text content to obj.prop.
* Assigns NaN if the text value is not a valid text representation of a floating point number.
* @private
* @param {Element} node The XML node element.
* @param {object} obj The object to add the element value to.
* @param {string} prop The property name.
*/
function addNumericProp(node, obj, prop) {
var property = prop.toLowerCase();
var value = parseFloat(node.textContent.trim());
obj[property] = value;
}
/**
* This function parses SLD XML nodes that can contain an SLD filter expression.
* If the SLD node contains only text elements, the result will be concatenated into a string.
* If the SLD node contains one or more non-literal nodes (for now, only PropertyName), the result
* will be an object with type:"expression" and an array of child nodes of which one or more have
* the type "propertyname".
*
* Functions and arithmetic operators (Add,Sub,Mul,Div) are not supported (yet).
* Note: for now, only these contents will be parsed:
* * Plain text nodes.
* * CDATA sections.
* * ogc:PropertyName elements (property name will be parsed as trimmed text).
* * ogc:Literal elements (contents will be parsed as trimmed text).
* See also:
* * http://schemas.opengis.net/filter/1.1.0/expr.xsd
* * https://docs.geoserver.org/stable/en/user/styling/sld/reference/filters.html#sld-filter-expression
* @private
* @param {Element} node XML Node.
* @param {object} obj Object to add XML node contents to.
* @param {string} prop Property name on obj that will hold the parsed node contents.
* @param {bool} [skipEmptyNodes] Default true. If true, emtpy (whitespace-only) text nodes will me omitted in the result.
*/
function addFilterExpressionProp(node, obj, prop, skipEmptyNodes) {
if ( skipEmptyNodes === void 0 ) skipEmptyNodes = true;
var childExpressions = [];
for (var k = 0; k < node.childNodes.length; k += 1) {
var childNode = node.childNodes[k];
var childExpression = {};
if (
childNode.namespaceURI === 'http://www.opengis.net/ogc' &&
childNode.localName === 'PropertyName'
) {
// Add ogc:PropertyName elements as type:propertyname.
childExpression.type = 'propertyname';
childExpression.value = childNode.textContent.trim();
} else if (childNode.nodeName === '#cdata-section') {
// Add CDATA section text content untrimmed.
childExpression.type = 'literal';
childExpression.value = childNode.textContent;
} else {
// Add ogc:Literal elements and plain text nodes as type:literal.
childExpression.type = 'literal';
childExpression.value = childNode.textContent.trim();
}
if (childExpression.type === 'literal' && skipEmptyNodes) {
if (childExpression.value.trim()) {
childExpressions.push(childExpression);
}
} else {
childExpressions.push(childExpression);
}
}
var property = prop.toLowerCase();
// If expression children are all literals, concatenate them into a string.
var allLiteral = childExpressions.every(
function (childExpression) { return childExpression.type === 'literal'; }
);
if (allLiteral) {
obj[property] = childExpressions
.map(function (expression) { return expression.value; })
.join('');
} else {
obj[property] = {
type: 'expression',
children: childExpressions,
};
}
}
/**
* recieves boolean of element with tagName
* @private
* @param {Element} element [description]
* @param {string} tagName [description]
* @return {boolean}
*/
function getBool(element, tagName) {
var collection = element.getElementsByTagNameNS(
'http://www.opengis.net/sld',
tagName
);
if (collection.length) {
return Boolean(collection.item(0).textContent);
}
return false;
}
/**
* css and svg params
* @private
* @param {Element} element
* @param {object} obj
* @param {String} prop
*/
function parameters(element, obj, prop) {
var propnames = {
CssParameter: 'styling',
SvgParameter: 'styling',
VendorOption: 'vendoroption',
};
var propname = propnames[prop] || 'styling';
obj[propname] = obj[propname] || {};
var name = element
.getAttribute('name')
.toLowerCase()
.replace(/-(.)/g, function (match, group1) { return group1.toUpperCase(); });
obj[propname][name] = element.textContent.trim();
}
var FilterParsers = {
Filter: function (element, obj) {
obj.filter = createFilter(element);
},
ElseFilter: function (element, obj) {
obj.elsefilter = true;
},
};
var SymbParsers = {
PolygonSymbolizer: addPropOrArray,
LineSymbolizer: addPropOrArray,
PointSymbolizer: addPropOrArray,
TextSymbolizer: addPropOrArray,
Fill: addProp,
Stroke: addProp,
GraphicStroke: addProp,
GraphicFill: addProp,
Graphic: addProp,
ExternalGraphic: addProp,
Gap: addNumericProp,
InitialGap: addNumericProp,
Mark: addProp,
Label: function (node, obj, prop) { return addFilterExpressionProp(node, obj, prop, false); },
Halo: addProp,
Font: addProp,
Radius: addPropWithTextContent,
LabelPlacement: addProp,
PointPlacement: addProp,
LinePlacement: addProp,
PerpendicularOffset: addPropWithTextContent,
AnchorPoint: addProp,
AnchorPointX: addPropWithTextContent,
AnchorPointY: addPropWithTextContent,
Opacity: addFilterExpressionProp,
Rotation: addFilterExpressionProp,
Displacement: addProp,
DisplacementX: addPropWithTextContent,
DisplacementY: addPropWithTextContent,
Size: addFilterExpressionProp,
WellKnownName: addPropWithTextContent,
VendorOption: parameters,
OnlineResource: function (element, obj) {
obj.onlineresource = element.getAttribute('xlink:href');
},
CssParameter: parameters,
SvgParameter: parameters,
};
/**
* Each propname is a tag in the sld that should be converted to plain object
* @private
* @type {Object}
*/
var parsers = Object.assign({}, {NamedLayer: function (element, obj) {
addPropArray(element, obj, 'layers');
},
UserLayer: function (element, obj) {
addPropArray(element, obj, 'layers');
},
UserStyle: function (element, obj) {
obj.styles = obj.styles || [];
var style = {
default: getBool(element, 'IsDefault'),
featuretypestyles: [],
};
readNode(element, style);
obj.styles.push(style);
},
FeatureTypeStyle: function (element, obj) {
var featuretypestyle = {
rules: [],
};
readNode(element, featuretypestyle);
obj.featuretypestyles.push(featuretypestyle);
},
Rule: function (element, obj) {
var rule = {};
readNode(element, rule);
obj.rules.push(rule);
},
Name: addPropWithTextContent,
MaxScaleDenominator: addPropWithTextContent,
MinScaleDenominator: addPropWithTextContent},
FilterParsers,
SymbParsers);
/**
* walks over xml nodes
* @private
* @param {Element} node derived from xml
* @param {object} obj recieves results
* @return {void}
*/
function readNode(node, obj) {
for (var n = node.firstElementChild; n; n = n.nextElementSibling) {
if (parsers[n.localName]) {
parsers[n.localName](n, obj, n.localName);
}
}
}
/**
* Creates a object from an sld xml string,
* @param {string} sld xml string
* @return {StyledLayerDescriptor} object representing sld style
*/
function Reader(sld) {
var result = {};
var parser = new DOMParser();
var doc = parser.parseFromString(sld, 'application/xml');
for (var n = doc.firstChild; n; n = n.nextSibling) {
result.version = n.getAttribute('version');
readNode(n, result);
}
return result;
}
/**
* @typedef StyledLayerDescriptor
* @name StyledLayerDescriptor
* @description a typedef for StyledLayerDescriptor {@link http://schemas.opengis.net/sld/1.1/StyledLayerDescriptor.xsd xsd}
* @property {string} version sld version
* @property {Layer[]} layers info extracted from NamedLayer element
*/
/**
* @typedef Layer
* @name Layer
* @description a typedef for Layer, the actual style object for a single layer
* @property {string} name layer name
* @property {Object[]} styles See explanation at [Geoserver docs](http://docs.geoserver.org/stable/en/user/styling/sld/reference/styles.html)
* @property {Boolean} styles[].default
* @property {String} [styles[].name]
* @property {FeatureTypeStyle[]} styles[].featuretypestyles Geoserver will draw multiple,
* libraries as openlayers can only use one definition!
*/
/**
* @typedef FeatureTypeStyle
* @name FeatureTypeStyle
* @description a typedef for FeatureTypeStyle: {@link http://schemas.opengis.net/se/1.1.0/FeatureStyle.xsd xsd}
* @property {Rule[]} rules
*/
/**
* @typedef Rule
* @name Rule
* @description a typedef for Rule to match a feature: {@link http://schemas.opengis.net/se/1.1.0/FeatureStyle.xsd xsd}
* @property {string} name rule name
* @property {Filter[]} [filter]
* @property {boolean} [elsefilter]
* @property {integer} [minscaledenominator]
* @property {integer} [maxscaledenominator]
* @property {PolygonSymbolizer} [polygonsymbolizer]
* @property {LineSymbolizer} [linesymbolizer]
* @property {PointSymbolizer} [pointsymbolizer]
* */
/**
* @typedef PolygonSymbolizer
* @name PolygonSymbolizer
* @description a typedef for [PolygonSymbolizer](http://schemas.opengis.net/se/1.1.0/Symbolizer.xsd), see also
* [geoserver docs](http://docs.geoserver.org/stable/en/user/styling/sld/reference/polygonsymbolizer.html)
* @property {Object} fill
* @property {array} fill.css one object per CssParameter with props name (camelcased) & value
* @property {Object} stroke
* @property {Object[]} stroke.css with camelcased name & value
* */
/**
* @typedef LineSymbolizer
* @name LineSymbolizer
* @description a typedef for [LineSymbolizer](http://schemas.opengis.net/se/1.1.0/Symbolizer.xsd), see also
* [geoserver docs](http://docs.geoserver.org/stable/en/user/styling/sld/reference/linesymbolizer.html#sld-reference-linesymbolizer)
* @property {Object} stroke
* @property {Object[]} stroke.css one object per CssParameter with props name (camelcased) & value
* @property {Object} graphicstroke
* @property {Object} graphicstroke.graphic
* @property {Object} graphicstroke.graphic.mark
* @property {string} graphicstroke.graphic.mark.wellknownname
* @property {Object} graphicstroke.graphic.mark.fill
* @property {Object} graphicstroke.graphic.mark.stroke
* @property {Number} graphicstroke.graphic.opacity
* @property {Number} graphicstroke.graphic.size
* @property {Number} graphicstroke.graphic.rotation
* */
/**
* @typedef PointSymbolizer
* @name PointSymbolizer
* @description a typedef for PointSymbolizer [xsd](http://schemas.opengis.net/se/1.1.0/Symbolizer.xsd)
* & [geoserver docs](http://docs.geoserver.org/latest/en/user/styling/sld/reference/pointsymbolizer.html)
* @property {Object} graphic
* @property {Object} graphic.externalgraphic
* @property {string} graphic.externalgraphic.onlineresource
* @property {Object} graphic.mark
* @property {string} graphic.mark.wellknownname
* @property {Object} graphic.mark.fill
* @property {Object} graphic.mark.stroke
* @property {Number} graphic.opacity
* @property {Number} graphic.size
* @property {Number} graphic.rotation
* */
function isNullOrUndefined(value) {
/* eslint-disable-next-line eqeqeq */
return value == null;
}
function compareNumbers(a, b) {
if (a < b) {
return -1;
}
if (a === b) {
return 0;
}
return 1;
}
function toNumber(text) {
if (text === '') {
return NaN;
}
return Number(text);
}
function compare(a, b, matchcase) {
var aNumber = toNumber(a);
var bNumber = toNumber(b);
if (!(Number.isNaN(aNumber) || Number.isNaN(bNumber))) {
return compareNumbers(aNumber, bNumber);
}
// If a and/or b is non-numeric, compare both values as strings.
var aString = a.toString();
var bString = b.toString();
// Note: using locale compare with sensitivity option fails the CI test, while it works on my PC.
// So, case insensitive comparison is done in a more brute-force way by using lower case comparison.
// Original method:
// const caseSensitiveCollator = new Intl.Collator(undefined, { sensitivity: 'case' });
// caseSensitiveCollator.compare(string1, string2);
if (matchcase) {
return aString.localeCompare(bString);
}
return aString.toLowerCase().localeCompare(bString.toLowerCase());
}
function propertyIsLessThan(comparison, value) {
if (isNullOrUndefined(value)) {
return false;
}
if (isNullOrUndefined(comparison.literal)) {
return false;
}
return compare(value, comparison.literal) < 0;
}
function propertyIsGreaterThan(comparison, value) {
if (isNullOrUndefined(value)) {
return false;
}
if (isNullOrUndefined(comparison.literal)) {
return false;
}
return compare(value, comparison.literal) > 0;
}
function propertyIsBetween(comparison, value) {
if (isNullOrUndefined(value)) {
return false;
}
var lowerBoundary = comparison.lowerboundary;
if (isNullOrUndefined(lowerBoundary)) {
return false;
}
var upperBoundary = comparison.upperboundary;
if (isNullOrUndefined(upperBoundary)) {
return false;
}
return (
compare(lowerBoundary, value) <= 0 && compare(upperBoundary, value) >= 0
);
}
function propertyIsEqualTo(comparison, value) {
if (isNullOrUndefined(value)) {
return false;
}
if (isNullOrUndefined(comparison.literal)) {
return false;
}
if (!comparison.matchcase) {
return compare(comparison.literal, value, false) === 0;
}
/* eslint-disable-next-line eqeqeq */
return value == comparison.literal;
}
// Watch out! Null-ish values should not pass propertyIsNotEqualTo,
// just like in databases.
// This means that PropertyIsNotEqualTo is not the same as NOT(PropertyIsEqualTo).
function propertyIsNotEqualTo(comparison, value) {
if (isNullOrUndefined(value)) {
return false;
}
return !propertyIsEqualTo(comparison, value);
}
/**
* A very basic implementation of a PropertyIsLike by converting match pattern to a regex.
* @private
* @param {object} comparison filter object for operator 'propertyislike'
* @param {string|number} value Feature property value.
* @param {object} getProperty A function with parameters (feature, propertyName) to extract
* the value of a property from a feature.
*/
function propertyIsLike(comparison, value) {
var pattern = comparison.literal;
if (isNullOrUndefined(value)) {
return false;
}
// Create regex string from match pattern.
var wildcard = comparison.wildcard;
var singlechar = comparison.singlechar;
var escapechar = comparison.escapechar;
var matchcase = comparison.matchcase;
// Replace wildcard by '.*'
var patternAsRegex = pattern.replace(new RegExp(("[" + wildcard + "]"), 'g'), '.*');
// Replace single char match by '.'
patternAsRegex = patternAsRegex.replace(
new RegExp(("[" + singlechar + "]"), 'g'),
'.'
);
// Replace escape char by '\' if escape char is not already '\'.
if (escapechar !== '\\') {
patternAsRegex = patternAsRegex.replace(
new RegExp(("[" + escapechar + "]"), 'g'),
'\\'
);
}
// Bookend the regular expression.
patternAsRegex = "^" + patternAsRegex + "$";
var rex =
matchcase === false
? new RegExp(patternAsRegex, 'i')
: new RegExp(patternAsRegex);
return rex.test(value);
}
/**
* Test feature properties against a comparison filter.
* @private
* @param {Filter} comparison A comparison filter object.
* @param {object} feature A feature object.
* @param {Function} getProperty A function with parameters (feature, propertyName)
* to extract a single property value from a feature.
* @return {bool} does feature fullfill comparison
*/
function doComparison(comparison, feature, getProperty) {
var value = getProperty(feature, comparison.propertyname);
switch (comparison.operator) {
case 'propertyislessthan':
return propertyIsLessThan(comparison, value);
case 'propertyisequalto':
return propertyIsEqualTo(comparison, value);
case 'propertyislessthanorequalto':
return (
propertyIsEqualTo(comparison, value) ||
propertyIsLessThan(comparison, value)
);
case 'propertyisnotequalto':
return propertyIsNotEqualTo(comparison, value);
case 'propertyisgreaterthan':
return propertyIsGreaterThan(comparison, value);
case 'propertyisgreaterthanorequalto':
return (
propertyIsEqualTo(comparison, value) ||
propertyIsGreaterThan(comparison, value)
);
case 'propertyisbetween':
return propertyIsBetween(comparison, value);
case 'propertyisnull':
return isNullOrUndefined(value);
case 'propertyislike':
return propertyIsLike(comparison, value);
default:
throw new Error(("Unkown comparison operator " + (comparison.operator)));
}
}
function doFIDFilter(fids, featureId) {
for (var i = 0; i < fids.length; i += 1) {
if (fids[i] === featureId) {
return true;
}
}
return false;
}
/**
* @private
* Get feature properties from a GeoJSON feature.
* @param {object} feature GeoJSON feature.
* @returns {object} Feature properties.
*
*/
function getGeoJSONProperty(feature, propertyName) {
return feature.properties[propertyName];
}
/**
* @private
* Gets feature id from a GeoJSON feature.
* @param {object} feature GeoJSON feature.
* @returns {number|string} Feature ID.
*/
function getGeoJSONFeatureId(feature) {
return feature.id;
}
/**
* Calls functions from Filter object to test if feature passes filter.
* Functions are called with filter part they match and feature.
* @private
* @param {Filter} filter
* @param {object} feature feature
* @param {object} options Custom filter options.
* @param {Function} options.getProperty An optional function with parameters (feature, propertyName)
* that can be used to extract properties from a feature.
* When not given, properties are read from feature.properties directly.
* @param {Function} options.getFeatureId An optional function to extract the feature id from a feature.
* When not given, feature id is read from feature.id.
* @return {boolean} True if the feature passes the conditions described by the filter object.
*/
function filterSelector(filter, feature, options) {
if ( options === void 0 ) options = {};
var getProperty =
typeof options.getProperty === 'function'
? options.getProperty
: getGeoJSONProperty;
var getFeatureId =
typeof options.getFeatureId === 'function'
? options.getFeatureId
: getGeoJSONFeatureId;
var type = filter.type;
switch (type) {
case 'featureid':
return doFIDFilter(filter.fids, getFeatureId(feature));
case 'comparison':
return doComparison(filter, feature, getProperty);
case 'and': {
if (!filter.predicates) {
throw new Error('And filter must have predicates array.');
}
// And without predicates should return false.
if (filter.predicates.length === 0) {
return false;
}
return filter.predicates.every(function (predicate) { return filterSelector(predicate, feature, options); }
);
}
case 'or': {
if (!filter.predicates) {
throw new Error('Or filter must have predicates array.');
}
return filter.predicates.some(function (predicate) { return filterSelector(predicate, feature, options); }
);
}
case 'not': {
if (!filter.predicate) {
throw new Error('Not filter must have predicate.');
}
return !filterSelector(filter.predicate, feature, options);
}
default:
throw new Error(("Unknown filter type: " + type));
}
}
/**
* [scaleSelector description]
* The "standardized rendering pixel size" is defined to be 0.28mm × 0.28mm
* @private
* @param {Rule} rule
* @param {number} resolution m/px
* @return {boolean}
*/
function scaleSelector(rule, resolution) {
if (
rule.maxscaledenominator !== undefined &&
rule.minscaledenominator !== undefined
) {
if (
resolution / 0.00028 < rule.maxscaledenominator &&
resolution / 0.00028 > rule.minscaledenominator
) {
return true;