소스 검색

Sistemato il cerca. Workaround: Post che non abbiamo li apro nel browser.

gine 7 년 전
부모
커밋
441b9eb9b9
5개의 변경된 파일159개의 추가작업 그리고 120개의 파일을 삭제
  1. 2 6
      www/index.html
  2. 7 65
      www/js/main.js
  3. 54 41
      www/js/query.js
  4. 89 0
      www/js/search.js
  5. 7 8
      www/js/update.js

+ 2 - 6
www/index.html

@@ -44,6 +44,7 @@
     <script type="text/javascript" src="js/query.js"></script>
     <script type="text/javascript" src="js/update.js"></script>
     <script type="text/javascript" src="js/tag.js"></script>
+    <script type="text/javascript" src="js/search.js"></script>
     <script type="text/javascript" src="js/events.js"></script>
     <script type="text/javascript" src="js/crud.events.js"></script>
     <script type="text/javascript" src="js/push.js"></script>
@@ -262,17 +263,12 @@
         </div>
     </div><!-- chiude pagina -->
     
-    <div data-role="page" id="ricerca" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
+    <div data-role="page" id="cerca" data-prev="index" data-next="" data-dom-cache="true" data-theme="a" class="ui-page">
         <div role="main" class="ui-content">
             <div class="ui-body">
                 <p class="introlettera">Risultati della ricerca</p>
                 <p class="listresult listatovirgole listevoci"></p>
             </div>
-
-            <div data-role="popup" id="aggiornaora" data-dismissible="false">
-                <p>Questa voce è nuova ed è disponibile online. Aggiorna ora gli articoli locali della tua app:</p>
-                <input type="button" value="OK" onclick="$( '#aggiornaora' ).popup( 'close' );update();alterContent('#info')" />
-            </div>
         </div>
     </div><!-- chiude pagina -->
     

+ 7 - 65
www/js/main.js

@@ -133,14 +133,6 @@ $(function () {
     });
 });
 
