Skip to content

Commit

Permalink
refactor: move marker fetching to map
Browse files Browse the repository at this point in the history
  • Loading branch information
Rupert Redington authored and Rupert Redington committed Nov 22, 2021
1 parent 689609c commit 0cf3266
Show file tree
Hide file tree
Showing 8 changed files with 90 additions and 128 deletions.
59 changes: 18 additions & 41 deletions src/components/LooMap/LooMap.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import { useMemo } from 'react';
import { useRouter } from 'next/router';
import { MapContainer, TileLayer, Marker, ZoomControl } from 'react-leaflet';
import { MapContainer, TileLayer, ZoomControl } from 'react-leaflet';
import 'leaflet/dist/leaflet.css';
import { css } from '@emotion/react';
import Box from '../Box';
import ToiletMarkerIcon from './ToiletMarkerIcon';
import LocateMapControl from './LocateMapControl';
import { Media } from '../Media';
import Markers from './Markers';
import { Loo } from '../../api-client/graphql';
interface Props {
focus?: Loo;
center: { lat: number; lng: number };
zoom?: number;
minZoom?: number;
maxZoom?: number;
staticMap?: boolean;
onViewportChanged?: () => void;
controlsOffset?: number;
showCrosshair?: boolean;
withAccessibilityOverlays?: boolean;
}

const KEY_ENTER = 13;

