2022-04-13 15:50:08 +02:00
|
|
|
/*
|
2024-06-06 16:57:08 +02:00
|
|
|
* Copyright (C) 2019-2024 CZ.NIC z.s.p.o. (https://www.nic.cz/)
|
2022-04-13 15:50:08 +02:00
|
|
|
*
|
|
|
|
* This is free software, licensed under the GNU General Public License v3.
|
|
|
|
* See /LICENSE for more information.
|
|
|
|
*/
|
|
|
|
|
|
|
|
import React, { useState, useRef } from "react";
|
2024-06-06 16:57:08 +02:00
|
|
|
|
2022-04-13 15:50:08 +02:00
|
|
|
import PropTypes from "prop-types";
|
2024-06-06 16:57:08 +02:00
|
|
|
|
|
|
|
import Input from "./Input";
|
2022-04-13 15:50:08 +02:00
|
|
|
|
|
|
|
CopyInput.propTypes = {
|
|
|
|
/** Field label. */
|
|
|
|
label: PropTypes.string.isRequired,
|
|
|
|
/** Field value. */
|
|
|
|
value: PropTypes.string,
|
|
|
|
/** Help text message. */
|
|
|
|
helpText: PropTypes.string,
|
|
|
|
/** Disable input field */
|
|
|
|
disabled: PropTypes.bool,
|
|
|
|
/** Readonly input field */
|
|
|
|
readOnly: PropTypes.bool,
|
|
|
|
};
|
|
|
|
|
2024-06-06 16:57:08 +02:00
|
|
|
function CopyInput({ value, ...props }) {
|
2022-04-13 15:50:08 +02:00
|
|
|
const inputTextRef = useRef();
|
|
|
|
const [isCopied, setIsCopied] = useState(false);
|
|
|
|
|
|
|
|
const handleCopyClick = async () => {
|
|
|
|
// Clipboard API works only in a secure (HTTPS) context.
|
|
|
|
if (navigator.clipboard) {
|
|
|
|
await navigator.clipboard.writeText(value);
|
|
|
|
} else {
|
|
|
|
// Fallback to the "classic" copy to clipboard implementation.
|
|
|
|
inputTextRef.current.focus();
|
|
|
|
inputTextRef.current.select();
|
|
|
|
document.execCommand("copy");
|
|
|
|
inputTextRef.current.blur();
|
|
|
|
}
|
|
|
|
|
|
|
|
setIsCopied(true);
|
|
|
|
setTimeout(() => {
|
|
|
|
setIsCopied(false);
|
|
|
|
}, 1500);
|
|
|
|
};
|
|
|
|
|
|
|
|
return (
|
|
|
|
<Input type="text" value={value} ref={inputTextRef} {...props}>
|
|
|
|
<div className="input-group-append">
|
|
|
|
<button
|
|
|
|
className="btn btn-outline-secondary"
|
|
|
|
type="button"
|
|
|
|
onClick={handleCopyClick}
|
|
|
|
>
|
|
|
|
<span>{isCopied ? _("Copied!") : _("Copy")}</span>
|
|
|
|
</button>
|
|
|
|
</div>
|
|
|
|
</Input>
|
|
|
|
);
|
|
|
|
}
|
2024-06-06 16:57:08 +02:00
|
|
|
|
|
|
|
export default CopyInput;
|