Published
Edited
Jun 24, 2018
Importers
1 star
Insert cell
Insert cell
viewof varname = cycling('I smell the ', ['red', 'blue'], [' roses',' violets'])
Insert cell
Insert cell
function cycling(prelude, choices, results) {
// Twine-style 'cycling links', but considerably more humane (to read, anyway)
// https://web.archive.org/web/20151117185450/http://furkleindustries.com/fictions/twine/twine2_resources/twine2_macros/
// wrapper dispatches events, c.f. https://beta.observablehq.com/@jashkenas/inputs
let form = html`<form name=form>
<span>${prelude}</span>
<input name=input type=button />
<output name=output />
</form>`
let widget = form.input // DOM.input('button')
let branching = Array.isArray(results)
let idx = 0 // TODO: is caching possible under topological sort?
function onClick(e) {
e && e.preventDefault()
// choices.push(choices.shift()) // YUCK, mutating external state.
// if (branching) results.push(results.shift())
idx = idx == choices.length-1 ? 0 : idx+1
refresh()
form.dispatchEvent(new CustomEvent("input"))
// consumed by Generators.input\1, as used by 'viewof' (TODO: link to actual cell)
// https://beta.observablehq.com/@mbostock/introduction-to-generators
// https://beta.observablehq.com/@mbostock/a-brief-introduction-to-viewof
}
function refresh() {
widget.value = choices[idx] // display value
form.value = [choices[idx], idx] // report value in an event
form.output.value = branching ? results[idx] : results // another magic display value
}
refresh()
widget.onclick = onClick // bind the effect
return form
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
style = html`<style>
@keyframes fadein {
from { opacity:0; }
to { opacity:1; }
}
</style>`
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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