Définition des premiers comportements du form-builder, dans 'js/form-builder.js'

This commit is contained in:
xdrm-brackets 2016-09-15 19:53:51 +02:00
parent 0959e171d5
commit f8e28de6f6
9 changed files with 129 additions and 304 deletions

View File

@ -1,226 +0,0 @@
<?php
namespace api;
use \manager\ManagerError;
/* CLASSE PERMETANT L'UTILISATION DU manifest.json POUR UTILISER DES APIS DIVERSES
*
* @return nomRetour<typeRetour> Description du retour
*
*/
class client{
// Fichier de configuration par defaut
private $config_path = __ROOT__.'/api/manifest.json';
public $error;
// liste des methodes
public static $METHODS = [
'POST' => [ CURLOPT_POST, true ],
'GET' => [ CURLOPT_HTTPGET, true ],
'PUT' => [ CURLOPT_CUSTOMREQUEST, 'PUT' ],
'DELETE' => [ CURLOPT_CUSTOMREQUEST, 'DELETE' ]
];
/*************/
/* ATTRIBUTS */
/*************/
private $manifest = null; // Contiendra le tableau correspondant au JSON
private $requests = []; // Contiendra la liste des requetes de l'api et leurs parametres
private $name;
private $description;
private $version;
/* CONSTRUCTEUR DU CLIENT DE L'API
*
* @config<String> Chemin du fichier de configuration de l'api
*
*/
public function __construct($config=null){
/* [0] Gestion du fichier de config si donne en param
=========================================================*/
if( $config !== null ) $this->config_path = $config;
/* [1] On recupere le contenu du fichier de config
=========================================================*/
$manifest = json_decode( file_get_contents($this->config_path), true );
// Si erreur de parsage ou de fichier, on retourne une erreur
if( $manifest === null ){
$this->error = ManagerError::ParsingFailed;
return;
}
/* [2] On repartie et classe les donnees
=========================================================*/
/* (1) Informations generales */
$name = $manifest['name'];
$description = $manifest['description'];
$version = $manifest['version'];
/* (2) Liste des requetes */
$this->requests = $manifest['requests'];
}
/* ENVOI ET CONSTRUCTION D'UNE REQUETE
*
* @request_name<String> Nom de la requete en question
* @parameters<Array> Liste des parametres de la requete
*
* @return response<Array> Reponse HTTP au format norme ou FAUX si une erreur occure
*
*/
public function send($request_name, $parameters=[]){
/* [1] On construit la requete avec les parametres
=========================================================*/
$build = $this->build($request_name, $parameters);
// Si la construction a echoue, on retourne une erreur
if( $build === false ) return false;
/* [2] Header et pre-data de la requete
=========================================================*/
/* (1) On definit l'URL */
$curl = curl_init($build['url']);
// permet de recupere le resultat au lieu de l'afficher
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
/* (2) On definit la methode */
$method_arguments = self::$METHODS[ $build['method'] ];
curl_setopt($curl, $method_arguments[0], $method_arguments[1]);
/* (3) On definit les headers */
$headers = [];
// On construit le header au bon format : 'name: value'
foreach($build['headers'] as $name=>$value)
array_push($headers, $name.': '.$value);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
/* (4) On definit les donnees POST si on est pas en get */
if( $build['method'] != 'GET' ){
$postdata = '';
// On formatte les donnees au format 'key=value&key=value'
foreach($build['postdata'] as $key=>$value)
$postdata .= $key.'='.$value.'&';
rtrim($postdata); // on supprime le '&' a la fin s'il y a
// On envoie les donnees
curl_setopt($curl, CURLOPT_POSTFIELDS, $postdata);
}
/* [4] Execution de la requete et recup de la response
=========================================================*/
$response = curl_exec($curl);
curl_close($curl);
/* [5] On retourne la reponse
=========================================================*/
return $response;
}
/* CONSTRUCTION D'UNE REQUETE
*
* @request_name<String> Nom de la requete
* @parameters<Array> Liste des parametres de la requete
*
* @return filledRequest<Array> Renvoie la requete avec les bons parametres
*
*/
private function build($request_name, $parameters=[]){
/* [0] Gestion des INPUTS
=========================================================*/
// On retourne une erreur si la requete n'existe pas
if( !isset($this->requests[$request_name]) ) return false;
// On enregistre une copie de la requete
$request = $this->requests[$request_name];
/* [1] Gestion de la methode
=========================================================*/
// Si la methode n'est pas prise en compte, on retourne une erreur
if( !isset( self::$METHODS[$request['method']] ) ) return false;
/* [2] Remplacement des parametres (valeurs globales)
=========================================================*/
/* (1) Remplacement dans l'URL */
$request['url'] = $this->fillParameters($request['url'], $parameters);
/* (2) Remplacement dans les headers */
foreach($request['headers'] as $name=>$value)
$request['headers'][$name] = $this->fillParameters($value, $parameters);
/* (2) Remplacement dans les postdata */
foreach($request['postdata'] as $name=>$value)
$request['postdata'][$name] = $this->fillParameters($value, $parameters);
/* [3] Retour de la requete construite
=========================================================*/
return $request;
}
/* REMPLACE LES PARAMETRES DANS UNE CHAINE
*
* @before<String> Chaine a etudier et dans laquelle remplacer les parametres
* @parameters<Array> Liste des parametres a remplacer (prefixes d'un '@')
*
* @return after<String> Chaine contenant les parametres de la liste @parameters
*
*/
private function fillParameters($before, $parameters){
// On initialise la valeur de retour
$after = $before;
/* [1] On remplace les parametres prefixes par '@'
=========================================================*/
foreach($parameters as $name=>$value){
$position = strpos($after, $name);
// Si on a trouve, on remplace le nom de variable par la valeur
if( $position !== false )
$after = substr($after, 0, $position) . $value . substr($after, $position+strlen($name) );
}
/* [2] On retourne la nouvelle chaine
=========================================================*/
return $after;
}
}
?>

