Skip to content

Commit

Permalink
front: add filter for signaling systems url
Browse files Browse the repository at this point in the history
  • Loading branch information
Akctarus authored and SharglutDev committed Jan 31, 2024
1 parent 74c1276 commit ff17ab1
Showing 1 changed file with 50 additions and 11 deletions.
61 changes: 50 additions & 11 deletions front/src/common/Map/Layers/blankStyle.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,63 @@
import { MapProps } from 'react-map-gl/maplibre';
import { MAIN_API } from 'config/config';
import { useMemo } from 'react';
import { useEffect, useMemo, useState } from 'react';
import { osrdEditoastApi } from 'common/api/osrdEditoastApi';

type Sprite = { url: string; id: string };

const isValidUrl = async (url: string) => {
const checkValidity = async (extension: string) => {
try {
const response = await fetch(`${url}.${extension}`);
return response.ok;
} catch (error) {
return false;
}
};
return (await checkValidity('json')) && checkValidity('png');
};

export const useMapBlankStyle = (): MapProps['mapStyle'] => {
const baseURL = MAIN_API.proxy_editoast;

const { data: signalingSystems } =
osrdEditoastApi.endpoints.getSpritesSignalingSystems.useQuery();

const getSpriteData = async () => {
if (!signalingSystems) return [];

const ponctualObjectsSprites: Sprite = {
url: 'https://static.osm.osrd.fr/sprites/sprites',
id: 'default',
};
const isDefaultSpriteValid = await isValidUrl(ponctualObjectsSprites.url);

const sprites: (Sprite | null)[] = await Promise.all([
isDefaultSpriteValid ? ponctualObjectsSprites : null,
...signalingSystems.map(async (id) => {
const signalingSystemsURL = `${window.location.origin}${baseURL}/sprites/${id}/sprites`;
const isValid = await isValidUrl(signalingSystemsURL);
return isValid ? { url: signalingSystemsURL, id } : null;
}),
]);

return sprites.filter((sprite) => sprite !== null) as Sprite[];
};

const [validSprites, setValidSprites] = useState<Sprite[]>([]);

useEffect(() => {
const fetchData = async () => {
if (signalingSystems) {
const spriteData = await getSpriteData();
setValidSprites(spriteData);
}
};
fetchData();
}, [signalingSystems]);

const props = useMemo(() => {
const sprite = signalingSystems
? [
{ url: 'https://static.osm.osrd.fr/sprites/sprites', id: 'default' },
...signalingSystems.map((id) => ({
url: `${window.location.origin}${baseURL}/sprites/${id}/sprites`,
id,
})),
]
: [];
const sprite = validSprites;
return {
version: 8,
name: 'Blank',
Expand All @@ -35,7 +74,7 @@ export const useMapBlankStyle = (): MapProps['mapStyle'] => {
},
],
} as MapProps['mapStyle'];
}, [signalingSystems]);
}, [validSprites]);

return props;
};
Expand Down

0 comments on commit ff17ab1

Please sign in to comment.