Skip to content

mootari/inputs

 
 

Repository files navigation

Observable Inputs

Observable Inputs are lightweight user interface components — buttons, sliders, dropdowns, tables, and the like — to help you explore data and build interactive displays in Observable notebooks. Each input can be used as an Observable view. For example, to allow a number x to be manipulated by a slider:

viewof x = Range([0, 100])

Now you can reference the live value of x in any cell, e.g.:

md`The value of *x* is ${x}.`

Any cell that references x will run automatically when the viewof x slider is moved. For live examples, see:

https://observablehq.com/@observablehq/inputs

Observable Inputs provides basic inputs:

  • Button - do something when a button is clicked
  • Checkbox - choose any from a set
  • Toggle - toggle between two values (on or off)
  • Radio - choose one from a set
  • Range - choose a numeric value in a range (slider)
  • Select - choose one or many from a set (drop-down menu)
  • Text - freeform single-line text input
  • Textarea - freeform multi-line text input

Observable Inputs provides fancy inputs for tabular data:

  • Search - query a tabular dataset
  • Table - browse a tabular dataset

Lastly, Inputs provides low-level utilities for more advanced usage:

  • Input - a programmatic interface for storing input state
  • bind - synchronize two or more inputs
  • disposal - detect when an input is discarded

Observable Inputs are released under the ISC license and depend only on Hypertext Literal, our tagged template literal for safely generating dynamic HTML.

Installing

In the near future, these components will be incorporated into the Observable standard library and available in notebooks by default. To use on Observable now:

import {Button, Checkbox, Toggle, Radio, Range, Select, Text, Search, Table} from "@observablehq/inputs"

Inputs

# Button(content = "≡", options) · Source, Examples

A Button labeled OK

viewof clicks = Button("OK", {label: "Click me"})

A Button emits an input event when you click it. Buttons may be used to trigger the evaluation of cells, say to restart an animation. The given content, either a string or an HTML element, is displayed within the button. If content is not specified, it defaults to “≡”, but a more meaningful value is strongly encouraged for usability.

By default, the value of a solitary Button (when content is a string or HTML) is how many times it has been clicked. The reduce function allows you to compute the new value of the Button when clicked, given the old value. For example, to set the value as the time of last click:

viewof time = Button("Refresh", {value: null, reduce: () => Date.now()})

If content is an array or iterable, then multiple buttons will be generated. Each element in content should be a tuple [contenti, reducei], where contenti is the content for the given button (a string or HTML), and reducei is the function to call when that button is clicked. For example, to have a counter that you can increment, decrement, or reset to zero:

viewof counter = Button([
  ["Increment", value => value + 1],
  ["Decrement", value => value - 1],
  ["Reset", () => 0]
], {label: "Counter", value: 0})

The available options are:

  • label - a label; either a string or an HTML element.
  • value - the initial value; defaults to 0.
  • reduce - a function to update the value on click; by default returns value + 1.
  • width - the width of the input (not including the label).
  • disabled - whether input is disabled; defaults to false.

# Checkbox(data, options) · Source, Examples

A multi-choice Checkbox input of flavors

viewof flavor = Checkbox(["Salty", "Spicy", "Sour", "Umami"], {label: "Flavor"})

A Checkbox allows the user to choose any of a given set of values (any of the given elements in the iterable data). Unlike a Select, a Checkbox’s choices are all visible up-front. The Checkbox’s value is an array of the elements from data that are currently selected.

The elements in data need not be strings; they can be anything. To customize display, optional keyof and valueof functions may be given; the result of the keyof function for each element in data is displayed to the user, while the result of the valueof function is exposed in the Checkbox’s value when selected. If data is a Map, the keyof function defaults to the map entry’s key (([key]) => key) and the valueof function defaults to the map entry’s value (([, value]) => value); otherwise, both keyof and valueof default to the identity function (d => d). For example, with d3.group:

viewof sportAthletes = Checkbox(d3.group(athletes, d => d.sport))

Keys may be sorted and uniqued via the sort and unique options, respectively. Elements in data are formatted via an optional format function which has the same defaults as keyof. As with the label option, the format function may return either a string or an HTML element.

The available options are:

  • label - a label; either a string or an HTML element.
  • sort - true, “ascending”, “descending”, or a comparator function to sort keys; defaults to false.
  • unique - true to only show unique keys; defaults to false.
  • format - a format function; defaults to formatAuto.
  • keyof - a function to return the key for the given element in data.
  • valueof - a function to return the value of the given element in data.
  • value - the initial value, an array; defaults to an empty array (no selection).
  • disabled - whether input is disabled, or the disabled values; defaults to false.

