@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
80 lines (79 loc) • 2.61 kB
JavaScript
"use client";
import _extends from "@babel/runtime-corejs3/helpers/esm/extends";
import React, { useCallback, useEffect, useRef } from 'react';
import classnames from 'classnames';
import { runIOSSelectionFix } from "../number-format/NumberUtils.js";
import { copyToClipboard, hasSelectedText, IS_IOS, warn } from "../../shared/helpers.js";
import { convertJsxToString } from "../../shared/component-helper.js";
import { useTranslation } from "../../shared/index.js";
import { Span } from "../../elements/index.js";
import Tooltip from "../Tooltip.js";
const CopyOnClick = ({
children,
className = null,
disabled = false,
showCursor = true,
copyContent = null,
tooltipContent = null,
...props
}) => {
const ref = useRef(null);
const timeoutRef = useRef();
const [active, setActive] = React.useState(false);
useEffect(() => {
if (IS_IOS) {
runIOSSelectionFix();
}
}, []);
const {
CopyOnClick: {
clipboard_copy
}
} = useTranslation();
const copy = useCallback(async str => {
const clear = () => clearInterval(timeoutRef.current);
clear();
try {
const success = await copyToClipboard(str);
if (success === true) {
setActive(true);
timeoutRef.current = setTimeout(() => setActive(false), 2000);
}
} catch (e) {
warn(e);
}
return () => clear();
}, []);
const onClickHandler = useCallback(() => {
if (!hasSelectedText()) {
try {
var _ref$current;
const str = convertJsxToString(copyContent || children) || ((_ref$current = ref.current) === null || _ref$current === void 0 ? void 0 : _ref$current.textContent);
if (str) {
const selection = window.getSelection();
const range = document.createRange();
range.selectNodeContents(ref.current);
selection.removeAllRanges();
selection.addRange(range);
copy(str);
}
} catch (e) {
warn(e);
}
}
}, [children, copyContent, copy]);
const params = {
onClick: disabled ? undefined : onClickHandler
};
const message = tooltipContent !== null && tooltipContent !== void 0 ? tooltipContent : clipboard_copy;
return React.createElement(Span, _extends({
className: classnames('dnb-copy-on-click', className, showCursor && !disabled && 'dnb-copy-on-click--cursor'),
ref: ref
}, props, params), children, React.createElement(Tooltip, {
active: active,
targetElement: ref
}, message));
};
CopyOnClick._supportsSpacingProps = true;
export default CopyOnClick;
//# sourceMappingURL=CopyOnClick.js.map