|
| 1 | +// Copyright (C) urljsf contributors. |
| 2 | +// Distributed under the terms of the Modified BSD License. |
| 3 | +import { useState } from 'react'; |
| 4 | + |
| 5 | +const PRE_STYLE = { position: 'relative' }; |
| 6 | + |
| 7 | +type TPreProps = React.DetailedHTMLProps< |
| 8 | + React.HTMLAttributes<HTMLPreElement>, |
| 9 | + HTMLPreElement |
| 10 | +>; |
| 11 | + |
| 12 | +const COPY_STYLE = { |
| 13 | + position: 'absolute', |
| 14 | + top: '0.25em', |
| 15 | + right: '0.25em', |
| 16 | + opacity: 0.8, |
| 17 | +}; |
| 18 | + |
| 19 | +const NOT_YET = 0; |
| 20 | +const COPIED = 1; |
| 21 | +const ERRORED = 2; |
| 22 | + |
| 23 | +const STATE_ICON = ['primary', 'success', 'warning']; |
| 24 | +const STATE_LABEL = ['copy', 'ok', 'error']; |
| 25 | + |
| 26 | +export function CopyPastePre(props: TPreProps): JSX.Element { |
| 27 | + const button: JSX.Element[] = []; |
| 28 | + |
| 29 | + const text = `${(props.children as any)?.props?.children || ''}`.trim(); |
| 30 | + |
| 31 | + if (text) { |
| 32 | + const [copyState, setCopyState] = useState(NOT_YET); |
| 33 | + const btnClass = `urljsf-copybutton btn btn-${STATE_ICON[copyState]}`; |
| 34 | + const btnLabel = STATE_LABEL[copyState]; |
| 35 | + |
| 36 | + const onClick = () => { |
| 37 | + setCopyState(copyText(text) ? COPIED : ERRORED); |
| 38 | + setTimeout(() => setCopyState(NOT_YET), 1000); |
| 39 | + }; |
| 40 | + |
| 41 | + button.push( |
| 42 | + <button |
| 43 | + className={btnClass} |
| 44 | + style={COPY_STYLE} |
| 45 | + onClick={onClick} |
| 46 | + aria-label="copy this text" |
| 47 | + > |
| 48 | + {btnLabel} |
| 49 | + </button>, |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + return ( |
| 54 | + <pre {...props} style={PRE_STYLE}> |
| 55 | + {...button} |
| 56 | + {props.children} |
| 57 | + </pre> |
| 58 | + ); |
| 59 | +} |
| 60 | + |
| 61 | +function copyText(text: string): boolean { |
| 62 | + const el = document.createElement('textarea'); |
| 63 | + let result = false; |
| 64 | + try { |
| 65 | + el.value = text; |
| 66 | + document.body.appendChild(el); |
| 67 | + el.select(); |
| 68 | + document.execCommand('copy'); |
| 69 | + result = true; |
| 70 | + } catch (err) { |
| 71 | + /* istanbul ignore next */ |
| 72 | + console.error('failed to copy', err); |
| 73 | + } finally { |
| 74 | + el.remove(); |
| 75 | + } |
| 76 | + return result; |
| 77 | +} |
0 commit comments