ClipboardButton: Simplify callbacks (#49847)

This commit is contained in:
kay delaney 2022-05-30 17:38:52 +01:00 committed by GitHub
parent e0bb01aea6
commit 70980fbb44
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 8 additions and 24 deletions

View File

@ -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]);

View File

@ -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"