-function benvenuta() {
-    $("#benvenuta").popup("open");
-}
-
-//function aggiornaora() {
-//    $("#aggiornaora").popup("open");
-//};
-
 function initMainPage() {
     if (checkConnection()) {
         postsUpdate(FONTE.categories.info);
@@ -167,7 +159,7 @@ $(document).on("mobileinit", function () {
 
 $(document).on("pagecontainerchange", function () {    
     var current = $(".ui-page-active").prop("id");     // Remove active class from nav buttons
-    if(current == 'about' || current == 'info' || current == 'ilove' || current == 'events'){
+    if(current == 'about' || current == 'info' || current == 'ilove' || current == 'events' || current == 'cerca'){
         $("#navfooter").addClass("hide");
     } else {
         $("#navfooter").removeClass("hide");
@@ -243,6 +235,7 @@ function onDeviceReady() {
     $("[data-role='navbar']").navbar();
     
     //Non uso pageContent per non lanciare 2 volte il recupero dei dati da internet
+    //per la pagina principale
     $("#navheader").removeClass("hide");
     $("#navfooter").addClass("hide");
 }
@@ -269,6 +262,10 @@ function postInList() {
     //SCRITTURA
     $("body").on('click', '.listevoci li > a', function (event) {
         // console.log("HUU_post in list");
+        if($(this).attr("rel") === 'external') {
+            return true;
+        }
+        
         var idOra = $(this).attr("data-post");
         var _class = $(this).attr("class");
         $("#titolosingle").empty();
@@ -287,52 +284,6 @@ function postInList() {
     });
 }
 
-function cercaMe() {
-    var input_text = $("input.cerca").val();
-    input_text = encodeURIComponent(input_text);
-    var jsonurl = weburl + "wp-json/wp/v2/posts?per_page=10&search=" + input_text + "";
-    $(".listresult").empty();
-    $("body").pagecontainer("change", "#ricerca");
-    $.mobile.loading('show');
-
-    var lastUpdate = window.localStorage.getItem('db_update_date');
-    if (lastUpdate) {
-        var lastUpdateDate = Date.parse(lastUpdate);
-
-        $.ajax({
-            dataType: "json",
-            url: jsonurl,
-            success: function (data) {
-                var items = [];
-                $.each(data, function (key, val) {
-                    var id = val.id;
-                    var time = val.modified;
-                    var title = val.title.rendered;
-                    var url = val.guid.rendered;
-                    var tag = data.tags;
-                    var splitTime = time.split("T");
-                    var cleanTime = splitTime[0];
-                    var dTime = new Date(time);
-                    if (dTime.getTime() <= lastUpdateDate) {
-                        //key mi dice l'indice'
-                        items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
-                    } else {
-                        items.push("<p><a href='#' onclick='aggiornaora();' style='color:#666;' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></p>");
-                    }
-                });
-                $("<ul/>", {
-                    "class": "my-new-list",
-                    html: items.join("")
-                }).prependTo(".listresult");
-                $.mobile.loading('hide');
-            },
-            error: JSONErrorHandler
-        });
-    } else {
-        toastr.error('Err: ERR_NOUPDATE');
-    }
-}
-
 function findImg(htmlString) {
     var pos = htmlString.indexOf('<img ');
     while (pos != -1) {
@@ -351,6 +302,7 @@ function imgNotFound(img) {
 
 function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
     if (!FONTE.ajaxError) {
+        $.mobile.loading('hide');
         var errMsg = "Err: ";
         if(jqXHR.status === 404) {
             errMsg += "Sito non raggiungibile. ";
@@ -360,16 +312,6 @@ function JSONErrorHandler(jqXHR, textStatus, errorThrown) {
     }
 }
 
-function cerca() {
-    var ret = checkConnection('ERR_CERCA');
-
-    if (ret) {
-        cercaMe();
-    }
-
-    return ret;
-}
-
 function segnalaBug() {
     return checkConnection('ERR_SEGNALA');
 }

+ 54 - 41
www/js/query.js

@@ -5,11 +5,10 @@ function myJsonCategory(Qcategory, div, addTagCategory) {
         for (var i = 0; i < resultSet.rows.length; i++) {
             var val = JSON.parse(resultSet.rows.item(i).post);
             var id = val.id;
-            var time = val.modified;
+            var date = val.date;
             var title = val.title.rendered;
             var url = val.guid.rendered;
-            var splitTime = time.split("T");
-            var cleanTime = splitTime[0];
+            var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);
             var tag = '';
             var cattag = '';
             /* if (addTagCategory) {
@@ -25,17 +24,43 @@ function myJsonCategory(Qcategory, div, addTagCategory) {
                  items.push("<li class='"+ cattag +"'><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small><span>" + tag + "</span>|</li>");
              }
             else {*/
-                items.push("<li><a href='#singleQpost' data-post='" + id + "'>" + title + "</a><br/><small>" + cleanTime + "</small></li>");
-
+                items.push(getLiPost(id, title, cleanTime));
         }
         $("<ul/>", {
             "class": "my-new-list",
             html: items.join("")
         }).prependTo(div);
+        $.mobile.loading('hide');
     });
-    $.mobile.loading('hide');
 }
 
+var getLiPostNotPresent = function(id, title, cleanTime, url, style){
+    //TODO:var onclick = " onclick='"+getWpPost()+ "' ";
+    var li =  "<li>"+
+                "<a style='"+ style +"' href='" + url + "' rel='external'>" + 
+                    title + 
+                "</a>"+
+                "<br/>"+
+                "<small>" + cleanTime + "</small>"+
+                "<hr class='post-divider'>"+
+              "</li>";
+                
+    return li;
+};
+
+var getLiPost = function(id, title, cleanTime){
+    var li =  "<li>"+
+                    "<a href='#singleQpost' data-post='" + id + "'>" + 
+                        title + 
+                    "</a>"+
+                    "<br/>"+
+                    "<small>" + cleanTime + "</small>"+
+                    "<hr class='post-divider'>"+
+                "</li>";
+                
+    return li;
+};
+
 var drawListPost = function(div, resultSet, position) {
     var items = [];
     for (var i = 0; i < resultSet.rows.length; i++) {
@@ -46,16 +71,7 @@ var drawListPost = function(div, resultSet, position) {
         var url = val.guid.rendered;
         var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);
 
-        var li =  "<li>"+
-                        "<a href='#singleQpost' data-post='" + id + "'>" + 
-                            title + 
-                        "</a>"+
-                        "<br/>"+
-                        "<small>" + cleanTime + "</small>"+
-                        "<hr class='post-divider'>"+
-                    "</li>";
-
-        items.push(li);
+        items.push(getLiPost(id, title, cleanTime));
     }
 
     var ul = $("<ul/>", {
@@ -102,6 +118,7 @@ function drawNoPostsFound(div) {
 }
 
 function sqlErrHandler(error){
+    $.mobile.loading('hide');
     console.log(error.message);
 }
 
@@ -128,6 +145,8 @@ POST.sql = {
     end : "ORDER BY date COLLATE NOCASE DESC LIMIT ?"
 };
 
+POST.table = "xm24_posts";
+
 var selectLastNews = function(div, categories) {
     var catsWhere = getCategoryWhere(categories);
     
@@ -235,6 +254,21 @@ function myJsonCategoryPaginated(Qcategory, div, pageNumber) {
     $.mobile.loading('hide');
 }
 
+var renderShareButton = function(div_content, title, url, content){
+    $('.share-btn').remove();
+    
+    content = content || '';
+    
+    var shareButton = $('<button>', {
+        class : "share-btn ui-btn ui-shadow ui-corner-all",
+        text: "Condividi"
+    }).click(function(){
+        shareMeNow(title, content, url);
+    });
+    
+    $(div_content).after(shareButton);
+};
+
 function drawPost(div_title, div_content, resultSet){
     for (var i = 0; i < resultSet.rows.length; i++) {
         var val = JSON.parse(resultSet.rows.item(i).post);
@@ -247,17 +281,8 @@ function drawPost(div_title, div_content, resultSet){
         content = findImg(content);
 
         $(div_title).html(title);
-        
-        var shareButton = $('<button>', {
-            class : "share-btn ui-btn ui-shadow ui-corner-all",
-            text: "Condividi"
-        }).click(function(){
-            shareMeNow(title, '',url);
-        });
-        
-        $('.share-btn').remove();
         $(div_content).html("<p>" + content + "</p>");
-        $(div_content).after(shareButton);
+        renderShareButton(div_content, title, url, '');
     }
 }
 
@@ -274,22 +299,13 @@ function drawEvent(div_title, div_content, resultSet){
         var geo = val.geo;
 
         $(div_title).html(title);
-        
-        var shareButton = $('<button>', {
-            class : "share-btn ui-btn ui-shadow ui-corner-all",
-            text: "Condividi"
-        }).click(function(){
-            shareMeNow(title, evInitDate + " "+ evEndDate, url);
-        });
-        
-        $('.share-btn').remove();
         $(div_content).html("<small>" + evInitDate +"-" + evEndDate +"</small><p>" + content + "</p>");
-        $(div_content).after(shareButton);
+        renderShareButton(div_content, title, url, evInitDate + " "+ evEndDate);
     }
 }
 
 function myJsonPost(Qid, div_title, div_content, _class) {
-    var table = "xm24_posts";
+    var table = POST.table;
     if(_class){
         table = EVENTS.table.single;
     }
@@ -300,9 +316,7 @@ function myJsonPost(Qid, div_title, div_content, _class) {
         } else {
             drawEvent(div_title, div_content, resultSet);
         }
-    }, function (error) {
-        console.log(error);
-    });
+    }, sqlErrHandler);
 }
 
 function myJsonPage(Qid, div_title, div_content) {
@@ -317,7 +331,6 @@ function myJsonPage(Qid, div_title, div_content) {
             var content = data.page;
             content = findImg(content);
             $(div_title).html(title);
-            //key mi dice l'indice'
             $(div_content).html("<p>" + content + "</p>");
         }
     });

+ 89 - 0
www/js/search.js

@@ -0,0 +1,89 @@
+var renderSearched = function(items, input_text){
+    var len =  items.length;
+    
+    //Forzo la chiusura del pannello che oogni tanto rimane aperto
+    $( "#outside" ).panel( "close" );
+    
+    var htmlItems = items.join("");
+    var container = "<ul>";
+    if(len === 0) {
+        container = "<p>";
+        htmlItems = "<i>Non sono stati trovati articoli per la ricerca: " + input_text + ".</i>";
+    }
+    
+    $(container, {
+        html: htmlItems
+    }).prependTo(".listresult");
+    
+    $.mobile.loading('hide');
+    
+    //In caso non ci sia contenuto lo scrivo già nel content, 
+    // non c'è bisogno anche del toaster
+    if(len > 0)
+        toastr.info('Trovati ' + items.length + ' articoli.');
+};
+
+function searchWpPosts() {
+    var table = POST.table;
+    
+    var input_text = $("input.cerca").val();
+    input_text = encodeURIComponent(input_text);
+    var jsonurl = weburl + REST_PARAMS.posts + REST_PARAMS.per_page + "&search=" + input_text + "";
+    $(".listresult").empty();
+    $("body").pagecontainer("change", "#cerca");
+    
+    $.mobile.loading('show');
+    $.ajax({
+        dataType: "json",
+        url: jsonurl,
+        success: function (data) {
+            var items = [];
+            var n_error = 0;
+            FONTE.updatedPostsCount = 0;
+            FONTE.neededPostsCount = data.length;
+            
+            if(FONTE.neededPostsCount === 0) {
+                renderSearched(items, input_text);
+                return false;
+            }
+            
+            $.each(data, function (key, val) {
+                var id = val.id;
+                var date = val.date;
+                var title = val.title.rendered;
+                var tag = data.tags;
+                var cleanTime = EVENTS.formatDate(date, EVENTS.dateFormat.display.date);
+            
+                FONTE.dbHandler.executeSql("SELECT * FROM " + table + " WHERE id = ?;", [id], function(resultSet) {
+                    FONTE.updatedPostsCount++;
+                    if(resultSet.rows.length > 0) {
+                        items.push(getLiPost(id, title, cleanTime));
+                    } else {
+                        items.push(getLiPostNotPresent(id, title, cleanTime, val.link, 'color:#666;'));
+                    }
+                    
+                    if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount) {
+                        renderSearched(items, input_text);
+                    }
+                }, function (error) {
+                    n_error++;
+                    if (n_error + FONTE.updatedPostsCount >= FONTE.neededPostsCount && FONTE.updatedPostsCount > 0 ) {
+                        renderSearched(items, input_text);
+                    }
+                });            
+            });
+        },
+
+        error: JSONErrorHandler
+    });
+}
+
+function cerca() {
+    var ret = checkConnection('ERR_CERCA');
+
+    if (ret) {
+        searchWpPosts();
+    }
+
+    return ret;
+}

+ 7 - 8
www/js/update.js

@@ -1,9 +1,12 @@
 var REST_PARAMS = REST_PARAMS || {};
+REST_PARAMS.api = "wp-json/wp/v2";
+REST_PARAMS.posts = REST_PARAMS.api + "/posts?";
+REST_PARAMS.pages = REST_PARAMS.api + "/pages?";
 REST_PARAMS.max_page = 10;
 REST_PARAMS.per_page = 'per_page=' + REST_PARAMS.max_page;
 
 function aggiornaPages() {
-    var jsonurl = weburl + "wp-json/wp/v2/pages/";
+    var jsonurl = weburl + REST_PARAMS.pages;
     $.ajax({
         dataType: "json",
         url: jsonurl,
@@ -29,7 +32,7 @@ function aggiornaSingleCategory(category) {
     //resetta la variabile d'errore per le chiamate ajax asincrone
     FONTE.ajaxError = false;
 
-    var jsonurl = weburl + "wp-json/wp/v2/posts?" + REST_PARAMS.per_page;
+    var jsonurl = weburl + REST_PARAMS.posts + REST_PARAMS.per_page;
 
     var storage = window.localStorage;
     var lastUpdate = storage.getItem('db_update_date');
@@ -38,10 +41,6 @@ function aggiornaSingleCategory(category) {
     getSinglePageRecur(jsonurl, category, 1);
 }
 
-function aggiornaora() {
-    $("#aggiornaora").popup("open");
-}
-
 function resetAndUpdate() {
     var storage = window.localStorage;
     //resetto la data e droppo le tabelle
@@ -65,7 +64,7 @@ function update() {
 function postsUpdate(categories) {
     var storage = window.localStorage;
     var type = getObjKey(FONTE.categories, categories);
-    var jsonurl = weburl + "wp-json/wp/v2/posts?" + REST_PARAMS.per_page + "&categories=" + categories.join(',');
+    var jsonurl = weburl + REST_PARAMS.posts + REST_PARAMS.per_page + "&categories=" + categories.join(',');
     
     FONTE.updatedCategoriesCount = 0;
     FONTE.updatedPostsCount = 0;
@@ -100,7 +99,7 @@ var updateLocalStorageDate = function(type){
 var getPrevNews = function(div, categories, page) {
     var storage = window.localStorage;
     var type = getObjKey(FONTE.categories, categories);
-    var jsonurl = weburl + "wp-json/wp/v2/posts?" + REST_PARAMS.per_page + "&categories=" + FONTE.categories[type].join(',');
+    var jsonurl = weburl + REST_PARAMS.posts + REST_PARAMS.per_page + "&categories=" + FONTE.categories[type].join(',');
     
     FONTE.updatedCategoriesCount = 0;
     FONTE.updatedPostsCount = 0;