Browse Source

Reprise JS

olivier.massot 8 years ago
parent
commit
2e96e922fb
2 changed files with 149 additions and 197 deletions
  1. 26 28
      MobiParc/index.html
  2. 123 169
      MobiParc/js/mobiparc.js

+ 26 - 28
MobiParc/index.html

@@ -13,8 +13,8 @@
     <noscript>
         <style type="text/css">body.nojs{visibility:visible;}</style>
     </noscript>
-    <script src="js/jquery-3.2.1.min.js" defer></script>
-    <script src="js/jquery-ui.min.js" defer></script>
+    <script src="js/jquery-3.2.1.min.js" defer></script> 
+    <script src="js/jquery-ui.min.js" defer></script> 
     <script src="js/handlebars.min.js" defer></script>
     <script src="js/mobiparc.js" defer></script>
    
@@ -58,12 +58,15 @@
         </section>
     </header>
 
-    <section class="main">
+    <section id="main" class="main">
         <noscript>
             <h1>Suivi mobile d'Activités</h1>
             Pour accéder à toutes les fonctionnalités de ce site, vous devez activer JavaScript. Voici les 
             <a href="//www.enable-javascript.com/fr/" target="js"> instructions pour activer JavaScript dans votre navigateur Web</a>
         </noscript>
+
+        <!--  Injection Jquery  -->
+
     </section>
 
     <section class="footer-top">
@@ -71,10 +74,6 @@
     </section>
         
     <footer>
-        <!--<nav class="obs">
-            <div><span class="modal-open">Alerte</span></div>
-            <div></div>
-        </nav>-->
         <span id="cRetour" class="cInvisible"></span>
     </footer>
     
@@ -87,11 +86,29 @@
         <span class="modal-close">X</span>
     </section>
 
-    <script id="activites" type="x-tmpl-mustache">
+    <script id="index" type="x-tmpl-mustache">
+        <h1>Suivi mobile d'activités</h1>
+      
+        <div class="home-pp">
+            <a href="#activites">
+                <div>
+                    <picture>
+                        <source type="image/svg+xml" srcset="img/alert.svg" media="(min-width:240px)">
+                        <img src="img/alert.png" width="224" alt="" />
+                    </picture><h3>
+                        Saisie d'activité
+                    </h3>
+
+                </div>
+            </a>
+        </div>
+    </script>
+
+    <script id="activites" type="x-tmpl-mustache" model="activites">
         <h1>Activité</h1>
         <h2>Nouvelle saisie</h2>
 
-        <form class="data-form activite">
+        <form class="data-form activite" data-dbname="activites">
 
             <h3>Activité</h3>
             
@@ -218,24 +235,5 @@
 
     </script>
 
-
-    <script id="index" type="x-tmpl-mustache">
-        <h1>Suivi mobile d'activités</h1>
-      
-        <div class="home-pp">
-            <a href="#activites">
-                <div>
-                    <picture>
-                        <source type="image/svg+xml" srcset="img/alert.svg" media="(min-width:240px)">
-                        <img src="img/alert.png" width="224" alt="" />
-                    </picture><h3>
-                        Saisie d'activité
-                    </h3>
-
-                </div>
-            </a>
-        </div>
-    </script>
-
 </body>
 </html>

+ 123 - 169
MobiParc/js/mobiparc.js

