@uncharted.software/lex

1.0.2

README

Lex.js

A preact-based micro-framework for building token-based search bars

Introduction

Lex is a micro-framework for building token-based search bars. Rather than predefining how searches are performed, Lex provides developers with the tools they need to define their own query language, and to develop unique UI components for constructing queries, thus supporting the widest possible set of potential use cases.

Lex is built internally with Preact, ensuring a minimal library size and compatibility with any modern SPA framework (VueJS, Aurelia, React, etc.) by remaining framework-neutral.

API Documentation and Demos

Online

For current API documentation, please visit: https://unchartedsoftware.github.io/lex/

For demos of key features, visit: https://unchartedsoftware.github.io/lex/demo/

Local

IMPORTANT: Node v14 required for local dev development. For current API documentation, please clone the project and run:

$ npm install
$ npm run serve-docs

For demos of key features, refer to source in the demo directory, while running:

$ npm install
$ npm run serve-demos

Testing

Testing is done through Playwright based on the demo examples included. Playwright is installed as a dependency but requires an additional step to pull the appropriate browsers for testing, to do this simply run:

$ npm install
$ npm run test:init

To run the tests simply start the demos using npm run demos and run the test:e2e script in a separate terminal. If developing within VSCode you can use the official Playwright Plugin to run the tests within the IDE.

Testing is still WIP and a number of tests still need to be added.

Using Lex

Defining a Search Language

In Lex, a search language is a finite-state machine. States represent "steps" towards successfully constructing a token through user-supplied values, and users transition() between them until they reach a terminal State (one with no children).

Lex attempts to provide an environment in which developers can craft their own search language, rather than enforcing one. Despite this goal, the following assumptions are made for the sake of improving user experience:

  1. A query consists of a list of tokens (i.e. [TOKEN1 TOKEN2 TOKEN3])
  2. The set of tokens in a Lex bar is interpeted as being joined by either ANDs or ORs (i.e. [TOKEN1 & TOKEN2 & TOKEN3]). This connective is not represented visually within the search bar, and thus is left up to the interpretation of the developer (however so far all existing apps using Lex have chosen AND).
  3. Tokens consist of a list of States - effectively, a path through the search language. Each State stores one or more values and, together, the sequence represents a statement such as [Name, is, Sean], [Age, is not, 7] or [Location, is, (Toronto,Victoria)].
  4. Multi-value States can represent an OR of values which, together with an overall choice of AND connective, strongly encourage Conjunctive Normal Form as the basis for a search language.

Defining a search language in Lex is accomplished via method chaining. Let's start with a basic search language, which allows a user to select a column to search and supply a value. The state machine for this language consists of three states, with specific rules governing the transition between the root state and its two children:

Choose Column ----(if string)----> Enter String
              \---(if numeric)---> Enter Number

Here is the implementation via Lex:

import { Lex, TransitionFactory, ValueState, ValueStateValue, TextEntryState, NumericEntryState } from 'lex';;

// Lex.from() starts a subtree of the language
const language = Lex.from('columnName', ValueState, {
  name: 'Choose a column to search',
  suggestions: [
    // ValueStates allow users to choose from a list
    // of values (or potentially create their own).
    // We set metadata "type"s on these options
    // to help us make transition decisions later.
    new ValueStateValue('Name', {type: 'string'}),
    new ValueStateValue('Age', {type: 'numeric'})
  ]
}).branch(
  Lex.from('value', TextEntryState, {
    // transitions to this State are considered legal
    // if the parent State's value had a metadata
    // type === 'string'
    ...TransitionFactory.valueMetaCompare({type: 'string'})
  }),
  Lex.from('value', NumericEntryState, {
    // Similarly, checking for parentVal.meta.type === 'numeric'
    ...TransitionFactory.valueMetaCompare({type: 'numeric'})
  }),
);

Consuming the language is as accomplished via configuration when constructing a new instance of Lex.

// Now we can instantiate a search bar that will respect this language.
const lex = new Lex({
  language: language
  // other configuration goes here
});
lex.render(document.getElementById('LexContainer'));

Lex supports far more complex languages, validation rules, state types etc. than are shown in this brief example. Check out the demo directory and API documentation for more details.

Extending Lex

Lex translates States from the search language into UI components as a user is creating or modifying a Token. These components fall into two categories:

  1. Builders - UI which is presented inline within a Token. This is generally a text input that the user can type into to supply values to the current State.
  2. Assistants - UI which is presented as a drop-down below a Token. Assistants provide an alternative, typically richer, mechanism for supplying values to the current State.

There must be one Builder for each State in a search language. Assistants are optional.

Lex contains several built-in State types, which are associated with default Builders and Assistants:

State Default Builder Default Assistant
LabelState LabelBuilder none
ValueState ValueBuilder ValueAssistant
RelationState ValueBuilder ValueAssistant
TerminalState TerminalBuilder none
TextEntryState ValueBuilder ValueAssistant
TextRelationState ValueBuilder ValueAssistant
NumericEntryState ValueBuilder ValueAssistant
NumericRelationState ValueBuilder ValueAssistant
CurrencyEntryState ValueBuilder ValueAssistant
DateTimeEntryState DateTimeEntryBuilder DateTimeEntryAssistant
DateTimeRelationState ValueBuilder ValueAssistant

Two things are evident in this table:

  1. Most State types extend ValueState, which is a powerful component supporting selecting a value from a list of suggestions, entering custom values, accepting multiple values, etc.
  2. Any State type which is missing a direct Builder or Assistant will attempt to use the corresponding components for its superclass State.

Lex may be extended, therefore, in the following ways (in descending order of likelihood):

  1. Via the implementation of new States, extending existing States (i.e. extending ValueState but using ValueBuilder and ValueAssistant)
  2. Via the implementation of new Assistants for existing States (i.e. implementing a custom drop-down UI for choosing dates and times)
  3. Via the implementation of new Builders for existing States (mostly for formatting "finished" Tokens in unique ways by overriding renderReadOnly())
  4. Via the implementation of entirely unique States, with custom Builders and Assistants. (i.e. implementing a GeoBoundsEntryState with a custom Builder, and an Assistant featuring a map)

The States, Builders and Assistants within the library are well-documented examples of how these extension types are accomplished, and exist as a reference for this purpose.

Overrides must be registered with Lex before the search bar is rendered:

// ...
lex.registerBuilder(DateTimeEntryState, CustomDateTimeEntryBuilder);
lex.registerAssistant(CurrencyEntryState, CustomCurrencyEntryAssistant);
lex.render(document.getElementById('LexContainer'));

Consuming Lex Within an Application

The following co-requisites must be part of your JS build in order to use Lex:

{
  "element-resize-detector": "1.1.x", // developed against "1.1.15"
  "preact": "8.x", // developed against: "8.5.2",
  "moment-timezone": "0.5.x", // developed against "0.5.34"
  "flatpickr": "4.6.x" // developed against: "4.6.3"
}

The following polyfills are required for use in IE and are not provided by this library:

  • ES6 Promise Polyfill

Styling Lex

Lex ships with both a compiled CSS stylesheet (lex.css) and a raw SASS stylesheet (lex.scss). If you wish to customize styles, you will need to include the raw SASS stylesheet in your build and override one or more of the following variables (shown here with their default values):

$lex-background: revert; // use the background color inherited from Bootstrap
$lex-border-color: revert; // use the border color inherited from Bootstrap
$lex-border-radius-base: 3px; // border radius for various things
$lex-highlight-color: #0097a7;  // highlight color for various things
$lex-highlight-text-color: #fff; // color for text shown on top of a highlight-color background
$lex-danger-highlight-color: #d9534f; // highlight color for dangerous things
$lex-danger-highlight-text-color: #fff; // color for text shown on top of a danger-highlight-color background
$lex-line-height: 1.67; // base line height for lex tokens, etc.
$lex-token-padding: 2px; // padding for lex tokens
$lex-token-value-spacing: 0.3em; // spacing for token value inputs
$lex-token-background: #ededed; // background color for tokens
$lex-token-color: #555; // text color for tokens (inherit from Bootstrap)
$lex-token-hover-color: lighten($lex-token-color, 15%); // hover color for close button
$lex-token-border-color: darken($lex-token-background, 15%); // border color for a token
$lex-token-active-background: darken($lex-token-background, 15%); // background for active token components
$lex-token-input-border-color: transparent; // border for lex token text inputs
$lex-token-remove-button-color: lighten($lex-token-color, 45%); // hover color for remove button in multi-entry
$lex-token-remove-button-hover-color: darken($lex-token-remove-button-color, 15%); // text color for remove button in multi-entry
$lex-token-active-background: darken($lex-token-background, 15%); // background color for active region of a token. should lighten for dark theme
$lex-token-invalid-background: #e2a4e2; // background color for invalid region of token. should lighten for dark theme
$lex-assistant-background: #fff; // background color for assistant drop-down
$lex-assistant-border-color: $lex-token-border-color; // border color for assistant drop-down
$lex-assistant-header-background: $lex-token-background; // header background color for assistant drop-down
$lex-assistant-header-color: #8d8d8d; // header text color for assistant drop-down

