Skip to content

Instantly share code, notes, and snippets.

@promontis
Created November 17, 2020 17:25
Show Gist options
  • Save promontis/96a095bb0d70d9adb1d48b58b6aab9d4 to your computer and use it in GitHub Desktop.
Save promontis/96a095bb0d70d9adb1d48b58b6aab9d4 to your computer and use it in GitHub Desktop.
/* eslint-disable react/prop-types */
import React, { ReactElement, useContext, useState } from "react";
import * as three from "three"
import { useDrag } from "../../../hooks/useDrag";
import { useHover } from "../../../hooks/useHover";
import { camContext } from "../controls";
interface Props {
render: (hovering: boolean) => ReactElement;
onMove?: () => void;
onMoveStart?: () => void;
onMoveEnd?: () => void;
onHover?: (hovering: boolean) => void;
}
export const Handle = React.forwardRef<three.Group | undefined, Props>(({ render, onMove, onMoveStart, onMoveEnd, onHover }, ref) => {
const enableControls = useContext(camContext)
const bindDrag = useDrag({
onDrag: () => {
if (onMove) onMove();
},
onDragStart: () => {
enableControls(false);
if (onMoveStart) onMoveStart();
},
onDragEnd: () => {
enableControls(true);
if (onMoveEnd) onMoveEnd();
}
});
const [bindHover, hovering] = useHover({
stopPropagation: false,
onHover: onHover
});
return (
<group ref={ref} {...bindDrag} {...bindHover}>
{render(hovering)}
</group>
);
});
export const ScaleHandles = ({ box, y, selected, setAxis, onHover }: Props): React.ReactElement => {
const handleHover = useCallback((hovering: boolean, axis: "X" | "Y" | "Z" | "XY" | "YZ" | "XZ" | "XYZ" | "E") => {
console.log(`handleHover selected: ${selected}`);
}, [selected]);
console.log(`scaleHandles selected: ${selected}`);
return (
<group visible={selected}>
<Handle ref={point0Ref} onHover={(hovering) => handleHover(hovering, "XZ")} render={ScaleCornerHandle} />
</group>
);
}
import { useCallback, useState } from "react";
interface useHoverConfig {
onHover?: (hovering: boolean) => void;
stopPropagation: boolean;
}
export function useHover({ onHover, stopPropagation }: useHoverConfig): [{
onPointerOver: (e: any) => void;
onPointerOut: (e: any) => void;
}, boolean] {
const [hovering, setHovering] = useState(false);
const hover = useCallback(
(e) => {
if (stopPropagation) {
e.stopPropagation();
}
setHovering(true);
if (onHover) onHover(true);
},
[onHover, stopPropagation]
);
const unhover = useCallback(
(e) => {
if (stopPropagation) {
e.stopPropagation();
}
setHovering(false);
if (onHover) onHover(false);
},
[onHover, stopPropagation]
);
const [bind] = useState(() => ({ onPointerOver: hover, onPointerOut: unhover }));
return [bind, hovering];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment