Skip to content

Commit

Permalink
feat: 🎸 add {bound} option to useMouse
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 26, 2019
1 parent f5faba5 commit 9bb02a1
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 7 deletions.
2 changes: 1 addition & 1 deletion src/__stories__/useMouse.story.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import ShowDocs from '../util/ShowDocs';
const Demo = () => {
const [whenHovered, toggleWhenHovered] = useToggle(false);
const ref = React.useRef(null);
const state = useMouse(ref, whenHovered)
const state = useMouse(ref, {whenHovered, bound: true})

return (
<>
Expand Down
19 changes: 13 additions & 6 deletions src/useMouse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,12 @@ export interface State {
elW: number;
}

const useMouse = (ref: RefObject<HTMLElement>, whenHovered: boolean = false): State => {
export interface UseMouseOptions {
whenHovered?: boolean;
bound?: boolean;
}

const useMouse = (ref: RefObject<HTMLElement>, {whenHovered = false, bound = false}: UseMouseOptions = {}): State => {
if (process.env.NODE_ENV === 'development') {
if ((typeof ref !== 'object') || (typeof ref.current === 'undefined')) {
console.error('useMouse expects a single ref argument.');
Expand All @@ -38,19 +43,21 @@ const useMouse = (ref: RefObject<HTMLElement>, whenHovered: boolean = false): St

frame.current = requestAnimationFrame(() => {
if (ref && ref.current) {
const {left, top, width, height} = ref.current.getBoundingClientRect();
const {left, top, width: elW, height: elH} = ref.current.getBoundingClientRect();
const posX = left + window.scrollX;
const posY = top + window.scrollY;
const elX = event.pageX - posX;
const elY = event.pageY - posY;

setState({
docX: event.pageX,
docY: event.pageY,
posX,
posY,
elX: event.pageX - posX,
elY: event.pageY - posY,
elH: height,
elW: width,
elX: bound ? Math.max(0, Math.min(elX, elW)) : elX,
elY: bound ? Math.max(0, Math.min(elY, elH)) : elY,
elH,
elW,
});
}
});
Expand Down

0 comments on commit 9bb02a1

Please sign in to comment.