Published
Edited
Feb 19, 2021
Importers
24 stars
Insert cell
Insert cell
Insert cell
Insert cell
viewof csv = CSVText({value: sampleCSV})
Insert cell
Insert cell
csv
Insert cell
Insert cell
viewof tsv = TSVText({value: sampleCSV})
Insert cell
Insert cell
tsv
Insert cell
Insert cell
Insert cell
viewof json = JSONText({value: sampleJSON})
Insert cell
json
Insert cell
Insert cell
viewof list = ListText({value: [-10000, 2750, 4250, 3250, 2750]})
Insert cell
list
Insert cell
Insert cell
viewof a = JSONText({value: ["First", "Second", "Third"]})
Insert cell
viewof b = bind(ListText(), viewof a)
Insert cell
a
Insert cell
Insert cell
ParsedText = ({value = "", parser = d => d, formatter = d => d} = {}) => {
const textarea = html`<textarea style=${style} oninput=${oninput}>`;
const node = html`<form onsubmit=${onsubmit}>
${textarea}
<button type=submit>Submit</button>
</form>`;

function oninput(e) {
e.stopPropagation();
}
function onsubmit(e) {
set(node, textarea.value);
e.preventDefault();
}

// Update the display whenever the value changes
Object.defineProperty(node, "value", {
get() {
return parser(value);
},
set(v) {
if (typeof v === "object") v = formatter(v);
textarea.value = value = v;
}
});

// Set the initial value
node.value = value;

return node;
}
Insert cell
DSVText = ({value, row = d3.autoType, delimiter = ",", headers = true} = {}) => {
const dsv = d3.dsvFormat(delimiter);
const parser = headers ? d => dsv.parse(d, row) : d => dsv.parseRows(d, row);
const formatter = headers ? dsv.format : dsv.formatRows;
return ParsedText({value, parser, formatter});
}
Insert cell
CSVText = options => DSVText({...options, delimiter: ","})
Insert cell
TSVText = options => DSVText({...options, delimiter: "\t"})
Insert cell
ListText = options => ParsedText({
...options,
parser: d => d3.autoType(d.split("\n")),
formatter: d => d.map(autoFormat).join("\n")
})
Insert cell
JSONText = options => ParsedText({
...options,
parser: JSON.parse,
formatter: d => JSON.stringify(d, null, 2)
})
Insert cell
style = ({
display: "block",
marginBottom: "3px",
width: "240px",
height: "120px",
fontFamily: "var(--sans-serif)",
whiteSpace: "nowrap"
})
Insert cell
function set(input, value) {
input.value = value;
input.dispatchEvent(new Event("input"));
}
Insert cell
autoFormat = d => d instanceof Date ? dateFormat(d) : String(d)
Insert cell
dateFormat = d3.utcFormat("%Y-%m-%d")
Insert cell
sampleCSV = FileAttachment("sample@1.csv").csv({typed: true})
Insert cell
sampleJSON = FileAttachment("sample.json").json()
Insert cell
d3 = require("d3@6")
Insert cell
import {bind, html} from "@observablehq/inputs"
Insert cell
import {toc} from "@mbostock/toc"
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more