Remplacement avec référence fonctionne pour les PRIMARY variables, à tester pour le reste, méthodes à part pour 'replaceArray' et 'replacePrimary', à faire pour 'replaceRegex' et 'replaceArrayVal'

This commit is contained in:
xdrm-brackets 2016-09-19 08:37:35 +02:00
parent dff156a88b
commit 2763a32e91
6 changed files with 231 additions and 117 deletions

View File

@ -1,3 +1,3 @@
var ElementObject={node:"node name defined earlier",attributes:{attr_name_1:"attr_value_1",attr_name_2:"attr_value_2"},children:[ElementObject],next_nodes:[ElementObject],prev_nodes:[ElementObject],text:"some text to be the innerHTML",repeat:"number to repeat ElementObject || {{array}} to repeat ElementObject",node_type:"html tag name",listeners:[EventListener]},default_definition={input:{node_type:"input"},"/^h([1-6])$/":{node_type:"h{$1}"},br:{node_type:"br"},option:{node_type:"option"},select:{node_type:"select"},
span:{node_type:"span"}},custom_definition={"/^input.([a-z]+)$/":{node:"input",attributes:{type:"{$1}","data-name":"{name}",value:"{value}",placeholder:"{placeholder}"},next_nodes:[{node:"br"}]},"custom-select":{node:"span",attributes:{"class":"select-container nobold"},children:[{node:"select",attributes:{"data-name":"{name}"},children:[{node:"option",attribute:{value:"{options.value}"},text:"{options.value}",repeat:"{{options}}"}]}],next_nodes:[{node:"br"}]}},form={node:"h4",attributes:{"data-icon":"o",
"class":"new-contact color2"},children:[{node:"input:hidden",$name:"uid",$value:"{uid}"},{node:"input:hidden",$name:"call",$value:"{call}"},{node:"input:hidden",$name:"sms",$value:"{sms}"},{node:"input:hidden",$name:"countcall",$value:"{countcall}"},{node:"input:hidden",$name:"countsms",$value:"{countsms}"},{node:"input:text",$name:"number",$value:"{number}",$placeholder:"{Num\u00e9ro de t\u00e9l\u00e9phone}"},{node:"custom-select",$name:"existing",$$options:"{{options}}"}]};
var reference_table={"2fd8":!0},ElementObject={node:"node name defined earlier",attributes:{attr_name_1:"attr_value_1",attr_name_2:"attr_value_2"},children:[ElementObject],next_nodes:[ElementObject],prev_nodes:[ElementObject],text:"some text to be the innerHTML",repeat:"number to repeat ElementObject || {{array}} to repeat ElementObject",node_type:"html tag name",listeners:[EventListener]},default_definition={input:{node_type:"input"},"/^h([1-6])$/":{node_type:"h{$1}"},br:{node_type:"br"},option:{node_type:"option"},
select:{node_type:"select"},span:{node_type:"span"}},custom_definition={"/^input.([a-z]+)$/":{node:"input",attributes:{type:"{$1}","data-name":"{name}",value:"{value}",placeholder:"{placeholder}"},next_nodes:[{node:"br"}]},"custom-select":{node:"span",attributes:{"class":"select-container nobold"},children:[{node:"select",attributes:{"data-name":"{name}"},children:[{node:"option",attribute:{value:"{options.value}"},text:"{options.value}",repeat:"{{options}}"}]}],next_nodes:[{node:"br"}]}},form={node:"h4",
attributes:{"data-icon":"o","class":"new-contact color2"},children:[{node:"input:hidden",$name:"uid",$value:"{uid}"},{node:"input:hidden",$name:"call",$value:"{call}"},{node:"input:hidden",$name:"sms",$value:"{sms}"},{node:"input:hidden",$name:"countcall",$value:"{countcall}"},{node:"input:hidden",$name:"countsms",$value:"{countsms}"},{node:"input:text",$name:"number",$value:"{number}",$placeholder:"{Num\u00e9ro de t\u00e9l\u00e9phone}"},{node:"custom-select",$name:"existing",$$options:"{{options}}"}]};

View File

@ -77,6 +77,9 @@
// variables are transformed to references, so they can be updated easily without rebuilding the whole model
// when the model is built the first time, all the passed variables are transformed to references
// and they are spread by references
var reference_table = {
'2fd8': true
};
////////////////////////
// LANGAGE DEFINITION //

View File

