plugins.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026
  1. // Avoid `console` errors in browsers that lack a console.
  2. (function() {
  3. var method;
  4. var noop = function () {};
  5. var methods = [
  6. 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
  7. 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
  8. 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
  9. 'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
  10. ];
  11. var length = methods.length;
  12. var console = (window.console = window.console || {});
  13. while (length--) {
  14. method = methods[length];
  15. // Only stub undefined methods.
  16. if (!console[method]) {
  17. console[method] = noop;
  18. }
  19. }
  20. }());
  21. //Affiche un message 'message' de type 'type' pendant 'timeout' secondes
  22. $.message = function (type,message,timeout){
  23. message = message.replace(/<\/?script|iframe|object[^>]*>/gim,'');
  24. $.toast({ type: type, content: message, timeout: timeout });
  25. }
  26. //Permet les notifications types toast sans dépendance de librairie/css/html
  27. $.toast = function (options) {
  28. var defaults = {
  29. title: null,
  30. content: '',
  31. type: 'info',
  32. timeout: 3000
  33. };
  34. var o = $.extend(defaults, options);
  35. var css = "word-wrap:break-word;color:#ffffff;border-radius:1px;margin-bottom:10px;text-align:center;width:100%;box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.3);position:relative;";
  36. var types = {
  37. error: { css: "background:#dc2626;", icon: 'fas fa-exclamation-triangle' },
  38. warning: { css: "background:#ffc107;color:#212529;", icon: 'fas fa-exclamation-circle' },
  39. info: { css: "background:#2AA7EA;", icon: 'fas fa-info-circle' },
  40. success: { css: "background:#28a745;", icon: 'fas fa-check' },
  41. }
  42. css += types[o.type].css;
  43. o.icon = types[o.type].icon;
  44. if ($('.toastContainer').length == 0)
  45. $('body').append('<div class="toastContainer" style="z-index:1100;position:fixed;right:15px;top:65px;width:350px;"></div>');
  46. var popupContainer = $('.toastContainer');
  47. var popup = $('<div style="' + css + '" class="noPrint toast-'+o.type+'"><i class="toastRemove fas fa-times hidden" style="position:absolute;top:5px;right:5px;cursor:pointer;" onclick="$(this).parent().remove();"; style="position:absolute;top:5px;right:5px;cursor:pointer;"></i><h1 class="toastTitle" style="margin:0;padding:10px;"></h1><i class="toastIcon" style="display:inline-block;vertical-align:top;width:30px;font-size:20px;margin:15px 0;"></i><p style="display: inline-block;margin-top: 10px;padding:0 10px 0 10px;width:300px;" class="toastContent"></p><div style="clear:both;"></div></div>');
  48. $(popupContainer).append(popup);
  49. if (o.title) $('.toastTitle', popup).html(o.title);
  50. $('.toastIcon', popup).attr('class', o.icon);
  51. if (!o.title) $('.toastTitle', popup).remove();
  52. $('.toastContent', popup).html(o.content);
  53. popup.removeClass('hidden');
  54. if (o.timeout != 0) {
  55. setTimeout(function () { popup.addClass('hidden'); }, o.timeout);
  56. } else {
  57. popup.find('.toastRemove').removeClass('hidden');
  58. }
  59. }
  60. $.page = function(element){
  61. var path = window.location.pathname.split('/') ;
  62. path = path[path.length-1];
  63. path = path.replace('.php','');
  64. return path;
  65. }
  66. $.getForm= function(element){
  67. return $(element).getForm();
  68. }
  69. $.setForm= function(element,data){
  70. var o = {};
  71. var obj = $(element);
  72. $('input,select,textarea',obj).each(function(i,element){
  73. if(element.id!=null && element.id!=""){
  74. if(data[element.id]!=null){
  75. if($(element).attr("type")=='checkbox' || $(element).attr("type")=='radio'){
  76. $(element).prop("checked",data[element.id]==1 || data[element.id]=='true' ?true:false);
  77. } else {
  78. $(element).val(data[element.id]);
  79. }
  80. }
  81. }
  82. });
  83. return o;
  84. }
  85. //Gestion des tableaux pour le formData
  86. $.form_data = function(formData, key,values){
  87. var hasFile = false;
  88. if(values instanceof File ) hasFile = true;
  89. if( typeof values == 'object' && !(values instanceof File) ){
  90. for(subkey in values)
  91. if($.form_data(formData,key + '[' + subkey + ']',values[subkey])) hasFile = true;
  92. }else{
  93. formData.append(key, values);
  94. }
  95. return hasFile;
  96. }
  97. $.action = function(data,success,error,progress) {
  98. var formData = new FormData();
  99. var defaultSuccess = data.defaultSuccess != undefined ? data.defaultSuccess : true;
  100. // if(data.defaultSuccess !== undefined) delete data.defaultSuccess;
  101. //hasFile determine si un fichier uploadé se trouve dans le tableau des data
  102. // Si c'est le cas, il envois les données en multipart, sinon il les envoie en json classique.
  103. var hasFile = false;
  104. $.each(data, function(key, value){
  105. if($.form_data(formData,key, value) == true) hasFile = true;
  106. });
  107. var request = {
  108. url : 'action.php',
  109. method : 'POST',
  110. success: function(response){
  111. if(response && !response.error){
  112. if(success!=null)success(response);
  113. } else {
  114. if(response.errorCode && response.errorCode=='401') window.location = 'action.php?action=logout';
  115. var errorMessage = 'ERREUR : '+"\n"+response.error;
  116. if(response.trace) errorMessage += "\n<div style='font-size:10px;max-height:200px;overflow:auto;text-align:left;'>"+response.trace+"</div>";
  117. if(defaultSuccess) $.message('error',errorMessage,0);
  118. if(error!=null) error(response);
  119. }
  120. },
  121. error : function(response){
  122. if(response.status == 200 && $.localhost() ){
  123. $('body').append('<div class="debugFrame" style="box-shadow: 0px 0px 10px rgba(0,0,0,0.5);z-index: 10001;padding: 5px;position: fixed;left: 0;top: 0;width: 40%;min-height: 100%;border-right: 2px solid #ff3b00;background: rgba(210, 222, 255, 0.9);overflow-y: auto;height: 100%; word-break: break-word;"><h3>Action debug</h3> <i style="position:absolute; right:10px; top:10px;font-size:1.5em;" onclick="$(this).parent().remove()" class="fas fa-times pointer"></i>'+response.responseText+'</div>');
  124. } else {
  125. if(response.readyState == 0 && error==null) return;
  126. if(error!=null){
  127. if(response.errorCode && response.errorCode=='401') window.location = 'action.php?action=logout';
  128. error(response);
  129. }else{
  130. $.message('error','Erreur indefinie, merci de contacter un administrateur',0);
  131. }
  132. }
  133. },
  134. xhr: function() {
  135. var xhr = new window.XMLHttpRequest();
  136. if(data.downloadResponse) xhr.responseType = 'blob';
  137. xhr.upload.addEventListener("progress", function(evt){
  138. if (evt.lengthComputable) {
  139. var percentComplete = (evt.loaded / evt.total) * 100;
  140. percentComplete = Math.round(percentComplete * 100) / 100;
  141. if(progress) progress(percentComplete,'upload');
  142. }
  143. }, false);
  144. xhr.addEventListener("progress", function(evt){
  145. if (evt.lengthComputable) {
  146. var percentComplete = evt.loaded / evt.total;
  147. if(progress) progress(percentComplete,'download');
  148. }
  149. }, false);
  150. xhr.addEventListener('readystatechange', function(e) {
  151. if(xhr.readyState == 4 && xhr.status == 200) {
  152. if(data.downloadResponse){
  153. var disposition = xhr.getResponseHeader('content-disposition');
  154. var matches = /"([^"]*)"/.exec(disposition);
  155. var filename = (matches != null && matches[1] ? matches[1] : 'file');
  156. var blob = new Blob([xhr.response], { type: xhr.response.type });
  157. var link = document.createElement('a');
  158. link.href = window.URL.createObjectURL(blob);
  159. link.download = filename;
  160. $('body').append(link);
  161. link.click();
  162. link.remove();
  163. window.URL.revokeObjectURL(link);
  164. }
  165. }
  166. });
  167. return xhr;
  168. }
  169. };
  170. if(!hasFile){
  171. request.data = data;
  172. }else{
  173. request.data = formData;
  174. request.processData = false;
  175. request.contentType = false;
  176. }
  177. $.ajax(request);
  178. }
  179. $.localhost = function(){
  180. return (document.location.hostname=='127.0.0.1' || document.location.hostname=='localhost');
  181. }
  182. $.hashData = function(name){
  183. var page = window.location.hash.substring(1);
  184. page += "&"+window.location.search.substring(1);
  185. data = {};
  186. if(page!='' && page!= null){
  187. options = page.split('&');
  188. var data = {};
  189. for(var key in options){
  190. infos = options[key].split('=');
  191. data[infos[0]] = infos[1];
  192. }
  193. }
  194. if(name == null) return data;
  195. if(typeof name === "object"){
  196. data = name;
  197. hashstring = '';
  198. for(var key in data)
  199. hashstring+= "&"+key+"="+data[key];
  200. hashstring = hashstring.substring(1);
  201. window.location.hash = hashstring;
  202. return;
  203. }
  204. return typeof data[name] == "undefined" ? '':data[name];
  205. }
  206. $.urlParam = function (name,value) {
  207. var parameters = window.location.href.match(/[\\?&]([^&#]*)=([^&#]*)/g);
  208. var data = {};
  209. for (var key in parameters) {
  210. var couple = parameters[key].substring(1, parameters[key].length).split('=');
  211. data[couple[0]] = couple[1];
  212. }
  213. if(name == null) return data;
  214. if (value == null)
  215. return data[name] ? data[name] : null;
  216. if (value != false) data[name] = value;
  217. var url = '?';
  218. for (var key in data) {
  219. if (value == false && key == name) continue;
  220. url += key + '=' + data[key]+'&';
  221. }
  222. window.history.pushState('', document.title, url.substring(0, url.length-1));
  223. }
  224. $.fn.extend({
  225. toJson : function(){
  226. return $.getForm(this);
  227. },
  228. getForm : function(){
  229. var o = {};
  230. var obj = $(this);
  231. for(var key in obj.data()){
  232. if(key!="action" && key != "id") continue;
  233. o[key] = obj.attr('data-'+key);
  234. }
  235. $('input,select,textarea',obj).each(function(i,element){
  236. if(element.id!=null && element.id!=""){
  237. if($(element).attr("type")=='checkbox' || $(element).attr("type")=='radio'){
  238. o[element.id] = ($(element).is(':checked')?1:0);
  239. }else{
  240. o[element.id] = $(element).val();
  241. }
  242. }
  243. });
  244. return o;
  245. },
  246. upload: function (options) {
  247. //var options = $.extend(defaults, options);
  248. return this.each(function () {
  249. var o = options;
  250. var droppedFiles = false;
  251. var div = $(this);
  252. var data = div.data();
  253. data.html =!div.attr('data-label') ? '': div.attr('data-label');
  254. data.label = data.html;
  255. div.html('');
  256. var o = $.extend(o, data);
  257. if(o.readonly == false){
  258. var form = $('<form class="box" method="post" action="' + o.action + '" enctype="multipart/form-data"><input type="file" name="'+(o.fileName?o.fileName:div.attr('id'))+'[]" multiple /></form>');
  259. div.append(form);
  260. var input = form.find('input[type="file"]');
  261. var zone = $('<div>' + o.label + '</div>');
  262. div.append(zone);
  263. //test if dnd is enabled n browser
  264. var div = document.createElement('div');
  265. var dragAndDropEnabled = (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && 'FormData' in window && 'FileReader' in window;
  266. //set elements styles
  267. input.attr('style', "width: 0.1px;height: 0.1px;opacity: 0;overflow: hidden; position: absolute;z-index: -1");
  268. zone.css('cursor', "pointer");
  269. //set events
  270. zone
  271. .on('click', function (e) {
  272. form.find('input[type="file"]').trigger('click');
  273. e.preventDefault();
  274. e.stopPropagation();
  275. })
  276. .on('drag dragstart dragend dragover dragenter dragleave drop', function (e) {
  277. e.preventDefault();
  278. e.stopPropagation();
  279. })
  280. .on('dragover dragenter', function () {
  281. if (o.hover) form.addClass(o.hover);
  282. })
  283. .on('dragleave dragend drop', function () {
  284. if (o.hover) form.removeClass(o.hover);
  285. })
  286. .on('drop', function (e) {
  287. droppedFiles = e.originalEvent.dataTransfer.files;
  288. form.trigger('submit');
  289. });
  290. input.on('change', function (e) {
  291. form.trigger('submit');
  292. });
  293. form.on('submit', function (e) {
  294. if (o.start) o.start();
  295. if (dragAndDropEnabled) {
  296. e.preventDefault();
  297. var ajaxData = new FormData();
  298. if (droppedFiles) {
  299. $.each(droppedFiles, function (i, file) {
  300. var ext = file.name.split('.');
  301. ext = ext.pop();
  302. if(o.allowed && $.inArray(ext.toLowerCase(),o.allowed.split(','))===-1){
  303. $.message('error','Extension fichier '+ext+' non permise (autorisé:'+o.allowed+')',0);
  304. return;
  305. }
  306. if(o.size && file.size > o.size){
  307. $.message('error','Taille fichier '+file.size+' octets trop grande (autorisé:'+o.size+' octets)',0);
  308. return;
  309. }
  310. ajaxData.append(input.attr('name'), file);
  311. });
  312. }else{
  313. ajaxData = new FormData(form.get(0));
  314. for(var key in $('input',form).get(0).files){
  315. var file = $('input',form).get(0).files[key];
  316. if(file.name==null || typeof file !='object') continue;
  317. var ext = file.name.split('.');
  318. ext = ext.pop();
  319. if(o.allowed && $.inArray(ext.toLowerCase(),o.allowed.split(','))===-1){
  320. $.message('error','Extension fichier '+ext+' non permise (autorisé:'+o.allowed+')',0);
  321. $('input',form).val();
  322. return;
  323. }
  324. if(o.size && file.size > o.size){
  325. $.message('error','Taille fichier '+file.size+' octets trop grande (autorisé:'+o.size+' octets)',0);
  326. $('input',form).val();
  327. return;
  328. }
  329. }
  330. }
  331. if (o.addData){
  332. var addionalData = o.addData();
  333. for(var k in addionalData){
  334. ajaxData.append(k, addionalData[k]);
  335. }
  336. }
  337. droppedFiles = null;
  338. $.ajax({
  339. url: form.attr('action'),
  340. type: form.attr('method'),
  341. data: ajaxData,
  342. dataType: 'json',
  343. cache: false,
  344. contentType: false,
  345. processData: false,
  346. complete: function (data) {
  347. if (o.complete) o.complete(data.responseJSON);
  348. },
  349. success: function (data) {
  350. if (o.success) o.success(data);
  351. },
  352. error: function (data) {
  353. if (o.error) o.error(data);
  354. }
  355. });
  356. } else {
  357. var iframeName = 'uploadiframe' + new Date().getTime();
  358. iframe = $('<iframe name="' + iframeName + '" style="display: none;"></iframe>');
  359. $('body').append(iframe);
  360. form.attr('target', iframeName);
  361. iframe.one('load', function () {
  362. var data = JSON.parse(iframe.contents().find('body').text());
  363. if (!data.success) alert(data.error);
  364. form.removeAttr('target');
  365. iframe.remove();
  366. if (o.complete) o.complete();
  367. });
  368. }
  369. });
  370. }
  371. });
  372. },
  373. clear: function (){
  374. return this.each(function() {
  375. var obj = $(this);
  376. obj.find('input,select,textarea').val('').prop('checked',false).prop('selected',false);
  377. });
  378. },
  379. addLine: function (rows){
  380. return this.each(function() {
  381. var obj = $(this);
  382. var model = null;
  383. var container = null;
  384. if(obj.prop("tagName") == 'UL'){
  385. container = obj;
  386. model = container.find('li:first-child');
  387. container.find('li:visible').remove();
  388. }else if(obj.prop("tagName") == 'TABLE'){
  389. container = obj.find('tbody');
  390. model = container.find('tr:first-child');
  391. container.find('tr:visible').remove();
  392. }else{
  393. container = obj;
  394. childName = container.children().get(0).nodeName;
  395. model = container.find(childName+':first-child');
  396. container.find(childName+':visible:not(.nofill)').remove();
  397. }
  398. var tpl = model.get(0).outerHTML;
  399. //fix jquery backslahes break
  400. tpl = tpl.replace(/{{##/g,'{{/').replace(/{{\/(.*)}}=""/g,'{{/$1}}');
  401. //fix images url not found on template
  402. tpl = tpl.replace(/(<img\s[^>]*\s)(data-src)/g,'$1src');
  403. for(var key in rows){
  404. var line = $(Mustache.render(tpl,rows[key]));
  405. container.append(line);
  406. line.removeClass('hidden');
  407. }
  408. });
  409. },
  410. fill: function (option,callback,progress){
  411. return this.each(function() {
  412. var obj = $(this);
  413. var model = null;
  414. var container = null;
  415. option = $.extend({
  416. differential : false,
  417. showing : function(item){
  418. //permet la personnalisation de l'apparition des lignes ( removeClass('hidden') par defaut)
  419. item.removeClass('hidden');
  420. }
  421. },option);
  422. var preloader = null;
  423. if(option.preloader){
  424. var preloader = $(option.preloader);
  425. preloader.css('position','absolute');
  426. preloader.css('left',(obj.offset().left+obj.width()/2)+'px');
  427. preloader.css('top',(obj.offset().top+30)+'px');
  428. $('body').append(preloader);
  429. }
  430. if(obj.prop("tagName") == 'UL'){
  431. container = obj;
  432. model = container.find('li:first-child');
  433. if(!option.export && !option.differential) container.children('li:visible').remove();
  434. } else if(obj.prop("tagName") == 'TABLE'){
  435. container = obj.find('tbody');
  436. model = container.find('tr:first-child');
  437. if(!option.export && !option.differential) container.children('tr:visible').remove();
  438. } else if(obj.prop("tagName") == "SELECT"){
  439. container = obj;
  440. model = container.find('option[value*="{{"]');
  441. if(model.length==0) model = $('<option class="hidden" value="{{value}}">{{label}}</option>');
  442. if(!option.export && !option.differential) container.find('option:not([value*="{{"])').remove();
  443. } else{
  444. container = obj;
  445. childName = container.children().get(0).nodeName;
  446. model = container.find(childName+':first-child');
  447. if(!option.export && !option.differential) container.find(childName+':visible:not(.nofill)').remove();
  448. }
  449. var tpl = model.get(0).outerHTML;
  450. //fix jquery backslashes break
  451. tpl = tpl.replace(/{{##/g,'{{/').replace(/{{\/(.*)}}=""/g,'{{/$1}}');
  452. //fix images url not found on template
  453. tpl = tpl.replace(/(<img\s[^>]*\s?)(data-src)/g,'$1src');
  454. var pagination = obj.nextAll('.pagination').length ? obj.nextAll('.pagination') : obj.parent().nextAll('.pagination');
  455. if(pagination.length!=0) option.page = $('li.active',pagination).attr('data-value');
  456. tpl = tpl.replace(/(data-style)/g, 'style');
  457. if(option.export)
  458. option.downloadResponse = true;
  459. //on clone l'objet option pour ne transmettre que des datas utiles
  460. data = $.extend({},option);
  461. delete data.showing;
  462. delete data.templating;
  463. $.action(data,function(r){
  464. //On ne gere la pagination et l'affichage tableau que si on est pas en mode export
  465. if(!option.export){
  466. var activeIds = [];
  467. for(var key in r.rows){
  468. var line;
  469. var data = r.rows[key];
  470. var lineTpl = tpl;
  471. if(option.templating) lineTpl = option.templating(data,line,tpl);
  472. if(!option.differential){
  473. line = $(Mustache.render(lineTpl,data));
  474. container.append(line);
  475. option.showing(line,key);
  476. }else{
  477. activeIds.push(data.id);
  478. var existing = $('> [data-id="'+data.id+'"]',container);
  479. //existe en data et pas dans le dom : ajout
  480. if(existing.length == 0){
  481. line = $(Mustache.render(lineTpl,data));
  482. line.attr('data-update-tag',data.updated);
  483. if(key==0){
  484. container.append(line);
  485. }else{
  486. var previousIndex = key-1;
  487. var previous = $('>[data-id]:visible',container).eq(previousIndex);
  488. previous.after(line);
  489. }
  490. option.showing(line,key);
  491. }else{
  492. //existe en data et dans le dom et pas de modification : on passe au suivant
  493. if(existing.attr('data-update-tag') == data.updated){
  494. continue;
  495. //existe en data et dans le dom mais a été modifié : on remplace
  496. }else{
  497. line = $(Mustache.render(lineTpl,data));
  498. line.attr('data-update-tag',data.updated);
  499. existing.after(line);
  500. existing.remove();
  501. option.showing(line,key);
  502. }
  503. }
  504. }
  505. }
  506. //suppression des élements dom qui ne sont plus en db
  507. if(option.differential){
  508. $('>[data-id]:visible',container).each(function(i,line){
  509. var line = $(line);
  510. if(activeIds.indexOf(line.attr('data-id')) == -1){
  511. console.log(line.attr('data-id'));
  512. console.log('suppression ',line);
  513. line.remove();
  514. }
  515. });
  516. }
  517. if(r.pagination){
  518. $('.page-item-previous,.page-item-next').remove();
  519. r.pagination.pages = Math.ceil(r.pagination.pages);
  520. var previewNumber = pagination.attr('data-range') != '' && pagination.attr('data-range') != null ? parseInt(pagination.attr('data-range')) : 5;
  521. previewNumber = previewNumber < 2 ? 2 : previewNumber;
  522. var template = pagination.find('li:not(:visible)');
  523. if(template.length>0 ){
  524. template = template.get(0).outerHTML;
  525. $('li:not(:eq(0))',pagination).remove();
  526. var current = parseInt(r.pagination.current);
  527. var previousPages = current-previewNumber;
  528. var nextPages = current+previewNumber;
  529. var dropDownTpl = '<div data-toggle="dropdown"><i class="fas fa-ellipsis-h pointer"></i></div><div class="dropdown-menu pagination-select">{{#choices}}<span class="dropdown-item">{{.}}</span>{{/choices}}</div>';
  530. for(i=0;i<r.pagination.pages;i++){
  531. var li = $(Mustache.render(template,{value:i,label:i+1}));
  532. if(
  533. (previousPages < i && i < nextPages)
  534. || i==0 || i==r.pagination.pages-1
  535. ){
  536. li.removeClass('hidden');
  537. if(i==current) li.addClass('active');
  538. }else{
  539. if(i==1 || i==r.pagination.pages-2){
  540. var dotli = li.clone()
  541. var start = i==1 ? 2: current+previewNumber+1;
  542. var end = i==1 ? (current+1)-previewNumber : r.pagination.pages-1;
  543. var choices = [];
  544. for(u=start; u<end+1;u++)
  545. choices.push(u);
  546. rightDropDown = $(Mustache.render(dropDownTpl,{choices:choices}));
  547. dotli.removeClass('hidden')
  548. .attr('title','Voir les pages '+(start)+' à '+(end))
  549. .removeAttr('onclick')
  550. .css('position','relative')
  551. .addClass('page-link').html(rightDropDown);
  552. pagination.append(dotli);
  553. }
  554. }
  555. pagination.append(li);
  556. }
  557. if(current!=0){
  558. var prev = $('<li class="page-item page-item-previous"><span class="page-link" ><span><i class="fas fa-angle-left"></i></span></span></li>');
  559. pagination.prepend(prev);
  560. prev.click(function(){
  561. pagination.find('li[data-value="'+(current-1)+'"]').trigger('click');
  562. });
  563. }
  564. if(current<r.pagination.pages-1){
  565. var next = $('<li class="page-item page-item-next"><span class="page-link" ><span><i class="fas fa-angle-right"></i></span></span></li>');
  566. pagination.append(next);
  567. next.click(function(){
  568. pagination.find('li[data-value="'+(current+1)+'"]').trigger('click');
  569. });
  570. }
  571. if(r.pagination.pages>1){
  572. pagination.find('.page-item:not(.hidden):first .page-link').css('border-radius','0.25rem 0 0 0.25rem');
  573. }else{
  574. pagination.find('.page-item:not(.hidden):first .page-link').css('border-radius','0.25rem 0.25rem 0.25rem 0.25rem');
  575. }
  576. $('.pagination-select span',pagination).click(function(){
  577. var selectedPage = (parseInt($(this).text())-1);
  578. pagination.find('li[data-value="'+selectedPage+'"]').trigger('click');
  579. });
  580. }
  581. }
  582. }
  583. if(preloader) preloader.remove();
  584. if(callback!=null)callback(r);
  585. },null,function(percent,type){
  586. if(progress) progress(percent,type);
  587. });
  588. });
  589. },
  590. filters: function (values){
  591. var obj = $(this);
  592. var box = obj.next('.filter-box');
  593. if(values){
  594. if(values.keyword && values.keyword!='')
  595. $('.filter-keyword',box).val(values.keyword);
  596. for(var key in values.advanced){
  597. var filter = values.advanced[key];
  598. filter_add($('.filter-add-button',box),filter);
  599. }
  600. return;
  601. }
  602. var formData = {
  603. keyword : $('.filter-keyword',box).val()
  604. };
  605. formData.advanced = [], formData.multiple = [], formData.custom = {};
  606. $('.filterRow:visible',box).each(function(i,row){
  607. var row = $(row);
  608. if(row.find('.filter-column').val()=='') return;
  609. var filter = {
  610. join : row.find('.filter-join').val(),
  611. column : row.find('.filter-column').val(),
  612. type : row.find('.filter-column option:selected').attr('data-filter-type'),
  613. operator : {},
  614. value : {}
  615. }
  616. if ($('.filter-value-block',row).length > 1) {
  617. $('.filter-value-block',row).each(function(j,block){
  618. var block = $(block);
  619. filter.operator[j] = block.find('.filter-operator').val();
  620. filter.value[j] = block.find('.filter-value').last().val();
  621. });
  622. formData.multiple.push(filter);
  623. } else {
  624. filter.operator = row.find('.filter-operator').val();
  625. values = row.find('.filter-value');
  626. if(values.length > 1){
  627. filter.value = [];
  628. for(var j=0; j<values.length; ++j){
  629. filter.value.push(values.eq(j).val());
  630. }
  631. values.eq(j).attr('data-custom') == 'true' ? formData.custom[filter.column] = filter : formData.advanced.push(filter);
  632. } else {
  633. filter.value = values.val();
  634. values.last().attr('data-custom') == 'true' ? formData.custom[filter.column] = filter : formData.advanced.push(filter);
  635. }
  636. }
  637. });
  638. return formData;
  639. },
  640. enter: function (option){
  641. return this.each(function() {
  642. var obj = $(this);
  643. obj.keydown(function(event){
  644. if(event.keyCode == 13){
  645. option();
  646. return false;
  647. }
  648. });
  649. });
  650. },
  651. sortable_table: function (option){
  652. if(option=='get'){
  653. var obj = $(this);
  654. var response = {};
  655. obj.find('thead th[data-sortable]').each(function(i,th){
  656. var th = $(th);
  657. if(th.attr('data-sort') && th.attr('data-sort')!=""){
  658. response = {
  659. sort : th.attr('data-sort'),
  660. sortable : th.attr('data-sortable')
  661. };
  662. }
  663. });
  664. return response;
  665. }
  666. return this.each(function() {
  667. var obj = $(this);
  668. obj.find('thead th[data-sortable]').click(function(){
  669. var th = $(this);
  670. var data = th.data();
  671. if(!data.sort || data.sort==''){
  672. data.sort = 'asc'
  673. }else if(data.sort == 'asc'){
  674. data.sort ='desc'
  675. }else{
  676. data.sort = '';
  677. }
  678. obj.find('thead th').removeClass('sort-asc').removeClass('sort-desc').removeAttr('data-sort');
  679. if(data.sort!='') th.addClass('sort-'+data.sort);
  680. th.attr('data-sort',data.sort);
  681. if(option.onSort) option.onSort();
  682. });
  683. });
  684. },
  685. autocomplete: function(o){
  686. return this.each(function() {
  687. var obj = $(this);
  688. if(o == 'off') return obj.typeahead('destroy');
  689. obj.attr('autocomplete','off');
  690. var option = obj.data();
  691. option = $.extend(option,o);
  692. obj.typeahead({
  693. items: (o.items) ? o.items : 5,
  694. minLength: o.suggest ? 0 : (o.minLength ? o.minLength : 2) ,
  695. fitToElement: false,
  696. autoSelect : false,
  697. selectOnBlur : false,
  698. displayText : function(item){
  699. return (o.skin) ? o.skin(item) : item.name || item;
  700. },
  701. source: function(keyword, response){
  702. if(o.onKeypress) o.onKeypress(obj);
  703. if(o.dynamicData) o.data = $.extend(o.data,o.dynamicData());
  704. $.action({
  705. action: option.action,
  706. keyword: obj.val(),
  707. data: o.data
  708. },function(r){
  709. if(r.rows != null)
  710. response(r.rows);
  711. });
  712. },
  713. highlighter: function(item){
  714. if(o.highlight) {
  715. return o.highlight(item)
  716. }
  717. else {
  718. var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
  719. return item.replace(new RegExp('('+query+')', 'ig'), function($1, match){
  720. return '<strong>'+match+'</strong>';
  721. });
  722. }
  723. },
  724. matcher: function(r){
  725. if(obj.val() == r.name)
  726. if(o.onClick)
  727. o.onClick(r,obj);
  728. return '<div>'+r.name+'</div>';
  729. },
  730. afterSelect: function(item) {
  731. obj.data('selected',true);
  732. if(o.onClick) o.onClick(item,obj);
  733. obj.trigger("change");
  734. }
  735. }).blur(function(){
  736. if(o.onBlur) o.onBlur(obj);
  737. });
  738. if(o.suggest){
  739. obj.on("click", function () {
  740. ev = $.Event("keydown");
  741. ev.keyCode = ev.which = 40;
  742. $(this).trigger(ev);
  743. return true
  744. });
  745. }
  746. obj.data('typeahead').next = function (event) {
  747. var active = this.$menu.find('.active').removeClass('active');
  748. var next = active.next();
  749. if (!next.length) {
  750. next = $(this.$menu.find($(this.options.item || this.theme.item).prop('tagName'))[0]);
  751. }
  752. while (next.hasClass('divider') || next.hasClass('dropdown-header')) {
  753. next = next.next();
  754. }
  755. next.addClass('active');
  756. var newVal = this.updater(next.data('value'));
  757. this.$element.val(newVal.name || newVal);
  758. };
  759. obj.data('typeahead').prev = function (event) {
  760. var active = this.$menu.find('.active').removeClass('active');
  761. var prev = active.prev();
  762. if (!prev.length){
  763. prev = this.$menu.find($(this.options.item || this.theme.item).prop('tagName')).last();
  764. }
  765. while (prev.hasClass('divider') || prev.hasClass('dropdown-header')) {
  766. prev = prev.prev();
  767. }
  768. prev.addClass('active');
  769. var newVal = this.updater(prev.data('value'));
  770. if (this.changeInputOnMove) this.$element.val(newVal.name || newVal);
  771. };
  772. });
  773. },
  774. location: function (options){
  775. return this.each(function() {
  776. try{
  777. //var options = $.extend({},options);
  778. var obj = $(this);
  779. obj.attr('autocomplete','off');
  780. var data = $('#algolia').data();
  781. var placesAutocomplete = places({
  782. appId: data.api,
  783. apiKey: data.key,
  784. container: obj.get(0)
  785. });
  786. placesAutocomplete.on('change', function(e) {
  787. var m = /[0-9]*/m.exec(e.suggestion.name)
  788. var infos = {
  789. latitude: e.suggestion.latlng.lat,
  790. longitude : e.suggestion.lng,
  791. types : e.suggestion.type,
  792. number : '',
  793. street : e.suggestion.name,
  794. city : e.suggestion.city,
  795. country : e.suggestion.country,
  796. code : e.suggestion.postcode,
  797. picture : '',
  798. map : ''
  799. };
  800. if(m && m.length > 0 ) infos.number = m[0] ;
  801. infos.address = (infos.street && infos.street.length && infos.number && infos.number.length) ? infos.number+' '+infos.street : (infos.street ? infos.street : '');
  802. if(options.select) options.select(infos);
  803. });
  804. }catch(e){
  805. console.warn('Composant Location en erreur, désactivé :'+e);
  806. }
  807. });
  808. },
  809. date: function (options){
  810. return this.each(function() {
  811. var obj = $(this);
  812. obj.on('paste', function(e){
  813. is_valid_date(e.originalEvent.clipboardData.getData('Text')) ? obj.val("") : e.preventDefault();
  814. });
  815. obj.datepicker({
  816. dateFormat: options.dateFormat,
  817. dayNames: ["Dimanche", "Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi", "Samedi"],
  818. dayNamesMin: ["Di", "Lu", "Ma", "Me", "Je", "Ve", "Sa"],
  819. dayNamesShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"],
  820. monthNames: ["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Aout","Septembre","Octobre","Novembre","Décembre"],
  821. monthNamesShort: ["Jan","Fév","Mars","Avr","Mai","Juin","Juil","Aout","Sept","Oct","Nov","Déc"],
  822. firstDay: 1,
  823. minDate: options.beginDate,
  824. maxDate: options.endDate,
  825. changeMonth: true,
  826. yearRange: "-30:+30",
  827. changeYear: true,
  828. onSelect: function(dateText, inst) {
  829. obj.trigger("blur");
  830. }
  831. }).keypress(function(event){
  832. var length = obj.val().length;
  833. if(length == 2 || length == 5) obj.val(obj.val()+'/');
  834. }).blur(function(event){
  835. obj.removeClass('border border-danger');
  836. if(obj.val()=='') return;
  837. var segments = obj.val().split('/');
  838. if(segments.length!=3) return;
  839. if(segments[0] > 31 || segments[1] > 12) obj.addClass('border border-danger');
  840. }).attr('maxlength','10');
  841. obj.attr('placeholder',options.placeholder);
  842. obj.attr('pattern',"^(\\d{2}(?:\\d{2})?)\/(\d{2})\/(\\d{2}(?:\\d{2})?)$");
  843. obj.attr('title','Format '+options.dateFormat);
  844. });
  845. },
  846. hour: function (options){
  847. return this.each(function() {
  848. var obj = $(this);
  849. obj.on('paste', function(e){
  850. is_valid_hour(e.originalEvent.clipboardData.getData('Text')) ? obj.val("") : e.preventDefault();
  851. });
  852. obj.timepicker({
  853. scrollDefault: 'now',
  854. timeFormat: options.timeFormat,
  855. step: options.step,
  856. onSelect: function(timeText, inst) {
  857. obj.trigger("blur");
  858. }
  859. }).keypress(function(e) {
  860. if(!e.key.match(/[0-9:]/)) e.preventDefault();
  861. if(obj.val().length == 2) obj.val(obj.val()+':');
  862. }).blur(function(event){
  863. obj.removeClass('border border-danger')
  864. if(obj.val()=='') return;
  865. var segments = obj.val().split(':');
  866. if(segments.length!=2) return;
  867. if(segments[0] > 23 || segments[1] > 59) obj.addClass('border border-danger');
  868. }).attr('maxlength','5');
  869. obj.attr("placeholder",options.placeholder);
  870. obj.attr('pattern',"(\\d{2})\\:(\\d{2})");
  871. obj.attr('title',"Format hh:mm");
  872. });
  873. },
  874. raiseNumber: function(from,to) {
  875. return this.each(function(){
  876. var obj = $(this);
  877. obj.text(from);
  878. var interval = 800 / (to - from);
  879. var interval = setInterval(function(){
  880. var number = parseFloat(obj.text());
  881. if(number>=to) {
  882. clearInterval(interval);
  883. return;
  884. }
  885. obj.text(number+1);
  886. },interval);
  887. });
  888. }
  889. });