File size: 2,375 Bytes
24cc101 | 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 | import marimo
__generated_with = "0.15.2"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
import anywidget
import traitlets
return anywidget, mo, traitlets
@app.cell
def _(mo):
mo.md(
r"""
# Marimo Copy Button
Using [anywidget](https://anywidget.dev/).
Check out accompanying blog post on [LovelyData](https://www.lovelydata.cz/en/blog/marimo-copy-button/).
"""
)
return
@app.cell
def _(anywidget, traitlets):
class CopyButton(anywidget.AnyWidget):
value = traitlets.Any("").tag(sync=True)
label = traitlets.Unicode("Copy to clipboard").tag(sync=True)
_esm = """
function render({ model, el }) {
const button = document.createElement("button");
const buttonText = model.get("label");
button.innerText = buttonText;
button.classList.add(
"font-medium", "bg-primary", "text-primary-foreground",
"hover:bg-primary/90", "shadow-xs", "border",
"border-primary", "h-7", "px-2", "rounded-md", "cursor-pointer")
el.appendChild(button);
// Add event listener to the button
button.addEventListener("click", async () => {
const valueToCopy = model.get('value');
try {
await navigator.clipboard.writeText(valueToCopy);
button.innerText = 'Copied!';
} catch (err) {
console.error('Failed to copy text:', err);
button.innerText = 'Error copying!';
} finally {
setTimeout(() => {
button.innerText = buttonText;
}, 2000);
}
});
}
export default { render };
"""
return (CopyButton,)
@app.cell
def _(mo):
copy_area = mo.ui.text_area(label="**Write something smart...**")
paste_area = mo.ui.text_area(label="**... and paste it here**")
return copy_area, paste_area
@app.cell
def _(CopyButton, copy_area, mo, paste_area):
mo.hstack(
[
mo.vstack([copy_area, CopyButton(value=copy_area.value, label="Copy to clipboard")]),
paste_area
],
widths="equal"
)
return
if __name__ == "__main__":
app.run()
|