# All files stylefunction.js

62.59% Statements 256/409
56% Branches 182/325
61.11% Functions 11/18
62.68% Lines 252/402

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    602
    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    613
    614
    615
    616
    617
    618
    619
    620
    621
    622
    623
    624
    625
    626
    627
    628
    629
    630
    631
    632
    633
    634
    635
    636
    637
    638
    639
    640
    641
    642
    643
    644
    645
    646
    647
    648
    649
    650
    651
    652
    653
    654
    655
    656
    657
    658
    659
    660
    661
    662
    663
    664
    665
    666
    667
    668
    669
    670
    671
    672
    673
    674
    675
    676
    677
    678
    679
    680
    681
    682
    683
    684
    685
    686
    687
    688
    689
    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    737
    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    808
    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    856
    857
    858
    859
    860
    861
    862
    863
    864
    865
    866
    867
    868
    869
    870
    871
    872
    873
    874
    875
    876
    877
    878
    879
    880
    881
    882
    883
    884
    885
    886
    887
    888
    889
    890
    891
    892
    893
    894
    895
    896
    897
    898
    899
    900
    901
    902
    903
    904
    905
    906
    907
    908
    909
    910
    911
    912
    913
    914
    915
    916
    917
    918
    919
    920
    921
    922
    923
    924
    925
    926
    927
    928
    929
    930
    931
    932
    933
    934
    935
    936
    937
    938
    939
    940
    941
    942
    943
    944
    945
    946
    947
    948
    949
    950
    951
    952
    953
    954
    955
    956
    957
    958
    959
    960
    961
    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985
    986
    987
    988
    989
    990
    991
    992
    993
    994
    995
    996
    997
    998
    999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    1015
    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    1038
    1039
    1040
    1041
    1042
    1043
    1044
    1045
    1046
    1047
    1048
    1049
    1050
    1051
    1052
    1053
    1054
    1055
    1056
    1057
    1058
    1059
    1060
    1061
    1062
    1063
    1064
    1065
    1066
    1067
    1068
    1069
    1070
    1071
    1072
    1073
    1074
    1075
    1076
    1077
    1078
    1079
    1080
    1081
    1082
    1083
    1084
    1085
    1086
    1087
    1088
    1089
    1090
    1091
    1092
    1093
    1094
    1095
    1096
    1097
    1098
    1099
    1100
    1101
    1102
    1103
    1104
    1105
    1106
    1107
    1108
    1109
    1110
    1111
    1112
    1113
    1114
    1115
    1116
    1117
    1118
    1119
    1120
    1121
    1122
    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    1141
    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    1165
    1166
    1167
    1168
    1169
    1170
    1171
    1172
    1173
    1174
    1175
    1176
    1177
    1178
    1179
    1180
    1181
    1182
    1183
    1184
    1185
    1186
    1187
    1188
    1189
    1190
    1191
    1192
    1193
    1194
    1195
    1196
    1197
    1198
    1199
    1200
    1201
    1202
    1203
    1204
    1205
    1206
    1207
    1208
    1209
    1210
    1211
    1212
    1213
    1214
    1215
    1216
    1217
    1218
    1219
    1220
    1221
    1222
    1223
    1224
    1225
    1226
    1227
    1228
    1229
    1230
    1231
    1232
    1233
    1234
    1235
    1236
    1237
    1238
    1239
    1240
    1241
    1242
    1243
    1244
    1245
    1246
    1247
    1248
    1249
    1250
    1251
    1252
    1253
    1254
    1255
    1256
    1257
    1258
    1259
    1260
    1261
    1262
    1263
    1264
    1265
    1266
    1267
    1268
    1269
    1270
    1271
    1272

    1x
    1x
    1x
    1x

    1x

    1x

    1x
    1x

    1x

    1x

    1x
    1x

    179x
    179x
    3x
    3x

    179x
    54x

    179x
    179x
    162x
    162x
    162x
    83x

    162x
    162x
    1x
    1x

    162x
    1x
    1x

    161x
    46x

    161x
    178x

    179x
    179x

    29x

    29x
    12x

    29x
    29x

    1x

    13x

    53x
    53x
    12x

    41x
    41x
    41x

    1x

    13x
    23x
    23x
    10x
    10x

    13x

    1x

    11x

    43x

    43x

    43x
    15x
    15x
    15x
    15x
    15x
    15x
    15x
    15x

    15x

    43x

    43x
    43x

    43x
    43x
    43x
    43x

    43x
    1878x
    1878x
    1878x

    1586x
    1586x
    43x
    43x
    43x

    43x
    43x
    1x

    1585x
    1585x
    280x
    280x

    1585x

    1585x

    42x
    42x

    42x

    42x
    24x
    24x
    24x

    24x
    24x
    24x

    24x
    24x

    24x

    24x
    47x
    47x
    47x

    47x
    47x
    47x

    7x

    40x
    40x
    25x

    25x
    25x

    17x

    17x

    17x

    17x
    1x

    17x
    16x

    17x
    16x
    16x
    16x

    11x

    11x

    16x
    15x
    15x

    16x
    16x
    16x
    16x

    16x

    25x
    3x

    3x

    3x
    3x
    3x
    3x

    1x

    1x

    3x
    3x

    3x

    3x

    3x
    3x
    3x

    3x

    25x
    25x
    25x

    25x
    3x

    3x
    3x

    3x
    3x
    1x

    1x

    1x
    1x

    1x

    1x

    1x

    25x

    25x
    5x

    5x

    5x

    5x

    5x

    5x

    5x

    5x

    5x

    5x

    25x
    5x
    5x
    5x
    5x

    5x
    5x

    5x
    5x

    5x
    5x

    5x
    5x
    5x

    5x

    5x

    5x
    5x
    5x

    5x

    5x

    5x
    5x

    5x

    5x

    5x
    5x
    5x
    3x
    3x

    3x

    3x
    3x

    3x

    2x

    2x
    2x

    5x
    5x
    3x
    3x
    2x

    5x
    5x

    5x

    5x

    5x
    5x

    5x

    5x

    5x

    5x
    5x

    5x

    24x
    18x
    18x
    2x

    2x

    18x

    42x
    42x
    42x
    42x

     /*
    ol-mapbox-style - Use Mapbox Style objects with OpenLayers
    Copyright 2016-present ol-mapbox-style contributors
    License: https://raw.githubusercontent.com/openlayers/ol-mapbox-style/master/LICENSE
    */

    import Circle from 'ol/style/Circle.js';
    import Fill from 'ol/style/Fill.js';
    import Icon from 'ol/style/Icon.js';
    import RenderFeature from 'ol/render/Feature.js';
    import Stroke from 'ol/style/Stroke.js';
    import Style from 'ol/style/Style.js';
    import Text from 'ol/style/Text.js';

    import mb2css from 'mapbox-to-css-font';
    import {
      Color,
      featureFilter as createFilter,
      derefLayers,
      expression,
      function as fn,
      latest as spec,
    } from '@mapbox/mapbox-gl-style-spec';
    import {
      applyLetterSpacing,
      createCanvas,
      defaultResolutions,
      deg2rad,
      getZoomForResolution,
      wrapText,
    } from './util.js';

    /**
     * @typedef {import("ol/layer/Vector").default} VectorLayer
     * @typedef {import("ol/layer/VectorTile").default} VectorTileLayer
     * @typedef {import("ol/style/Style").StyleFunction} StyleFunction
     */

    const isFunction = fn.isFunction;
    const convertFunction = fn.convertFunction;
    const isExpression = expression.isExpression;
    const createPropertyExpression = expression.createPropertyExpression;

    const types = {
      'Point': 1,
      'MultiPoint': 1,
      'LineString': 2,
      'MultiLineString': 2,
      'Polygon': 3,
      'MultiPolygon': 3,
    };
    const anchor = {
      'center': [0.5, 0.5],
      'left': [0, 0.5],
      'right': [1, 0.5],
      'top': [0.5, 0],
      'bottom': [0.5, 1],
      'top-left': [0, 0],
      'top-right': [1, 0],
      'bottom-left': [0, 1],
      'bottom-right': [1, 1],
    };

    const expressionData = function (rawExpression, propertySpec) {
      const compiledExpression = createPropertyExpression(
        rawExpression,
        propertySpec
      );
      Iif (compiledExpression.result === 'error') {
        throw new Error(
          compiledExpression.value
            .map((err) => `${err.key}: ${err.message}`)
            .join(', ')
        );
      }
      return compiledExpression.value;
    };

    const emptyObj = {};
    const zoomObj = {zoom: 0};
    let renderFeatureCoordinates, renderFeature;

    /**
     * @private
     * @param {Object} layer Gl object layer.
     * @param {string} layoutOrPaint 'layout' or 'paint'.
     * @param {string} property Feature property.
     * @param {number} zoom Zoom.
     * @param {Object} feature Gl feature.
     * @param {Object} [functionCache] Function cache.
     * @return {?} Value.
     */
    export function getValue(
      layer,
      layoutOrPaint,
      property,
      zoom,
      feature,
      functionCache
    ) {
      const layerId = layer.id;
      if (!functionCache) {
        functionCache = {};
        console.warn('No functionCache provided to getValue()'); //eslint-disable-line no-console
      }
      if (!functionCache[layerId]) {
        functionCache[layerId] = {};
      }
      const functions = functionCache[layerId];
      if (!functions[property]) {
        let value = (layer[layoutOrPaint] || emptyObj)[property];
        const propertySpec = spec[`${layoutOrPaint}_${layer.type}`][property];
        if (value === undefined) {
          value = propertySpec.default;
        }
        let isExpr = isExpression(value);
        if (!isExpr && isFunction(value)) {
          value = convertFunction(value, propertySpec);
          isExpr = true;
        }
        if (isExpr) {
          const compiledExpression = expressionData(value, propertySpec);
          functions[property] =
            compiledExpression.evaluate.bind(compiledExpression);
        } else {
          if (propertySpec.type == 'color') {
            value = Color.parse(value);
          }
          functions[property] = function () {
            return value;
          };
        }
      }
      zoomObj.zoom = zoom;
      return functions[property](zoomObj, feature);
    }

    /**
     * @private
     * @param {string} layerId Layer id.
     * @param {?} filter Filter.
     * @param {Object} feature Feature.
     * @param {number} zoom Zoom.
     * @param {Object} [filterCache] Filter cache.
     * @return {boolean} Filter result.
     */
    function evaluateFilter(layerId, filter, feature, zoom, filterCache) {
      Iif (!filterCache) {
        console.warn('No filterCache provided to evaluateFilter()'); //eslint-disable-line no-console
      }
      if (!(layerId in filterCache)) {
        filterCache[layerId] = createFilter(filter).filter;
      }
      zoomObj.zoom = zoom;
      return filterCache[layerId](zoomObj, feature);
    }

    let renderTransparentEnabled = false;

    /**
     * ```js
     * import {renderTransparent} from 'ol-mapbox-style/dist/stylefunction';
     * ```
     * Configure whether features with a transparent style should be rendered. When
     * set to `true`, it will be possible to hit detect content that is not visible,
     * like transparent fills of polygons, using `ol/layer/Layer#getFeatures()` or
     * `ol/Map#getFeaturesAtPixel()`
     * @param {boolean} enabled Rendering of transparent elements is enabled.
     * Default is `false`.
     */
    export function renderTransparent(enabled) {
      renderTransparentEnabled = enabled;
    }

    /**
     * @private
     * @param {?} color Color.
     * @param {number} opacity Opacity.
     * @return {string} Color.
     */
    function colorWithOpacity(color, opacity) {
      Eif (color) {
        if (!renderTransparentEnabled && (color.a === 0 || opacity === 0)) {
          return undefined;
        }
        const a = color.a;
        opacity = opacity === undefined ? 1 : opacity;
        return a === 0
          ? 'transparent'
          : 'rgba(' +
              Math.round((color.r * 255) / a) +
              ',' +
              Math.round((color.g * 255) / a) +
              ',' +
              Math.round((color.b * 255) / a) +
              ',' +
              a * opacity +
              ')';
      }
      return color;
    }

    const templateRegEx = /^([^]*)\{(.*)\}([^]*)$/;

    /**
     * @private
     * @param {string} text Text.
     * @param {Object} properties Properties.
     * @return {string} Text.
     */
    function fromTemplate(text, properties) {
      let parts;
      do {
        parts = text.match(templateRegEx);
        if (parts) {
          const value = properties[parts[2]] || '';
          text = parts[1] + value + parts[3];
        }
      } while (parts);
      return text;
    }

    let recordLayer = false;

    /**
     * ```js
     * import {recordStyleLayer} from 'ol-mapbox-style/dist/stylefunction';
     * ```
     * Turns recording of the Mapbox Style's `layer` on and off. When turned on,
     * the layer that a rendered feature belongs to will be set as the feature's
     * `mapbox-layer` property.
     * @param {boolean} [record=false] Recording of the style layer is on.
     */
    export function recordStyleLayer(record) {
      recordLayer = record;
    }

    /**
     * ```js
     * import stylefunction from 'ol-mapbox-style/dist/stylefunction';
     * ```
     * Creates a style function from the `glStyle` object for all layers that use
     * the specified `source`, which needs to be a `"type": "vector"` or
     * `"type": "geojson"` source and applies it to the specified OpenLayers layer.
     *
     * Two additional properties will be set on the provided layer:
     *
     *  * `mapbox-source`: The `id` of the Mapbox Style document's source that the
     *    OpenLayers layer was created from. Usually `apply()` creates one
     *    OpenLayers layer per Mapbox Style source, unless the layer stack has
     *    layers from different sources in between.
     *  * `mapbox-layers`: The `id`s of the Mapbox Style document's layers that are
     *    included in the OpenLayers layer.
     *
     * This function also works in a web worker. In worker mode, the main thread needs
     * to listen to messages from the worker and respond with another message to make
     * sure that sprite image loading works:
     *
     * ```js
     *  worker.addEventListener('message', event => {
     *   if (event.data.action === 'loadImage') {
     *     const image = new Image();
     *     image.crossOrigin = 'anonymous';
     *     image.addEventListener('load', function() {
     *       createImageBitmap(image, 0, 0, image.width, image.height).then(imageBitmap => {
     *         worker.postMessage({
     *           action: 'imageLoaded',
     *           image: imageBitmap,
     *           src: event.data.src
     *         }, [imageBitmap]);
     *       });
     *     });
     *     image.src = event.data.src;
     *   }
     * });
     * ```
     *
     * @param {VectorLayer|VectorTileLayer} olLayer OpenLayers layer to
     * apply the style to. In addition to the style, the layer will get two
     * properties: `mapbox-source` will be the `id` of the `glStyle`'s source used
     * for the layer, and `mapbox-layers` will be an array of the `id`s of the
     * `glStyle`'s layers.
     * @param {string|Object} glStyle Mapbox Style object.
     * @param {string|Array<string>} source `source` key or an array of layer `id`s
     * from the Mapbox Style object. When a `source` key is provided, all layers for
     * the specified source will be included in the style function. When layer `id`s
     * are provided, they must be from layers that use the same source.
     * @param {Array<number>} [resolutions=[78271.51696402048, 39135.75848201024, 19567.87924100512, 9783.93962050256, 4891.96981025128, 2445.98490512564, 1222.99245256282, 611.49622628141, 305.748113140705, 152.8740565703525, 76.43702828517625, 38.21851414258813, 19.109257071294063, 9.554628535647032, 4.777314267823516, 2.388657133911758, 1.194328566955879, 0.5971642834779395, 0.29858214173896974, 0.14929107086948487, 0.07464553543474244]]
     * Resolutions for mapping resolution to zoom level.
     * @param {Object} [spriteData=undefined] Sprite data from the url specified in
     * the Mapbox Style object's `sprite` property. Only required if a `sprite`
     * property is specified in the Mapbox Style object.
     * @param {string} [spriteImageUrl=undefined] Sprite image url for the sprite
     * specified in the Mapbox Style object's `sprite` property. Only required if a
     * `sprite` property is specified in the Mapbox Style object.
     * @param {function(Array<string>):Array<string>} [getFonts=undefined] Function that
     * receives a font stack as arguments, and returns a (modified) font stack that
     * is available. Font names are the names used in the Mapbox Style object. If
     * not provided, the font stack will be used as-is. This function can also be
     * used for loading web fonts.
     * @return {StyleFunction} Style function for use in
     * `ol.layer.Vector` or `ol.layer.VectorTile`.
     */
    export default function (
      olLayer,
      glStyle,
      source,
      resolutions = defaultResolutions,
      spriteData,
      spriteImageUrl,
      getFonts
    ) {
      Iif (typeof glStyle == 'string') {
        glStyle = JSON.parse(glStyle);
      }
      Iif (glStyle.version != 8) {
        throw new Error('glStyle version 8 required.');
      }

      let spriteImage, spriteImgSize;
      if (spriteImageUrl) {
        Eif (typeof Image !== 'undefined') {
          const img = new Image();
          img.crossOrigin = 'anonymous';
          img.onload = function () {
            spriteImage = img;
            spriteImgSize = [img.width, img.height];
            olLayer.changed();
            img.onload = null;
          };
          img.src = spriteImageUrl;
        } else if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) { //eslint-disable-line
          const worker = /** @type {*} */ (self);
          // Main thread needs to handle 'loadImage' and dispatch 'imageLoaded'
          worker.postMessage({
            action: 'loadImage',
            src: spriteImageUrl,
          });
          worker.addEventListener('message', function handler(event) {
            if (
              event.data.action === 'imageLoaded' &&
              event.data.src === spriteImageUrl
            ) {
              spriteImage = event.data.image;
              spriteImgSize = [spriteImage.width, spriteImage.height];
            }
          });
        }
      }

      const allLayers = derefLayers(glStyle.layers);

      const layersBySourceLayer = {};
      const mapboxLayers = [];

      const iconImageCache = {};
      const patternCache = {};
      const functionCache = {};
      const filterCache = {};

      let mapboxSource;
      for (let i = 0, ii = allLayers.length; i < ii; ++i) {
        const layer = allLayers[i];
        const layerId = layer.id;
        if (
          (typeof source == 'string' && layer.source == source) ||
          source.indexOf(layerId) !== -1
        ) {
          const sourceLayer = layer['source-layer'];
          if (!mapboxSource) {
            mapboxSource = layer.source;
            const source = glStyle.sources[mapboxSource];
            Iif (!source) {
              throw new Error(`Source "${mapboxSource}" is not defined`);
            }
            const type = source.type;
            if (type !== 'vector' && type !== 'geojson') {
              throw new Error(
                `Source "${mapboxSource}" is not of type "vector" or "geojson", but "${type}"`
              );
            }
          }
          let layers = layersBySourceLayer[sourceLayer];
          if (!layers) {
            layers = [];
            layersBySourceLayer[sourceLayer] = layers;
          }
          layers.push({
            layer: layer,
            index: i,
          });
          mapboxLayers.push(layerId);
        }
      }

      const textHalo = new Stroke();
      const textColor = new Fill();

      const styles = [];

      const styleFunction = function (feature, resolution) {
        const properties = feature.getProperties();
        const layers = layersBySourceLayer[properties.layer];
        Iif (!layers) {
          return;
        }
        let zoom = resolutions.indexOf(resolution);
        Eif (zoom == -1) {
          zoom = getZoomForResolution(resolution, resolutions);
        }
        const type = types[feature.getGeometry().getType()];
        const f = {
          properties: properties,
          type: type,
        };
        let stylesLength = -1;
        let featureBelongsToLayer;
        for (let i = 0, ii = layers.length; i < ii; ++i) {
          const layerData = layers[i];
          const layer = layerData.layer;
          const layerId = layer.id;

          const layout = layer.layout || emptyObj;
          const paint = layer.paint || emptyObj;
          if (
            layout.visibility === 'none' ||
            ('minzoom' in layer && zoom < layer.minzoom) ||
            ('maxzoom' in layer && zoom >= layer.maxzoom)
          ) {
            continue;
          }
          const filter = layer.filter;
          if (!filter || evaluateFilter(layerId, filter, f, zoom, filterCache)) {
            featureBelongsToLayer = layer;
            let color, opacity, fill, stroke, strokeColor, style;
            const index = layerData.index;
            if (
              type == 3 &&
              (layer.type == 'fill' || layer.type == 'fill-extrusion')
            ) {
              opacity = getValue(
                layer,
                'paint',
                layer.type + '-opacity',
                zoom,
                f,
                functionCache
              );
              Iif (layer.type + '-pattern' in paint) {
                const fillIcon = getValue(
                  layer,
                  'paint',
                  layer.type + '-pattern',
                  zoom,
                  f,
                  functionCache
                );
                if (fillIcon) {
                  const icon =
                    typeof fillIcon === 'string'
                      ? fromTemplate(fillIcon, properties)
                      : fillIcon.toString();
                  if (spriteImage && spriteData && spriteData[icon]) {
                    ++stylesLength;
                    style = styles[stylesLength];
                    if (
                      !style ||
                      !style.getFill() ||
                      style.getStroke() ||
                      style.getText()
                    ) {
                      style = new Style({
                        fill: new Fill(),
                      });
                      styles[stylesLength] = style;
                    }
                    fill = style.getFill();
                    style.setZIndex(index);
                    const icon_cache_key = icon + '.' + opacity;
                    let pattern = patternCache[icon_cache_key];
                    if (!pattern) {
                      const spriteImageData = spriteData[icon];
                      const canvas = createCanvas(
                        spriteImageData.width,
                        spriteImageData.height
                      );
                      const ctx = /** @type {CanvasRenderingContext2D} */ (
                        canvas.getContext('2d')
                      );
                      ctx.globalAlpha = opacity;
                      ctx.drawImage(
                        spriteImage,
                        spriteImageData.x,
                        spriteImageData.y,
                        spriteImageData.width,
                        spriteImageData.height,
                        0,
                        0,
                        spriteImageData.width,
                        spriteImageData.height
                      );
                      pattern = ctx.createPattern(canvas, 'repeat');
                      patternCache[icon_cache_key] = pattern;
                    }
                    fill.setColor(pattern);
                  }
                }
              } else {
                color = colorWithOpacity(
                  getValue(
                    layer,
                    'paint',
                    layer.type + '-color',
                    zoom,
                    f,
                    functionCache
                  ),
                  opacity
                );
                if (layer.type + '-outline-color' in paint) {
                  strokeColor = colorWithOpacity(
                    getValue(
                      layer,
                      'paint',
                      layer.type + '-outline-color',
                      zoom,
                      f,
                      functionCache
                    ),
                    opacity
                  );
                }
                if (!strokeColor) {
                  strokeColor = color;
                }
                if (color || strokeColor) {
                  ++stylesLength;
                  style = styles[stylesLength];
                  if (
                    !style ||
                    (color && !style.getFill()) ||
                    (!color && style.getFill()) ||
                    (strokeColor && !style.getStroke()) ||
                    (!strokeColor && style.getStroke()) ||
                    style.getText()
                  ) {
                    style = new Style({
                      fill: color ? new Fill() : undefined,
                      stroke: strokeColor ? new Stroke() : undefined,
                    });
                    styles[stylesLength] = style;
                  }
                  if (color) {
                    fill = style.getFill();
                    fill.setColor(color);
                  }
                  Eif (strokeColor) {
                    stroke = style.getStroke();
                    stroke.setColor(strokeColor);
                    stroke.setWidth(0.5);
                  }
                  style.setZIndex(index);
                }
              }
            }
            if (type != 1 && layer.type == 'line') {
              color =
                !('line-pattern' in paint) && 'line-color' in paint
                  ? colorWithOpacity(
                      getValue(
                        layer,
                        'paint',
                        'line-color',
                        zoom,
                        f,
                        functionCache
                      ),
                      getValue(
                        layer,
                        'paint',
                        'line-opacity',
                        zoom,
                        f,
                        functionCache
                      )
                    )
                  : undefined;
              const width = getValue(
                layer,
                'paint',
                'line-width',
                zoom,
                f,
                functionCache
              );
              Eif (color && width > 0) {
                ++stylesLength;
                style = styles[stylesLength];
                if (
                  !style ||
                  !style.getStroke() ||
                  style.getFill() ||
                  style.getText()
                ) {
                  style = new Style({
                    stroke: new Stroke(),
                  });
                  styles[stylesLength] = style;
                }
                stroke = style.getStroke();
                stroke.setLineCap(
                  getValue(layer, 'layout', 'line-cap', zoom, f, functionCache)
                );
                stroke.setLineJoin(
                  getValue(layer, 'layout', 'line-join', zoom, f, functionCache)
                );
                stroke.setMiterLimit(
                  getValue(
                    layer,
                    'layout',
                    'line-miter-limit',
                    zoom,
                    f,
                    functionCache
                  )
                );
                stroke.setColor(color);
                stroke.setWidth(width);
                stroke.setLineDash(
                  paint['line-dasharray']
                    ? getValue(
                        layer,
                        'paint',
                        'line-dasharray',
                        zoom,
                        f,
                        functionCache
                      ).map(function (x) {
                        return x * width;
                      })
                    : null
                );
                style.setZIndex(index);
              }
            }

            let hasImage = false;
            let text = null;
            let placementAngle = 0;
            let icon, iconImg, skipLabel;
            if ((type == 1 || type == 2) && 'icon-image' in layout) {
              const iconImage = getValue(
                layer,
                'layout',
                'icon-image',
                zoom,
                f,
                functionCache
              );
              Eif (iconImage) {
                icon =
                  typeof iconImage === 'string'
                    ? fromTemplate(iconImage, properties)
                    : iconImage.toString();
                let styleGeom = undefined;
                if (spriteImage && spriteData && spriteData[icon]) {
                  const iconRotationAlignment = getValue(
                    layer,
                    'layout',
                    'icon-rotation-alignment',
                    zoom,
                    f,
                    functionCache
                  );
                  Iif (type == 2) {
                    const geom = feature.getGeometry();
                    // ol package and ol-debug.js only
                    if (geom.getFlatMidpoint || geom.getFlatMidpoints) {
                      const extent = geom.getExtent();
                      const size = Math.sqrt(
                        Math.max(
                          Math.pow((extent[2] - extent[0]) / resolution, 2),
                          Math.pow((extent[3] - extent[1]) / resolution, 2)
                        )
                      );
                      if (size > 150) {
                        //FIXME Do not hard-code a size of 150
                        const midpoint =
                          geom.getType() === 'MultiLineString'
                            ? geom.getFlatMidpoints()
                            : geom.getFlatMidpoint();
                        if (!renderFeature) {
                          renderFeatureCoordinates = [NaN, NaN];
                          renderFeature = new RenderFeature(
                            'Point',
                            renderFeatureCoordinates,
                            [],
                            {},
                            null
                          );
                        }
                        styleGeom = renderFeature;
                        renderFeatureCoordinates[0] = midpoint[0];
                        renderFeatureCoordinates[1] = midpoint[1];
                        const placement = getValue(
                          layer,
                          'layout',
                          'symbol-placement',
                          zoom,
                          f,
                          functionCache
                        );
                        if (
                          placement === 'line' &&
                          iconRotationAlignment === 'map'
                        ) {
                          const stride = geom.getStride();
                          const coordinates = geom.getFlatCoordinates();
                          for (
                            let i = 0, ii = coordinates.length - stride;
                            i < ii;
                            i += stride
                          ) {
                            const x1 = coordinates[i];
                            const y1 = coordinates[i + 1];
                            const x2 = coordinates[i + stride];
                            const y2 = coordinates[i + stride + 1];
                            const minX = Math.min(x1, x2);
                            const minY = Math.min(y1, y2);
                            const maxX = Math.max(x1, x2);
                            const maxY = Math.max(y1, y2);
                            if (
                              midpoint[0] >= minX &&
                              midpoint[0] <= maxX &&
                              midpoint[1] >= minY &&
                              midpoint[1] <= maxY
                            ) {
                              placementAngle = Math.atan2(y1 - y2, x2 - x1);
                              break;
                            }
                          }
                        }
                      }
                    }
                  }
                  Eif (type !== 2 || styleGeom) {
                    const iconSize = getValue(
                      layer,
                      'layout',
                      'icon-size',
                      zoom,
                      f,
                      functionCache
                    );
                    const iconColor =
                      paint['icon-color'] !== undefined
                        ? getValue(
                            layer,
                            'paint',
                            'icon-color',
                            zoom,
                            f,
                            functionCache
                          )
                        : null;
                    Iif (!iconColor || iconColor.a !== 0) {
                      let icon_cache_key = icon + '.' + iconSize;
                      if (iconColor !== null) {
                        icon_cache_key += '.' + iconColor;
                      }
                      iconImg = iconImageCache[icon_cache_key];
                      if (!iconImg) {
                        const spriteImageData = spriteData[icon];

                        iconImg = new Icon({
                          color: iconColor
                            ? [
                                iconColor.r * 255,
                                iconColor.g * 255,
                                iconColor.b * 255,
                                iconColor.a,
                              ]
                            : undefined,
                          img: spriteImage,
                          imgSize: spriteImgSize,
                          size: [spriteImageData.width, spriteImageData.height],
                          offset: [spriteImageData.x, spriteImageData.y],
                          rotateWithView: iconRotationAlignment === 'map',
                          scale: iconSize / spriteImageData.pixelRatio,
                          displacement:
                            'icon-offset' in layout
                              ? getValue(
                                  layer,
                                  'layout',
                                  'icon-offset',
                                  zoom,
                                  f,
                                  functionCache
                                ).map((v) => -v * spriteImageData.pixelRatio)
                              : undefined,
                        });
                        iconImageCache[icon_cache_key] = iconImg;
                      }
                    }
                    Iif (iconImg) {
                      ++stylesLength;
                      style = styles[stylesLength];
                      if (
                        !style ||
                        !style.getImage() ||
                        style.getFill() ||
                        style.getStroke()
                      ) {
                        style = new Style();
                        styles[stylesLength] = style;
                      }
                      style.setGeometry(styleGeom);
                      iconImg.setRotation(
                        placementAngle +
                          deg2rad(
                            getValue(
                              layer,
                              'layout',
                              'icon-rotate',
                              zoom,
                              f,
                              functionCache
                            )
                          )
                      );
                      iconImg.setOpacity(
                        getValue(
                          layer,
                          'paint',
                          'icon-opacity',
                          zoom,
                          f,
                          functionCache
                        )
                      );
                      iconImg.setAnchor(
                        anchor[
                          getValue(
                            layer,
                            'layout',
                            'icon-anchor',
                            zoom,
                            f,
                            functionCache
                          )
                        ]
                      );
                      style.setImage(iconImg);
                      text = style.getText();
                      style.setText(undefined);
                      style.setZIndex(index);
                      hasImage = true;
                      skipLabel = false;
                    }
                  } else {
                    skipLabel = true;
                  }
                }
              }
            }

            Iif (type == 1 && layer.type === 'circle') {
              ++stylesLength;
              style = styles[stylesLength];
              if (
                !style ||
                !style.getImage() ||
                style.getFill() ||
                style.getStroke()
              ) {
                style = new Style();
                styles[stylesLength] = style;
              }
              const circleRadius =
                'circle-radius' in paint
                  ? getValue(
                      layer,
                      'paint',
                      'circle-radius',
                      zoom,
                      f,
                      functionCache
                    )
                  : 5;
              const circleStrokeColor = colorWithOpacity(
                getValue(
                  layer,
                  'paint',
                  'circle-stroke-color',
                  zoom,
                  f,
                  functionCache
                ),
                getValue(
                  layer,
                  'paint',
                  'circle-stroke-opacity',
                  zoom,
                  f,
                  functionCache
                )
              );
              const circleColor = colorWithOpacity(
                getValue(layer, 'paint', 'circle-color', zoom, f, functionCache),
                getValue(layer, 'paint', 'circle-opacity', zoom, f, functionCache)
              );
              const circleStrokeWidth = getValue(
                layer,
                'paint',
                'circle-stroke-width',
                zoom,
                f,
                functionCache
              );
              const cache_key =
                circleRadius +
                '.' +
                circleStrokeColor +
                '.' +
                circleColor +
                '.' +
                circleStrokeWidth;
              iconImg = iconImageCache[cache_key];
              if (!iconImg) {
                iconImg = new Circle({
                  radius: circleRadius,
                  stroke:
                    circleStrokeColor && circleStrokeWidth > 0
                      ? new Stroke({
                          width: circleStrokeWidth,
                          color: circleStrokeColor,
                        })
                      : undefined,
                  fill: circleColor
                    ? new Fill({
                        color: circleColor,
                      })
                    : undefined,
                });
                iconImageCache[cache_key] = iconImg;
              }
              style.setImage(iconImg);
              text = style.getText();
              style.setText(undefined);
              style.setGeometry(undefined);
              style.setZIndex(index);
              hasImage = true;
            }

            let label, font, textLineHeight, textSize, letterSpacing, maxTextWidth;
            if ('text-field' in layout) {
              textSize = Math.round(
                getValue(layer, 'layout', 'text-size', zoom, f, functionCache)
              );
              const fontArray = getValue(
                layer,
                'layout',
                'text-font',
                zoom,
                f,
                functionCache
              );
              textLineHeight = getValue(
                layer,
                'layout',
                'text-line-height',
                zoom,
                f,
                functionCache
              );
              font = mb2css(
                getFonts ? getFonts(fontArray) : fontArray,
                textSize,
                textLineHeight
              );
              letterSpacing = getValue(
                layer,
                'layout',
                'text-letter-spacing',
                zoom,
                f,
                functionCache
              );
              maxTextWidth = getValue(
                layer,
                'layout',
                'text-max-width',
                zoom,
                f,
                functionCache
              );
              const textField = getValue(
                layer,
                'layout',
                'text-field',
                zoom,
                f,
                functionCache
              );
              Iif (typeof textField === 'object' && textField.sections) {
                if (textField.sections.length === 1) {
                  label = textField.toString();
                } else {
                  label = textField.sections.reduce((acc, chunk, i) => {
                    const fonts = chunk.fontStack
                      ? chunk.fontStack.split(',')
                      : fontArray;
                    const chunkFont = mb2css(
                      getFonts ? getFonts(fonts) : fonts,
                      textSize * (chunk.scale || 1),
                      textLineHeight
                    );
                    let text = chunk.text;
                    if (text === '\n') {
                      acc.push('\n', '');
                      return acc;
                    }
                    if (type == 2) {
                      acc.push(applyLetterSpacing(text, letterSpacing), chunkFont);
                      return;
                    }
                    text = wrapText(
                      text,
                      chunkFont,
                      maxTextWidth,
                      letterSpacing
                    ).split('\n');
                    for (let i = 0, ii = text.length; i < ii; ++i) {
                      if (i > 0) {
                        acc.push('\n', '');
                      }
                      acc.push(text[i], chunkFont);
                    }
                    return acc;
                  }, []);
                }
              } else {
                label = fromTemplate(textField, properties).trim();
              }
              opacity = getValue(
                layer,
                'paint',
                'text-opacity',
                zoom,
                f,
                functionCache
              );
            }
            if (label && opacity && !skipLabel) {
              Eif (!hasImage) {
                ++stylesLength;
                style = styles[stylesLength];
                Eif (
                  !style ||
                  !style.getText() ||
                  style.getFill() ||
                  style.getStroke()
                ) {
                  style = new Style();
                  styles[stylesLength] = style;
                }
                style.setImage(undefined);
                style.setGeometry(undefined);
              }
              Eif (!style.getText()) {
                style.setText(
                  text ||
                    new Text({
                      padding: [2, 2, 2, 2],
                    })
                );
              }
              text = style.getText();
              const textTransform = layout['text-transform'];
              Iif (textTransform == 'uppercase') {
                label = Array.isArray(label)
                  ? label.map((t, i) => (i % 2 ? t : t.toUpperCase()))
                  : label.toUpperCase();
              } else Iif (textTransform == 'lowercase') {
                label = Array.isArray(label)
                  ? label.map((t, i) => (i % 2 ? t : t.toLowerCase()))
                  : label.toLowerCase();
              }
              const wrappedLabel = Array.isArray(label)
                ? label
                : type == 2
                ? applyLetterSpacing(label, letterSpacing)
                : wrapText(label, font, maxTextWidth, letterSpacing);
              text.setText(wrappedLabel);
              text.setFont(font);
              text.setRotation(
                deg2rad(
                  getValue(layer, 'layout', 'text-rotate', zoom, f, functionCache)
                )
              );
              const textAnchor = getValue(
                layer,
                'layout',
                'text-anchor',
                zoom,
                f,
                functionCache
              );
              const placement =
                hasImage || type == 1
                  ? 'point'
                  : getValue(
                      layer,
                      'layout',
                      'symbol-placement',
                      zoom,
                      f,
                      functionCache
                    );
              text.setPlacement(placement);
              let textHaloWidth = getValue(
                layer,
                'paint',
                'text-halo-width',
                zoom,
                f,
                functionCache
              );
              const textOffset = getValue(
                layer,
                'layout',
                'text-offset',
                zoom,
                f,
                functionCache
              );
              const textTranslate = getValue(
                layer,
                'paint',
                'text-translate',
                zoom,
                f,
                functionCache
              );
              // Text offset has to take halo width and line height into account
              let vOffset = 0;
              let hOffset = 0;
              if (placement == 'point') {
                let textAlign = 'center';
                Iif (textAnchor.indexOf('left') !== -1) {
                  textAlign = 'left';
                  hOffset = textHaloWidth;
                } else Iif (textAnchor.indexOf('right') !== -1) {
                  textAlign = 'right';
                  hOffset = -textHaloWidth;
                }
                text.setTextAlign(textAlign);
                const textRotationAlignment = getValue(
                  layer,
                  'layout',
                  'text-rotation-alignment',
                  zoom,
                  f,
                  functionCache
                );
                text.setRotateWithView(textRotationAlignment == 'map');
              } else {
                text.setMaxAngle(
                  (deg2rad(
                    getValue(
                      layer,
                      'layout',
                      'text-max-angle',
                      zoom,
                      f,
                      functionCache
                    )
                  ) *
                    label.length) /
                    wrappedLabel.length
                );
                text.setTextAlign();
                text.setRotateWithView(false);
              }
              let textBaseline = 'middle';
              if (textAnchor.indexOf('bottom') == 0) {
                textBaseline = 'bottom';
                vOffset = -textHaloWidth - 0.5 * (textLineHeight - 1) * textSize;
              } else Iif (textAnchor.indexOf('top') == 0) {
                textBaseline = 'top';
                vOffset = textHaloWidth + 0.5 * (textLineHeight - 1) * textSize;
              }
              text.setTextBaseline(textBaseline);
              text.setOffsetX(
                textOffset[0] * textSize + hOffset + textTranslate[0]
              );
              text.setOffsetY(
                textOffset[1] * textSize + vOffset + textTranslate[1]
              );
              textColor.setColor(
                colorWithOpacity(
                  getValue(layer, 'paint', 'text-color', zoom, f, functionCache),
                  opacity
                )
              );
              text.setFill(textColor);
              const haloColor = colorWithOpacity(
                getValue(layer, 'paint', 'text-halo-color', zoom, f, functionCache),
                opacity
              );
              Iif (haloColor) {
                textHalo.setColor(haloColor);
                // spec here : https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-symbol-text-halo-width
                // Halo width must be doubled because it is applied around the center of the text outline
                textHaloWidth *= 2;
                // 1/4 of text size (spec) x 2
                const halfTextSize = 0.5 * textSize;
                textHalo.setWidth(
                  textHaloWidth <= halfTextSize ? textHaloWidth : halfTextSize
                );
                text.setStroke(textHalo);
              } else {
                text.setStroke(undefined);
              }
              const textPadding = getValue(
                layer,
                'layout',
                'text-padding',
                zoom,
                f,
                functionCache
              );
              const padding = text.getPadding();
              Iif (textPadding !== padding[0]) {
                padding[0] = textPadding;
                padding[1] = textPadding;
                padding[2] = textPadding;
                padding[3] = textPadding;
              }
              style.setZIndex(index);
            }
          }
        }

        if (stylesLength > -1) {
          styles.length = stylesLength + 1;
          if (recordLayer) {
            Eif (typeof feature.set === 'function') {
              // ol/Feature
              feature.set('mapbox-layer', featureBelongsToLayer);
            } else {
              // ol/render/Feature
              feature.getProperties()['mapbox-layer'] = featureBelongsToLayer;
            }
          }
          return styles;
        }
      };

      olLayer.setStyle(styleFunction);
      olLayer.set('mapbox-source', mapboxSource);
      olLayer.set('mapbox-layers', mapboxLayers);
      return styleFunction;
    }

    export {
      colorWithOpacity as _colorWithOpacity,
      evaluateFilter as _evaluateFilter,
      fromTemplate as _fromTemplate,
      getValue as _getValue,
    };