fixed map clicks on sticker drag

This commit is contained in:
Fedor Katurov 2020-01-09 12:44:25 +07:00
parent 67eeaa7293
commit 7bdf07cae5
7 changed files with 150 additions and 141 deletions

View file

@ -1,25 +1,20 @@
import React from 'react'; import React, { FC } from 'react';
import { Icon } from '~/components/panels/Icon'; import { Icon } from '~/components/panels/Icon';
import * as EDITOR_ACTIONS from '~/redux/editor/actions' import * as EDITOR_ACTIONS from '~/redux/editor/actions';
import classnames from "classnames"; import classnames from 'classnames';
import { connect } from 'react-redux';
import { selectEditor } from '~/redux/editor/selectors';
type Props = { const noPoints = ({
routerPoints: number, editorRouterCancel,
width: number, }: {
is_routing: boolean, editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel;
}) => (
editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel,
editorRouterSubmit: typeof EDITOR_ACTIONS.editorRouterSubmit,
}
const noPoints = ({ editorRouterCancel }: { editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel }) => (
<React.Fragment> <React.Fragment>
<div className="helper router-helper"> <div className="helper router-helper">
<div className="helper__text"> <div className="helper__text">
<Icon icon="icon-pin-1" /> <Icon icon="icon-pin-1" />
<div className="big white upper"> <div className="big white upper">Укажите первую точку на карте</div>
Укажите первую точку на карте
</div>
</div> </div>
</div> </div>
<div className="helper router-helper"> <div className="helper router-helper">
@ -33,7 +28,11 @@ const noPoints = ({ editorRouterCancel }: { editorRouterCancel: typeof EDITOR_AC
</React.Fragment> </React.Fragment>
); );
const firstPoint = ({ editorRouterCancel }: { editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel }) => ( const firstPoint = ({
editorRouterCancel,
}: {
editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel;
}) => (
<React.Fragment> <React.Fragment>
<div className="helper router-helper"> <div className="helper router-helper">
<div className="helper__text"> <div className="helper__text">
@ -53,10 +52,11 @@ const firstPoint = ({ editorRouterCancel }: { editorRouterCancel: typeof EDITOR_
); );
const draggablePoints = ({ const draggablePoints = ({
editorRouterCancel, editorRouterSubmit editorRouterCancel,
editorRouterSubmit,
}: { }: {
editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel, editorRouterCancel: typeof EDITOR_ACTIONS.editorRouterCancel;
editorRouterSubmit: typeof EDITOR_ACTIONS.editorRouterSubmit, editorRouterSubmit: typeof EDITOR_ACTIONS.editorRouterSubmit;
}) => ( }) => (
<React.Fragment> <React.Fragment>
<div className="helper"> <div className="helper">
@ -79,9 +79,23 @@ const draggablePoints = ({
</React.Fragment> </React.Fragment>
); );
export const RouterDialog = ({ const mapStateToProps = state => ({
routerPoints, editorRouterCancel, editorRouterSubmit, width, is_routing, editor: selectEditor(state),
}: Props) => ( });
const mapDispatchToProps = {
editorRouterCancel: EDITOR_ACTIONS.editorRouterCancel,
editorRouterSubmit: EDITOR_ACTIONS.editorRouterSubmit,
};
type Props = ReturnType<typeof mapStateToProps> & typeof mapDispatchToProps & { width?: number };
const RouterDialogUnconnected: FC<Props> = ({
editor: { routerPoints, is_routing },
editorRouterCancel,
editorRouterSubmit,
width,
}) => (
<div className="control-dialog" style={{ width }}> <div className="control-dialog" style={{ width }}>
<div className={classnames('save-loader', { active: is_routing })} /> <div className={classnames('save-loader', { active: is_routing })} />
@ -90,3 +104,7 @@ export const RouterDialog = ({
{routerPoints >= 2 && draggablePoints({ editorRouterCancel, editorRouterSubmit })} {routerPoints >= 2 && draggablePoints({ editorRouterCancel, editorRouterSubmit })}
</div> </div>
); );
const RouterDialog = connect(mapStateToProps, mapDispatchToProps)(RouterDialogUnconnected);
export { RouterDialog };

18
src/constants/map.ts Normal file
View file

@ -0,0 +1,18 @@
import { Map } from 'leaflet';
export class MapContainer extends Map {
disableClicks = () => {
this.clickable = false;
};
enableClicks = () => {
this.clickable = true;
};
public clickable = true;
}
export const MainMap = new MapContainer(document.getElementById('canvas')).setView(
[55.0153275, 82.9071235],
13
);

View file

@ -1,20 +1,18 @@
import { Map as MapInterface, map } from "leaflet"; import React from 'react';
import React from "react";
import { createPortal } from "react-dom";
import {
selectMapProvider,
selectMapRoute,
selectMapStickers
} from "~/redux/map/selectors";
import { connect } from "react-redux";
import * as MAP_ACTIONS from "~/redux/map/actions";
import { Route } from "~/containers/map/Route"; import { MainMap } from '~/constants/map';
import { TileLayer } from "~/containers/map/TileLayer"; import { Map as MapInterface } from 'leaflet';
import { Stickers } from "~/containers/map/Stickers"; import { createPortal } from 'react-dom';
import { selectMapProvider, selectMapRoute, selectMapStickers } from '~/redux/map/selectors';
import { connect } from 'react-redux';
import * as MAP_ACTIONS from '~/redux/map/actions';
import { Route } from '~/containers/map/Route';
import { TileLayer } from '~/containers/map/TileLayer';
import { Stickers } from '~/containers/map/Stickers';
import 'leaflet/dist/leaflet.css'; import 'leaflet/dist/leaflet.css';
import { selectEditorEditing } from "~/redux/editor/selectors"; import { selectEditorEditing } from '~/redux/editor/selectors';
const mapStateToProps = state => ({ const mapStateToProps = state => ({
provider: selectMapProvider(state), provider: selectMapProvider(state),
@ -27,15 +25,13 @@ const mapDispatchToProps = {
mapSetRoute: MAP_ACTIONS.mapSetRoute, mapSetRoute: MAP_ACTIONS.mapSetRoute,
mapDropSticker: MAP_ACTIONS.mapDropSticker, mapDropSticker: MAP_ACTIONS.mapDropSticker,
mapSetSticker: MAP_ACTIONS.mapSetSticker, mapSetSticker: MAP_ACTIONS.mapSetSticker,
mapClicked: MAP_ACTIONS.mapClicked mapClicked: MAP_ACTIONS.mapClicked,
}; };
type IProps = React.HTMLAttributes<HTMLDivElement> & type IProps = React.HTMLAttributes<HTMLDivElement> &
ReturnType<typeof mapStateToProps> & ReturnType<typeof mapStateToProps> &
typeof mapDispatchToProps & {}; typeof mapDispatchToProps & {};
export let MainMap = map(document.getElementById('canvas')).setView([55.0153275, 82.9071235], 13);
const MapUnconnected: React.FC<IProps> = ({ const MapUnconnected: React.FC<IProps> = ({
provider, provider,
route, route,
@ -45,44 +41,38 @@ const MapUnconnected: React.FC<IProps> = ({
mapClicked, mapClicked,
mapSetRoute, mapSetRoute,
mapSetSticker, mapSetSticker,
mapDropSticker mapDropSticker,
}) => { }) => {
const ref = React.useRef(null); const onClick = React.useCallback(
const [layer, setLayer] = React.useState<MapInterface>(null); event => {
if (!MainMap.clickable) return;
const onClick = React.useCallback(event => { mapClicked(event.latlng);
mapClicked(event.latlng); },
}, [mapClicked]); [mapClicked]
);
React.useEffect(() => { React.useEffect(() => {
if (!ref.current) return; MainMap.addEventListener('click', onClick);
setLayer(MainMap);
}, []);
React.useEffect(() => {
if (!layer) return;
layer.addEventListener("click", onClick)
return () => { return () => {
layer.removeEventListener("click", onClick) MainMap.removeEventListener('click', onClick);
} };
}, [layer, onClick]); }, [MainMap, onClick]);
return createPortal( return createPortal(
<div ref={ref}> <div>
<TileLayer provider={provider} map={layer} /> <TileLayer provider={provider} map={MainMap} />
<Route route={route} mapSetRoute={mapSetRoute} map={layer} is_editing={editing} /> <Route route={route} mapSetRoute={mapSetRoute} map={MainMap} is_editing={editing} />
<Stickers <Stickers
stickers={stickers} stickers={stickers}
map={layer} map={MainMap}
mapSetSticker={mapSetSticker} mapSetSticker={mapSetSticker}
mapDropSticker={mapDropSticker} mapDropSticker={mapDropSticker}
is_editing={editing} is_editing={editing}
/> />
</div>, </div>,
document.getElementById("canvas") document.getElementById('canvas')
); );
}; };

View file

@ -1,14 +1,15 @@
import React from "react"; import React from 'react';
import { Map, marker, Marker } from "leaflet"; import { marker, Marker } from 'leaflet';
import { IStickerDump } from "~/redux/map/types"; import { IStickerDump } from '~/redux/map/types';
import { STICKERS } from "~/constants/stickers"; import { STICKERS } from '~/constants/stickers';
import { StickerDesc } from "~/components/StickerDesc"; import { StickerDesc } from '~/components/StickerDesc';
import classNames from "classnames"; import classNames from 'classnames';
import { DomMarker } from "~/utils/DomMarker"; import { DomMarker } from '~/utils/DomMarker';
import { createPortal } from "react-dom"; import { createPortal } from 'react-dom';
import { MapContainer } from '~/constants/map';
interface IProps { interface IProps {
map: Map; map: MapContainer;
sticker: IStickerDump; sticker: IStickerDump;
index: number; index: number;
is_editing: boolean; is_editing: boolean;
@ -17,10 +18,8 @@ interface IProps {
mapDropSticker: (index: number) => void; mapDropSticker: (index: number) => void;
} }
export const getLabelDirection = (angle: number): "left" | "right" => export const getLabelDirection = (angle: number): 'left' | 'right' =>
angle % Math.PI >= -(Math.PI / 2) && angle % Math.PI <= Math.PI / 2 angle % Math.PI >= -(Math.PI / 2) && angle % Math.PI <= Math.PI / 2 ? 'left' : 'right';
? "left"
: "right";
const getX = e => const getX = e =>
e.touches && e.touches.length > 0 e.touches && e.touches.length > 0
@ -33,53 +32,56 @@ const Sticker: React.FC<IProps> = ({
index, index,
mapSetSticker, mapSetSticker,
mapDropSticker, mapDropSticker,
is_editing is_editing,
}) => { }) => {
const [layer, setLayer] = React.useState<Marker>(null); const [layer, setLayer] = React.useState<Marker>(null);
const [dragging, setDragging] = React.useState(false); const [dragging, setDragging] = React.useState(false);
const [angle, setAngle] = React.useState(sticker.angle); const [angle, setAngle] = React.useState(sticker.angle);
const element = React.useMemo(() => document.createElement("div"), []); const element = React.useMemo(() => document.createElement('div'), []);
const stickerArrow = React.useRef(null); const stickerArrow = React.useRef(null);
const stickerImage = React.useRef(null); const stickerImage = React.useRef(null);
const onChange = React.useCallback(state => mapSetSticker(index, state), [ const onChange = React.useCallback(state => mapSetSticker(index, state), [mapSetSticker, index]);
mapSetSticker, const onDelete = React.useCallback(state => mapDropSticker(index), [mapSetSticker, index]);
index
]);
const onDelete = React.useCallback(state => mapDropSticker(index), [
mapSetSticker,
index
]);
const onDragStart = React.useCallback(() => { const onDragStart = React.useCallback(() => {
layer.dragging.disable(); layer.dragging.disable();
map.dragging.disable(); map.dragging.disable();
map.disableClicks();
setDragging(true); setDragging(true);
}, [setDragging, layer, map]); }, [setDragging, layer, map]);
const onDragStop = React.useCallback(() => { const onDragStop = React.useCallback(() => {
layer.dragging.enable();
map.dragging.enable();
setDragging(false); setDragging(false);
onChange({ onChange({
...sticker, ...sticker,
angle angle,
}); });
layer.dragging.enable();
map.dragging.enable();
setTimeout(map.enableClicks, 100);
}, [setDragging, layer, map, sticker, angle]); }, [setDragging, layer, map, sticker, angle]);
const onMoveStarted = React.useCallback(() => {
map.disableClicks();
}, [onChange, sticker, map]);
const onMoveFinished = React.useCallback( const onMoveFinished = React.useCallback(
event => { event => {
const target = event.target as Marker; const target = event.target as Marker;
onChange({ onChange({
...sticker, ...sticker,
latlng: target.getLatLng() latlng: target.getLatLng(),
}); });
map.enableClicks();
}, },
[onChange, sticker] [onChange, sticker, map]
); );
const onDrag = React.useCallback( const onDrag = React.useCallback(
@ -98,7 +100,7 @@ const Sticker: React.FC<IProps> = ({
text => text =>
onChange({ onChange({
...sticker, ...sticker,
text text,
}), }),
[sticker, onChange] [sticker, onChange]
); );
@ -122,21 +124,25 @@ const Sticker: React.FC<IProps> = ({
React.useEffect(() => { React.useEffect(() => {
if (!layer) return; if (!layer) return;
layer.addEventListener("dragend", onMoveFinished); layer.addEventListener('dragstart', onMoveStarted);
layer.addEventListener('dragend', onMoveFinished);
return () => layer.removeEventListener("dragend", onMoveFinished); return () => {
}, [layer, onMoveFinished]); layer.removeEventListener('dragstart', onMoveStarted);
layer.removeEventListener('dragend', onMoveFinished);
};
}, [layer, onMoveFinished, onMoveStarted]);
// Attaches and detaches handlers when user starts dragging // Attaches and detaches handlers when user starts dragging
React.useEffect(() => { React.useEffect(() => {
if (dragging) { if (dragging) {
document.addEventListener("mousemove", onDrag); document.addEventListener('mousemove', onDrag);
document.addEventListener("mouseup", onDragStop); document.addEventListener('mouseup', onDragStop);
} }
return () => { return () => {
document.removeEventListener("mousemove", onDrag); document.removeEventListener('mousemove', onDrag);
document.removeEventListener("mouseup", onDragStop); document.removeEventListener('mouseup', onDragStop);
}; };
}, [dragging, onDrag]); }, [dragging, onDrag]);
@ -146,7 +152,7 @@ const Sticker: React.FC<IProps> = ({
const icon = new DomMarker({ const icon = new DomMarker({
element, element,
className: "sticker-container" className: 'sticker-container',
}); });
const item = marker(sticker.latlng, { icon, draggable: true }).addTo(map); const item = marker(sticker.latlng, { icon, draggable: true }).addTo(map);
@ -160,27 +166,20 @@ const Sticker: React.FC<IProps> = ({
}, [element, map, sticker]); }, [element, map, sticker]);
React.useEffect(() => { React.useEffect(() => {
element.className = is_editing element.className = is_editing ? 'sticker-container' : 'sticker-container inactive';
? "sticker-container"
: "sticker-container inactive";
}, [element, is_editing]); }, [element, is_editing]);
return createPortal( return createPortal(
<React.Fragment> <React.Fragment>
<div className="sticker-arrow" ref={stickerArrow} /> <div className="sticker-arrow" ref={stickerArrow} />
<div <div className={classNames(`sticker-label ${direction}`)} ref={stickerImage}>
className={classNames(`sticker-label ${direction}`, {})}
ref={stickerImage}
>
<StickerDesc value={sticker.text} onChange={onTextChange} /> <StickerDesc value={sticker.text} onChange={onTextChange} />
<div <div
className="sticker-image" className="sticker-image"
style={{ style={{
backgroundImage: `url('${STICKERS[sticker.set].url}`, backgroundImage: `url('${STICKERS[sticker.set].url}`,
backgroundPosition: `${-STICKERS[sticker.set].layers[ backgroundPosition: `${-STICKERS[sticker.set].layers[sticker.sticker].off * 72} 50%`,
sticker.sticker
].off * 72} 50%`
}} }}
onMouseDown={onDragStart} onMouseDown={onDragStart}
onMouseUp={onDragStop} onMouseUp={onDragStop}
@ -188,15 +187,11 @@ const Sticker: React.FC<IProps> = ({
onTouchEnd={onDragStop} onTouchEnd={onDragStop}
/> />
<div <div className="sticker-delete" onMouseDown={onDelete} onTouchStart={onDelete} />
className="sticker-delete"
onMouseDown={onDelete}
onTouchStart={onDelete}
/>
</div> </div>
</React.Fragment>, </React.Fragment>,
element element
); );
}; };
export { Sticker }; export { Sticker };

View file

@ -3,17 +3,16 @@ import { IStickerDump } from '~/redux/map/types';
import { FeatureGroup, Map } from 'leaflet'; import { FeatureGroup, Map } from 'leaflet';
import { Sticker } from '~/containers/map/Sticker'; import { Sticker } from '~/containers/map/Sticker';
import { mapSetSticker, mapDropSticker } from '~/redux/map/actions'; import { mapSetSticker, mapDropSticker } from '~/redux/map/actions';
import { MapContainer } from '~/constants/map';
interface IProps { interface IProps {
stickers: IStickerDump[]; stickers: IStickerDump[];
is_editing: boolean; is_editing: boolean;
map: Map; map: MapContainer;
mapSetSticker: typeof mapSetSticker; mapSetSticker: typeof mapSetSticker;
mapDropSticker: typeof mapDropSticker; mapDropSticker: typeof mapDropSticker;
} }
// const { FC, useContext, useState, useEffect } = React;
const Stickers: React.FC<IProps> = React.memo( const Stickers: React.FC<IProps> = React.memo(
({ stickers, is_editing, map, mapSetSticker, mapDropSticker }) => { ({ stickers, is_editing, map, mapSetSticker, mapDropSticker }) => {
const [layer, setLayer] = React.useState<FeatureGroup>(null); const [layer, setLayer] = React.useState<FeatureGroup>(null);

View file

@ -9,7 +9,6 @@ import {
editorSetMode, editorSetMode,
editorSetReady, editorSetReady,
editorSetRenderer, editorSetRenderer,
editorSetDialog,
editorSetDialogActive, editorSetDialogActive,
editorClearAll, editorClearAll,
editorSetFeature, editorSetFeature,
@ -172,40 +171,25 @@ function* cropAShotSaga(params) {
} }
function* locationChangeSaga({ location }: ReturnType<typeof editorLocationChanged>) { function* locationChangeSaga({ location }: ReturnType<typeof editorLocationChanged>) {
const {
user: { id, random_url },
}: ReturnType<typeof selectUser> = yield select(selectUser);
const { ready }: ReturnType<typeof selectEditor> = yield select(selectEditor); const { ready }: ReturnType<typeof selectEditor> = yield select(selectEditor);
const { address }: ReturnType<typeof selectMap> = yield select(selectMap);
const { owner, address }: ReturnType<typeof selectMap> = yield select(selectMap);
if (!ready) return; if (!ready) return;
const { path, mode } = getUrlData(location); const { path, mode } = getUrlData(location);
if (address !== path) { if (address !== path) {
const map = yield call(loadMapSaga, path); yield call(loadMapSaga, path);
if (map && map.route && map.route.owner && mode === 'edit' && map.route.owner !== id) {
return yield call(replaceAddressIfItsBusy, map.random_url, map.address);
}
} else if (mode === 'edit' && owner.id !== id) {
return yield call(replaceAddressIfItsBusy, random_url, address);
} else {
yield put(mapSetAddressOrigin(''));
} }
if (mode !== 'edit') { if (mode !== 'edit') {
yield put(editorSetEditing(false)); yield put(editorSetEditing(false));
// editor.stopEditing();
} else { } else {
yield put(editorSetEditing(true)); yield put(editorSetEditing(true));
// editor.startEditing();
} }
} }
function* keyPressedSaga({ key, target }: ReturnType<typeof editorKeyPressed>): any { function* keyPressedSaga({ key, target }: ReturnType<typeof editorKeyPressed>) {
if (target === 'INPUT' || target === 'TEXTAREA') { if (target === 'INPUT' || target === 'TEXTAREA') {
return; return;
} }
@ -237,7 +221,6 @@ function* keyPressedSaga({ key, target }: ReturnType<typeof editorKeyPressed>):
function* getGPXTrackSaga(): SagaIterator { function* getGPXTrackSaga(): SagaIterator {
const { route, stickers, title, address }: ReturnType<typeof selectMap> = yield select(selectMap); const { route, stickers, title, address }: ReturnType<typeof selectMap> = yield select(selectMap);
// const { title, address }: = yield select(selectUser);
if (!route || route.length <= 0) return; if (!route || route.length <= 0) return;
@ -246,6 +229,11 @@ function* getGPXTrackSaga(): SagaIterator {
return downloadGPXTrack({ track, title }); return downloadGPXTrack({ track, title });
} }
function* routerCancel() {
yield put(editorSetMode(MODES.NONE))
// TODO: clear router
}
export function* editorSaga() { export function* editorSaga() {
yield takeEvery(EDITOR_ACTIONS.STOP_EDITING, stopEditingSaga); yield takeEvery(EDITOR_ACTIONS.STOP_EDITING, stopEditingSaga);
yield takeLatest(EDITOR_ACTIONS.TAKE_A_SHOT, takeAShotSaga); yield takeLatest(EDITOR_ACTIONS.TAKE_A_SHOT, takeAShotSaga);
@ -253,4 +241,5 @@ export function* editorSaga() {
yield takeLatest(EDITOR_ACTIONS.LOCATION_CHANGED, locationChangeSaga); yield takeLatest(EDITOR_ACTIONS.LOCATION_CHANGED, locationChangeSaga);
yield takeLatest(EDITOR_ACTIONS.KEY_PRESSED, keyPressedSaga); yield takeLatest(EDITOR_ACTIONS.KEY_PRESSED, keyPressedSaga);
yield takeLatest(EDITOR_ACTIONS.GET_GPX_TRACK, getGPXTrackSaga); yield takeLatest(EDITOR_ACTIONS.GET_GPX_TRACK, getGPXTrackSaga);
yield takeLatest(EDITOR_ACTIONS.ROUTER_CANCEL, routerCancel);
} }

View file

@ -13,7 +13,7 @@ import {
middleCoordPx, middleCoordPx,
} from '~/utils/geom'; } from '~/utils/geom';
import { Point } from 'leaflet'; import { Point } from 'leaflet';
import { MainMap } from '~/containers/map/Map'; import { MainMap } from '~/constants/map';
export interface ITilePlacement { export interface ITilePlacement {
minX: number; minX: number;