Gestion de 'node_link' en clonage (et non référence) + gestion du passage de 'scope'

This commit is contained in:
xdrm-brackets 2016-09-18 10:44:21 +02:00
parent 3d346f5efe
commit 504ee83d33
4 changed files with 47 additions and 43 deletions

View File

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

View File

@ -147,10 +147,10 @@ FormBuilder.formatFormObject = function(object, defs){
var found_def = FormBuilder.fetchNodeDefinition(object.node, defs);
// Si on trouve
if( found_def !== null ){
if( typeof found_def.def != 'undefined' ){
// 1. On inclus la définition dans l'attribut 'node_link'
object.node_link = found_def.def;
// 1. On clone la définition dans l'attribut 'node_link'
object.node_link = JSON.parse( JSON.stringify(found_def.def) );
// 2. On ajoute les matches dans l'attribut 'scope'
if( found_def.hasOwnProperty('scope') )
@ -200,7 +200,7 @@ FormBuilder.fetchNodeDefinition = function(node, defs){
=========================================================*/
if( defs != null && defs.hasOwnProperty(node) ){
return { def: defs.node, scope: null };
return { def: defs.node };
/* [2] Sinon, on cherche une REGEX
@ -240,7 +240,7 @@ FormBuilder.fetchNodeDefinition = function(node, defs){
// Si on a rien trouvé, on retourne NULL
return null;
return {};
};
@ -252,23 +252,24 @@ FormBuilder.fetchNodeDefinition = function(node, defs){
* @return replaced<Object> Objet avec les remplacements effectués
*
*/
FormBuilder.replaceStatements = function(object, scope){
FormBuilder.replaceStatements = function(object, scope, pad){
/* [0] Initialisation
=========================================================*/
/* (1) Paramètres */
object = (object instanceof Object) ? object : {};
scope = (scope instanceof Object) ? JSON.parse(JSON.stringify(scope)) : {};
/*DEBUG*/pad= (pad==null) ? '' : pad + ' ';
/* (2) Variables */
var key, r, tmpr, m;
var next_scope = {};
object.received = scope;
/* (3) On récupère le scope s'il est dans l'attribut 'scope' */
if( object.hasOwnProperty('scope') && object.scope instanceof Object )
for( key in object.scope )
next_scope[key] = object.scope[key];
scope[key] = object.scope[key];
object.received = JSON.parse(JSON.stringify(scope));
/* [1] On remplace les valeurs
=========================================================*/
@ -409,38 +410,39 @@ FormBuilder.replaceStatements = function(object, scope){
/* (1) Ajout des variables de type '$nomVar'
---------------------------------------------------------*/
if( FormBuilder.regex.pri_in_key.test(key) )
next_scope[ key.substring(1) ] = object[key];
scope[ key.substring(1) ] = object[key];
/* (2) Ajout des tableaux de type '$$nomArr'
---------------------------------------------------------*/
else if( FormBuilder.regex.arr_in_key.test(key) )
next_scope[ key.substring(2) ] = object[key];
scope[ key.substring(2) ] = object[key];
}
/* [3] On lance récursivement
=========================================================*/
/* (1) on clone le scope */
scope = JSON.parse(JSON.stringify(scope));
for( key in object ){
/* S'il ne s'agit d'un attribut interdit */
if( FormBuilder.spread_attr.indexOf(key) > -1 ){
console.log('spreads to', key);
/* (1) on envoie aussi le scope actuel (le tout cloné) */
Object.assign( next_scope, scope );
/* (3) Si c'est un tableau, on lance récursivement pour chaque item */
/* (1) Si c'est un tableau, on lance récursivement pour chaque item */
if( object[key] instanceof Array )
for( var i in object[key] ){
console.log(object, key+'['+i+']', scope);
FormBuilder.replaceStatements(object[key][i], next_scope);
console.log(pad+''+object.node, key+'['+i+']');
FormBuilder.replaceStatements(object[key][i], scope, pad);
}
/* (2) Si c'est un objet, on lance récursivement */
else if( object[key] instanceof Object ){
console.warn(object, key, scope);
FormBuilder.replaceStatements(object[key], next_scope);
console.log(pad+''+object.node, key);
FormBuilder.replaceStatements(object[key], scope, pad);
}

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"]});
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.a",$name:"uid",$value:"{uid}"},{node:"input.b",$name:"call",$value:"{call}"},{node:"input.c",$name:"sms",$value:"{sms}"},{node:"input.d",$name:"countcall",$value:"{countcall}"},{node:"input.e",$name:"countsms",$value:"{countsms}"},{node:"input.f",$name:"total",$value:"{countcall} calls + {countsms} sms to {number}"},
{node:"input.g",$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({});

View File

@ -53,14 +53,14 @@ var 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.a', $name: 'uid', $value: '{uid}' },
{ node: 'input.b', $name: 'call', $value: '{call}' },
{ node: 'input.c', $name: 'sms', $value: '{sms}' },
{ node: 'input.d', $name: 'countcall', $value: '{countcall}' },
{ node: 'input.e', $name: 'countsms', $value: '{countsms}' },
{ node: 'input.f', $name: 'total', $value: '{countcall} calls + {countsms} sms to {number}' },
{ node: 'input.text', $name: 'number', $value: '{number}' },
{ node: 'input.g', $name: 'number', $value: '{number}' },
{ node: 'custom-select', $name: 'existing', $$options: '{{options}}' }
]
@ -75,12 +75,14 @@ var form = {
var 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']
});
// fb.build({
// uid: 1,
// call: 2,
// sms: 3,
// countcall: 4,
// countsms: 5,
// number: '01 02 03 04 05',
// options: ['a', 'b', 'c', 'd']
// });
fb.build({});