Skip to content

Instantly share code, notes, and snippets.

@Soreine
Created April 14, 2017 08:03
Show Gist options
  • Save Soreine/865dc74006320de93ed698546590e6c4 to your computer and use it in GitHub Desktop.
Save Soreine/865dc74006320de93ed698546590e6c4 to your computer and use it in GitHub Desktop.
React - MultiHover
/* @flow */
import { Set } from 'immutable';
/*
* Hover state manager for multiple elements.
*
* Usage:
*
* onHoverChange callback is called whenever the mouse enter the group
* of elements, and whenever it leaves them.
*
* Inject mouse events handlers on all the elements, provided by the method `handlers`.
*/
class MultiHover {
hoverSet: Set<string> = new Set();
onHoverChange: *;
constructor(onHoverChange: (hovered: boolean) => void) {
this.onHoverChange = onHoverChange;
}
onChange(newHoverSet: *) {
const oldHoverSet = this.hoverSet;
this.hoverSet = newHoverSet;
const hoveredChange = oldHoverSet.isEmpty() !== newHoverSet.isEmpty();
if (hoveredChange) {
const hovered = !newHoverSet.isEmpty();
this.onHoverChange(hovered);
}
}
/*
* Returns the mouse event handlers to follow the hover state of a
* React component
*/
handlers(key: string) {
return {
onMouseEnter: () => {
this.onChange(this.hoverSet.add(key));
},
onMouseLeave: () => {
this.onChange(this.hoverSet.delete(key));
}
};
}
}
export default MultiHover;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment