Javascript control for editing equations that supports embedded tokens for variables in the equations.
We created this control to support editing feature scoring equations in Aha!. It allows users to mix arbitrary mathematical equations with user defined variables.
Add to your Gemfile and bundle:
gem 'token-text-area', git: 'https://github.com/k1w1/token-text-area.git'
Include JavaScript in your application.js
manifest:
//= require token-text-area
Include CSS in your application.css.less
manifest:
*= require token-text-area
In your view, use the token_text_area
helper to create the token text area:
token_text_area(equation, variables, options = {})
- equation - an existing equation with which to populate the equation editor (use
nil
if no such equation exists) - variables - an array of hashes representing variables in the equation, with hash attributes
id
,name
, andvalue
. For example:[{id: 1, name: 'Business Value', value: 5}]
. If the equation is in readonly mode (see next bullet) and the value is present, it will be displayed after the variable name in the token. - options - a hash of options. You may pass HTML or data attributes to be attached to the token text area. Options specific to token-text-area are
readonly
andcontainer_tag
. Ifreadonly
is set to true, the equation will be readonly- not editable with values shown if available. Ifcontainer_tag
is set, the given tag will be used for the editor; if not set,:div
is the default.
You must initialize the editor in your JavaScript or CoffeeScript. The API accepts two methods: onQuery
and onChange
.
onQuery
is triggered when typing in the text area and may be used to populate the autocomplete menu. Passing an array of JSON objects withid
andname
attributes tocallback(data);
will populate the autocomplete menu with those objects.onChange
is triggered when the value of the text area changes, and may be used to save the equation value (or similar).
A complete example initialization:
$("#editor").tokenTextArea({
onQuery: function(query, callback) {
$.ajax({
type: 'GET',
url: '/autocomplete/results/path/?query=' + query,
dataType: 'json',
success: function(data) {
return callback(data);
}
});
},
onChange: function(equation) {
$.ajax({
type: 'PUT',
url: '/some/save/path/',
dataType: 'json',
data: {
equation: equation
}
});
}
});
Variables in equations are automatically converted for server-side storage in the onChange
event from <span class="token"...
to #variable_id#
placeholder notation, where variable_id is the ID attribute of the variable. In the token_text_area
helper, variables are automatically converted from #variable_id#
notation back to display-friendly <span class="token"...
by looking up the variable ID in the variables
array parameter.
bundle install
bundle exec rackup
http://localhost:9292/examples/index.html