This repository has been archived on 2024-01-26. You can view files and clone it, but cannot push or open issues or pull requests.
calcifer/web/semantic/dist/components/search.js

1346 lines
43 KiB
JavaScript
Raw Normal View History

2015-03-29 19:33:23 +02:00
/*!
2016-06-10 00:34:34 +02:00
* # Semantic UI 2.1.7 - Search
2015-03-29 19:33:23 +02:00
* http://github.com/semantic-org/semantic-ui/
*
*
2016-06-10 00:34:34 +02:00
* Copyright 2015 Contributors
2015-03-29 19:33:23 +02:00
* Released under the MIT license
* http://opensource.org/licenses/MIT
*
*/
;(function ($, window, document, undefined) {
"use strict";
$.fn.search = function(parameters) {
var
$allModules = $(this),
moduleSelector = $allModules.selector || '',
time = new Date().getTime(),
performance = [],
query = arguments[0],
methodInvoked = (typeof query == 'string'),
queryArguments = [].slice.call(arguments, 1),
returnedValue
;
$(this)
.each(function() {
var
2016-06-10 00:34:34 +02:00
settings = ( $.isPlainObject(parameters) )
? $.extend(true, {}, $.fn.search.settings, parameters)
: $.extend({}, $.fn.search.settings),
2015-03-29 19:33:23 +02:00
className = settings.className,
metadata = settings.metadata,
regExp = settings.regExp,
2016-06-10 00:34:34 +02:00
fields = settings.fields,
2015-03-29 19:33:23 +02:00
selector = settings.selector,
error = settings.error,
namespace = settings.namespace,
eventNamespace = '.' + namespace,
moduleNamespace = namespace + '-module',
$module = $(this),
$prompt = $module.find(selector.prompt),
$searchButton = $module.find(selector.searchButton),
$results = $module.find(selector.results),
$result = $module.find(selector.result),
$category = $module.find(selector.category),
element = this,
instance = $module.data(moduleNamespace),
module
;
2016-06-10 00:34:34 +02:00
2015-03-29 19:33:23 +02:00
module = {
initialize: function() {
module.verbose('Initializing module');
2016-06-10 00:34:34 +02:00
module.determine.searchFields();
module.bind.events();
module.set.type();
module.create.results();
2015-03-29 19:33:23 +02:00
module.instantiate();
},
instantiate: function() {
module.verbose('Storing instance of module', module);
instance = module;
$module
.data(moduleNamespace, module)
;
},
destroy: function() {
module.verbose('Destroying instance');
$module
.off(eventNamespace)
2016-06-10 00:34:34 +02:00
.removeData(moduleNamespace)
2015-03-29 19:33:23 +02:00
;
},
2016-06-10 00:34:34 +02:00
bind: {
events: function() {
module.verbose('Binding events to search');
if(settings.automatic) {
$module
.on(module.get.inputEvent() + eventNamespace, selector.prompt, module.event.input)
;
$prompt
.attr('autocomplete', 'off')
;
}
$module
// prompt
.on('focus' + eventNamespace, selector.prompt, module.event.focus)
.on('blur' + eventNamespace, selector.prompt, module.event.blur)
.on('keydown' + eventNamespace, selector.prompt, module.handleKeyboard)
// search button
.on('click' + eventNamespace, selector.searchButton, module.query)
// results
.on('mousedown' + eventNamespace, selector.results, module.event.result.mousedown)
.on('mouseup' + eventNamespace, selector.results, module.event.result.mouseup)
.on('click' + eventNamespace, selector.result, module.event.result.click)
;
}
},
determine: {
searchFields: function() {
// this makes sure $.extend does not add specified search fields to default fields
// this is the only setting which should not extend defaults
if(parameters && parameters.searchFields !== undefined) {
settings.searchFields = parameters.searchFields;
}
}
},
2015-03-29 19:33:23 +02:00
event: {
2016-06-10 00:34:34 +02:00
input: function() {
clearTimeout(module.timer);
module.timer = setTimeout(module.query, settings.searchDelay);
},
2015-03-29 19:33:23 +02:00
focus: function() {
module.set.focus();
if( module.has.minimumCharacters() ) {
2016-06-10 00:34:34 +02:00
module.query();
if( module.can.show() ) {
module.showResults();
}
2015-03-29 19:33:23 +02:00
}
},
blur: function(event) {
var
2016-06-10 00:34:34 +02:00
pageLostFocus = (document.activeElement === this),
callback = function() {
module.cancel.query();
module.remove.focus();
module.timer = setTimeout(module.hideResults, settings.hideDelay);
}
2015-03-29 19:33:23 +02:00
;
2016-06-10 00:34:34 +02:00
if(pageLostFocus) {
return;
}
if(module.resultsClicked) {
module.debug('Determining if user action caused search to close');
$module
.one('click', selector.results, function(event) {
if( !module.is.animating() && !module.is.hidden() ) {
callback();
}
})
;
}
else {
module.debug('Input blurred without user action, closing results');
callback();
2015-03-29 19:33:23 +02:00
}
},
result: {
mousedown: function() {
module.resultsClicked = true;
},
mouseup: function() {
module.resultsClicked = false;
},
click: function(event) {
module.debug('Search result selected');
var
$result = $(this),
$title = $result.find(selector.title).eq(0),
$link = $result.find('a[href]').eq(0),
href = $link.attr('href') || false,
target = $link.attr('target') || false,
title = $title.html(),
2016-06-10 00:34:34 +02:00
// title is used for result lookup
value = ($title.length > 0)
2015-03-29 19:33:23 +02:00
? $title.text()
: false,
results = module.get.results(),
2016-06-10 00:34:34 +02:00
result = $result.data(metadata.result) || module.get.result(value, results),
2015-03-29 19:33:23 +02:00
returnedValue
;
if( $.isFunction(settings.onSelect) ) {
if(settings.onSelect.call(element, result, results) === false) {
module.debug('Custom onSelect callback cancelled default select action');
return;
}
}
module.hideResults();
2016-06-10 00:34:34 +02:00
if(value) {
module.set.value(value);
2015-03-29 19:33:23 +02:00
}
if(href) {
module.verbose('Opening search link found in result', $link);
if(target == '_blank' || event.ctrlKey) {
window.open(href);
}
else {
window.location.href = (href);
}
}
}
}
},
handleKeyboard: function(event) {
var
// force selector refresh
$result = $module.find(selector.result),
$category = $module.find(selector.category),
currentIndex = $result.index( $result.filter('.' + className.active) ),
resultSize = $result.length,
keyCode = event.which,
keys = {
backspace : 8,
enter : 13,
escape : 27,
upArrow : 38,
downArrow : 40
},
newIndex
;
// search shortcuts
if(keyCode == keys.escape) {
module.verbose('Escape key pressed, blurring search field');
2016-06-10 00:34:34 +02:00
module.trigger.blur();
2015-03-29 19:33:23 +02:00
}
if( module.is.visible() ) {
if(keyCode == keys.enter) {
module.verbose('Enter key pressed, selecting active result');
if( $result.filter('.' + className.active).length > 0 ) {
module.event.result.click.call($result.filter('.' + className.active), event);
event.preventDefault();
return false;
}
}
else if(keyCode == keys.upArrow) {
module.verbose('Up key pressed, changing active result');
newIndex = (currentIndex - 1 < 0)
? currentIndex
: currentIndex - 1
;
$category
.removeClass(className.active)
;
$result
.removeClass(className.active)
.eq(newIndex)
.addClass(className.active)
.closest($category)
.addClass(className.active)
;
event.preventDefault();
}
else if(keyCode == keys.downArrow) {
module.verbose('Down key pressed, changing active result');
newIndex = (currentIndex + 1 >= resultSize)
? currentIndex
: currentIndex + 1
;
$category
.removeClass(className.active)
;
$result
.removeClass(className.active)
.eq(newIndex)
.addClass(className.active)
.closest($category)
.addClass(className.active)
;
event.preventDefault();
}
}
else {
// query shortcuts
if(keyCode == keys.enter) {
module.verbose('Enter key pressed, executing query');
module.query();
module.set.buttonPressed();
$prompt.one('keyup', module.remove.buttonFocus);
}
}
},
setup: {
api: function() {
var
apiSettings = {
2016-06-10 00:34:34 +02:00
debug : settings.debug,
2015-03-29 19:33:23 +02:00
on : false,
2016-06-10 00:34:34 +02:00
cache : 'local',
2015-03-29 19:33:23 +02:00
action : 'search',
2016-06-10 00:34:34 +02:00
onError : module.error
2015-03-29 19:33:23 +02:00
},
searchHTML
;
module.verbose('First request, initializing API');
$module.api(apiSettings);
}
},
can: {
useAPI: function() {
return $.fn.api !== undefined;
},
2016-06-10 00:34:34 +02:00
show: function() {
return module.is.focused() && !module.is.visible() && !module.is.empty();
},
2015-03-29 19:33:23 +02:00
transition: function() {
return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
}
},
is: {
2016-06-10 00:34:34 +02:00
animating: function() {
return $results.hasClass(className.animating);
},
hidden: function() {
return $results.hasClass(className.hidden);
},
2015-03-29 19:33:23 +02:00
empty: function() {
return ($results.html() === '');
},
visible: function() {
return ($results.filter(':visible').length > 0);
},
focused: function() {
return ($prompt.filter(':focus').length > 0);
}
},
2016-06-10 00:34:34 +02:00
trigger: {
blur: function() {
var
events = document.createEvent('HTMLEvents'),
promptElement = $prompt[0]
;
if(promptElement) {
module.verbose('Triggering native blur event');
events.initEvent('blur', false, false);
promptElement.dispatchEvent(events);
}
}
},
2015-03-29 19:33:23 +02:00
get: {
2016-06-10 00:34:34 +02:00
inputEvent: function() {
var
prompt = $prompt[0],
inputEvent = (prompt !== undefined && prompt.oninput !== undefined)
? 'input'
: (prompt !== undefined && prompt.onpropertychange !== undefined)
? 'propertychange'
: 'keyup'
;
return inputEvent;
},
2015-03-29 19:33:23 +02:00
value: function() {
return $prompt.val();
},
results: function() {
var
results = $module.data(metadata.results)
;
return results;
},
result: function(value, results) {
var
2016-06-10 00:34:34 +02:00
lookupFields = ['title', 'id'],
result = false
;
value = (value !== undefined)
? value
: module.get.value()
;
results = (results !== undefined)
? results
: module.get.results()
2015-03-29 19:33:23 +02:00
;
if(settings.type === 'category') {
module.debug('Finding result that matches', value);
$.each(results, function(index, category) {
if($.isArray(category.results)) {
2016-06-10 00:34:34 +02:00
result = module.search.object(value, category.results, lookupFields)[0];
// don't continue searching if a result is found
if(result) {
return false;
2015-03-29 19:33:23 +02:00
}
}
});
}
else {
module.debug('Finding result in results object', value);
2016-06-10 00:34:34 +02:00
result = module.search.object(value, results, lookupFields)[0];
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
return result || false;
2015-03-29 19:33:23 +02:00
},
},
set: {
focus: function() {
$module.addClass(className.focus);
},
loading: function() {
$module.addClass(className.loading);
},
value: function(value) {
module.verbose('Setting search input value', value);
2016-06-10 00:34:34 +02:00
$prompt
.val(value)
;
},
type: function(type) {
type = type || settings.type;
if(settings.type == 'category') {
$module.addClass(settings.type);
}
2015-03-29 19:33:23 +02:00
},
buttonPressed: function() {
$searchButton.addClass(className.pressed);
}
},
remove: {
loading: function() {
$module.removeClass(className.loading);
},
focus: function() {
$module.removeClass(className.focus);
},
buttonPressed: function() {
$searchButton.removeClass(className.pressed);
}
},
query: function() {
var
searchTerm = module.get.value(),
cache = module.read.cache(searchTerm)
;
2016-06-10 00:34:34 +02:00
if( module.has.minimumCharacters() ) {
if(cache) {
module.debug('Reading result from cache', searchTerm);
module.save.results(cache.results);
module.addResults(cache.html);
module.inject.id(cache.results);
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
else {
module.debug('Querying for', searchTerm);
if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
module.search.local(searchTerm);
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
else if( module.can.useAPI() ) {
2015-03-29 19:33:23 +02:00
module.search.remote(searchTerm);
}
else {
2016-06-10 00:34:34 +02:00
module.error(error.source);
2015-03-29 19:33:23 +02:00
}
}
settings.onSearchQuery.call(element, searchTerm);
}
2016-06-10 00:34:34 +02:00
else {
module.hideResults();
}
2015-03-29 19:33:23 +02:00
},
search: {
local: function(searchTerm) {
var
2016-06-10 00:34:34 +02:00
results = module.search.object(searchTerm, settings.content),
2015-03-29 19:33:23 +02:00
searchHTML
;
module.set.loading();
2016-06-10 00:34:34 +02:00
module.save.results(results);
module.debug('Returned local search results', results);
2015-03-29 19:33:23 +02:00
searchHTML = module.generateResults({
2016-06-10 00:34:34 +02:00
results: results
2015-03-29 19:33:23 +02:00
});
module.remove.loading();
2016-06-10 00:34:34 +02:00
module.addResults(searchHTML);
module.inject.id(results);
2015-03-29 19:33:23 +02:00
module.write.cache(searchTerm, {
html : searchHTML,
2016-06-10 00:34:34 +02:00
results : results
2015-03-29 19:33:23 +02:00
});
},
remote: function(searchTerm) {
var
apiSettings = {
onSuccess : function(response) {
module.parse.response.call(element, response, searchTerm);
},
2016-06-10 00:34:34 +02:00
onFailure: function() {
module.displayMessage(error.serverError);
},
2015-03-29 19:33:23 +02:00
urlData: {
query: searchTerm
}
}
;
if( !$module.api('get request') ) {
module.setup.api();
}
$.extend(true, apiSettings, settings.apiSettings);
module.debug('Executing search', apiSettings);
module.cancel.query();
$module
.api('setting', apiSettings)
.api('query')
;
},
2016-06-10 00:34:34 +02:00
object: function(searchTerm, source, searchFields) {
2015-03-29 19:33:23 +02:00
var
2016-06-10 00:34:34 +02:00
results = [],
fuzzyResults = [],
searchExp = searchTerm.toString().replace(regExp.escape, '\\$&'),
matchRegExp = new RegExp(regExp.beginsWith + searchExp, 'i'),
2015-03-29 19:33:23 +02:00
2016-06-10 00:34:34 +02:00
// avoid duplicates when pushing results
addResult = function(array, result) {
var
notResult = ($.inArray(result, results) == -1),
notFuzzyResult = ($.inArray(result, fuzzyResults) == -1)
;
if(notResult && notFuzzyResult) {
array.push(result);
}
}
;
2015-03-29 19:33:23 +02:00
source = source || settings.source;
2016-06-10 00:34:34 +02:00
searchFields = (searchFields !== undefined)
? searchFields
: settings.searchFields
;
2015-03-29 19:33:23 +02:00
2016-06-10 00:34:34 +02:00
// search fields should be array to loop correctly
if(!$.isArray(searchFields)) {
searchFields = [searchFields];
}
// exit conditions if no source
if(source === undefined || source === false) {
2015-03-29 19:33:23 +02:00
module.error(error.source);
return [];
}
2016-06-10 00:34:34 +02:00
// iterate through search fields looking for matches
2015-03-29 19:33:23 +02:00
$.each(searchFields, function(index, field) {
$.each(source, function(label, content) {
var
2016-06-10 00:34:34 +02:00
fieldExists = (typeof content[field] == 'string')
2015-03-29 19:33:23 +02:00
;
2016-06-10 00:34:34 +02:00
if(fieldExists) {
if( content[field].search(matchRegExp) !== -1) {
// content starts with value (first in results)
addResult(results, content);
2015-03-29 19:33:23 +02:00
}
else if(settings.searchFullText && module.fuzzySearch(searchTerm, content[field]) ) {
2016-06-10 00:34:34 +02:00
// content fuzzy matches (last in results)
addResult(fuzzyResults, content);
2015-03-29 19:33:23 +02:00
}
}
});
});
2016-06-10 00:34:34 +02:00
return $.merge(results, fuzzyResults);
2015-03-29 19:33:23 +02:00
}
},
fuzzySearch: function(query, term) {
var
termLength = term.length,
queryLength = query.length
;
2016-06-10 00:34:34 +02:00
if(typeof query !== 'string') {
return false;
}
2015-03-29 19:33:23 +02:00
query = query.toLowerCase();
term = term.toLowerCase();
if(queryLength > termLength) {
return false;
}
if(queryLength === termLength) {
return (query === term);
}
search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
var
queryCharacter = query.charCodeAt(characterIndex)
;
while(nextCharacterIndex < termLength) {
if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
continue search;
}
}
return false;
}
return true;
},
parse: {
response: function(response, searchTerm) {
var
searchHTML = module.generateResults(response)
;
module.verbose('Parsing server response', response);
if(response !== undefined) {
2016-06-10 00:34:34 +02:00
if(searchTerm !== undefined && response[fields.results] !== undefined) {
module.addResults(searchHTML);
module.inject.id(response[fields.results]);
2015-03-29 19:33:23 +02:00
module.write.cache(searchTerm, {
html : searchHTML,
2016-06-10 00:34:34 +02:00
results : response[fields.results]
2015-03-29 19:33:23 +02:00
});
2016-06-10 00:34:34 +02:00
module.save.results(response[fields.results]);
2015-03-29 19:33:23 +02:00
}
}
}
},
cancel: {
query: function() {
if( module.can.useAPI() ) {
$module.api('abort');
}
}
},
has: {
minimumCharacters: function() {
var
searchTerm = module.get.value(),
numCharacters = searchTerm.length
;
return (numCharacters >= settings.minCharacters);
}
},
2016-06-10 00:34:34 +02:00
clear: {
cache: function(value) {
var
cache = $module.data(metadata.cache)
;
if(!value) {
module.debug('Clearing cache', value);
$module.removeData(metadata.cache);
}
else if(value && cache && cache[value]) {
module.debug('Removing value from cache', value);
delete cache[value];
$module.data(metadata.cache, cache);
}
}
},
2015-03-29 19:33:23 +02:00
read: {
cache: function(name) {
var
cache = $module.data(metadata.cache)
;
if(settings.cache) {
module.verbose('Checking cache for generated html for query', name);
return (typeof cache == 'object') && (cache[name] !== undefined)
? cache[name]
: false
;
}
return false;
}
},
2016-06-10 00:34:34 +02:00
create: {
id: function(resultIndex, categoryIndex) {
var
resultID = (resultIndex + 1), // not zero indexed
categoryID = (categoryIndex + 1),
firstCharCode,
letterID,
id
;
if(categoryIndex !== undefined) {
// start char code for "A"
letterID = String.fromCharCode(97 + categoryIndex);
id = letterID + resultID;
module.verbose('Creating category result id', id);
}
else {
id = resultID;
module.verbose('Creating result id', id);
}
return id;
},
results: function() {
if($results.length === 0) {
$results = $('<div />')
.addClass(className.results)
.appendTo($module)
;
}
}
},
inject: {
result: function(result, resultIndex, categoryIndex) {
module.verbose('Injecting result into results');
var
$selectedResult = (categoryIndex !== undefined)
? $results
.children().eq(categoryIndex)
.children(selector.result).eq(resultIndex)
: $results
.children(selector.result).eq(resultIndex)
;
module.verbose('Injecting results metadata', $selectedResult);
$selectedResult
.data(metadata.result, result)
;
},
id: function(results) {
module.debug('Injecting unique ids into results');
var
// since results may be object, we must use counters
categoryIndex = 0,
resultIndex = 0
;
if(settings.type === 'category') {
// iterate through each category result
$.each(results, function(index, category) {
resultIndex = 0;
$.each(category.results, function(index, value) {
var
result = category.results[index]
;
if(result.id === undefined) {
result.id = module.create.id(resultIndex, categoryIndex);
}
module.inject.result(result, resultIndex, categoryIndex);
resultIndex++;
});
categoryIndex++;
});
}
else {
// top level
$.each(results, function(index, value) {
var
result = results[index]
;
if(result.id === undefined) {
result.id = module.create.id(resultIndex);
}
module.inject.result(result, resultIndex);
resultIndex++;
});
}
return results;
}
},
2015-03-29 19:33:23 +02:00
save: {
results: function(results) {
module.verbose('Saving current search results to metadata', results);
$module.data(metadata.results, results);
}
},
write: {
cache: function(name, value) {
var
cache = ($module.data(metadata.cache) !== undefined)
? $module.data(metadata.cache)
: {}
;
if(settings.cache) {
module.verbose('Writing generated html to cache', name, value);
cache[name] = value;
$module
.data(metadata.cache, cache)
;
}
}
},
addResults: function(html) {
if( $.isFunction(settings.onResultsAdd) ) {
if( settings.onResultsAdd.call($results, html) === false ) {
module.debug('onResultsAdd callback cancelled default action');
return false;
}
}
$results
.html(html)
;
2016-06-10 00:34:34 +02:00
if( module.can.show() ) {
module.showResults();
}
2015-03-29 19:33:23 +02:00
},
showResults: function() {
2016-06-10 00:34:34 +02:00
if(!module.is.visible()) {
2015-03-29 19:33:23 +02:00
if( module.can.transition() ) {
module.debug('Showing results with css animations');
$results
.transition({
animation : settings.transition + ' in',
2016-06-10 00:34:34 +02:00
debug : settings.debug,
verbose : settings.verbose,
2015-03-29 19:33:23 +02:00
duration : settings.duration,
queue : true
})
;
}
else {
module.debug('Showing results with javascript');
$results
.stop()
.fadeIn(settings.duration, settings.easing)
;
}
settings.onResultsOpen.call($results);
}
},
hideResults: function() {
if( module.is.visible() ) {
if( module.can.transition() ) {
module.debug('Hiding results with css animations');
$results
.transition({
animation : settings.transition + ' out',
2016-06-10 00:34:34 +02:00
debug : settings.debug,
verbose : settings.verbose,
2015-03-29 19:33:23 +02:00
duration : settings.duration,
queue : true
})
;
}
else {
module.debug('Hiding results with javascript');
$results
.stop()
.fadeOut(settings.duration, settings.easing)
;
}
settings.onResultsClose.call($results);
}
},
generateResults: function(response) {
module.debug('Generating html from response', response);
var
template = settings.templates[settings.type],
2016-06-10 00:34:34 +02:00
isProperObject = ($.isPlainObject(response[fields.results]) && !$.isEmptyObject(response[fields.results])),
isProperArray = ($.isArray(response[fields.results]) && response[fields.results].length > 0),
2015-03-29 19:33:23 +02:00
html = ''
;
if(isProperObject || isProperArray ) {
if(settings.maxResults > 0) {
if(isProperObject) {
if(settings.type == 'standard') {
module.error(error.maxResults);
}
}
else {
2016-06-10 00:34:34 +02:00
response[fields.results] = response[fields.results].slice(0, settings.maxResults);
2015-03-29 19:33:23 +02:00
}
}
if($.isFunction(template)) {
2016-06-10 00:34:34 +02:00
html = template(response, fields);
2015-03-29 19:33:23 +02:00
}
else {
module.error(error.noTemplate, false);
}
}
else {
html = module.displayMessage(error.noResults, 'empty');
}
settings.onResults.call(element, response);
return html;
},
displayMessage: function(text, type) {
type = type || 'standard';
module.debug('Displaying message', text, type);
module.addResults( settings.templates.message(text, type) );
return settings.templates.message(text, type);
},
setting: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, settings, name);
}
else if(value !== undefined) {
settings[name] = value;
}
else {
return settings[name];
}
},
internal: function(name, value) {
if( $.isPlainObject(name) ) {
$.extend(true, module, name);
}
else if(value !== undefined) {
module[name] = value;
}
else {
return module[name];
}
},
debug: function() {
if(settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.debug.apply(console, arguments);
}
}
},
verbose: function() {
if(settings.verbose && settings.debug) {
if(settings.performance) {
module.performance.log(arguments);
}
else {
module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
module.verbose.apply(console, arguments);
}
}
},
error: function() {
module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
module.error.apply(console, arguments);
},
performance: {
log: function(message) {
var
currentTime,
executionTime,
previousTime
;
if(settings.performance) {
currentTime = new Date().getTime();
previousTime = time || currentTime;
executionTime = currentTime - previousTime;
time = currentTime;
performance.push({
'Name' : message[0],
'Arguments' : [].slice.call(message, 1) || '',
'Element' : element,
'Execution Time' : executionTime
});
}
clearTimeout(module.performance.timer);
2016-06-10 00:34:34 +02:00
module.performance.timer = setTimeout(module.performance.display, 500);
2015-03-29 19:33:23 +02:00
},
display: function() {
var
title = settings.name + ':',
totalTime = 0
;
time = false;
clearTimeout(module.performance.timer);
$.each(performance, function(index, data) {
totalTime += data['Execution Time'];
});
title += ' ' + totalTime + 'ms';
if(moduleSelector) {
title += ' \'' + moduleSelector + '\'';
}
if($allModules.length > 1) {
title += ' ' + '(' + $allModules.length + ')';
}
if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
console.groupCollapsed(title);
if(console.table) {
console.table(performance);
}
else {
$.each(performance, function(index, data) {
console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
});
}
console.groupEnd();
}
performance = [];
}
},
invoke: function(query, passedArguments, context) {
var
object = instance,
maxDepth,
found,
response
;
passedArguments = passedArguments || queryArguments;
context = element || context;
if(typeof query == 'string' && object !== undefined) {
query = query.split(/[\. ]/);
maxDepth = query.length - 1;
$.each(query, function(depth, value) {
var camelCaseValue = (depth != maxDepth)
? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
: query
;
if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
object = object[camelCaseValue];
}
else if( object[camelCaseValue] !== undefined ) {
found = object[camelCaseValue];
return false;
}
else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
object = object[value];
}
else if( object[value] !== undefined ) {
found = object[value];
return false;
}
else {
return false;
}
});
}
if( $.isFunction( found ) ) {
response = found.apply(context, passedArguments);
}
else if(found !== undefined) {
response = found;
}
if($.isArray(returnedValue)) {
returnedValue.push(response);
}
else if(returnedValue !== undefined) {
returnedValue = [returnedValue, response];
}
else if(response !== undefined) {
returnedValue = response;
}
return found;
}
};
if(methodInvoked) {
if(instance === undefined) {
module.initialize();
}
module.invoke(query);
}
else {
if(instance !== undefined) {
instance.invoke('destroy');
}
module.initialize();
}
})
;
return (returnedValue !== undefined)
? returnedValue
: this
;
};
$.fn.search.settings = {
2016-06-10 00:34:34 +02:00
name : 'Search',
2015-03-29 19:33:23 +02:00
namespace : 'search',
debug : false,
2016-06-10 00:34:34 +02:00
verbose : false,
2015-03-29 19:33:23 +02:00
performance : true,
type : 'standard',
2016-06-10 00:34:34 +02:00
// template to use (specified in settings.templates)
2015-03-29 19:33:23 +02:00
minCharacters : 1,
2016-06-10 00:34:34 +02:00
// minimum characters required to search
2015-03-29 19:33:23 +02:00
apiSettings : false,
2016-06-10 00:34:34 +02:00
// API config
2015-03-29 19:33:23 +02:00
source : false,
2016-06-10 00:34:34 +02:00
// object to search
2015-03-29 19:33:23 +02:00
searchFields : [
'title',
'description'
],
2016-06-10 00:34:34 +02:00
// fields to search
displayField : '',
// field to display in standard results template
2015-03-29 19:33:23 +02:00
searchFullText : true,
2016-06-10 00:34:34 +02:00
// whether to include fuzzy results in local search
automatic : true,
// whether to add events to prompt automatically
2015-03-29 19:33:23 +02:00
hideDelay : 0,
2016-06-10 00:34:34 +02:00
// delay before hiding menu after blur
searchDelay : 200,
// delay before searching
2015-03-29 19:33:23 +02:00
maxResults : 7,
2016-06-10 00:34:34 +02:00
// maximum results returned from local
2015-03-29 19:33:23 +02:00
cache : true,
2016-06-10 00:34:34 +02:00
// whether to store lookups in local cache
2015-03-29 19:33:23 +02:00
2016-06-10 00:34:34 +02:00
// transition settings
2015-03-29 19:33:23 +02:00
transition : 'scale',
2016-06-10 00:34:34 +02:00
duration : 200,
2015-03-29 19:33:23 +02:00
easing : 'easeOutExpo',
2016-06-10 00:34:34 +02:00
// callbacks
2015-03-29 19:33:23 +02:00
onSelect : false,
onResultsAdd : false,
2016-06-10 00:34:34 +02:00
onSearchQuery : function(query){},
2015-03-29 19:33:23 +02:00
onResults : function(response){},
onResultsOpen : function(){},
onResultsClose : function(){},
className: {
2016-06-10 00:34:34 +02:00
animating : 'animating',
active : 'active',
empty : 'empty',
focus : 'focus',
hidden : 'hidden',
loading : 'loading',
results : 'results',
pressed : 'down'
2015-03-29 19:33:23 +02:00
},
error : {
source : 'Cannot search. No source used, and Semantic API module was not included',
noResults : 'Your search returned no results',
logging : 'Error in debug logging, exiting.',
noEndpoint : 'No search endpoint was specified',
noTemplate : 'A valid template name was not specified.',
2016-06-10 00:34:34 +02:00
serverError : 'There was an issue querying the server.',
2015-03-29 19:33:23 +02:00
maxResults : 'Results must be an array to use maxResults setting',
method : 'The method you called is not defined.'
},
metadata: {
cache : 'cache',
2016-06-10 00:34:34 +02:00
results : 'results',
result : 'result'
2015-03-29 19:33:23 +02:00
},
regExp: {
2016-06-10 00:34:34 +02:00
escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
beginsWith : '(?:\s|^)'
},
// maps api response attributes to internal representation
fields: {
categories : 'results', // array of categories (category view)
categoryName : 'name', // name of category (category view)
categoryResults : 'results', // array of results (category view)
description : 'description', // result description
image : 'image', // result image
price : 'price', // result price
results : 'results', // array of results (standard)
title : 'title', // result title
url : 'url', // result url
action : 'action', // "view more" object name
actionText : 'text', // "view more" text
actionURL : 'url' // "view more" url
2015-03-29 19:33:23 +02:00
},
selector : {
prompt : '.prompt',
searchButton : '.search.button',
results : '.results',
category : '.category',
result : '.result',
title : '.title, .name'
},
templates: {
escape: function(string) {
var
badChars = /[&<>"'`]/g,
shouldEscape = /[&<>"'`]/,
escape = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#x27;",
"`": "&#x60;"
},
escapedChar = function(chr) {
return escape[chr];
}
;
if(shouldEscape.test(string)) {
return string.replace(badChars, escapedChar);
}
return string;
},
message: function(message, type) {
var
html = ''
;
if(message !== undefined && type !== undefined) {
html += ''
+ '<div class="message ' + type + '">'
;
// message type
if(type == 'empty') {
html += ''
+ '<div class="header">No Results</div class="header">'
+ '<div class="description">' + message + '</div class="description">'
;
}
else {
html += ' <div class="description">' + message + '</div>';
}
html += '</div>';
}
return html;
},
2016-06-10 00:34:34 +02:00
category: function(response, fields) {
2015-03-29 19:33:23 +02:00
var
html = '',
escape = $.fn.search.settings.templates.escape
;
2016-06-10 00:34:34 +02:00
if(response[fields.categoryResults] !== undefined) {
2015-03-29 19:33:23 +02:00
// each category
2016-06-10 00:34:34 +02:00
$.each(response[fields.categoryResults], function(index, category) {
if(category[fields.results] !== undefined && category.results.length > 0) {
html += '<div class="category">';
if(category[fields.categoryName] !== undefined) {
html += '<div class="name">' + category[fields.categoryName] + '</div>';
}
2015-03-29 19:33:23 +02:00
// each item inside category
$.each(category.results, function(index, result) {
2016-06-10 00:34:34 +02:00
if(result[fields.url]) {
html += '<a class="result" href="' + result[fields.url] + '">';
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
else {
html += '<a class="result">';
}
if(result[fields.image] !== undefined) {
2015-03-29 19:33:23 +02:00
html += ''
+ '<div class="image">'
2016-06-10 00:34:34 +02:00
+ ' <img src="' + result[fields.image] + '">'
2015-03-29 19:33:23 +02:00
+ '</div>'
;
}
html += '<div class="content">';
2016-06-10 00:34:34 +02:00
if(result[fields.price] !== undefined) {
html += '<div class="price">' + result[fields.price] + '</div>';
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
if(result[fields.title] !== undefined) {
html += '<div class="title">' + result[fields.title] + '</div>';
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
if(result[fields.description] !== undefined) {
html += '<div class="description">' + result[fields.description] + '</div>';
2015-03-29 19:33:23 +02:00
}
html += ''
+ '</div>'
;
2016-06-10 00:34:34 +02:00
html += '</a>';
2015-03-29 19:33:23 +02:00
});
html += ''
+ '</div>'
;
}
});
2016-06-10 00:34:34 +02:00
if(response[fields.action]) {
2015-03-29 19:33:23 +02:00
html += ''
2016-06-10 00:34:34 +02:00
+ '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
+ response[fields.action][fields.actionText]
2015-03-29 19:33:23 +02:00
+ '</a>';
}
return html;
}
return false;
},
2016-06-10 00:34:34 +02:00
standard: function(response, fields) {
2015-03-29 19:33:23 +02:00
var
html = ''
;
2016-06-10 00:34:34 +02:00
if(response[fields.results] !== undefined) {
2015-03-29 19:33:23 +02:00
// each result
2016-06-10 00:34:34 +02:00
$.each(response[fields.results], function(index, result) {
if(result[fields.url]) {
html += '<a class="result" href="' + result[fields.url] + '">';
2015-03-29 19:33:23 +02:00
}
else {
html += '<a class="result">';
}
2016-06-10 00:34:34 +02:00
if(result[fields.image] !== undefined) {
2015-03-29 19:33:23 +02:00
html += ''
+ '<div class="image">'
2016-06-10 00:34:34 +02:00
+ ' <img src="' + result[fields.image] + '">'
2015-03-29 19:33:23 +02:00
+ '</div>'
;
}
html += '<div class="content">';
2016-06-10 00:34:34 +02:00
if(result[fields.price] !== undefined) {
html += '<div class="price">' + result[fields.price] + '</div>';
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
if(result[fields.title] !== undefined) {
html += '<div class="title">' + result[fields.title] + '</div>';
2015-03-29 19:33:23 +02:00
}
2016-06-10 00:34:34 +02:00
if(result[fields.description] !== undefined) {
html += '<div class="description">' + result[fields.description] + '</div>';
2015-03-29 19:33:23 +02:00
}
html += ''
+ '</div>'
;
html += '</a>';
});
2016-06-10 00:34:34 +02:00
if(response[fields.action]) {
2015-03-29 19:33:23 +02:00
html += ''
2016-06-10 00:34:34 +02:00
+ '<a href="' + response[fields.action][fields.actionURL] + '" class="action">'
+ response[fields.action][fields.actionText]
2015-03-29 19:33:23 +02:00
+ '</a>';
}
return html;
}
return false;
}
}
};
2016-06-10 00:34:34 +02:00
})( jQuery, window, document );