Created
April 14, 2017 08:03
-
-
Save Soreine/865dc74006320de93ed698546590e6c4 to your computer and use it in GitHub Desktop.
React - MultiHover
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* @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