2021-02-06 13:32:38 +11:00
|
|
|
import React, { useState, useRef, useContext } from "react";
|
2020-06-28 12:28:58 +10:00
|
|
|
import { omit, isEmpty } from "../helpers/shared";
|
2020-05-25 15:34:22 +10:00
|
|
|
|
|
|
|
const MapLoadingContext = React.createContext();
|
|
|
|
|
|
|
|
export function MapLoadingProvider({ children }) {
|
|
|
|
const [loadingAssetCount, setLoadingAssetCount] = useState(0);
|
|
|
|
|
|
|
|
function assetLoadStart() {
|
|
|
|
setLoadingAssetCount((prevLoadingAssets) => prevLoadingAssets + 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
function assetLoadFinish() {
|
|
|
|
setLoadingAssetCount((prevLoadingAssets) => prevLoadingAssets - 1);
|
|
|
|
}
|
|
|
|
|
2020-06-28 13:37:04 +10:00
|
|
|
const assetProgressRef = useRef({});
|
|
|
|
const loadingProgressRef = useRef(null);
|
2020-06-28 12:28:58 +10:00
|
|
|
function assetProgressUpdate({ id, count, total }) {
|
|
|
|
if (count === total) {
|
2020-06-28 13:37:04 +10:00
|
|
|
assetProgressRef.current = omit(assetProgressRef.current, [id]);
|
2020-06-28 12:28:58 +10:00
|
|
|
} else {
|
2020-06-28 13:37:04 +10:00
|
|
|
assetProgressRef.current = {
|
|
|
|
...assetProgressRef.current,
|
2020-06-28 12:28:58 +10:00
|
|
|
[id]: { count, total },
|
2020-06-28 13:37:04 +10:00
|
|
|
};
|
|
|
|
}
|
|
|
|
if (!isEmpty(assetProgressRef.current)) {
|
|
|
|
let total = 0;
|
|
|
|
let count = 0;
|
|
|
|
for (let progress of Object.values(assetProgressRef.current)) {
|
|
|
|
total += progress.total;
|
|
|
|
count += progress.count;
|
|
|
|
}
|
|
|
|
loadingProgressRef.current = count / total;
|
2020-06-28 12:28:58 +10:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-25 15:34:22 +10:00
|
|
|
const isLoading = loadingAssetCount > 0;
|
|
|
|
|
|
|
|
const value = {
|
|
|
|
assetLoadStart,
|
|
|
|
assetLoadFinish,
|
|
|
|
isLoading,
|
2020-06-28 12:28:58 +10:00
|
|
|
assetProgressUpdate,
|
2020-06-28 13:37:04 +10:00
|
|
|
loadingProgressRef,
|
2020-05-25 15:34:22 +10:00
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<MapLoadingContext.Provider value={value}>
|
|
|
|
{children}
|
|
|
|
</MapLoadingContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2021-02-06 13:32:38 +11:00
|
|
|
export function useMapLoading() {
|
|
|
|
const context = useContext(MapLoadingContext);
|
|
|
|
if (context === undefined) {
|
|
|
|
throw new Error("useMapLoading must be used within a MapLoadingProvider");
|
|
|
|
}
|
|
|
|
return context;
|
|
|
|
}
|
|
|
|
|
2020-05-25 15:34:22 +10:00
|
|
|
export default MapLoadingContext;
|