@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
87 lines (86 loc) • 2.71 kB
JavaScript
"use client";
import React, { useCallback, useEffect, useRef } from 'react';
import clsx from 'clsx';
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";
import withComponentMarkers from "../../shared/helpers/withComponentMarkers.js";
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
const CopyOnClick = ({
children,
className = null,
disabled = false,
showCursor = true,
copyContent = null,
tooltipContent = null,
...props
}) => {
const ref = useRef(null);
const timeoutRef = useRef(undefined);
const [active, setActive] = React.useState(false);
useEffect(() => {
if (IS_IOS) {
runIOSSelectionFix();
}
}, []);
const {
CopyOnClick: {
clipboardCopy
}
} = 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 : clipboardCopy;
return _jsxs(Span, {
className: clsx('dnb-copy-on-click', className, showCursor && !disabled && 'dnb-copy-on-click--cursor'),
ref: ref,
...props,
...params,
children: [children, _jsx(Tooltip, {
open: active,
targetElement: ref,
children: message
})]
});
};
withComponentMarkers(CopyOnClick, {
_supportsSpacingProps: true
});
export default CopyOnClick;
//# sourceMappingURL=CopyOnClick.js.map