View File

@ -1,39 +0,0 @@
{
"name": "@api_name",
"version": "@api_version_number",
"description": "@api_description",
"requests": {
"@request_name":{
"url": "@request_request_url",
"headers": {
"@header_name_1": "@header_value_1",
"@header_name_2": "@header_value_2",
},
"method": "@request_http_method",
"description": "@request_description",
"input": {
"@input_variable1_name" : "@input_default1_value",
"@input_variable2_name" : "@input_default2_value",
"@input_variable..._name": "@input_default..._value",
"@input_variableA_name" : "<@input_variableA_type>",
"@input_variableB_name" : "<@input_variableB_type>",
"@input_variable..._name": "<@input_variable..._type>",
},
"output": {
"@output_variable1_name" : "<@output_variable1_type>",
"@output_variable2_name" : "<@output_variable2_type>",
"@output_variable..._name": "<@output_variable..._type>",
}
}
}
}

View File

@ -1,36 +0,0 @@
{
"name": "socioview_api",
"version": "0.1",
"description": "API de la plateforme d'acquisition et de visualisation de donnees dans le cadre d'etudes relationnelles en sociologie",
"requests": {
"parse-call-log": {
"url": "socioview/api/",
"method": "POST",
"headers": { "Authorization": "Digest @token" },
"postdata": {
"path": "call_log/unserialize",
"data": "[@xmlstring]"
},
"description": "Renvoie a partir du contenu d'un fichier de journal d'appel XML un objet classant les relations SMS/MMS par nombre de messages recus et emis, et de meme pour les appels classes par nombre d'appels."
},
"generate-network-chart-data": {
"url": "socioview/api/",
"method": "POST",
"headers": { "Authorization": "Digest @token" },
"postdata": {
"path": "charts/network_data"
},
"description": "Renvoie un jeu de donnees pour un graphique de type network"
}
}
}

View File

@ -53,11 +53,11 @@
/* [1] Test du client de l'API generique
=========================================================*/
// $api = new client();
//
// $response = $api->send('generate-network-chart-data', [
// '@token'=> '52945efbed43b50c12413f2f0e9519bfd9e98ce8'
// ]);
//
// var_dump($response);

2
js/lib/form-builder-min.js vendored Normal file
View File

