All files TileManager.ts

98.24% Statements 56/57
81.81% Branches 9/11
100% Functions 15/15
98.14% Lines 53/54

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                                                3x 3x       69x 66x   3x   1x 1x   1x 1x     1x 1x       3x                     14x 14x                         3x 3x 3x                     2x 2x 1x   1x                       14x 14x             193x             16x 16x     16x 16x   16x 31x 91x     16x                                         1x       1x 1x       1x         1x 1x       1x                                   1x             1x 1x             1x   1x       14x 14x 14x             22x       12x 12x 11x   1x 1x    
/**
 * Api methods used in control and layer
 * For advanced usage
 *
 * @module TileManager
 *
 */
 
import { Bounds, Browser, CRS, Point, Util } from 'leaflet';
import { openDB, deleteDB, IDBPDatabase } from 'idb';
import { FeatureCollection, Polygon } from 'geojson';
 
export type TileInfo = {
  key: string;
  url: string;
  urlTemplate: string;
  x: number;
  y: number;
  z: number;
  createdAt: number;
};
 
export type StoredTile = TileInfo & { blob: Blob };
 
const tileStoreName = 'tileStore';
const urlTemplateIndex = 'urlTemplate';
let dbPromise: Promise<IDBPDatabase> | undefined;
 
export function openTilesDataBase(): Promise<IDBPDatabase> {
  if (dbPromise) {
    return dbPromise;
  }
  dbPromise = openDB('leaflet.offline', 2, {
    upgrade(db, oldVersion) {
      deleteDB('leaflet_offline');
      deleteDB('leaflet_offline_areas');
 
      if (oldVersion < 1) {
        const tileStore = db.createObjectStore(tileStoreName, {
          keyPath: 'key',
        });
        tileStore.createIndex(urlTemplateIndex, 'urlTemplate');
        tileStore.createIndex('z', 'z');
      }
    },
  });
  return dbPromise;
}
 
/**
 * @example
 * ```js
 * import { getStorageLength } from 'leaflet.offline'
 * getStorageLength().then(i => console.log(i + 'tiles in storage'))
 * ```
 */
export async function getStorageLength(): Promise<number> {
  const db = await openTilesDataBase();
  return db.count(tileStoreName);
}
 
/**
 * @example
 * ```js
 * import { getStorageInfo } from 'leaflet.offline'
 * getStorageInfo('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png')
 * ```
 */
export async function getStorageInfo(
  urlTemplate: string,
): Promise<StoredTile[]> {
  const range = IDBKeyRange.only(urlTemplate);
  const db = await openTilesDataBase();
  return db.getAllFromIndex(tileStoreName, urlTemplateIndex, range);
}
 
/**
 * @example
 * ```js
 * import { downloadTile } from 'leaflet.offline'
 * downloadTile(tileInfo.url).then(blob => saveTile(tileInfo, blob))
 * ```
 */
export async function downloadTile(tileUrl: string): Promise<Blob> {
  const response = await fetch(tileUrl);
  if (!response.ok) {
    throw new Error(`Request failed with status ${response.statusText}`);
  }
  return response.blob();
}
/**
 * @example
 * ```js
 * saveTile(tileInfo, blob).then(() => console.log(`saved tile from ${tileInfo.url}`))
 * ```
 */
export async function saveTile(
  tileInfo: TileInfo,
  blob: Blob,
): Promise<IDBValidKey> {
  const db = await openTilesDataBase();
  return db.put(tileStoreName, {
    blob,
    ...tileInfo,
  });
}
 
export function getTileUrl(urlTemplate: string, data: any): string {
  return Util.template(urlTemplate, {
    ...data,
    r: Browser.retina ? '@2x' : '',
  });
}
 
export function getTilePoints(area: Bounds, tileSize: Point): Point[] {
  const points: Point[] = [];
  Iif (!area.min || !area.max) {
    return points;
  }
  const topLeftTile = area.min.divideBy(tileSize.x).floor();
  const bottomRightTile = area.max.divideBy(tileSize.x).floor();
 
  for (let j = topLeftTile.y; j <= bottomRightTile.y; j += 1) {
    for (let i = topLeftTile.x; i <= bottomRightTile.x; i += 1) {
      points.push(new Point(i, j));
    }
  }
  return points;
}
/**
 * Get a geojson of tiles from one resource
 *
 * @example
 * const urlTemplate = 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
 * const getGeoJsonData = () => LeafletOffline.getStorageInfo(urlTemplate)
 *  .then((data) => LeafletOffline.getStoredTilesAsJson(baseLayer, data));
 *
 * getGeoJsonData().then((geojson) => {
 *   storageLayer = L.geoJSON(geojson).bindPopup(
 *     (clickedLayer) => clickedLayer.feature.properties.key,
 *   );
 * });
 *
 */
export function getStoredTilesAsJson(
  tileSize: { x: number; y: number },
  tiles: TileInfo[],
): FeatureCollection<Polygon> {
  const featureCollection: FeatureCollection<Polygon> = {
    type: 'FeatureCollection',
    features: [],
  };
  for (let i = 0; i < tiles.length; i += 1) {
    const topLeftPoint = new Point(
      tiles[i].x * tileSize.x,
      tiles[i].y * tileSize.y,
    );
    const bottomRightPoint = new Point(
      topLeftPoint.x + tileSize.x,
      topLeftPoint.y + tileSize.y,
    );
 
    const topLeftlatlng = CRS.EPSG3857.pointToLatLng(topLeftPoint, tiles[i].z);
    const botRightlatlng = CRS.EPSG3857.pointToLatLng(
      bottomRightPoint,
      tiles[i].z,
    );
    featureCollection.features.push({
      type: 'Feature',
      properties: tiles[i],
      geometry: {
        type: 'Polygon',
        coordinates: [
          [
            [topLeftlatlng.lng, topLeftlatlng.lat],
            [botRightlatlng.lng, topLeftlatlng.lat],
            [botRightlatlng.lng, botRightlatlng.lat],
            [topLeftlatlng.lng, botRightlatlng.lat],
            [topLeftlatlng.lng, topLeftlatlng.lat],
          ],
        ],
      },
    });
  }
 
  return featureCollection;
}
 
/**
 * Remove tile by key
 */
export async function removeTile(key: string): Promise<void> {
  const db = await openTilesDataBase();
  return db.delete(tileStoreName, key);
}
 
/**
 * Get single tile blob
 */
export async function getBlobByKey(key: string): Promise<Blob> {
  return (await openTilesDataBase())
    .get(tileStoreName, key)
    .then((result) => result && result.blob);
}
 
export async function hasTile(key: string): Promise<boolean> {
  const db = await openTilesDataBase();
  const result = await db.getKey(tileStoreName, key);
  return result !== undefined;
}
 
/**
 * Remove everything
 */
export async function truncate(): Promise<void> {
  return (await openTilesDataBase()).clear(tileStoreName);
}
 
export async function getTileImageSource(key: string, url: string) {
  const shouldUseUrl = !(await hasTile(key));
  if (shouldUseUrl) {
    return url;
  }
  const blob = await getBlobByKey(key);
  return URL.createObjectURL(blob);
}