# Toggle(options) · Source, Examples

viewof mute = Toggle({label: "Mute"})

A Toggle is a solitary checkbox. By default, the Toggle’s value is whether the checkbox is checked (true or false); a values = [on, off] option can be specified to toggle between two arbitrary values.

The available options are:

  • label - a label; either a string or an HTML element.
  • values - the two values to toggle between; defaults to [true, false].
  • value - the initial value; defaults to the second value (false).
  • disabled - whether input is disabled; defaults to false.

# Radio(data, options) · Source, Examples

A single-choice Radio input of colors

viewof color = Radio(["red", "green", "blue"]), {label: "Color"})

A Radio allows the user to choose one of a given set of values. Unlike a Select, a Radio’s choices are all visible up-front. The Radio’s value is an element from data, or null if no choice has been made.

The elements in data need not be strings; they can be anything. To customize display, optional keyof and valueof functions may be given; the result of the keyof function for each element in data is displayed to the user, while the result of the valueof function is exposed as the Radio’s value when selected. If data is a Map, the keyof function defaults to the map entry’s key (([key]) => key) and the valueof function defaults to the map entry’s value (([, value]) => value); otherwise, both keyof and valueof default to the identity function (d => d). For example, with d3.group:

viewof sportAthletes = Radio(d3.group(athletes, d => d.sport))

Keys may be sorted and uniqued via the sort and unique options, respectively. Elements in data are formatted via an optional format function which has the same defaults as keyof. As with the label option, the format function may return either a string or an HTML element.

The available options are:

  • label - a label; either a string or an HTML element.
  • sort - true, “ascending”, “descending”, or a comparator function to sort keys; defaults to false.
  • unique - true to only show unique keys; defaults to false.
  • format - a format function; defaults to formatAuto.
  • keyof - a function to return the key for the given element in data.
  • valueof - a function to return the value of the given element in data.
  • value - the initial value; defaults to null (no selection).
  • disabled - whether input is disabled, or the disabled values; defaults to false.

# Range([min, max] = [0, 1], options) · Source, Examples

A Range input of intensity, a number between 0 and 100

viewof intensity = Range([0, 100], {step: 1, label: "Intensity"})

A Range input specifies a number between the given min and max (inclusive). This number can be adjusted roughly with a slider, or precisely by typing a number.

The available options are:

  • label - a label; either a string or an HTML element.
  • step - the step (precision); the interval between adjacent values.
  • format - a format function; must return a valid number string.
  • placeholder - a placeholder string for when the input is empty.
  • transform - an optional non-linear transform.
  • invert - the inverse transform.
  • value - the initial value; defaults to (min + max) / 2.
  • width - the width of the input (not including the label).
  • disabled - whether input is disabled; defaults to false.
  • validate - a function to check whether the number input is valid.

The given value is clamped to the given extent, and rounded if step is defined. However, note that the min, max and step options affect only the slider behavior, the number input’s buttons, and whether the browser shows a warning if a typed number is invalid; they do not constrain the typed number.

If a transform function is specified, an inverse transform function invert is strongly recommended. If invert is not provided, the Range will fallback to Newton’s method, but this may be slow or inaccurate. Passing Math.sqrt, Math.log, or Math.exp as a transform will automatically supply the corresponding invert. If min is greater than max, i.e. if the extent is inverted, then transform and invert will default to value => -value.

If validate is not defined, text.checkValidity is used. While the input is not considered valid, changes to the input will not be reported.

# Search(data, options) · Source, Examples

A Search input over a tabular dataset of athletes

viewof foundAthletes = Search(athletes, {label: "Athletes"})

A Search input allows freeform, full-text search of an in-memory tabular dataset or an iterable (column) of values using a simple query parser. It is often used in conjunction with a Table. The value of a Search is an array of elements from the iterable data that match the current query. If the query is currently empty, the search input’s value is all elements in data.

A Search input can work with either tabular data (an array of objects) or a single column (an array of strings). When searching tabular input, all properties on each object in data are searched by default, but you can limit the search to a specific set of properties using the column option. For example, to only search the “sport” and “nationality” column:

viewof foundAthletes = Search(athletes, {label: "Athletes", columns: ["sport", "nationality"]})

For example, to search U.S. state names:

viewof state = Search(["Alabama", "Alaska", "Arizona", "Arkansas", "California", ], {label: "State"})

The available options are:

  • label - a label; either a string or an HTML element.
  • query - the initial search terms; defaults to the empty string.
  • placeholder - a placeholder string for when the query is empty.
  • columns - an array of columns to search; defaults to data.columns.
  • format - a function to show the number of results.
  • spellcheck - whether to activate the browser’s spell-checker.
  • filter - the filter factory: a function that receives the query and returns a filter.
  • width - the width of the input (not including the label).
  • datalist - an iterable of suggested values.
  • disabled - whether input is disabled; defaults to false.

If a filter function is specified, it is invoked whenever the query changes; the function it returns is then passed each element from data, along with its zero-based index, and should return a truthy value if the given element matches the query. The default filter splits the current query into space-separated tokens and checks that each token matches the beginning of at least one string in the data’s columns, case-insensitive. For example, the query [hello world] will match the string “Worldwide Hello Services” but not “hello”.

# Select(data, options) · Source, Examples

A Select input asking to choose a t-shirt size

viewof size = Select(["Small", "Medium", "Large"], {label: "Size"})
viewof inks = Select(["cyan", "magenta", "yellow", "black"], {multiple: true, label: "Inks"})

A Select allows the user to choose one of a given set of values (one of the given elements in the iterable data); or, if desired, multiple values may be chosen. Unlike a Radio, only one (or a few) choices are visible up-front, affording a compact display even when many options are available. If multiple choice is allowed via the multiple option, the Select’s value is an array of the elements from data that are currently selected; if single choice is required, the Select’s value is an element from data, or null if no choice has been made.

The elements in data need not be strings; they can be anything. To customize display, optional keyof and valueof functions may be given; the result of the keyof function for each element in data is displayed to the user, while the result of the valueof function is exposed as the Select’s value when selected. If data is a Map, the keyof function defaults to the map entry’s key (([key]) => key) and the valueof function defaults to the map entry’s value (([, value]) => value); otherwise, both keyof and valueof default to the identity function (d => d). For example, with d3.group:

viewof sportAthletes = Select(d3.group(athletes, d => d.sport))

Keys may be sorted and uniqued via the sort and unique options, respectively. Elements in data are formatted via an optional format function which has the same defaults as keyof. While the label option may be either a string or an HTML element, the format function must return a string (unlike a Radio).

The available options are:

  • label - a label; either a string or an HTML element.
  • multiple - whether to allow multiple choice; defaults to false.
  • size - if multiple is true, the number of options to show.
  • sort - true, “ascending”, “descending”, or a comparator function to sort keys; defaults to false.
  • unique - true to only show unique keys; defaults to false.
  • format - a format function; defaults to formatAuto.
  • keyof - a function to return the key for the given element in data.
  • valueof - a function to return the value of the given element in data.
  • value - the initial value, an array if multiple choice is allowed.
  • width - the width of the input (not including the label).
  • disabled - whether input is disabled, or the disabled values; defaults to false.

# Table(data, options) · Source, Examples

A Table input showing rows of Olympic athletes

A Table displays a tabular dataset; data should be an iterable of objects, such as the result of loading a CSV file. Each object corresponds to a row, while each field corresponds to a column. To improve performance with large datasets, the rows of the table are lazily rendered on scroll. Rows may be sorted by clicking column headers (once for ascending, then again for descending).

While intended primarily for display, a Table also serves as an input. The value of the Table is its selected rows: a filtered (and possibly sorted) view of the data. Rows can be selected by clicking or shift-clicking checkboxes. See also Search, which can be used for rapid filtering of the table’s rows.

By default, the Table infers the type of each column by inspecting values, assuming that non-null values in each column have consistent types. Numbers are formatted in English; dates are formatted in ISO 8601 UTC. Numbers columns are further right-aligned with tabular figures to assist comparison. The format and align of each column can be customized as options if desired.

By default, the Table uses fixed layout if data has fewer than twelve columns. This improves performance and avoids reflow when scrolling due to lazily-rendered rows. If data has twelve or more columns, the auto layout is used instead, which automatically sizes columns based on the content. This behavior can be changed by specifying the layout option explicitly.

The available options are:

  • columns - the columns (property names) to show; defaults to data.columns.
  • value - a subset of data to use as the initial selection (checked rows).
  • rows - the maximum number of rows to show; defaults to 11.5.
  • sort - the column to sort by; defaults to null (input order).
  • reverse - whether to reverse the initial sort (descending instead of ascending).
  • format - an object of column name to format function.
  • align - an object of column name to “left”, “right”, or “center”.
  • width - the table width, or an object of column name to width.
  • layout - the table layout; defaults to fixed for ≤12 columns.
  • required - if true, the table’s value is all data if no selection; defaults to true.

If width is “auto”, the table width will be based on the table contents; note that this may cause the table to resize as rows are lazily rendered.

