Correction du 'scope' [FCT]

This commit is contained in:
xdrm-brackets 2016-09-18 15:11:19 +02:00
parent ca63da8d61
commit 6fb77480ca
5 changed files with 77 additions and 59 deletions

View File

@ -71,6 +71,12 @@
// 2- if a number @n is given, the element will be repeated @n times
//////////////////////
// REFERENCE SYSTEM //
//////////////////////
// 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
////////////////////////
// LANGAGE DEFINITION //
@ -92,6 +98,11 @@ var ElementObject = {
};
/////////////
// EXAMPLE //
/////////////
var default_definition = {
'input': { node_type: 'input' },
'/^h([1-6])$/': { node_type: 'h{$1}' },

View File

@ -1,9 +1,9 @@
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 c in a)this.defs_object[c]=a[c]};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,c){if(a.hasOwnProperty("children"))for(var h in a.children)a.children[h].parent=a,FormBuilder.formatFormObject(a.children[h],c);return a};
FormBuilder.fetchNodeDefinition=function(a,c){var h,b;r=FormBuilder.regex.reg_in_key;if("undefined"!=typeof c&&c.hasOwnProperty(a))return{def:c[a]};for(h in c)if(r.test(h)&&(b=new RegExp(h.slice(1,-1)),b.test(a))){matches={};for(b=1;b<RegExp.length&&10>b;b++)matches["$"+b]=RegExp["$"+b];return{def:c[h],scope:matches}}return{}};
FormBuilder.replaceStatements=function(a,c,h){a=a instanceof Object?a:{};c=c instanceof Object?JSON.parse(JSON.stringify(c)):{};var b,e,d,f,k;if(a.hasOwnProperty("scope")&&a.scope instanceof Object)for(b in a.scope)c[b]=a.scope[b];if(a.hasOwnProperty("node")&&"string"==typeof a.node&&(e=FormBuilder.fetchNodeDefinition(a.node,h),e.hasOwnProperty("def")&&(a.node_link=JSON.parse(JSON.stringify(e.def)),e.hasOwnProperty("scope"))))for(b in e.scope)c[b]=e.scope[b];for(b in a)if("string"==typeof a[b]){e=
FormBuilder.regex.arr_out_set;f=[];(d=e.exec(a[b]))&&f.push(d[1]);for(d in f)c.hasOwnProperty(f[d])||(c[f[d]]=[]),a[b]=c[f[d]];if(!(0<f.length)){e=FormBuilder.regex.pri_out_val;for(var g=[];null!==(d=e.exec(a[b]));)g.push(d);f=0;k=[];for(d in g)k.push(a[b].substring(f,g[d].index)),e=a[b].substring(g[d].index+1,g[d].index+g[d][0].length-1),c.hasOwnProperty(e)||k.push(c[e]),f=g[d].index+g[d][0].length;a[b]=FormBuilder.buildString(k);if(!(0<g.length)){e=FormBuilder.regex.reg_out_val;f=-1;for(g=[];null!==
(d=e.exec(a[b]))&&!(f>=e.lastIndex);)f=e.lastIndex,g.push(d[1]);for(d in g)c.hasOwnProperty(g[d])||(c[g[d]]=""),e=new RegExp("{\\$"+g[d][1]+"}","g"),a[b]=a[b].replace(e,c[g[d]]);if(!(0<g.length)){e=FormBuilder.regex.arr_out_val;for(f=[];null!==(d=e.exec(a[b]));)f.push(d[1]);for(d in f)c.hasOwnProperty(f[d])||(c[f[d]]=""),e=new RegExp("/{"+f[d]+"}/","g"),a[b].replace(e,c[f[d]])}}}}for(b in a)FormBuilder.regex.pri_in_key.test(b)?c[b.substring(1)]=a[b]:FormBuilder.regex.arr_in_key.test(b)&&(c[b.substring(2)]=
a[b]);c=JSON.parse(JSON.stringify(c));for(b in a)if(-1<FormBuilder.spread_attr.indexOf(b))if(a[b]instanceof Array)for(var l in a[b])FormBuilder.replaceStatements(a[b][l],c,h);else a[b]instanceof Object&&FormBuilder.replaceStatements(a[b],c,h);return a};FormBuilder.buildString=function(a){var c,h="";for(c in a)console.log(a[c]),h=a[c]instanceof refObject?h+(""+a[c].get()):h+(""+a[c].toString());return h};
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"),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};

View File

