ClipboardButton: Simplify callbacks (#49847)

This commit is contained in:
kay delaney
2022-05-30 18:38:52 +02:00
committed by GitHub
parent e0bb01aea6
commit 70980fbb44
2 changed files with 8 additions and 24 deletions
@@ -2,41 +2,25 @@ import React, { useCallback, useRef } from 'react';
import { Button, ButtonProps } from '../Button'; 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 { export interface Props extends ButtonProps {
/** A function that returns text to be copied */ /** A function that returns text to be copied */
getText(): string; getText(): string;
/** Callback when the text has been successfully copied */ /** 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 */ /** 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) { export function ClipboardButton({ onClipboardCopy, onClipboardError, children, getText, ...buttonProps }: Props) {
const buttonRef = useRef<null | HTMLButtonElement>(null); const buttonRef = useRef<null | HTMLButtonElement>(null);
const copyTextCallback = useCallback(async () => { const copyTextCallback = useCallback(async () => {
const textToCopy = getText(); const textToCopy = getText();
// Can be removed in 9.x
const dummyEvent: ClipboardEvent = {
action: 'copy',
clearSelection: dummyClearFunc,
text: textToCopy,
trigger: buttonRef.current!,
};
try { try {
await copyText(textToCopy, buttonRef); await copyText(textToCopy, buttonRef);
onClipboardCopy?.(dummyEvent); onClipboardCopy?.(textToCopy);
} catch { } catch (e) {
onClipboardError?.(dummyEvent); onClipboardError?.(textToCopy, e);
} }
}, [getText, onClipboardCopy, onClipboardError]); }, [getText, onClipboardCopy, onClipboardError]);
@@ -203,8 +203,8 @@ export const RuleDetailsActionButtons: FC<Props> = ({ rule, rulesSource }) => {
onClipboardCopy={() => { onClipboardCopy={() => {
notifyApp.success('URL copied!'); notifyApp.success('URL copied!');
}} }}
onClipboardError={(e) => { onClipboardError={(copiedText) => {
notifyApp.error('Error while copying URL', e.text); notifyApp.error('Error while copying URL', copiedText);
}} }}
className={style.button} className={style.button}
size="sm" size="sm"