Alter the text displayed for a token in ace-editor - ace-editor

I have this example where I am locating a matching string via regex and changing the styles using highlight rules.
this.$rules = {
start: [{
token: 'variableRef',
regex: /\$variable\..+\$/
}]
};
and alter the color using a css class:
.ace_variableRef {
color: red;
}
But what I would really like to do is change the text that is being displayed from $variable.1.name$ to the "resolved value". I have access to:
var variables = {
1: 'timeout'
};
so I can use the reference path to get the value, but is it even possible to do this with ace-editor?
Ideally I would display the string in the user friendly way, but keep the original reference value handy (in metadata or something) since that is what is actually stored in the db.

You can accomplish this by defining a custom onMatch for your rule, like so
this.$rules = {
start: [{
onMatch: function(value, state, stack) {
var values = this.splitRegex.exec(value);
return [{
type: 'variableRef',
value: variables[values[1]]
}]
},
regex: /\$variable\.(\d+).+\$/
}]
};
but the actual text will remain unaltered (thus causing oddities with text selection/cursor), so you'll need to pad/clip the resulting value for it to match length of values[0]

Related

Using SyntaxHighlightRules for Syntax validation

I've built some new Ace Editor Modes for my custom language (JMS Message representations) with a sophisticated state machine. Now it would be great to reuse that syntax highlighting also to create the errors. Is that possible ?
In other words, let's say my syntax highlighting creates 'invalid' tokens and I want to use the line number of that token to flag an error and then do something like this: https://github.com/ajaxorg/ace/wiki/Syntax-validation
The simplest format is the HEX format:
this.$rules = {
"start": [
{ regex: /[!#].*$/, token: "comment" },
{ regex: /^0x[0-9a-f]+:/, token: "constant" }, // hex offset
{ regex: /(?:[0-9a-fA-F]{4} |[0-9a-fA-F]{2} )/, token: "constant.numeric" }, // hex value
{ regex: /[\S ]{1,16}$/, token: "string" }, // printable value
{ regex: "\\s+", token: "text" },
{ defaultToken: "invalid" }
]
};
And let's say the editor created this state with an invalid token in line 4:
Is there a (preferably easy) way to get to the line numbers of my invalid tokens ? Or to reuse my $rules state machine for syntax checking ?
Found it - I must admin, Ace Editor is really good stuff. Always works as expected.
What works for me, after computing the tokens of the document with the rules state machine, I iterate through all tokens and find the once that are 'invalid' and then set annotations on those lines. Initially simply 'Syntax error' but different types of 'invalid' could mean different things in the future. This way I only have to write the validation syntax validation once.
aceEditor.session.on('change', function(delta) {
var sess = aceEditor.session;
sess.clearAnnotations();
var invalids = [];
for( var row=0;row<sess.getLength();row++ ) {
var tokens = sess.getTokens(row);
if( !tokens ) continue;
for( var t=0;t<tokens.length;t++ ) {
if( tokens[t].type==="invalid" ) {
invalids.push({ row: row, column: 0, text: "Syntax error", type: "error" });
}
}
}
sess.setAnnotations( invalids );
});
There might be a smarter way to do this (maybe an onToken(type,row,column) function somewhere ?), but above works for me.

Custom column filter on a formatted column

I need help using a custom column filter for handling JS objects.
I have a slickgrid table where the values in one column are JS object:
[
{ id: "1234", text: "Batman"},
{ id: "2345", text: "Robin"}
]
I use a custom formatter to smash the object into a string:
// convert [{id:string, text:string}...] to string
const optionFormatter: Formatter = (row, cell, value, columnDef, dataContext: any) =>
value ? value.map(o => o.text).join(', ') : '';
Which displays in slickgrid as
Batman, Robin
my slickgrid options use gridmenu and enables column filtering:
this.gridOptions = {
enableGridMenu: true,
enableFiltering: true,
enableAutoResize: true,
enableColumnReorder: true
};
My columnDef enables filtering for this column:
{
id: 'owners',
name: 'Owners',
field: 'owners',
sortable: false,
formatter: optionFormatter,
filterable: true
}
Everything works if the value in the cell is a string, but the filter doesn't work if the cell is an object. I assume the filter is searching the pre-formatted value.
Is there a way to provide the column with a custom filter function that knows how to search the JS object for the query string? For example if I could just search the JSON.stringify(value), that would be good enough.
Alternatively, this answer describes how I could use the formatter to store the formatted text as a different string property in dataContext. If I do that, how do I specify which property to filter, seeing as it is a different property than the column field?
I found a workaround.
preprocess my data, calling JSON.stringify on all values that are objects:
flattenFeature(f: Feature): any{
var res = {};
for (var prop in f) {
res[prop] = (typeof f[prop] === 'object') ? JSON.stringify(f[prop]) : f[prop];
}
return res;
}
Then in my formatter, I parse the json, before formatting:
// convert [{id:string, text:string}...] to string
const optionFormatter: Formatter = (row, cell, value, columnDef, dataContext) =>
value ? JSON.parse(value).map(o => o.text).join(', ') : '';
This allows the standard string filter to search the stringify'd JSON

bootstrap-typeahead's displayfield using multiple values

I'm sorry if this is a duplicate question but I do not understand the answers of other people. I'm using Twitter Bootstrap Ajax Typeahead Plugin (https://github.com/biggora/bootstrap-ajax-typeahead/) to search emails from data that comes from an SQL query. This is the code I use with a php file, where I use people's emails as valueField and people's names as displayField and it works well.
inputSearch.typeahead({
ajax: {
url: urlAjax + '?requete=rechercheannuaire',
displayField: "description",
valueField: "id",
triggerLength: 2,
method: "get",
loadingClass: "loading-circle",
preProcess: function(data){
if(data.type === "error")
{
return false;
}
return data.datas;
}
},
onSelect: function(data){
//alert("assez tot");
data.text = data.value;
//console.log(data);
$("#chercherinvite").val(data.text);
return data;
}
});
The problem is that I have to be able to search "Dujardin" as well as "Du Jardin" and I cannot find a way to assign multiple values to displayField. If someone could explain how typeahead works, I'd be thankfull, I don't understand the documentation.
According to the plugin documentation, you cannot assign multiple values to the displayField option. However, it is possible for you to re-write events.
After a quick lookup into the source code of bootstrap-ajax-typeahead, we can figure out that the "matcher" event is used as the filter for displaying - or not - values to the user.
To allow to match both "Du jardin" and "Dujardin", we have to manipulate strings. Here, I suggest you to :
Remove any diacritic character
Remove any non-word character (all except [A-Za-z0-9_])
Remove any underscore
Set the string to lowercase
To do #1, I suggest you to use this fantastic script by rdllopes.
I wrote a POC. Here is the JSON source (called "source.json"):
[
{ "id": 1, "name": "jdupont#example.com - Jean Du Pont"},
{ "id": 2, "name": "jdupont2#example.com - Jean Dupont"},
{ "id": 3, "name": "jdupont3#example.com - Jéan Dupônt"},
{ "id": 4, "name": "mbridge#example.com - Michel Bridge"}
]
And here is the script that I used for matching elements :
$('#search').typeahead({
// Our source is a simple JSON file
ajax: 'source.json',
// Display field is a list of names
displayField: 'name',
// And value field a list of IDs
valueField: 'id',
matcher: function(item)
{
// For both needle and haystack, we :
// 1. Remove any diacritic character
// 2. Remove any non-word character (all except [A-Za-z0-9_])
// 3. Remove any underscore
// 4. Set the string to lowercase
var needle = removeDiacritics(this.query).replace(/[^\w]/gi, '').replace('_', '').toLowerCase();
var haystack = removeDiacritics(item).replace(/[^\w]/gi, '').replace('_', '').toLowerCase();
// Does the needle exists in haystack?
return ~haystack.indexOf(needle);
}
});

CKEditor - Use Advanced Content Filter rule to specify values

It seems that some plugins of CKEditor specify values of properties. For example, the left-to-right plugin has the following rule:
{
"styles":null,
"requiredStyles":null,
"classes":null,
"requiredClasses":null,
"attributes":{
"dir":"ltr"
},
"requiredAttributes":{
"dir":true
},
"elements":{
"span":true
},
"featureName":"styles",
"propertiesOnly":false,
"match":null
},
How can I specify values with string format rules?
Something like span[!dir=ltr].
You can't. String format doesn't allow such definition. You can specify span[!dir] so all spans require dir attribute and nothing else. With object definition you can do more, e.g. use functions:
...
'ul, li: true,
'$0': {
match: function( el ) {
return el.name == 'b';
},
propertiesOnly: true,
attributes: 'dir'
}
'$1': {
...
Why do you persist to use string format? You can use objects and store it as JSON.

Translating JSON into custom dijit objects

I am looking for an example where JSON constructed from the server side is used to represent objects that are then translated into customized widgets in dojo. The JSON would have to be very specific in its structure, so it would not be a very general solution. Could someone point me to an example of this. It would essentially be the reverse of this
http://docs.dojocampus.org/dojo/formToJson
First of all let me point out that JSON produced by dojo.formToJson() is not enough to recreate the original widgets:
{"field1": "value1", "field2": "value2"}
field1 can be literally anything: a checkbox, a radio button, a select, a text area, a text box, or anything else. You have to be more specific what widgets to use to represent fields. And I am not even touching the whole UI presentation layer: placement, styling, and so on.
But it is possible to a certain degree.
If we want to use Dojo widgets (Dijits), we can leverage the fact that they all are created uniformly:
var myDijit = new dijit.form.DijitName(props, node);
In this line:
dijit.form.DijitName is a dijit's class.
props is a dijit-specific properties.
node is an anchor node where to place this dijit. It is optional, and you don't need to specify it, but at some point you have to insert your dijit manually.
So let's encode this information as a JSON string taking this dijit snippet as an example:
var myDijit = new dijit.form.DropDownSelect({
options: [
{ label: 'foo', value: 'foo', selected: true },
{ label: 'bar', value: 'bar' }
]
}, "myNode");
The corresponding JSON can be something like that:
{
type: "DropDownSelect",
props: {
options: [
{ label: 'foo', value: 'foo', selected: true },
{ label: 'bar', value: 'bar' }
]
},
node: "myNode"
}
And the code to parse it:
function createDijit(json){
if(!json.type){
throw new Error("type is missing!");
}
var cls = dojo.getObject(json.type, false, dijit.form);
if(!cls){
// we couldn't find the type in dijit.form
// dojox widget? custom widget? let's try the global scope
cls = dojo.getObject(json.type, false);
}
if(!cls){
throw new Error("cannot find your widget type!");
}
var myDijit = new cls(json.props, json.node);
return myDijit;
}
That's it. This snippet correctly handles the dot notation in types, and it is smart enough to check the global scope too, so you can use JSON like that for your custom dijits:
{
type: "my.form.Box",
props: {
label: "The answer is:",
value: 42
},
node: "answer"
}
You can treat DOM elements the same way by wrapping dojo.create() function, which unifies the creation of DOM elements:
var myWidget = dojo.create("input", {
type: "text",
value: "42"
}, "myNode", "replace");
Obviously you can specify any placement option, or no placement at all.
Now let's repeat the familiar procedure and create our JSON sample:
{
tag: "input",
props: {
type: "text",
value: 42
},
node: "myNode",
pos: "replace"
}
And the code to parse it is straightforward:
function createNode(json){
if(!json.tag){
throw new Error("tag is missing!");
}
var myNode = dojo.create(json.tag, json.props, json.node, json.pos);
return myNode;
}
You can even categorize JSON items dynamically:
function create(json){
if("tag" in json){
// this is a node definition
return createNode(json);
}
// otherwise it is a dijit definition
return createDijit(json);
}
You can represent your form as an array of JSON snippets we defined earlier and go over it creating your widgets:
function createForm(array){
dojo.forEach(array, create);
}
All functions are trivial and essentially one-liners — just how I like it ;-)
I hope it'll give you something to build on your own custom solution.

Resources