@evergis/common 1.0.0 → 1.0.2-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,11 +1,13 @@
1
1
  import { expression } from '@mapbox/mapbox-gl-style-spec';
2
- import { isNil, isEmpty, isEqual, isObject as isObject$1 } from 'lodash';
3
- import { v4 } from 'uuid';
4
- import { toMercator, bboxPolygon } from '@turf/turf';
2
+ import isEmpty from 'lodash.isempty';
3
+ import isEqual from 'lodash.isequal';
4
+ import isNil from 'lodash.isnil';
5
5
  import { parseJSON, parseISO, isValid, toDate, format } from 'date-fns';
6
6
  import { ru, enUS } from 'date-fns/locale';
7
7
  import { AttributeType } from '@evergis/api';
8
8
  import { stringify } from 'wkt';
9
+ import { toMercator, bboxPolygon } from '@turf/turf';
10
+ import { v4 } from 'uuid';
9
11
 
10
12
  /* ---------------------------------------------------------------------------------------------------------------- *
11
13
  * Data-driven style information provided according to https://docs.mapbox.com/style-spec/reference/layers/ *
@@ -347,1793 +349,1793 @@ const SPEC_PROP_VALUE_OPTIONS = {
347
349
  },
348
350
  };
349
351
 
350
- /* eslint-disable max-lines, no-console, class-methods-use-this, @typescript-eslint/no-magic-numbers */
351
- class ClientStyleValidator {
352
- options;
353
- constructor(options) {
354
- this.options = options || {};
352
+ /**
353
+ * Returns true if n is a finite number, otherwise false
354
+ * @param n
355
+ */
356
+ const isNumber = function (n) {
357
+ return typeof n === 'number' && isFinite(n);
358
+ };
359
+ /**
360
+ * Returns true if s is a string, otherwise false
361
+ * @param s
362
+ */
363
+ const isString = function (s) {
364
+ return typeof s === 'string';
365
+ };
366
+
367
+ /**
368
+ * Utility class for working with different representations of colors in browsers
369
+ * @alias sGis.utils.Color
370
+ */
371
+ class Color {
372
+ /**
373
+ * @param string - any valid css color string
374
+ */
375
+ constructor(string) {
376
+ this._original = string;
377
+ if (!isString(string))
378
+ string = string.toString();
379
+ this._color = string && string.trim() || 'transparent';
380
+ this._setChannels();
355
381
  }
356
- validate(clientStyle) {
357
- if (isNil(clientStyle) || isEmpty(clientStyle) || isNil(clientStyle?.items) || isEmpty(clientStyle?.items)) {
358
- return true;
382
+ _setChannels() {
383
+ let format = this.format;
384
+ if (format && formats[format]) {
385
+ this._channels = formats[format](this._color);
359
386
  }
360
- if (clientStyle.items.some(item => isNil(item.paint))) {
361
- if (this.options.verbose) {
362
- console.error("Validate client style:", "`paint` prop is mandatory", "\n");
363
- }
364
- return false;
387
+ else {
388
+ this._channels = { r: NaN, g: NaN, b: NaN, a: NaN };
365
389
  }
366
- return clientStyle.items.every(item => Object.entries({ ...item.layout, ...item.paint }).every(([key, value]) => this.validateSpecPropValue(key, value)));
367
- }
368
- getSpecPropValueOptions(key) {
369
- return SPEC_PROP_VALUE_OPTIONS[key];
370
- }
371
- isHeatmapColorValid(value) {
372
- return (expression.isExpression(value) &&
373
- isEqual(value[0], "interpolate") &&
374
- isEqual(value[1], ["linear"]) &&
375
- isEqual(value[2], ["heatmap-density"]) &&
376
- value.length % 2 !== 0 &&
377
- value.length > 3 &&
378
- value
379
- .slice(3)
380
- .filter((_, i) => i % 2 === 0)
381
- .every(e => typeof e === "number") &&
382
- value
383
- .slice(3)
384
- .filter((_, i) => i % 2 !== 0)
385
- .every(e => typeof e === "string"));
386
390
  }
387
- isZoomInterpolate(value) {
388
- return Array.isArray(value) && value[0] === "interpolate" && Array.isArray(value[2]) && value[2][0] === "zoom";
389
- }
390
- validateSupportedConcatExpression(key, value) {
391
- if (key !== "text-field") {
392
- if (this.options.verbose) {
393
- console.error("Validate supported concat expression:", "supported only for `text-field`", key, value, "\n");
394
- }
395
- return false;
391
+ get _min() { return Math.min(this._channels.r, this._channels.g, this._channels.b); }
392
+ get _max() { return Math.max(this._channels.r, this._channels.g, this._channels.b); }
393
+ get _delta() { return this._max - this._min; }
394
+ /**
395
+ * Returns the color as a string in the requested format
396
+ * @param format - target format. Available values: "hex" - #AARRGGBB, "rgb" - "rgb(r, g, b)", "rgba" - "rgba(r, g, b, a)"
397
+ */
398
+ toString(format) {
399
+ if (format === 'hex') {
400
+ return '#' + decToHex(this.r) + decToHex(this.g) + decToHex(this.b) + decToHex(this.a);
396
401
  }
397
- if (!expression.isExpression(value)) {
398
- if (this.options.verbose) {
399
- console.error("Validate supported concat expression:", "not an expression", key, value, "\n");
400
- }
401
- return false;
402
+ else if (format === 'rgb') {
403
+ return 'rgb(' + this.r + ',' + this.g + ',' + this.b + ')';
402
404
  }
403
- const result = value[0] === "concat" &&
404
- value.length > 2 &&
405
- value
406
- .slice(1)
407
- .every(i => typeof i === "string" || (Array.isArray(i) && i[0] === "get" && typeof i[1] === "string"));
408
- if (!result) {
409
- if (this.options.verbose) {
410
- console.error("Validate supported concat expression:", "invalid expression", key, value, "\n");
411
- }
405
+ else {
406
+ return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + (this.a / 255).toFixed(2).replace(/\.*0+$/, '') + ')';
412
407
  }
413
- return result;
414
408
  }
415
- validateSupportedMatchExpression(key, value) {
416
- if (!this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
417
- if (this.options.verbose) {
418
- console.error("Validate supported match expression:", "expression not supported", key, value, "\n");
419
- }
420
- return false;
421
- }
422
- if (!expression.isExpression(value)) {
423
- if (this.options.verbose) {
424
- console.error("Validate supported match expression:", "not an expression", key, value, "\n");
425
- }
426
- return false;
427
- }
428
- const result = value[0] === "match" &&
429
- Array.isArray(value[1]) &&
430
- value[1].length === 2 &&
431
- value[1][0] === "get" &&
432
- typeof value[1][1] === "string" &&
433
- value.length > 3 &&
434
- value.length % 2 !== 0 &&
435
- value
436
- .slice(2)
437
- .every(e => typeof e === "number" ||
438
- typeof e === "string" ||
439
- (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
440
- if (!result) {
441
- if (this.options.verbose) {
442
- console.error("Validate supported match expression:", "invalid expression", key, value, "\n");
443
- }
409
+ /**
410
+ * Returns the string given to the constructor of the instance
411
+ * @type {String}
412
+ */
413
+ get original() { return this._original; }
414
+ /**
415
+ * Returns true if the instance represents a valid color, i.e. that after parsing of the string given to the constructor,
416
+ * the format is recognized and values of all channels are resolved to valid numbers.
417
+ * @returns {Boolean}
418
+ */
419
+ get isValid() { return isNumber(this._channels.a) && isNumber(this._channels.r) && isNumber(this._channels.g) && isNumber(this._channels.b); }
420
+ /**
421
+ * Converts HSV color value into RGB
422
+ * @param h - hue value
423
+ * @param s - saturation value
424
+ * @param v - 'value' value
425
+ */
426
+ setHsv(h, s, v) {
427
+ let rgbColors = [];
428
+ h /= 60;
429
+ s /= 100;
430
+ v /= 100;
431
+ let floor = Math.floor(h);
432
+ let mod = floor % 6;
433
+ let f = h - floor;
434
+ let p = Math.round(255 * v * (1 - s));
435
+ let q = Math.round(255 * v * (1 - s * f));
436
+ let t = Math.round(255 * v * (1 - s * (1 - f)));
437
+ v = Math.round(255 * v);
438
+ switch (mod) {
439
+ case 0:
440
+ rgbColors = [v, t, p];
441
+ break;
442
+ case 1:
443
+ rgbColors = [q, v, p];
444
+ break;
445
+ case 2:
446
+ rgbColors = [p, v, t];
447
+ break;
448
+ case 3:
449
+ rgbColors = [p, q, v];
450
+ break;
451
+ case 4:
452
+ rgbColors = [t, p, v];
453
+ break;
454
+ case 5:
455
+ rgbColors = [v, p, q];
456
+ break;
444
457
  }
445
- return result;
458
+ this._channels.r = rgbColors[0];
459
+ this._channels.g = rgbColors[1];
460
+ this._channels.b = rgbColors[2];
461
+ return this;
446
462
  }
447
- validateSupportedCaseExpression(key, value) {
448
- if (!this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
449
- if (this.options.verbose) {
450
- console.error("Validate supported case expression:", "expression not supported", key, value, "\n");
463
+ /**
464
+ * Returns the format of the input color sting. Possible values: hex3, hex6, hex4, hex8, rgb, rgba, name.
465
+ * (name is the named css color values like "white")
466
+ */
467
+ get format() {
468
+ if (this._color.substr(0, 1) === '#' && this._color.search(/[^#0-9a-fA-F]/) === -1) {
469
+ if (this._color.length === 4) {
470
+ return 'hex3';
451
471
  }
452
- return false;
453
- }
454
- if (!expression.isExpression(value)) {
455
- if (this.options.verbose) {
456
- console.error("Validate supported case expression:", "not an expression", key, value, "\n");
472
+ else if (this._color.length === 7) {
473
+ return 'hex6';
457
474
  }
458
- return false;
459
- }
460
- const result = value[0] === "case" &&
461
- value.length > 3 &&
462
- value.length % 2 === 0 &&
463
- value
464
- .slice(1)
465
- .filter((_, i) => i % 2 === 0 && i < value.slice(1).length - 1)
466
- .every(e => Array.isArray(e) &&
467
- e[0] === "all" &&
468
- e.length > 1 &&
469
- e
470
- .slice(1)
471
- .every(ce => Array.isArray(ce) &&
472
- ce.length === 3 &&
473
- [">=", ">", "<", "<="].includes(ce[0]) &&
474
- ce[1][0] === "get" &&
475
- typeof ce[1][1] === "string" &&
476
- typeof ce[2] === "number")) &&
477
- value
478
- .slice(1)
479
- .filter((_, i) => i % 2 !== 0)
480
- .every(e => typeof e === "number" ||
481
- typeof e === "string" ||
482
- (key === "text-field" && this.validateSupportedConcatExpression(key, e))) &&
483
- (typeof value[value.slice(1).length - 1] === "number" ||
484
- typeof value[value.slice(1).length - 1] === "string" ||
485
- (key === "text-field" && this.validateSupportedConcatExpression(key, value)));
486
- if (!result) {
487
- if (this.options.verbose) {
488
- console.error("Validate supported case expression:", "invalid expression", key, value, "\n");
475
+ else if (this._color.length === 5) {
476
+ return 'hex4';
489
477
  }
490
- }
491
- return result;
492
- }
493
- validateSupportedStepExpression(key, value) {
494
- if (!this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
495
- if (this.options.verbose) {
496
- console.error("Validate supported step expression:", "expression not supported", key, value, "\n");
478
+ else if (this._color.length === 9) {
479
+ return 'hex8';
497
480
  }
498
- return false;
499
481
  }
500
- if (!expression.isExpression(value)) {
501
- if (this.options.verbose) {
502
- console.error("Validate supported step expression:", "not an expression", key, value, "\n");
503
- }
504
- return false;
505
- }
506
- const result = value[0] === "step" &&
507
- Array.isArray(value[1]) &&
508
- value[1].length === 2 &&
509
- value[1][0] === "get" &&
510
- typeof value[1][1] === "string" &&
511
- value.length > 3 &&
512
- value.length % 2 !== 0 &&
513
- value
514
- .slice(2)
515
- .filter((_, i) => i % 2 === 0)
516
- .every(e => typeof e === "number" ||
517
- typeof e === "string" ||
518
- (key === "text-field" && this.validateSupportedConcatExpression(key, e))) &&
519
- value
520
- .slice(2)
521
- .filter((_, i) => i % 2 !== 0)
522
- .every(e => typeof e === "number");
523
- if (!result) {
524
- if (this.options.verbose) {
525
- console.error("Validate supported step expression:", "invalid expression", key, value, "\n");
526
- }
527
- }
528
- return result;
529
- }
530
- validateLinearZoomInterpolate(key, value) {
531
- return (this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
532
- isEqual(value[0], "interpolate") &&
533
- isEqual(value[1], ["linear"]) &&
534
- isEqual(value[2], ["zoom"]) &&
535
- value.length % 2 !== 0 &&
536
- value.length > 4 &&
537
- value
538
- .slice(3)
539
- .filter((_, i) => i % 2 === 0)
540
- .every(e => typeof e === "number") &&
541
- value
542
- .slice(3)
543
- .filter((_, i) => i % 2 !== 0)
544
- .every(e => {
545
- return (typeof e === "number" ||
546
- typeof e === "string" ||
547
- this.validateSupportedExpression(key, e, true) ||
548
- (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
549
- }));
550
- }
551
- validateExponentialZoomInterpolate(key, value) {
552
- return (this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
553
- isEqual(value[0], "interpolate") &&
554
- Array.isArray(value[1]) &&
555
- value[1].length === 2 &&
556
- value[1][0] === "exponential" &&
557
- typeof value[1][1] === "number" &&
558
- isEqual(value[2], ["zoom"]) &&
559
- value.length % 2 !== 0 &&
560
- value.length > 4 &&
561
- value
562
- .slice(3)
563
- .filter((_, i) => i % 2 === 0)
564
- .every(e => typeof e === "number") &&
565
- value
566
- .slice(3)
567
- .filter((_, i) => i % 2 !== 0)
568
- .every(e => {
569
- return (typeof e === "number" ||
570
- typeof e === "string" ||
571
- this.validateSupportedExpression(key, e, true) ||
572
- (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
573
- }));
574
- }
575
- validateCubicBezierZoomInterpolate(key, value) {
576
- return (this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
577
- isEqual(value[0], "interpolate") &&
578
- Array.isArray(value[1]) &&
579
- value[1].length === 5 &&
580
- value[1][0] === "cubic-bezier" &&
581
- value[1].slice(1).every(e => typeof e === "number") &&
582
- isEqual(value[2], ["zoom"]) &&
583
- value.length % 2 !== 0 &&
584
- value.length > 4 &&
585
- value
586
- .slice(3)
587
- .filter((_, i) => i % 2 === 0)
588
- .every(e => typeof e === "number") &&
589
- value
590
- .slice(3)
591
- .filter((_, i) => i % 2 !== 0)
592
- .every(e => {
593
- return (typeof e === "number" ||
594
- typeof e === "string" ||
595
- this.validateSupportedExpression(key, e, true) ||
596
- (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
597
- }));
598
- }
599
- validateLinearDataInterpolate(key, value) {
600
- return (this.getSpecPropValueOptions(key)?.dataExpressionSupport &&
601
- isEqual(value[0], "interpolate") &&
602
- isEqual(value[1], ["linear"]) &&
603
- Array.isArray(value[2]) &&
604
- value[2].length === 2 &&
605
- value[2][0] === "get" &&
606
- typeof value[2][1] === "string" &&
607
- value.length % 2 !== 0 &&
608
- value.length > 4 &&
609
- value
610
- .slice(3)
611
- .filter((_, i) => i % 2 === 0)
612
- .every(e => typeof e === "number") &&
613
- value
614
- .slice(3)
615
- .filter((_, i) => i % 2 !== 0)
616
- .every(e => typeof e === "number" ||
617
- typeof e === "string" ||
618
- (key === "text-field" && this.validateSupportedConcatExpression(key, e))));
619
- }
620
- validateExponentialDataInterpolate(key, value) {
621
- return (this.getSpecPropValueOptions(key)?.dataExpressionSupport &&
622
- isEqual(value[0], "interpolate") &&
623
- Array.isArray(value[1]) &&
624
- value[1].length === 2 &&
625
- value[1][0] === "exponential" &&
626
- typeof value[1][1] === "number" &&
627
- Array.isArray(value[2]) &&
628
- value[2].length === 2 &&
629
- value[2][0] === "get" &&
630
- typeof value[2][1] === "string" &&
631
- value.length % 2 !== 0 &&
632
- value.length > 4 &&
633
- value
634
- .slice(3)
635
- .filter((_, i) => i % 2 === 0)
636
- .every(e => typeof e === "number") &&
637
- value
638
- .slice(3)
639
- .filter((_, i) => i % 2 !== 0)
640
- .every(e => typeof e === "number" ||
641
- typeof e === "string" ||
642
- (key === "text-field" && this.validateSupportedConcatExpression(key, e))));
643
- }
644
- validateCubicBezierDataInterpolate(key, value) {
645
- return (this.getSpecPropValueOptions(key)?.dataExpressionSupport &&
646
- isEqual(value[0], "interpolate") &&
647
- Array.isArray(value[1]) &&
648
- value[1].length === 5 &&
649
- value[1][0] === "cubic-bezier" &&
650
- value[1].slice(1).every(e => typeof e === "number") &&
651
- Array.isArray(value[2]) &&
652
- value[2].length === 2 &&
653
- value[2][0] === "get" &&
654
- typeof value[2][1] === "string" &&
655
- value.length % 2 !== 0 &&
656
- value.length > 4 &&
657
- value
658
- .slice(3)
659
- .filter((_, i) => i % 2 === 0)
660
- .every(e => typeof e === "number") &&
661
- value
662
- .slice(3)
663
- .filter((_, i) => i % 2 !== 0)
664
- .every(e => typeof e === "number" ||
665
- typeof e === "string" ||
666
- (key === "text-field" && this.validateSupportedConcatExpression(key, e))));
667
- }
668
- validateZoomInterpolate(key, value) {
669
- return (this.validateLinearZoomInterpolate(key, value) ||
670
- this.validateExponentialZoomInterpolate(key, value) ||
671
- this.validateCubicBezierZoomInterpolate(key, value));
672
- }
673
- validateDataInterpolate(key, value) {
674
- return (this.validateLinearDataInterpolate(key, value) ||
675
- this.validateExponentialDataInterpolate(key, value) ||
676
- this.validateCubicBezierDataInterpolate(key, value));
677
- }
678
- validateSupportedInterpolateExpression(key, value, excludeZoomInterpolate) {
679
- if (!expression.isExpression(value)) {
680
- if (this.options.verbose) {
681
- console.error("Validate supported interpolate expression:", "not an expression", key, value, "\n");
682
- }
683
- return false;
684
- }
685
- if (key === "heatmap-color") {
686
- const isColorValid = this.isHeatmapColorValid(value);
687
- if (!isColorValid) {
688
- if (this.options.verbose) {
689
- console.error("Validate supported interpolate expression:", "invalid color value", key, value, "\n");
690
- }
691
- }
692
- return this.isHeatmapColorValid(value);
693
- }
694
- if (!this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
695
- !this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
696
- if (this.options.verbose) {
697
- console.error("Validate supported interpolate expression:", "interpolate not supported", key, value, "\n");
698
- }
699
- }
700
- const result = (!excludeZoomInterpolate && this.validateZoomInterpolate(key, value)) || this.validateDataInterpolate(key, value);
701
- if (!result) {
702
- if (this.options.verbose) {
703
- console.error("Validate supported interpolate expression:", "invalid expression", key, value, "\n");
704
- }
705
- }
706
- return result;
707
- }
708
- validateSupportedExpression(key, value, excludeZoomInterpolate) {
709
- if (!expression.isExpression(value)) {
710
- if (this.options.verbose) {
711
- console.error("Validate supported expression:", "not an expression", key, value, "\n");
712
- }
713
- return false;
714
- }
715
- const expressionType = value[0];
716
- if (typeof expressionType !== "string" ||
717
- !["match", "case", "step", "interpolate", "concat"].includes(expressionType)) {
718
- if (this.options.verbose) {
719
- console.error("Validate supported expression:", "expression type not supported", key, value, "\n");
720
- }
721
- return false;
482
+ else if (this._color.substr(0, 4) === 'rgb(') {
483
+ return 'rgb';
722
484
  }
723
- switch (expressionType) {
724
- case "match":
725
- return this.validateSupportedMatchExpression(key, value);
726
- case "case":
727
- return this.validateSupportedCaseExpression(key, value);
728
- case "step":
729
- return this.validateSupportedStepExpression(key, value);
730
- case "concat":
731
- return this.validateSupportedConcatExpression(key, value);
732
- case "interpolate":
733
- return this.validateSupportedInterpolateExpression(key, value, excludeZoomInterpolate);
734
- default:
735
- return false;
485
+ else if (this._color.substr(0, 5) === 'rgba(') {
486
+ return 'rgba';
736
487
  }
737
- }
738
- validateTransitionValue(key, value) {
739
- const propValueOptions = this.getSpecPropValueOptions(key.replace(/-transition$/, ""));
740
- if (propValueOptions && propValueOptions.transitionable === false) {
741
- if (this.options.verbose) {
742
- console.error("Validate transition value:", "transition not supported", key, value, "\n");
743
- }
744
- return false;
488
+ else if (this._color.substr(0, 4) === 'hsv(') {
489
+ return 'hsv';
745
490
  }
746
- const result = isObject$1(value) &&
747
- (("delay" in value && typeof value.delay === "number") ||
748
- ("duration" in value && typeof value.duration === "number"));
749
- if (!result) {
750
- if (this.options.verbose) {
751
- console.error("Validate transition value:", "invalid transition value", key, value, "\n");
752
- }
491
+ else if (this._color in Color.names) {
492
+ return 'name';
753
493
  }
754
- return result;
755
494
  }
756
- validateSpecPropValue(key, value) {
757
- if (key.endsWith("-transition")) {
758
- return this.validateTransitionValue(key, value);
759
- }
760
- const propValueOptions = this.getSpecPropValueOptions(key);
761
- if (!propValueOptions) {
762
- return (typeof value === "string" ||
763
- typeof value === "number" ||
764
- typeof value === "boolean" ||
765
- (Array.isArray(value) && value.every(item => typeof item === "number")) ||
766
- (Array.isArray(value) && value.every(item => typeof item === "string")) ||
767
- expression.isExpression(value));
768
- }
769
- if (propValueOptions.arrayValue) {
770
- return (typeof value === propValueOptions.valueTypeAllowed ||
771
- (Array.isArray(value) && value.every(item => typeof item === propValueOptions.valueTypeAllowed)) ||
772
- this.validateSupportedExpression(key, value));
773
- }
774
- return typeof value === propValueOptions.valueTypeAllowed || this.validateSupportedExpression(key, value);
495
+ /**
496
+ * Returns red channel value as integer from 0 to 255.
497
+ */
498
+ get r() { return this._channels.r; }
499
+ set r(v) { this._channels.r = v; }
500
+ /**
501
+ * Returns green channel value as integer from 0 to 255.
502
+ */
503
+ get g() { return this._channels.g; }
504
+ set g(v) { this._channels.g = v; }
505
+ /**
506
+ * Returns blue channel value as integer from 0 to 255.
507
+ */
508
+ get b() { return this._channels.b; }
509
+ set b(v) { this._channels.b = v; }
510
+ /**
511
+ * Returns opacity channel value as integer from 0 to 255.
512
+ */
513
+ get a() { return this._channels.a; }
514
+ set a(v) { this._channels.a = v; }
515
+ /**
516
+ * Returns hue channel value as integer from 0 to 360.
517
+ */
518
+ get h() {
519
+ let max = this._max;
520
+ let min = this._min;
521
+ let delta = this._delta;
522
+ let h;
523
+ let { r, g, b } = this._channels;
524
+ if (max === min)
525
+ h = 0;
526
+ else if (r === max)
527
+ h = (g - b) / delta;
528
+ else if (g === max)
529
+ h = 2 + (b - r) / delta;
530
+ else if (b === max)
531
+ h = 4 + (r - g) / delta;
532
+ h = Math.min(h * 60, 360);
533
+ if (h < 0)
534
+ h += 360;
535
+ h = Math.round(h);
536
+ return h;
537
+ }
538
+ /**
539
+ * Returns saturation channel value as integer from 0 to 100.
540
+ */
541
+ get s() {
542
+ let s;
543
+ let max = this._max;
544
+ if (max === 0)
545
+ s = 0;
546
+ else
547
+ s = this._delta / max * 1000 / 10;
548
+ s = Math.round(s);
549
+ return s;
775
550
  }
551
+ /**
552
+ * Returns 'value' channel of hsv space as integer from 0 to 100.
553
+ */
554
+ get v() { return Math.round(this._max / 255 * 1000 / 10); }
555
+ /**
556
+ * Returns values of the channels as integers from 0 to 255. Format is { r: r, g: g, b: b, a: a }.
557
+ */
558
+ get channels() { return Object.assign({}, this._channels); }
776
559
  }
777
-
778
- const enrichStyleItemsWithIds = (style) => {
779
- return {
780
- ...style,
781
- items: style.items.map(item => {
782
- return {
783
- ...item,
784
- id: item.id || v4(),
785
- };
786
- }),
787
- };
560
+ // Big List of Colors
561
+ // ------------------
562
+ // <http://www.w3.org/TR/css3-color/#svg-color>
563
+ //noinspection SpellCheckingInspection
564
+ Color.names = {
565
+ aliceblue: "f0f8ff",
566
+ antiquewhite: "faebd7",
567
+ aqua: "0ff",
568
+ aquamarine: "7fffd4",
569
+ azure: "f0ffff",
570
+ beige: "f5f5dc",
571
+ bisque: "ffe4c4",
572
+ black: "000",
573
+ blanchedalmond: "ffebcd",
574
+ blue: "00f",
575
+ blueviolet: "8a2be2",
576
+ brown: "a52a2a",
577
+ burlywood: "deb887",
578
+ burntsienna: "ea7e5d",
579
+ cadetblue: "5f9ea0",
580
+ chartreuse: "7fff00",
581
+ chocolate: "d2691e",
582
+ coral: "ff7f50",
583
+ cornflowerblue: "6495ed",
584
+ cornsilk: "fff8dc",
585
+ crimson: "dc143c",
586
+ cyan: "0ff",
587
+ darkblue: "00008b",
588
+ darkcyan: "008b8b",
589
+ darkgoldenrod: "b8860b",
590
+ darkgray: "a9a9a9",
591
+ darkgreen: "006400",
592
+ darkgrey: "a9a9a9",
593
+ darkkhaki: "bdb76b",
594
+ darkmagenta: "8b008b",
595
+ darkolivegreen: "556b2f",
596
+ darkorange: "ff8c00",
597
+ darkorchid: "9932cc",
598
+ darkred: "8b0000",
599
+ darksalmon: "e9967a",
600
+ darkseagreen: "8fbc8f",
601
+ darkslateblue: "483d8b",
602
+ darkslategray: "2f4f4f",
603
+ darkslategrey: "2f4f4f",
604
+ darkturquoise: "00ced1",
605
+ darkviolet: "9400d3",
606
+ deeppink: "ff1493",
607
+ deepskyblue: "00bfff",
608
+ dimgray: "696969",
609
+ dimgrey: "696969",
610
+ dodgerblue: "1e90ff",
611
+ firebrick: "b22222",
612
+ floralwhite: "fffaf0",
613
+ forestgreen: "228b22",
614
+ fuchsia: "f0f",
615
+ gainsboro: "dcdcdc",
616
+ ghostwhite: "f8f8ff",
617
+ gold: "ffd700",
618
+ goldenrod: "daa520",
619
+ gray: "808080",
620
+ green: "008000",
621
+ greenyellow: "adff2f",
622
+ grey: "808080",
623
+ honeydew: "f0fff0",
624
+ hotpink: "ff69b4",
625
+ indianred: "cd5c5c",
626
+ indigo: "4b0082",
627
+ ivory: "fffff0",
628
+ khaki: "f0e68c",
629
+ lavender: "e6e6fa",
630
+ lavenderblush: "fff0f5",
631
+ lawngreen: "7cfc00",
632
+ lemonchiffon: "fffacd",
633
+ lightblue: "add8e6",
634
+ lightcoral: "f08080",
635
+ lightcyan: "e0ffff",
636
+ lightgoldenrodyellow: "fafad2",
637
+ lightgray: "d3d3d3",
638
+ lightgreen: "90ee90",
639
+ lightgrey: "d3d3d3",
640
+ lightpink: "ffb6c1",
641
+ lightsalmon: "ffa07a",
642
+ lightseagreen: "20b2aa",
643
+ lightskyblue: "87cefa",
644
+ lightslategray: "789",
645
+ lightslategrey: "789",
646
+ lightsteelblue: "b0c4de",
647
+ lightyellow: "ffffe0",
648
+ lime: "0f0",
649
+ limegreen: "32cd32",
650
+ linen: "faf0e6",
651
+ magenta: "f0f",
652
+ maroon: "800000",
653
+ mediumaquamarine: "66cdaa",
654
+ mediumblue: "0000cd",
655
+ mediumorchid: "ba55d3",
656
+ mediumpurple: "9370db",
657
+ mediumseagreen: "3cb371",
658
+ mediumslateblue: "7b68ee",
659
+ mediumspringgreen: "00fa9a",
660
+ mediumturquoise: "48d1cc",
661
+ mediumvioletred: "c71585",
662
+ midnightblue: "191970",
663
+ mintcream: "f5fffa",
664
+ mistyrose: "ffe4e1",
665
+ moccasin: "ffe4b5",
666
+ navajowhite: "ffdead",
667
+ navy: "000080",
668
+ oldlace: "fdf5e6",
669
+ olive: "808000",
670
+ olivedrab: "6b8e23",
671
+ orange: "ffa500",
672
+ orangered: "ff4500",
673
+ orchid: "da70d6",
674
+ palegoldenrod: "eee8aa",
675
+ palegreen: "98fb98",
676
+ paleturquoise: "afeeee",
677
+ palevioletred: "db7093",
678
+ papayawhip: "ffefd5",
679
+ peachpuff: "ffdab9",
680
+ peru: "cd853f",
681
+ pink: "ffc0cb",
682
+ plum: "dda0dd",
683
+ powderblue: "b0e0e6",
684
+ purple: "800080",
685
+ rebeccapurple: "663399",
686
+ red: "f00",
687
+ rosybrown: "bc8f8f",
688
+ royalblue: "4169e1",
689
+ saddlebrown: "8b4513",
690
+ salmon: "fa8072",
691
+ sandybrown: "f4a460",
692
+ seagreen: "2e8b57",
693
+ seashell: "fff5ee",
694
+ sienna: "a0522d",
695
+ silver: "c0c0c0",
696
+ skyblue: "87ceeb",
697
+ slateblue: "6a5acd",
698
+ slategray: "708090",
699
+ slategrey: "708090",
700
+ snow: "fffafa",
701
+ springgreen: "00ff7f",
702
+ steelblue: "4682b4",
703
+ tan: "d2b48c",
704
+ teal: "008080",
705
+ thistle: "d8bfd8",
706
+ tomato: "ff6347",
707
+ turquoise: "40e0d0",
708
+ violet: "ee82ee",
709
+ wheat: "f5deb3",
710
+ white: "fff",
711
+ whitesmoke: "f5f5f5",
712
+ yellow: "ff0",
713
+ yellowgreen: "9acd32",
714
+ transparent: '0000'
788
715
  };
789
-
790
- /** Стабильный ID элемента стиля для MapLibre, в том числе когда `item.id` не задан. */
791
- const getClientStyleItemId = (items, index) => {
792
- const explicitId = items[index]?.id;
793
- if (explicitId) {
794
- return explicitId;
795
- }
796
- const explicitIds = new Set(items.map(item => item.id).filter(Boolean));
797
- let generatedId = `__item_${index}`;
798
- while (explicitIds.has(generatedId)) {
799
- generatedId = `_${generatedId}`;
800
- }
801
- return generatedId;
802
- };
803
-
804
- const enrichStyleModelsWithIds = (style) => {
805
- return {
806
- ...style,
807
- models: style.models.map(model => {
808
- return {
809
- ...model,
810
- id: model.id || v4(),
811
- };
812
- }),
813
- };
814
- };
815
-
816
- const findAttributeInExpression = (expression) => {
817
- if (Array.isArray(expression) && expression.length === 2 && expression[0] === "get") {
818
- return [expression[1]];
819
- }
820
- return expression.reduce((acc, curr) => {
821
- if (!Array.isArray(curr)) {
822
- return acc;
823
- }
824
- if (curr[0] === "get") {
825
- return [...new Set([...acc, curr[1]])];
826
- }
827
- return [...new Set([...acc, ...findAttributeInExpression(curr)])];
828
- }, []);
829
- };
830
-
831
- const getActualExtrusionHeight = (paint) => {
832
- return Array.isArray(paint?.["fill-extrusion-height"]) && paint?.["fill-extrusion-height"][0] === "+"
833
- ? paint?.["fill-extrusion-height"][1]
834
- : paint?.["fill-extrusion-height"];
835
- };
836
-
837
- const getLayerClientStyle = (layer) => {
838
- const clientStyle = layer?.configuration?.clientStyle;
839
- return {
840
- ...clientStyle,
841
- items: clientStyle?.items ?? [],
842
- };
843
- };
844
-
845
- const extractAttributesFromObject = (obj) => {
846
- if (!obj || isEmpty(obj)) {
847
- return [];
848
- }
849
- return Object.entries(obj).reduce((acc, [, value]) => {
850
- if (!Array.isArray(value)) {
851
- return acc;
852
- }
853
- return [...new Set([...acc, ...findAttributeInExpression(value)])];
854
- }, []);
855
- };
856
- const getStyleAttributes = (style) => {
857
- if (!style) {
858
- return [];
859
- }
860
- return style?.items?.reduce((acc, curr) => {
861
- const paintAttributes = extractAttributesFromObject(curr.paint);
862
- const layoutAttributes = extractAttributesFromObject(curr.layout);
863
- const filterAttributes = curr.filter
864
- ? findAttributeInExpression(curr.filter)
865
- : [];
866
- return [...new Set([...acc, ...paintAttributes, ...layoutAttributes, ...filterAttributes])];
867
- }, []);
868
- };
869
-
870
- const DEFAULT_COLOR = "#00ffff";
871
- const DEFAULT_BLUR = 0;
872
- const DEFAULT_OPACITY = 0.5;
873
- const DEFAULT_TRANSLATE = [0, 0];
874
- const DEFAULT_FILL_EXTRUSION_BASE = 0;
875
- const DEFAULT_FILL_EXTRUSION_VERTICAL_GRADIENT = true;
876
- const DEFAULT_FILL_EXTRUSION_HEIGHT = 0;
877
- const DEFAULT_CIRCLE_RADIUS = 4;
878
- const DEFAULT_CIRCLE_STROKE_WIDTH = 0;
879
- const DEFAULT_LINE_WIDTH = 1;
880
- const DEFAULT_LINE_CAP = "butt";
881
- const DEFAULT_LINE_JOIN = "miter";
882
- const DEFAULT_SYMBOL_COLOR = "#000000";
883
- const DEFAULT_SYMBOL_HALO_COLOR = "#ffffff";
884
- const DEFAULT_SYMBOL_PLACEMENT = "point";
885
- const DEFAULT_SYMBOL_SPACING = 250;
886
- const DEFAULT_ICON_OVERLAP = "never";
887
- const DEFAULT_ICON_SIZE = 0.5;
888
- const DEFAULT_ICON_ANCHOR = "center";
889
- const DEFAULT_ICON_PADDING = [2];
890
- const DEFAULT_ICON_ROTATE = 0;
891
- const DEFAULT_TEXT_SIZE = 16;
892
- const DEFAULT_TEXT_ANCHOR = "center";
893
- const DEFAULT_TEXT_JUSTIFY = "center";
894
- const DEFAULT_TEXT_TRANSFORM = "none";
895
- const DEFAULT_HEATMAP_RADIUS = 30;
896
- const DEFAULT_HEATMAP_WEIGHT = 1;
897
- const DEFAULT_HEATMAP_INTENSITY = 1;
898
- const DEFAULT_HEATMAP_COLOR = [
899
- "interpolate",
900
- ["linear"],
901
- ["heatmap-density"],
902
- 0, "rgba(0, 0, 255, 0)",
903
- 0.1, "royalblue",
904
- 0.3, "cyan",
905
- 0.5, "lime",
906
- 0.7, "yellow",
907
- 1, "red",
908
- ];
909
- const DEFAULT_FILL_STYLE = {
910
- items: [
911
- {
912
- type: "fill",
913
- layout: {},
914
- paint: {
915
- "fill-color": DEFAULT_COLOR,
916
- "fill-opacity": DEFAULT_OPACITY,
917
- },
918
- },
919
- ],
920
- };
921
- const DEFAULT_FILL_EXTRUSION_STYLE = {
922
- items: [
923
- {
924
- type: "fill-extrusion",
925
- layout: {},
926
- paint: {
927
- "fill-extrusion-base": DEFAULT_FILL_EXTRUSION_BASE,
928
- "fill-extrusion-vertical-gradient": DEFAULT_FILL_EXTRUSION_VERTICAL_GRADIENT,
929
- "fill-extrusion-color": DEFAULT_COLOR,
930
- "fill-extrusion-opacity": DEFAULT_OPACITY,
931
- "fill-extrusion-height": DEFAULT_FILL_EXTRUSION_HEIGHT,
932
- },
933
- },
934
- ],
935
- };
936
- const DEFAULT_LINE_STYLE = {
937
- items: [
938
- {
939
- type: "line",
940
- layout: {
941
- "line-cap": DEFAULT_LINE_CAP,
942
- "line-join": DEFAULT_LINE_JOIN,
943
- },
944
- paint: {
945
- "line-color": DEFAULT_COLOR,
946
- "line-width": DEFAULT_LINE_WIDTH,
947
- "line-blur": DEFAULT_BLUR,
948
- "line-opacity": DEFAULT_OPACITY,
949
- "line-translate": DEFAULT_TRANSLATE,
950
- },
951
- },
952
- ],
953
- };
954
- const DEFAULT_CIRCLE_STYLE = {
955
- items: [
956
- {
957
- type: "circle",
958
- layout: {},
959
- paint: {
960
- "circle-radius": DEFAULT_CIRCLE_RADIUS,
961
- "circle-color": DEFAULT_COLOR,
962
- "circle-blur": DEFAULT_BLUR,
963
- "circle-opacity": DEFAULT_OPACITY,
964
- "circle-translate": DEFAULT_TRANSLATE,
965
- "circle-stroke-width": DEFAULT_CIRCLE_STROKE_WIDTH,
966
- "circle-stroke-color": DEFAULT_COLOR,
967
- "circle-stroke-opacity": DEFAULT_OPACITY,
968
- },
969
- },
970
- ],
971
- };
972
- const DEFAULT_SYMBOL_STYLE = {
973
- items: [
974
- {
975
- type: "symbol",
976
- layout: {
977
- "symbol-placement": DEFAULT_SYMBOL_PLACEMENT,
978
- "symbol-spacing": DEFAULT_SYMBOL_SPACING,
979
- "icon-overlap": DEFAULT_ICON_OVERLAP,
980
- "icon-size": DEFAULT_ICON_SIZE,
981
- "icon-anchor": DEFAULT_ICON_ANCHOR,
982
- "icon-padding": DEFAULT_ICON_PADDING,
983
- "icon-rotate": DEFAULT_ICON_ROTATE,
984
- "text-size": DEFAULT_TEXT_SIZE,
985
- "text-anchor": DEFAULT_TEXT_ANCHOR,
986
- "text-justify": DEFAULT_TEXT_JUSTIFY,
987
- "text-transform": DEFAULT_TEXT_TRANSFORM,
988
- },
989
- paint: {
990
- "icon-color": DEFAULT_SYMBOL_COLOR,
991
- "icon-halo-color": DEFAULT_SYMBOL_HALO_COLOR,
992
- "icon-opacity": DEFAULT_OPACITY,
993
- "text-color": DEFAULT_SYMBOL_COLOR,
994
- "text-halo-color": DEFAULT_SYMBOL_HALO_COLOR,
995
- "text-opacity": DEFAULT_OPACITY,
996
- },
997
- },
998
- ],
999
- };
1000
- const DEFAULT_HEATMAP_STYLE = {
1001
- items: [
1002
- {
1003
- type: "heatmap",
1004
- layout: {},
1005
- paint: {
1006
- "heatmap-radius": DEFAULT_HEATMAP_RADIUS,
1007
- "heatmap-weight": DEFAULT_HEATMAP_WEIGHT,
1008
- "heatmap-intensity": DEFAULT_HEATMAP_INTENSITY,
1009
- "heatmap-color": DEFAULT_HEATMAP_COLOR,
1010
- "heatmap-opacity": DEFAULT_OPACITY,
1011
- },
1012
- },
1013
- ],
1014
- };
1015
-
1016
- /**
1017
- * Извлекает имена иконок из выражения icon-image.
1018
- *
1019
- * Поддерживает:
1020
- * - Строки: "parking" → ["parking"]
1021
- * - match: ["match", ["get", "type"], "a", "icon-a", "b", "icon-b", "default"] → ["icon-a", "icon-b", "default"]
1022
- * - case: ["case", [...], "icon-a", "icon-b"] → ["icon-a", "icon-b"]
1023
- * - coalesce: ["coalesce", ["image", "icon-a"], ["image", "icon-b"]] → ["icon-a", "icon-b"]
1024
- * - image: ["image", "icon-a"] → ["icon-a"]
1025
- *
1026
- * @param iconImage - значение icon-image из layout
1027
- * @returns массив имён иконок
1028
- */
1029
- const parseIconNames = (iconImage) => {
1030
- if (!iconImage) {
1031
- return [];
1032
- }
1033
- // Простая строка: "parking"
1034
- if (typeof iconImage === "string") {
1035
- return [iconImage];
1036
- }
1037
- // Выражение Mapbox
1038
- if (Array.isArray(iconImage) && iconImage.length > 0) {
1039
- const [operator, ...args] = iconImage;
1040
- switch (operator) {
1041
- // ["match", input, label1, output1, label2, output2, ..., fallback]
1042
- case "match": {
1043
- const results = [];
1044
- // Пропускаем первый аргумент (input), берём каждый второй начиная с индекса 2
1045
- for (let i = 2; i < args.length; i += 2) {
1046
- if (typeof args[i] === "string") {
1047
- results.push(args[i]);
716
+ function decToHex(dec) {
717
+ let hex = Math.floor(dec).toString(16);
718
+ return hex.length === 1 ? '0' + hex : hex;
719
+ }
720
+ let formats = {
721
+ hex3: function (string) {
722
+ return {
723
+ r: parseInt(string.substr(1, 1) + string.substr(1, 1), 16),
724
+ g: parseInt(string.substr(2, 1) + string.substr(2, 1), 16),
725
+ b: parseInt(string.substr(3, 1) + string.substr(3, 1), 16),
726
+ a: 255
727
+ };
728
+ },
729
+ hex6: function (string) {
730
+ return {
731
+ r: parseInt(string.substr(1, 2), 16),
732
+ g: parseInt(string.substr(3, 2), 16),
733
+ b: parseInt(string.substr(5, 2), 16),
734
+ a: 255
735
+ };
736
+ },
737
+ hex4: function (string) {
738
+ return {
739
+ r: parseInt(string.substr(1, 1) + string.substr(1, 1), 16),
740
+ g: parseInt(string.substr(2, 1) + string.substr(2, 1), 16),
741
+ b: parseInt(string.substr(3, 1) + string.substr(3, 1), 16),
742
+ a: parseInt(string.substr(4, 1) + string.substr(4, 1), 16)
743
+ };
744
+ },
745
+ hex8: function (string) {
746
+ return {
747
+ r: parseInt(string.substr(1, 2), 16),
748
+ g: parseInt(string.substr(3, 2), 16),
749
+ b: parseInt(string.substr(5, 2), 16),
750
+ a: parseInt(string.substr(7, 2), 16)
751
+ };
752
+ },
753
+ rgb: function (string) {
754
+ let percents = string.match(/%/g);
755
+ if (!percents || percents.length === 3) {
756
+ var channels = string.substring(string.search(/\(/) + 1, string.length - 1).split(',');
757
+ for (var i = 0; i < 3; i++) {
758
+ if (channels[i]) {
759
+ channels[i] = channels[i].trim();
760
+ var percent = channels[i].match(/[.\d\-]+%/);
761
+ if (percent) {
762
+ var points = channels[i].match(/\./g);
763
+ channels[i] = channels[i].search(/[^\d.\-%]/) === -1 && (!points || points.length < 2) ? parseFloat(percent[0]) : NaN;
764
+ if (channels[i] < 0) {
765
+ channels[i] = 0;
766
+ }
767
+ else if (channels[i] > 100) {
768
+ channels[i] = 100;
769
+ }
770
+ channels[i] = Math.floor(channels[i] * 255 / 100);
1048
771
  }
1049
- else if (Array.isArray(args[i])) {
1050
- results.push(...parseIconNames(args[i]));
772
+ else {
773
+ channels[i] = channels[i] && (channels[i].match(/[^ \-0-9]/) === null) && channels[i].match(/[0-9]+/g).length === 1 ? parseInt(channels[i]) : NaN;
774
+ if (channels[i] < 0) {
775
+ channels[i] = 0;
776
+ }
777
+ else if (channels[i] > 255) {
778
+ channels[i] = 255;
779
+ }
1051
780
  }
1052
781
  }
1053
- // Последний аргумент - fallback (если нечётное количество после input)
1054
- const lastArg = args[args.length - 1];
1055
- if (typeof lastArg === "string") {
1056
- results.push(lastArg);
1057
- }
1058
- else if (Array.isArray(lastArg)) {
1059
- results.push(...parseIconNames(lastArg));
1060
- }
1061
- return [...new Set(results)];
1062
782
  }
1063
- // ["case", condition1, output1, condition2, output2, ..., fallback]
1064
- case "case": {
1065
- const results = [];
1066
- for (let i = 1; i < args.length; i += 2) {
1067
- if (typeof args[i] === "string") {
1068
- results.push(args[i]);
1069
- }
1070
- else if (Array.isArray(args[i])) {
1071
- results.push(...parseIconNames(args[i]));
1072
- }
783
+ }
784
+ else {
785
+ channels = [];
786
+ }
787
+ return {
788
+ r: channels[0],
789
+ g: channels[1],
790
+ b: channels[2],
791
+ a: 255
792
+ };
793
+ },
794
+ rgba: function (string) {
795
+ let channels = formats.rgb(string);
796
+ channels.a = undefined;
797
+ let match = string.match(/[\-0-9\.]+/g);
798
+ if (match && match[3]) {
799
+ let points = match[3].match(/\./g);
800
+ if (!points || points.length === 1) {
801
+ channels.a = parseFloat(match[3]);
802
+ if (channels.a < 0) {
803
+ channels.a = 0;
1073
804
  }
1074
- // Fallback
1075
- if (args.length % 2 === 0) {
1076
- const lastArg = args[args.length - 1];
1077
- if (typeof lastArg === "string") {
1078
- results.push(lastArg);
1079
- }
1080
- else if (Array.isArray(lastArg)) {
1081
- results.push(...parseIconNames(lastArg));
1082
- }
805
+ else if (channels.a > 1) {
806
+ channels.a = 1;
1083
807
  }
1084
- return [...new Set(results)];
1085
- }
1086
- // ["coalesce", expr1, expr2, ...]
1087
- case "coalesce": {
1088
- const results = [];
1089
- args.forEach(arg => {
1090
- if (typeof arg === "string") {
1091
- results.push(arg);
1092
- }
1093
- else if (Array.isArray(arg)) {
1094
- results.push(...parseIconNames(arg));
1095
- }
1096
- });
1097
- return [...new Set(results)];
1098
- }
1099
- // ["image", name] или ["image", name1, name2, ...]
1100
- case "image": {
1101
- return args.filter((arg) => typeof arg === "string");
808
+ channels.a = Math.round(channels.a * 255);
1102
809
  }
1103
- // ["concat", ...] или другие - рекурсивно ищем строки
1104
- default: {
1105
- const results = [];
1106
- args.forEach(arg => {
1107
- if (Array.isArray(arg)) {
1108
- results.push(...parseIconNames(arg));
1109
- }
1110
- });
1111
- return [...new Set(results)];
810
+ }
811
+ return channels;
812
+ },
813
+ name: function (string) {
814
+ let color = new Color('#' + Color.names[string]);
815
+ return color.channels;
816
+ }
817
+ };
818
+
819
+ class ColorScale {
820
+ constructor(palette) {
821
+ this.palette = palette;
822
+ }
823
+ getColor(p) {
824
+ const palette = this.palette.slice();
825
+ palette[0][0] = 0;
826
+ palette[palette.length - 1][0] = 1;
827
+ let colors = palette.map(item => { return new Color(item[1]); });
828
+ if (p >= 1) {
829
+ let color = new Color(palette[palette.length - 1][1]);
830
+ color.a = 255;
831
+ return color.toString();
832
+ }
833
+ for (let i = 0; i < palette.length; i++) {
834
+ if (palette[i][0] > p) {
835
+ let width = palette[i][0] - palette[i - 1][0];
836
+ let color1 = colors[i - 1];
837
+ let color2 = colors[i];
838
+ let k = (p - palette[i - 1][0]) / width;
839
+ let channels = ['r', 'g', 'b', 'a'].map(function (ch) { return Math.round(color1[ch] + (color2[ch] - color1[ch]) * k); });
840
+ channels[3] = 1;
841
+ return 'rgba(' + channels.join(',') + ')';
1112
842
  }
1113
843
  }
844
+ return null;
1114
845
  }
1115
- return [];
846
+ ;
847
+ }
848
+
849
+ const transparentizeColor = (originalColor, percent) => {
850
+ const color = new Color(originalColor);
851
+ color.a = Math.round((255 / 100) * percent);
852
+ return color.toString("hex");
1116
853
  };
1117
- /**
1118
- * Свойства, содержащие имена изображений (иконки и паттерны).
1119
- */
1120
- const IMAGE_PROPERTIES = {
1121
- layout: ["icon-image"],
1122
- paint: ["fill-pattern", "line-pattern", "fill-extrusion-pattern"],
854
+ const hexToRgba = (hexCode, opacity = 1) => {
855
+ let hex = hexCode.replace("#", "");
856
+ if (hex.length === 3) {
857
+ hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
858
+ }
859
+ const r = parseInt(hex.substring(0, 2), 16);
860
+ const g = parseInt(hex.substring(2, 4), 16);
861
+ const b = parseInt(hex.substring(4, 6), 16);
862
+ return `rgba(${r}, ${g}, ${b}, ${opacity})`;
863
+ };
864
+ const rgbToHex = (r, g, b) => {
865
+ const componentToHex = (c) => {
866
+ const hex = c.toString(16);
867
+ return hex.padStart(2, "0");
868
+ };
869
+ return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`;
1123
870
  };
871
+ const decimalOpacityToHex = (opacity) => {
872
+ const hex = Math.round(opacity * 255).toString(16);
873
+ return hex.padStart(2, "0");
874
+ };
875
+ const GRADIENT_COLORS = [
876
+ "#00C2FF",
877
+ "#67ADFE",
878
+ "#766EFB",
879
+ "#9D60F2",
880
+ "#EC63D6",
881
+ "#F35991",
882
+ "#EC474C",
883
+ "#FF7144",
884
+ "#FF9F33",
885
+ "#DEDE56",
886
+ "#A1E062",
887
+ "#51D8A5",
888
+ ];
889
+ const HEX_RRGGBB_LENGTH = 7;
1124
890
  /**
1125
- * Извлекает все имена изображений из clientStyle.
1126
- * Включает иконки (icon-image) и паттерны (fill-pattern, line-pattern, fill-extrusion-pattern).
1127
- *
1128
- * @param clientStyle - конфигурация стиля слоя
1129
- * @returns массив уникальных имён изображений
891
+ * Растягивает палитру на нужное количество цветов: опорные цвета равномерно
892
+ * раскладываются по шкале, недостающие интерполируются между ними.
893
+ * @param colors - опорные цвета палитры в hex
894
+ * @param count - требуемое количество цветов
895
+ * @returns массив ровно из count цветов
1130
896
  */
1131
- const parseIconNamesFromClientStyle = (clientStyle) => {
1132
- if (!clientStyle?.items) {
897
+ const stretchPalette = (colors, count) => {
898
+ if (!colors?.length || count <= 0)
1133
899
  return [];
1134
- }
1135
- const imageNames = new Set();
1136
- clientStyle.items.forEach(item => {
1137
- // Парсим icon-image из layout
1138
- IMAGE_PROPERTIES.layout.forEach(prop => {
1139
- const value = item.layout?.[prop];
1140
- if (value) {
1141
- parseIconNames(value).forEach(name => imageNames.add(name));
1142
- }
1143
- });
1144
- // Парсим fill-pattern, line-pattern, fill-extrusion-pattern из paint
1145
- IMAGE_PROPERTIES.paint.forEach(prop => {
1146
- const value = item.paint?.[prop];
1147
- if (value) {
1148
- parseIconNames(value).forEach(name => imageNames.add(name));
1149
- }
1150
- });
900
+ if (colors.length === 1)
901
+ return Array.from({ length: count }, () => colors[0]);
902
+ const scale = new ColorScale(colors.map((color, index) => [index / (colors.length - 1), color]));
903
+ return Array.from({ length: count }, (_, index) => {
904
+ const color = scale.getColor(count === 1 ? 0 : index / (count - 1));
905
+ return color ? new Color(color).toString("hex").slice(0, HEX_RRGGBB_LENGTH) : colors[colors.length - 1];
1151
906
  });
1152
- return [...imageNames];
1153
907
  };
1154
-
1155
- /** Предел широты сферического меркатора (EPSG:3857): дальше проекция уходит в бесконечность. */
1156
- const MERCATOR_MAX_LATITUDE = 85.05112878;
1157
- /** Предел долготы: карта рендерит копии мира, но экстент за пределами ±180° бэкенду не нужен. */
1158
- const MERCATOR_MAX_LONGITUDE = 180;
1159
-
908
+ const getGradientColors = (colorsCount) => stretchPalette(GRADIENT_COLORS, colorsCount === undefined || colorsCount < GRADIENT_COLORS.length ? GRADIENT_COLORS.length : colorsCount);
1160
909
  /**
1161
- * Returns true if n is a finite number, otherwise false
1162
- * @param n
910
+ * Converts HSL hue value to RGB
911
+ * @param p - lower bound
912
+ * @param q - upper bound
913
+ * @param t - hue value
914
+ * @returns RGB component value (0-1)
1163
915
  */
1164
- const isNumber = function (n) {
1165
- return typeof n === 'number' && isFinite(n);
916
+ const hue2rgb = (p, q, t) => {
917
+ if (t < 0)
918
+ t += 1;
919
+ if (t > 1)
920
+ t -= 1;
921
+ if (t < 1 / 6)
922
+ return p + (q - p) * 6 * t;
923
+ if (t < 1 / 2)
924
+ return q;
925
+ if (t < 2 / 3)
926
+ return p + (q - p) * (2 / 3 - t) * 6;
927
+ return p;
1166
928
  };
1167
929
  /**
1168
- * Returns true if s is a string, otherwise false
1169
- * @param s
930
+ * Converts RGB component (0-1) to hex string
931
+ * @param value - RGB component value (0-1)
932
+ * @returns hex string (00-ff)
1170
933
  */
1171
- const isString = function (s) {
1172
- return typeof s === 'string';
934
+ const toHex = (value) => {
935
+ const hex = Math.round(value * 255).toString(16);
936
+ return hex.padStart(2, "0");
1173
937
  };
1174
-
1175
938
  /**
1176
- * Utility class for working with different representations of colors in browsers
1177
- * @alias sGis.utils.Color
939
+ * Adjusts color brightness
940
+ * @param color - hex color string (e.g., "#2196f3")
941
+ * @param lightnessAdjustment - lightness adjustment in HSL units (e.g., 5 or -5)
942
+ * @returns adjusted color in hex format
1178
943
  */
1179
- class Color {
1180
- /**
1181
- * @param string - any valid css color string
1182
- */
1183
- constructor(string) {
1184
- this._original = string;
1185
- if (!isString(string))
1186
- string = string.toString();
1187
- this._color = string && string.trim() || 'transparent';
1188
- this._setChannels();
1189
- }
1190
- _setChannels() {
1191
- let format = this.format;
1192
- if (format && formats[format]) {
1193
- this._channels = formats[format](this._color);
1194
- }
1195
- else {
1196
- this._channels = { r: NaN, g: NaN, b: NaN, a: NaN };
1197
- }
1198
- }
1199
- get _min() { return Math.min(this._channels.r, this._channels.g, this._channels.b); }
1200
- get _max() { return Math.max(this._channels.r, this._channels.g, this._channels.b); }
1201
- get _delta() { return this._max - this._min; }
1202
- /**
1203
- * Returns the color as a string in the requested format
1204
- * @param format - target format. Available values: "hex" - #AARRGGBB, "rgb" - "rgb(r, g, b)", "rgba" - "rgba(r, g, b, a)"
1205
- */
1206
- toString(format) {
1207
- if (format === 'hex') {
1208
- return '#' + decToHex(this.r) + decToHex(this.g) + decToHex(this.b) + decToHex(this.a);
1209
- }
1210
- else if (format === 'rgb') {
1211
- return 'rgb(' + this.r + ',' + this.g + ',' + this.b + ')';
1212
- }
1213
- else {
1214
- return 'rgba(' + this.r + ',' + this.g + ',' + this.b + ',' + (this.a / 255).toFixed(2).replace(/\.*0+$/, '') + ')';
1215
- }
1216
- }
1217
- /**
1218
- * Returns the string given to the constructor of the instance
1219
- * @type {String}
1220
- */
1221
- get original() { return this._original; }
1222
- /**
1223
- * Returns true if the instance represents a valid color, i.e. that after parsing of the string given to the constructor,
1224
- * the format is recognized and values of all channels are resolved to valid numbers.
1225
- * @returns {Boolean}
1226
- */
1227
- get isValid() { return isNumber(this._channels.a) && isNumber(this._channels.r) && isNumber(this._channels.g) && isNumber(this._channels.b); }
1228
- /**
1229
- * Converts HSV color value into RGB
1230
- * @param h - hue value
1231
- * @param s - saturation value
1232
- * @param v - 'value' value
1233
- */
1234
- setHsv(h, s, v) {
1235
- let rgbColors = [];
1236
- h /= 60;
1237
- s /= 100;
1238
- v /= 100;
1239
- let floor = Math.floor(h);
1240
- let mod = floor % 6;
1241
- let f = h - floor;
1242
- let p = Math.round(255 * v * (1 - s));
1243
- let q = Math.round(255 * v * (1 - s * f));
1244
- let t = Math.round(255 * v * (1 - s * (1 - f)));
1245
- v = Math.round(255 * v);
1246
- switch (mod) {
1247
- case 0:
1248
- rgbColors = [v, t, p];
1249
- break;
1250
- case 1:
1251
- rgbColors = [q, v, p];
1252
- break;
1253
- case 2:
1254
- rgbColors = [p, v, t];
1255
- break;
1256
- case 3:
1257
- rgbColors = [p, q, v];
944
+ const adjustColor = (color, lightnessAdjustment = 5) => {
945
+ // Convert hex to RGB
946
+ const hex = color.replace("#", "");
947
+ const r = parseInt(hex.substring(0, 2), 16) / 255;
948
+ const g = parseInt(hex.substring(2, 4), 16) / 255;
949
+ const b = parseInt(hex.substring(4, 6), 16) / 255;
950
+ // Convert RGB to HSL
951
+ const max = Math.max(r, g, b);
952
+ const min = Math.min(r, g, b);
953
+ let h = 0;
954
+ let s = 0;
955
+ const l = (max + min) / 2;
956
+ if (max !== min) {
957
+ const d = max - min;
958
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
959
+ switch (max) {
960
+ case r:
961
+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
1258
962
  break;
1259
- case 4:
1260
- rgbColors = [t, p, v];
963
+ case g:
964
+ h = ((b - r) / d + 2) / 6;
1261
965
  break;
1262
- case 5:
1263
- rgbColors = [v, p, q];
966
+ case b:
967
+ h = ((r - g) / d + 4) / 6;
1264
968
  break;
1265
969
  }
1266
- this._channels.r = rgbColors[0];
1267
- this._channels.g = rgbColors[1];
1268
- this._channels.b = rgbColors[2];
1269
- return this;
1270
970
  }
1271
- /**
1272
- * Returns the format of the input color sting. Possible values: hex3, hex6, hex4, hex8, rgb, rgba, name.
1273
- * (name is the named css color values like "white")
1274
- */
1275
- get format() {
1276
- if (this._color.substr(0, 1) === '#' && this._color.search(/[^#0-9a-fA-F]/) === -1) {
1277
- if (this._color.length === 4) {
1278
- return 'hex3';
1279
- }
1280
- else if (this._color.length === 7) {
1281
- return 'hex6';
1282
- }
1283
- else if (this._color.length === 5) {
1284
- return 'hex4';
1285
- }
1286
- else if (this._color.length === 9) {
1287
- return 'hex8';
971
+ const adjustedL = Math.max(0, Math.min(100, (l * 100) + lightnessAdjustment)) / 100;
972
+ // Convert HSL back to RGB
973
+ let rNew;
974
+ let gNew;
975
+ let bNew;
976
+ if (s === 0) {
977
+ rNew = gNew = bNew = adjustedL;
978
+ }
979
+ else {
980
+ const q = adjustedL < 0.5 ? adjustedL * (1 + s) : adjustedL + s - adjustedL * s;
981
+ const p = 2 * adjustedL - q;
982
+ rNew = hue2rgb(p, q, h + 1 / 3);
983
+ gNew = hue2rgb(p, q, h);
984
+ bNew = hue2rgb(p, q, h - 1 / 3);
985
+ }
986
+ return `#${toHex(rNew)}${toHex(gNew)}${toHex(bNew)}`;
987
+ };
988
+ const OPAQUE_ALPHA = "ff";
989
+ /**
990
+ * Цвет в hex: `#rrggbb`, а при неполной непрозрачности — `#rrggbbaa`.
991
+ *
992
+ * Полностью непрозрачная альфа отбрасывается: в значении она ничего не уточняет, а строку
993
+ * удлиняет — и в конфиге, и в данных удобнее короткая запись.
994
+ */
995
+ const colorToHex = (color) => {
996
+ const hex = color.toString("hex");
997
+ return hex.slice(HEX_RRGGBB_LENGTH).toLowerCase() === OPAQUE_ALPHA ? hex.slice(0, HEX_RRGGBB_LENGTH) : hex;
998
+ };
999
+
1000
+ const NO_CONTENT_VALUE = "—";
1001
+ var DateFormat;
1002
+ (function (DateFormat) {
1003
+ DateFormat["ClientDefaultFormat"] = "dd.MM.yyyy HH:mm";
1004
+ DateFormat["DateTime"] = "dd.MM.yyyy HH:mm:ss";
1005
+ DateFormat["UTC"] = "yyyy-MM-dd'T'HH:mm:ss.sssxxx";
1006
+ DateFormat["AxisTooltip"] = "d MMMM yyyy";
1007
+ })(DateFormat || (DateFormat = {}));
1008
+ const stringDateParsers = [parseJSON, parseISO, rawDate => new Date(rawDate)];
1009
+ const getDate = (rawDate) => {
1010
+ if (!rawDate) {
1011
+ return null;
1012
+ }
1013
+ if (typeof rawDate === "string") {
1014
+ for (const parser of stringDateParsers) {
1015
+ const date = parser(rawDate);
1016
+ if (isValid(date)) {
1017
+ return toDate(date);
1288
1018
  }
1289
1019
  }
1290
- else if (this._color.substr(0, 4) === 'rgb(') {
1291
- return 'rgb';
1292
- }
1293
- else if (this._color.substr(0, 5) === 'rgba(') {
1294
- return 'rgba';
1295
- }
1296
- else if (this._color.substr(0, 4) === 'hsv(') {
1297
- return 'hsv';
1298
- }
1299
- else if (this._color in Color.names) {
1300
- return 'name';
1301
- }
1020
+ return null;
1302
1021
  }
1303
- /**
1304
- * Returns red channel value as integer from 0 to 255.
1305
- */
1306
- get r() { return this._channels.r; }
1307
- set r(v) { this._channels.r = v; }
1308
- /**
1309
- * Returns green channel value as integer from 0 to 255.
1310
- */
1311
- get g() { return this._channels.g; }
1312
- set g(v) { this._channels.g = v; }
1313
- /**
1314
- * Returns blue channel value as integer from 0 to 255.
1315
- */
1316
- get b() { return this._channels.b; }
1317
- set b(v) { this._channels.b = v; }
1318
- /**
1319
- * Returns opacity channel value as integer from 0 to 255.
1320
- */
1321
- get a() { return this._channels.a; }
1322
- set a(v) { this._channels.a = v; }
1323
- /**
1324
- * Returns hue channel value as integer from 0 to 360.
1325
- */
1326
- get h() {
1327
- let max = this._max;
1328
- let min = this._min;
1329
- let delta = this._delta;
1330
- let h;
1331
- let { r, g, b } = this._channels;
1332
- if (max === min)
1333
- h = 0;
1334
- else if (r === max)
1335
- h = (g - b) / delta;
1336
- else if (g === max)
1337
- h = 2 + (b - r) / delta;
1338
- else if (b === max)
1339
- h = 4 + (r - g) / delta;
1340
- h = Math.min(h * 60, 360);
1341
- if (h < 0)
1342
- h += 360;
1343
- h = Math.round(h);
1344
- return h;
1022
+ const parsedDate = toDate(rawDate);
1023
+ return isValid(parsedDate) ? parsedDate : null;
1024
+ };
1025
+ const formatDate$1 = (date, { dateFormat = DateFormat.ClientDefaultFormat, defaultValue = NO_CONTENT_VALUE } = {}) => {
1026
+ const dateValue = date ? getDate(date) : null;
1027
+ if (isValid(dateValue)) {
1028
+ return format(dateValue, dateFormat);
1345
1029
  }
1346
- /**
1347
- * Returns saturation channel value as integer from 0 to 100.
1348
- */
1349
- get s() {
1350
- let s;
1351
- let max = this._max;
1352
- if (max === 0)
1353
- s = 0;
1354
- else
1355
- s = this._delta / max * 1000 / 10;
1356
- s = Math.round(s);
1357
- return s;
1030
+ return `${defaultValue}`;
1031
+ };
1032
+
1033
+ const debounce = (callback, delay) => {
1034
+ let timeId;
1035
+ return (...args) => {
1036
+ if (timeId) {
1037
+ window.clearTimeout(timeId);
1038
+ }
1039
+ timeId = window.setTimeout(() => {
1040
+ callback(...args);
1041
+ }, delay);
1042
+ };
1043
+ };
1044
+
1045
+ const MILLION = 1000000;
1046
+ const TEN_THOUSANDS = 10000;
1047
+ const THOUSAND = 1000;
1048
+ const COMPACT_FRACTION_DIGITS = 1;
1049
+ const roundTotalSum = (value, fractionDigits) => {
1050
+ if (!value)
1051
+ return "";
1052
+ const digits = fractionDigits ?? COMPACT_FRACTION_DIGITS;
1053
+ if (value >= MILLION) {
1054
+ return `${(value / MILLION).toFixed(digits)}M`;
1358
1055
  }
1359
- /**
1360
- * Returns 'value' channel of hsv space as integer from 0 to 100.
1361
- */
1362
- get v() { return Math.round(this._max / 255 * 1000 / 10); }
1363
- /**
1364
- * Returns values of the channels as integers from 0 to 255. Format is { r: r, g: g, b: b, a: a }.
1365
- */
1366
- get channels() { return Object.assign({}, this._channels); }
1367
- }
1368
- // Big List of Colors
1369
- // ------------------
1370
- // <http://www.w3.org/TR/css3-color/#svg-color>
1371
- //noinspection SpellCheckingInspection
1372
- Color.names = {
1373
- aliceblue: "f0f8ff",
1374
- antiquewhite: "faebd7",
1375
- aqua: "0ff",
1376
- aquamarine: "7fffd4",
1377
- azure: "f0ffff",
1378
- beige: "f5f5dc",
1379
- bisque: "ffe4c4",
1380
- black: "000",
1381
- blanchedalmond: "ffebcd",
1382
- blue: "00f",
1383
- blueviolet: "8a2be2",
1384
- brown: "a52a2a",
1385
- burlywood: "deb887",
1386
- burntsienna: "ea7e5d",
1387
- cadetblue: "5f9ea0",
1388
- chartreuse: "7fff00",
1389
- chocolate: "d2691e",
1390
- coral: "ff7f50",
1391
- cornflowerblue: "6495ed",
1392
- cornsilk: "fff8dc",
1393
- crimson: "dc143c",
1394
- cyan: "0ff",
1395
- darkblue: "00008b",
1396
- darkcyan: "008b8b",
1397
- darkgoldenrod: "b8860b",
1398
- darkgray: "a9a9a9",
1399
- darkgreen: "006400",
1400
- darkgrey: "a9a9a9",
1401
- darkkhaki: "bdb76b",
1402
- darkmagenta: "8b008b",
1403
- darkolivegreen: "556b2f",
1404
- darkorange: "ff8c00",
1405
- darkorchid: "9932cc",
1406
- darkred: "8b0000",
1407
- darksalmon: "e9967a",
1408
- darkseagreen: "8fbc8f",
1409
- darkslateblue: "483d8b",
1410
- darkslategray: "2f4f4f",
1411
- darkslategrey: "2f4f4f",
1412
- darkturquoise: "00ced1",
1413
- darkviolet: "9400d3",
1414
- deeppink: "ff1493",
1415
- deepskyblue: "00bfff",
1416
- dimgray: "696969",
1417
- dimgrey: "696969",
1418
- dodgerblue: "1e90ff",
1419
- firebrick: "b22222",
1420
- floralwhite: "fffaf0",
1421
- forestgreen: "228b22",
1422
- fuchsia: "f0f",
1423
- gainsboro: "dcdcdc",
1424
- ghostwhite: "f8f8ff",
1425
- gold: "ffd700",
1426
- goldenrod: "daa520",
1427
- gray: "808080",
1428
- green: "008000",
1429
- greenyellow: "adff2f",
1430
- grey: "808080",
1431
- honeydew: "f0fff0",
1432
- hotpink: "ff69b4",
1433
- indianred: "cd5c5c",
1434
- indigo: "4b0082",
1435
- ivory: "fffff0",
1436
- khaki: "f0e68c",
1437
- lavender: "e6e6fa",
1438
- lavenderblush: "fff0f5",
1439
- lawngreen: "7cfc00",
1440
- lemonchiffon: "fffacd",
1441
- lightblue: "add8e6",
1442
- lightcoral: "f08080",
1443
- lightcyan: "e0ffff",
1444
- lightgoldenrodyellow: "fafad2",
1445
- lightgray: "d3d3d3",
1446
- lightgreen: "90ee90",
1447
- lightgrey: "d3d3d3",
1448
- lightpink: "ffb6c1",
1449
- lightsalmon: "ffa07a",
1450
- lightseagreen: "20b2aa",
1451
- lightskyblue: "87cefa",
1452
- lightslategray: "789",
1453
- lightslategrey: "789",
1454
- lightsteelblue: "b0c4de",
1455
- lightyellow: "ffffe0",
1456
- lime: "0f0",
1457
- limegreen: "32cd32",
1458
- linen: "faf0e6",
1459
- magenta: "f0f",
1460
- maroon: "800000",
1461
- mediumaquamarine: "66cdaa",
1462
- mediumblue: "0000cd",
1463
- mediumorchid: "ba55d3",
1464
- mediumpurple: "9370db",
1465
- mediumseagreen: "3cb371",
1466
- mediumslateblue: "7b68ee",
1467
- mediumspringgreen: "00fa9a",
1468
- mediumturquoise: "48d1cc",
1469
- mediumvioletred: "c71585",
1470
- midnightblue: "191970",
1471
- mintcream: "f5fffa",
1472
- mistyrose: "ffe4e1",
1473
- moccasin: "ffe4b5",
1474
- navajowhite: "ffdead",
1475
- navy: "000080",
1476
- oldlace: "fdf5e6",
1477
- olive: "808000",
1478
- olivedrab: "6b8e23",
1479
- orange: "ffa500",
1480
- orangered: "ff4500",
1481
- orchid: "da70d6",
1482
- palegoldenrod: "eee8aa",
1483
- palegreen: "98fb98",
1484
- paleturquoise: "afeeee",
1485
- palevioletred: "db7093",
1486
- papayawhip: "ffefd5",
1487
- peachpuff: "ffdab9",
1488
- peru: "cd853f",
1489
- pink: "ffc0cb",
1490
- plum: "dda0dd",
1491
- powderblue: "b0e0e6",
1492
- purple: "800080",
1493
- rebeccapurple: "663399",
1494
- red: "f00",
1495
- rosybrown: "bc8f8f",
1496
- royalblue: "4169e1",
1497
- saddlebrown: "8b4513",
1498
- salmon: "fa8072",
1499
- sandybrown: "f4a460",
1500
- seagreen: "2e8b57",
1501
- seashell: "fff5ee",
1502
- sienna: "a0522d",
1503
- silver: "c0c0c0",
1504
- skyblue: "87ceeb",
1505
- slateblue: "6a5acd",
1506
- slategray: "708090",
1507
- slategrey: "708090",
1508
- snow: "fffafa",
1509
- springgreen: "00ff7f",
1510
- steelblue: "4682b4",
1511
- tan: "d2b48c",
1512
- teal: "008080",
1513
- thistle: "d8bfd8",
1514
- tomato: "ff6347",
1515
- turquoise: "40e0d0",
1516
- violet: "ee82ee",
1517
- wheat: "f5deb3",
1518
- white: "fff",
1519
- whitesmoke: "f5f5f5",
1520
- yellow: "ff0",
1521
- yellowgreen: "9acd32",
1522
- transparent: '0000'
1056
+ if (value >= TEN_THOUSANDS) {
1057
+ return `${(value / THOUSAND).toFixed(digits)}K`;
1058
+ }
1059
+ return value;
1523
1060
  };
1524
- function decToHex(dec) {
1525
- let hex = Math.floor(dec).toString(16);
1526
- return hex.length === 1 ? '0' + hex : hex;
1527
- }
1528
- let formats = {
1529
- hex3: function (string) {
1530
- return {
1531
- r: parseInt(string.substr(1, 1) + string.substr(1, 1), 16),
1532
- g: parseInt(string.substr(2, 1) + string.substr(2, 1), 16),
1533
- b: parseInt(string.substr(3, 1) + string.substr(3, 1), 16),
1534
- a: 255
1535
- };
1061
+
1062
+ const TIME_ZONE_FORMAT = ' "GMT"z'; // eslint-disable-line
1063
+ var ScalingFactor;
1064
+ (function (ScalingFactor) {
1065
+ ScalingFactor[ScalingFactor["Default"] = 1] = "Default";
1066
+ ScalingFactor[ScalingFactor["Thousands"] = 0.001] = "Thousands";
1067
+ ScalingFactor[ScalingFactor["Millions"] = 0.000001] = "Millions";
1068
+ ScalingFactor[ScalingFactor["Acres"] = 0.01] = "Acres";
1069
+ ScalingFactor[ScalingFactor["Hectares"] = 0.0001] = "Hectares";
1070
+ })(ScalingFactor || (ScalingFactor = {}));
1071
+ const formatDate = (str, isRuLocale) => format(Date.now(), str, { locale: isRuLocale ? ru : enUS });
1072
+ const timeOptions = [
1073
+ {
1074
+ text: formatDate("kk:mm:ss"),
1075
+ value: "hh:mm:ss",
1076
+ },
1077
+ {
1078
+ text: formatDate("hh:mm:ss aa"),
1079
+ value: "hh:mm:ss tt",
1080
+ },
1081
+ {
1082
+ text: formatDate("kk:mm"),
1083
+ value: "hh:mm",
1084
+ },
1085
+ {
1086
+ text: formatDate("hh:mm aa"),
1087
+ value: "hh:mm tt",
1088
+ },
1089
+ ];
1090
+ const dateOptions = [
1091
+ {
1092
+ text: formatDate("dd.MM.yyyy"),
1093
+ value: "dd.MM.yyyy",
1094
+ },
1095
+ {
1096
+ text: formatDate("dd MMMM yyyy", true),
1097
+ value: "dd MMMM yyyy",
1098
+ },
1099
+ {
1100
+ text: formatDate("yyyy, dd MMMM", true),
1101
+ value: "yyyy, dd MMMM",
1536
1102
  },
1537
- hex6: function (string) {
1538
- return {
1539
- r: parseInt(string.substr(1, 2), 16),
1540
- g: parseInt(string.substr(3, 2), 16),
1541
- b: parseInt(string.substr(5, 2), 16),
1542
- a: 255
1543
- };
1103
+ ];
1104
+ const pointOptions = [
1105
+ {
1106
+ value: "default",
1107
+ localizationKey: "defaultValue",
1544
1108
  },
1545
- hex4: function (string) {
1546
- return {
1547
- r: parseInt(string.substr(1, 1) + string.substr(1, 1), 16),
1548
- g: parseInt(string.substr(2, 1) + string.substr(2, 1), 16),
1549
- b: parseInt(string.substr(3, 1) + string.substr(3, 1), 16),
1550
- a: parseInt(string.substr(4, 1) + string.substr(4, 1), 16)
1551
- };
1109
+ {
1110
+ value: "DD MM SS",
1111
+ localizationKey: "degreesMinutesSeconds",
1552
1112
  },
1553
- hex8: function (string) {
1554
- return {
1555
- r: parseInt(string.substr(1, 2), 16),
1556
- g: parseInt(string.substr(3, 2), 16),
1557
- b: parseInt(string.substr(5, 2), 16),
1558
- a: parseInt(string.substr(7, 2), 16)
1559
- };
1113
+ {
1114
+ value: "DD.",
1115
+ localizationKey: "decimalDegrees",
1560
1116
  },
1561
- rgb: function (string) {
1562
- let percents = string.match(/%/g);
1563
- if (!percents || percents.length === 3) {
1564
- var channels = string.substring(string.search(/\(/) + 1, string.length - 1).split(',');
1565
- for (var i = 0; i < 3; i++) {
1566
- if (channels[i]) {
1567
- channels[i] = channels[i].trim();
1568
- var percent = channels[i].match(/[.\d\-]+%/);
1569
- if (percent) {
1570
- var points = channels[i].match(/\./g);
1571
- channels[i] = channels[i].search(/[^\d.\-%]/) === -1 && (!points || points.length < 2) ? parseFloat(percent[0]) : NaN;
1572
- if (channels[i] < 0) {
1573
- channels[i] = 0;
1574
- }
1575
- else if (channels[i] > 100) {
1576
- channels[i] = 100;
1577
- }
1578
- channels[i] = Math.floor(channels[i] * 255 / 100);
1579
- }
1580
- else {
1581
- channels[i] = channels[i] && (channels[i].match(/[^ \-0-9]/) === null) && channels[i].match(/[0-9]+/g).length === 1 ? parseInt(channels[i]) : NaN;
1582
- if (channels[i] < 0) {
1583
- channels[i] = 0;
1584
- }
1585
- else if (channels[i] > 255) {
1586
- channels[i] = 255;
1587
- }
1588
- }
1589
- }
1590
- }
1591
- }
1592
- else {
1593
- channels = [];
1594
- }
1595
- return {
1596
- r: channels[0],
1597
- g: channels[1],
1598
- b: channels[2],
1599
- a: 255
1600
- };
1117
+ ];
1118
+ const numberOptions = [
1119
+ {
1120
+ value: ScalingFactor.Default.toString(),
1121
+ localizationKey: "defaultValue",
1601
1122
  },
1602
- rgba: function (string) {
1603
- let channels = formats.rgb(string);
1604
- channels.a = undefined;
1605
- let match = string.match(/[\-0-9\.]+/g);
1606
- if (match && match[3]) {
1607
- let points = match[3].match(/\./g);
1608
- if (!points || points.length === 1) {
1609
- channels.a = parseFloat(match[3]);
1610
- if (channels.a < 0) {
1611
- channels.a = 0;
1612
- }
1613
- else if (channels.a > 1) {
1614
- channels.a = 1;
1615
- }
1616
- channels.a = Math.round(channels.a * 255);
1617
- }
1618
- }
1619
- return channels;
1123
+ {
1124
+ value: ScalingFactor.Thousands.toString(),
1125
+ localizationKey: "inThousands",
1620
1126
  },
1621
- name: function (string) {
1622
- let color = new Color('#' + Color.names[string]);
1623
- return color.channels;
1127
+ {
1128
+ value: ScalingFactor.Millions.toString(),
1129
+ localizationKey: "inMillions",
1130
+ },
1131
+ {
1132
+ value: ScalingFactor.Acres.toString(),
1133
+ localizationKey: "inAcres",
1134
+ },
1135
+ {
1136
+ value: ScalingFactor.Hectares.toString(),
1137
+ localizationKey: "inHectares",
1138
+ },
1139
+ ];
1140
+ const convertDDToDMS = (value) => {
1141
+ const absolute = Math.abs(value);
1142
+ const degrees = Math.floor(absolute);
1143
+ const minutesNotTruncated = (absolute - degrees) * 60;
1144
+ const minutes = Math.floor(minutesNotTruncated);
1145
+ const seconds = Math.floor((minutesNotTruncated - minutes) * 60);
1146
+ return `${degrees}° ${minutes}' ${seconds}"`;
1147
+ };
1148
+ const formatPointValue = ({ t, stringFormat, value }) => {
1149
+ if (stringFormat.format === pointOptions[1].value) {
1150
+ const lon = value[1];
1151
+ const lat = value[0];
1152
+ const lonDirection = lon >= 0 ? t("east", { ns: "common" }) : t("west", { ns: "common" });
1153
+ const latDirection = lat >= 0 ? t("north", { ns: "common" }) : t("south", { ns: "common" });
1154
+ return `${convertDDToDMS(lon)} ${lonDirection}, ${convertDDToDMS(lat)} ${latDirection}`;
1155
+ }
1156
+ if (stringFormat.format.includes("DD.") && value.length) {
1157
+ const rounding = stringFormat.format.replace("DD.", "").length;
1158
+ return `${value[0].toFixed(rounding)}, ${value[1].toFixed(rounding)}`;
1624
1159
  }
1160
+ return null;
1625
1161
  };
1626
-
1627
- class ColorScale {
1628
- constructor(palette) {
1629
- this.palette = palette;
1162
+ const getValueFromOptions = (options, format) => options.find(({ value }) => format && format.includes(value));
1163
+ const numberWithSpaces = (input, precision) => {
1164
+ if (input === null || input === undefined) {
1165
+ return "";
1630
1166
  }
1631
- getColor(p) {
1632
- const palette = this.palette.slice();
1633
- palette[0][0] = 0;
1634
- palette[palette.length - 1][0] = 1;
1635
- let colors = palette.map(item => { return new Color(item[1]); });
1636
- if (p >= 1) {
1637
- let color = new Color(palette[palette.length - 1][1]);
1638
- color.a = 255;
1639
- return color.toString();
1167
+ return parseFloat((typeof input === "string" ? parseFloat(input) : input).toString()).toLocaleString("ru-RU", {
1168
+ maximumFractionDigits: precision ?? 10,
1169
+ });
1170
+ };
1171
+ const formatDateValue = (stringFormat, dateValue) => {
1172
+ let value = dateValue;
1173
+ if (typeof value === "string") {
1174
+ value = new Date(value).getTime();
1175
+ }
1176
+ const isRuLocale = stringFormat.culture && stringFormat.culture === "ru-RU";
1177
+ const showTimeZone = stringFormat.format.includes(TIME_ZONE_FORMAT);
1178
+ const dateOption = getValueFromOptions(dateOptions, stringFormat.format);
1179
+ const dateOptionValue = dateOption && dateOption.value;
1180
+ const dateFormat = value && dateOptionValue
1181
+ ? format(value, dateOptionValue, {
1182
+ locale: ru,
1183
+ })
1184
+ : "";
1185
+ const timeOption = getValueFromOptions(timeOptions, stringFormat.format);
1186
+ const timeOptionValue = timeOption && (isRuLocale ? timeOption.value : `${timeOption.value} aa`);
1187
+ const timeFormat = (timeOptionValue && format(value, showTimeZone ? `${timeOptionValue} zz` : timeOptionValue)) || "";
1188
+ return dateFormat ? [dateFormat, timeFormat].filter(Boolean).join(" ") : "";
1189
+ };
1190
+ const appendUnitsLabel = (value, unitsLabel, noUnits) => (unitsLabel && !noUnits ? `${value} ${unitsLabel}` : value)?.toString() || "";
1191
+ const formatNumberValue = (stringFormat, value, type, noUnits = false) => {
1192
+ const { scalingFactor, rounding, splitDigitGroup, roundDigitGroup, unitsLabel } = stringFormat || {};
1193
+ const isIntValue = [AttributeType.Int32, AttributeType.Int64].includes(type);
1194
+ const isDefaultScaling = stringFormat && stringFormat.scalingFactor === +numberOptions[0].value;
1195
+ let currentValue = value;
1196
+ if (isIntValue && isDefaultScaling && currentValue) {
1197
+ currentValue = parseInt(currentValue.toString(), 10);
1198
+ }
1199
+ if (scalingFactor) {
1200
+ currentValue *= scalingFactor;
1201
+ }
1202
+ const hasRounding = !isNil(rounding);
1203
+ const compactValue = roundDigitGroup
1204
+ ? roundTotalSum(Number(currentValue), hasRounding ? rounding : undefined)
1205
+ : null;
1206
+ if (typeof compactValue === "string" && compactValue) {
1207
+ return appendUnitsLabel(compactValue, unitsLabel, noUnits);
1208
+ }
1209
+ if (hasRounding && (!isIntValue || !isDefaultScaling) && !isNil(currentValue)) {
1210
+ currentValue = Number(currentValue).toFixed(rounding);
1211
+ }
1212
+ if (splitDigitGroup) {
1213
+ currentValue = numberWithSpaces(currentValue);
1214
+ }
1215
+ if (currentValue) {
1216
+ currentValue = currentValue.toString().replace(".", ",");
1217
+ }
1218
+ return appendUnitsLabel(currentValue, unitsLabel, noUnits);
1219
+ };
1220
+ const formatAttributeValue = ({ t, type, value, stringFormat, noUnits = false }) => {
1221
+ const isNilValue = isNil(value);
1222
+ if (type === AttributeType.Point) {
1223
+ if (!stringFormat?.format || isNilValue) {
1224
+ return null;
1640
1225
  }
1641
- for (let i = 0; i < palette.length; i++) {
1642
- if (palette[i][0] > p) {
1643
- let width = palette[i][0] - palette[i - 1][0];
1644
- let color1 = colors[i - 1];
1645
- let color2 = colors[i];
1646
- let k = (p - palette[i - 1][0]) / width;
1647
- let channels = ['r', 'g', 'b', 'a'].map(function (ch) { return Math.round(color1[ch] + (color2[ch] - color1[ch]) * k); });
1648
- channels[3] = 1;
1649
- return 'rgba(' + channels.join(',') + ')';
1226
+ return formatPointValue({ t, stringFormat, value: value?.coordinates });
1227
+ }
1228
+ if (type === AttributeType.DateTime) {
1229
+ if (isNilValue) {
1230
+ return null;
1231
+ }
1232
+ if (!stringFormat?.format) {
1233
+ return value;
1234
+ }
1235
+ return formatDateValue(stringFormat, value);
1236
+ }
1237
+ if ([
1238
+ AttributeType.Int32,
1239
+ AttributeType.Int64,
1240
+ AttributeType.Double,
1241
+ AttributeType.Polygon,
1242
+ AttributeType.LineString,
1243
+ AttributeType.MultiPoint,
1244
+ AttributeType.MultiPolygon,
1245
+ AttributeType.MultiLineString,
1246
+ ].includes(type) &&
1247
+ !isNaN(value)) {
1248
+ if (!stringFormat && !isNilValue) {
1249
+ return value.toString();
1250
+ }
1251
+ return formatNumberValue(stringFormat, value, type, noUnits);
1252
+ }
1253
+ if (type === AttributeType.Json) {
1254
+ if (isNilValue || value?.length === 0) {
1255
+ return "";
1256
+ }
1257
+ return `${t("total", { ns: "table" })} ${value.length}`;
1258
+ }
1259
+ return !isNilValue ? value.toString() : "";
1260
+ };
1261
+ const formatNumber = (number) => {
1262
+ let result = "";
1263
+ const gapSize = 3;
1264
+ if (typeof number === "number") {
1265
+ const numsArray = String(number).split(".");
1266
+ const numeral = numsArray[0];
1267
+ let spaceBefore = numeral.length % gapSize;
1268
+ for (let i = 0; i < numeral.length; i += 1) {
1269
+ if (i === spaceBefore) {
1270
+ result = `${result} `;
1271
+ spaceBefore += 3;
1650
1272
  }
1273
+ result += numeral[i];
1651
1274
  }
1652
- return null;
1275
+ if (numsArray[1]) {
1276
+ return [result.trim(), numsArray[1]].join(".");
1277
+ }
1278
+ return result.trim();
1653
1279
  }
1654
- ;
1655
- }
1656
-
1657
- const transparentizeColor = (originalColor, percent) => {
1658
- const color = new Color(originalColor);
1659
- color.a = Math.round((255 / 100) * percent);
1660
- return color.toString("hex");
1280
+ return number || "0";
1661
1281
  };
1662
- const hexToRgba = (hexCode, opacity = 1) => {
1663
- let hex = hexCode.replace("#", "");
1664
- if (hex.length === 3) {
1665
- hex = `${hex[0]}${hex[0]}${hex[1]}${hex[1]}${hex[2]}${hex[2]}`;
1282
+ const formatArea = (t, num) => {
1283
+ let result = num;
1284
+ let measure = t("sqMeter", { ns: "common" });
1285
+ if (num >= 10000000) {
1286
+ result = num / 1000000;
1287
+ measure = t("sqKilometer", { ns: "common" });
1666
1288
  }
1667
- const r = parseInt(hex.substring(0, 2), 16);
1668
- const g = parseInt(hex.substring(2, 4), 16);
1669
- const b = parseInt(hex.substring(4, 6), 16);
1670
- return `rgba(${r}, ${g}, ${b}, ${opacity})`;
1671
- };
1672
- const rgbToHex = (r, g, b) => {
1673
- const componentToHex = (c) => {
1674
- const hex = c.toString(16);
1675
- return hex.padStart(2, "0");
1676
- };
1677
- return `#${componentToHex(r)}${componentToHex(g)}${componentToHex(b)}`;
1289
+ else if (num >= 10000) {
1290
+ result = num / 10000;
1291
+ measure = t("hectare", { ns: "common" });
1292
+ }
1293
+ return `${numberWithSpaces(result, 2)} ${measure}`;
1678
1294
  };
1679
- const decimalOpacityToHex = (opacity) => {
1680
- const hex = Math.round(opacity * 255).toString(16);
1681
- return hex.padStart(2, "0");
1295
+ const formatLength = (t, num) => {
1296
+ let result = num;
1297
+ let measure = t("meter", { ns: "common" });
1298
+ if (num > 10000) {
1299
+ result = num / 1000;
1300
+ measure = t("kilometer", { ns: "common" });
1301
+ }
1302
+ return `${numberWithSpaces(result, 2)} ${measure}`;
1682
1303
  };
1683
- const GRADIENT_COLORS = [
1684
- "#00C2FF",
1685
- "#67ADFE",
1686
- "#766EFB",
1687
- "#9D60F2",
1688
- "#EC63D6",
1689
- "#F35991",
1690
- "#EC474C",
1691
- "#FF7144",
1692
- "#FF9F33",
1693
- "#DEDE56",
1694
- "#A1E062",
1695
- "#51D8A5",
1696
- ];
1697
- const HEX_RRGGBB_LENGTH = 7;
1698
- /**
1699
- * Растягивает палитру на нужное количество цветов: опорные цвета равномерно
1700
- * раскладываются по шкале, недостающие интерполируются между ними.
1701
- * @param colors - опорные цвета палитры в hex
1702
- * @param count - требуемое количество цветов
1703
- * @returns массив ровно из count цветов
1704
- */
1705
- const stretchPalette = (colors, count) => {
1706
- if (!colors?.length || count <= 0)
1707
- return [];
1708
- if (colors.length === 1)
1709
- return Array.from({ length: count }, () => colors[0]);
1710
- const scale = new ColorScale(colors.map((color, index) => [index / (colors.length - 1), color]));
1711
- return Array.from({ length: count }, (_, index) => {
1712
- const color = scale.getColor(count === 1 ? 0 : index / (count - 1));
1713
- return color ? new Color(color).toString("hex").slice(0, HEX_RRGGBB_LENGTH) : colors[colors.length - 1];
1714
- });
1304
+ const formatPolygonMeasure = (t, area, perimiter) => {
1305
+ return `S : ${formatArea(t, area)} P : ${formatLength(t, perimiter)}`;
1715
1306
  };
1716
- const getGradientColors = (colorsCount) => stretchPalette(GRADIENT_COLORS, colorsCount === undefined || colorsCount < GRADIENT_COLORS.length ? GRADIENT_COLORS.length : colorsCount);
1717
- /**
1718
- * Converts HSL hue value to RGB
1719
- * @param p - lower bound
1720
- * @param q - upper bound
1721
- * @param t - hue value
1722
- * @returns RGB component value (0-1)
1723
- */
1724
- const hue2rgb = (p, q, t) => {
1725
- if (t < 0)
1726
- t += 1;
1727
- if (t > 1)
1728
- t -= 1;
1729
- if (t < 1 / 6)
1730
- return p + (q - p) * 6 * t;
1731
- if (t < 1 / 2)
1732
- return q;
1733
- if (t < 2 / 3)
1734
- return p + (q - p) * (2 / 3 - t) * 6;
1735
- return p;
1307
+
1308
+ const geometryToEwkt = (geometry) => {
1309
+ if (!geometry) {
1310
+ return "";
1311
+ }
1312
+ const projected = toMercator({ type: "Feature", geometry, properties: {} });
1313
+ const projectedCoords = projected?.geometry?.coordinates;
1314
+ const wkt = stringify({ ...geometry, coordinates: projectedCoords });
1315
+ return `SRID=3857;${wkt}`;
1736
1316
  };
1737
- /**
1738
- * Converts RGB component (0-1) to hex string
1739
- * @param value - RGB component value (0-1)
1740
- * @returns hex string (00-ff)
1741
- */
1742
- const toHex = (value) => {
1743
- const hex = Math.round(value * 255).toString(16);
1744
- return hex.padStart(2, "0");
1317
+
1318
+ function isObject(value) {
1319
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1320
+ }
1321
+
1322
+ const isLayerService = (value) => isObject(value) && "name" in value;
1323
+
1324
+ const isNumeric = (number) => !isNaN(parseFloat(number)) && isFinite(number);
1325
+
1326
+ const metersPerPixel = (zoom, lat) => {
1327
+ return (156543.03 * Math.cos(lat * (Math.PI / 180))) / 2 ** zoom;
1745
1328
  };
1746
- /**
1747
- * Adjusts color brightness
1748
- * @param color - hex color string (e.g., "#2196f3")
1749
- * @param lightnessAdjustment - lightness adjustment in HSL units (e.g., 5 or -5)
1750
- * @returns adjusted color in hex format
1751
- */
1752
- const adjustColor = (color, lightnessAdjustment = 5) => {
1753
- // Convert hex to RGB
1754
- const hex = color.replace("#", "");
1755
- const r = parseInt(hex.substring(0, 2), 16) / 255;
1756
- const g = parseInt(hex.substring(2, 4), 16) / 255;
1757
- const b = parseInt(hex.substring(4, 6), 16) / 255;
1758
- // Convert RGB to HSL
1759
- const max = Math.max(r, g, b);
1760
- const min = Math.min(r, g, b);
1761
- let h = 0;
1762
- let s = 0;
1763
- const l = (max + min) / 2;
1764
- if (max !== min) {
1765
- const d = max - min;
1766
- s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
1767
- switch (max) {
1768
- case r:
1769
- h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
1770
- break;
1771
- case g:
1772
- h = ((b - r) / d + 2) / 6;
1773
- break;
1774
- case b:
1775
- h = ((r - g) / d + 4) / 6;
1776
- break;
1329
+
1330
+ /* eslint-disable max-lines, no-console, class-methods-use-this, @typescript-eslint/no-magic-numbers */
1331
+ class ClientStyleValidator {
1332
+ options;
1333
+ constructor(options) {
1334
+ this.options = options || {};
1335
+ }
1336
+ validate(clientStyle) {
1337
+ if (isNil(clientStyle) || isEmpty(clientStyle) || isNil(clientStyle?.items) || isEmpty(clientStyle?.items)) {
1338
+ return true;
1339
+ }
1340
+ if (clientStyle.items.some(item => isNil(item.paint))) {
1341
+ if (this.options.verbose) {
1342
+ console.error("Validate client style:", "`paint` prop is mandatory", "\n");
1343
+ }
1344
+ return false;
1345
+ }
1346
+ return clientStyle.items.every(item => Object.entries({ ...item.layout, ...item.paint }).every(([key, value]) => this.validateSpecPropValue(key, value)));
1347
+ }
1348
+ getSpecPropValueOptions(key) {
1349
+ return SPEC_PROP_VALUE_OPTIONS[key];
1350
+ }
1351
+ isHeatmapColorValid(value) {
1352
+ return (expression.isExpression(value) &&
1353
+ isEqual(value[0], "interpolate") &&
1354
+ isEqual(value[1], ["linear"]) &&
1355
+ isEqual(value[2], ["heatmap-density"]) &&
1356
+ value.length % 2 !== 0 &&
1357
+ value.length > 3 &&
1358
+ value
1359
+ .slice(3)
1360
+ .filter((_, i) => i % 2 === 0)
1361
+ .every(e => typeof e === "number") &&
1362
+ value
1363
+ .slice(3)
1364
+ .filter((_, i) => i % 2 !== 0)
1365
+ .every(e => typeof e === "string"));
1366
+ }
1367
+ isZoomInterpolate(value) {
1368
+ return Array.isArray(value) && value[0] === "interpolate" && Array.isArray(value[2]) && value[2][0] === "zoom";
1369
+ }
1370
+ validateSupportedConcatExpression(key, value) {
1371
+ if (key !== "text-field") {
1372
+ if (this.options.verbose) {
1373
+ console.error("Validate supported concat expression:", "supported only for `text-field`", key, value, "\n");
1374
+ }
1375
+ return false;
1376
+ }
1377
+ if (!expression.isExpression(value)) {
1378
+ if (this.options.verbose) {
1379
+ console.error("Validate supported concat expression:", "not an expression", key, value, "\n");
1380
+ }
1381
+ return false;
1382
+ }
1383
+ const result = value[0] === "concat" &&
1384
+ value.length > 2 &&
1385
+ value
1386
+ .slice(1)
1387
+ .every(i => typeof i === "string" || (Array.isArray(i) && i[0] === "get" && typeof i[1] === "string"));
1388
+ if (!result) {
1389
+ if (this.options.verbose) {
1390
+ console.error("Validate supported concat expression:", "invalid expression", key, value, "\n");
1391
+ }
1392
+ }
1393
+ return result;
1394
+ }
1395
+ validateSupportedMatchExpression(key, value) {
1396
+ if (!this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
1397
+ if (this.options.verbose) {
1398
+ console.error("Validate supported match expression:", "expression not supported", key, value, "\n");
1399
+ }
1400
+ return false;
1401
+ }
1402
+ if (!expression.isExpression(value)) {
1403
+ if (this.options.verbose) {
1404
+ console.error("Validate supported match expression:", "not an expression", key, value, "\n");
1405
+ }
1406
+ return false;
1407
+ }
1408
+ const result = value[0] === "match" &&
1409
+ Array.isArray(value[1]) &&
1410
+ value[1].length === 2 &&
1411
+ value[1][0] === "get" &&
1412
+ typeof value[1][1] === "string" &&
1413
+ value.length > 3 &&
1414
+ value.length % 2 !== 0 &&
1415
+ value
1416
+ .slice(2)
1417
+ .every(e => typeof e === "number" ||
1418
+ typeof e === "string" ||
1419
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
1420
+ if (!result) {
1421
+ if (this.options.verbose) {
1422
+ console.error("Validate supported match expression:", "invalid expression", key, value, "\n");
1423
+ }
1777
1424
  }
1425
+ return result;
1778
1426
  }
1779
- const adjustedL = Math.max(0, Math.min(100, (l * 100) + lightnessAdjustment)) / 100;
1780
- // Convert HSL back to RGB
1781
- let rNew;
1782
- let gNew;
1783
- let bNew;
1784
- if (s === 0) {
1785
- rNew = gNew = bNew = adjustedL;
1427
+ validateSupportedCaseExpression(key, value) {
1428
+ if (!this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
1429
+ if (this.options.verbose) {
1430
+ console.error("Validate supported case expression:", "expression not supported", key, value, "\n");
1431
+ }
1432
+ return false;
1433
+ }
1434
+ if (!expression.isExpression(value)) {
1435
+ if (this.options.verbose) {
1436
+ console.error("Validate supported case expression:", "not an expression", key, value, "\n");
1437
+ }
1438
+ return false;
1439
+ }
1440
+ const result = value[0] === "case" &&
1441
+ value.length > 3 &&
1442
+ value.length % 2 === 0 &&
1443
+ value
1444
+ .slice(1)
1445
+ .filter((_, i) => i % 2 === 0 && i < value.slice(1).length - 1)
1446
+ .every(e => Array.isArray(e) &&
1447
+ e[0] === "all" &&
1448
+ e.length > 1 &&
1449
+ e
1450
+ .slice(1)
1451
+ .every(ce => Array.isArray(ce) &&
1452
+ ce.length === 3 &&
1453
+ [">=", ">", "<", "<="].includes(ce[0]) &&
1454
+ ce[1][0] === "get" &&
1455
+ typeof ce[1][1] === "string" &&
1456
+ typeof ce[2] === "number")) &&
1457
+ value
1458
+ .slice(1)
1459
+ .filter((_, i) => i % 2 !== 0)
1460
+ .every(e => typeof e === "number" ||
1461
+ typeof e === "string" ||
1462
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e))) &&
1463
+ (typeof value[value.slice(1).length - 1] === "number" ||
1464
+ typeof value[value.slice(1).length - 1] === "string" ||
1465
+ (key === "text-field" && this.validateSupportedConcatExpression(key, value)));
1466
+ if (!result) {
1467
+ if (this.options.verbose) {
1468
+ console.error("Validate supported case expression:", "invalid expression", key, value, "\n");
1469
+ }
1470
+ }
1471
+ return result;
1786
1472
  }
1787
- else {
1788
- const q = adjustedL < 0.5 ? adjustedL * (1 + s) : adjustedL + s - adjustedL * s;
1789
- const p = 2 * adjustedL - q;
1790
- rNew = hue2rgb(p, q, h + 1 / 3);
1791
- gNew = hue2rgb(p, q, h);
1792
- bNew = hue2rgb(p, q, h - 1 / 3);
1473
+ validateSupportedStepExpression(key, value) {
1474
+ if (!this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
1475
+ if (this.options.verbose) {
1476
+ console.error("Validate supported step expression:", "expression not supported", key, value, "\n");
1477
+ }
1478
+ return false;
1479
+ }
1480
+ if (!expression.isExpression(value)) {
1481
+ if (this.options.verbose) {
1482
+ console.error("Validate supported step expression:", "not an expression", key, value, "\n");
1483
+ }
1484
+ return false;
1485
+ }
1486
+ const result = value[0] === "step" &&
1487
+ Array.isArray(value[1]) &&
1488
+ value[1].length === 2 &&
1489
+ value[1][0] === "get" &&
1490
+ typeof value[1][1] === "string" &&
1491
+ value.length > 3 &&
1492
+ value.length % 2 !== 0 &&
1493
+ value
1494
+ .slice(2)
1495
+ .filter((_, i) => i % 2 === 0)
1496
+ .every(e => typeof e === "number" ||
1497
+ typeof e === "string" ||
1498
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e))) &&
1499
+ value
1500
+ .slice(2)
1501
+ .filter((_, i) => i % 2 !== 0)
1502
+ .every(e => typeof e === "number");
1503
+ if (!result) {
1504
+ if (this.options.verbose) {
1505
+ console.error("Validate supported step expression:", "invalid expression", key, value, "\n");
1506
+ }
1507
+ }
1508
+ return result;
1793
1509
  }
1794
- return `#${toHex(rNew)}${toHex(gNew)}${toHex(bNew)}`;
1795
- };
1796
- const OPAQUE_ALPHA = "ff";
1797
- /**
1798
- * Цвет в hex: `#rrggbb`, а при неполной непрозрачности — `#rrggbbaa`.
1799
- *
1800
- * Полностью непрозрачная альфа отбрасывается: в значении она ничего не уточняет, а строку
1801
- * удлиняет — и в конфиге, и в данных удобнее короткая запись.
1802
- */
1803
- const colorToHex = (color) => {
1804
- const hex = color.toString("hex");
1805
- return hex.slice(HEX_RRGGBB_LENGTH).toLowerCase() === OPAQUE_ALPHA ? hex.slice(0, HEX_RRGGBB_LENGTH) : hex;
1806
- };
1807
-
1808
- const NO_CONTENT_VALUE = "—";
1809
- var DateFormat;
1810
- (function (DateFormat) {
1811
- DateFormat["ClientDefaultFormat"] = "dd.MM.yyyy HH:mm";
1812
- DateFormat["DateTime"] = "dd.MM.yyyy HH:mm:ss";
1813
- DateFormat["UTC"] = "yyyy-MM-dd'T'HH:mm:ss.sssxxx";
1814
- DateFormat["AxisTooltip"] = "d MMMM yyyy";
1815
- })(DateFormat || (DateFormat = {}));
1816
- const stringDateParsers = [parseJSON, parseISO, rawDate => new Date(rawDate)];
1817
- const getDate = (rawDate) => {
1818
- if (!rawDate) {
1819
- return null;
1510
+ validateLinearZoomInterpolate(key, value) {
1511
+ return (this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
1512
+ isEqual(value[0], "interpolate") &&
1513
+ isEqual(value[1], ["linear"]) &&
1514
+ isEqual(value[2], ["zoom"]) &&
1515
+ value.length % 2 !== 0 &&
1516
+ value.length > 4 &&
1517
+ value
1518
+ .slice(3)
1519
+ .filter((_, i) => i % 2 === 0)
1520
+ .every(e => typeof e === "number") &&
1521
+ value
1522
+ .slice(3)
1523
+ .filter((_, i) => i % 2 !== 0)
1524
+ .every(e => {
1525
+ return (typeof e === "number" ||
1526
+ typeof e === "string" ||
1527
+ this.validateSupportedExpression(key, e, true) ||
1528
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
1529
+ }));
1530
+ }
1531
+ validateExponentialZoomInterpolate(key, value) {
1532
+ return (this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
1533
+ isEqual(value[0], "interpolate") &&
1534
+ Array.isArray(value[1]) &&
1535
+ value[1].length === 2 &&
1536
+ value[1][0] === "exponential" &&
1537
+ typeof value[1][1] === "number" &&
1538
+ isEqual(value[2], ["zoom"]) &&
1539
+ value.length % 2 !== 0 &&
1540
+ value.length > 4 &&
1541
+ value
1542
+ .slice(3)
1543
+ .filter((_, i) => i % 2 === 0)
1544
+ .every(e => typeof e === "number") &&
1545
+ value
1546
+ .slice(3)
1547
+ .filter((_, i) => i % 2 !== 0)
1548
+ .every(e => {
1549
+ return (typeof e === "number" ||
1550
+ typeof e === "string" ||
1551
+ this.validateSupportedExpression(key, e, true) ||
1552
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
1553
+ }));
1554
+ }
1555
+ validateCubicBezierZoomInterpolate(key, value) {
1556
+ return (this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
1557
+ isEqual(value[0], "interpolate") &&
1558
+ Array.isArray(value[1]) &&
1559
+ value[1].length === 5 &&
1560
+ value[1][0] === "cubic-bezier" &&
1561
+ value[1].slice(1).every(e => typeof e === "number") &&
1562
+ isEqual(value[2], ["zoom"]) &&
1563
+ value.length % 2 !== 0 &&
1564
+ value.length > 4 &&
1565
+ value
1566
+ .slice(3)
1567
+ .filter((_, i) => i % 2 === 0)
1568
+ .every(e => typeof e === "number") &&
1569
+ value
1570
+ .slice(3)
1571
+ .filter((_, i) => i % 2 !== 0)
1572
+ .every(e => {
1573
+ return (typeof e === "number" ||
1574
+ typeof e === "string" ||
1575
+ this.validateSupportedExpression(key, e, true) ||
1576
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e)));
1577
+ }));
1578
+ }
1579
+ validateLinearDataInterpolate(key, value) {
1580
+ return (this.getSpecPropValueOptions(key)?.dataExpressionSupport &&
1581
+ isEqual(value[0], "interpolate") &&
1582
+ isEqual(value[1], ["linear"]) &&
1583
+ Array.isArray(value[2]) &&
1584
+ value[2].length === 2 &&
1585
+ value[2][0] === "get" &&
1586
+ typeof value[2][1] === "string" &&
1587
+ value.length % 2 !== 0 &&
1588
+ value.length > 4 &&
1589
+ value
1590
+ .slice(3)
1591
+ .filter((_, i) => i % 2 === 0)
1592
+ .every(e => typeof e === "number") &&
1593
+ value
1594
+ .slice(3)
1595
+ .filter((_, i) => i % 2 !== 0)
1596
+ .every(e => typeof e === "number" ||
1597
+ typeof e === "string" ||
1598
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e))));
1599
+ }
1600
+ validateExponentialDataInterpolate(key, value) {
1601
+ return (this.getSpecPropValueOptions(key)?.dataExpressionSupport &&
1602
+ isEqual(value[0], "interpolate") &&
1603
+ Array.isArray(value[1]) &&
1604
+ value[1].length === 2 &&
1605
+ value[1][0] === "exponential" &&
1606
+ typeof value[1][1] === "number" &&
1607
+ Array.isArray(value[2]) &&
1608
+ value[2].length === 2 &&
1609
+ value[2][0] === "get" &&
1610
+ typeof value[2][1] === "string" &&
1611
+ value.length % 2 !== 0 &&
1612
+ value.length > 4 &&
1613
+ value
1614
+ .slice(3)
1615
+ .filter((_, i) => i % 2 === 0)
1616
+ .every(e => typeof e === "number") &&
1617
+ value
1618
+ .slice(3)
1619
+ .filter((_, i) => i % 2 !== 0)
1620
+ .every(e => typeof e === "number" ||
1621
+ typeof e === "string" ||
1622
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e))));
1623
+ }
1624
+ validateCubicBezierDataInterpolate(key, value) {
1625
+ return (this.getSpecPropValueOptions(key)?.dataExpressionSupport &&
1626
+ isEqual(value[0], "interpolate") &&
1627
+ Array.isArray(value[1]) &&
1628
+ value[1].length === 5 &&
1629
+ value[1][0] === "cubic-bezier" &&
1630
+ value[1].slice(1).every(e => typeof e === "number") &&
1631
+ Array.isArray(value[2]) &&
1632
+ value[2].length === 2 &&
1633
+ value[2][0] === "get" &&
1634
+ typeof value[2][1] === "string" &&
1635
+ value.length % 2 !== 0 &&
1636
+ value.length > 4 &&
1637
+ value
1638
+ .slice(3)
1639
+ .filter((_, i) => i % 2 === 0)
1640
+ .every(e => typeof e === "number") &&
1641
+ value
1642
+ .slice(3)
1643
+ .filter((_, i) => i % 2 !== 0)
1644
+ .every(e => typeof e === "number" ||
1645
+ typeof e === "string" ||
1646
+ (key === "text-field" && this.validateSupportedConcatExpression(key, e))));
1820
1647
  }
1821
- if (typeof rawDate === "string") {
1822
- for (const parser of stringDateParsers) {
1823
- const date = parser(rawDate);
1824
- if (isValid(date)) {
1825
- return toDate(date);
1648
+ validateZoomInterpolate(key, value) {
1649
+ return (this.validateLinearZoomInterpolate(key, value) ||
1650
+ this.validateExponentialZoomInterpolate(key, value) ||
1651
+ this.validateCubicBezierZoomInterpolate(key, value));
1652
+ }
1653
+ validateDataInterpolate(key, value) {
1654
+ return (this.validateLinearDataInterpolate(key, value) ||
1655
+ this.validateExponentialDataInterpolate(key, value) ||
1656
+ this.validateCubicBezierDataInterpolate(key, value));
1657
+ }
1658
+ validateSupportedInterpolateExpression(key, value, excludeZoomInterpolate) {
1659
+ if (!expression.isExpression(value)) {
1660
+ if (this.options.verbose) {
1661
+ console.error("Validate supported interpolate expression:", "not an expression", key, value, "\n");
1826
1662
  }
1663
+ return false;
1827
1664
  }
1828
- return null;
1665
+ if (key === "heatmap-color") {
1666
+ const isColorValid = this.isHeatmapColorValid(value);
1667
+ if (!isColorValid) {
1668
+ if (this.options.verbose) {
1669
+ console.error("Validate supported interpolate expression:", "invalid color value", key, value, "\n");
1670
+ }
1671
+ }
1672
+ return this.isHeatmapColorValid(value);
1673
+ }
1674
+ if (!this.getSpecPropValueOptions(key)?.interpolateExpressionSupport &&
1675
+ !this.getSpecPropValueOptions(key)?.dataExpressionSupport) {
1676
+ if (this.options.verbose) {
1677
+ console.error("Validate supported interpolate expression:", "interpolate not supported", key, value, "\n");
1678
+ }
1679
+ }
1680
+ const result = (!excludeZoomInterpolate && this.validateZoomInterpolate(key, value)) || this.validateDataInterpolate(key, value);
1681
+ if (!result) {
1682
+ if (this.options.verbose) {
1683
+ console.error("Validate supported interpolate expression:", "invalid expression", key, value, "\n");
1684
+ }
1685
+ }
1686
+ return result;
1829
1687
  }
1830
- const parsedDate = toDate(rawDate);
1831
- return isValid(parsedDate) ? parsedDate : null;
1832
- };
1833
- const formatDate$1 = (date, { dateFormat = DateFormat.ClientDefaultFormat, defaultValue = NO_CONTENT_VALUE } = {}) => {
1834
- const dateValue = date ? getDate(date) : null;
1835
- if (isValid(dateValue)) {
1836
- return format(dateValue, dateFormat);
1688
+ validateSupportedExpression(key, value, excludeZoomInterpolate) {
1689
+ if (!expression.isExpression(value)) {
1690
+ if (this.options.verbose) {
1691
+ console.error("Validate supported expression:", "not an expression", key, value, "\n");
1692
+ }
1693
+ return false;
1694
+ }
1695
+ const expressionType = value[0];
1696
+ if (typeof expressionType !== "string" ||
1697
+ !["match", "case", "step", "interpolate", "concat"].includes(expressionType)) {
1698
+ if (this.options.verbose) {
1699
+ console.error("Validate supported expression:", "expression type not supported", key, value, "\n");
1700
+ }
1701
+ return false;
1702
+ }
1703
+ switch (expressionType) {
1704
+ case "match":
1705
+ return this.validateSupportedMatchExpression(key, value);
1706
+ case "case":
1707
+ return this.validateSupportedCaseExpression(key, value);
1708
+ case "step":
1709
+ return this.validateSupportedStepExpression(key, value);
1710
+ case "concat":
1711
+ return this.validateSupportedConcatExpression(key, value);
1712
+ case "interpolate":
1713
+ return this.validateSupportedInterpolateExpression(key, value, excludeZoomInterpolate);
1714
+ default:
1715
+ return false;
1716
+ }
1837
1717
  }
1838
- return `${defaultValue}`;
1839
- };
1840
-
1841
- const debounce = (callback, delay) => {
1842
- let timeId;
1843
- return (...args) => {
1844
- if (timeId) {
1845
- window.clearTimeout(timeId);
1718
+ validateTransitionValue(key, value) {
1719
+ const propValueOptions = this.getSpecPropValueOptions(key.replace(/-transition$/, ""));
1720
+ if (propValueOptions && propValueOptions.transitionable === false) {
1721
+ if (this.options.verbose) {
1722
+ console.error("Validate transition value:", "transition not supported", key, value, "\n");
1723
+ }
1724
+ return false;
1846
1725
  }
1847
- timeId = window.setTimeout(() => {
1848
- callback(...args);
1849
- }, delay);
1850
- };
1851
- };
1852
-
1853
- const MILLION = 1000000;
1854
- const TEN_THOUSANDS = 10000;
1855
- const THOUSAND = 1000;
1856
- const COMPACT_FRACTION_DIGITS = 1;
1857
- const roundTotalSum = (value, fractionDigits) => {
1858
- if (!value)
1859
- return "";
1860
- const digits = fractionDigits ?? COMPACT_FRACTION_DIGITS;
1861
- if (value >= MILLION) {
1862
- return `${(value / MILLION).toFixed(digits)}M`;
1726
+ const result = isObject(value) &&
1727
+ (("delay" in value && typeof value.delay === "number") ||
1728
+ ("duration" in value && typeof value.duration === "number"));
1729
+ if (!result) {
1730
+ if (this.options.verbose) {
1731
+ console.error("Validate transition value:", "invalid transition value", key, value, "\n");
1732
+ }
1733
+ }
1734
+ return result;
1863
1735
  }
1864
- if (value >= TEN_THOUSANDS) {
1865
- return `${(value / THOUSAND).toFixed(digits)}K`;
1736
+ validateSpecPropValue(key, value) {
1737
+ if (key.endsWith("-transition")) {
1738
+ return this.validateTransitionValue(key, value);
1739
+ }
1740
+ const propValueOptions = this.getSpecPropValueOptions(key);
1741
+ if (!propValueOptions) {
1742
+ return (typeof value === "string" ||
1743
+ typeof value === "number" ||
1744
+ typeof value === "boolean" ||
1745
+ (Array.isArray(value) && value.every(item => typeof item === "number")) ||
1746
+ (Array.isArray(value) && value.every(item => typeof item === "string")) ||
1747
+ expression.isExpression(value));
1748
+ }
1749
+ if (propValueOptions.arrayValue) {
1750
+ return (typeof value === propValueOptions.valueTypeAllowed ||
1751
+ (Array.isArray(value) && value.every(item => typeof item === propValueOptions.valueTypeAllowed)) ||
1752
+ this.validateSupportedExpression(key, value));
1753
+ }
1754
+ return typeof value === propValueOptions.valueTypeAllowed || this.validateSupportedExpression(key, value);
1866
1755
  }
1867
- return value;
1868
- };
1756
+ }
1869
1757
 
1870
- const TIME_ZONE_FORMAT = ' "GMT"z'; // eslint-disable-line
1871
- var ScalingFactor;
1872
- (function (ScalingFactor) {
1873
- ScalingFactor[ScalingFactor["Default"] = 1] = "Default";
1874
- ScalingFactor[ScalingFactor["Thousands"] = 0.001] = "Thousands";
1875
- ScalingFactor[ScalingFactor["Millions"] = 0.000001] = "Millions";
1876
- ScalingFactor[ScalingFactor["Acres"] = 0.01] = "Acres";
1877
- ScalingFactor[ScalingFactor["Hectares"] = 0.0001] = "Hectares";
1878
- })(ScalingFactor || (ScalingFactor = {}));
1879
- const formatDate = (str, isRuLocale) => format(Date.now(), str, { locale: isRuLocale ? ru : enUS });
1880
- const timeOptions = [
1881
- {
1882
- text: formatDate("kk:mm:ss"),
1883
- value: "hh:mm:ss",
1884
- },
1885
- {
1886
- text: formatDate("hh:mm:ss aa"),
1887
- value: "hh:mm:ss tt",
1888
- },
1889
- {
1890
- text: formatDate("kk:mm"),
1891
- value: "hh:mm",
1892
- },
1893
- {
1894
- text: formatDate("hh:mm aa"),
1895
- value: "hh:mm tt",
1896
- },
1897
- ];
1898
- const dateOptions = [
1899
- {
1900
- text: formatDate("dd.MM.yyyy"),
1901
- value: "dd.MM.yyyy",
1902
- },
1903
- {
1904
- text: formatDate("dd MMMM yyyy", true),
1905
- value: "dd MMMM yyyy",
1906
- },
1907
- {
1908
- text: formatDate("yyyy, dd MMMM", true),
1909
- value: "yyyy, dd MMMM",
1910
- },
1911
- ];
1912
- const pointOptions = [
1913
- {
1914
- value: "default",
1915
- localizationKey: "defaultValue",
1916
- },
1917
- {
1918
- value: "DD MM SS",
1919
- localizationKey: "degreesMinutesSeconds",
1920
- },
1921
- {
1922
- value: "DD.",
1923
- localizationKey: "decimalDegrees",
1924
- },
1925
- ];
1926
- const numberOptions = [
1927
- {
1928
- value: ScalingFactor.Default.toString(),
1929
- localizationKey: "defaultValue",
1930
- },
1931
- {
1932
- value: ScalingFactor.Thousands.toString(),
1933
- localizationKey: "inThousands",
1934
- },
1935
- {
1936
- value: ScalingFactor.Millions.toString(),
1937
- localizationKey: "inMillions",
1938
- },
1939
- {
1940
- value: ScalingFactor.Acres.toString(),
1941
- localizationKey: "inAcres",
1942
- },
1943
- {
1944
- value: ScalingFactor.Hectares.toString(),
1945
- localizationKey: "inHectares",
1946
- },
1947
- ];
1948
- const convertDDToDMS = (value) => {
1949
- const absolute = Math.abs(value);
1950
- const degrees = Math.floor(absolute);
1951
- const minutesNotTruncated = (absolute - degrees) * 60;
1952
- const minutes = Math.floor(minutesNotTruncated);
1953
- const seconds = Math.floor((minutesNotTruncated - minutes) * 60);
1954
- return `${degrees}° ${minutes}' ${seconds}"`;
1955
- };
1956
- const formatPointValue = ({ t, stringFormat, value }) => {
1957
- if (stringFormat.format === pointOptions[1].value) {
1958
- const lon = value[1];
1959
- const lat = value[0];
1960
- const lonDirection = lon >= 0 ? t("east", { ns: "common" }) : t("west", { ns: "common" });
1961
- const latDirection = lat >= 0 ? t("north", { ns: "common" }) : t("south", { ns: "common" });
1962
- return `${convertDDToDMS(lon)} ${lonDirection}, ${convertDDToDMS(lat)} ${latDirection}`;
1758
+ const enrichStyleItemsWithIds = (style) => {
1759
+ return {
1760
+ ...style,
1761
+ items: style.items.map(item => {
1762
+ return {
1763
+ ...item,
1764
+ id: item.id || v4(),
1765
+ };
1766
+ }),
1767
+ };
1768
+ };
1769
+
1770
+ /** Стабильный ID элемента стиля для MapLibre, в том числе когда `item.id` не задан. */
1771
+ const getClientStyleItemId = (items, index) => {
1772
+ const explicitId = items[index]?.id;
1773
+ if (explicitId) {
1774
+ return explicitId;
1963
1775
  }
1964
- if (stringFormat.format.includes("DD.") && value.length) {
1965
- const rounding = stringFormat.format.replace("DD.", "").length;
1966
- return `${value[0].toFixed(rounding)}, ${value[1].toFixed(rounding)}`;
1776
+ const explicitIds = new Set(items.map(item => item.id).filter(Boolean));
1777
+ let generatedId = `__item_${index}`;
1778
+ while (explicitIds.has(generatedId)) {
1779
+ generatedId = `_${generatedId}`;
1967
1780
  }
1968
- return null;
1781
+ return generatedId;
1969
1782
  };
1970
- const getValueFromOptions = (options, format) => options.find(({ value }) => format && format.includes(value));
1971
- const numberWithSpaces = (input, precision) => {
1972
- if (input === null || input === undefined) {
1973
- return "";
1974
- }
1975
- return parseFloat((typeof input === "string" ? parseFloat(input) : input).toString()).toLocaleString("ru-RU", {
1976
- maximumFractionDigits: precision ?? 10,
1977
- });
1783
+
1784
+ const enrichStyleModelsWithIds = (style) => {
1785
+ return {
1786
+ ...style,
1787
+ models: style.models.map(model => {
1788
+ return {
1789
+ ...model,
1790
+ id: model.id || v4(),
1791
+ };
1792
+ }),
1793
+ };
1978
1794
  };
1979
- const formatDateValue = (stringFormat, dateValue) => {
1980
- let value = dateValue;
1981
- if (typeof value === "string") {
1982
- value = new Date(value).getTime();
1795
+
1796
+ const findAttributeInExpression = (expression) => {
1797
+ if (Array.isArray(expression) && expression.length === 2 && expression[0] === "get") {
1798
+ return [expression[1]];
1983
1799
  }
1984
- const isRuLocale = stringFormat.culture && stringFormat.culture === "ru-RU";
1985
- const showTimeZone = stringFormat.format.includes(TIME_ZONE_FORMAT);
1986
- const dateOption = getValueFromOptions(dateOptions, stringFormat.format);
1987
- const dateOptionValue = dateOption && dateOption.value;
1988
- const dateFormat = value && dateOptionValue
1989
- ? format(value, dateOptionValue, {
1990
- locale: ru,
1991
- })
1992
- : "";
1993
- const timeOption = getValueFromOptions(timeOptions, stringFormat.format);
1994
- const timeOptionValue = timeOption && (isRuLocale ? timeOption.value : `${timeOption.value} aa`);
1995
- const timeFormat = (timeOptionValue && format(value, showTimeZone ? `${timeOptionValue} zz` : timeOptionValue)) || "";
1996
- return dateFormat ? [dateFormat, timeFormat].filter(Boolean).join(" ") : "";
1800
+ return expression.reduce((acc, curr) => {
1801
+ if (!Array.isArray(curr)) {
1802
+ return acc;
1803
+ }
1804
+ if (curr[0] === "get") {
1805
+ return [...new Set([...acc, curr[1]])];
1806
+ }
1807
+ return [...new Set([...acc, ...findAttributeInExpression(curr)])];
1808
+ }, []);
1997
1809
  };
1998
- const appendUnitsLabel = (value, unitsLabel, noUnits) => (unitsLabel && !noUnits ? `${value} ${unitsLabel}` : value)?.toString() || "";
1999
- const formatNumberValue = (stringFormat, value, type, noUnits = false) => {
2000
- const { scalingFactor, rounding, splitDigitGroup, roundDigitGroup, unitsLabel } = stringFormat || {};
2001
- const isIntValue = [AttributeType.Int32, AttributeType.Int64].includes(type);
2002
- const isDefaultScaling = stringFormat && stringFormat.scalingFactor === +numberOptions[0].value;
2003
- let currentValue = value;
2004
- if (isIntValue && isDefaultScaling && currentValue) {
2005
- currentValue = parseInt(currentValue.toString(), 10);
2006
- }
2007
- if (scalingFactor) {
2008
- currentValue *= scalingFactor;
2009
- }
2010
- const hasRounding = !isNil(rounding);
2011
- const compactValue = roundDigitGroup
2012
- ? roundTotalSum(Number(currentValue), hasRounding ? rounding : undefined)
2013
- : null;
2014
- if (typeof compactValue === "string" && compactValue) {
2015
- return appendUnitsLabel(compactValue, unitsLabel, noUnits);
2016
- }
2017
- if (hasRounding && (!isIntValue || !isDefaultScaling) && !isNil(currentValue)) {
2018
- currentValue = Number(currentValue).toFixed(rounding);
2019
- }
2020
- if (splitDigitGroup) {
2021
- currentValue = numberWithSpaces(currentValue);
1810
+
1811
+ const getActualExtrusionHeight = (paint) => {
1812
+ return Array.isArray(paint?.["fill-extrusion-height"]) && paint?.["fill-extrusion-height"][0] === "+"
1813
+ ? paint?.["fill-extrusion-height"][1]
1814
+ : paint?.["fill-extrusion-height"];
1815
+ };
1816
+
1817
+ const getLayerClientStyle = (layer) => {
1818
+ const clientStyle = layer?.configuration?.clientStyle;
1819
+ return {
1820
+ ...clientStyle,
1821
+ items: clientStyle?.items ?? [],
1822
+ };
1823
+ };
1824
+
1825
+ const extractAttributesFromObject = (obj) => {
1826
+ if (!obj || isEmpty(obj)) {
1827
+ return [];
2022
1828
  }
2023
- if (currentValue) {
2024
- currentValue = currentValue.toString().replace(".", ",");
1829
+ return Object.entries(obj).reduce((acc, [, value]) => {
1830
+ if (!Array.isArray(value)) {
1831
+ return acc;
1832
+ }
1833
+ return [...new Set([...acc, ...findAttributeInExpression(value)])];
1834
+ }, []);
1835
+ };
1836
+ const getStyleAttributes = (style) => {
1837
+ if (!style) {
1838
+ return [];
2025
1839
  }
2026
- return appendUnitsLabel(currentValue, unitsLabel, noUnits);
1840
+ return style?.items?.reduce((acc, curr) => {
1841
+ const paintAttributes = extractAttributesFromObject(curr.paint);
1842
+ const layoutAttributes = extractAttributesFromObject(curr.layout);
1843
+ const filterAttributes = curr.filter
1844
+ ? findAttributeInExpression(curr.filter)
1845
+ : [];
1846
+ return [...new Set([...acc, ...paintAttributes, ...layoutAttributes, ...filterAttributes])];
1847
+ }, []);
1848
+ };
1849
+
1850
+ const DEFAULT_COLOR = "#00ffff";
1851
+ const DEFAULT_BLUR = 0;
1852
+ const DEFAULT_OPACITY = 0.5;
1853
+ const DEFAULT_TRANSLATE = [0, 0];
1854
+ const DEFAULT_FILL_EXTRUSION_BASE = 0;
1855
+ const DEFAULT_FILL_EXTRUSION_VERTICAL_GRADIENT = true;
1856
+ const DEFAULT_FILL_EXTRUSION_HEIGHT = 0;
1857
+ const DEFAULT_CIRCLE_RADIUS = 4;
1858
+ const DEFAULT_CIRCLE_STROKE_WIDTH = 0;
1859
+ const DEFAULT_LINE_WIDTH = 1;
1860
+ const DEFAULT_LINE_CAP = "butt";
1861
+ const DEFAULT_LINE_JOIN = "miter";
1862
+ const DEFAULT_SYMBOL_COLOR = "#000000";
1863
+ const DEFAULT_SYMBOL_HALO_COLOR = "#ffffff";
1864
+ const DEFAULT_SYMBOL_PLACEMENT = "point";
1865
+ const DEFAULT_SYMBOL_SPACING = 250;
1866
+ const DEFAULT_ICON_OVERLAP = "never";
1867
+ const DEFAULT_ICON_SIZE = 0.5;
1868
+ const DEFAULT_ICON_ANCHOR = "center";
1869
+ const DEFAULT_ICON_PADDING = [2];
1870
+ const DEFAULT_ICON_ROTATE = 0;
1871
+ const DEFAULT_TEXT_SIZE = 16;
1872
+ const DEFAULT_TEXT_ANCHOR = "center";
1873
+ const DEFAULT_TEXT_JUSTIFY = "center";
1874
+ const DEFAULT_TEXT_TRANSFORM = "none";
1875
+ const DEFAULT_HEATMAP_RADIUS = 30;
1876
+ const DEFAULT_HEATMAP_WEIGHT = 1;
1877
+ const DEFAULT_HEATMAP_INTENSITY = 1;
1878
+ const DEFAULT_HEATMAP_COLOR = [
1879
+ "interpolate",
1880
+ ["linear"],
1881
+ ["heatmap-density"],
1882
+ 0, "rgba(0, 0, 255, 0)",
1883
+ 0.1, "royalblue",
1884
+ 0.3, "cyan",
1885
+ 0.5, "lime",
1886
+ 0.7, "yellow",
1887
+ 1, "red",
1888
+ ];
1889
+ const DEFAULT_FILL_STYLE = {
1890
+ items: [
1891
+ {
1892
+ type: "fill",
1893
+ layout: {},
1894
+ paint: {
1895
+ "fill-color": DEFAULT_COLOR,
1896
+ "fill-opacity": DEFAULT_OPACITY,
1897
+ },
1898
+ },
1899
+ ],
1900
+ };
1901
+ const DEFAULT_FILL_EXTRUSION_STYLE = {
1902
+ items: [
1903
+ {
1904
+ type: "fill-extrusion",
1905
+ layout: {},
1906
+ paint: {
1907
+ "fill-extrusion-base": DEFAULT_FILL_EXTRUSION_BASE,
1908
+ "fill-extrusion-vertical-gradient": DEFAULT_FILL_EXTRUSION_VERTICAL_GRADIENT,
1909
+ "fill-extrusion-color": DEFAULT_COLOR,
1910
+ "fill-extrusion-opacity": DEFAULT_OPACITY,
1911
+ "fill-extrusion-height": DEFAULT_FILL_EXTRUSION_HEIGHT,
1912
+ },
1913
+ },
1914
+ ],
1915
+ };
1916
+ const DEFAULT_LINE_STYLE = {
1917
+ items: [
1918
+ {
1919
+ type: "line",
1920
+ layout: {
1921
+ "line-cap": DEFAULT_LINE_CAP,
1922
+ "line-join": DEFAULT_LINE_JOIN,
1923
+ },
1924
+ paint: {
1925
+ "line-color": DEFAULT_COLOR,
1926
+ "line-width": DEFAULT_LINE_WIDTH,
1927
+ "line-blur": DEFAULT_BLUR,
1928
+ "line-opacity": DEFAULT_OPACITY,
1929
+ "line-translate": DEFAULT_TRANSLATE,
1930
+ },
1931
+ },
1932
+ ],
1933
+ };
1934
+ const DEFAULT_CIRCLE_STYLE = {
1935
+ items: [
1936
+ {
1937
+ type: "circle",
1938
+ layout: {},
1939
+ paint: {
1940
+ "circle-radius": DEFAULT_CIRCLE_RADIUS,
1941
+ "circle-color": DEFAULT_COLOR,
1942
+ "circle-blur": DEFAULT_BLUR,
1943
+ "circle-opacity": DEFAULT_OPACITY,
1944
+ "circle-translate": DEFAULT_TRANSLATE,
1945
+ "circle-stroke-width": DEFAULT_CIRCLE_STROKE_WIDTH,
1946
+ "circle-stroke-color": DEFAULT_COLOR,
1947
+ "circle-stroke-opacity": DEFAULT_OPACITY,
1948
+ },
1949
+ },
1950
+ ],
1951
+ };
1952
+ const DEFAULT_SYMBOL_STYLE = {
1953
+ items: [
1954
+ {
1955
+ type: "symbol",
1956
+ layout: {
1957
+ "symbol-placement": DEFAULT_SYMBOL_PLACEMENT,
1958
+ "symbol-spacing": DEFAULT_SYMBOL_SPACING,
1959
+ "icon-overlap": DEFAULT_ICON_OVERLAP,
1960
+ "icon-size": DEFAULT_ICON_SIZE,
1961
+ "icon-anchor": DEFAULT_ICON_ANCHOR,
1962
+ "icon-padding": DEFAULT_ICON_PADDING,
1963
+ "icon-rotate": DEFAULT_ICON_ROTATE,
1964
+ "text-size": DEFAULT_TEXT_SIZE,
1965
+ "text-anchor": DEFAULT_TEXT_ANCHOR,
1966
+ "text-justify": DEFAULT_TEXT_JUSTIFY,
1967
+ "text-transform": DEFAULT_TEXT_TRANSFORM,
1968
+ },
1969
+ paint: {
1970
+ "icon-color": DEFAULT_SYMBOL_COLOR,
1971
+ "icon-halo-color": DEFAULT_SYMBOL_HALO_COLOR,
1972
+ "icon-opacity": DEFAULT_OPACITY,
1973
+ "text-color": DEFAULT_SYMBOL_COLOR,
1974
+ "text-halo-color": DEFAULT_SYMBOL_HALO_COLOR,
1975
+ "text-opacity": DEFAULT_OPACITY,
1976
+ },
1977
+ },
1978
+ ],
2027
1979
  };
2028
- const formatAttributeValue = ({ t, type, value, stringFormat, noUnits = false }) => {
2029
- const isNilValue = isNil(value);
2030
- if (type === AttributeType.Point) {
2031
- if (!stringFormat?.format || isNilValue) {
2032
- return null;
2033
- }
2034
- return formatPointValue({ t, stringFormat, value: value?.coordinates });
2035
- }
2036
- if (type === AttributeType.DateTime) {
2037
- if (isNilValue) {
2038
- return null;
2039
- }
2040
- if (!stringFormat?.format) {
2041
- return value;
2042
- }
2043
- return formatDateValue(stringFormat, value);
2044
- }
2045
- if ([
2046
- AttributeType.Int32,
2047
- AttributeType.Int64,
2048
- AttributeType.Double,
2049
- AttributeType.Polygon,
2050
- AttributeType.LineString,
2051
- AttributeType.MultiPoint,
2052
- AttributeType.MultiPolygon,
2053
- AttributeType.MultiLineString,
2054
- ].includes(type) &&
2055
- !isNaN(value)) {
2056
- if (!stringFormat && !isNilValue) {
2057
- return value.toString();
2058
- }
2059
- return formatNumberValue(stringFormat, value, type, noUnits);
1980
+ const DEFAULT_HEATMAP_STYLE = {
1981
+ items: [
1982
+ {
1983
+ type: "heatmap",
1984
+ layout: {},
1985
+ paint: {
1986
+ "heatmap-radius": DEFAULT_HEATMAP_RADIUS,
1987
+ "heatmap-weight": DEFAULT_HEATMAP_WEIGHT,
1988
+ "heatmap-intensity": DEFAULT_HEATMAP_INTENSITY,
1989
+ "heatmap-color": DEFAULT_HEATMAP_COLOR,
1990
+ "heatmap-opacity": DEFAULT_OPACITY,
1991
+ },
1992
+ },
1993
+ ],
1994
+ };
1995
+
1996
+ /**
1997
+ * Извлекает имена иконок из выражения icon-image.
1998
+ *
1999
+ * Поддерживает:
2000
+ * - Строки: "parking" → ["parking"]
2001
+ * - match: ["match", ["get", "type"], "a", "icon-a", "b", "icon-b", "default"] → ["icon-a", "icon-b", "default"]
2002
+ * - case: ["case", [...], "icon-a", "icon-b"] → ["icon-a", "icon-b"]
2003
+ * - coalesce: ["coalesce", ["image", "icon-a"], ["image", "icon-b"]] → ["icon-a", "icon-b"]
2004
+ * - image: ["image", "icon-a"] → ["icon-a"]
2005
+ *
2006
+ * @param iconImage - значение icon-image из layout
2007
+ * @returns массив имён иконок
2008
+ */
2009
+ const parseIconNames = (iconImage) => {
2010
+ if (!iconImage) {
2011
+ return [];
2060
2012
  }
2061
- if (type === AttributeType.Json) {
2062
- if (isNilValue || value?.length === 0) {
2063
- return "";
2064
- }
2065
- return `${t("total", { ns: "table" })} ${value.length}`;
2013
+ // Простая строка: "parking"
2014
+ if (typeof iconImage === "string") {
2015
+ return [iconImage];
2066
2016
  }
2067
- return !isNilValue ? value.toString() : "";
2068
- };
2069
- const formatNumber = (number) => {
2070
- let result = "";
2071
- const gapSize = 3;
2072
- if (typeof number === "number") {
2073
- const numsArray = String(number).split(".");
2074
- const numeral = numsArray[0];
2075
- let spaceBefore = numeral.length % gapSize;
2076
- for (let i = 0; i < numeral.length; i += 1) {
2077
- if (i === spaceBefore) {
2078
- result = `${result} `;
2079
- spaceBefore += 3;
2017
+ // Выражение Mapbox
2018
+ if (Array.isArray(iconImage) && iconImage.length > 0) {
2019
+ const [operator, ...args] = iconImage;
2020
+ switch (operator) {
2021
+ // ["match", input, label1, output1, label2, output2, ..., fallback]
2022
+ case "match": {
2023
+ const results = [];
2024
+ // Пропускаем первый аргумент (input), берём каждый второй начиная с индекса 2
2025
+ for (let i = 2; i < args.length; i += 2) {
2026
+ if (typeof args[i] === "string") {
2027
+ results.push(args[i]);
2028
+ }
2029
+ else if (Array.isArray(args[i])) {
2030
+ results.push(...parseIconNames(args[i]));
2031
+ }
2032
+ }
2033
+ // Последний аргумент - fallback (если нечётное количество после input)
2034
+ const lastArg = args[args.length - 1];
2035
+ if (typeof lastArg === "string") {
2036
+ results.push(lastArg);
2037
+ }
2038
+ else if (Array.isArray(lastArg)) {
2039
+ results.push(...parseIconNames(lastArg));
2040
+ }
2041
+ return [...new Set(results)];
2042
+ }
2043
+ // ["case", condition1, output1, condition2, output2, ..., fallback]
2044
+ case "case": {
2045
+ const results = [];
2046
+ for (let i = 1; i < args.length; i += 2) {
2047
+ if (typeof args[i] === "string") {
2048
+ results.push(args[i]);
2049
+ }
2050
+ else if (Array.isArray(args[i])) {
2051
+ results.push(...parseIconNames(args[i]));
2052
+ }
2053
+ }
2054
+ // Fallback
2055
+ if (args.length % 2 === 0) {
2056
+ const lastArg = args[args.length - 1];
2057
+ if (typeof lastArg === "string") {
2058
+ results.push(lastArg);
2059
+ }
2060
+ else if (Array.isArray(lastArg)) {
2061
+ results.push(...parseIconNames(lastArg));
2062
+ }
2063
+ }
2064
+ return [...new Set(results)];
2065
+ }
2066
+ // ["coalesce", expr1, expr2, ...]
2067
+ case "coalesce": {
2068
+ const results = [];
2069
+ args.forEach(arg => {
2070
+ if (typeof arg === "string") {
2071
+ results.push(arg);
2072
+ }
2073
+ else if (Array.isArray(arg)) {
2074
+ results.push(...parseIconNames(arg));
2075
+ }
2076
+ });
2077
+ return [...new Set(results)];
2078
+ }
2079
+ // ["image", name] или ["image", name1, name2, ...]
2080
+ case "image": {
2081
+ return args.filter((arg) => typeof arg === "string");
2082
+ }
2083
+ // ["concat", ...] или другие - рекурсивно ищем строки
2084
+ default: {
2085
+ const results = [];
2086
+ args.forEach(arg => {
2087
+ if (Array.isArray(arg)) {
2088
+ results.push(...parseIconNames(arg));
2089
+ }
2090
+ });
2091
+ return [...new Set(results)];
2080
2092
  }
2081
- result += numeral[i];
2082
- }
2083
- if (numsArray[1]) {
2084
- return [result.trim(), numsArray[1]].join(".");
2085
2093
  }
2086
- return result.trim();
2087
- }
2088
- return number || "0";
2089
- };
2090
- const formatArea = (t, num) => {
2091
- let result = num;
2092
- let measure = t("sqMeter", { ns: "common" });
2093
- if (num >= 10000000) {
2094
- result = num / 1000000;
2095
- measure = t("sqKilometer", { ns: "common" });
2096
- }
2097
- else if (num >= 10000) {
2098
- result = num / 10000;
2099
- measure = t("hectare", { ns: "common" });
2100
- }
2101
- return `${numberWithSpaces(result, 2)} ${measure}`;
2102
- };
2103
- const formatLength = (t, num) => {
2104
- let result = num;
2105
- let measure = t("meter", { ns: "common" });
2106
- if (num > 10000) {
2107
- result = num / 1000;
2108
- measure = t("kilometer", { ns: "common" });
2109
2094
  }
2110
- return `${numberWithSpaces(result, 2)} ${measure}`;
2095
+ return [];
2111
2096
  };
2112
- const formatPolygonMeasure = (t, area, perimiter) => {
2113
- return `S : ${formatArea(t, area)} P : ${formatLength(t, perimiter)}`;
2097
+ /**
2098
+ * Свойства, содержащие имена изображений (иконки и паттерны).
2099
+ */
2100
+ const IMAGE_PROPERTIES = {
2101
+ layout: ["icon-image"],
2102
+ paint: ["fill-pattern", "line-pattern", "fill-extrusion-pattern"],
2114
2103
  };
2115
-
2116
- const geometryToEwkt = (geometry) => {
2117
- if (!geometry) {
2118
- return "";
2104
+ /**
2105
+ * Извлекает все имена изображений из clientStyle.
2106
+ * Включает иконки (icon-image) и паттерны (fill-pattern, line-pattern, fill-extrusion-pattern).
2107
+ *
2108
+ * @param clientStyle - конфигурация стиля слоя
2109
+ * @returns массив уникальных имён изображений
2110
+ */
2111
+ const parseIconNamesFromClientStyle = (clientStyle) => {
2112
+ if (!clientStyle?.items) {
2113
+ return [];
2119
2114
  }
2120
- const projected = toMercator({ type: "Feature", geometry, properties: {} });
2121
- const projectedCoords = projected?.geometry?.coordinates;
2122
- const wkt = stringify({ ...geometry, coordinates: projectedCoords });
2123
- return `SRID=3857;${wkt}`;
2115
+ const imageNames = new Set();
2116
+ clientStyle.items.forEach(item => {
2117
+ // Парсим icon-image из layout
2118
+ IMAGE_PROPERTIES.layout.forEach(prop => {
2119
+ const value = item.layout?.[prop];
2120
+ if (value) {
2121
+ parseIconNames(value).forEach(name => imageNames.add(name));
2122
+ }
2123
+ });
2124
+ // Парсим fill-pattern, line-pattern, fill-extrusion-pattern из paint
2125
+ IMAGE_PROPERTIES.paint.forEach(prop => {
2126
+ const value = item.paint?.[prop];
2127
+ if (value) {
2128
+ parseIconNames(value).forEach(name => imageNames.add(name));
2129
+ }
2130
+ });
2131
+ });
2132
+ return [...imageNames];
2124
2133
  };
2125
2134
 
2126
- function isObject(value) {
2127
- return value !== null && typeof value === "object" && !Array.isArray(value);
2128
- }
2129
-
2130
- const isLayerService = (value) => isObject(value) && "name" in value;
2131
-
2132
- const isNumeric = (number) => !isNaN(parseFloat(number)) && isFinite(number);
2133
-
2134
- const metersPerPixel = (zoom, lat) => {
2135
- return (156543.03 * Math.cos(lat * (Math.PI / 180))) / 2 ** zoom;
2136
- };
2135
+ /** Предел широты сферического меркатора (EPSG:3857): дальше проекция уходит в бесконечность. */
2136
+ const MERCATOR_MAX_LATITUDE = 85.05112878;
2137
+ /** Предел долготы: карта рендерит копии мира, но экстент за пределами ±180° бэкенду не нужен. */
2138
+ const MERCATOR_MAX_LONGITUDE = 180;
2137
2139
 
2138
2140
  const clamp = (value, limit) => Math.min(Math.max(value, -limit), limit);
2139
2141
  /**