Finish autocomplete

This commit is contained in:
Raphael 2011-02-01 11:54:55 -08:00
parent 518642d0d7
commit 7d18e2bcd8
10 changed files with 113 additions and 149 deletions

View file

@ -160,7 +160,7 @@ class Person < ActiveRecord::Base
end end
def as_json(opts={}) def as_json(opts={})
{:id => self.guid, :label => 'giraffes', :name => self.name, :avatar => self.profile.image_url(:thumb_small)} {:id => self.guid, :name => self.name, :avatar => self.profile.image_url(:thumb_small), :url => "/people/#{self.id}"}
end end
protected protected

View file

@ -1,50 +0,0 @@
#content
%h1= @person.name
#content_inner
#i.entity_profile.vcard.author
%h2 User profile
%dl.entity_nickname
%dt Nickname
%dd
%a.nickname.url.uid{:href=>@person.url, :rel=>'me'}= @person.name
%dl.entity_given_name
%dt First name
%dd
%span.given_name= @person.profile.first_name
%dl.entity_family_name
%dt Family name
%dd
%span.family_name= @person.profile.last_name
%dl.entity_fn
%dt Full name
%dd
%span.fn= @person.name
%dl.entity_url
%dt URL
%dd
%a#pod_location.url{:href=>@person.url, :rel=>'me'}= @person.url
%dl.entity_photo
%dt Photo
%dd
%img.photo.avatar{:src=>image_or_default(@person), :width=>'300px', :height=>'300px'}
%dl.entity_photo_medium
%dt Photo
%dd
%img.photo.avatar{:src=>image_or_default(@person, :thumb_medium), :width=>'100px', :height=>'100px'}
%dl.entity_photo_small
%dt Photo
%dd
%img.photo.avatar{:src=>image_or_default(@person, :thumb_small), :width=>'50px', :height=>'50px'}
%dl.entity_searchable
%dt Searchable
%dd
%span.searchable= @person.profile.searchable

View file

@ -11,11 +11,11 @@ javascripts:
- public/javascripts/vendor/jquery.hotkeys.js - public/javascripts/vendor/jquery.hotkeys.js
- public/javascripts/vendor/jquery.autoresize.min.js - public/javascripts/vendor/jquery.autoresize.min.js
- public/javascripts/vendor/jquery.infinitescroll.min.js - public/javascripts/vendor/jquery.infinitescroll.min.js
- public/javascripts/vendor/jquery.autocomplete.js
- public/javascripts/vendor/facebox.js - public/javascripts/vendor/facebox.js
- public/javascripts/vendor/timeago.js - public/javascripts/vendor/timeago.js
- public/javascripts/vendor/fileuploader.js - public/javascripts/vendor/fileuploader.js
- public/javascripts/vendor/Mustache.js - public/javascripts/vendor/Mustache.js
- public/javascripts/jquery.autocomplete-custom.js
- public/javascripts/diaspora.js - public/javascripts/diaspora.js
- public/javascripts/widgets/i18n.js - public/javascripts/widgets/i18n.js
- public/javascripts/widgets/alert.js - public/javascripts/widgets/alert.js

View file

@ -30,5 +30,8 @@ $(document).ready(function() {
$('a').live('tap',function(){ $('a').live('tap',function(){
$(this).addClass('tapped'); $(this).addClass('tapped');
}) })
// autocomplete search box
Search.initialize();
}); });

View file

