# Code coverage report for ControlSaveTiles.ts

# All files ControlSaveTiles.ts

83.51% Statements 76/91
61.9% Branches 13/21
77.27% Functions 17/22
82.55% Lines 71/86

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

    9x

    9x
    9x
    9x
    9x

    13x

    13x

    13x
    13x
    13x

    10x
    10x
    10x

    10x
    10x

    20x
    20x
    20x
    20x

    20x

    20x

    6x
    6x
    6x
    5x
    18x
    18x
    18x
    9x

    9x
    9x
    8x

    9x

    5x
    5x
    9x

    6x
    1x

    5x

    6x

    6x

    6x

    6x
    1x
    1x

    1x

    1x
    4x

    5x

    6x

    6x
    10x

    10x

    6x

    5x

    8x
    8x
    8x
    8x
    3x
    3x

    9x
    9x
    9x
    9x
    9x

    9x

    9x

    9x

    1x

    1x

     import {
      Control,
      ControlOptions,
      DomEvent,
      DomUtil,
      LatLngBounds,
      bounds,
      Map,
    } from 'leaflet';
    import { TileLayerOffline } from './TileLayerOffline';
    import {
      truncate,
      getStorageLength,
      downloadTile,
      saveTile,
      TileInfo,
      hasTile,
    } from './TileManager';

    export interface SaveTileOptions extends ControlOptions {
      saveText: string;
      rmText: string;
      maxZoom: number;
      saveWhatYouSee: boolean;
      bounds: LatLngBounds | null;
      confirm: ((status: SaveStatus, successCallback: Function) => void) | null;
      confirmRemoval:
        | ((status: SaveStatus, successCallback: Function) => void)
        | null;
      parallel: number;
      zoomlevels?: number[];
      alwaysDownload: boolean;
    }

    export interface SaveStatus {
      _tilesforSave: TileInfo[];
      storagesize: number;
      lengthToBeSaved: number;
      lengthSaved: number;
      lengthLoaded: number;
    }

    export class ControlSaveTiles extends Control {
      _map!: Map;

      _refocusOnMap!: DomEvent.EventHandlerFn;

      _baseLayer!: TileLayerOffline;

      options: SaveTileOptions;

      status: SaveStatus = {
        storagesize: 0,
        lengthToBeSaved: 0,
        lengthSaved: 0,
        lengthLoaded: 0,
        _tilesforSave: [],
      };

      constructor(baseLayer: TileLayerOffline, options: Partial<SaveTileOptions>) {
        super(options);
        this._baseLayer = baseLayer;
        this.setStorageSize();
        this.options = {
          ...{
            position: 'topleft',
            saveText: '+',
            rmText: '-',
            maxZoom: 19,
            saveWhatYouSee: false,
            bounds: null,
            confirm: null,
            confirmRemoval: null,
            parallel: 50,
            zoomlevels: undefined,
            alwaysDownload: true,
          },
          ...options,
        };
      }

      setStorageSize() {
        Iif (this.status.storagesize) {
          return Promise.resolve(this.status.storagesize);
        }
        return getStorageLength()
          .then((numberOfKeys) => {
            this.status.storagesize = numberOfKeys;
            this._baseLayer.fire('storagesize', this.status);
            return numberOfKeys;
          })
          .catch(() => 0);
      }

      getStorageSize(callback: Function) {
        this.setStorageSize().then((result) => {
          Iif (callback) {
            callback(result);
          }
        });
      }

      setLayer(layer: TileLayerOffline) {
        this._baseLayer = layer;
      }

      onAdd() {
        const container = DomUtil.create('div', 'savetiles leaflet-bar');
        const { options } = this;
        this._createButton(
          options.saveText,
          'savetiles',
          container,
          this._saveTiles,
        );
        this._createButton(options.rmText, 'rmtiles', container, this._rmTiles);
        return container;
      }

      _createButton(
        html: string,
        className: string,
        container: HTMLElement,
        fn: DomEvent.EventHandlerFn,
      ) {
        const link = DomUtil.create('a', className, container);
        link.innerHTML = html;
        link.href = '#';
        link.ariaRoleDescription = 'button';

        DomEvent.on(link, 'mousedown dblclick', DomEvent.stopPropagation)
          .on(link, 'click', DomEvent.stop)
          .on(link, 'click', fn, this)
          .on(link, 'click', this._refocusOnMap, this);

        return link;
      }

      _saveTiles() {
        const tiles = this._calculateTiles();
        this._resetStatus(tiles);
        const successCallback = async () => {
          this._baseLayer.fire('savestart', this.status);
          const loader = async (): Promise<void> => {
            const tile = tiles.shift();
            if (tile === undefined) {
              return Promise.resolve();
            }
            const blob = await this._loadTile(tile);
            if (blob) {
              await this._saveTile(tile, blob);
            }
            return loader();
          };
          const parallel = Math.min(tiles.length, this.options.parallel);
          for (let i = 0; i < parallel; i += 1) {
            loader();
          }
        };
        if (this.options.confirm) {
          this.options.confirm(this.status, successCallback);
        } else {
          successCallback();
        }
      }

      _calculateTiles() {
        let tiles: TileInfo[] = [];
        // minimum zoom to prevent the user from saving the whole world
        const minZoom = 5;
        // current zoom or zoom options
        let zoomlevels = [];

        if (this.options.saveWhatYouSee) {
          const currentZoom = this._map.getZoom();
          Iif (currentZoom < minZoom) {
            throw new Error(
              `It's not possible to save with zoom below level ${minZoom}.`,
            );
          }
          const { maxZoom } = this.options;

          for (let zoom = currentZoom; zoom <= maxZoom; zoom += 1) {
            zoomlevels.push(zoom);
          }
        } else {
          zoomlevels = this.options.zoomlevels || [this._map.getZoom()];
        }

        const latlngBounds = this.options.bounds || this._map.getBounds();

        for (let i = 0; i < zoomlevels.length; i += 1) {
          const area = bounds(
            this._map.project(latlngBounds.getNorthWest(), zoomlevels[i]),
            this._map.project(latlngBounds.getSouthEast(), zoomlevels[i]),
          );
          tiles = tiles.concat(this._baseLayer.getTileUrls(area, zoomlevels[i]));
        }
        return tiles;
      }

      _resetStatus(tiles: TileInfo[]) {
        this.status = {
          lengthLoaded: 0,
          lengthToBeSaved: tiles.length,
          lengthSaved: 0,
          _tilesforSave: tiles,
          storagesize: this.status.storagesize,
        };
      }

      async _loadTile(tile: TileInfo) {
        let blob;
        Iif (
          this.options.alwaysDownload === true ||
          (await hasTile(tile.key)) === false
        ) {
          blob = await downloadTile(tile.url);
        }

        this.status.lengthLoaded += 1;

        this._baseLayer.fire('loadtileend', this.status);
        Iif (this.status.lengthLoaded === this.status.lengthToBeSaved) {
          this._baseLayer.fire('loadend', this.status);
        }
        return blob;
      }

      async _saveTile(tile: TileInfo, blob: Blob): Promise<void> {
        await saveTile(tile, blob);
        this.status.lengthSaved += 1;
        this._baseLayer.fire('savetileend', this.status);
        if (this.status.lengthSaved === this.status.lengthToBeSaved) {
          this._baseLayer.fire('saveend', this.status);
          this.setStorageSize();
        }
      }

      _rmTiles() {
        const successCallback = () => {
          truncate().then(() => {
            this.status.storagesize = 0;
            this._baseLayer.fire('tilesremoved');
            this._baseLayer.fire('storagesize', this.status);
          });
        };
        Iif (this.options.confirmRemoval) {
          this.options.confirmRemoval(this.status, successCallback);
        } else {
          successCallback();
        }
      }
    }

    export function savetiles(
      baseLayer: TileLayerOffline,
      options: Partial<SaveTileOptions>,
    ) {
      return new ControlSaveTiles(baseLayer, options);
    }

    /**  @ts-ignore */
    if (window.L) {
      /**  @ts-ignore */
      window.L.control.savetiles = savetiles;
    }