main.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  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: "guid" });
  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", "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. data.guid = createGuid();
  83. //data.tstamp = Date.now();
  84. data.user = localStorage.hasOwnProperty("params") ? JSON.parse(localStorage.getItem("params")).user : "(unknown)";
  85. txs = db.transaction(model, "readwrite");
  86. store = txs.objectStore(model);
  87. store.put(data);
  88. store.getAll().onsuccess = function (event) {
  89. $("#main").empty();
  90. var data = { data: event.target.result };
  91. var template = Handlebars.compile(section.html());
  92. $("#main").html(template(data));
  93. };
  94. });
  95. // Gere le clic sur un bouton supprimer
  96. $("body").on("click", ".del", function (event) {
  97. var del = $(this);
  98. if (confirm("Supprimer la selection!") == true) {
  99. $(del).prop("disabled", true);
  100. $(".ui-selected").each(function () {
  101. var elt = $(this);
  102. var id = $(elt).data("id");
  103. //var datatype = $(elt).data("type");
  104. txs = db.transaction(model, "readwrite");
  105. store = txs.objectStore(model);
  106. store.delete(id).onsuccess = function (evt) {
  107. $(elt).remove();
  108. };
  109. });
  110. }
  111. });
  112. }
  113. else {
  114. //template = Handlebars.compile(section.html());
  115. //$("#main").html(template({}));
  116. $("#main").html(section.html());
  117. }
  118. }
  119. load();
  120. // Recharge dynamiquement le contenu HTML à chaque changement d'url
  121. $(window).on('hashchange', function () {
  122. console.log("Trigger: hashchange");
  123. load();
  124. });
  125. //######### MAIN ###############
  126. // ### Interactions
  127. // Affiche ou masque la sidebar
  128. $('.bt-menu').on('click', 'svg', function () {
  129. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  130. });
  131. $(document).on('click', '.sidebar', function () {
  132. $(this).closest('nav').find('div:not(:first)').toggleClass('sidebar');
  133. });
  134. // Affiche ou masque le bouton de sync
  135. if (navigator.onLine) {
  136. $(".data-sync").removeAttr("disabled");
  137. }
  138. else {
  139. if (!$(".data-sync").is(":disabled"))
  140. {
  141. $(".data-sync").attr("disabled")
  142. }
  143. }
  144. /* retour haut de page*/
  145. window.onscroll = function (ev) {
  146. document.getElementById("back-top").className =(window.pageYOffset > 100) ? "": "hidden";
  147. };
  148. $('#back-top').on('click', function () {
  149. $('html, body').animate({ scrollTop: 0 }, 200);
  150. });
  151. // Gere l'affichage des classes modales
  152. $(".toggle-sync-dlg").click(function () {
  153. $(".modal-content,.modal-background").toggleClass("active");
  154. if ($(this).hasClass("modal-close")) location.reload();
  155. });
  156. // Rend selectionables les lignes des tables (.selectable)
  157. $("#main").selectable({
  158. filter: ".selectable tr",
  159. stop: function () {
  160. $(".del").removeAttr("disabled");
  161. }
  162. });
  163. // ### Synchronisation des données
  164. $(".data-sync").on("click", function () {
  165. if (!request) {
  166. request = indexedDB.open(db_name, db_version);
  167. request.onerror = function () {
  168. console.log("Error while accessing the db");
  169. alert("Erreur: impossible d'accéder à la base de données locale.");
  170. return;
  171. };
  172. }
  173. var db = request.result;
  174. var txs = db.transaction("activites", "readonly");
  175. var stores = txs.objectStore("activites");
  176. console.log("post all");
  177. stores.openCursor().onsuccess = function (event) {
  178. var cursor = event.target.result;
  179. if (cursor) {
  180. cursor.value.model = "activites";
  181. var id = cursor.value.guid;
  182. var posting = $.post("/api/mobiparc", { data: JSON.stringify(cursor.value) });
  183. // Put the results in a div
  184. posting.done(function (data) {
  185. if (data == true) {
  186. var tx = db.transaction("activites", "readwrite");
  187. var store = tx.objectStore("activites");
  188. store.delete(id).onsuccess = function (evt) {
  189. $('.sync-result').append("Sync ok activite : " + id + "<br>");
  190. };
  191. }
  192. });
  193. cursor.continue();
  194. }
  195. else {
  196. console.log("end activite");
  197. }
  198. };
  199. })
  200. //###### TOOLBOX ######
  201. function createGuid() {
  202. return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
  203. (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
  204. )
  205. }
  206. function getLocation() {
  207. try {
  208. if (navigator.geolocation) {
  209. navigator.geolocation.getCurrentPosition(showPosition);
  210. } else {
  211. console.log("Geolocation is not supported by this browser.");
  212. return 0;
  213. }
  214. }
  215. catch (e) {
  216. console.log("Geolocation: error");
  217. }
  218. }
  219. function showPosition(position) {
  220. $("input[name='coordinates']").val(position.coords.latitude + "," + position.coords.longitude);
  221. console.log(position.coords);
  222. }
  223. // ### Serialization
  224. /**
  225. * Checks that an element has a non-empty `name` and `value` property.
  226. * @param {Element} element the element to check
  227. * @return {Bool} true if the element is an input, false if not
  228. */
  229. var isValidElement = function isValidElement(element) {
  230. return element.name && element.value;
  231. };
  232. /**
  233. * Checks if an element’s value can be saved (e.g. not an unselected checkbox).
  234. * @param {Element} element the element to check
  235. * @return {Boolean} true if the value should be added, false if not
  236. */
  237. var isValidValue = function isValidValue(element) {
  238. return !['checkbox', 'radio'].includes(element.type) || element.checked;
  239. };
  240. /**
  241. * Checks if an input is a checkbox, because checkboxes allow multiple values.
  242. * @param {Element} element the element to check
  243. * @return {Boolean} true if the element is a checkbox, false if not
  244. */
  245. var isCheckbox = function isCheckbox(element) {
  246. return element.type === 'checkbox';
  247. };
  248. //var isHidden = function isHidden(element) {
  249. // return element.type === 'hidden';
  250. //};
  251. /**
  252. * Checks if an input is a `select` with the `multiple` attribute.
  253. * @param {Element} element the element to check
  254. * @return {Boolean} true if the element is a multiselect, false if not
  255. */
  256. var isMultiSelect = function isMultiSelect(element) {
  257. return element.options && element.multiple;
  258. };
  259. /**
  260. * Retrieves the selected options from a multi-select as an array.
  261. * @param {HTMLOptionsCollection} options the options for the select
  262. * @return {Array} an array of selected option values
  263. */
  264. var getSelectValues = function getSelectValues(options) {
  265. return [].reduce.call(options, function (values, option) {
  266. return option.selected ? values.concat(option.value) : values;
  267. }, []);
  268. };
  269. /**
  270. * A more verbose implementation of `formToJSON()` to explain how it works.
  271. *
  272. * NOTE: This function is unused, and is only here for the purpose of explaining how
  273. * reducing form elements works.
  274. *
  275. * @param {HTMLFormControlsCollection} elements the form elements
  276. * @return {Object} form data as an object literal
  277. */
  278. var formToJSON_deconstructed = function formToJSON_deconstructed(elements) {
  279. // This is the function that is called on each element of the array.
  280. var reducerFunction = function reducerFunction(data, element) {
  281. // Add the current field to the object.
  282. data[element.name] = element.value;
  283. // For the demo only: show each step in the reducer’s progress.
  284. console.log(JSON.stringify(data));
  285. return data;
  286. };
  287. // This is used as the initial value of `data` in `reducerFunction()`.
  288. var reducerInitialValue = {};
  289. // To help visualize what happens, log the inital value, which we know is `{}`.
  290. console.log('Initial `data` value:', JSON.stringify(reducerInitialValue));
  291. // Now we reduce by `call`-ing `Array.prototype.reduce()` on `elements`.
  292. var formData = [].reduce.call(elements, reducerFunction, reducerInitialValue);
  293. // The result is then returned for use elsewhere.
  294. return formData;
  295. };
  296. /**
  297. * Retrieves input data from a form and returns it as a JSON object.
  298. * @param {HTMLFormControlsCollection} elements the form elements
  299. * @return {Object} form data as an object literal
  300. */
  301. var formToJSON = function formToJSON(elements) {
  302. return [].reduce.call(elements, function (data, element) {
  303. // Make sure the element has the required properties and should be added.
  304. if (isValidElement(element) && isValidValue(element)) {
  305. /*
  306. * Some fields allow for more than one value, so we need to check if this
  307. * is one of those fields and, if so, store the values as an array.
  308. */
  309. if (isCheckbox(element)) {
  310. data[element.name] = (data[element.name] || []).concat(element.value);
  311. } else if (isMultiSelect(element)) {
  312. data[element.name] = getSelectValues(element);
  313. } else {
  314. data[element.name] = element.value;
  315. }
  316. }
  317. return data;
  318. }, {});
  319. };
  320. /*
  321. Intensify by TEMPLATED
  322. templated.co @templatedco
  323. Released for free under the Creative Commons Attribution 3.0 license (templated.co/license)
  324. */
  325. (function ($) {
  326. skel.breakpoints({
  327. xlarge: '(max-width: 1680px)',
  328. large: '(max-width: 1280px)',
  329. medium: '(max-width: 980px)',
  330. small: '(max-width: 736px)',
  331. xsmall: '(max-width: 480px)'
  332. });
  333. $(function () {
  334. var $window = $(window),
  335. $body = $('body'),
  336. $header = $('#header');
  337. // Disable animations/transitions until the page has loaded.
  338. $body.addClass('is-loading');
  339. $window.on('load', function () {
  340. window.setTimeout(function () {
  341. $body.removeClass('is-loading');
  342. }, 100);
  343. });
  344. // Fix: Placeholder polyfill.
  345. $('form').placeholder();
  346. // Prioritize "important" elements on medium.
  347. skel.on('+medium -medium', function () {
  348. $.prioritize(
  349. '.important\\28 medium\\29',
  350. skel.breakpoint('medium').active
  351. );
  352. });
  353. // Scrolly.
  354. $('.scrolly').scrolly({
  355. offset: function () {
  356. return $header.height();
  357. }
  358. });
  359. // Menu.
  360. $('#menu')
  361. .append('<a href="#menu" class="close"></a>')
  362. .appendTo($body)
  363. .panel({
  364. delay: 500,
  365. hideOnClick: true,
  366. hideOnSwipe: true,
  367. resetScroll: true,
  368. resetForms: true,
  369. side: 'right'
  370. });
  371. });
  372. })(jQuery);