Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ERA-7681] - Map Drawing Tools #725

Merged
merged 22 commits into from
Aug 16, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
95b8762
half-assed implementation of useDrawToolGeoJson hook for a PoC.
JoshuaVulcan Aug 2, 2022
4c7a435
map layer and source hooks. map draw tool data hooks. abstracting rul…
JoshuaVulcan Aug 4, 2022
045b1de
removing unused 'autocomplete line' geojson calc
JoshuaVulcan Aug 5, 2022
8a71a46
test planning. code simplification.
JoshuaVulcan Aug 5, 2022
d2b315d
breaking up combined component code. test files.
JoshuaVulcan Aug 5, 2022
a7b0d7c
upgrading to React 18.2.0
JoshuaVulcan Aug 8, 2022
7705bfa
test scaffolding, switching to direct map context usage for draw tool…
JoshuaVulcan Aug 8, 2022
91be1e8
context refactor for tests
JoshuaVulcan Aug 9, 2022
81234d7
goodbye Layer and Source. hello hooks. lots of code cleanup in paymen…
JoshuaVulcan Aug 10, 2022
5cd996c
using renderHook to test (and scaffold tests for) new custom map inte…
JoshuaVulcan Aug 11, 2022
d444c15
fixing sidebar test scaffolding for more consistent results. cleaning…
JoshuaVulcan Aug 11, 2022
30b52ee
PR feedback, test tweaks
JoshuaVulcan Aug 11, 2022
964d485
test coverage across the board
JoshuaVulcan Aug 11, 2022
ee0a97f
guard clause for optional method
JoshuaVulcan Aug 11, 2022
008f6fa
guard clause for optional method
JoshuaVulcan Aug 11, 2022
98d5d8c
removing test focus
JoshuaVulcan Aug 11, 2022
bf4670e
Merge branch 'develop' into ERA-7681
JoshuaVulcan Aug 11, 2022
101b815
merging up develop, resolving conflicts, PR feedback tweaks
JoshuaVulcan Aug 12, 2022
437326b
bootstrap update to fix broken dropdowns
JoshuaVulcan Aug 12, 2022
ee3ccf1
undoing accidental lib updates in the wrong branch :-)
JoshuaVulcan Aug 15, 2022
d228b94
toggling drawing mode feature flag back to line
JoshuaVulcan Aug 16, 2022
f5e1ff1
merging up develop, resolving conflicts
JoshuaVulcan Aug 16, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ REACT_APP_ROUTE_PREFIX=/
REACT_APP_BASE_MAP_STYLES='mapbox://styles/vjoelm/ciobuir0n0061bdnj1c54oakh?optimize=true'

# Feature flags
REACT_APP_ENABLE_PATROL_NEW_UI=false
REACT_APP_ENABLE_REPORT_NEW_UI=false
REACT_APP_ENABLE_PATROL_NEW_UI=true
REACT_APP_ENABLE_REPORT_NEW_UI=true
REACT_APP_ENABLE_GEOPERMISSION_UI=true
REACT_APP_ENABLE_EVENT_GEOMETRY=false
2 changes: 1 addition & 1 deletion .env.development
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
REACT_APP_DAS_HOST=https://develop.pamdas.org
REACT_APP_GA_TRACKING_ID=UA-12413928-16
REACT_APP_MOCK_EVENTS_API=true
REACT_APP_MOCK_EVENTS_API=false
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"humanize-duration": "^3.27.1",
"localforage": "^1.7.3",
"lodash-es": "^4.17.11",
"mapbox-gl": "^2.4.1",
"mapbox-gl": "^2.9.2",
"mb-isochrone": "^0.1.0",
"pluralize": "^8.0.0",
"prop-types": "^15.7.2",
Expand Down Expand Up @@ -110,7 +110,7 @@
],
"resolutions": {
"eslint-loader": "3.0.2",
"mapbox-gl": "2.4.1",
"mapbox-gl": "2.9.2",
"node-fetch": "2.6.7",
"immer": "9.0.6"
}
Expand Down
55 changes: 55 additions & 0 deletions src/MapDrawingTools/MapLayers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import React, { memo, useEffect } from 'react';

import { withMap } from '../EarthRangerMap';

import { useMapLayer, useMapSource } from '../hooks';

import { linePaint, lineLayout, circlePaint, fillLayout, fillPaint, symbolPaint, symbolLayout } from './layerStyles';

export const RULER_POINTS_LAYER_ID = 'RULER_POINTS_LAYER_ID';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why can't we reuse LAYER_IDS.POINTS for the ruler?


export const LAYER_IDS = {
POINTS: 'draw-layer-points',
LINES: 'draw-layer-lines',
LABELS: 'draw-layer-labels',
FILL: 'draw-layer-fill',
};

const SOURCE_IDS = {
LINE_SOURCE: 'map-line-source',
FILL_SOURCE: 'map-fill-source',
};

const MapDrawingLayers = (props) => {
const {
data,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think data is a good name for this prop. IT's very generic. Why not to receive instead:
{ drawnLineSegments, fillPolygon, map } ?
We could also not receive map as a prop and calculate it from context, cleaning up the cascade props a little, but this is just a suggestion and personal preference.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good suggestion -- I'm already in the process of contextifying everything so that works out 🙂

Data vs explicitly naming the properties...I have no strong preference, I thought it would be easier to just pass the full hook return value down rather than destructure and assign as individual props. I'll play with it.

map,
} = props;

useMapSource(SOURCE_IDS.LINE_SOURCE, data?.drawnLineSegments, { type: 'geojson' });
useMapSource(SOURCE_IDS.FILL_SOURCE, data?.fillPolygon, { type: 'geojson' });

const circleLayer = useMapLayer(LAYER_IDS.POINTS, 'circle', SOURCE_IDS.LINE_SOURCE, circlePaint);
useMapLayer(LAYER_IDS.LINES, 'line', SOURCE_IDS.LINE_SOURCE, linePaint, lineLayout);
useMapLayer(LAYER_IDS.LABELS, 'symbol', SOURCE_IDS.LINE_SOURCE, symbolPaint, symbolLayout);
useMapLayer(LAYER_IDS.FILL, 'fill', SOURCE_IDS.FILL_SOURCE, fillPaint, fillLayout);

useEffect(() => {
if (circleLayer) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we make sure that map is defined too?

const onCircleMouseEnter = () => map.getCanvas().style.cursor = 'pointer';
const onCircleMouseLeave = () => map.getCanvas().style.cursor = '';

map.on('mouseenter', LAYER_IDS.POINTS, onCircleMouseEnter);
JoshuaVulcan marked this conversation as resolved.
Show resolved Hide resolved
map.on('mouseleave', LAYER_IDS.POINTS, onCircleMouseLeave);

return () => {
map.off('mouseenter', LAYER_IDS.POINTS, onCircleMouseEnter);
map.off('mouseleave', LAYER_IDS.POINTS, onCircleMouseLeave);
};
}
}, [circleLayer, map]);

return null;
};

export default memo(withMap(MapDrawingLayers));
Empty file.
36 changes: 36 additions & 0 deletions src/MapDrawingTools/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { useMemo } from 'react';

import { DRAWING_MODES } from '.';
import { createLineSegmentGeoJsonForCoords, createFillPolygonForCoords } from './utils';

