mirror of
https://github.com/grafana/grafana.git
synced 2025-02-25 18:55:37 -06:00
ClipboardButton: Simplify callbacks (#49847)
This commit is contained in:
parent
e0bb01aea6
commit
70980fbb44
@ -2,41 +2,25 @@ import React, { useCallback, useRef } from 'react';
|
||||
|
||||
import { Button, ButtonProps } from '../Button';
|
||||
|
||||
/** @deprecated Will be removed in next major release */
|
||||
interface ClipboardEvent {
|
||||
action: string;
|
||||
text: string;
|
||||
trigger: Element;
|
||||
clearSelection(): void;
|
||||
}
|
||||
|
||||
export interface Props extends ButtonProps {
|
||||
/** A function that returns text to be copied */
|
||||
getText(): string;
|
||||
/** Callback when the text has been successfully copied */
|
||||
onClipboardCopy?(e: ClipboardEvent): void;
|
||||
onClipboardCopy?(copiedText: string): void;
|
||||
/** Callback when there was an error copying the text */
|
||||
onClipboardError?(e: ClipboardEvent): void;
|
||||
onClipboardError?(copiedText: string, error: unknown): void;
|
||||
}
|
||||
|
||||
const dummyClearFunc = () => {};
|
||||
|
||||
export function ClipboardButton({ onClipboardCopy, onClipboardError, children, getText, ...buttonProps }: Props) {
|
||||
const buttonRef = useRef<null | HTMLButtonElement>(null);
|
||||
const copyTextCallback = useCallback(async () => {
|
||||
const textToCopy = getText();
|
||||
// Can be removed in 9.x
|
||||
const dummyEvent: ClipboardEvent = {
|
||||
action: 'copy',
|
||||
clearSelection: dummyClearFunc,
|
||||
text: textToCopy,
|
||||
trigger: buttonRef.current!,
|
||||
};
|
||||
|
||||
try {
|
||||
await copyText(textToCopy, buttonRef);
|
||||
onClipboardCopy?.(dummyEvent);
|
||||
} catch {
|
||||
onClipboardError?.(dummyEvent);
|
||||
onClipboardCopy?.(textToCopy);
|
||||
} catch (e) {
|
||||
onClipboardError?.(textToCopy, e);
|
||||
}
|
||||
}, [getText, onClipboardCopy, onClipboardError]);
|
||||
|
||||
|
@ -203,8 +203,8 @@ export const RuleDetailsActionButtons: FC<Props> = ({ rule, rulesSource }) => {
|
||||
onClipboardCopy={() => {
|
||||
notifyApp.success('URL copied!');
|
||||
}}
|
||||
onClipboardError={(e) => {
|
||||
notifyApp.error('Error while copying URL', e.text);
|
||||
onClipboardError={(copiedText) => {
|
||||
notifyApp.error('Error while copying URL', copiedText);
|
||||
}}
|
||||
className={style.button}
|
||||
size="sm"
|
||||
|
Loading…
Reference in New Issue
Block a user