Merged Completion List back into Facettes
authorveltr
Thu, 11 Oct 2012 15:42:38 +0200
changeset 250 7c3f54ce68af
parent 248 91bc8521e3cb
child 251 e6675a5b2195
Merged Completion List back into Facettes
web/hdalab/static/hdalab/css/facettes.css
web/hdalab/static/hdalab/js/completion.js
web/hdalab/static/hdalab/js/gomina.js
web/hdalab/templates/base.html
web/hdalab/templates/completion.html
web/hdalab/templates/facettes.html
web/hdalab/urls.py
web/hdalab/views/ajax.py
--- a/web/hdalab/static/hdalab/css/facettes.css	Thu Oct 04 12:25:12 2012 +0200
+++ b/web/hdalab/static/hdalab/css/facettes.css	Thu Oct 11 15:42:38 2012 +0200
@@ -430,4 +430,57 @@
     position: absolute; width: 10px; height: 10px; background: #000000; border-radius: 5px; display: none;
 }
 
+/* COMPLETION */
 
+#tagsearch {
+    width: 100%; font-size: 16px; font-weight: bold; border-style: none; border-bottom: 1px solid #000;
+}
+
+#tagsearch.waiting {
+    background: url(../img/small-loader.gif) no-repeat right;
+}
+
+ul.ui-autocomplete {
+    font-family: "Open Sans"; max-width: 230px;
+    max-height: 400px; overflow-y: auto; overflow-x: hidden;
+}
+
+.wpinfo {
+    margin-left: 240px;
+}
+
+.ui-menu-item:hover .acwp {
+    display: block;
+}
+
+.acnb {
+    float: right; font-size: 12px; margin: 2px 0 0 2px;
+}
+
+.actitle {
+    font-size: 13px;
+}
+
+.wptitle {
+    font-size: 13px; font-weight: bold;
+}
+
+.wpimg {
+    max-width: 80px; max-height: 60px; float: left; margin: 5px 2px 2px 0; border: none;
+}
+
+.wpabstract {
+    font-size: 11px;
+}
+
+.wpsource {
+    font-size: 10px; font-style: bold;
+}
+
+.clear {
+    clear: both;
+}
+
+.actitle strong, .wptitle strong {
+    color: #c000c0;
+}
--- a/web/hdalab/static/hdalab/js/completion.js	Thu Oct 04 12:25:12 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,130 +0,0 @@
-var gomNs = {
-    languageCode: 'fr'
-}
-
-function showResults(data) {
-    $("#contentcount").html('<b>'+data.count+'</b> ' + ngettext('notice', 'notices', data.count));
-    var contentdata = data.contents;
-    if (contentdata && contentdata.length) {
-        var _htmlCl = '<ul id="contentlist">'
-            + contentdata.map(function(_d) {
-                var _html = '<li class="content-item"><h3>'
-                    + _d.title
-                    + '</h3>'
-                    + ( typeof _d.coords == "object" ?
-                        '<div class="maplet"><img src="http://maps.googleapis.com/maps/api/staticmap?center=47,1.5&zoom=4&size=160x160&maptype=roadmap&markers=color:red%7C'
-                        + _d.coords.latitude
-                        + ','
-                        + _d.coords.longitude
-                        + '&sensor=false" /><h4>'
-                        + gettext('Localisation&nbsp;:')
-                        + ' '
-                        + _d.coords.city_name
-                        + '</h4></div>'
-                        : '')
-                    + '<h4><a href="'
-                    + _d.url
-                    + '" target="_blank">'
-                    + _d.url.replace(/(^.{40}).+(.{30}$)/m,'$1 &hellip; $2')
-                    + '</a></h4><p>'
-                    + _d.description.replace(/(^.{0,160})([\s]|$)(.*)/,'$1&hellip;')
-                    + '</p><ul class="content-tags">'
-                    + _d.tags.map(function(_t) {
-                        return '<li class="content-tag-item"><a href="#" onclick="getContents(this.textContent.trim()); return false;" original-label="'
-                            + _t.label
-                            + '"'
-                            + (_t.match ? ' class="tagmatch"' : '')
-                            + '>'
-                            + _t.translated_label
-                            + '</a></li>';
-                    }).join('')
-                    + '</ul>';
-                _html += '</li>';
-                return _html;
-            }).join('')
-            + '</ul>';
-        $("#contents").html(_htmlCl).scrollTop(0);
-    }
-    else {
-        $("#contents").html("");
-    }
-}
-
-function getContents(label) {
-    $.getJSON(
-        gomNs.urls['contentsbytag'],
-        {
-            label: label
-        },
-        showResults
-    );
-}
-
-function ellipse(_text, _length) {
-    var _rgxp = new RegExp('(^.{0,' + _length + '})([\s]|$)(.*)')
-    return _text.replace(/(\n|\r|\r\n)/mg,' ').trim().replace(_rgxp,'$1…')
-}
-
-function highlightText(_text, _search) {
-    var _rgxp = new RegExp('(' + _search.replace(/(\W)/g, '\\$1') + ')','gi');
-    return _text.replace(_rgxp, '<strong>$1</strong>');
-}
-
-function wikipediaUrl(_text) {
-    return "http://" + gomNs.languageCode + ".wikipedia.org/wiki/" + encodeURI(_text.replace(/ /g,'_'))
-}
-
-wpTemplate = _.template(
-    '<h4 class="wptitle"><% print(highlightText(item.label, inputvalue)); %></h4><% if (item.thumbnail) { %><img class="wpimg" src="<%-item.thumbnail%>" /><% };'
-    + ' if (item.abstract) { %><p class="wpabstract"><% print(ellipse(item.abstract,250))%></p><p class="wpsource"><a href="<% print(wikipediaUrl(item.label)) %>" target="_blank"><% print(gettext("Source&nbsp;: Wikipédia")) %></a></p><% }; %><div class="clear"></div>'
-);
-
-acTemplate = _.template(
-    '<a><span class="acnb"><%- item.nb %></span><h4 class="actitle"><% print(highlightText(item.label, inputvalue)); %></h4></a>'
-)
-
-$(document).ready(function() {
-    $(" #tagform ").submit(function() {
-        return false;
-    });
-    var cache = {}, /*CACHE => http://jqueryui.com/demos/autocomplete/#remote-with-cache */
-        lastXhr;
-    $( "#tagsearch" ).autocomplete({
-        source: function( request, response ) {
-            var term = request.term;
-            if ( term in cache ) {
-                $("#tagsearch").removeClass("waiting");
-                response( cache[ term ] );
-                return;
-            }
-            $("#tagsearch").addClass("waiting");
-            lastXhr = $.getJSON( gomNs.urls['tag_search'], request, function( data, status, xhr ) {
-                cache[ term ] = data;
-                if ( xhr === lastXhr ) {
-                    response( data );
-                    $("#tagsearch").removeClass("waiting");
-                }
-            });
-        },
-        minLength: ( gomNs.languageCode == 'ja' ? 1 : 2 ),
-        focus: function( event, ui ) {
-            $(".wpinfo").html(wpTemplate({
-                item: ui.item,
-                inputvalue: $("#tagsearch").val()
-            }));
-        },
-        select: function( event, ui ) {
-            getContents(ui.item.label);
-        }
-    })
-    .data("autocomplete")._renderItem = function(ul, item) {
-        var _contents = acTemplate({
-            item: item,
-            inputvalue: $("#tagsearch").val()
-        });
-        return $( "<li>" )
-            .data( "item.autocomplete", item )
-            .html( _contents )
-            .appendTo( ul );
-    };
-});
--- a/web/hdalab/static/hdalab/js/gomina.js	Thu Oct 04 12:25:12 2012 +0200
+++ b/web/hdalab/static/hdalab/js/gomina.js	Thu Oct 11 15:42:38 2012 +0200
@@ -407,7 +407,7 @@
             + _(data.tags).map(function(_d) {
                 return '<li style="font-size:'
                     + parseInt(10 + _scale * Math.sqrt(_d.score - _minTag))
-                    + 'px;"><a href="#" onclick="addFilter(\'tag\', this.getAttribute(\'original-label\'), true); return false;" original-label="'
+                    + 'px;"><a href="#" onclick="addFilter(\'tag\', this.getAttribute(\'original-label\')); return false;" original-label="'
                     + _d.label
                     +'"'
                     + (_d.match ? ' class="tagmatch"' : '')
@@ -456,7 +456,7 @@
             '<ul class="disc-ul">'
             + _disc.map(function(_d) {
                 var _col = getGradient(_d.score / _max);
-                return '<li class="disc-li" onclick="addFilter(\'tag\', this.getAttribute(\'original-label\'), true); return false;" original-label="'
+                return '<li class="disc-li" onclick="addFilter(\'tag\', this.getAttribute(\'original-label\')); return false;" original-label="'
                     + _d.label
                     + '"><div class="disc-label"><a href="#">'
                     + _d.translated_label
@@ -645,6 +645,28 @@
 function animStop() {
     $("#waiting").empty().fadeOut();
 }
+function ellipse(_text, _length) {
+    var _rgxp = new RegExp('(^.{0,' + _length + '})([\s]|$)(.*)')
+    return _text.replace(/(\n|\r|\r\n)/mg,' ').trim().replace(_rgxp,'$1…')
+}
+
+function highlightText(_text, _search) {
+    var _rgxp = new RegExp('(' + _search.replace(/(\W)/g, '\\$1') + ')','gi');
+    return _text.replace(_rgxp, '<strong>$1</strong>');
+}
+
+function wikipediaUrl(_text) {
+    return "http://" + gomNs.languageCode + ".wikipedia.org/wiki/" + encodeURI(_text.replace(/ /g,'_'))
+}
+
+wpTemplate = _.template(
+    '<h4 class="wptitle"><% print(highlightText(item.label, inputvalue)); %></h4><% if (item.thumbnail) { %><img class="wpimg" src="<%-item.thumbnail%>" /><% };'
+    + ' if (item.abstract) { %><p class="wpabstract"><% print(ellipse(item.abstract,250))%></p><p class="wpsource"><a href="<% print(wikipediaUrl(item.label)) %>" target="_blank"><% print(gettext("Source&nbsp;: Wikipédia")) %></a></p><% }; %><div class="clear"></div>'
+);
+
+acTemplate = _.template(
+    '<a><span class="acnb"><%- item.nb %></span><h4 class="actitle"><% print(highlightText(item.label, inputvalue)); %></h4></a>'
+);
 
 $(document).ready(function() {
     switch(gomNs.mappingLibrary) {
@@ -832,4 +854,47 @@
        }
        return false;
     });
+        $(" #tagform ").submit(function() {
+        return false;
+    });
+    var cache = {}, /*CACHE => http://jqueryui.com/demos/autocomplete/#remote-with-cache */
+        lastXhr;
+    $( "#tagsearch" ).autocomplete({
+        source: function( request, response ) {
+            var term = request.term;
+            if ( term in cache ) {
+                $("#tagsearch").removeClass("waiting");
+                response( cache[ term ] );
+                return;
+            }
+            $("#tagsearch").addClass("waiting");
+            lastXhr = $.getJSON( gomNs.urls['tag_search'], request, function( data, status, xhr ) {
+                cache[ term ] = data;
+                if ( xhr === lastXhr ) {
+                    response( data );
+                    $("#tagsearch").removeClass("waiting");
+                }
+            });
+        },
+        minLength: ( gomNs.languageCode == 'ja' ? 1 : 2 ),
+        focus: function( event, ui ) {
+            $(".wpinfo").html(wpTemplate({
+                item: ui.item,
+                inputvalue: $("#tagsearch").val()
+            }));
+        },
+        select: function( event, ui ) {
+            addFilter('tag', ui.item.original_label);
+        }
+    })
+    .data("autocomplete")._renderItem = function(ul, item) {
+        var _contents = acTemplate({
+            item: item,
+            inputvalue: $("#tagsearch").val()
+        });
+        return $( "<li>" )
+            .data( "item.autocomplete", item )
+            .html( _contents )
+            .appendTo( ul );
+    };
 });
--- a/web/hdalab/templates/base.html	Thu Oct 04 12:25:12 2012 +0200
+++ b/web/hdalab/templates/base.html	Thu Oct 11 15:42:38 2012 +0200
@@ -28,7 +28,6 @@
                 <li><a class="{% block facettes_actif %}{% endblock %}" href="{% url facettes %}">Recherche par facettes</a></li>
 <!--
                 <li><a class="{% block categories_actif %}{% endblock %}" href="{% url categories %}">Catégories de Wikipedia</a></li>
-                <li><a class="{% block completion_actif %}{% endblock %}" href="{% url completion %}">Liste de complétion</a></li>
 -->
             </ul>
             <h1>
--- a/web/hdalab/templates/completion.html	Thu Oct 04 12:25:12 2012 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,85 +0,0 @@
-{% extends "base.html" %}
-
-{% load i18n %}
-
-{% block title %}{{block.super}} &gt; {% trans "Recherche par liste de completion" %}{% endblock %}
-
-{% block css_import %}
-{{block.super}}
-        <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}hdalab/lib/leaflet/leaflet.css" />
-        <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}hdalab/css/ui-lightness/jquery-ui-1.8.16.custom.css" />
-        <link rel="stylesheet" type="text/css" href="{{STATIC_URL}}hdalab/css/completion.css" />
-{% endblock %}
-
-{% block js_import %}
-{{block.super}}
-        <script src="{{STATIC_URL}}hdalab/lib/raphael-min.js"></script>
-        <script src="{{STATIC_URL}}hdalab/lib/underscore-min.js"></script>
-        <script src="{{STATIC_URL}}hdalab/lib/jquery-ui-1.8.16.custom.min.js"></script>
-
-        <script src="{% url jsi18n 'hdalab' %}"></script>
-        <script src="{{STATIC_URL}}hdalab/js/completion.js?v=130829"></script>
-        
-        <script type="text/javascript">
-        gomNs.languageCode = '{{LANGUAGE_CODE}}';
-        gomNs.urls = {
-            'contentsbytag': "{% url contentsbytag %}",
-            'tag_search': "{% url tag_search %}"
-        };
-        </script>
-{% endblock %}
-
-{% block completion_actif %}actif{% endblock %}
-
-{% block main_content %}
-        <div id="titlebar">
-            <div id="titleleft">
-                <h2 id="hdatitle">{% trans "Recherche par liste de completion" %}&nbsp;</h2>
-            </div>
-            <div id="titleright">
-                <div id='langselect'>
-                    <form action="{% url django.views.i18n.set_language %}" method="post" id="lang_form">
-                    {% csrf_token %}
-                        <!--input name="next" type="hidden" value="" /-->
-                        {% get_language_info_list for LANGUAGES as languages %}
-                        {% for language in languages %}
-                            <input type="submit" name="language" class="langbutton{% if language.code == LANGUAGE_CODE %} selected{% endif %}" style="background-image: url({{STATIC_URL}}hdalab/img/flag_{{ language.code }}.png)" value="{{ language.code }}" title="{{ language.name_local }}" />
-                        {% endfor %}
-                    </form>
-                </div>
-            </div>
-        </div>
-        <div id="columns">
-            <div id="leftcol">
-                <div class="bloc" id="bloc_taginfo">
-                    <div class="barrebloc">
-                        <h2>{% trans "Rechercher un tag" %}</h2>
-                    </div>
-                    <div class="corpsbloc" id="taginfo">
-                        <form id="tagform">
-                            <input id="tagsearch" placeholder="{% trans "Rechercher un tag" %}" />
-                        </form>
-                        <div class="wpinfo">
-                            
-                        </div>
-                    </div>
-                </div>
-                <div class="bloc" id="bloc_translationinfo">
-                {% trans "translation_info" %}
-                </div>
-            </div>
-            <div id="rightcol">
-                <div class="bloc" id="bloc_notices">
-                    <div class="barrebloc">
-                        <h2>{% trans "Resultats de recherche" %}</h2>
-                    </div>
-                    <div class="corpsbloc">
-                        <div id="contentcount"></div>
-                        <div id="contents"></div>
-                    </div>
-                </div>
-            </div>
-        </div>
-    </div>
-
-{% endblock %}
--- a/web/hdalab/templates/facettes.html	Thu Oct 04 12:25:12 2012 +0200
+++ b/web/hdalab/templates/facettes.html	Thu Oct 11 15:42:38 2012 +0200
@@ -28,6 +28,7 @@
             'filter': "{% url filter %}",
             'session_info': "{% url session_info %}",
             'countries': "{{STATIC_URL}}hdalab/lib/countries.geo.json",