export const useDrawToolGeoJson = (points = [], cursorCoords = null, drawMode = DRAWING_MODES.POLYGON) => {
const drawnLinePoints = useMemo(() =>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Couldn't memoization costs add latency since the user may move the cursor fast?

Copy link
Collaborator Author

@JoshuaVulcan JoshuaVulcan Aug 9, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe so!

cursorCoords
? [...points, cursorCoords]
: [...points],
[points, cursorCoords]);

const shouldCalcPolygonData = drawMode === DRAWING_MODES.POLYGON && drawnLinePoints.length > 2;

const fillPolygonPoints = useMemo(() =>
shouldCalcPolygonData
? [...drawnLinePoints, drawnLinePoints.at(0)]
: null, [drawnLinePoints, shouldCalcPolygonData]);

const geoJsonObject = useMemo(() => {
if (drawnLinePoints.length < 2) return null;

const data = {
drawnLineSegments: createLineSegmentGeoJsonForCoords(drawnLinePoints),
};

if (fillPolygonPoints) {
data.fillPolygon = createFillPolygonForCoords(fillPolygonPoints);
}

return data;

}, [drawnLinePoints, fillPolygonPoints]);

return geoJsonObject;
};
Empty file.
144 changes: 144 additions & 0 deletions src/MapDrawingTools/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import React, { memo, Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Popup } from 'react-mapbox-gl';
import debounce from 'lodash/debounce';
import noop from 'lodash/noop';
import length from '@turf/length';
import PropTypes from 'prop-types';
import isEqual from 'react-fast-compare';

import { calcPositiveBearing } from '../utils/location';
import { withMap } from '../EarthRangerMap';

import { useDrawToolGeoJson } from '../MapDrawingTools/hooks';
import { useMapEventBinding } from '../hooks';

import styles from './styles.module.scss';
import MapLayers from './MapLayers';

import { LAYER_IDS } from './MapLayers';

export const RULER_POINTS_LAYER_ID = 'RULER_POINTS_LAYER_ID';

export const DRAWING_MODES = {
POLYGON: 'polygon',
LINE: 'line',
};

const MapDrawingTools = (props) => {
const {
children,
drawing = true,
drawingMode = DRAWING_MODES.POLYGON,
onChange = noop,
onClickPoint = noop,
onClickFill = noop,
points,
onClickLine = noop,
onClickLabel = noop,
} = props;

const [pointerLocation, setPointerLocation] = useState(null);

const cursorPopupCoords = useMemo(() => pointerLocation ? [pointerLocation.lng, pointerLocation.lat] : points[points.length - 1], [pointerLocation, points]);
const data = useDrawToolGeoJson(points, (drawing && cursorPopupCoords), drawingMode);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, I don't think data is a good name for this. We could follow the hook convention drawToolGeoJson, but honestly I'd rather receive the two properties spread: { drawnLineSegmentsGeoJson, fillPolygonGeoJson } so it's really clear what we are handling here.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I like it for the dataContainer, in passing up the data on eventing. for the MapLayers component I agree, it can be broken apart as props and passed explicitly. Will reactor.

const dataContainer = useRef(data);

const lineLength = useMemo(() => {
if (!data?.drawnLineSegments) return null;

return `${length(data.drawnLineSegments).toFixed(2)}km`;
}, [data?.drawnLineSegments]);

const showLayer = pointerLocation || points.length;

const onMapClick = useCallback(debounce((e) => {
const { lngLat } = e;
e.preventDefault();
e.originalEvent.stopPropagation();
onChange([...points, [lngLat.lng, lngLat.lat]], dataContainer.current);
}, 100), [onChange, points]);


const onMapDblClick = useCallback((e) => {
onMapClick(e);

e.preventDefault();
e.originalEvent.stopPropagation();
onMapClick.cancel();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What does this cancel do?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This ensures we don't have funny sync-related issues where a second click fires. It's ported over from the existing ruler code


}, [onMapClick]);

const onMouseMove = useCallback((e) => {
setPointerLocation(e.lngLat);
}, []);

useMapEventBinding('click', onClickLine, LAYER_IDS.LINES);
useMapEventBinding('click', onClickPoint, LAYER_IDS.POINTS);
useMapEventBinding('click', onClickLabel, LAYER_IDS.LABELS);
useMapEventBinding('click', onClickFill, LAYER_IDS.FILL);

useMapEventBinding('mousemove', onMouseMove, null, drawing);
useMapEventBinding('dblclick', onMapDblClick, null, drawing);
useMapEventBinding('click', onMapClick, null, drawing);

useEffect(() => {
dataContainer.current = data;
}, [dataContainer, data]);

if (!showLayer) return null;

return <>
{drawing && <CursorPopup coords={cursorPopupCoords} lineLength={lineLength} points={points} />}
<MapLayers data={data} />
{children}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see the purpose of supporting children here if we are not going to wrap them.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For ❇️ the future ❇️ but it's trivial to add/remove

</>;
};

