-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcopy.go
81 lines (69 loc) · 1.9 KB
/
copy.go
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
package components
import (
"fmt"
"strings"
"github.com/adrianolmedo/components/randutil"
lucide "github.com/eduardolat/gomponents-lucide"
"github.com/maragudk/gomponents"
"github.com/maragudk/gomponents/html"
)
// CopyButtonSimple is the same as CopyButton, but with a less
// verbose api and default props.
func CopyButtonSimple(textToCopy string) gomponents.Node {
return CopyButton(CopyButtonProps{
TextToCopy: textToCopy,
})
}
// CopyButtonProps is the properties for the CopyButton component.
type CopyButtonProps struct {
// TextToCopy is the text that should be copied to the
// clipboard when the button is clicked.
TextToCopy string
// Size is the size of the button. Can be "sm", "md" (default) or "lg".
Size Size
}
// CopyButton is a button that copies text to the clipboard when clicked.
func CopyButton(props CopyButtonProps) gomponents.Node {
id := randutil.UUIDStrWithoutDashes()
sc := copyButtonScript(id, props.TextToCopy)
return html.Div(
html.Class("inline-block"),
sc.script,
Button(ButtonProps{
Color: "neutral",
Size: props.Size,
Square: true,
Children: []gomponents.Node{
html.ID(id),
html.Title("Copiar"),
sc.copyEvent,
lucide.Copy(html.Class("size-4")),
},
}),
)
}
// copyButtonScript returns a script that copies the given text to the clipboard
// and an event that calls the script when clicked.
func copyButtonScript(
id string,
textToCopy string,
) struct {
script gomponents.Node
copyEvent gomponents.Node
} {
escapedTextToCopy := strings.ReplaceAll(textToCopy, "`", "\\`")
rawScript := fmt.Sprintf(
"<script>function copy%s(){ copyToClipboard(`%s`); }</script>",
id,
escapedTextToCopy,
)
script := gomponents.Raw(rawScript)
copyEvent := gomponents.Attr("onclick", fmt.Sprintf("copy%s()", id))
return struct {
script gomponents.Node
copyEvent gomponents.Node
}{
script: script,
copyEvent: copyEvent,
}
}