forked from microsoft/react-native-windows
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ClipboardModule.cs
111 lines (101 loc) · 3.21 KB
/
ClipboardModule.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using ReactNative.Bridge;
using System;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using DataTransfer = Windows.ApplicationModel.DataTransfer;
namespace ReactNative.Modules.Clipboard
{
/// <summary>
/// A module that allows JS to get/set clipboard contents.
/// </summary>
class ClipboardModule : NativeModuleBase
{
private readonly IClipboardInstance _clipboard;
public ClipboardModule() : this(new ClipboardInstance())
{
}
public ClipboardModule(IClipboardInstance clipboard)
{
_clipboard = clipboard;
}
/// <summary>
/// The name of the native module.
/// </summary>
public override string Name
{
get
{
return "Clipboard";
}
}
/// <summary>
/// Get the clipboard content through a promise.
/// </summary>
/// <param name="promise">The promise.</param>
[ReactMethod]
public void getString(IPromise promise)
{
if (promise == null)
{
throw new ArgumentNullException(nameof(promise));
}
RunOnDispatcher(async () =>
{
try
{
var clip = _clipboard.GetContent();
if (clip == null)
{
promise.Resolve("");
}
else if (clip.Contains(DataTransfer.StandardDataFormats.Text))
{
var text = await clip.GetTextAsync().AsTask().ConfigureAwait(false);
promise.Resolve(text);
}
else
{
promise.Resolve("");
}
}
catch (Exception ex)
{
promise.Reject(ex);
}
});
}
/// <summary>
/// Add text to the clipboard or clear the clipboard.
/// </summary>
/// <param name="text">The text. If null clear clipboard.</param>
[ReactMethod]
public void setString(string text)
{
RunOnDispatcher(() =>
{
if (text == null)
{
_clipboard.Clear();
}
else
{
var package = new DataTransfer.DataPackage();
package.SetData(DataTransfer.StandardDataFormats.Text, text);
_clipboard.SetContent(package);
}
});
}
/// <summary>
/// Run action on UI thread.
/// </summary>
/// <param name="action">The action.</param>
private static async void RunOnDispatcher(DispatchedHandler action)
{
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, action).AsTask().ConfigureAwait(false);
}
}
}