extracted handlers to createChangeStateMethods

main
Inga 🏳‍🌈 1 year ago
parent 1d79801e59
commit 6f2008f108
  1. 56
      src/routePlanner/index.tsx
  2. 54
      src/routePlanner/reducer.ts

@ -1,66 +1,18 @@
import { useCallback, useReducer } from 'preact/hooks';
import { Coordinates } from '../shared/types';
import { useMemo, useReducer } from 'preact/hooks';
import { ExportComponent } from './export';
import { MapComponent } from './map';
import { MarkersComponent } from './markers';
import { ReorderMarkersParams } from './types';
import { createChangeStateMethods, markersReducer } from './reducer';
import './style.css';
import { markersReducer } from './reducer';
export const RoutePlanner = () => {
const [markers, dispatchMarkers] = useReducer(markersReducer, []);
const reorderMarkers = useCallback(
({ oldIndex, newIndex }: ReorderMarkersParams): void =>
dispatchMarkers({
type: 'reorder',
data: { oldIndex, newIndex },
}),
[],
);
const moveMarkerUp = useCallback(
(key: string) =>
dispatchMarkers({
type: 'moveUp',
data: { key },
}),
[],
);
const moveMarkerDown = useCallback(
(key: string) =>
dispatchMarkers({
type: 'moveDown',
data: { key },
}),
[],
);
const removeMarker = useCallback(
(key: string) =>
dispatchMarkers({
type: 'remove',
data: { key },
}),
const { reorderMarkers, addMarker } = useMemo(
() => createChangeStateMethods(dispatchMarkers),
[],
);
const addMarker = useCallback(
(coordinates: Coordinates) =>
dispatchMarkers({
type: 'add',
data: {
coordinates,
moveUp: moveMarkerUp,
moveDown: moveMarkerDown,
remove: removeMarker,
},
}),
[moveMarkerUp, moveMarkerDown, removeMarker],
);
return (
<section class="route-planner">
<section class="markers">

@ -1,6 +1,8 @@
import { nanoid } from 'nanoid';
import { Marker, ReducerAction } from './types';
import { Marker, ReducerAction, ReorderMarkersParams } from './types';
import { reorderElements } from '../shared/collections';
import { Dispatch } from 'preact/hooks';
import { Coordinates } from '../shared/types';
const reindexMarkers = (markers: Marker[]) =>
markers.map((marker, i) => {
@ -77,3 +79,53 @@ export const markersReducer = (
throw new Error(`Unsupported type ${type}`);
}
};
export const createChangeStateMethods = (
dispatchMarkers: Dispatch<ReducerAction>,
) => {
const reorderMarkers = ({
oldIndex,
newIndex,
}: ReorderMarkersParams): void =>
dispatchMarkers({
type: 'reorder',
data: { oldIndex, newIndex },
});
const moveMarkerUp = (key: string) =>
dispatchMarkers({
type: 'moveUp',
data: { key },
});
const moveMarkerDown = (key: string) =>
dispatchMarkers({
type: 'moveDown',
data: { key },
});
const removeMarker = (key: string) =>
dispatchMarkers({
type: 'remove',
data: { key },
});
const addMarker = (coordinates: Coordinates) =>
dispatchMarkers({
type: 'add',
data: {
coordinates,
moveUp: moveMarkerUp,
moveDown: moveMarkerDown,
remove: removeMarker,
},
});
return {
reorderMarkers,
moveMarkerUp,
moveMarkerDown,
removeMarker,
addMarker,
};
};

Loading…
Cancel
Save