@ -5,6 +5,8 @@
/* | |_| | | | | || |___ | | | | | | */
/* \___/ |_| |___|_____|___| |_| |_| */
/****************************************************/
/* [1] REFERENCES DE VALEURS
=========================================================*/
var refObject = function(variable){ this.value = variable; };
refObject.prototype = {
@ -23,8 +25,6 @@ var ref = function(variable){ return new refObject(variable); };
/************************************************************************************/
/* _____ ___ ____ __ __ ____ _ _ ___ _ ____ _____ ____ */
/* | ___/ _ \| _ \| \/ | | __ )| | | |_ _| | | _ \| ____| _ \ */
@ -136,8 +136,15 @@ FormBuilder.prototype.add_definition = function(def_object){
FormBuilder.prototype.build = function(scope){
/* [0] Gestion du paramètres
==================================================================*/
/* (1) On initialise le scope vide s'il n'est pas donné */
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];
/* [1] On clone l'object
=========================================================*/
this.built_form = JSON.parse(JSON.stringify(this.form_object));
@ -297,7 +304,7 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
scope = (scope instanceof Object) ? JSON.parse(JSON.stringify(scope)) : {};
/* (2) Variables */
var key, r, tmp, m, found, lasti, parts;
var key, r, tmp, m, found, lasti;
/* (3) On récupère le scope s'il est dans l'attribut 'scope' */
if( object.hasOwnProperty('scope') && object.scope instanceof Object )
@ -328,6 +335,7 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
}
object.received = scope;
/* [2] On remplace les valeurs
==================================================================*/
@ -367,43 +375,7 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
continue;
/* (2.2) 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.3) Pour chaque match */
lasti = 0, parts = [];
for( m in m_pri ){
// {1} On construit les valeurs pour le 'string-builder' //
parts.push( object[key].substring(lasti, m_pri[m].index) );
// {2} Sa la valeur n'existe pas dans le scope, on la crée //
tmp = object[key].substring(m_pri[m].index+1, m_pri[m].index+m_pri[m][0].length-1);
if( !scope.hasOwnProperty(tmp) )
parts.push( scope[tmp] );
lasti = m_pri[m].index + m_pri[m][0].length;
// object[key] = object[key].replace(tmp, scope[m_pri[m]]);
// console.log('pri', m_pri[m], scope[m_pri[m]]);
}
// On met la fonction à amorcer pour construire la valeur
object[key] = FormBuilder.buildString(parts);
/* (1.4) Si on a trouvé qqch, on passe à la clé suivante */
if( m_pri.length > 0 )
continue;
/* (2.3) On cherche toutes les variables REGEX à remplacer
/* (2.2) On cherche toutes les variables REGEX à remplacer
---------------------------------------------------------*/
/* (1.1) On récupère les remplacements REGEX */
m = null, r = FormBuilder.regex.reg_out_val,
@ -427,7 +399,8 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
scope[m_reg[m]] = ''; // on met une chaine vide
// {2} on remplace toutes les occurences par la valeur //
tmp = new RegExp( "\{\\$"+m_reg[m][1]+"\}", 'g' );
tmp = new RegExp( "{$"+m_reg[m][1]+"}", 'g' );
// FIXME
object[key] = object[key].replace(tmp, scope[m_reg[m]]);
// console.log('reg', m_reg[m], scope);
@ -439,6 +412,36 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
continue;
/* (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;
/* (2.4) On cherche toutes les valeurs de TABLEAUX à remplacer
---------------------------------------------------------*/
/* (1.1) On récupère les remplacements de valeurs de TABLEAUX */
@ -457,11 +460,15 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
scope[m_aval[m]] = ''; // on met une chaine vide
// {2} on remplace toutes les occurences par la valeur //
tmp = new RegExp( "/\{"+m_aval[m]+"\}/", 'g' );
object[key].replace(tmp, scope[m_aval[m]]);
tmp = new RegExp( "{"+m_aval[m]+"}", 'g' );
object[key] = object[key].replace(tmp, scope[m_aval[m]]);
}
/* (1.4) Si on a trouvé qqch, on passe à la clé suivante */
// if( m_aval.length > 0 )
// continue;
}
@ -529,24 +536,24 @@ FormBuilder.replaceStatements = function(object, scope, definitions){
FormBuilder.buildString = function(parts){
/* [0] Initialisation
=========================================================*/
/* (1) Variables */
var i;
var built = "";
var i, built = "";
/* [1] On remplace par les valeurs
=========================================================*/
for( i in parts ){
console.log(parts[i]);
/* (1) Si <refObject>, on ajoute la valeur */
if( parts[i] instanceof refObject )
built += '' + parts[i].get();
/* (2) Sinon, on ajoute simplement */
else
else if( typeof parts[i] != 'undefined' )
built += '' + parts[i].toString();
/* (3) Erreur */
else
console.log(parts[i], 'cant be displayed');
}

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(document.body,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);
{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);

View File

@ -72,7 +72,7 @@ var form = {
var fb = new FormBuilder(document.body, form);
var fb = new FormBuilder(form);
fb.add_definition(default_definition);
fb.add_definition(custom_definition);
fb.build({