API Documentation

API documentation for Lex follows, divided into sections.

Core Framework

Lex

Lex - A micro-framework for building search bars.

This class is an EventEmitter and exposes the following events:

  • on('token start', () => {}) when the user begins to create or edit a token.
  • on('token end', () => {}) when the user finishes creating or editing a token.
  • on('token action', (tokenIdx, actionVkey, newModel, newUnboxedModel, oldActionVal) => {}) when the user triggers a token action.
  • on('query changed', (newModel, oldModel, newUnboxedModel, oldUnboxedModel, nextTokenStarted) => {}) when query model changes.
  • on('suggestions changed', (newModel, oldModel, newUnboxedModel, oldUnboxedModel) => {}) when suggestion model changes.
  • on('validity changed', (newValidity, oldValidity) => {}) when validity of an active builder changes.
new Lex(config: object)

Extends EventEmitter

Parameters
config (object) The configuration for this instance of Lex .
Name Description
config.language StateTemplate The root state of the search language this bar will support.
config.placeholder (string | undefined) Placeholder text for the search bar (optional).
config.container (string | DOMNode) Container for Lex popups, such as Assistants .
config.proxiedEvents Array<string> A list of keydown events to proxy from Builder s to Assistant s. If the active Builder does not consume said event, it will be sent to the active Assistant (if any). ['ArrowUp', 'ArrowDown', 'Tab', 'Enter'] by default.
config.defaultQuery Array<Object> The default search state for this search box. Can either be an array of arrays of boxed or unboxed (basic type) values.
config.tokenXIcon string The default X icon for tokens (DOM string).
config.multivalueDelimiterKey number The JS key code of the delimiter which will notionally 'separate' multiple values in any visual representation of a multivalue state. 188 (',') by default.
config.multivaluePasteDelimiter string The characters which are supported as delimiters text which is pasted into a multivalue state. ',' by default.
config.cssClass Array<string> Add unique classes to the lex search bar and associated assistant
config.cancelOnBlur boolean Whether or not to cancel token creation/editing on blur. True by default.
config.onAcceptSuggestion (function | undefined) A callback called when the user presses "add" on a suggestion. A no-op by default ( (s, idx) => s ) but, if supplied, can be used to transform the incoming boxed suggestion, perform additional actions, etc. Return null to stop Lex from updating suggestions and query automatically, or return the suggestion (or a transformed version) to allow Lex to handle the rest.
config.onRejectSuggestion (function | undefined) A callback called when the user presses "x" on a suggestion. A no-op by default ( (s, idx) => true ) but, if supplied, can be used to perform additional actions or stop Lex from auto-updating the suggestions and query (by returning false )
Example
// Instantiate a new instance of lex and bind it to the page.
const lex = new Lex(language);
lex.render(document.getElementById('lex-container'));
// Override default builder/assistant associations
const lex = new Lex(language);
lex.registerBuilder(ValueState, MyCustomOptionBuilder);
Static Members
from(vkey, StateKlass, config)
Instance Members
registerBuilder(templateClass, builderClass)
registerAssistant(templateClass, assistantClass)
registerActionButton(templateClass, actionButtonClass)
render(target)
unmount()
reset(shouldFireChangeEvent)
setSuggestions(suggestions, shouldFireChangeEvent)
focus()
setEnabled(enabled)
setQuery(query, shouldFireChangeEvent)

StateTemplate

A factory for a State, which can be used to produce instances from the provided configuration object.Also a builder for chaining this StateTemplate to children, creating a DAG of StateTemplates which describes your search language.

new StateTemplate(klass: Class, config: object)
Parameters
klass (Class) A State class that this factory will produce.
config (object = {}) Options which will be applied to State klass upon instantiation.
Instance Members
getInstance(parent)
impliesAction(ActionKlass, config)
to(vkey, StateKlass, config)
branch(branches)

State