@ -1,9 +1,11 @@
var refObject=function(a){this.value=a};refObject.prototype={value:this.value,get:function(){return this.value},set:function(a){this.value=a},valueOf:function(){return this.get()}};var ref=function(a){return new refObject(a)},FormBuilder=function(a){this.form_object=a};FormBuilder.prototype={form_object:this.form_object,defs_object:{},parent_element:null,built_form:null,root_element:null};
FormBuilder.regex={reg_in_key:/^\/\^(.+)\$\/$/,reg_out_val:/\{(\$[1-9])\}/,pri_out_val:/\{([a-z-]+)\}/g,pri_in_key:/^\$([a-z-]+)$/,arr_out_set:/^\{\{([a-z-]+)\}\}$/,arr_out_val:/\{([a-z-]+)\.([a-z-]+)\}/g,arr_in_key:/^\$\$([a-z-]+)$/};FormBuilder.spread_attr=["children","next_nodes","prev_nodes","attributes","node_link"];FormBuilder.allowed_attr="node node_type next_nodes prev_nodes attributes children text repeat".split(" ");
FormBuilder.prototype.add_definition=function(a){for(var b in a)this.defs_object[b]=a[b]};FormBuilder.prototype.build=function(a){a=null==a?{}:a;this.built_form=JSON.parse(JSON.stringify(this.form_object));this.built_form=FormBuilder.formatFormObject(this.built_form,this.defs_object);this.built_form=FormBuilder.replaceStatements(this.built_form,a,this.defs_object)};
FormBuilder.prototype.attach=function(a){if(!(a instanceof Element)&&null==this.parent_element)return!1;this.parent_element=a instanceof Element?a:this.parent_element};FormBuilder.formatFormObject=function(a,b){if(a.hasOwnProperty("children"))for(var g in a.children)a.children[g].parent=a,FormBuilder.formatFormObject(a.children[g],b);return a};
FormBuilder.fetchNodeDefinition=function(a,b){var g,c;r=FormBuilder.regex.reg_in_key;if("undefined"!=typeof b&&b.hasOwnProperty(a))return{def:b[a]};for(g in b)if(r.test(g)&&(c=new RegExp(g.slice(1,-1)),c.test(a))){matches={};for(c=1;c<RegExp.length&&10>c;c++)matches["$"+c]=RegExp["$"+c];return{def:b[g],scope:matches}}return{}};
FormBuilder.replaceStatements=function(a,b,g){a=a instanceof Object?a:{};b=b instanceof Object?JSON.parse(JSON.stringify(b)):{};var c,f,e,h;if(a.hasOwnProperty("scope")&&a.scope instanceof Object)for(c in a.scope)b[c]=a.scope[c];if(a.hasOwnProperty("node")&&"string"==typeof a.node&&(f=FormBuilder.fetchNodeDefinition(a.node,g),f.hasOwnProperty("def")&&(a.node_link=JSON.parse(JSON.stringify(f.def)),f.hasOwnProperty("scope"))))for(c in f.scope)b[c]=f.scope[c];a.received=b;for(c in a)if("string"==typeof a[c]){f=
FormBuilder.regex.arr_out_set;var d=[];(e=f.exec(a[c]))&&d.push(e[1]);for(e in d)b.hasOwnProperty(d[e])||(b[d[e]]=[]),a[c]=b[d[e]];if(!(0<d.length)){f=FormBuilder.regex.reg_out_val;h=-1;for(d=[];null!==(e=f.exec(a[c]))&&!(h>=f.lastIndex);)h=f.lastIndex,d.push(e[1]);for(e in d)b.hasOwnProperty(d[e])||(b[d[e]]=""),f=new RegExp("{\\$"+d[e][1]+"}","g"),console.log(f),a[c]=a[c].replace(f,b[d[e]]);if(!(0<d.length)){f=FormBuilder.regex.pri_out_val;for(d=[];null!==(e=f.exec(a[c]));)d.push(e[1]);for(e in d)b.hasOwnProperty(d[e])||
(b[d[e]]=""),f=new RegExp("{"+d[e]+"}","g"),console.log("replacing",a[c],f,b[d[e]]),a[c]=a[c].replace(f,b[d[e]]);f=FormBuilder.regex.arr_out_val;for(d=[];null!==(e=f.exec(a[c]));)d.push(e[1]);for(e in d)b.hasOwnProperty(d[e])||(b[d[e]]=""),f=new RegExp("{"+d[e]+"}","g"),a[c]=a[c].replace(f,b[d[e]])}}}for(c in a)FormBuilder.regex.pri_in_key.test(c)?b[c.substring(1)]=a[c]:FormBuilder.regex.arr_in_key.test(c)&&(b[c.substring(2)]=a[c]);b=JSON.parse(JSON.stringify(b));for(c in a)if(-1<FormBuilder.spread_attr.indexOf(c))if(a[c]instanceof
Array)for(var k in a[c])FormBuilder.replaceStatements(a[c][k],b,g);else a[c]instanceof Object&&FormBuilder.replaceStatements(a[c],b,g);return a};FormBuilder.buildString=function(a){var b,g="";for(b in a)a[b]instanceof refObject?g+=""+a[b].get():"undefined"!=typeof a[b]?g+=""+a[b].toString():console.log(a[b],"cant be displayed");return g};
var ref=function(a,b){for(var d=null;null==d||a.hasOwnProperty(d);)d="$"+(1048576+Math.floor(15728639*Math.random())).toString(16)+"$";a[d]=b;return d},FormBuilder=function(a){this.form_object=a};FormBuilder.prototype={form_object:this.form_object,defs_object:{},parent_element:null,built_form:null,root_element:null,ref_table:{}};
FormBuilder.regex={reg_in_key:/^\/\^(.+)\$\/$/,reg_out_val:/\{(\$[1-9])\}/,pri_out_val:/\{([a-z-]+)\}/g,pri_in_key:/^\$([a-z-]+)$/,arr_out_set:/^\{\{([a-z-]+)\}\}$/,arr_out_val:/\{([a-z-]+)\.([a-z-]+)\}/g,arr_in_key:/^\$\$([a-z-]+)$/,ref_pri:/^\$[a-f0-9]{6}\$$/};FormBuilder.spread_attr=["children","next_nodes","prev_nodes","attributes","node_link"];FormBuilder.allowed_attr="node node_type next_nodes prev_nodes attributes children text repeat".split(" ");
FormBuilder.prototype.add_definition=function(a){for(var b in a)this.defs_object[b]=a[b]};FormBuilder.prototype.build=function(a){a=null==a?{}:a;for(var b in a)a[b]=ref(this.ref_table,a[b]);this.built_form=JSON.parse(JSON.stringify(this.form_object));this.built_form=FormBuilder.formatFormObject(this.built_form,this.defs_object);this.built_form=FormBuilder.replaceStatements(this.built_form,a,this.defs_object,this.ref_table)};
FormBuilder.prototype.attach=function(a){if(!(a instanceof Element)&&null==this.parent_element)return!1;this.parent_element=a instanceof Element?a:this.parent_element};FormBuilder.formatFormObject=function(a,b){if(a.hasOwnProperty("children"))for(var d in a.children)a.children[d].parent=a,FormBuilder.formatFormObject(a.children[d],b);return a};
FormBuilder.fetchNodeDefinition=function(a,b){var d,e;r=FormBuilder.regex.reg_in_key;if("undefined"!=typeof b&&b.hasOwnProperty(a))return{def:b[a]};for(d in b)if(r.test(d)&&(e=new RegExp(d.slice(1,-1)),e.test(a))){matches={};for(e=1;e<RegExp.length&&10>e;e++)matches["$"+e]=RegExp["$"+e];return{def:b[d],scope:matches}}return{}};
FormBuilder.replaceStatements=function(a,b,d,e){a=a instanceof Object?a:{};b=b instanceof Object?JSON.parse(JSON.stringify(b)):{};var c,h,f,g,n,k,l;if(a.hasOwnProperty("scope")&&a.scope instanceof Object)for(c in a.scope)b[c]=a.scope[c];if(a.hasOwnProperty("node")&&"string"==typeof a.node&&(f=FormBuilder.fetchNodeDefinition(a.node,d),f.hasOwnProperty("def")&&(a.node_link=JSON.parse(JSON.stringify(f.def)),f.hasOwnProperty("scope"))))for(c in f.scope)b[c]=f.scope[c];for(c in a)if("string"==typeof a[c])if(a[c]=
[a[c]],f=FormBuilder.replaceStatementsArray(a[c][0],b),!1!==f)a[c][0]=f;else{h=FormBuilder.regex.reg_out_val;g=-1;for(k=[];null!==(f=h.exec(a[c][0]))&&!(g>=h.lastIndex);)g=h.lastIndex,k.push(f[1]);for(f in k)b.hasOwnProperty(k[f])||(b[k[f]]=""),h=new RegExp("{\\$"+k[f][1]+"}","g"),a[c][0]=a[c][0].replace(h,b[k[f]]);if(!(0<k.length))for(n in a[c]=FormBuilder.replaceStatementsPrimary(a[c],b),h=FormBuilder.regex.arr_out_val,a[c])if(null!=a[c][n]){for(l=[];null!==(f=h.exec(a[c][n]));)l.push(f);g=0;k=
[];for(f in l)(0<g||0<l[f].index)&&k.push(a[c][n].substr(g,l[f].index)),b.hasOwnProperty(l[f][1])||(b[l[f][1]]=""),k.push(b[l[f][1]]),g=l[f].index+l[f][0].length;g<a[c][n].length&&k.push(a[c][n].substr(g,a[c][n].length));0<l.length&&(a[c]=a[c].slice(0,n).concat(k).concat(a[c].slice(n+1)))}}for(c in a)FormBuilder.regex.pri_in_key.test(c)?b[c.substring(1)]=ref(e,a[c]):FormBuilder.regex.arr_in_key.test(c)&&(b[c.substring(2)]=ref(e,a[c]));b=JSON.parse(JSON.stringify(b));for(c in a)if(-1<FormBuilder.spread_attr.indexOf(c))if(a[c]instanceof
Array)for(var p in a[c])FormBuilder.replaceStatements(a[c][p],b,d,e);else a[c]instanceof Object&&FormBuilder.replaceStatements(a[c],b,d,e);return a};FormBuilder.replaceStatementsArray=function(a,b){var d=null,d=FormBuilder.regex.arr_out_set.exec(a);if(null===d)return!1;b.hasOwnProperty(d[1])||(b[d[1]]=[]);return b[d[1]]};
FormBuilder.replaceStatementsPrimary=function(a,b){var d=FormBuilder.regex.pri_out_val,e=null,c=[],h,f,g;for(g=0;g<a.length;g++){m=null;c=[];h=0;for(f=[];null!==(e=d.exec(a[g]));)c.push(e);for(e=0;e<c.length;e++)(0<h||0<c[e].index)&&f.push(a[g].substr(h,c[e].index)),b.hasOwnProperty(c[e][1])||(b[c[e][1]]=""),f.push(b[c[e][1]]),h=c[e].index+c[e][0].length;h<a[g].length&&f.push(a[g].substr(h,a[g].length));0<c.length&&(a=a.slice(0,g).concat(f).concat(a.slice(g+1)))}return a};
FormBuilder.buildString=function(a,b){var d,e="";if("string"==typeof b&&FormBuilder.regex.ref_pri.test(b))return a[b];for(d in b)e=FormBuilder.regex.ref_pri.test(b[d])&&a.hasOwnProperty(b[d])?a[b[d]]instanceof Array?e+(""+FormBuilder.buildString(a,a[b[d]])):e+(""+a[b[d]]):e+(""+b[d].toString());return e};

