@ducor/react
Version:
admin template ui interface
58 lines (57 loc) • 2.2 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
import copy from "copy-to-clipboard";
import { isNumber, isString } from "lodash";
import { useCallback, useEffect, useState } from "react";
/**
* `useClipboard` is a custom hook that performs the operation of copying a value to the clipboard.
*
* @see Docs https://ui.ducor.net/hooks/use-clipboard
*/
var useClipboard = function (defaultValue, timeoutOrOptions) {
if (defaultValue === void 0) { defaultValue = ""; }
if (timeoutOrOptions === void 0) { timeoutOrOptions = {}; }
var _a = useState(false), hasCopied = _a[0], setHasCopied = _a[1];
var _b = useState(defaultValue), value = _b[0], setValue = _b[1];
useEffect(function () { return setValue(defaultValue); }, [defaultValue]);
var _c = isNumber(timeoutOrOptions)
? { timeout: timeoutOrOptions }
: timeoutOrOptions, _d = _c.timeout, timeout = _d === void 0 ? 1500 : _d, copyOptions = __rest(_c, ["timeout"]);
var onCopy = useCallback(function (newValue) {
if (!isString(newValue)) {
newValue = value;
}
else {
setValue(newValue);
}
var hasCopied = copy(newValue, copyOptions);
setHasCopied(hasCopied);
}, [value, copyOptions]);
useEffect(function () {
var timeoutId = null;
if (hasCopied)
timeoutId = window.setTimeout(function () {
setHasCopied(false);
}, timeout);
return function () {
if (timeoutId)
window.clearTimeout(timeoutId);
};
}, [timeout, hasCopied]);
return {
hasCopied: hasCopied,
setValue: setValue,
value: value,
onCopy: onCopy,
};
};
export default useClipboard;