Describes a particular state in a state machine (DAG) which represents the interactive build process for a token. The state machine implied by a tree of States will be traversed one state at a time (parent to child) by the user as they interact with its visual representation, resulting in a sequence of state values which constitute a valid "token" within your search language.

This class is meant to be extended to implement new state types.

State supports a notion of boxed/unboxed values, where the internal representation of the value is richer than the String version supplied by the user. Override boxValue and unboxValue to utilize this functionality. By default, the internal representation and the user-supplied one are the same (a string), and no overriding is necessary.

Values should not be Arrays, but can be objects (Arrays interfere with internal multi-value handling).

this.value always accepts/returns a boxed value. Where desired, the boxed and unboxed versions of the value can be identical.

States support an archive for values, in order to facilitate multi- value entry. Valid values may be pushed onto the archive, making room for a new value entry to take place. The top archived value may also be moved back to replace the current value.

This class is an EventEmitter, exposing the following events:

  • on('value changed', (newVal, oldVal) => {}) when the internal value changes.
  • on('value archived', () => {}) when a value is archived.
  • on('value unarchived', () => {}) when a value is archived.
  • on('preview value changed', (newVal, oldVal) => {}) when the internal preview value changes.
  • on('unboxed value change attempted', (newUnboxedVal, oldUnboxedVal)) when a user attempts to change the unboxed value. If it cannot be boxed, it may not trigger value changed.
new State(config: object)

Extends EventEmitter

Parameters
config (object) Options for State class.
Name Description
config.parent (State | undefined) The parent state. undefined if this is a root.
config.name string A useful label for this state - used for display purposes.
config.vkey string A key used to enter the value of this state into the value object of the containing machine.
config.transition (Function | undefined) A function which returns true if this state is the next child to transition to, given the value of its parent. Undefined if this is root.
config.validate (Function | undefined) A function which returns true iff this state has a valid value. Should throw an exception otherwise.
config.defaultValue any The default boxed value for this state before it has been touched. Can be undefined. Should not be an Array (but can be an object ).
config.autoAdvanceDefault boolean If a defaultValue is set and autoAdvanceDefault is true, this State auto-transition to the next State using its defaultValue .
config.readOnly boolean This state is read only (for display purposes only) and should be skipped by the state machine. False by default.
config.bindOnly boolean This state is bind only (can be created programatically, but not by a user). False by default.
config.hideLifecycleInteractions boolean This state should not be presented with visual lifecycle interactions. False by default.
config.multivalue boolean Whether or not this state supports multi-value entry.
config.multivalueLimit (number | undefined) An optional limit on the number of values this state can contain.
config.icon (string | Function) A function which produces an icon suggestion (HTML string ) for the containing Token , given the value of this state. May also supply an HTML string to suggest regardless of state value. The suggestion closest to the current valid state is used.
config.cssClasses Array<string> One or more CSS classes which, when this State is transitioned to, will be applied to the containing Token . They will be removed if the machine is rewound before this State .
config.resetOnRewind boolean This state should reset child states when rewound to during a token edit. False by default.
Example
class MyCustomState extends State {
  constructor (config) {
    super(config);
    const {myCustomOption} = config;
    // do something with myCustomOption
  }

  boxValue (userVal) {
    // userVal is what a user might type to supply a value to this state
    // TODO implement transform into richer internal representation
  }

  unboxValue (internalRepresentation) {
    // TODO return a string representation of the richer internal representation.
  }
}
Instance Members
initialize(context, initialUnboxedValue)
boxValue(userVal)
unboxValue(internalRepresentation)
isValid
isValidTransition(ignoreBindOnly)
value
value
boxedValue
boxedValue
unboxedValue
unboxedValue
previewValue
previewValue
boxedPreviewValue
boxedPreviewValue
unboxedPreviewValue
unboxedPreviewValue
archive
boxedArchive
unboxedArchive
canArchiveValue
archiveValue(context, skipValidation)
unarchiveValue(context)
removeArchivedValue(idx, context)
removeArchivedValues()
updateArchivedValue(idx, newBoxedValue)

Builder

An abstract superclass for a Component which can be used to construct a portion of a Token.

Subclasses generally implement renderInteractive and focus.

new Builder()

Extends Component

