All files / api/geolocation/src index.ts

95.23% Statements 20/21
100% Branches 4/4
90.9% Functions 10/11
100% Lines 16/16

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      19x 153x 19x 23x 23x     8x 9x       56x       11x 1x     10x 10x 6x 6x   4x 4x        
import { useSyncExternalStore } from "react";
 
let sharedDeviceLocation: readonly [number, number] | undefined;
const locationListeners = new Set<() => void>();
const getSharedDeviceLocation = () => sharedDeviceLocation;
const subscribeToDeviceLocation = (listener: () => void) => {
  locationListeners.add(listener);
  return () => { locationListeners.delete(listener); };
};
function updateSharedDeviceLocation(coordinates?: readonly [number, number]) {
  sharedDeviceLocation = coordinates;
  locationListeners.forEach(listener => listener());
}
 
export function useSharedDeviceLocation() {
  return useSyncExternalStore(subscribeToDeviceLocation, getSharedDeviceLocation, () => undefined);
}
 
export function geoLocateCurrentPosition(): Promise<GeolocationPosition> {
  if (!navigator.geolocation) {
    return Promise.reject(new Error("Geolocation is unavailable."));
  }
 
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(location => {
      updateSharedDeviceLocation([location.coords.longitude, location.coords.latitude]);
      resolve(location);
    }, error => {
      if (error.code === 1) updateSharedDeviceLocation();
      reject(error);
    }, { timeout: 15000 });
  });
}