@ -0,0 +1,2 @@
var default_definition={input:{html:"<input {{__attributes__}}>"},"h/^([1-6])$/":{html:"<h{{$1}} {{__attributes__}}>{{__children__}}</h{{$1}}>"},br:{html:"<br>"},option:{html:"<option {{__attributes__}}>{{__children__}}</option>"},select:{html:"<select {{__attributes__}}>{{__children__}}</select>"}},custom_definition={"input:/^([a-z]+)$/":{node:"input",attributes:{type:"{{$1}}","data-name":"{{name}}",value:"{{value}}",placeholder:"{{placeholder}}"},next_child:{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}}"}]};

118
js/lib/form-builder.js Normal file
View File

@ -0,0 +1,118 @@
// <h4 data-icon='o' class='new-contact color2'>
//
// <input type='hidden' data-name='uid' value='@uid'>\n+
// <input type='hidden' data-name='call' value='@call'>\n+
// <input type='hidden' data-name='sms' value='@sms'>\n+
//
// <input type='hidden' data-name='countcall' value='@countcall'>\n+
// <input type='hidden' data-name='countsms' value='@countsms'>\n+
//
// <input type='text' data-name='number' placeholder='Numéro de téléphone' value='@number' >
//
// <span class='select-container nobold'><select data-name='existing'>\n+
// <option value='.'>Utiliser pseudo</option>\n+
// @contacts+
// </select></span>\n+
//
// &nbsp;&nbsp;&nbsp;&nbsp;ou&nbsp;&nbsp;&nbsp;&nbsp;\n+
//
// <input type='text' data-name='username' placeholder='Pseudo' value='@username' >
// <input type='submit' class='primary sub-number' value='Enregistrer'>
//
// </h4>\n\n);
//////////////
// USE CASE //
//////////////
////////////////
// PARAMETERS //
////////////////
// {xx} - where 'xx' is a variable name which will be (literally) replaced by the $xx given parameter (if missing, by an empty string)
// note that the parameter in a higher level have to be preceeded by '$'
// /!\ warning: the variable name must only contain [ lowercase_letters, hyphens ]
//
// {{zz}} - where 'zz' is an array variable name which will be (for each item) replaced by the $$zz given array (see next statement)
// note that the parameter in a higher level have to be preceeded by '$$'
//
// {zz.xx} - where 'zz' is an array name + 'xx' is an index name of this array's items, it will be replaced by zz[0][xx], then zz[1][xx], etc
// note that this is the only case when the dot (.) is allowed in variable naming
//
// {__attributes__} - default variable name for the attributes
// {__children__} - default variable name for the children
/////////////////////////
// REGURAL EXPRESSIONS //
/////////////////////////
// /^yy$/ - where '^yy$' is a regular expression, matches will be added to the input parameters named like so : '$1', '$2'
// note that it have to match the whole string and begin with '/^' and end with '$/'
////////////////////////
// DEFAULT ATTRIBUTES //
////////////////////////
//
// @node - is a "key" of a definition that describes an element
// @html - overrides all to specify the html content corresponding of the element
// @children - the set of the element's children (doesn't check if it is a container or not)
// @data - parameters to pass to a lower level
// @attributes - attributes are replaced in a lower level
// @listeners - contient les associations 'eventName' => 'listenerFuncName'
// $xxx - where 'xxx' is a variable name that will be replaced in a lower level
// $$zzz - where 'zzz' is an array variable name that will be split in a lower level
var default_definition = {
'input': { html: '<input {__attributes__}>' },
'h/^([1-6])$/': { html: '<h{$1} {__attributes__}>{__children__}</h{$1}>' },
'br': { html: '<br>' },
'option': { html: '<option {__attributes__}>{__children__}</option>' },
'select': { html: '<select {__attributes__}>{__children__}</select>' },
'span': { html: '<span {__attributes__}>{__children__}</span>' }
};
var custom_definition = {
'input:/^([a-z]+)$/': {
node: 'input',
attributes: {
'type': '{$1}',
'data-name': '{name}',
'value': '{value}',
'placeholder': '{placeholder}' },
next_child: { 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}' },
children: { html: '{options.value}' } } },
next_child: { node: 'br' } },
};
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:text', $name: 'number', $value: '{number}' },
{ node: 'custom-select', $name: 'number', $$options: '{{options}}' }
]
};
// <span class='select-container nobold'><select data-name='existing'>\n+
// <option value='.'>Utiliser pseudo</option>\n+
// @contacts+
// </select></span>\n+

1
js/lib/form-builder/main-min.js vendored Normal file
View File

@ -0,0 +1 @@
document.body.innerHTML="";

View File

@ -0,0 +1,3 @@
/* [0] On efface le <body>
=========================================================*/
document.body.innerHTML = '';

View File

@ -26,6 +26,7 @@
<!-- Dépendences Javascript -->
<script type='text/javascript' src='/js/lib/crc32-min.js' ></script> <!-- Système de hash unique et rapide -->
<script type='text/javascript' src='/js/lib/local-storage-interface-min.js' ></script> <!-- Interface de gestion du 'localStorage' -->
<script type='text/javascript' src='/js/lib/form-builder.js' ></script> <!-- Gestion de construction de <form> -->
<script type='text/javascript' src='/js/lib/html-builder-min.js' ></script> <!-- Gestion de construction de HTML -->
<script type='text/javascript' src='/js/lib/input-checker-min.js' ></script> <!-- Gestion dynamique des saisies -->
<script type='text/javascript' src='/js/lib/form-deflater-min.js' ></script> <!-- Gestion des formulaires js-friendly -->
@ -120,7 +121,8 @@
<!-- Dépendences Javascript après chargement des éléments -->
<script type='text/javascript' src='/js/action-script-min.js'></script>
<script type='text/javascript' src='/js/lib/form-builder/main.js'></script>
<!-- <script type='text/javascript' src='/js/action-script-min.js'></script> -->
</body>
</html>