|
| 1 | +import throttle from 'lodash.throttle'; |
| 2 | +import { DebouncedFunc } from 'lodash'; |
| 3 | +import { |
| 4 | + ClickEvent, |
| 5 | + StartDraggingEvent, |
| 6 | + StopDraggingEvent, |
| 7 | + DraggingEvent, |
| 8 | + ModeProps, |
| 9 | +} from '../types'; |
| 10 | +import { LineString, FeatureCollection } from '../geojson-types'; |
| 11 | +import { getPickedEditHandle } from '../utils'; |
| 12 | +import { DrawLineStringMode } from './draw-line-string-mode'; |
| 13 | + |
| 14 | +type DragHandler = (event: DraggingEvent, props: ModeProps<FeatureCollection>) => void; |
| 15 | + |
| 16 | +type ThrottledDragHandler = DebouncedFunc<DragHandler>; |
| 17 | + |
| 18 | +export class DrawLineStringByDraggingMode extends DrawLineStringMode { |
| 19 | + handleDraggingThrottled: ThrottledDragHandler | DragHandler | null | undefined = null; |
| 20 | + |
| 21 | + // Override the default behavior of DrawLineStringMode to not add a point when the user clicks on the map |
| 22 | + handleClick(event: ClickEvent, props: ModeProps<FeatureCollection>) { |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + handleStartDragging(event: StartDraggingEvent, props: ModeProps<FeatureCollection>) { |
| 27 | + event.cancelPan(); |
| 28 | + if (props.modeConfig && props.modeConfig.throttleMs) { |
| 29 | + this.handleDraggingThrottled = throttle(this.handleDraggingAux, props.modeConfig.throttleMs); |
| 30 | + } else { |
| 31 | + this.handleDraggingThrottled = this.handleDraggingAux; |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + handleStopDragging(event: StopDraggingEvent, props: ModeProps<FeatureCollection>) { |
| 36 | + this.addClickSequence(event); |
| 37 | + const clickSequence = this.getClickSequence(); |
| 38 | + if (this.handleDraggingThrottled && 'cancel' in this.handleDraggingThrottled) { |
| 39 | + this.handleDraggingThrottled.cancel(); |
| 40 | + } |
| 41 | + |
| 42 | + if (clickSequence.length > 2) { |
| 43 | + const lineStringToAdd: LineString = { |
| 44 | + type: 'LineString', |
| 45 | + coordinates: clickSequence, |
| 46 | + }; |
| 47 | + |
| 48 | + this.resetClickSequence(); |
| 49 | + |
| 50 | + const editAction = this.getAddFeatureAction(lineStringToAdd, props.data); |
| 51 | + if (editAction) { |
| 52 | + props.onEdit(editAction); |
| 53 | + } |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + handleDraggingAux(event: DraggingEvent, props: ModeProps<FeatureCollection>) { |
| 58 | + const { picks } = event; |
| 59 | + const clickedEditHandle = getPickedEditHandle(picks); |
| 60 | + |
| 61 | + if (!clickedEditHandle) { |
| 62 | + // Don't add another point right next to an existing one. |
| 63 | + this.addClickSequence(event); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + handleDragging(event: DraggingEvent, props: ModeProps<FeatureCollection>) { |
| 68 | + if (this.handleDraggingThrottled) { |
| 69 | + this.handleDraggingThrottled(event, props); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments