-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path02-html-and-js-copy-clipboard.qmd
73 lines (54 loc) · 1.81 KB
/
02-html-and-js-copy-clipboard.qmd
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
---
title: "Quarto & JS"
format:
html:
include-in-header:
text: '<script src="./js/copyToClipboard.js"></script>'
---
# Task: Copy R Output Chunk to Clipboard with JS
## Input/Output
```{r}
print("[email protected]")
```
## A: HTML Code chunk with a \<button onclick="function()" />
> Note that the function is imported from a`.js` file in the document header
> consider assinging a `id` (`label`?) to the code chunk and try to grab the `.cell-output code` by `#id`
```{=html}
<button onclick="copyToClipboard('.cell-output code')">Copy</button>
```
## B: raw HTML button (no chunk) + inline definition of copy function
<button onclick="copyToClipboard('.cell-output code')">Copy</button>
## C: recycling a OJS DOM generic
> see [https://github.com/observablehq/inputs#Button](https://github.com/observablehq/inputs#Button)
```{ojs}
//| code-fold: true
Inputs.button(
html`📧 <i>Copy</i>`,
{value: null, reduce:() => copyToClipboard('.cell-output code')}
)
```
## D: same as C but function is defined in OJS chunk
```{ojs}
//| code-fold: false
copyToClipboardB = function(domRef) {
// get DOM Element which contains the output
// i.e. ".cell-output code" to the first output chunk
const dom = document.querySelector(domRef);
// get the clean inner string of the DOM Element (no HTML)
const innerText = dom.innerText;
// with RegEx, remove [nr] and "
const cleanString = innerText.replace(/\[\d+]\s/, '').replace(/"/g, "")
// write to clipboard
navigator.clipboard.writeText(cleanString);
console.log(cleanString) // TODO: remove in production
}
```
```{ojs}
//| echo: false
Inputs.button("Copy", {value: null, reduce:() => copyToClipboardB('.cell-output code') })
```
## E: using a OJS `html` template literal
```{ojs}
html`
<button onclick="copyToClipboard('.cell-output code')">Copy</button>`
```