@supunlakmal/hooks
Version:
A collection of reusable React hooks
59 lines • 2.81 kB
JavaScript
import { useState, useCallback } from 'react';
const isBrowser = typeof window !== 'undefined';
/**
* Hook to use the experimental EyeDropper API.
*
* Allows users to sample colors from their screen.
* Note: This API is experimental and browser support is limited.
*
* @param {UseEyeDropperOptions} [options] Configuration options.
* @returns {UseEyeDropperReturn} Object with EyeDropper state and controls.
*/
export function useEyeDropper(options) {
const [isSupported] = useState(() => {
return isBrowser && typeof window.EyeDropper === 'function';
});
const [sRGBHex, setSRGBHex] = useState(null);
const [error, setError] = useState(null);
const open = useCallback(async () => {
var _a, _b;
if (!isSupported) {
const notSupportedError = new Error('EyeDropper API is not supported in this browser.');
setError(notSupportedError);
(_a = options === null || options === void 0 ? void 0 : options.onError) === null || _a === void 0 ? void 0 : _a.call(options, notSupportedError);
console.error(notSupportedError.message);
return;
}
setError(null); // Clear previous errors
setSRGBHex(null); // Reset color
const eyeDropper = new window.EyeDropper();
// AbortController can be used if cancellation is needed, but basic usage shown here
// const controller = new AbortController();
// const signal = controller.signal;
try {
const result = await eyeDropper.open( /* { signal } */);
setSRGBHex(result.sRGBHex);
}
catch (err) {
// Handle errors, including user cancellation (which typically throws DOMException: The user aborted a request.)
const currentError = err instanceof Error
? err
: new Error('Failed to open EyeDropper or operation was cancelled.');
// Don't treat user cancellation as a hook error state unless specifically desired
if (currentError.name !== 'AbortError' &&
!(currentError instanceof DOMException &&
currentError.message.includes('aborted'))) {
setError(currentError);
(_b = options === null || options === void 0 ? void 0 : options.onError) === null || _b === void 0 ? void 0 : _b.call(options, currentError);
console.error('EyeDropper error:', currentError);
}
else {
// User cancelled, reset color potentially
setSRGBHex(null);
console.log('EyeDropper operation cancelled by user.');
}
}
}, [isSupported, options]);
return { isSupported, sRGBHex, open, error };
}
//# sourceMappingURL=useEyeDropper.js.map