const LooMap = ({
loos = [],
const LooMap: React.FC<Props> = ({
focus,
showCrosshair,
controlsOffset = 0,
center,
Expand All @@ -21,38 +30,6 @@ const LooMap = ({
staticMap = false,
}) => {
const router = useRouter();
const memoizedMarkers = useMemo(
() =>
loos.map((toilet) => (
<Marker
key={toilet.id}
position={toilet.location}
zIndexOffset={toilet.isHighlighted ? 1000 : 0}
icon={
new ToiletMarkerIcon({
isHighlighted: toilet.isHighlighted,
toiletId: toilet.id,
isUseOurLoosCampaign: toilet.campaignUOL,
})
}
label={toilet.name || 'Unnamed toilet'}
eventHandlers={{
click: () => {
if (!staticMap) {
router.push(`/loos/${toilet.id}`);
}
},
keydown: (event: { originalEvent: { keyCode: number } }) => {
if (!staticMap && event.originalEvent.keyCode === KEY_ENTER) {
router.push(`/loos/${toilet.id}`);
}
},
}}
keyboard={false}
/>
)),
[loos, staticMap, router]
);

return (
<Box
Expand Down Expand Up @@ -138,7 +115,7 @@ const LooMap = ({
minZoom={minZoom}
maxZoom={maxZoom}
/>
{memoizedMarkers}
<Markers focus={focus} />
<Media greaterThan="md">
<ZoomControl position="bottomright" />
</Media>
Expand Down
23 changes: 0 additions & 23 deletions src/components/LooMap/Marker.tsx

This file was deleted.

68 changes: 68 additions & 0 deletions src/components/LooMap/Markers.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { useMemo, useCallback } from 'react';
import { useRouter } from 'next/router';
import { useFindLoosNearbyQuery } from '../../api-client/graphql';
import { Marker, useMapEvents, useMap } from 'react-leaflet';
import ToiletMarkerIcon from './ToiletMarkerIcon';

const KEY_ENTER = 13;

function mapToFindVars(map) {
return {
lat: map.getCenter().lat,
lng: map.getCenter().lng,
radius: Math.ceil(
map.getBounds().getNorthEast().distanceTo(map.getCenter())
),
};
}

const Markers = ({ focus }) => {
const router = useRouter();
const map = useMap();

const { data, refetch } = useFindLoosNearbyQuery({
variables: {
...mapToFindVars(map),
},
});

useMapEvents({
moveend: () => refetch(mapToFindVars(map)),
});

const memoizedMarkers = useMemo(() => {
if (!data?.loosByProximity) {
return null;
}
return data.loosByProximity.map((toilet) => (
<Marker
key={toilet.id}
position={toilet.location}
zIndexOffset={toilet.id === focus?.id ? 1000 : 0}
icon={
new ToiletMarkerIcon({
isHighlighted: toilet.id === focus?.id,
toiletId: toilet.id,
isUseOurLoosCampaign: toilet.campaignUOL,
})
}
alt={toilet.name || 'Unnamed toilet'}
eventHandlers={{
click: () => {
router.push(`/loos/${toilet.id}`);
},
keydown: (event: { originalEvent: { keyCode: number } }) => {
if (event.originalEvent.keyCode === KEY_ENTER) {
router.push(`/loos/${toilet.id}`);
}
},
}}
keyboard={false}
/>
));
}, [data, router, focus]);

return <>{memoizedMarkers}</>;
};

export default Markers;
2 changes: 1 addition & 1 deletion src/components/LooMap/ToiletMarkerIcon.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const ToiletMarkerIcon = L.DivIcon.extend({
initialize: function (options: {
isHighlighted: any;
toiletId?: any;
isUseOurLoosCampaign?: any;
isUseOurLoosCampaign: any;
}) {
this.options = {
...this.options,
Expand Down
12 changes: 1 addition & 11 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import config from '../config';
import { useRouter } from 'next/router';
import { withApollo } from '../components/withApollo';
import { NextPage } from 'next';
import { useFindLoosNearbyQuery } from '../api-client/graphql';
import useFilters from '../hooks/useFilters';

const SIDEBAR_BOTTOM_MARGIN = 32;
Expand All @@ -26,15 +25,7 @@ const HomePage = () => {
const { message } = router.query;
const [mapState, setMapState] = useMapState();

const { data } = useFindLoosNearbyQuery({
variables: {
lat: mapState.center.lat,
lng: mapState.center.lng,
radius: Math.ceil(mapState.radius),
},
});

const { filters, filtered, setFilters } = useFilters(data?.loosByProximity);
const { filters, filtered, setFilters } = useFilters([]);

const pageTitle = config.getTitle('Home');

Expand Down Expand Up @@ -72,7 +63,6 @@ const HomePage = () => {
</Box>

<LooMap
loos={filtered}
center={mapState.center}
zoom={mapState.zoom}
onViewportChanged={setMapState}
Expand Down
16 changes: 0 additions & 16 deletions src/pages/loos/[id]/edit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import Box from '../../../components/Box';
import Login from '../../../components/Login';

import config from '../../../config';
import useNearbyLoos from '../../../hooks/useNearbyLoos';
import { useMapState } from '../../../components/MapState';

import dynamic from 'next/dynamic';
Expand Down Expand Up @@ -59,12 +58,6 @@ const EditPage = (props: { match: { params: { id?: string } } }) => {
}
}, [looLocation, setMapState]);

const { data } = useNearbyLoos({
lat: mapState.center.lat,
lng: mapState.center.lng,
radius: mapState.radius,
});

// local state mapCenter to get fix issues with react-leaflet not being stateless and lat lng rounding issues
const [mapCenter, setMapCenter] = useState({ lat: 0, lng: 0 });

Expand Down Expand Up @@ -167,21 +160,12 @@ const EditPage = (props: { match: { params: { id?: string } } }) => {

<Box display="flex" height="40vh">
<LooMap
loos={getLoosToDisplay()}
center={mapState.center}
zoom={mapState.zoom}
minZoom={config.editMinZoom}
showCenter
showContributor
showLocateControl
showCrosshair
controlsOffset={20}
withAccessibilityOverlays={false}
onViewportChanged={(mapPosition: {
center: (prevState: undefined) => undefined;
}) => {
setMapCenter(mapPosition.center);
}}
/>
</Box>

Expand Down
26 changes: 2 additions & 24 deletions src/pages/loos/[id]/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ import { useRouter } from 'next/router';
import { withApollo } from '../../../components/withApollo';
import { GetServerSideProps, GetStaticPaths } from 'next';
import useFilters from '../../../hooks/useFilters';
import { useFindLoosNearbyQuery } from '../../../api-client/graphql';
import { ssrFindLooById, PageFindLooByIdComp } from '../../../api-client/page';

const SIDEBAR_BOTTOM_MARGIN = 32;
Expand All @@ -29,27 +28,7 @@ const LooPage: PageFindLooByIdComp = (props) => {
const router = useRouter();
const { id, message } = router.query;

const { data: nearbyLoos } = useFindLoosNearbyQuery({
variables: {
lat: loo.location.lat,
lng: loo.location.lng,
radius: Math.ceil(mapState.radius),
},
skip: !loo,
});

const { filters, filtered, setFilters } = useFilters(
nearbyLoos?.loosByProximity
);

const markers = useMemo(() => {
if (!loo) {
return [];
}
let list = filtered ? filtered.filter((l) => l.id !== loo.id) : [];
list.push({ ...loo, isHighlighted: true });
return list;
}, [loo, filtered]);
const { filters, filtered, setFilters } = useFilters([]);

// set initial map center to toilet if on /loos/:id
// React.useEffect(() => {
Expand Down Expand Up @@ -103,10 +82,9 @@ const LooPage: PageFindLooByIdComp = (props) => {
</Box>

<LooMap
loos={markers}
focus={loo}
center={mapState.center}
zoom={mapState.zoom}
onViewportChanged={setMapState}
controlsOffset={toiletPanelDimensions.height}
/>

Expand Down
12 changes: 0 additions & 12 deletions src/pages/loos/add.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import LocationSearch from '../../components/LocationSearch';
import Login from '../../components/Login';

import { useMapState } from '../../components/MapState';
import useNearbyLoos from '../../hooks/useNearbyLoos';

import config from '../../config';
import dynamic from 'next/dynamic';
Expand Down Expand Up @@ -40,12 +39,6 @@ const AddPage = (props) => {
const { user, error, isLoading } = useUser();
const [mapState, setMapState] = useMapState();

const { data } = useNearbyLoos({
lat: mapState.center.lat,
lng: mapState.center.lng,
radius: mapState.radius,
});

const router = useRouter();

const { lat, lng } = router.query;
Expand Down Expand Up @@ -103,14 +96,9 @@ const AddPage = (props) => {

<Box position="relative" display="flex" height="40vh">
<LooMap
loos={data}
center={mapState.center}
zoom={mapState.zoom}
minZoom={config.editMinZoom}
showCenter
showContributor
showSearchControl
showLocateControl
showCrosshair
controlsOffset={20}
withAccessibilityOverlays={false}
Expand Down

0 comments on commit 0cf3266

Please sign in to comment.