# Text(options) · Source, Examples

A Text input asking to enter your name

viewof name = Text({label: "Name", placeholder: "Enter your name"})

A Text allows freeform single-line text input. For example, a Text might be used to allow the user to enter a search query. (See also Search.) By default, a Text will report its value immediately on input. If more deliberate behavior is desired, say if the input will trigger an expensive computation or remote API, the submit option can be set to true to wait until a button is clicked or the Enter key is pressed.

The available options are:

  • label - a label; either a string or an HTML element.
  • type - the input type, such as “password” or “email”; defaults to “text”.
  • value - the initial value; defaults to the empty string.
  • placeholder - the placeholder attribute.
  • spellcheck - whether to activate the browser’s spell-checker.
  • pattern - the pattern attribute.
  • minlength - minimum length attribute.
  • maxlength - maximum length attribute.
  • required - if true, the input must be non-empty; defaults to minlength > 0.
  • validate - a function to check whether the text input is valid.
  • width - the width of the input (not including the label).
  • submit - whether to require explicit submission before updating; defaults to false.
  • datalist - an iterable of suggested values.
  • readonly - whether input is readonly; defaults to false.
  • disabled - whether input is disabled; defaults to false.

If validate is not defined, text.checkValidity is used. While the input is not considered valid, changes to the input will not be reported.

# Textarea(options) · Source

A Textarea asking for your biography

viewof bio = Textarea({label: "Biography", placeholder: "Tell us a little about yourself…"})

A Textarea allows multi-line freeform text input. By default, a Textarea will report its value immediately on input. If more deliberate behavior is desired, the submit option can be set to true to wait until a button is clicked or Command-Enter is pressed.

The available options are:

  • label - a label; either a string or an HTML element.
  • value - the initial value; defaults to the empty string.
  • placeholder - the placeholder attribute.
  • spellcheck - whether to activate the browser’s spell-checker.
  • minlength - minimum length attribute.
  • maxlength - maximum length attribute.
  • required - if true, the input must be non-empty; defaults to minlength > 0.
  • validate - a function to check whether the text input is valid.
  • width - the width of the input (not including the label).
  • rows - the number of rows of text to show.
  • submit - whether to require explicit submission before updating; defaults to false.
  • readonly - whether input is readonly; defaults to false.
  • disabled - whether input is disabled; defaults to false.

If validate is not defined, text.checkValidity is used. While the input is not considered valid, changes to the input will not be reported.

Utilities

# Input(value) · Source, Examples

Returns an EventTarget with the specified value. This is typically used in conjunction with bind to synchronize multiple inputs, with the Input being the primary state store. An Input is similar to a mutable, except that it allows listeners.

# bind(target, source, invalidation) · Source, Examples

The bind function allows a target input to be bound to a source input, synchronizing the two: interaction with the source input will propagate to the target input and vice versa.

The relationship between target and source is not symmetric: the target input should be considered a dependant of the source input, and if desired, only the source should be declared an Observable view. For example:

viewof i = Input(42) // the “primary” input
bind(Range([0, 100]), viewof i) // a bound “secondary” input

When the target emits a type-appropriate event, the target’s type-appropriate value will be applied to the source and a type-appropriate event will be dispatched on the source; when the source emits a type-appropriate event, the source’s type-appropriate value will be applied to the target, but no event will be dispatched, avoiding an infinite loop.

The type-appropriate event is a click event for buttons and submit inputs, a change event for file inputs, and an input event for anything else. The type-appropriate value is input.valueAsNumber for range and number inputs, input.valueAsDate for date inputs, input.checked for checkbox inputs, input.files for multiple file inputs, input.files[0] for single-file inputs, and input.value for anything else.

If invalidation is specified, it is a promise; when the promise resolves, the target will stop listening to the source. If invalidation is not specified, it defaults to the disposal promise on the specified target. Note that source will remain listening to the target, however, until the target is garbage-collected.

# disposal(element) · Source

The disposal promise is a heuristic for detecting when an input has been removed from the DOM, say to detach synchronized inputs. It is used by bind by default as the invalidation promise, but is exported here for convenience.

# searchFilter(query) · Source

The default query parser used by Search.

# formatAuto(value) · Source

If value is null, returns the empty string; if value is a number, calls formatNumber if value is a date, calls formatDate; otherwise coerces value to a string.

# formatNumber(number) · Source

The default number formatter used by Table.

# formatDate(date) · Source

The default date formatter used by Table.

Packages

No packages published

Languages

  • JavaScript 48.8%
  • HTML 46.6%
  • CSS 4.6%