Published
Edited
Aug 23, 2021
10 forks
Importers
40 stars
Insert cell
Insert cell
viewof image = imageInput({
crossOrigin: "anonymous",
initialUrl: await FileAttachment("beastie-boys.jpg").url()
})
Insert cell
image
Insert cell
viewof data = jsonInput({
initialUrl: await FileAttachment("points.json").url()
})
Insert cell
data
Insert cell
Insert cell
function fileInput({
initialUrl, // e.g., "https://example.com/file.txt"
accept, // e.g., ".txt,.md"
load = value => value // A function to specify which value is exposed.
}) {
let file = null;
const form = html`<form>
${Object.assign(html`<input name=url>`, {value: initialUrl})}
<button>Submit</button>
${Object.assign(html`<input data-type=file name=file type=file>`, {accept})}
`;
form.onsubmit = event => {
form.value = load(form.url.value);
form.dispatchEvent(new CustomEvent("input"));
event.preventDefault();
};
form.url.oninput = event => {
event.stopPropagation();
};
form.file.oninput = () => {
if (file !== null) URL.revokeObjectURL(file);
file = URL.createObjectURL(form.file.files[0]);
form.value = load(form.url.value = file);
};
if (initialUrl !== undefined) {
form.value = load(initialUrl);
}
return form;
}
Insert cell
function imageInput({initialUrl, width, height, crossOrigin, accept = ".png,.jpg,.gif,.webp"}) {
return fileInput({
initialUrl,
accept,
load(url) {
return new Promise((resolve, reject) => {
const image = new Image;
image.style.display = "block";
if (width !== undefined) image.width = width;
if (height !== undefined) image.height = height;
if (crossOrigin !== undefined) image.crossOrigin = crossOrigin;
image.onload = () => resolve(image);
image.onerror = reject;
image.src = url;
});
}
});
}
Insert cell
function jsonInput({initialUrl, init, accept = ".json"}) {
return fileInput({
initialUrl,
accept,
load(url) {
return fetch(url, init).then(response => {
if (!response.ok) throw new Error(response.status + " " + response.statusText);
return response.json();
});
}
});
}
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