scratch-paint/src/containers/selection-hoc.jsx

81 lines
2.6 KiB
React
Raw Normal View History

import paper from 'paper';
2017-09-11 14:23:30 -04:00
import PropTypes from 'prop-types';
import React from 'react';
import {connect} from 'react-redux';
import bindAll from 'lodash.bindall';
import {getSelectedItems} from '../helper/selection';
import {getColorsFromSelection} from '../helper/style-path';
import {changeStrokeColor} from '../reducers/stroke-color';
import {changeStrokeWidth} from '../reducers/stroke-width';
import {changeFillColor} from '../reducers/fill-color';
2017-09-11 14:23:30 -04:00
2017-09-22 12:12:07 -04:00
const SelectionHOC = function (WrappedComponent) {
2017-09-11 14:23:30 -04:00
class SelectionComponent extends React.Component {
constructor (props) {
super(props);
bindAll(this, [
'removeItemById'
]);
}
2017-09-11 14:23:30 -04:00
componentDidMount () {
if (this.props.hoveredItemId) {
2017-09-11 14:23:30 -04:00
paper.view.update();
}
}
componentDidUpdate (prevProps) {
// Hovered item has changed
if ((this.props.hoveredItemId && this.props.hoveredItemId !== prevProps.hoveredItemId) ||
(!this.props.hoveredItemId && prevProps.hoveredItemId)) {
// Remove the old hover item if any
this.removeItemById(prevProps.hoveredItemId);
}
}
removeItemById (itemId) {
if (itemId) {
const match = paper.project.getItem({
match: item => (item.id === itemId)
});
if (match) {
match.remove();
}
2017-09-11 14:23:30 -04:00
}
}
render () {
const {
hoveredItemId, // eslint-disable-line no-unused-vars
2017-09-11 14:23:30 -04:00
...props
} = this.props;
return (
<WrappedComponent {...props} />
);
}
}
SelectionComponent.propTypes = {
hoveredItemId: PropTypes.number
2017-09-11 14:23:30 -04:00
};
const mapStateToProps = state => ({
hoveredItemId: state.scratchPaint.hoveredItemId
2017-09-11 14:23:30 -04:00
});
const mapDispatchToProps = dispatch => ({
onUpdateColors: (() => {
const selectedItems = getSelectedItems(true /* recursive */);
if (selectedItems.length === 0) {
return;
}
const colorState = getColorsFromSelection();
dispatch(changeFillColor(colorState.fillColor));
dispatch(changeStrokeColor(colorState.strokeColor));
dispatch(changeStrokeWidth(colorState.strokeWidth));
})
});
2017-09-11 14:23:30 -04:00
return connect(
mapStateToProps,
mapDispatchToProps
2017-09-11 14:23:30 -04:00
)(SelectionComponent);
};
2017-09-22 12:12:07 -04:00
export default SelectionHOC;