CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/frontend/copy-paste-buffer.ts
Views: 687
1
/*
2
* This file is part of CoCalc: Copyright © 2020 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
/*
7
An internal copy/paste buffer
8
9
MOTIVATION: There is no way to sync with the official operating system copy/paste buffer,
10
due to security restrictions. However, for some platforms (iPad, I'm looking at you!),
11
it's still very useful to have our own internal copy/paste buffer. This is it.
12
It stores a string right now. Who knows, maybe someboday it'll do interesting
13
richer content too.
14
*/
15
16
let buffer = "";
17
18
// TODO: get_buffer could be done via a permission request, though that is a potential security issue.
19
// See https://alligator.io/js/async-clipboard-api/
20
export function get_buffer(): string {
21
return buffer;
22
}
23
24
export function set_buffer(s: string | undefined): void {
25
buffer = s ?? "";
26
27
// In addition to saving the test to our own internal buffer (that get_buffer produces),
28
// we also attempt to write that buffer to the actual clipboard. In some cases this might
29
// work and produces a better user experience.
30
if (navigator.clipboard != null) {
31
// this is async -- requires at least chrome 66.
32
navigator.clipboard.writeText(buffer);
33
return;
34
}
35
// failing that, try to copy what is selected to the internal buffer...
36
try {
37
// https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand
38
// This ignores the input s above, since it operates on whatever is selected.
39
// NOTE: there might be no context in CoCalc where this will actually work, since
40
// it is supposed to be used in an event handler (like in the x11 xpra code?).
41
document.execCommand("copy");
42
} catch (_) {}
43
}
44
45