+            'tag_search': "{% url tag_search %}"
         };
         ZeroClipboard.setMoviePath('{{STATIC_URL}}hdalab/lib/ZeroClipboard.swf');
         </script>
@@ -118,6 +119,19 @@
                 <div class="corpsbloc" id="tagcloud">
                 </div>
             </div>
+            <div class="bloc" id="bloc_taginfo">
+                <div class="barrebloc">
+                    <h2>{% trans "Rechercher un tag" %}</h2>
+                </div>
+                <div class="corpsbloc" id="taginfo">
+                    <form id="tagform">
+                        <input id="tagsearch" placeholder="{% trans "Rechercher un tag" %}" />
+                    </form>
+                    <div class="wpinfo">
+                        
+                    </div>
+                </div>
+            </div>
             <div class="bloc" id="bloc_translationinfo">
             {% trans "translation_info" %}
             </div>
--- a/web/hdalab/urls.py	Thu Oct 04 12:25:12 2012 +0200
+++ b/web/hdalab/urls.py	Thu Oct 11 15:42:38 2012 +0200
@@ -25,7 +25,6 @@
     
     url(r'^facettes/', TemplateView.as_view(template_name="facettes.html"), name='facettes'),
     url(r'^categories/', TemplateView.as_view(template_name="categories.html"), name='categories'),
