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

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more