Alright, let’s dive in.
First things first: You can import UrlParam
just like any other cell:
import {UrlParam} from '@mootari/triangles-and-circles'
If you copy over code, please remember to add a comment for the proper attribution.
Next, we’ll discard inputGroup
because it adds another layer of abstraction that will be difficult to deal with. However, we’ll import a new helper that enables us to change values of @jashkenas/inputs widgets from the outside:
import {mutableForm} from '@mootari/mutable-forms'
Time to build our options form. A little more overhead since we’ll go fully custom, but that gives us a high degree of flexibility.
viewof options = {
const widgets = {
sides: mutableForm(slider({
title: 'Number of sides (grid)', min:3, max: 20, step: 1, value: 8,
})),
radius: mutableForm(slider({
title: 'Size', min:3, max: 20, step: 1, value: 8,
})),
};
// The outermost div is what we present to Observable's Runtime as our view.
// It wraps both widgets, nicely lining them up horizontally.
const view = html`<div style="display:flex;flex-wrap:wrap">
<div style="margin:0 10px 10px">${widgets.sides}</div>
<div style="margin:0 10px 10px">${widgets.radius}</div>
`;
// Empty value object for our view which we'll populate below.
view.value = {};
// For each widget, add a property to the value.
for(const [name, widget] of Object.entries(widgets)) {
Object.defineProperty(view.value, name, {
// Getter. Accessing options[name] returns widgets[name].value
get: () => widget.value,
// Setter. Assigning a value to options[name] sets it for widgets[name].value
set: value => { widget.value = value },
// Makes the property visible in the Inspector (and when iterating over the properties).
enumerable: true,
});
}
return view;
}
All we need to do now is to set the options from the URL. Removing the fluff texts, we’re left with:
{
const preset = new UrlParam('preset').getData();
// A shorthand to the value object.
const value = viewof options.value;
for(const name in preset) {
// Simply assign all values. mutableForm() takes care of
// setting the value on a widget's input and dispatching
// the required event.
if(name in value) value[name] = preset[name];
}
// Let's see what was in that preset data.
return preset;
}