aretherecookies-mobile/js/components/ActionsButton.js
2018-08-12 11:34:45 -05:00

98 lines
2.6 KiB
JavaScript

// @flow
import React from 'react';
import { ActionButton } from 'react-native-material-ui';
import { compose, pure, withHandlers } from 'recompose';
import { withRouterContext, withViewMode, withPushRoute } from '../enhancers/routeEnhancers';
import queryString from 'query-string';
import { routeWithQuery } from '../helpers/RouteHelpers';
import { prop, head, length, map } from 'ramda';
type Props = {
actions: Array<'add-food' | 'filter-modal' | 'view-mode'>,
viewMode: string,
actionPressed: Function,
toggleFilterModal: ?Function,
pushRoute: Function,
router: Object,
addFoodItem: Function,
setViewMode: (mode: string) => void,
placeId?: string,
};
const actionDefs = {
'add-food': () => ({ icon: 'add', label: 'Add New', name: 'add-food' }),
'filter-modal': () => ({ icon: 'filter-list', label: 'Filter', name: 'filter-modal' }),
'view-mode': props =>
props.viewMode === 'map'
? { icon: 'list', label: 'View list', name: 'list-view' }
: { icon: 'map', label: 'View map', name: 'map-view' },
};
const ActionsButton = (props: Props) => {
const actions = map(action => actionDefs[action](props), props.actions || []);
const transition = length(actions) > 1 ? 'speedDial' : null;
const icon = length(actions) > 1 ? 'add' : prop('icon', head(actions));
return (
<ActionButton
actions={actions}
icon={icon}
transition={transition}
onPress={props.actionPressed}
onLongPress={props.actionPressed}
/>
);
};
export default compose(
pure,
withRouterContext,
withViewMode,
withPushRoute,
withHandlers({
addFoodItem: ({ pushRoute, placeId }: Props) => () => {
pushRoute(
routeWithQuery('/createFoodItem', {
routeTitle: 'Add a Food Item',
placeId,
})
);
},
setViewMode: ({ router }: Props) => (viewMode: string) => {
const history = router.history;
const search = router.route.location.search;
history.replace({
search: queryString.stringify({
search,
viewMode,
}),
});
},
}),
withHandlers({
actionPressed: (props: Props) =>
function handleActionPressed(action: ?String) {
switch (action) {
case 'add-food':
props.addFoodItem();
break;
case 'filter-modal':
props.toggleFilterModal && props.toggleFilterModal();
break;
case 'map-view':
case 'list-view':
case 'view-mode':
props.setViewMode(props.viewMode === 'map' ? 'list' : 'map');
break;
case 'main-button':
if (length(props.actions) === 1) {
handleActionPressed(head(props.actions));
}
break;
default:
break;
}
},
})
)(ActionsButton);