Copier
This notebook ports a notebook by Mike Bostock [@mbostock] called Copier. All mistakes and deviations from the original are my own.
***Update Sep. 2021:*** *Buttons are now available as part of [**Observable Inputs**](/@observablehq/inputs), and you can use navigator.clipboard.writeText to copy text to the clipboard! This notebook will remain for history, but please upgrade.*
A button to help copy snippets of text to the clipboard. To use in your notebook:
~~~js
import {Copier} from "@mbostock/copier"
~~~
Copier("Click me!", {value: "Hello, world!"})
Copier([
["1", "I have eaten the plums that were in the icebox"],
["2", "and which you were probably saving for breakfast"],
["3", "Forgive me they were delicious so sweet and so cold"]
], {label: "Snippets"})
Implementation
(() => {
let count = 0;
return Object.assign(
html`<button>Click me to copy text!`,
{
onclick: () => pbcopy(`Hello, world! ${++count}`)
}
);
})()
const pbcopy = text => navigator.clipboard.writeText(text)
function Copier(content = "Copy code", options) {
if (Array.isArray(content)) content = Array.from(content, ([key, value]) => [key, () => (pbcopy(value), value)]);
return Inputs.button(content, {...options, reduce: (value) => (pbcopy(value), value)});
}
const copy = pbcopy // Deprecated alias