Public
Edited
Dec 27, 2022
Importers
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
viewof wiki = SearchForm({
placeholder: "Type-in to search...",
description: "Searching en.wikipedia.org entities",
defaultValue: 'Test',
suggestion: async (text) => {
const res = await d3.json(
`https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${text}&namespace=0&limit=10&origin=*`
);
return res[1];
}
})
Insert cell
wiki
Insert cell
Insert cell
Insert cell
Insert cell
viewof wikiObject = SearchForm({
placeholder: "Type-in to search...",
description: "Searching en.wikipedia.org entities with their URLs",
format: (d) => d.entry, // what you want to search and display
suggestion: async (text) => {
const res = await d3.json(
`https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${text}&namespace=0&limit=10&origin=*`
);
return res[1].map((d, i) => ({
entry: d,
url: res[3][i]
}));
}
})
Insert cell
wikiObject
Insert cell
Insert cell
Insert cell
function SearchForm({
uid = DOM.uid("autosuggestion").id,
placeholder = "",
description = "",
format = (d) => d,
suggestion = () => [],
defaultValue = ""
} = {}) {
const input = htl.html`<input
type="text"
placeholder="${placeholder}"
list="${uid}"
autocomplete="off"
>`;

const tag = htl.html`<div style="font-size: 0.85rem; font-style: italic; margin-top: 3px;">${description}</div>`;

const datalist = htl.html`<datalist id="${uid}">`;

const form = htl.html`<div>${input}${tag}${datalist}`;

let results = [];

form.value = defaultValue; // starting value
form.onsubmit = (event) => event.preventDefault();

form.onchange = (event) => {
const value = event.target.value;
console.log('form.onchange', value, form.value)
form.value = results.find((d) => format(d) == value) || "";
input.blur(); // removes keyboard focus from the element upon submission
form.dispatchEvent(new CustomEvent("input"));
};

// "cache"
const options = new Map();

const getOption = async (text) =>
options.get(text) ||
(text ? options.set(text, await suggestion(text)) : options.set(text, []),
options.get(text));

input.oninput = async (event) => {
let value = event.target.value;

results = await getOption(value);

d3.select(`#${uid}`)
.selectAll("option")
.data(results)
.join("option")
.attr("value", format);
};

if (defaultValue) {
form.dispatchEvent(new CustomEvent("input"));
form.querySelector('input').value = defaultValue;
}

return form;
}
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