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

Snap To Rail #1027

Open
wants to merge 6 commits into
base: mtc-deploy
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
8 changes: 8 additions & 0 deletions lib/common/util/text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// @flow

import toLower from 'lodash/toLower'
import upperFirst from 'lodash/upperFirst'

export default function toSentenceCase (s: string): string {
return upperFirst(toLower(s))
}
18 changes: 9 additions & 9 deletions lib/editor/actions/map/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,17 +162,17 @@ export function handleControlPointDrag (
patternCoordinates: any
) {
return function (dispatch: dispatchFn, getState: getStateFn) {
const {avoidMotorways, currentDragId, followStreets} = getState().editor.editSettings.present
const {avoidMotorways, currentDragId, snapToOption} = getState().editor.editSettings.present
Copy link
Contributor

Choose a reason for hiding this comment

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

Could we call this followOption instead of snapToOption?

recalculateShape({
avoidMotorways,
controlPoints,
defaultToStraightLine: false,
dragId: currentDragId,
editType: 'update',
followStreets,
index,
newPoint: latlng,
patternCoordinates
patternCoordinates,
snapToOption
}).then(result => {
const {currentDragId} = getState().editor.editSettings.present
// If there is a dragId in the store and it matches the result, the user
Expand Down Expand Up @@ -204,17 +204,17 @@ export function handleControlPointDragEnd (
dispatch(controlPointDragOrEnd())

// recalculate shape for final position
const {avoidMotorways, followStreets} = getState().editor.editSettings.present
const {avoidMotorways, snapToOption} = getState().editor.editSettings.present
recalculateShape({
avoidMotorways,
controlPoints,
defaultToStraightLine: false,
editType: 'update',
index,
followStreets,
newPoint: latlng,
patternCoordinates,
snapControlPointToNewSegment: true
snapControlPointToNewSegment: true,
snapToOption
}).then(result => {
// const {updatedShapePoints: shapePoints, updatedControlPoints} = result
if (!result.coordinates) {
Expand Down Expand Up @@ -244,7 +244,7 @@ export function handleControlPointDragStart (controlPoint: ControlPoint) {

export function removeControlPoint (controlPoints: Array<ControlPoint>, index: number, pattern: Pattern, patternCoordinates: any) {
return async function (dispatch: dispatchFn, getState: getStateFn) {
const {avoidMotorways, followStreets} = getState().editor.editSettings.present
const {avoidMotorways, snapToOption} = getState().editor.editSettings.present
const {
coordinates,
updatedControlPoints
Expand All @@ -253,8 +253,8 @@ export function removeControlPoint (controlPoints: Array<ControlPoint>, index: n
controlPoints,
editType: 'delete',
index,
followStreets,
patternCoordinates
patternCoordinates,
snapToOption
})
// Update active pattern in store (does not save to server).
dispatch(updatePatternGeometry({
Expand Down
27 changes: 14 additions & 13 deletions lib/editor/actions/map/stopStrategies.js
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,10 @@ export function addStopAtInterval (latlng: LatLng, activePattern: Pattern, contr
}

export function addStopToPattern (pattern: Pattern, stop: GtfsStop, index?: ?number) {
// eslint-disable-next-line complexity
return async function (dispatch: dispatchFn, getState: getStateFn) {
const {data, editSettings} = getState().editor
const {avoidMotorways, followStreets} = editSettings.present
const {avoidMotorways, snapToOption} = editSettings.present
const {patternStops: currentPatternStops, shapePoints} = pattern
const patternStops = clone(currentPatternStops)
const {controlPoints, patternSegments} = getControlPoints(getState())
Expand Down Expand Up @@ -260,7 +261,7 @@ export function addStopToPattern (pattern: Pattern, stop: GtfsStop, index?: ?num
} else {
dispatch(updatePatternStops(pattern, patternStops))
// Otherwise, check if a shape ought to be created. Then, save.
if (patternStops.length === 2 && followStreets) {
if (patternStops.length === 2 && snapToOption) {
Copy link
Contributor

Choose a reason for hiding this comment

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

This is anticipating followStreets to be a boolean. To reduce accidental regressions maybe we leave followStreets as is and create a new variable followRail? I know it's clunkier but it lets us touch much less code

// Create shape between stops the added stop is the second one and
// followStreets is enabled. Otherwise, there is no need to create a
// new shape because it would just be a straight line segment anyways.
Expand All @@ -272,7 +273,7 @@ export function addStopToPattern (pattern: Pattern, stop: GtfsStop, index?: ?num
}
const points = [previousStop, stop]
.map((stop, index) => ({lng: stop.stop_lon, lat: stop.stop_lat}))
const patternSegments = await getPolyline(points, true, avoidMotorways)
const patternSegments = await getPolyline(points, true, avoidMotorways, snapToOption)
// Update pattern stops and geometry.
const controlPoints = controlPointsFromSegments(patternStops, patternSegments)
dispatch(updatePatternGeometry({controlPoints, patternSegments}))
Expand Down Expand Up @@ -335,11 +336,11 @@ export function addStopToPattern (pattern: Pattern, stop: GtfsStop, index?: ?num
controlPoints: clonedControlPoints,
defaultToStraightLine: false,
editType: 'update',
followStreets,
index: spliceIndex,
newPoint: {lng: stop.stop_lon, lat: stop.stop_lat},
snapControlPointToNewSegment: true,
patternCoordinates: clonedPatternSegments
patternCoordinates: clonedPatternSegments,
snapToOption
})
} catch (err) {
console.log(err)
Expand Down Expand Up @@ -376,11 +377,11 @@ export function addStopToPattern (pattern: Pattern, stop: GtfsStop, index?: ?num
controlPoints: clonedControlPoints,
defaultToStraightLine: false,
editType: 'update',
followStreets,
index,
newPoint: {lng: stop.stop_lon, lat: stop.stop_lat},
snapControlPointToNewSegment: true,
patternCoordinates: clonedPatternSegments
patternCoordinates: clonedPatternSegments,
snapToOption
})
} catch (err) {
console.log(err)
Expand All @@ -406,12 +407,12 @@ export function addStopToPattern (pattern: Pattern, stop: GtfsStop, index?: ?num
*/
function extendPatternToPoint (pattern, endPoint, newEndPoint, stop = null, splitInterval = 0) {
return async function (dispatch: dispatchFn, getState: getStateFn) {
const {avoidMotorways, followStreets} = getState().editor.editSettings.present
const {avoidMotorways, snapToOption} = getState().editor.editSettings.present
const {controlPoints, patternSegments} = getControlPoints(getState())
const clonedControlPoints = clone(controlPoints)
let newShape
if (followStreets) {
newShape = await getPolyline([endPoint, newEndPoint], false, avoidMotorways)
if (snapToOption) {
newShape = await getPolyline([endPoint, newEndPoint], false, avoidMotorways, snapToOption)
}
if (!newShape) {
// Get single coordinate for straight line if polyline fails or if not
Expand Down Expand Up @@ -503,16 +504,16 @@ export function removeStopFromPattern (pattern: Pattern, stop: GtfsStop, index:
// If pattern has no shape points, don't attempt to refactor pattern shape
console.log('pattern coordinates do not exist')
} else {
const {avoidMotorways, followStreets} = getState().editor.editSettings.present
const {avoidMotorways, snapToOption} = getState().editor.editSettings.present
let result
try {
result = await recalculateShape({
avoidMotorways,
controlPoints: clonedControlPoints,
editType: 'delete',
index: cpIndex,
followStreets,
patternCoordinates: clonedPatternSegments
patternCoordinates: clonedPatternSegments,
snapToOption
})
} catch (err) {
console.log(err)
Expand Down
26 changes: 20 additions & 6 deletions lib/editor/components/pattern/EditSettings.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import {Alert, Checkbox, Form, FormControl, ControlLabel} from 'react-bootstrap'
import Rcslider from 'rc-slider'

import {updateEditSetting} from '../../actions/active'
import {CLICK_OPTIONS} from '../../util'
import toSentenceCase from '../../../common/util/to-sentence-case'
import {CLICK_OPTIONS, SNAP_TO_OPTIONS} from '../../util'
import toSentenceCase from '../../../common/util/text'
import type {EditSettingsState} from '../../../types/reducers'

type Props = {
Expand Down Expand Up @@ -59,12 +59,11 @@ export default class EditSettings extends Component<Props, State> {
const {editSettings, patternSegment, updateEditSetting} = this.props
const {
editGeometry,
followStreets,
onMapClick,
stopInterval
stopInterval,
snapToOption
} = editSettings
const SETTINGS = [
{type: 'followStreets', label: 'Snap to streets'},
{type: 'avoidMotorways', label: 'Avoid highways in routing'},
{type: 'hideStopHandles', label: 'Hide stop handles'},
{type: 'hideInactiveSegments', label: 'Hide inactive segments'},
Expand All @@ -75,6 +74,21 @@ export default class EditSettings extends Component<Props, State> {
const noSegmentIsActive = !patternSegment && patternSegment !== 0
return (
<div>
<ControlLabel><small>Snap to options</small></ControlLabel>
<FormControl
componentClass='select'
value={snapToOption}
name={'snapToOption'}
onChange={this._onSelectChange}>
{SNAP_TO_OPTIONS.map(v => {
return (
<option
key={v}
value={v}>{toSentenceCase(v.replace(/_/g, ' '))}
Copy link
Contributor

Choose a reason for hiding this comment

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

You could avoid this by using an enum and then having a map from enum to string

Copy link
Contributor

Choose a reason for hiding this comment

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

with JS you could even have one large object that has both enum value and string!

</option>
)
})}
</FormControl>
{SETTINGS.map((s, i) => (
<Checkbox
checked={editSettings[s.type]}
Expand All @@ -83,7 +97,7 @@ export default class EditSettings extends Component<Props, State> {
// this state would cause the entire shape to disappear).
disabled={
(s.type === 'hideInactiveSegments' && noSegmentIsActive) ||
(s.type === 'avoidMotorways' && !followStreets)
(s.type === 'avoidMotorways' && snapToOption !== 'STREET')
Copy link
Contributor

@miles-grant-ibigroup miles-grant-ibigroup Mar 12, 2025

Choose a reason for hiding this comment

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

No magic strings! Let's use enums instead if we stick with snapToOption

}
name={s.type}
style={{margin: '3px 0'}}
Expand Down
10 changes: 5 additions & 5 deletions lib/editor/components/pattern/EditShapePanel.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ export default class EditShapePanel extends Component<Props> {
/**
* Construct new pattern geometry from the pattern stop locations.
*/
async drawPatternFromStops (pattern: Pattern, stopsCoordinates: Array<LatLng>, followStreets: boolean): Promise<any> {
async drawPatternFromStops (pattern: Pattern, stopsCoordinates: Array<LatLng>): Promise<any> {
const {editSettings, saveActiveGtfsEntity, setErrorMessage, updatePatternGeometry} = this.props
let patternSegments = []
if (followStreets) {
patternSegments = await getPolyline(stopsCoordinates, true, editSettings.present.avoidMotorways)
if (editSettings.present.snapToOption !== 'NONE') {
patternSegments = await getPolyline(stopsCoordinates, true, editSettings.present.avoidMotorways, editSettings.present.snapToOption)
} else {
// Construct straight-line segments using stop coordinates
stopsCoordinates
Expand Down Expand Up @@ -92,7 +92,7 @@ export default class EditShapePanel extends Component<Props> {
}

_generateShapeFromStops = () => {
const {activePattern, editSettings, stops} = this.props
const {activePattern, stops} = this.props
const stopLocations = stops && activePattern.patternStops && activePattern.patternStops.length
? activePattern.patternStops
.map((s, index) => {
Expand All @@ -104,7 +104,7 @@ export default class EditShapePanel extends Component<Props> {
return {lng: stop.stop_lon, lat: stop.stop_lat}
})
: []
this.drawPatternFromStops(activePattern, stopLocations, editSettings.present.followStreets)
this.drawPatternFromStops(activePattern, stopLocations)
Copy link
Contributor

Choose a reason for hiding this comment

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

Uh oh! I'm not sure followStreets was meant to be removed. Maybe let's keep followStreets as is and add a new boolean for followRail. It makes the UI work a bit more tricky but it helps us avoid touching too many files

}

_confirmCreateFromStops = () => {
Expand Down
11 changes: 8 additions & 3 deletions lib/editor/reducers/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export const defaultState = {
currentDragId: null,
distanceFromIntersection: 5,
editGeometry: false,
followStreets: true,
hideInactiveSegments: false,
intersectionStep: 2,
onMapClick: CLICK_OPTIONS[0],
Expand All @@ -29,6 +28,7 @@ export const defaultState = {
showStops: true,
showTooltips: true,
hideStopHandles: true,
snapToOption: 'NONE',
stopInterval: 400
}

Expand All @@ -49,7 +49,7 @@ export const reducers = {
...defaultState,
// Do not reset follow streets if exiting pattern editing.
// TODO: Are there other edit settings that should not be overridden?
followStreets: state.followStreets
snapToOption: state.snapToOption
}
},
'SETTING_ACTIVE_GTFS_ENTITY' (
Expand Down Expand Up @@ -96,6 +96,11 @@ export const reducers = {
action: ActionType<typeof updateEditSetting>
): EditSettingsState {
const {setting, value} = action.payload
return update(state, { [setting]: {$set: value} })
// RAIL-TODO: make sure followStreet is properly set.
// RAIL-TODO: use in a lot of places, make sure nothing breaks????
return update(state, {
[setting]: {$set: value},
followStreets: {$set: value === 'STREET'}
})
Comment on lines +99 to +104
Copy link
Contributor

Choose a reason for hiding this comment

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

Yes let's definitely leave followStreets alone

}
}
5 changes: 5 additions & 0 deletions lib/editor/util/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,11 @@ export const CLICK_OPTIONS: Array<string> = [
'ADD_STOPS_AT_INTERVAL',
'ADD_STOPS_AT_INTERSECTIONS'
]
export const SNAP_TO_OPTIONS: Array<string> = [
Copy link
Contributor

Choose a reason for hiding this comment

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

Why is this an array instead of an enum?

'NONE',
'STREET',
'RAIL'
]
export const YEAR_FORMAT: string = 'YYYY-MM-DD'
export const EXCEPTION_EXEMPLARS = {
MONDAY: 0,
Expand Down
29 changes: 17 additions & 12 deletions lib/editor/util/map.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// @flow

import ll from '@conveyal/lonlat'
import {divIcon} from 'leaflet'
import {Bounds, divIcon} from 'leaflet'
import clone from 'lodash/cloneDeep'
import fetch from 'isomorphic-fetch'
import distance from '@turf/distance'
Expand Down Expand Up @@ -44,11 +44,16 @@ type R5Response = {
}>
}

export const stopIsOutOfBounds = (stop: GtfsStop, bounds: any) => {
return stop.stop_lat > bounds.getNorth() ||
stop.stop_lat < bounds.getSouth() ||
stop.stop_lon > bounds.getEast() ||
stop.stop_lon < bounds.getWest()
export const coordIsOutOfBounds = (coords: LatLng, bounds: Bounds) => {
if (!coords || !coords.lat || !coords.lng || !bounds) return true

return coords.lat > bounds.getNorth() ||
coords.lat < bounds.getSouth() ||
coords.lng > bounds.getEast() ||
coords.lng < bounds.getWest()
}
export const stopIsOutOfBounds = (stop: GtfsStop, bounds: Bounds) => {
return coordIsOutOfBounds({lat: stop.stop_lat, lng: stop.stop_lon}, bounds)
}

export const getStopIcon = (
Expand Down Expand Up @@ -263,22 +268,22 @@ export async function recalculateShape ({
defaultToStraightLine = true,
dragId,
editType,
followStreets,
index,
newPoint,
patternCoordinates,
snapControlPointToNewSegment = false
snapControlPointToNewSegment = false,
snapToOption
}: {
avoidMotorways?: boolean,
controlPoints: Array<ControlPoint>,
defaultToStraightLine?: boolean,
dragId?: null | string,
editType: string,
followStreets: boolean,
index: number,
newPoint?: LatLng,
patternCoordinates: Array<Coordinates>,
snapControlPointToNewSegment?: boolean
snapControlPointToNewSegment?: boolean,
snapToOption: string
}): Promise<{
coordinates: ?Array<any>,
dragId?: ?string,
Expand Down Expand Up @@ -392,9 +397,9 @@ export async function recalculateShape ({
// calculate new segment (valhalla or straight line)
const newSegment = await getSegment(
pointsToRoute,
followStreets,
defaultToStraightLine,
avoidMotorways
avoidMotorways,
snapToOption
)
if (!newSegment || !newSegment.coordinates) {
// If new segment calculation is unsuccessful, return null for coordinates and
Expand Down
Loading
Loading