-    url(r'^completion/', TemplateView.as_view(template_name="completion.html"), name='completion'),
     url(r'^$', TemplateView.as_view(template_name="index.html"), name='home'),
 
 )
@@ -37,5 +36,4 @@
     (r'^a/catsearch$', 'catsearch', {}, 'cat_search'),
     (r'^a/cattree$', 'cattree', {}, 'cat_tree'),
     (r'^a/filltree$', 'filltree', {}, 'fill_tree'),
-    (r'^a/contentsbytag$', 'contentsbytag', {}, 'contentsbytag'),
 )
--- a/web/hdalab/views/ajax.py	Thu Oct 04 12:25:12 2012 +0200
+++ b/web/hdalab/views/ajax.py	Thu Oct 11 15:42:38 2012 +0200
@@ -423,72 +423,14 @@
         
     return HttpResponse(content=outputstr, mimetype='application/json')
 
-def contentsbytag(request):
-    
-    lang = request.GET.get('lang',request.LANGUAGE_CODE)
-    label = request.GET.get('label', None).strip().lower()
-    max_tag_order = int(request.GET.get('mto', '30'))
-    content_count = int(request.GET.get('contentcount', '30'))
-    
-    cache_key = fix_cache_key("contentsbytag-%s"%unicode(label).encode("utf-8"))
-    
-    outputstr = cache.get(cache_key)
-    
-    if outputstr is None:
-        
-        matchtagids = []
-        
-        contentqs = Datasheet.objects.filter(validated=True)
-        
-        no_translate_langs = [ 'fr' ]
-        if lang in no_translate_langs:
-            tagsqs = Tag.objects.filter( label__iexact = label )
-        else:
-            tagsqs = Tag.objects.select_related('dbpedia_fields').filter(dbpedia_fields__translations__label__iexact = label, dbpedia_fields__translations__language_code=lang)
-            
-        contentqs = contentqs.select_related('taggedsheet__tag').filter(taggedsheet__tag__in=tagsqs).distinct()
-        
-        cont_count = contentqs.count()
-        
-        contenus = dict([(content.id, {'score' : 0, 'tags' : [], 'id':content.id, 'title': content.title, 'description': content.description, 'url': content.url}) for content in contentqs[0:content_count]])
-        contentids = contenus.keys()
-        
-        qs = DatasheetExtras.objects.select_related('insee').filter(datasheet__in = contentids)
-        for dse in qs:
-            contenus[dse.datasheet_id]['coords'] = {'city_name': dse.insee.city_name, 'latitude': dse.insee.latitude, 'longitude': dse.insee.longitude}
-        
-        qs = list(TaggedSheet.objects.select_related('tag', 'tag__dbpedia_fields').filter(datasheet__in = contentids).order_by('order'))
-        
-        if lang in no_translate_langs:
-            translations = {}
-        else:
-            transqs = DbpediaFieldsTranslation.objects.filter(master__in = [ts.tag.dbpedia_fields for ts in qs], language_code = lang)
-            translations = dict([(trans.master_id,trans.label) for trans in transqs])
-        
-        for ts in qs:
-            translated_label = translations.get(ts.tag.dbpedia_fields.id, ts.tag.label) if ts.tag.dbpedia_fields is not None else ts.tag.label
-            match_tag = ( label == translated_label.lower() )
-            contenus[ts.datasheet_id]['tags'].append({'id': ts.tag.id, 'label':ts.tag.label, 'order':ts.order, 'match': match_tag , 'translated_label': translated_label})
-            
-            if match_tag:
-                contenus[ts.datasheet_id]['score'] += 2*max_tag_order - ts.order
-            
-        contenus = sorted(contenus.values(),key=lambda e: -e['score'])
-        
-        output = {'count': cont_count, 'contents': contenus}
-        outputstr = json.dumps(output)
-        cache.set(cache_key, outputstr)
-        
-    return HttpResponse(content=outputstr, mimetype='application/json')
-
 def subtree(tree):
-    MAX_TAG_ORDER = 8
+    MAX_TAG_ORDER = 16
     label = tree['label']
     sub = tree.get('contents',[])
     
     datasheets = Datasheet.objects.filter(validated = True, taggedsheet__tag__label__iexact = label, taggedsheet__order__lte = MAX_TAG_ORDER).annotate(tagorder=Min('taggedsheet__order')).select_related('organisation').distinct()
     
-    contents = [{ 'description': ds.description, 'title': ds.title, 'url': ds.url, 'score': MAX_TAG_ORDER - ds.tagorder, 'id': ds.id, 'hda_id': ds.hda_id, 'organization': ds.organisation.name } for ds in datasheets]
+    contents = [{ 'description': ds.description, 'title': ds.title, 'url': ds.url, 'score': int((MAX_TAG_ORDER - ds.tagorder)/2), 'id': ds.id, 'hda_id': ds.hda_id, 'organization': ds.organisation.name } for ds in datasheets]
     
     contents = sorted(contents, key=lambda e: -e['score'])