Example
// See OptionBuilder for an example implementation.
Instance Members
cleanupListeners()
connectListeners()
componentWillUnmount()
componentWillMount()
componentWillReceiveProps(nextProps)
processProps(props)
focus()
renderInteractive(props, state)
delegateEvent(e)
cancelOnBlur
isValid
defaultValue
machine
machineState
value
value
boxedValue
boxedValue
unboxedValue
unboxedValue
archive
boxedArchive
unboxedArchive

Assistant

Richer interaction areas for building values.

These have no read-only mode, and are utilized as "drop-downs" to provide additional interactivity and visualization as users.

Subclasses generally implement delegateEvent, renderInteractive and focus.

new Assistant()

Extends Builder

Example
// See OptionAssistant for an example implementation.
Instance Members
processProps(props)
beforeChangeMachineState()
afterChangeMachineState()
loading
renderAssistantBody(props, state)

TransitionFactory

Convenient builders for constructing transition functions.

new TransitionFactory()
Static Members
valueKeyIs(valueKeys)
valueKeyIsNot(valueKeys)
valueMetaCompare(toCompare)

Choice States

ValueState

A state representing the selection of a value from a list of suggested values. Intended to facilitate both simple cases (such as selecting from a list of predefined options) and advanced ones (such as selecting from a list of dynamically updating suggestions).

By default, this state (and any extending classes) can be visually represented by ValueBuilder and ValueAssistant.