@ -8,11 +8,11 @@
* http://www.gnu.org/licenses/gpl.html * http://www.gnu.org/licenses/gpl.html
* *
* Revision: $Id: jquery.autocomplete.js 5785 2008-07-12 10:37:33Z joern.zaefferer $ * Revision: $Id: jquery.autocomplete.js 5785 2008-07-12 10:37:33Z joern.zaefferer $
* * Modified by Diaspora
*/ */
;(function($) { ;(function($) {
$.fn.extend({ $.fn.extend({
autocomplete: function(urlOrData, options) { autocomplete: function(urlOrData, options) {
var isUrl = typeof urlOrData == "string"; var isUrl = typeof urlOrData == "string";
@ -22,13 +22,13 @@ $.fn.extend({
delay: isUrl ? $.Autocompleter.defaults.delay : 10, delay: isUrl ? $.Autocompleter.defaults.delay : 10,
max: options && !options.scroll ? 10 : 150 max: options && !options.scroll ? 10 : 150
}, options); }, options);
// if highlight is set to false, replace it with a do-nothing function // if highlight is set to false, replace it with a do-nothing function
options.highlight = options.highlight || function(value) { return value; }; options.highlight = options.highlight || function(value) { return value; };
// if the formatMatch option is not specified, then use formatItem for backwards compatibility // if the formatMatch option is not specified, then use formatItem for backwards compatibility
options.formatMatch = options.formatMatch || options.formatItem; options.formatMatch = options.formatMatch || options.formatItem;
return this.each(function() { return this.each(function() {
new $.Autocompleter(this, options); new $.Autocompleter(this, options);
}); });
@ -77,9 +77,9 @@ $.Autocompleter = function(input, options) {
mouseDownOnSelect: false mouseDownOnSelect: false
}; };
var select = $.Autocompleter.Select(options, input, selectCurrent, config); var select = $.Autocompleter.Select(options, input, selectCurrent, config);
var blockSubmit; var blockSubmit;
// prevent form submit in opera when selecting with return key // prevent form submit in opera when selecting with return key
$.browser.opera && $(input.form).bind("submit.autocomplete", function() { $.browser.opera && $(input.form).bind("submit.autocomplete", function() {
if (blockSubmit) { if (blockSubmit) {
@ -87,13 +87,13 @@ $.Autocompleter = function(input, options) {
return false; return false;
} }
}); });
// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all // only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) { $input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
// track last key pressed // track last key pressed
lastKeyPressCode = event.keyCode; lastKeyPressCode = event.keyCode;
switch(event.keyCode) { switch(event.keyCode) {
case KEY.UP: case KEY.UP:
event.preventDefault(); event.preventDefault();
if ( select.visible() ) { if ( select.visible() ) {
@ -102,7 +102,7 @@ $.Autocompleter = function(input, options) {
onChange(0, true); onChange(0, true);
} }
break; break;
case KEY.DOWN: case KEY.DOWN:
event.preventDefault(); event.preventDefault();
if ( select.visible() ) { if ( select.visible() ) {
@ -111,7 +111,7 @@ $.Autocompleter = function(input, options) {
onChange(0, true); onChange(0, true);
} }
break; break;
case KEY.PAGEUP: case KEY.PAGEUP:
event.preventDefault(); event.preventDefault();
if ( select.visible() ) { if ( select.visible() ) {
@ -120,7 +120,7 @@ $.Autocompleter = function(input, options) {
onChange(0, true); onChange(0, true);
} }
break; break;
case KEY.PAGEDOWN: case KEY.PAGEDOWN:
event.preventDefault(); event.preventDefault();
if ( select.visible() ) { if ( select.visible() ) {
@ -129,7 +129,7 @@ $.Autocompleter = function(input, options) {
onChange(0, true); onChange(0, true);
} }
break; break;
// matches also semicolon // matches also semicolon
case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA: case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
case KEY.TAB: case KEY.TAB:
@ -141,11 +141,11 @@ $.Autocompleter = function(input, options) {
return false; return false;
} }
break; break;
case KEY.ESC: case KEY.ESC:
select.hide(); select.hide();
break; break;
default: default:
clearTimeout(timeout); clearTimeout(timeout);
timeout = setTimeout(onChange, options.delay); timeout = setTimeout(onChange, options.delay);
@ -196,16 +196,16 @@ $.Autocompleter = function(input, options) {
$input.unbind(); $input.unbind();
$(input.form).unbind(".autocomplete"); $(input.form).unbind(".autocomplete");
}); });
function selectCurrent() { function selectCurrent() {
var selected = select.selected(); var selected = select.selected();
if( !selected ) if( !selected )
return false; return false;
var v = selected.result; var v = selected.result;
previousValue = v; previousValue = v;
if ( options.multiple ) { if ( options.multiple ) {
var words = trimWords($input.val()); var words = trimWords($input.val());
if ( words.length > 1 ) { if ( words.length > 1 ) {
@ -213,26 +213,26 @@ $.Autocompleter = function(input, options) {
} }
v += options.multipleSeparator; v += options.multipleSeparator;
} }
$input.val(v); $input.val(v);
hideResultsNow(); hideResultsNow();
$input.trigger("result", [selected.data, selected.value]); $input.trigger("result", [selected.data, selected.value]);
return true; return true;
} }
function onChange(crap, skipPrevCheck) { function onChange(crap, skipPrevCheck) {
if( lastKeyPressCode == KEY.DEL ) { if( lastKeyPressCode == KEY.DEL ) {
select.hide(); select.hide();
return; return;
} }
var currentValue = $input.val(); var currentValue = $input.val();
if ( !skipPrevCheck && currentValue == previousValue ) if ( !skipPrevCheck && currentValue == previousValue )
return; return;
previousValue = currentValue; previousValue = currentValue;
currentValue = lastWord(currentValue); currentValue = lastWord(currentValue);
if ( currentValue.length >= options.minChars) { if ( currentValue.length >= options.minChars) {
$input.addClass(options.loadingClass); $input.addClass(options.loadingClass);
@ -244,7 +244,7 @@ $.Autocompleter = function(input, options) {
select.hide(); select.hide();
} }
}; };
function trimWords(value) { function trimWords(value) {
if ( !value ) { if ( !value ) {
return [""]; return [""];
@ -257,14 +257,14 @@ $.Autocompleter = function(input, options) {
}); });
return result; return result;
} }
function lastWord(value) { function lastWord(value) {
if ( !options.multiple ) if ( !options.multiple )
return value; return value;
var words = trimWords(value); var words = trimWords(value);
return words[words.length - 1]; return words[words.length - 1];
} }
// fills in the input box w/the first match (assumed to be the best match) // fills in the input box w/the first match (assumed to be the best match)
// q: the term entered // q: the term entered
// sValue: the first matching result // sValue: the first matching result
@ -330,14 +330,14 @@ $.Autocompleter = function(input, options) {
success(term, data); success(term, data);
// if an AJAX url has been supplied, try loading the data now // if an AJAX url has been supplied, try loading the data now
} else if( (typeof options.url == "string") && (options.url.length > 0) ){ } else if( (typeof options.url == "string") && (options.url.length > 0) ){
var extraParams = { var extraParams = {
timestamp: +new Date() timestamp: +new Date()
}; };
$.each(options.extraParams, function(key, param) { $.each(options.extraParams, function(key, param) {
extraParams[key] = typeof param == "function" ? param() : param; extraParams[key] = typeof param == "function" ? param() : param;
}); });
$.ajax({ $.ajax({
// try to leverage ajaxQueue plugin to abort previous requests // try to leverage ajaxQueue plugin to abort previous requests
mode: "abort", mode: "abort",
@ -361,7 +361,7 @@ $.Autocompleter = function(input, options) {
failure(term); failure(term);
} }
}; };
function parse(data) { function parse(data) {
var parsed = []; var parsed = [];
var rows = data.split("\n"); var rows = data.split("\n");
@ -400,6 +400,7 @@ $.Autocompleter.defaults = {
extraParams: {}, extraParams: {},
selectFirst: true, selectFirst: true,
formatItem: function(row) { return row[0]; }, formatItem: function(row) { return row[0]; },
selectionChanged : function(newItem) {},
formatMatch: null, formatMatch: null,
autoFill: false, autoFill: false,
width: 0, width: 0,
@ -416,9 +417,9 @@ $.Autocompleter.Cache = function(options) {
var data = {}; var data = {};
var length = 0; var length = 0;
function matchSubset(s, sub) { function matchSubset(s, sub) {
if (!options.matchCase) if (!options.matchCase)
s = s.toLowerCase(); s = s.toLowerCase();
var i = s.indexOf(sub); var i = s.indexOf(sub);
if (options.matchContains == "word"){ if (options.matchContains == "word"){
@ -427,17 +428,17 @@ $.Autocompleter.Cache = function(options) {
if (i == -1) return false; if (i == -1) return false;
return i == 0 || options.matchContains; return i == 0 || options.matchContains;
}; };
function add(q, value) { function add(q, value) {
if (length > options.cacheLength){ if (length > options.cacheLength){
flush(); flush();
} }
if (!data[q]){ if (!data[q]){
length++; length++;
} }
data[q] = value; data[q] = value;
} }
function populate(){ function populate(){
if( !options.data ) return false; if( !options.data ) return false;
// track the matches // track the matches
@ -446,23 +447,23 @@ $.Autocompleter.Cache = function(options) {
// no url was specified, we need to adjust the cache length to make sure it fits the local data store // no url was specified, we need to adjust the cache length to make sure it fits the local data store
if( !options.url ) options.cacheLength = 1; if( !options.url ) options.cacheLength = 1;
// track all options for minChars = 0 // track all options for minChars = 0
stMatchSets[""] = []; stMatchSets[""] = [];
// loop through the array and create a lookup structure // loop through the array and create a lookup structure
for ( var i = 0, ol = options.data.length; i < ol; i++ ) { for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
var rawValue = options.data[i]; var rawValue = options.data[i];
// if rawValue is a string, make an array otherwise just reference the array // if rawValue is a string, make an array otherwise just reference the array
rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue; rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;
var value = options.formatMatch(rawValue, i+1, options.data.length); var value = options.formatMatch(rawValue, i+1, options.data.length);
if ( value === false ) if ( value === false )
continue; continue;
var firstChar = value.charAt(0).toLowerCase(); var firstChar = value.charAt(0).toLowerCase();
// if no lookup array for this character exists, look it up now // if no lookup array for this character exists, look it up now
if( !stMatchSets[firstChar] ) if( !stMatchSets[firstChar] )
stMatchSets[firstChar] = []; stMatchSets[firstChar] = [];
// if the match is a string // if the match is a string
@ -471,7 +472,7 @@ $.Autocompleter.Cache = function(options) {
data: rawValue, data: rawValue,
result: options.formatResult && options.formatResult(rawValue) || value result: options.formatResult && options.formatResult(rawValue) || value
}; };
// push the current match into the set list // push the current match into the set list
stMatchSets[firstChar].push(row); stMatchSets[firstChar].push(row);
@ -489,15 +490,15 @@ $.Autocompleter.Cache = function(options) {
add(i, value); add(i, value);
}); });
} }
// populate any existing data // populate any existing data
setTimeout(populate, 25); setTimeout(populate, 25);
function flush(){ function flush(){
data = {}; data = {};
length = 0; length = 0;
} }
return { return {
flush: flush, flush: flush,
add: add, add: add,
@ -505,7 +506,7 @@ $.Autocompleter.Cache = function(options) {
load: function(q) { load: function(q) {
if (!options.cacheLength || !length) if (!options.cacheLength || !length)
return null; return null;
/* /*
* if dealing w/local data and matchContains than we must make sure * if dealing w/local data and matchContains than we must make sure
* to loop through all the data collections looking for matches * to loop through all the data collections looking for matches
*/ */
@ -525,9 +526,9 @@ $.Autocompleter.Cache = function(options) {
} }
}); });
} }
} }
return csub; return csub;
} else } else
// if the exact item exists, use it // if the exact item exists, use it
if (data[q]){ if (data[q]){
return data[q]; return data[q];
@ -555,7 +556,7 @@ $.Autocompleter.Select = function (options, input, select, config) {
var CLASSES = { var CLASSES = {
ACTIVE: "ac_over" ACTIVE: "ac_over"
}; };
var listItems, var listItems,
active = -1, active = -1,
data, data,
@ -563,7 +564,7 @@ $.Autocompleter.Select = function (options, input, select, config) {
needsInit = true, needsInit = true,
element, element,
list; list;
// Create results // Create results
function init() { function init() {
if (!needsInit) if (!needsInit)
@ -573,11 +574,11 @@ $.Autocompleter.Select = function (options, input, select, config) {
.addClass(options.resultsClass) .addClass(options.resultsClass)
.css("position", "absolute") .css("position", "absolute")
.appendTo(document.body); .appendTo(document.body);
list = $("<ul/>").appendTo(element).mouseover( function(event) { list = $("<ul/>").appendTo(element).mouseover( function(event) {
if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') { if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event)); active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
$(target(event)).addClass(CLASSES.ACTIVE); $(target(event)).addClass(CLASSES.ACTIVE);
} }
}).click(function(event) { }).click(function(event) {
$(target(event)).addClass(CLASSES.ACTIVE); $(target(event)).addClass(CLASSES.ACTIVE);
@ -590,13 +591,13 @@ $.Autocompleter.Select = function (options, input, select, config) {
}).mouseup(function() { }).mouseup(function() {
config.mouseDownOnSelect = false; config.mouseDownOnSelect = false;
}); });
if( options.width > 0 ) if( options.width > 0 )
element.css("width", options.width); element.css("width", options.width);
needsInit = false; needsInit = false;
} }
function target(event) { function target(event) {
var element = event.target; var element = event.target;
while(element && element.tagName != "LI") while(element && element.tagName != "LI")
@ -608,7 +609,7 @@ $.Autocompleter.Select = function (options, input, select, config) {
} }
function moveSelect(step) { function moveSelect(step) {
listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE); listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
movePosition(step); movePosition(step);
var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE); var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
if(options.scroll) { if(options.scroll) {
@ -622,8 +623,9 @@ $.Autocompleter.Select = function (options, input, select, config) {
list.scrollTop(offset); list.scrollTop(offset);
} }
} }
options.selectionChanged(activeItem);
}; };
function movePosition(step) { function movePosition(step) {
active += step; active += step;
if (active < 0) { if (active < 0) {
@ -632,13 +634,13 @@ $.Autocompleter.Select = function (options, input, select, config) {
active = 0; active = 0;
} }
} }
function limitNumberOfItems(available) { function limitNumberOfItems(available) {
return options.max && options.max < available return options.max && options.max < available
? options.max ? options.max
: available; : available;
} }
function fillList() { function fillList() {
list.empty(); list.empty();
var max = limitNumberOfItems(data.length); var max = limitNumberOfItems(data.length);
@ -660,7 +662,7 @@ $.Autocompleter.Select = function (options, input, select, config) {
if ( $.fn.bgiframe ) if ( $.fn.bgiframe )
list.bgiframe(); list.bgiframe();
} }
return { return {
display: function(d, q) { display: function(d, q) {
init(); init();
@ -712,7 +714,7 @@ $.Autocompleter.Select = function (options, input, select, config) {
maxHeight: options.scrollHeight, maxHeight: options.scrollHeight,
overflow: 'auto' overflow: 'auto'
}); });
if($.browser.msie && typeof document.body.style.maxHeight === "undefined") { if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
var listHeight = 0; var listHeight = 0;
listItems.each(function() { listItems.each(function() {
@ -725,7 +727,7 @@ $.Autocompleter.Select = function (options, input, select, config) {
listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) ); listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
} }
} }
} }
}, },
selected: function() { selected: function() {
@ -759,4 +761,4 @@ $.Autocompleter.Selection = function(field, start, end) {
field.focus(); field.focus();
}; };
})(jQuery); })(jQuery);

View file

@ -1,27 +1,51 @@
var Search = { var Search = {
source : '/people.json',
selector : '#global_search input#q',
formatItem: function(row){ formatItem: function(row){
return "<img src='"+"images/user/default.png"+"' class='avatar'/>" + row['name']; if(row['search']) {
return 'Search for ' + row['name'];
} else {
return "<img src='"+ row['avatar'] +"' class='avatar'/>" + row['name'];
}
}, },
formatResult: function(row){ formatResult: function(row){
return row['name']; return row['name'];
}, },
parse : function(data) { parse : function(data) {
return data.map(function(person){ results = data.map(function(person){
return {data : person, value : person['name']} return {data : person, value : person['name']}
}); });
results.push(Search.searchLinkli());
return results;
},
selectItemCallback : function(event, data, formatted) {
$(Search.selector).val(formatted);
window.location = data['url'];
},
options : function(){return {
minChars : 3,
max : 4,
formatItem : Search.formatItem,
formatResult : Search.formatResult,
parse : Search.parse,
};},
searchLinkli : function() {
var searchTerm = $(Search.selector).val();
return {
data : {
'search' : true,
'url' : '/people?q=' + searchTerm,
'name' : searchTerm
},
value : searchTerm
};
},
initialize : function() {
$(Search.selector).autocomplete(Search.source, Search.options());
$(Search.selector).result(Search.selectItemCallback);
} }
} }
$(document).ready(function() {
$('#global_search input').autocomplete('/people.json',
{
minChars : 3,
max : 8,
autoFill : true,
formatItem : Search.formatItem,
formatResult : Search.formatResult,
parse : Search.parse
});
});
//$(":text, textarea").result(findValueCallback).next().click(function() { $(this).prev().search(); });

File diff suppressed because one or more lines are too long

View file

@ -35,7 +35,7 @@ describe ApplicationHelper do
person_image_link(nil).should == "" person_image_link(nil).should == ""
end end
it "returns a link containing the person's photo" do it "returns a link containing the person's photo" do
person_image_link(@person).should include(image_or_default(@person)) person_image_link(@person).should include(@person.profile.image_url)
end end
it "returns a link to the person's profile" do it "returns a link to the person's profile" do
person_image_link(@person).should include(person_path(@person)) person_image_link(@person).should include(person_path(@person))

View file

@ -314,7 +314,7 @@ describe DataConversion::ImportToMysql do
profile = Profile.where(:mongo_id => "4d2b6eb6cc8cb43cc2000001").first profile = Profile.where(:mongo_id => "4d2b6eb6cc8cb43cc2000001").first
profile.image_url_medium.should be_nil profile.image_url_medium.should be_nil
profile.searchable.should == true profile.searchable.should == true
profile.image_url.should be_nil profile[:image_url].should be_nil
profile.gender.should be_nil profile.gender.should be_nil
profile.diaspora_handle.should == profile.person.diaspora_handle profile.diaspora_handle.should == profile.person.diaspora_handle
profile.last_name.should == 'weinstien' profile.last_name.should == 'weinstien'

View file

@ -91,7 +91,7 @@ describe Photo do
@user.profile.image_url = @photo.url(:thumb_large) @user.profile.image_url = @photo.url(:thumb_large)
@user.person.save @user.person.save
@photo.destroy @photo.destroy
Person.find(@user.person.id).profile.image_url.should be_nil Person.find(@user.person.id).profile[:image_url].should be_nil
end end
it 'should not use the imported filename as the url' do it 'should not use the imported filename as the url' do