useEyeDropper
The useEyeDropper
hook can be used to extract a custom color from the design area, in the process commonly known as "eye dropping". The hook returns an object with four properties:
isOpen
- specifies whether the eye dropper is currently openisReady
- specifies whether the eye dropper is ready for use after being openedopen
- a function that activates the eye dropper. This function returns a promise that resolves with the selected color or rejects in case of an error/cancellation. You can provide an optionalAbortSignal
as a parameter when calling this function, which will allow you to cancel the operation.dispense
- a function used to complete the eye dropping operation. It accepts a hex color as an argument. The provided color is "dispensed" into the activation site by resolving the promise obtained by callingopen
.
Before using this hook, be sure to include the EyeDropperProvider
from this package in your component tree.
The interactive part of the eye dropping process is provided by EyeDropperDesignLayer
from this package.
const EyeDropperControls = observer(() => {
const { isOpen, open } = useEyeDropper();
const [selectedColor, setSelectedColor] = useState<string | undefined>(undefined);
const abortControllerRef = useRef<AbortController | null>(null);
const handleOpen = async () => {
try {
abortControllerRef.current = new AbortController();
const newColor = await open({ abortSignal: abortControllerRef.current.signal });
setSelectedColor(newColor);
} catch {
abortControllerRef.current = null;
setSelectedColor(undefined);
}
};
const handleCancel = () => {
abortControllerRef.current?.abort();
abortControllerRef.current = null;
};
return (
<div>
<div>
<button onClick={handleOpen} disabled={isOpen}>
Open eye dropper
</button>
<button onClick={handleCancel} disabled={!isOpen}>
Cancel eye dropper
</button>
</div>
<div>Current color: {selectedColor}</div>
</div>
);
});