# Selection controller

Controller for multiple/singular options selection.

# Installation

yarn add @aspectus/selection-controller

# Usage

# controller.prepareData(options: Array, value, keyGetter)

Extends options with metadata. Cleans/syncs value against current options.

Returns prepared value and options:

const { value, options } = controller.prepareData(...);

# controller.updateValue(change, currentValue, keyGetter, multiple = false)

Updates current value with the provided "change". "Change" might be:

  • Array - Replaces current value with provided change.
  • null or keyGetter(change) === null - Clears current value to null as if there is nothing selected.
  • option or keyGetter(option) - Adds(if it's not in) or removes(if it's in) change from currentValue.

# Example:

import controller from '@aspectus/selection-controller';

let value = null;
const initialData = [
  { id: null, label: 'Not selected' },
  { id: 'other-option-22340912094123340395710', label: 'Other option' },
  { id: 'third-option-09872082502459786238384', label: 'Third option' },
];
const keyGetter = x => x.id;
const prepared = controller.prepareData(initialData, value, keyGetter);
const multiple = true;

value = prepared.value;

// Singular data update
value = controller.updateValue(initialData[1], value, keyGetter);
// >>> [{ id: 'other-option-22340912094123340395710', label: 'Other option' }]
value = controller.updateValue(initialData[2], value, keyGetter);
// >>> [{ id: 'third-option-09872082502459786238384', label: 'Third option' }]

value = null;

// Multiple data update
value = controller.updateValue(initialData[2], value, keyGetter, multiple);
// >>> [{ id: 'third-option-09872082502459786238384', label: 'Third option' }]
value = controller.updateValue(initialData[1], value, keyGetter, multiple);
// >>> [
//  { id: 'third-option-09872082502459786238384', label: 'Third option' },
//  { id: 'other-option-22340912094123340395710', label: 'Other option' }
// ]
value = controller.updateValue(initialData[1], value, keyGetter, multiple);
// >>> [{ id: 'third-option-09872082502459786238384', label: 'Third option' }]
value = controller.updateValue(initialData[2], value, keyGetter, multiple);
// >>> [null]
value = controller.updateValue(initialData[2], value, keyGetter, multiple);
// >>> [{ id: 'third-option-09872082502459786238384', label: 'Third option' }]
value = controller.updateValue([initialData[1]], value, keyGetter, multiple);
// >>> [{ id: 'other-option-22340912094123340395710', label: 'Other option' }]
value = controller.updateValue(null, value, keyGetter, multiple);
// >>> [null]