2020-05-25 01:34:22 -04:00
|
|
|
import React, { useState } from "react";
|
2020-06-27 22:28:58 -04:00
|
|
|
import { omit, isEmpty } from "../helpers/shared";
|
2020-05-25 01:34:22 -04: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-27 22:28:58 -04:00
|
|
|
const [assetProgress, setAssetProgress] = useState({});
|
|
|
|
function assetProgressUpdate({ id, count, total }) {
|
|
|
|
if (count === total) {
|
|
|
|
setAssetProgress(omit(assetProgress, [id]));
|
|
|
|
} else {
|
|
|
|
setAssetProgress((prevAssetProgress) => ({
|
|
|
|
...prevAssetProgress,
|
|
|
|
[id]: { count, total },
|
|
|
|
}));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-25 01:34:22 -04:00
|
|
|
const isLoading = loadingAssetCount > 0;
|
2020-06-27 22:28:58 -04:00
|
|
|
let loadingProgress = null;
|
|
|
|
if (!isEmpty(assetProgress)) {
|
|
|
|
let total = 0;
|
|
|
|
let count = 0;
|
|
|
|
for (let progress of Object.values(assetProgress)) {
|
|
|
|
total += progress.total;
|
|
|
|
count += progress.count;
|
|
|
|
}
|
|
|
|
loadingProgress = count / total;
|
|
|
|
}
|
2020-05-25 01:34:22 -04:00
|
|
|
|
|
|
|
const value = {
|
|
|
|
assetLoadStart,
|
|
|
|
assetLoadFinish,
|
|
|
|
isLoading,
|
2020-06-27 22:28:58 -04:00
|
|
|
assetProgressUpdate,
|
|
|
|
loadingProgress,
|
2020-05-25 01:34:22 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<MapLoadingContext.Provider value={value}>
|
|
|
|
{children}
|
|
|
|
</MapLoadingContext.Provider>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export default MapLoadingContext;
|