main.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. // requires jquery 1.7+
  2. // JS s'execute: Retire l'avertissement 'Javascript est requis' (de fait, on sait que JS est actif...)
  3. document.body.classList.remove("nojs");
  4. //### Helpers handlebars personnalisés
  5. Handlebars.registerHelper('lower', function (options) {
  6. return options.fn(this).toLowerCase();
  7. });
  8. Handlebars.registerHelper('repuri', function (find, replace, options) {
  9. return encodeURI(options.fn(this).replace(find, replace).toString());
  10. });
  11. Handlebars.registerHelper('todate', function (options) {
  12. var d = options.fn(this);
  13. var dt = new Date(Number.parseInt(d) * 1);
  14. return dt.toLocaleString();
  15. });
  16. Handlebars.registerHelper('timestamp', function (options) {
  17. return Number.parseInt(options.fn(this));
  18. });
  19. Handlebars.registerHelper('if_eq', function (a, opts) {
  20. var b = localStorage.hasOwnProperty("contact") ? localStorage.getItem("contact") : "";
  21. if (a === b) // Or === depending on your needs
  22. return opts.fn(this);
  23. else
  24. return opts.inverse(this);
  25. });
  26. //### Initialisation
  27. // ************** CONFIGURATION *****************
  28. // Nom et version de la base de données locale à créer/utiliser
  29. var db_name = "ModelePWA"
  30. var db_version = "3"
  31. // Si deleteOnSuccess est vrai, les données synchronisées seront supprimées de la base locale.
  32. var deleteOnSync = true;
  33. // Les stores de la liste doNotSync ne seront pas synchronisés.
  34. var doNotSync = ["params"];
  35. var postUrl = "/api/modelepwa";
  36. // **********************************************
  37. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
  38. var request;
  39. // Installe le service worker
  40. if ('serviceWorker' in navigator) {
  41. console.log("[ServiceWorker] Installe");
  42. navigator.serviceWorker.register('../sw.js');
  43. }
  44. var sectionId;
  45. var section;
  46. var objId;
  47. var submitHandler;
  48. var deleteHandler;
  49. var editHandler;
  50. // Charge la page en fonction de l'url actuelle
  51. var load = function () {
  52. // Reinitialise l'affichage des sections
  53. $("#sync").hide();
  54. $("#main").empty();
  55. $("#main").show();
  56. // Parse l'url actuelle
  57. var base = window.location.hash.split('?')[0];
  58. sectionId = base.length > 0 ? base : "#index";
  59. section = $("body").find(sectionId);
  60. var qry = {};
  61. var qrystr = window.location.hash.split('?')[1];
  62. if (qrystr) {
  63. var definitions = qrystr.split('&');
  64. definitions.forEach(function (val, key) {
  65. var parts = val.split('=', 2);
  66. qry[parts[0]] = parts[1];
  67. });
  68. }
  69. // Met à jour le contenu de #main avec la section demandée dans l'url/
  70. // Si l'attribut 'model' existe pour cette section, charge les données depuis la localDb
  71. // et compile la section avec handlebars.
  72. if ($(section).attr("model")) {
  73. var model = $(section).attr("model");
  74. var template = Handlebars.compile(section.html());
  75. // Charge la base de données, et le stockage courant
  76. request = indexedDB.open(db_name, db_version);
  77. var db;
  78. var txs;
  79. var store;
  80. // Cree les stockages necessaires si ceux ci sont manquants
  81. request.onupgradeneeded = function () {
  82. var db = request.result;
  83. db.createObjectStore(model, { keyPath: "guid" });
  84. console.log("[DB] Cree '" + model + "'");
  85. };
  86. // Si l'accès a la db s'est bien passé:
  87. request.onsuccess = function () {
  88. var data;
  89. db = request.result;
  90. txs = db.transaction(model, "readonly");
  91. store = txs.objectStore(model);
  92. // Si un id specifique a été demandé, on charge specifiquement cet objet.
  93. // Sinon: on les charge tous en memoire.
  94. if (qry["id"]) {
  95. store.get(qry["id"]).onsuccess = function (event) {
  96. data = { data: event.target.result };
  97. $("#main").html(template(data));
  98. populateForm(data['data']);
  99. }
  100. }
  101. else {
  102. store.getAll().onsuccess = function (event) {
  103. data = { data: event.target.result };
  104. $("#main").html(template(data));
  105. };
  106. }
  107. };
  108. request.onerror = function () {
  109. console.log("Error while loading the db '" + model + "'");
  110. $("#main").html(template({}));
  111. return;
  112. };
  113. // (Re)définit la fonction d'interception de la soumission de formulaires
  114. submitHandler = function (event) {
  115. var form = $("#main").find("form")[0];
  116. // Stop the form from submitting since we’re handling that with AJAX.
  117. event.preventDefault();
  118. // Call our function to get the form data.
  119. var data = formToJSON(form.elements);
  120. data.guid = createGuid();
  121. txs = db.transaction(model, "readwrite");
  122. store = txs.objectStore(model);
  123. store.put(data);
  124. };
  125. // (Re)définit la fonction de suppression des lignes de l'index
  126. deleteHandler = function(event) {
  127. var del = $(this);
  128. if (confirm("Supprimer la selection?") == true) {
  129. $(del).prop("disabled", true);
  130. $(".ui-selected").each(function () {
  131. var elt = $(this);
  132. var id = $(elt).data("id");
  133. txs = db.transaction(model, "readwrite");
  134. store = txs.objectStore(model);
  135. store.delete(id).onsuccess = function (evt) {
  136. $(elt).remove();
  137. $(".del").prop('disabled', false);
  138. };
  139. });
  140. }
  141. };
  142. // (Re)définit la fonction de suppression d'edition
  143. editHandler = function(event) {
  144. var edit = $(this);
  145. var id = $(".ui-selected:first").data("id")
  146. txs = db.transaction(model, "readonly");
  147. store = txs.objectStore(model);
  148. var obj = store.get(id);
  149. obj.onsuccess = function (event) {
  150. window.location = "/#activites?id=" + id;
  151. };
  152. };
  153. }
  154. else {
  155. // Pas de modele, on charge simplement le html de la section.
  156. $("#main").html(section.html());
  157. }
  158. }
  159. load();
  160. // Recharge dynamiquement le contenu HTML à chaque changement d'url
  161. $(window).on('hashchange', function () {
  162. load();
  163. });
  164. // Met a jour le contenu des champs d'un formulaire
  165. // Le binbding se fait via l'id du champs
  166. var populateForm = function (data) {
  167. if ($("form").length) {
  168. $("input, select, textarea").each(function () {
  169. var input = $(this);
  170. var fieldName = input.attr('id');
  171. input.val(data[fieldName]);
  172. });
  173. }
  174. }
  175. // ###########################
  176. // ### Interactions
  177. // Intercepte la soumission de formulaires
  178. $("#main").on("submit", "form", function (event) {
  179. submitHandler(event);
  180. window.location = "/#index";
  181. });
  182. // Gere le clic sur un bouton Supprimer
  183. $("#main").on("click", ".del", function (event) {
  184. deleteHandler(event);
  185. });
  186. // Gere le clic sur un bouton Editer
  187. $("#main").on("click", ".edit", function (event) {
  188. editHandler(event);
  189. });
  190. // Gere le clic sur le bouton de menu pour afficher ou masquer la sidebar
  191. $('.bt-menu').on('click', 'svg', function () {
  192. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  193. });
  194. $(document).on('click', '.sidebar', function () {
  195. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  196. });
  197. // Affiche ou masque le bouton de sync selon que le poste est en ligne ou non
  198. if (navigator.onLine) {
  199. $(".start-sync").removeAttr("disabled");
  200. }
  201. else {
  202. if (!$(".start-sync").is(":disabled"))
  203. {
  204. $(".start-sync").attr("disabled")
  205. }
  206. }
  207. // Affiche ou masque, et gere le clic sur le bouton de retour au haut de page.
  208. window.onscroll = function (ev) {
  209. document.getElementById("back-top").className =(window.pageYOffset > 100) ? "": "hidden";
  210. };
  211. $('#back-top').on('click', function () {
  212. $('html, body').animate({ scrollTop: 0 }, 200);
  213. });
  214. // Rend les lignes des tables .selectable selectionnables
  215. mo = new MutationObserver(function (mutations, observer) {
  216. $(".selectable > tbody").bind("mousedown", function (e) {
  217. e.metaKey = true;
  218. }).selectable({
  219. filter: "tr",
  220. stop: function () {
  221. $(".del").prop('disabled', ($(".ui-selected").length == 0));
  222. $(".edit").prop('disabled', ($(".ui-selected").length != 1));
  223. },
  224. });
  225. })
  226. mo.observe(document.querySelector('#main'), { childList: true });
  227. // ### Synchronisation des données
  228. $(".start-sync").on("click", function () {
  229. // (!) voir en debut de fichier pour la configuration de la synchro (cf. les variables doNotSync et deleteOnSync)
  230. // Affiche la page de synchro
  231. $("#main").hide();
  232. $("#sync").show();
  233. // Verifie l'acces à la LocalDb
  234. if (!request) {
  235. request = indexedDB.open(db_name, db_version);
  236. request.onerror = function () {
  237. console.log("Error while accessing the db");
  238. $("#sync").find(".status").html("<p>Erreur de synchronisation: impossible d'accéder à la base de données locale.</p>");
  239. return;
  240. };
  241. }
  242. var db = request.result;
  243. $("#sync").find(".status").html("<p>Synchronisation en cours, veuillez patienter...</p>");
  244. var model;
  245. // Parcourt les differents stores
  246. for (var i = 0; i < db.objectStoreNames.length; i++) {
  247. model = db.objectStoreNames[i];
  248. if (doNotSync.indexOf(model) >= 0) {
  249. console.log("Ignored: " + model);
  250. continue;
  251. }
  252. console.log("Sync: " + model);
  253. var txs = db.transaction(model, "readonly");
  254. var stores = txs.objectStore(model);
  255. stores.openCursor().onsuccess = function (event) {
  256. var cursor = event.target.result;
  257. if (cursor) {
  258. cursor.value.model = model;
  259. var id = cursor.value.guid;
  260. var posting = $.post(postUrl, { data: JSON.stringify(cursor.value) });
  261. // Put the results in a div
  262. posting.done(function (data) {
  263. if (deleteOnSync & data) {
  264. var tx = db.transaction(model, "readwrite");
  265. var store = tx.objectStore(model);
  266. store.delete(id).onsuccess = function (evt) {
  267. };
  268. }
  269. });
  270. cursor.continue();
  271. }
  272. };
  273. stores.openCursor().onerror = function (event) {
  274. console.log(event);
  275. }
  276. }
  277. console.log("Synchro ok");
  278. $("#sync").find(".end-sync").show();
  279. $("#sync").find(".status").html("<p>Synchronisation terminée.</p>");
  280. });
  281. $(".end-sync").click(function () {
  282. load();
  283. });
  284. //###### TOOLBOX ######
  285. function createGuid() {
  286. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  287. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  288. )
  289. }
  290. function getLocation() {
  291. try {
  292. if (navigator.geolocation) {
  293. navigator.geolocation.getCurrentPosition(showPosition);
  294. } else {
  295. console.log("Geolocation is not supported by this browser.");
  296. return 0;
  297. }
  298. }
  299. catch (e) {
  300. console.log("Geolocation: error");
  301. }
  302. }
  303. function showPosition(position) {
  304. $("input[name='coordinates']").val(position.coords.latitude + "," + position.coords.longitude);
  305. console.log(position.coords);
  306. }
  307. // ### Serialization
  308. /**
  309. * Checks that an element has a non-empty `name` and `value` property.
  310. * @param {Element} element the element to check
  311. * @return {Bool} true if the element is an input, false if not
  312. */
  313. var isValidElement = function isValidElement(element) {
  314. return element.name && element.value;
  315. };
  316. /**
  317. * Checks if an element’s value can be saved (e.g. not an unselected checkbox).
  318. * @param {Element} element the element to check
  319. * @return {Boolean} true if the value should be added, false if not
  320. */
  321. var isValidValue = function isValidValue(element) {
  322. return !['checkbox', 'radio'].includes(element.type) || element.checked;
  323. };
  324. /**
  325. * Checks if an input is a checkbox, because checkboxes allow multiple values.
  326. * @param {Element} element the element to check
  327. * @return {Boolean} true if the element is a checkbox, false if not
  328. */
  329. var isCheckbox = function isCheckbox(element) {
  330. return element.type === 'checkbox';
  331. };
  332. //var isHidden = function isHidden(element) {
  333. // return element.type === 'hidden';
  334. //};
  335. /**
  336. * Checks if an input is a `select` with the `multiple` attribute.
  337. * @param {Element} element the element to check
  338. * @return {Boolean} true if the element is a multiselect, false if not
  339. */
  340. var isMultiSelect = function isMultiSelect(element) {
  341. return element.options && element.multiple;
  342. };
  343. /**
  344. * Retrieves the selected options from a multi-select as an array.
  345. * @param {HTMLOptionsCollection} options the options for the select
  346. * @return {Array} an array of selected option values
  347. */
  348. var getSelectValues = function getSelectValues(options) {
  349. return [].reduce.call(options, function (values, option) {
  350. return option.selected ? values.concat(option.value) : values;
  351. }, []);
  352. };
  353. /**
  354. * A more verbose implementation of `formToJSON()` to explain how it works.
  355. *
  356. * NOTE: This function is unused, and is only here for the purpose of explaining how
  357. * reducing form elements works.
  358. *
  359. * @param {HTMLFormControlsCollection} elements the form elements
  360. * @return {Object} form data as an object literal
  361. */
  362. var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {
  363. // This is the function that is called on each element of the array.
  364. var reducerFunction = function reducerFunction(data, element) {
  365. // Add the current field to the object.
  366. data[element.name] = element.value;
  367. // For the demo only: show each step in the reducer’s progress.
  368. console.log(JSON.stringify(data));
  369. return data;
  370. };
  371. // This is used as the initial value of `data` in `reducerFunction()`.
  372. var reducerInitialValue = {};
  373. // To help visualize what happens, log the inital value, which we know is `{}`.
  374. console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));
  375. // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  376. var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);
  377. // The result is then returned for use elsewhere.
  378. return formData;
  379. };
  380. /**
  381. * Retrieves input data from a form and returns it as a JSON object.
  382. * @param {HTMLFormControlsCollection} elements the form elements
  383. * @return {Object} form data as an object literal
  384. */
  385. var formToJSON = function formToJSON(elements) {
  386. return [].reduce.call(elements, function (data, element) {
  387. // Make sure the element has the required properties and should be added.
  388. if (isValidElement(element) && isValidValue(element)) {
  389. /*
  390. * Some fields allow for more than one value, so we need to check if this
  391. * is one of those fields and, if so, store the values as an array.
  392. */
  393. if (isCheckbox(element)) {
  394. data[element.name] = (data[element.name] || []).concat(element.value);
  395. } else if (isMultiSelect(element)) {
  396. data[element.name] = getSelectValues(element);
  397. } else {
  398. data[element.name] = element.value;
  399. }
  400. }
  401. return data;
  402. }, {});
  403. };