# Flourish controls

Add interchangeable controls (dropdown, buttons or slider), a searchbox and a controls container to a page.

## How to install

`npm install -s @flourish/controls`

Add one or more control objects to your template state as well an object for the controls container

``` js
export var state = {
	controls_container: {},
	buttons_control: {
		control_type: "buttons"
	},
	dropdown_control: {
		control_type: "dropdown"
	},
	...
}
```

Add settings for the controls container in `template.yml`.

``` yaml
  - property: controls_container
    import: "@flourish/controls/container"
```

This will add a controls container alignment and spacing options in the settings.

Then import `@flourish/controls` for each controls instance.

``` yaml
- property: buttons_control
    import: "@flourish/controls"
- property: dropdown_control
    import: "@flourish/controls"
```

## Basics

Initialise the controls container and individual controls outside any function:

``` js
import { createControlsContainer, createControls } from "@flourish/controls";

var buttons_control = createControls(state.buttons_control);
var dropdown_control = createControls(state.dropdown_control)

var controls_container = createControlsContainer(state.controls_container)
	.appendTo(layout.getSection("controls"))
	.add([buttons_control, dropdown_control]);

```

You can add an id string to a control using the second argument:

```js
var buttons_control = createControls(state.buttons_control, "fl-buttons-control");
```

Add an on change handler to each controls instance: `buttons_control.on("change", update);`. This is usually done in the `draw` function.

In `update` you typically want to update the set of `options` and then call `update` method on the container and control(s):

```
controls_container.update();

buttons_control
    .options(button_options)
    .update();

dropdown_control
    .options(dropdown_options)
    .update();
```

If you're using this module alongside `@flourish/ui-styles` you should call the update method from the ui-styles object first (this will ensure the dropdown icon correctly matches the size and color styles set in the ui-styles panel). For example:

```
function updateControlStyles() {
	controls_style.update();
	button_style.update();
	dropdown_style.update();
	slider_style.update();
}

updateControlStyles();
```

## Searchbox

Create a control with `control_type: "searchbox"`. Search is disabled by default;
set `search_enabled` to enable it. Import its editor settings separately:

```yaml
- property: searchbox
  import: "@flourish/controls/searchbox"
- property: searchbox_style
  import: "@flourish/ui-styles/searchbox-style"
```

The searchbox can be added to a controls container or appended directly to a DOM
node. Use `createSearchboxStyle` from `@flourish/ui-styles` for its styling:

```js
import { createControls } from "@flourish/controls";
import { createSearchboxStyle } from "@flourish/ui-styles";
import createSearch from "@flourish/search";

const state = {
	searchbox: { control_type: "searchbox", search_enabled: true },
	searchbox_style: {},
};
const searchbox = createControls(state.searchbox)
	.appendTo(document.querySelector("#search-container"))
	.on("change", (item) => {
		// Handle the selected result in the template.
		console.log(item.value);
	});
const searchbox_style = createSearchboxStyle(
	state.searchbox_style,
	"#search-container .fl-control-searchbox",
);

function updateSearch(items) {
	// Each item has a display label and a value identifying the result.
	searchbox_style.update();
	searchbox.options(items).visible(items.length > 0);
	searchbox.setSearchMethod(createSearch(items, (item) => item.label));
	searchbox.update();
}

updateSearch([{ label: "London", value: "london" }]);
```

Rebuild the search method when the searchable data changes. Templates decide
which records are searchable and what selecting a result does. If the searchbox
occupies layout space, update its visibility before measuring that space.

`search_placeholder` sets the placeholder. `search_dropdown` shows suggestions
on focus, including for an empty query; otherwise searching starts at two
characters. `search_mode` supports `anywhere`, `start` and `whole` when using
`@flourish/search`. A search function can also supply a `.normalizer()` before it
is passed to `setSearchMethod`.

### Searchbox methods and events

- `setSearchMethod(fn)` takes a function from query text to an array of results.
  `@flourish/search` provides this function, or you can supply your own. Without
  a custom method, the control uses a case-insensitive substring search over its
  options. Passing `null` makes searches return no results. Returns the control.
- `on("change", callback)` receives the selected search result as its first
  argument. A custom search method's result is passed through unchanged; the
  default method returns `{ label, value }`. Result selection does not update
  the ordinary control index. Mouse selection happens on `mousedown`; keyboard
  selection uses the highlighted result with Enter or Tab.
- `onSearchInput(callback)` registers a callback receiving the input text on
  query-editing keyups (excluding arrow keys, Enter and Tab). Templates can use
  this to clear a previous selection. Returns the control.
- `getSearchDropdownItems()` returns the current dropdown results, capped at
  500 items.
- `getSelectedSearchResult()` returns the last selected result, or `null` before
  any result is selected. It is not automatically cleared when the query or
  available options change; templates should manage their own active selection.

Result labels use `label`, then `display`, then `value` for object results, or
the result itself for primitive values. The searchbox does not manage chart
highlights, popups or panels.

## Controls container methods

### `appendTo(parent_container)`

Appends the controls container to the `parent_container` DOM node (this should usually be `layout.getSection("controls")`). Returns the controls container object.

### `add([controls_instances])`

Takes an array of controls instances and appends these to the controls container. Returns the controls container object.

### `update()`

This updates the controls container and all the appended controls instances (calling their individual `update()` methods). Returns the controls container object.

## Controls methods

### `appendTo(parent_container)`

Appends the control to the `parent_container` DOM node and injects CSS into the `head` if necessary.

Returns the control object.

### `format(formatterFunction, exclude)`

Specify an output formatter to format the contents of the control. This takes a function from the `@flourish/formatters` module or an `output_format_id` from the `@flourish/interpreter` module. Optionally pass an array of values to exclude from formatting.

### `getNode()`

Returns the container of the control that has been created. It will have a class of `"fl-controls-container"`

### `getSortedIndex()`

Returns the index of the currently chosen value in a sorted version of the options array.

### `index([i])`

With no argument returns the (unsorted) index of the currently selected option. If `i` is specified and corresponds to an index into the `options` array, sets the currently selected option to `i`. Returns the control object.

### `n_options()`

Returns the current number of options.

### `on(event, callback)`

Add `callback` to the list of `event` handlers. Currently the only supported `event` is "change". Returns the control object.

### `options([arr])`

With no argument returns a copy of the current list of options displayed by the current control. With an array, replaces the current options with a copy of `arr` and returns the control object.

### `parse(parserFunction)`

Specify a function to parse the contents of the control. This takes a function from the `@flourish/localization` or `@flourish/interpreter` module.

### `remove()`

Removes the control (and its resize event handler) from the DOM. Returns the control object.

### `trigger(event)`

Calls all the handlers assigned to `event` and returns the control object. Currently the only supported `event` type is "change".

### `update()`

Rebuilds the control with latest settings. Returns the control object.

### `value([val])`

With no argument returns the string value of the currently selected option. With `val` present changes the current index to match that of `val` in the options array and returns the control object. If `val` is not in the options array then nothing is changed but the control object is still returned.

### `visible([boolean])`

Set the visibility of the control


## Styling the controls

The controls have very basic styling. You can overwrite these styles with your own css and styling. We recommend using [@flourish/ui-styles](https://github.com/kiln/flourish-ui-styles) to style the controls.