@@ -1,4 +1,8 @@
-
+// requires jquery 1.7+
+
+// JS s'execute: Retire l'avertissement 'Javascript est requis' (de fait, on sait que JS est actif...)
+document.body.classList.remove("nojs");
+
 //### Helpers handlebars personnalisés
 Handlebars.registerHelper('lower', function (options) {
     return options.fn(this).toLowerCase();
@@ -26,16 +30,10 @@ Handlebars.registerHelper('if_eq', function (a, opts) {
         return opts.inverse(this);
 });
 
-// ### References
-
-// ref a la section main
-var main = document.getElementsByClassName('main')[0];
-
 
 //### Initialisation
 
-// JS s'execute: Retire l'avertissement 'Javascript est requis' (de fait, on sait que JS est actif...)
-document.body.classList.remove("nojs");
+var db_version = "3"
 
 // Installe le service worker
 if ('serviceWorker' in navigator) {
@@ -43,45 +41,125 @@ if ('serviceWorker' in navigator) {
     navigator.serviceWorker.register('../sw.js');
 }
 
-// Nettoie la section main
-$(".main").empty();
+var sectionId;
+var section;
 
-// Open (or create) the database
-var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
-var open = indexedDB.open("MobiParc", 3);
+var load = function () {
+    // Vide la section main
+    $("#main").empty();
 
-// Create the schema
-open.onupgradeneeded = function () {
-    var db = open.result;
-    var store = db.createObjectStore("activites", { keyPath: "tstamp" });
-    console.log("[Activites DB] Cree");
-};
+    // Page en cours
+    sectionId = (window.location.hash.slice(1).length > 0 ? window.location.hash.slice(1) : "index");
+    section = $("body").find('#' + sectionId);
 
-// Obtient l'id de la section a afficher en fonction de l'url
-function getSectionId() {
-    return (window.location.hash.slice(1).length > 0 ? window.location.hash.slice(1) : "index");
-};
-// Memorise la section en cours
-var sectionId = getSectionId();
+    // compile la section avec handlebars
+    if ($(section).attr("model")) {
+        var model = $(section).attr("model");
 
-// compile la page entiere avec handlebars
-var template = Handlebars.compile(document.getElementById(sectionId).innerHTML);
+        var template = Handlebars.compile(section.html());
+
+        // Charge la base de données, et le stockage courant
+        var indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
+        var request = indexedDB.open("MobiParc", db_version);
+        var db;
+        var txs;
+        var store;
+
+        // Cree les stockages necessaires si ceux ci sont manquants
+        request.onupgradeneeded = function () {
+            var db = request.result;
+            db.createObjectStore(model, { keyPath: "tstamp" });
+            console.log("[DB] Cree '" + model + "'");
+        };
+
+        request.onsuccess = function () {
+            db = request.result;
+            txs = db.transaction(model, "readonly");
+            store = txs.objectStore(model);
+            store.getAll().onsuccess = function (event) {
+                var data = { data: event.target.result };
+                $("#main").html(template(data));
+            };
+        };
+
+        request.onerror = function () {
+            console.log("Error while loading the db '" + model + "'");
+            $("#main").html(template({}));
+            return;
+        };
+
+        // Intercepte la soumision de formulaires
+        $("#main").on("submit", ".data-form", function (event) {
+            console.log("handle submit");
+
+            var form = $("#main").find(".data-form")[0];
+
+            // Stop the form from submitting since we’re handling that with AJAX.
+            event.preventDefault();
+
+            // Call our function to get the form data.
+            var data = formToJSON(form.elements);
+
+            // Demo only: print the form data onscreen as a formatted JSON object.
+            var dataContainer = document.getElementsByClassName('results-display')[0];
+
+            // Use `JSON.stringify()` to make the output valid, human-readable JSON.
+            dataContainer.textContent = JSON.stringify(data, null, "  ");
+
+            if ($(form).hasClass("activite")) {
+                data.tstamp = Date.now();
+                data.user = localStorage.hasOwnProperty("params") ? JSON.parse(localStorage.getItem("params")).user : "(unknown)";
+
+                txs = db.transaction(model, "readwrite");
+                store = txs.objectStore(model);
+                store.put(data);
+                
+                store.getAll().onsuccess = function (event) {
+                    $("#main").empty();
+                    var data = { data: event.target.result };
+                    var template = Handlebars.compile(section.html());
+                    $("#main").html(template(data));
+                };
+            }
+        });
+
+        // Gere le clic sur un bouton supprimer
+        $("body").on("click", ".del", function (event) {
+            var del = $(this);
+            if (confirm("Supprimer la selection!") == true) {
+
+                $(del).prop("disabled", true);
+
+                $(".ui-selected").each(function () {
+                    var elt = $(this);
+                    var id = $(elt).data("id");
+                    //var datatype = $(elt).data("type");
+
+                    txs = db.transaction(model, "readwrite");
+                    store = txs.objectStore(model);
+                    store.delete(id).onsuccess = function (evt) {
+                        $(elt).remove();
+                    };
+                });
+            }
+        });
+
+    }
+    else {
+        $("#main").html($(section).html());
+    }
 
-// Essaie de peupler la page en cours avec les données de la base (s'il y en a a afficher)
-try {
-    var db = open.result;
-    var txs = db.transaction(sectionId, "readonly");
-    var stores = txs.objectStore(sectionId);
-    console.log("Got all " + sectionId + ": ");
-    stores.getAll().onsuccess = function (event) {
-        var data = { data: event.target.result };
-        main.innerHTML = template(data);
-    };
-}
-catch (e) {
-    main.innerHTML = template({});
 }
 
+load();
+
+// Recharge dynamiquement le contenu HTML à chaque changement d'url
+$(window).on('hashchange', function () {
+    console.log("Trigger: hashchange");
+    load();
+});
+
+
 //######### MAIN  ###############
 
 // ### Interactions
@@ -120,135 +198,11 @@ $(".modal-open, .modal-background, .modal-close").click(function () {
     if ($(this).hasClass("modal-close")) location.reload();
 });
 
-// Recharge dynamiquement le contenu HTML à chaque changement d'url
-$(window).on('hashchange', function () {
-
-    var href = $(this).attr('href');
-
-    $('html, body').animate({ scrollTop: 0 }, 200);
-
-    template = Handlebars.compile(document.getElementById(sectionId).innerHTML);
-
-    if (sectionId != 'activites') {
-
-        $(".main").empty();
-        try {
-            var db = open.result;
-            var txs = db.transaction(sectionId, "readonly");
-            var stores = txs.objectStore(sectionId);
-            console.log("Got all " + sectionId + ": ");
-            stores.getAll().onsuccess = function (event) {
-                var data = { data: event.target.result };
-
-                main.innerHTML = template(data);
-            };
-        }
-        catch (e) {
-            main.innerHTML = template({});
-        }
-    }
-});
-
-var addSubmitHandler = function() {
-    if ($(".main").find(".data-form").length) {
-        form = $(".main").find(".data-form")[0];
-        form.addEventListener('submit', handleFormSubmit);
-        console.log("handler added");
-    }
-};
-addSubmitHandler();
-
-// Observeur: suit les modifications apportees a la section main
-// >> Infos: https://davidwalsh.name/mutationobserver-api
-var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
-var mainsection = document.querySelector("section.main");
-var observer = new MutationObserver(function (mutations) {
-    //gestion des mise element selectable
-    $(".selectable > tbody").selectable({
-        filter: "tr",
-        stop: function () {
-            $(".del").removeAttr("disabled");
-        }
-    });
-
-    document.getElementsByClassName('results-display')[0].innerHTML = null;
-
-});
-
-// Notify me of everything!
-var observerConfig = {
-    attributes: true,
-    childList: true,
-    characterData: true
-};
-target = document.querySelector("section.main");
-observer.observe(target, observerConfig);
-
-
-// Intercepte la soumision de formulaires
-if ($(".main").find(".data-form").length) {
-    var form = $(".main").find(".data-form")[0];
-
-    $(form).on("submit", function (event) { // on requires jquery 1.7+
-        handleFormSubmit(event);
-    });
-}
-
-var form;
-var handleFormSubmit = function handleFormSubmit(event) {
-    console.log("handle submit");
-
-    // Stop the form from submitting since we’re handling that with AJAX.
-    event.preventDefault();
-
-    // Call our function to get the form data.
-    var data = formToJSON(form.elements);
-
-    // Demo only: print the form data onscreen as a formatted JSON object.
-    var dataContainer = document.getElementsByClassName('results-display')[0];
-
-    // Use `JSON.stringify()` to make the output valid, human-readable JSON.
-    dataContainer.textContent = JSON.stringify(data, null, "  ");
-
-    if ($(form).hasClass("activite")) {
-        data.tstamp = Date.now();
-        data.user = localStorage.hasOwnProperty("params") ? JSON.parse(localStorage.getItem("params")).user : "(unknown)";
-        
-        var db = open.result;
-        var txs = db.transaction("activites", "readwrite");
-        var stores = txs.objectStore("activites");
-        stores.put(data);
-
-        $(".main").empty();
-
-        stores.getAll().onsuccess = function (event) {
-            var data = { data: event.target.result };
-            var template = Handlebars.compile(document.getElementById("activites").innerHTML);
-            $(".main").html(template(data));
-        };
-    }
-    console.log(data);
-};
-
-// Gere le clic sur un bouton supprimer
-$("body").on("click", ".del", function (event) {
-
-    var del = $(this);
-    if (confirm("Supprimer la selection!") == true) {
-
-        $(del).prop("disabled", true);
-
-        $(".ui-selected").each(function () {
-            var elt = $(this);
-            var id = $(elt).data("id");
-            var datatype = $(elt).data("type");
-            var db = open.result;
-            var tx = db.transaction(datatype, "readwrite");
-            var store = tx.objectStore(datatype);
-            store.delete(id).onsuccess = function (evt) {
-                $(elt).remove();
-            };
-        });
+// Rend selectionables les lignes des tables (.selectable)
+$("#main").selectable({
+    filter: ".selectable tr",
+    stop: function () {
+        $(".del").removeAttr("disabled");
     }
 });