main
Last change
on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago |
Update repo after prototype presentation
|
-
Property mode
set to
100644
|
File size:
2.2 KB
|
Rev | Line | |
---|
[d565449] | 1 | import writeText from 'copy-to-clipboard';
|
---|
| 2 | import { useCallback } from 'react';
|
---|
| 3 | import useMountedState from './useMountedState';
|
---|
| 4 | import useSetState from './useSetState';
|
---|
| 5 | var useCopyToClipboard = function () {
|
---|
| 6 | var isMounted = useMountedState();
|
---|
| 7 | var _a = useSetState({
|
---|
| 8 | value: undefined,
|
---|
| 9 | error: undefined,
|
---|
| 10 | noUserInteraction: true,
|
---|
| 11 | }), state = _a[0], setState = _a[1];
|
---|
| 12 | var copyToClipboard = useCallback(function (value) {
|
---|
| 13 | if (!isMounted()) {
|
---|
| 14 | return;
|
---|
| 15 | }
|
---|
| 16 | var noUserInteraction;
|
---|
| 17 | var normalizedValue;
|
---|
| 18 | try {
|
---|
| 19 | // only strings and numbers casted to strings can be copied to clipboard
|
---|
| 20 | if (typeof value !== 'string' && typeof value !== 'number') {
|
---|
| 21 | var error = new Error("Cannot copy typeof " + typeof value + " to clipboard, must be a string");
|
---|
| 22 | if (process.env.NODE_ENV === 'development')
|
---|
| 23 | console.error(error);
|
---|
| 24 | setState({
|
---|
| 25 | value: value,
|
---|
| 26 | error: error,
|
---|
| 27 | noUserInteraction: true,
|
---|
| 28 | });
|
---|
| 29 | return;
|
---|
| 30 | }
|
---|
| 31 | // empty strings are also considered invalid
|
---|
| 32 | else if (value === '') {
|
---|
| 33 | var error = new Error("Cannot copy empty string to clipboard.");
|
---|
| 34 | if (process.env.NODE_ENV === 'development')
|
---|
| 35 | console.error(error);
|
---|
| 36 | setState({
|
---|
| 37 | value: value,
|
---|
| 38 | error: error,
|
---|
| 39 | noUserInteraction: true,
|
---|
| 40 | });
|
---|
| 41 | return;
|
---|
| 42 | }
|
---|
| 43 | normalizedValue = value.toString();
|
---|
| 44 | noUserInteraction = writeText(normalizedValue);
|
---|
| 45 | setState({
|
---|
| 46 | value: normalizedValue,
|
---|
| 47 | error: undefined,
|
---|
| 48 | noUserInteraction: noUserInteraction,
|
---|
| 49 | });
|
---|
| 50 | }
|
---|
| 51 | catch (error) {
|
---|
| 52 | setState({
|
---|
| 53 | value: normalizedValue,
|
---|
| 54 | error: error,
|
---|
| 55 | noUserInteraction: noUserInteraction,
|
---|
| 56 | });
|
---|
| 57 | }
|
---|
| 58 | }, []);
|
---|
| 59 | return [state, copyToClipboard];
|
---|
| 60 | };
|
---|
| 61 | export default useCopyToClipboard;
|
---|
Note:
See
TracBrowser
for help on using the repository browser.