@grafana/ui
Version:
Grafana Components Library
107 lines (102 loc) • 3.27 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var jsxRuntime = require('react/jsx-runtime');
var css = require('@emotion/css');
var React = require('react');
var i18n = require('@grafana/i18n');
var ThemeContext = require('../../themes/ThemeContext.cjs');
var Button = require('../Button/Button.cjs');
var Icon = require('../Icon/Icon.cjs');
var InlineToast = require('../InlineToast/InlineToast.cjs');
;
const SHOW_SUCCESS_DURATION = 2 * 1e3;
function ClipboardButton({
onClipboardCopy,
onClipboardError,
children,
getText,
icon,
variant,
...buttonProps
}) {
const styles = ThemeContext.useStyles2(getStyles);
const [showCopySuccess, setShowCopySuccess] = React.useState(false);
React.useEffect(() => {
let timeoutId;
if (showCopySuccess) {
timeoutId = setTimeout(() => {
setShowCopySuccess(false);
}, SHOW_SUCCESS_DURATION);
}
return () => {
window.clearTimeout(timeoutId);
};
}, [showCopySuccess]);
const buttonRef = React.useRef(null);
const copyTextCallback = React.useCallback(async () => {
const textToCopy = getText();
try {
await copyText(textToCopy, buttonRef);
setShowCopySuccess(true);
onClipboardCopy == null ? void 0 : onClipboardCopy(textToCopy);
} catch (e) {
onClipboardError == null ? void 0 : onClipboardError(textToCopy, e);
}
}, [getText, onClipboardCopy, onClipboardError]);
const copiedText = i18n.t("clipboard-button.inline-toast.success", "Copied");
return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
showCopySuccess && /* @__PURE__ */ jsxRuntime.jsx(InlineToast.InlineToast, { placement: "top", referenceElement: buttonRef.current, children: copiedText }),
/* @__PURE__ */ jsxRuntime.jsxs(
Button.Button,
{
onClick: copyTextCallback,
icon,
variant: showCopySuccess ? "success" : variant,
...buttonProps,
className: css.cx(styles.button, showCopySuccess && styles.successButton, buttonProps.className),
ref: buttonRef,
children: [
children,
showCopySuccess && /* @__PURE__ */ jsxRuntime.jsx("div", { className: styles.successOverlay, children: /* @__PURE__ */ jsxRuntime.jsx(Icon.Icon, { name: "check" }) })
]
}
)
] });
}
const copyText = async (text, buttonRef) => {
var _a;
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text);
} else {
const textarea = document.createElement("textarea");
(_a = buttonRef.current) == null ? void 0 : _a.appendChild(textarea);
textarea.value = text;
textarea.focus();
textarea.select();
document.execCommand("copy");
textarea.remove();
}
};
const getStyles = (theme) => {
return {
button: css.css({
position: "relative"
}),
successButton: css.css({
"> *": css.css({
visibility: "hidden"
})
}),
successOverlay: css.css({
position: "absolute",
top: 0,
bottom: 0,
right: 0,
left: 0,
visibility: "visible"
// re-visible the overlay
})
};
};
exports.ClipboardButton = ClipboardButton;
//# sourceMappingURL=ClipboardButton.cjs.map