Skip to content

Commit

Permalink
Updated hooks for map load sensing
Browse files Browse the repository at this point in the history
  • Loading branch information
davenquinn committed May 26, 2024
1 parent 3ffe5af commit 2dc9991
Showing 1 changed file with 8 additions and 32 deletions.
40 changes: 8 additions & 32 deletions packages/mapbox-react/src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,26 @@
import { RefObject, useEffect, useRef } from "react";
import { RefObject, useEffect } from "react";
import mapboxgl from "mapbox-gl";
import { toggleMapLabelVisibility } from "@macrostrat/mapbox-utils";
import { useMapRef } from "./context";
import { useMapRef, useMapStatus } from "./context";

/** A newer and more flexible version of useMapConditionalStyle */
export function useMapStyleOperator(
operator: (map: mapboxgl.Map) => void,
dependencies: any[] = []
) {
const mapRef = useMapRef();
const isInitialized = useStyleInitialized();
const { isInitialized } = useMapStatus();
useEffect(() => {
const map = mapRef.current;
if (map == null) return;
if (map.isStyleLoaded()) {
if (isInitialized) {
operator(map);
}
const fn = () => operator(map);
return fn();
map.on("style.load", fn);
return () => {
map.off("style.load", fn);
};
}, [mapRef.current, isInitialized, ...dependencies]);
}

Expand Down Expand Up @@ -60,30 +63,3 @@ export function useMapLabelVisibility(
_toggleMapLabels
);
}

/** This function tracks whether a style has been loaded.
* This works around the fact that the isStyleLoaded method
* sometimes returns false even when the style has been loaded,
* resulting in the isStyleLoaded event not being fired.
*
* This may be related to the issue described here, which has
* apparently been fixed in recent Mapbox GL JS versions:
* https://github.com/mapbox/mapbox-gl-js/issues/8691
*/
export function useStyleInitialized() {
const mapRef = useMapRef();
const isInitialized = useRef<Boolean>();
useEffect(() => {
const map = mapRef.current;
if (map == null) return;
if (map.isStyleLoaded()) {
isInitialized.current = true;
}
const fn = () => (isInitialized.current = true);
map.on("style.load", fn);
return () => {
map.off("style.load", fn);
};
}, [mapRef.current]);
return isInitialized.current;
}

0 comments on commit 2dc9991

Please sign in to comment.