Debian Codegraph @

node/@patternfly/react-core/src/components/ClipboardCopy/ClipboardCopy.tsx

raw
1 import { Component, Fragment, createRef } from 'react';
2 import styles from '@patternfly/react-styles/css/components/ClipboardCopy/clipboard-copy';
3 import { css } from '@patternfly/react-styles';
4 import { PickOptional } from '../../helpers/typeUtils';
5 import { TooltipPosition } from '../Tooltip';
6 import { TextInput } from '../TextInput';
7 import { Truncate, TruncateProps } from '../Truncate';
8 import { GenerateId } from '../../helpers/GenerateId/GenerateId';
9 import { ClipboardCopyButton } from './ClipboardCopyButton';
10 import { ClipboardCopyToggle } from './ClipboardCopyToggle';
11 import { ClipboardCopyExpanded } from './ClipboardCopyExpanded';
12 import { getOUIAProps, OUIAProps } from '../../helpers';
13
14 export const clipboardCopyFunc = (_event: React.ClipboardEvent<HTMLDivElement>, text?: React.ReactNode) => {
15 try {
16 navigator.clipboard.writeText(text.toString());
17 } catch (error) {
18 // eslint-disable-next-line no-console
19 console.warn(
20 "Clipboard API not found, this copy function will not work. This is likely because you're using an",
21 "unsupported browser or you're not using HTTPS. \n\nIf you're a developer building an application which needs",
22 "to support copying to the clipboard without the clipboard API, you'll have to create your own copy",
23 'function and pass it to the ClipboardCopy component as the onCopy prop. For more information see',
24 'https://developer.mozilla.org/en-US/docs/Web/API/Navigator/clipboard'
25 );
26
27 // eslint-disable-next-line no-console
28 console.error(error);
29 }
30 };
31
32 export enum ClipboardCopyVariant {
33 inline = 'inline',
34 expansion = 'expansion',
35 inlineCompact = 'inline-compact'
36 }
37
38 export interface ClipboardCopyState {
39 text: string;
40 expanded: boolean;
41 copied: boolean;
42 textWhenExpanded: string;
43 }
44
45 export interface ClipboardCopyProps extends Omit<React.HTMLProps<HTMLDivElement>, 'onChange' | 'children'>, OUIAProps {
46 /** Additional classes added to the clipboard copy container. */
47 className?: string;
48 /** Tooltip message to display when hover the copy button */
49 hoverTip?: string;
50 /** Tooltip message to display when clicking the copy button */
51 clickTip?: string;
52 /** Aria-label to use on the copy button */
53 copyAriaLabel?: string;
54 /** Aria-label to use on the TextInput. */
55 textAriaLabel?: string;
56 /** Aria-label to use on the ClipboardCopyToggle. */
57 toggleAriaLabel?: string;
58 /** ID to use on the TextInput. */
59 inputId?: string;
60 /** Name attribute to use on the TextInput. */
61 inputName?: string;
62 /** Flag to show if the input is read only. */
63 isReadOnly?: boolean;
64 /** Flag to determine if clipboard copy is in the expanded state initially */
65 isExpanded?: boolean;
66 /** Flag to determine if clipboard copy content includes code */
67 isCode?: boolean;
68 /** Flag to determine if inline clipboard copy should be block styling */
69 isBlock?: boolean;
70 /** Adds Clipboard Copy variant styles. */
71 variant?: typeof ClipboardCopyVariant | 'inline' | 'expansion' | 'inline-compact';
72 /** Copy button tooltip position. */
73 position?:
74 | TooltipPosition
75 | 'auto'
76 | 'top'
77 | 'bottom'
78 | 'left'
79 | 'right'
80 | 'top-start'
81 | 'top-end'
82 | 'bottom-start'
83 | 'bottom-end'
84 | 'left-start'
85 | 'left-end'
86 | 'right-start'
87 | 'right-end';
88 /** Maximum width of the tooltip (default 150px). */
89 maxWidth?: string;
90 /** Delay in ms before the tooltip disappears. */
91 exitDelay?: number;
92 /** Delay in ms before the tooltip appears. */
93 entryDelay?: number;
94 /** A function that is triggered on clicking the copy button. This will replace the existing clipboard copy functionality entirely. */
95 onCopy?: (event: React.ClipboardEvent<HTMLDivElement>, text?: React.ReactNode) => void;
96 /** A function that is triggered on changing the text. */
97 onChange?: (event: React.FormEvent, text?: string) => void;
98 /** Callback function when text input is focused */
99 onInputFocus?: (event?: any) => void;
100 /** Callback function when text input is blurred (focus leaves) */
101 onInputBlur?: (event?: any) => void;
102 /** The text which is copied. */
103 children: string | string[];
104 /** Additional actions for inline clipboard copy. Should be wrapped with ClipboardCopyAction. */
105 additionalActions?: React.ReactNode;
106 /** Enables and customizes truncation for an inline-compact ClipboardCopy. */
107 truncation?: boolean | Omit<TruncateProps, 'content'>;
108 /** Value to overwrite the randomly generated data-ouia-component-id.*/
109 ouiaId?: number | string;
110 /** Set the value of data-ouia-safe. Only set to true when the component is in a static state, i.e. no animations are occurring. At all other times, this value must be false. */
111 ouiaSafe?: boolean;
112 }
113
114 class ClipboardCopy extends Component<ClipboardCopyProps, ClipboardCopyState> {
115 static displayName = 'ClipboardCopy';
116 timer = null as number;
117 private clipboardRef: React.RefObject<any>;
118 constructor(props: ClipboardCopyProps) {
119 super(props);
120 const text = Array.isArray(this.props.children) ? this.props.children.join(' ') : (this.props.children as string);
121 this.state = {
122 text,
123 expanded: this.props.isExpanded,
124 copied: false,
125 textWhenExpanded: text
126 };
127
128 this.clipboardRef = createRef();
129 }
130
131 static defaultProps: PickOptional<ClipboardCopyProps> = {
132 hoverTip: 'Copy to clipboard',
133 clickTip: 'Successfully copied to clipboard!',
134 isReadOnly: false,
135 isExpanded: false,
136 isCode: false,
137 variant: 'inline',
138 position: TooltipPosition.top,
139 maxWidth: '150px',
140 exitDelay: 1500,
141 entryDelay: 300,
142 onCopy: clipboardCopyFunc,
143 onChange: (): any => undefined,
144 textAriaLabel: 'Copyable input',
145 toggleAriaLabel: 'Show content',
146 additionalActions: null,
147 truncation: false,
148 ouiaSafe: true
149 };
150
151 // eslint-disable-next-line @typescript-eslint/no-unused-vars
152 componentDidUpdate = (prevProps: ClipboardCopyProps, prevState: ClipboardCopyState) => {
153 if (prevProps.children !== this.props.children) {
154 const newText = Array.isArray(this.props.children)
155 ? this.props.children.join(' ')
156 : (this.props.children as string);
157 this.setState({ text: newText, textWhenExpanded: newText });
158 }
159 };
160
161 componentWillUnmount = () => {
162 if (this.timer) {
163 window.clearTimeout(this.timer);
164 }
165 };
166
167 expandContent = (_event: React.MouseEvent<Element, MouseEvent>) => {
168 this.setState((prevState) => ({
169 expanded: !prevState.expanded
170 }));
171 };
172
173 updateText = (event: React.FormEvent, text: string) => {
174 this.setState({ text });
175 this.props.onChange(event, text);
176 };
177
178 updateTextWhenExpanded = (event: React.FormEvent, text: string) => {
179 this.setState({ textWhenExpanded: text });
180 this.props.onChange(event, text);
181 };
182
183 render = () => {
184 const {
185 /* eslint-disable @typescript-eslint/no-unused-vars */
186 isExpanded,
187 onChange, // Don't pass to <div>
188 onInputFocus, // Don't pass to <div>
189 onInputBlur, // Don't pass to <div>
190 /* eslint-enable @typescript-eslint/no-unused-vars */
191 isReadOnly,
192 isCode,
193 isBlock,
194 exitDelay,
195 maxWidth,
196 entryDelay,
197 onCopy,
198 hoverTip,
199 clickTip,
200 textAriaLabel,
201 toggleAriaLabel,
202 inputId,
203 inputName,
204 variant,
205 position,
206 className,
207 additionalActions,
208 truncation,
209 ouiaId,
210 ouiaSafe,
211 copyAriaLabel,
212 ...divProps
213 } = this.props;
214 const textIdPrefix = 'text-input-';
215 const toggleIdPrefix = 'toggle-';
216 const contentIdPrefix = 'content-';
217
218 const copyableText = this.state.text;
219 const shouldTruncate = variant === ClipboardCopyVariant.inlineCompact && truncation;
220 const inlineCompactContent = shouldTruncate ? (
221 <Truncate
222 tooltipProps={{ triggerRef: this.clipboardRef }}
223 content={copyableText}
224 {...(typeof truncation === 'object' && truncation)}
225 />
226 ) : (
227 copyableText
228 );
229
230 return (
231 <div
232 className={css(
233 styles.clipboardCopy,
234 variant === ClipboardCopyVariant.inlineCompact && styles.modifiers.inline,
235 isBlock && styles.modifiers.block,
236 this.state.expanded && styles.modifiers.expanded,
237 shouldTruncate && styles.modifiers.truncate,
238 className
239 )}
240 ref={this.clipboardRef}
241 {...(shouldTruncate && { tabIndex: 0 })}
242 {...divProps}
243 {...getOUIAProps(ClipboardCopy.displayName, ouiaId, ouiaSafe)}
244 >
245 {variant === ClipboardCopyVariant.inlineCompact && (
246 <GenerateId prefix="">
247 {(id) => (
248 <Fragment>
249 {!isCode && (
250 <span className={css(styles.clipboardCopyText)} id={`${textIdPrefix}${id}`}>
251 {inlineCompactContent}
252 </span>
253 )}
254 {isCode && (
255 <code className={css(styles.clipboardCopyText, styles.modifiers.code)} id={`${textIdPrefix}${id}`}>
256 {inlineCompactContent}
257 </code>
258 )}
259 <span className={css(styles.clipboardCopyActions)}>
260 <span className={css(styles.clipboardCopyActionsItem)}>
261 <ClipboardCopyButton
262 variant="plain"
263 exitDelay={exitDelay}
264 entryDelay={entryDelay}
265 maxWidth={maxWidth}
266 position={position}
267 id={`copy-button-${id}`}
268 aria-label={copyAriaLabel ?? hoverTip}
269 onClick={(event: any) => {
270 onCopy(event, copyableText);
271 this.setState({ copied: true });
272 }}
273 onTooltipHidden={() => this.setState({ copied: false })}
274 hasNoPadding
275 >
276 {this.state.copied ? clickTip : hoverTip}
277 </ClipboardCopyButton>
278 </span>
279 {additionalActions && additionalActions}
280 </span>
281 </Fragment>
282 )}
283 </GenerateId>
284 )}
285 {variant !== ClipboardCopyVariant.inlineCompact && (
286 <GenerateId prefix="">
287 {(id) => (
288 <Fragment>
289 <div className={css(styles.clipboardCopyGroup)}>
290 {variant === ClipboardCopyVariant.expansion && (
291 <ClipboardCopyToggle
292 isExpanded={this.state.expanded}
293 onClick={(_event) => {
294 this.expandContent(_event);
295 if (this.state.expanded) {
296 this.setState({ text: this.state.textWhenExpanded });
297 } else {
298 this.setState({ textWhenExpanded: copyableText });
299 }
300 }}
301 id={`${toggleIdPrefix}${id}`}
302 contentId={`${contentIdPrefix}${id}`}
303 aria-label={toggleAriaLabel}
304 />
305 )}
306 <TextInput
307 readOnlyVariant={isReadOnly || this.state.expanded ? 'default' : undefined}
308 onChange={this.updateText}
309 value={this.state.expanded ? this.state.textWhenExpanded : copyableText}
310 id={inputId ?? `text-input-${id}`}
311 name={inputName}
312 aria-label={textAriaLabel}
313 onFocus={onInputFocus}
314 onBlur={onInputBlur}
315 {...(isCode && { dir: 'ltr' })}
316 />
317 <ClipboardCopyButton
318 exitDelay={exitDelay}
319 entryDelay={entryDelay}
320 maxWidth={maxWidth}
321 position={position}
322 id={`copy-button-${id}`}
323 aria-label={copyAriaLabel ?? hoverTip}
324 onClick={(event: any) => {
325 onCopy(event, this.state.expanded ? this.state.textWhenExpanded : copyableText);
326 this.setState({ copied: true });
327 }}
328 onTooltipHidden={() => this.setState({ copied: false })}
329 >
330 {this.state.copied ? clickTip : hoverTip}
331 </ClipboardCopyButton>
332 </div>
333 {this.state.expanded && (
334 <ClipboardCopyExpanded
335 isReadOnly={isReadOnly}
336 isCode={isCode}
337 id={`content-${id}`}
338 onChange={this.updateTextWhenExpanded}
339 >
340 {copyableText}
341 </ClipboardCopyExpanded>
342 )}
343 </Fragment>
344 )}
345 </GenerateId>
346 )}
347 </div>
348 );
349 };
350 }
351
352 export { ClipboardCopy };