This class is an EventEmitter and exposes the following events (in addition to State's events):

  • on('fetching suggestions', () => {}) when a fetch for suggestions is triggered.
  • on('fetching suggestions finished', (err) => {}) when a fetch for suggestions is finished, regardless of whether or not the suggestions changed. err may be defined if something went wrong.
  • on('suggestions changed', (newSuggestions, oldSuggestions) => {}) when the internal list of suggestions changes.
  • on('typed text changed', (newText, oldText) => {}) when a user types text into the associated Builder.
new ValueState(config: object)

Extends State

Parameters
config (object) A configuration object. Inherits all options from State , and adds additional elements.
Name Description
config.overrideValidation (boolean | undefined) Whether or not config.validate fully overrides ValueState 's internal validation. If false , it works in conjunction with it. false by default.
config.fetchSuggestions (AsyncFunction | undefined) A (required) function which is utilized for fetching suggestions via a hint (what the user has typed). async (hint, context, formattedHint) => ValueStateValue[] , executing in the scope of this ValueState , allowing access to its instance methods. If this is specified, config.suggestions should be null.
config.allowUnknown (boolean | undefined) Allow user to supply unknown values (not from suggestions). Defaults to false.
config.onUnknownValue (Function | undefined) Optional hook ( (ValueStateValue) => ValueStateValue ) which, when a user enters an unknown ValueStateValue , allows for augmentation with things like metadata. Must return a new ValueStateValue , since ValueStateValue is immutable.
config.suggestionLimit (number | undefined) A limit on the number of suggestions that will be shown at one time. Defaults to 5.
config.units string A textual label which represents "units" for the value state, such as "(h) or (kg)".
Instance Members
typedText
typedText
suggestions
suggestions
allowUnknown
suggestionLimit
suggestionsDisabled
units
unformatUnboxedValue(typedText, context)
formatUnboxedValue(key, context)
boxValue(key)
unboxValue(option)
fetchSuggestions(hint, context, formattedHint)

ValueStateValue

A rich value, which might be an object (such as a Date) or a basic type, along with associated metadata.

new ValueStateValue(key: string, meta: any, config: object)
Parameters
key (string) A string representation for this value. If two ValueStateValues are equal, their keys are equal (so they keys should be unique).
meta (any) Whatever you want.
config (object = {}) Additional configuration for this ValueStateValue .
Name Description
config.hidden boolean If true, this ValueStateValue will never be suggested to the user.
config.displayKey (string | undefined) A shorter representation of key displayed in read-only mode. Optional.
config.highlighted boolean Whether or not this ValueStateValue is "highlighted" to the user. No more than one ValueStateValue should be highlighted within an ValueState .
Instance Members
key
displayKey
hidden
meta

RelationState

This state supports the selection of a relation from a list of options.

new RelationState(config: object)

Extends ValueState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name and options . config.options should be a function returning ValueStateValue s.

TextRelationState

This state supports the selection of a text relation from a list of options.

new TextRelationState(config: object)

Extends RelationState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name and options .
Static Members
IS
IS_NOT
IS_LIKE
CONTAINS
DOES_NOT_CONTAIN

NumericRelationState

This state supports the selection of a numeric relation from a list of options.

new NumericRelationState(config: object)

Extends RelationState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name and options .
Static Members
EQUALS
DOES_NOT_EQUAL
LESS_THAN
GREATER_THAN
BETWEEN

DateTimeRelationState

This state supports the selection of a datetime relation from a list of options.

new DateTimeRelationState(config: object)

Extends RelationState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name and options .
Static Members
EQUALS
DOES_NOT_EQUAL
BEFORE
AFTER
BETWEEN

Value Entry States

TextEntryState

This state supports the entry of a String value, with possible auto-complete.

new TextEntryState(config: object)

Extends ValueState

Parameters
config (object) A configuration object.

NumericEntryState

This state supports the entry of a Number value, with possible auto-complete.

new NumericEntryState(config: object)

Extends ValueState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name , validate (valid iff !isNaN ) and allowUnknown (true).

CurrencyEntryState

This state supports the entry of a (stringified) Number value, with possible auto-complete.

new CurrencyEntryState(config: object)

Extends ValueState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name , validate (valid iff !isNaN ) and allowUnknown (true).

DateTimeEntryState

This state supports the entry of a Date/Time value, with support for a custom acceptable format.

new DateTimeEntryState(config: object)

Extends State

Parameters
config (object) A configuration object. Supports all of the parameters from State , providing defaults for name and validate .
Name Description
config.format (string | undefined) The acceptable format for a typed date. Defaults to 'YYYY/MM/DD' .
config.timezone (string | undefined) The assumed timezone for a typed date. Defaults to 'Etc/UTC' .
config.enableTime boolean If the date picker should display time picking UI.
config.enableCalendar boolean If the date picker should display the date picking UI.
config.hilightedDate Date The default selected date, defaults to today.
config.time24hr boolean If the date picker should display time picking UI in 24 hour format.
Instance Members
format
timezone
minDate
maxDate
enableTime
enableCalendar
time24hr
hilightedDate
boxValue(datestring)
unboxValue(dateobj)

Static States

LabelState

A non-interactive state providing a mechanism to add a textual label between two other builders.

By default, this state (and any extending classes) can be visually represented by LabelBuilder.

new LabelState(config: object)

Extends State

Parameters
config (object) A configuration object. Inherits all options from StateTemplate , and adds additional elements.
Name Description
config.label string The label to display. Will also be used as the (fixed) value.

Builders

ValueBuilder

A visual interaction mechanism for supplying values to a ValueState. By default, this is registered as the Builder for ValueStates.

new ValueBuilder()

Extends Builder

Example
lex.registerBuilder(ValueState, ValueBuilder)

LabelBuilder

A visual representation of a LabelState

new LabelBuilder()

Extends Builder

Example
lex.registerBuilder(LabelState, LabelBuilder)

TerminalBuilder

A visual representation of a TerminalState

new TerminalBuilder()

Extends Builder

Example
lex.registerBuilder(TerminalState, TerminalBuilder)

DateTimeEntryBuilder

A visual interaction mechanism for supplying values to an DateTimeEntryState. By default, this is registered as the Builder for DateTimeEntryStates.

new DateTimeEntryBuilder()

Extends Builder

Example
lex.registerBuilder(DateTimeEntryState, DateTimeEntryBuilder)

Assistants

ValueAssistant

A visual interaction mechanism for supplying values to a ValueState. By default, this is registered as the Assistant for ValueStates.

new ValueAssistant()

Extends Assistant

Example
lex.registerAssistant(ValueState, ValueAssistant)

DateTimeEntryAssistant

A visual interaction mechanism for supplying values to an DateTimeEntryState. By default, this is registered as the Assistant for DatetimeEntryStates.

new DateTimeEntryAssistant()

Extends Assistant

Example
lex.registerAssistant(DateTimeEntryState, DateTimeEntryAssistant)

Miscellaneous

ActionTemplate

A factory for an Action, which can be used to produce instances from the provided configuration object.

new ActionTemplate(klass: Class, config: object)
Parameters
klass (Class) An Action class that this factory will produce.
config (object = {}) Options which will be applied to Action klass upon instantiation.
Instance Members
getInstance()

Action

A concrete Action, presented as a button only on completed Tokens, which allows users to interact with Tokens in some way. Each Action has its own internal value, and can only affect its own internal value.

new Action(config: object)

Extends EventEmitter

Parameters
config (object) Options for Action class.
Name Description
config.name string A name for this Action , used by default for display purposes.
config.vkey string A key used to uniquely identify the value of this Action when returned alongside others from the same Token .
config.defaultValue object The default internal value for this Action .
Instance Members
value
value
initialize(context)
suggestCssClass()

TerminalState

A non-interactive, invisible state providing a mechanism for simulating an "optionally terminal" state. For example, an ValueState where certain values terminate the machine, but others do not.

new TerminalState(config: object)

Extends State

Parameters
config (object) A configuration object. Inherits all options from State .

EnumEntryStateValue

An EnumEntryStateValue represents an Enumeration value, with a string name and a numerical index.

new EnumEntryStateValue(idx: any, name: any)

Extends ValueStateValue

Parameters
idx (any)
name (any)

EnumEntryState

This state supports the entry of an enum Value, a string associated with a number, with possible auto-complete config.enums should be supplied as an array of EnumEntryStateValues. For example, the enum value "hello"->1 would be represented as new EnumEntryStateValue(1, 'hello').

new EnumEntryState(config: object)

Extends ValueState

Parameters
config (object) A configuration object. Supports most of the parameters from ValueState and StateTemplate , providing defaults for name . allowUnknown is and must be false. Possible Enumeration values must be fixed and provided via config.enums ; config.fetchSuggestions and config.suggestions are not supported.

TokenSuggestionStateValue

An TokenSuggestionStateValue represents an TokenSuggestionState value, with regexp pattern(s) and a function producing a full Token value which would be suggested if a regexp is matched.

new TokenSuggestionStateValue(regexArr: any, description: Function, factory: AsyncFunction)

Extends ValueStateValue

Parameters
regexArr (any)
description (Function) A function which, receiving the match, returns the text to show a user describing this suggestion.
factory (AsyncFunction) A function which, receiving the match, returns a TokenStateMachine boxedValue.

TokenSuggestionState

This state supports the suggestion of entire token values, with possible auto-complete.

new TokenSuggestionState(config: object)

Extends ValueState

Parameters
config (object) A configuration object. Supports all of the parameters from ValueState and StateTemplate , providing defaults for name , validate and allowUnknown (false). suggestions and fetchSuggestions are not supported, and are supplanted by config.tokenSuggestions .

ActionButton

Interactions for Tokens.

Subclasses generally implement render, onClick.

new ActionButton()

Extends Component

Instance Members
cleanupListeners()
connectListeners()
componentWillUnmount()
componentWillMount()
componentWillReceiveProps(nextProps)
processProps(props)
onValueChanged(newVal, oldVal)
render(props, state)

Called just before a component, such as this Builder or an Assistant, requests a transition. This is useful, for example, when an Assistant wants to trigger a transition but needs its associated Builder to commit a typed value to state.unboxedValue first.

Call from a subclass to request the state machine for the containing token to attempt transition.

Parameters
options (object) Options for transition
Name Description
options.nextToken boolean If true, and this transition ends a token, this will trigger the start of a new one.

Call from a subclass to request an immediate cancelling of the current state machine, and the creation of a brand new token.

Parameters
boxedTokenValue (object) The boxed token value to immediately create

Call from a subclass to request the state machine for the containing token to attempt archive a value.

Call from a subclass to request the state machine for the containing token to attempt unarchiving a value.

Call from a subclass to request the state machine for the containing token to attempt removal of a specific value from the archive.

Parameters
idx (number) The index of the value to remove.

Call from a subclass to request the state machine for the containing token to attempt removal of all values from the archive.

Call from a subclass to request the state machine for the containing token to attempt replacement of a specific archived value.

Parameters
idx (number) The index of the value to replace.
newBoxedValue (object) The new boxed value to replace the specified archived value with.

Call from a subclass to request the state machine for the containing token to attempt rewind.

Call from a subclass to request the state machine for the containing token to attempt rewind to this builder

Call from a subclass to inform containing components that this component has received focus. Since "focus" is not necessarily a literal concept (and could be triggered by a button press, or some other interaction), this is an artificial bubbling mechanism.

Call from a subclass to inform containing components that this Builder is cancelling input.

Call from a subclass to inform containing components that this component has been blurred. Since "focus" is not necessarily a literal concept (and could be triggered by a button press, or some other interaction), this is an artificial bubbling mechanism.

Parameters
e (Event) A blur event from some DOM element within this Builder's visual representation.