mirror of
https://github.com/portainer/portainer.git
synced 2025-07-23 07:19:41 +02:00
add copy to clipboard to web editor (#9009)
This commit is contained in:
parent
1cda08ca11
commit
3a49dbf803
4 changed files with 65 additions and 18 deletions
|
@ -1,6 +1,12 @@
|
|||
import { useEffect, useState } from 'react';
|
||||
|
||||
export function useCopy(copyText: string, fadeDelay = 1000) {
|
||||
export type CopyTextType = string | (() => string);
|
||||
|
||||
export function useCopy(
|
||||
copyText: CopyTextType,
|
||||
fadeDelay = 1000,
|
||||
context: HTMLElement = document.body
|
||||
) {
|
||||
const [copiedSuccessfully, setCopiedSuccessfully] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
|
@ -15,19 +21,25 @@ export function useCopy(copyText: string, fadeDelay = 1000) {
|
|||
}, [copiedSuccessfully, fadeDelay]);
|
||||
|
||||
function handleCopy() {
|
||||
const text = typeof copyText === 'function' ? copyText() : copyText;
|
||||
|
||||
if (!text) {
|
||||
return;
|
||||
}
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/Clipboard
|
||||
// https://caniuse.com/?search=clipboard
|
||||
if (navigator.clipboard) {
|
||||
navigator.clipboard.writeText(copyText);
|
||||
navigator.clipboard.writeText(text);
|
||||
} else {
|
||||
// https://stackoverflow.com/a/57192718
|
||||
const inputEl = document.createElement('textarea');
|
||||
inputEl.value = copyText;
|
||||
document.body.appendChild(inputEl);
|
||||
inputEl.value = text;
|
||||
context.appendChild(inputEl);
|
||||
inputEl.select();
|
||||
document.execCommand('copy');
|
||||
inputEl.hidden = true;
|
||||
document.body.removeChild(inputEl);
|
||||
context.removeChild(inputEl);
|
||||
}
|
||||
setCopiedSuccessfully(true);
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue