1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var tslib_1 = require("tslib");
|
---|
4 | var copy_to_clipboard_1 = tslib_1.__importDefault(require("copy-to-clipboard"));
|
---|
5 | var react_1 = require("react");
|
---|
6 | var useMountedState_1 = tslib_1.__importDefault(require("./useMountedState"));
|
---|
7 | var useSetState_1 = tslib_1.__importDefault(require("./useSetState"));
|
---|
8 | var useCopyToClipboard = function () {
|
---|
9 | var isMounted = useMountedState_1.default();
|
---|
10 | var _a = useSetState_1.default({
|
---|
11 | value: undefined,
|
---|
12 | error: undefined,
|
---|
13 | noUserInteraction: true,
|
---|
14 | }), state = _a[0], setState = _a[1];
|
---|
15 | var copyToClipboard = react_1.useCallback(function (value) {
|
---|
16 | if (!isMounted()) {
|
---|
17 | return;
|
---|
18 | }
|
---|
19 | var noUserInteraction;
|
---|
20 | var normalizedValue;
|
---|
21 | try {
|
---|
22 | // only strings and numbers casted to strings can be copied to clipboard
|
---|
23 | if (typeof value !== 'string' && typeof value !== 'number') {
|
---|
24 | var error = new Error("Cannot copy typeof " + typeof value + " to clipboard, must be a string");
|
---|
25 | if (process.env.NODE_ENV === 'development')
|
---|
26 | console.error(error);
|
---|
27 | setState({
|
---|
28 | value: value,
|
---|
29 | error: error,
|
---|
30 | noUserInteraction: true,
|
---|
31 | });
|
---|
32 | return;
|
---|
33 | }
|
---|
34 | // empty strings are also considered invalid
|
---|
35 | else if (value === '') {
|
---|
36 | var error = new Error("Cannot copy empty string to clipboard.");
|
---|
37 | if (process.env.NODE_ENV === 'development')
|
---|
38 | console.error(error);
|
---|
39 | setState({
|
---|
40 | value: value,
|
---|
41 | error: error,
|
---|
42 | noUserInteraction: true,
|
---|
43 | });
|
---|
44 | return;
|
---|
45 | }
|
---|
46 | normalizedValue = value.toString();
|
---|
47 | noUserInteraction = copy_to_clipboard_1.default(normalizedValue);
|
---|
48 | setState({
|
---|
49 | value: normalizedValue,
|
---|
50 | error: undefined,
|
---|
51 | noUserInteraction: noUserInteraction,
|
---|
52 | });
|
---|
53 | }
|
---|
54 | catch (error) {
|
---|
55 | setState({
|
---|
56 | value: normalizedValue,
|
---|
57 | error: error,
|
---|
58 | noUserInteraction: noUserInteraction,
|
---|
59 | });
|
---|
60 | }
|
---|
61 | }, []);
|
---|
62 | return [state, copyToClipboard];
|
---|
63 | };
|
---|
64 | exports.default = useCopyToClipboard;
|
---|