View File

@ -7,18 +7,22 @@
/****************************************************/
/* [1] REFERENCES DE VALEURS
=========================================================*/
var refObject = function(variable){ this.value = variable; };
// Construction d'un référence
var ref = function(ref_table, variable){
/* (1) On cherche une nouvelle clé */
var key = null;
refObject.prototype = {
value: this.value,
get: function(){ return this.value; },
set: function(variable){ this.value = variable; },
valueOf: function(){ return this.get(); }
while( key == null || ref_table.hasOwnProperty(key) )
key = '$'+ ( 0x100000+Math.floor( Math.random()*0xefffff) ).toString(16)+'$';
/* (2) On attribue la valeur */
ref_table[key] = variable;
/* (3) On retourne la clé */
return key;
};
// alias
var ref = function(variable){ return new refObject(variable); };
// Lecteur de référence
@ -63,8 +67,8 @@ FormBuilder.prototype = {
defs_object: {}, // objet des définitions des éléments
parent_element: null, // element qui contiendra le formulaire
built_form: null, // Object correspondant au formulaire construit
root_element: null // Element correspondant à l'objet construit
root_element: null, // Element correspondant à l'objet construit
ref_table: {} // Tableau contenant la liste des références
};
@ -80,7 +84,9 @@ FormBuilder.regex = {
pri_in_key: /^\$([a-z-]+)$/, // Regex associée à la clé d'une variable primitive
arr_out_set: /^\{\{([a-z-]+)\}\}$/, // Regex associée à un tableau à remplacer
arr_out_val: /\{([a-z-]+)\.([a-z-]+)\}/g, // Regex associée à une valeur de tableau à remplacer (primitif)
arr_in_key: /^\$\$([a-z-]+)$/ // Regex associée à la clé d'un tableau
arr_in_key: /^\$\$([a-z-]+)$/, // Regex associée à la clé d'un tableau
ref_pri: /^\$[a-f0-9]{6}\$$/ // Clé de référence
};
FormBuilder.spread_attr = [ // Liste des attributs diffusant le scope
@ -140,10 +146,8 @@ FormBuilder.prototype.build = function(scope){
scope = (scope == null) ? {} : scope;
/* (2) On transforme toutes les variables en références */
// TODO: prendre uniquement les références
// for( var key in scope )
// scope[key] = scope[key];
for( var key in scope )
scope[key] = ref(this.ref_table, scope[key]);
/* [1] On clone l'object
=========================================================*/
@ -158,7 +162,7 @@ FormBuilder.prototype.build = function(scope){
/* [3] On remplace les valeurs
==================================================================*/
this.built_form = FormBuilder.replaceStatements(this.built_form, scope, this.defs_object);
this.built_form = FormBuilder.replaceStatements(this.built_form, scope, this.defs_object, this.ref_table);
};
@ -292,11 +296,12 @@ FormBuilder.fetchNodeDefinition = function(node, defs){
* @object<Object> Objet dans lequel remplacer les valeurs
* @scope<Object> Ensemble des variables permettant le remplacement
* @definitions<Object> Définitions des éléments
* @ref_table<Object> Table des références
*
* @return replaced<Object> Objet avec les remplacements effectués
*
*/
FormBuilder.replaceStatements = function(object, scope, definitions){
FormBuilder.replaceStatements = function(object, scope, definitions, ref_table){
/* [0] Initialisation
==================================================================*/
/* (1) Paramètres */
@ -304,7 +309,8 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
scope = (scope instanceof Object) ? JSON.parse(JSON.stringify(scope)) : {};
/* (2) Variables */
var key, r, tmp, m, found, lasti;
var key, r, tmp, m, found, lasti, s, parts;
var m_arr, m_reg, m_pri, m_aval;
/* (3) On récupère le scope s'il est dans l'attribut 'scope' */
if( object.hasOwnProperty('scope') && object.scope instanceof Object )
@ -335,7 +341,6 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
}
object.received = scope;
/* [2] On remplace les valeurs
==================================================================*/
@ -345,34 +350,21 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
==================================================================*/
if( typeof object[key] == 'string' ){
// On transforme en tableau
object[key] = [object[key]];
/* (2.1) On cherche tous les TABLEAUX à remplacer
---------------------------------------------------------*/
/* (1.1) On récupère les remplacements de TABLEAUX */
m = null, r = FormBuilder.regex.arr_out_set;
var m_arr = [];
/* (1.2) Si ça match */
if( m = r.exec(object[key]) )
m_arr.push( m[1] );
/* (1.3) Pour chaque match */
for( m in m_arr ){
// {1} Si la var n'est pas dans le scope //
if( !scope.hasOwnProperty(m_arr[m]) )
scope[m_arr[m]] = []; // on met un tableau vide
// {2} on attribue le tableau //
object[key] = scope[m_arr[m]];
// console.log('arr', m_arr[m], scope[m_arr[m]]);
/* (1) On récupère le remplacement */
m_arr = FormBuilder.replaceStatementsArray(object[key][0], scope);
/* (2) Si on a remplacé, on remplace, et on passe à la clé suivante */
if( m_arr !== false ){
object[key][0] = m_arr;
continue;
}
/* (1.4) Si on a trouvé qqch, on passe à la clé suivante */
if( m_arr.length > 0 )
continue;
/* (2.2) On cherche toutes les variables REGEX à remplacer
@ -380,11 +372,11 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
/* (1.1) On récupère les remplacements REGEX */
m = null, r = FormBuilder.regex.reg_out_val,
lasti = -1;
var m_reg = [];
m_reg = [];
/* (1.2) Tant que ça match */
var max = 10;
while( (m=r.exec(object[key])) !== null && max > 0 ){
while( (m=r.exec(object[key][0])) !== null && max > 0 ){
// si on boucle, on sort
if( lasti >= r.lastIndex ) break;
lasti = r.lastIndex;
@ -400,7 +392,7 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
// {2} on remplace toutes les occurences par la valeur //
tmp = new RegExp( "{\\$"+m_reg[m][1]+"}", 'g' );
object[key] = object[key].replace(tmp, scope[m_reg[m]]);
object[key][0] = object[key][0].replace(tmp, scope[m_reg[m]]);
}
@ -411,60 +403,66 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
/* (2.3) On cherche toutes les variables PRIMITIVES à remplacer
---------------------------------------------------------*/
/* (1.1) On récupère les remplacements PRIMITIFS */
m = null, r = FormBuilder.regex.pri_out_val;
var m_pri = [];
/* (1.2) Tant que ça match */
while( (m=r.exec(object[key])) !== null )
m_pri.push( m[1] );
/* (1.3) Pour chaque match */
for( m in m_pri ){
// {1} Si la var n'est pas dans le scope //
if( !scope.hasOwnProperty(m_pri[m]) )
scope[m_pri[m]] = ''; // on met une chaine vide
// {2} on remplace toutes les occurences par la valeur //
tmp = new RegExp( "{"+m_pri[m]+"}", 'g' );
console.log('replacing', object[key], tmp, scope[m_pri[m]]);
object[key] = object[key].replace(tmp, scope[m_pri[m]]);
}
/* (1.4) Si on a trouvé qqch, on passe à la clé suivante */
// if( m_pri.length > 0 )
// continue;
/* (1) On récupère les remplacements */
object[key] = FormBuilder.replaceStatementsPrimary(object[key], scope);
/* (2.4) On cherche toutes les valeurs de TABLEAUX à remplacer
---------------------------------------------------------*/
/* (1.1) On récupère les remplacements de valeurs de TABLEAUX */
m = null, r = FormBuilder.regex.arr_out_val;
var m_aval = [];
r = FormBuilder.regex.arr_out_val;
/* (1.2) Tant que ça match */
while( (m=r.exec(object[key])) !== null )
m_aval.push( m[1] );
/* (1.2) Pour chaque partie de la chaine */
for( s in object[key] ){
// bugfix
if( object[key][s] == null )
continue;
/* (1.3) Pour chaque match */
for( m in m_aval ){ //TODO: implémenter l'ajout des items d'un tableau au scope lors d'un "repeat"
// {1} Si la var n'est pas dans le scope //
if( !scope.hasOwnProperty(m_aval[m]) )
scope[m_aval[m]] = ''; // on met une chaine vide
m = null,
m_aval = [];
// {2} on remplace toutes les occurences par la valeur //
tmp = new RegExp( "{"+m_aval[m]+"}", 'g' );
object[key] = object[key].replace(tmp, scope[m_aval[m]]);
/* (1.3) Tant que ça match */
while( (m=r.exec(object[key][s])) !== null )
m_aval.push( m );
/* (1.4) Pour chaque match */
lasti = 0;
parts = [];
for( m in m_aval ){
// {1} On met la chaine d'avant le match //
if( lasti > 0 || m_aval[m].index > 0 )
parts.push( object[key][s].substr(lasti, m_aval[m].index) );
// {2} Si la var n'est pas dans le scope //
if( !scope.hasOwnProperty(m_aval[m][1]) )
scope[m_aval[m][1]] = ''; // on met une chaine vide
// {3} On met le match //
parts.push( scope[m_aval[m][1]] );
// {4} On met à jour l'index de fin pour la suite //
lasti = m_aval[m].index + m_aval[m][0].length;
// // {2} [OLD]on remplace toutes les occurences par la valeur //
// tmp = new RegExp( "{"+m_pri[m]+"}", 'g' );
// object[key][s] = object[key][s].replace(tmp, scope[m_pri[m]]);
}
/* (1.4) Si on a trouvé qqch, on passe à la clé suivante */
// if( m_aval.length > 0 )
// continue;
// {5} On ajoute la partie après le match //
if( lasti < object[key][s].length )
parts.push( object[key][s].substr(lasti, object[key][s].length) );
/* (1.5) Si on l'attribue */
if( m_aval.length > 0 )
object[key] = object[key].slice(0, s).concat(parts).concat(object[key].slice(s+1));
}
}
@ -479,12 +477,12 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
/* (1) Ajout des variables de type '$nomVar'
---------------------------------------------------------*/
if( FormBuilder.regex.pri_in_key.test(key) )
scope[ key.substring(1) ] = object[key];
scope[ key.substring(1) ] = ref( ref_table, object[key] );
/* (2) Ajout des tableaux de type '$$nomArr'
---------------------------------------------------------*/
else if( FormBuilder.regex.arr_in_key.test(key) )
scope[ key.substring(2) ] = object[key];
scope[ key.substring(2) ] = ref( ref_table, object[key] );
}
@ -503,13 +501,13 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
/* (1) Si c'est un tableau, on lance récursivement pour chaque item */
if( object[key] instanceof Array )
for( var i in object[key] )
FormBuilder.replaceStatements(object[key][i], scope, definitions);
FormBuilder.replaceStatements(object[key][i], scope, definitions, ref_table);
// console.log(object.node, key+'['+i+']');
/* (2) Si c'est un objet, on lance récursivement */
else if( object[key] instanceof Object )
FormBuilder.replaceStatements(object[key], scope, definitions);
FormBuilder.replaceStatements(object[key], scope, definitions, ref_table);
// console.log(object.node, key);
@ -523,38 +521,147 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
};
/* REMPLACE UN TABLEAU SOUS LA FORME "{{arrayName}}" par sa référence
*
* @statement<String> String contenant la chaine
* @scope<Object> Objet contenant le scope
*
* @return newVal<String> Retourne la nouvelle (ref) valeur ou FALSE si rien n'a été fais
*
*/
FormBuilder.replaceStatementsArray = function(statement, scope){
/* (1) On initialise les variables */
var match = null;
var regex = FormBuilder.regex.arr_out_set;
/* (2) On exécute la regex */
match = regex.exec(statement);
/* (3) Si ça match pas, on retourne FALSE */
if( match === null )
return false;
/* (4) Sinon, si le tableau n'est pas dans le scope, on l'initialise */
if( !scope.hasOwnProperty(match[1]) )
scope[match[1]] = []; // on met un tableau vide
/* (5) On remplace le 'statement' par le tableau */
return scope[match[1]];
};
/* REMPLACE LES VARIABLE SOUS LA FORME "{varName}" par leur référence
*
* @statements<Array> Tableau contenant les parties de la chaine
* @scope<Object> Objet contenant le scope
*
* @return splitVal<Array> Tableau contenant les parties de la chaine (références + chaine)
*
*/
FormBuilder.replaceStatementsPrimary = function(statements, scope){
/* [1] Initialisation
=========================================================*/
var regex = FormBuilder.regex.pri_out_val;
var match = null;
var matches = [];
var lasti, parts, p, i;
/* [2] Pour chaque partie de la chaine
=========================================================*/
for( p = 0 ; p < statements.length ; p++ ){
/* (1) Initialisation */
m = null, matches = [],
lasti = 0, parts = [];
/* (2) Tant que ça match, on récupère les infos du match */
while( (match=regex.exec(statements[p])) !== null )
matches.push( match );
/* [3] Pour chaque match
=========================================================*/
for( i = 0 ; i < matches.length ; i++ ){
/* (1) On met la chaine d'avant le match (si existe) */
if( lasti > 0 || matches[i].index > 0 )
parts.push( statements[p].substr(lasti, matches[i].index) );
/* (2) Si la var n'est pas dans le scope, on l'initialise vide */
if( !scope.hasOwnProperty(matches[i][1]) )
scope[matches[i][1]] = ''; // on met une chaine vide
/* (3) On insère la valeur du scope */
parts.push( scope[matches[i][1]] );
/* (4) On met à jour l'index de fin pour la suite */
lasti = matches[i].index + matches[i][0].length;
}
/* (5) On ajoute la partie après le match */
if( lasti < statements[p].length )
parts.push( statements[p].substr(lasti, statements[p].length) );
/* [4] Si on a remplacé qqch, on remplace statements[p] par sa décomposition
=========================================================*/
if( matches.length > 0 )
statements = statements.slice(0, p).concat(parts).concat(statements.slice(p+1));
}
/* [5] On retourne la chaine modifiée (ou non)
=========================================================*/
return statements;
};
/* CONSTRUIT UNE CHAINE A PARTIR DE SES PARTIES (VARIABLES OU TEXTE BRUT)
*
* @ref_table<Object> Objet contenant les références
* @parts<Array> Tableau contenant les parties
*
* @return built<String> Chaine recomposée
*
*/
FormBuilder.buildString = function(parts){
FormBuilder.buildString = function(ref_table, parts){
/* [0] Initialisation
=========================================================*/
var i, built = "";
/* [1] On remplace par les valeurs
/* [1] Si c'est un tableau, on le retourne
=========================================================*/
if( typeof parts == 'string' && FormBuilder.regex.ref_pri.test(parts) )
return ref_table[parts];
/* [2] Sinon, on remplace par les valeurs
=========================================================*/
for( i in parts ){
/* (1) Si <refObject>, on ajoute la valeur */
if( parts[i] instanceof refObject )
built += '' + parts[i].get();
/* (1) Si <refObject>, on ajoute la valeur (si elle existe) */
if( FormBuilder.regex.ref_pri.test(parts[i]) && ref_table.hasOwnProperty(parts[i]) ){
// si le résultat est un tableau, on lance récursivement
if( ref_table[parts[i]] instanceof Array )
built += ''+ FormBuilder.buildString(ref_table, ref_table[parts[i]]);
// sinon
else
built += '' + ref_table[parts[i]];
/* (2) Sinon, on ajoute simplement */
else if( typeof parts[i] != 'undefined' )
}else
built += '' + parts[i].toString();
/* (3) Erreur */
else
console.log(parts[i], 'cant be displayed');
}
/* [2] On retourne le résultat
/* [3] On retourne le résultat
=========================================================*/
return built;

View File

@ -1,4 +1,4 @@
document.body.innerHTML="";"use strict";
var default_definition={input:{node_type:"input"},"/^h([1-6])$/":{node_type:"h{$1}"},br:{node_type:"br"},option:{node_type:"option"},select:{node_type:"select"},span:{node_type:"span"}},custom_definition={"/^input.([a-z]+)$/":{node:"input",attributes:{type:"{$1}","data-name":"{name}",value:"{value}",placeholder:"{placeholder}"},next_nodes:[{node:"br"}]},"custom-select":{node:"span",attributes:{"class":"select-container nobold"},children:[{node:"select",attributes:{"data-name":"{name}"},children:[{node:"option",
attribute:{value:"{options.value}"},text:"{options.value}",repeat:"{{options}}"}]}],next_nodes:[{node:"br"}]}},form={node:"h4",attributes:{"data-icon":"o","class":"new-contact color2"},children:[{node:"input.hidden",$name:"uid",$value:"{uid}"},{node:"input.hidden",$name:"call",$value:"{call}"},{node:"input.hidden",$name:"sms",$value:"{sms}"},{node:"input.hidden",$name:"countcall",$value:"{countcall}"},{node:"input.hidden",$name:"countsms",$value:"{countsms}"},{node:"input.hidden",$name:"total",$value:"{countcall} calls + {countsms} sms to {number}"},
{node:"input.text",$name:"number",$value:"{number}"},{node:"custom-select",$name:"existing",$$options:"{{options}}"}]},fb=new FormBuilder(form);fb.add_definition(default_definition);fb.add_definition(custom_definition);fb.build({uid:1,call:2,sms:3,countcall:4,countsms:5,number:"01 02 03 04 05",options:["a","b","c","d"]});console.log(fb.built_form);
attribute:{value:"{options.value}"},text:"{options.value}",repeat:"{{options}}"}]}],next_nodes:[{node:"br"}]}},form={node:"h4",attributes:{"data-icon":"o","class":"new-contact color2"},children:[{node:"input.hidden",$name:"uid",$value:"{uid}"},{node:"input.hidden",$name:"call",$value:"{call}"},{node:"input.hidden",$name:"sms",$value:"{sms}"},{node:"input.hidden",$name:"countcall",$value:"{countcall}"},{node:"input.hidden",$name:"countsms",$value:"{countsms}"},{node:"input.hidden",$name:"total",$value:"xx{countcall} calls + {countsms} sms to {number}xx"},
{node:"input.text",$name:"number",$value:"{number}"},{node:"custom-select",$name:"existing",$$options:"{{options}}"}]},fb=new FormBuilder(form);fb.add_definition(default_definition);fb.add_definition(custom_definition);fb.build({uid:1,call:2,sms:3,countcall:4,countsms:5,number:"01 02 03 04 05",options:["a","b","c","d"]});console.log(fb.built_form);var str=function(a){return FormBuilder.buildString(fb.ref_table,a)};

View File

@ -58,7 +58,7 @@ var form = {
{ node: 'input.hidden', $name: 'sms', $value: '{sms}' },
{ node: 'input.hidden', $name: 'countcall', $value: '{countcall}' },
{ node: 'input.hidden', $name: 'countsms', $value: '{countsms}' },
{ node: 'input.hidden', $name: 'total', $value: '{countcall} calls + {countsms} sms to {number}' },
{ node: 'input.hidden', $name: 'total', $value: 'xx{countcall} calls + {countsms} sms to {number}xx' },
{ node: 'input.text', $name: 'number', $value: '{number}' },
@ -85,3 +85,5 @@ fb.build({
options: ['a', 'b', 'c', 'd']
});
console.log(fb.built_form);
var str = function(attr){ return FormBuilder.buildString(fb.ref_table, attr); };