export default memo(withMap(MapDrawingTools));

PropTypes.propTypes = {
points: PropTypes.array,
};

const CursorPopup = (props) => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it would be cleaner to have this one in its own file, with its own tests and all. What do you think?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep!

const { coords, points, lineLength } = props;

const popupClassName = `${styles.popup} ${styles.notDone}`;
const popupOffset = [-8, 0];
const popupAnchorPosition = 'right';

const popupLocationAndPreviousPointAreIdentical = isEqual(coords, points[points.length - 1]);
const showPromptForSecondPoint = popupLocationAndPreviousPointAreIdentical && points.length === 1;
return <Popup className={popupClassName} offset={popupOffset} coordinates={coords} anchor={popupAnchorPosition}>
{points.length === 0 && <p>Click to start</p>}
{!!points.length && <Fragment>
{showPromptForSecondPoint && <div>
<p>Select another point</p>
</div>}
{!showPromptForSecondPoint && <Fragment>
<p>Bearing: {calcPositiveBearing(points[points.length - 1], coords).toFixed(2)}&deg;</p>
<p>Distance: {lineLength}</p>
{!!points.length && <>
<small>Click to add a point.<br />Hit &quot;enter&quot; or &quot;return&quot; to complete.</small>
</>}
</Fragment>}
</Fragment>}
</Popup>;
};

/*
points,
drawing,
drawingMode,
onChange
onComplete
onClickPoint
onClickFill
onClickLine
onClickLabel
*/


/* how to show popup when completed
how to show popup when clicking individual point
*/
Empty file.
33 changes: 33 additions & 0 deletions src/MapDrawingTools/layerStyles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { DEFAULT_SYMBOL_PAINT } from '../constants';

export const linePaint = {
'line-color': 'orange',
'line-dasharray': [2, 4],
'line-width': 2,
};

export const lineLayout = {
'line-join': 'round',
'line-cap': 'round',
};

export const symbolLayout = {
'text-allow-overlap': true,
'icon-allow-overlap': true,
'symbol-placement': 'line-center',
'text-font': ['Open Sans Regular'],
'text-field': ['get', 'lengthLabel'],
};

export const symbolPaint = {
...DEFAULT_SYMBOL_PAINT,
'text-halo-width': 2,
};

export const circlePaint = {
'circle-radius': 5,
'circle-color': 'orange',
};

export const fillLayout = { visibility: 'visible' };
export const fillPaint = { 'fill-color': 'red', 'fill-opacity': 0.4 };
25 changes: 25 additions & 0 deletions src/MapDrawingTools/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { lineString, polygon } from '@turf/helpers';
import length from '@turf/length';
import lineSegment from '@turf/line-segment';

export const createLineSegmentGeoJsonForCoords = (coords) => {
const lineSegments = lineSegment(lineString(coords));

lineSegments.features = lineSegments.features.map(feature => {
const lineLength = length(feature);
const lengthLabel = `${lineLength.toFixed(2)}km`;

return {
...feature,
properties: {
...feature.properties,
length: lineLength,
lengthLabel,
}
};
});

return lineSegments;
};

export const createFillPolygonForCoords = (coords) => polygon([coords]);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we have this trivial method just to keep it in utils with createLineSegmentGeoJsonForCoords even though it seems unnecessary. I'd just mention that it would be great to follow the same name convention, we are missing GeoJson here

Empty file.
Loading