mobiparc.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  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. var db_name = "MobiParc"
  28. var db_version = "3"
  29. var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
  30. var request;
  31. // Installe le service worker
  32. if ('serviceWorker' in navigator) {
  33. console.log("[ServiceWorker] Installe");
  34. navigator.serviceWorker.register('../sw.js');
  35. }
  36. var sectionId;
  37. var section;
  38. var load = function () {
  39. // Vide la section main
  40. $("#main").empty();
  41. // Page en cours
  42. sectionId = (window.location.hash.slice(1).length > 0 ? window.location.hash.slice(1) : "index");
  43. section = $("body").find('#' + sectionId);
  44. // compile la section avec handlebars
  45. if ($(section).attr("model")) {
  46. var model = $(section).attr("model");
  47. var template = Handlebars.compile(section.html());
  48. // Charge la base de données, et le stockage courant
  49. //var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
  50. request = indexedDB.open(db_name, db_version);
  51. var db;
  52. var txs;
  53. var store;
  54. // Cree les stockages necessaires si ceux ci sont manquants
  55. request.onupgradeneeded = function () {
  56. var db = request.result;
  57. db.createObjectStore(model, { keyPath: "tstamp" });
  58. console.log("[DB] Cree '" + model + "'");
  59. };
  60. request.onsuccess = function () {
  61. db = request.result;
  62. txs = db.transaction(model, "readonly");
  63. store = txs.objectStore(model);
  64. store.getAll().onsuccess = function (event) {
  65. var data = { data: event.target.result };
  66. $("#main").html(template(data));
  67. };
  68. };
  69. request.onerror = function () {
  70. console.log("Error while loading the db '" + model + "'");
  71. $("#main").html(template({}));
  72. return;
  73. };
  74. // Intercepte la soumision de formulaires
  75. $("#main").on("submit", ".data-form", function (event) {
  76. console.log("handle submit");
  77. var form = $("#main").find(".data-form")[0];
  78. // Stop the form from submitting since we’re handling that with AJAX.
  79. event.preventDefault();
  80. // Call our function to get the form data.
  81. var data = formToJSON(form.elements);
  82. // Demo only: print the form data onscreen as a formatted JSON object.
  83. var dataContainer = document.getElementsByClassName('results-display')[0];
  84. // Use `JSON.stringify()` to make the output valid, human-readable JSON.
  85. dataContainer.textContent = JSON.stringify(data, null, " ");
  86. if ($(form).hasClass("activite")) {
  87. data.tstamp = Date.now();
  88. data.user = localStorage.hasOwnProperty("params") ? JSON.parse(localStorage.getItem("params")).user : "(unknown)";
  89. txs = db.transaction(model, "readwrite");
  90. store = txs.objectStore(model);
  91. store.put(data);
  92. store.getAll().onsuccess = function (event) {
  93. $("#main").empty();
  94. var data = { data: event.target.result };
  95. var template = Handlebars.compile(section.html());
  96. $("#main").html(template(data));
  97. };
  98. }
  99. });
  100. // Gere le clic sur un bouton supprimer
  101. $("body").on("click", ".del", function (event) {
  102. var del = $(this);
  103. if (confirm("Supprimer la selection!") == true) {
  104. $(del).prop("disabled", true);
  105. $(".ui-selected").each(function () {
  106. var elt = $(this);
  107. var id = $(elt).data("id");
  108. //var datatype = $(elt).data("type");
  109. txs = db.transaction(model, "readwrite");
  110. store = txs.objectStore(model);
  111. store.delete(id).onsuccess = function (evt) {
  112. $(elt).remove();
  113. };
  114. });
  115. }
  116. });
  117. }
  118. else {
  119. $("#main").html($(section).html());
  120. }
  121. }
  122. load();
  123. // Recharge dynamiquement le contenu HTML à chaque changement d'url
  124. $(window).on('hashchange', function () {
  125. console.log("Trigger: hashchange");
  126. load();
  127. });
  128. //######### MAIN ###############
  129. // ### Interactions
  130. // Affiche ou masque la sidebar
  131. $('.bt-menu').on('click', 'svg', function () {
  132. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  133. });
  134. $(document).on('click', '.sidebar', function () {
  135. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  136. });
  137. // Affiche ou masque le bouton de sync
  138. if (navigator.onLine) {
  139. $(".data-sync").removeAttr("disabled");
  140. }
  141. else {
  142. if (!$(".data-sync").is(":disabled"))
  143. {
  144. $(".data-sync").attr("disabled")
  145. }
  146. }
  147. /* retour haut de page*/
  148. window.onscroll = function (ev) {
  149. document.getElementById("cRetour").className = (window.pageYOffset > 100) ? "cVisible" : "cInvisible";
  150. };
  151. $('#cRetour').on('click', function () {
  152. $('html, body').animate({ scrollTop: 0 }, 200);
  153. });
  154. // Gere l'affichage des classes modales
  155. $(".modal-open, .modal-background, .modal-close").click(function () {
  156. $(".modal-content,.modal-background").toggleClass("active");
  157. if ($(this).hasClass("modal-close")) location.reload();
  158. });
  159. // Rend selectionables les lignes des tables (.selectable)
  160. $("#main").selectable({
  161. filter: ".selectable tr",
  162. stop: function () {
  163. $(".del").removeAttr("disabled");
  164. }
  165. });
  166. // ### Synchronisation des données
  167. $(".data-sync").on("click", function () {
  168. if (!request) {
  169. request = indexedDB.open(db_name, db_version);
  170. request.onerror = function () {
  171. console.log("Error while accessing the db");
  172. alert("Erreur: impossible d'accéder à la base de données locale.");
  173. return;
  174. };
  175. }
  176. var db = request.result;
  177. var txs = db.transaction("activites", "readonly");
  178. var stores = txs.objectStore("activites");
  179. console.log("post all");
  180. stores.openCursor().onsuccess = function (event) {
  181. var cursor = event.target.result;
  182. if (cursor) {
  183. cursor.value.model = "activites";
  184. var id = cursor.value.tstamp;
  185. var posting = $.post("/api/mobiparc", { data: JSON.stringify(cursor.value) });
  186. // Put the results in a div
  187. posting.done(function (data) {
  188. if (data == true) {
  189. var tx = db.transaction("activites", "readwrite");
  190. var store = tx.objectStore("activites");
  191. store.delete(id).onsuccess = function (evt) {
  192. $('.sync-result').append("Sync ok activite : " + id + "<br>");
  193. };
  194. }
  195. });
  196. cursor.continue();
  197. }
  198. else {
  199. console.log("end activite");
  200. }
  201. };
  202. })
  203. //###### TOOLBOX ######
  204. function createGuid() {
  205. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  206. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  207. )
  208. }
  209. function getLocation() {
  210. try {
  211. if (navigator.geolocation) {
  212. navigator.geolocation.getCurrentPosition(showPosition);
  213. } else {
  214. console.log("Geolocation is not supported by this browser.");
  215. return 0;
  216. }
  217. }
  218. catch (e) {
  219. console.log("Geolocation: error");
  220. }
  221. }
  222. function showPosition(position) {
  223. $("input[name='coordinates']").val(position.coords.latitude + "," + position.coords.longitude);
  224. console.log(position.coords);
  225. }
  226. // ### Serialization
  227. /**
  228. * Checks that an element has a non-empty `name` and `value` property.
  229. * @param {Element} element the element to check
  230. * @return {Bool} true if the element is an input, false if not
  231. */
  232. var isValidElement = function isValidElement(element) {
  233. return element.name && element.value;
  234. };
  235. /**
  236. * Checks if an element’s value can be saved (e.g. not an unselected checkbox).
  237. * @param {Element} element the element to check
  238. * @return {Boolean} true if the value should be added, false if not
  239. */
  240. var isValidValue = function isValidValue(element) {
  241. return !['checkbox', 'radio'].includes(element.type) || element.checked;
  242. };
  243. /**
  244. * Checks if an input is a checkbox, because checkboxes allow multiple values.
  245. * @param {Element} element the element to check
  246. * @return {Boolean} true if the element is a checkbox, false if not
  247. */
  248. var isCheckbox = function isCheckbox(element) {
  249. return element.type === 'checkbox';
  250. };
  251. //var isHidden = function isHidden(element) {
  252. // return element.type === 'hidden';
  253. //};
  254. /**
  255. * Checks if an input is a `select` with the `multiple` attribute.
  256. * @param {Element} element the element to check
  257. * @return {Boolean} true if the element is a multiselect, false if not
  258. */
  259. var isMultiSelect = function isMultiSelect(element) {
  260. return element.options && element.multiple;
  261. };
  262. /**
  263. * Retrieves the selected options from a multi-select as an array.
  264. * @param {HTMLOptionsCollection} options the options for the select
  265. * @return {Array} an array of selected option values
  266. */
  267. var getSelectValues = function getSelectValues(options) {
  268. return [].reduce.call(options, function (values, option) {
  269. return option.selected ? values.concat(option.value) : values;
  270. }, []);
  271. };
  272. /**
  273. * A more verbose implementation of `formToJSON()` to explain how it works.
  274. *
  275. * NOTE: This function is unused, and is only here for the purpose of explaining how
  276. * reducing form elements works.
  277. *
  278. * @param {HTMLFormControlsCollection} elements the form elements
  279. * @return {Object} form data as an object literal
  280. */
  281. var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {
  282. // This is the function that is called on each element of the array.
  283. var reducerFunction = function reducerFunction(data, element) {
  284. // Add the current field to the object.
  285. data[element.name] = element.value;
  286. // For the demo only: show each step in the reducer’s progress.
  287. console.log(JSON.stringify(data));
  288. return data;
  289. };
  290. // This is used as the initial value of `data` in `reducerFunction()`.
  291. var reducerInitialValue = {};
  292. // To help visualize what happens, log the inital value, which we know is `{}`.
  293. console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));
  294. // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  295. var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);
  296. // The result is then returned for use elsewhere.
  297. return formData;
  298. };
  299. /**
  300. * Retrieves input data from a form and returns it as a JSON object.
  301. * @param {HTMLFormControlsCollection} elements the form elements
  302. * @return {Object} form data as an object literal
  303. */
  304. var formToJSON = function formToJSON(elements) {
  305. return [].reduce.call(elements, function (data, element) {
  306. // Make sure the element has the required properties and should be added.
  307. if (isValidElement(element) && isValidValue(element)) {
  308. /*
  309. * Some fields allow for more than one value, so we need to check if this
  310. * is one of those fields and, if so, store the values as an array.
  311. */
  312. if (isCheckbox(element)) {
  313. data[element.name] = (data[element.name] || []).concat(element.value);
  314. } else if (isMultiSelect(element)) {
  315. data[element.name] = getSelectValues(element);
  316. } else {
  317. data[element.name] = element.value;
  318. }
  319. }
  320. return data;
  321. }, {});
  322. };