You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1272 lines
40 KiB

9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /*!
  2. * # Semantic UI 2.0.0 - Search
  3. * http://github.com/semantic-org/semantic-ui/
  4. *
  5. *
  6. * Copyright 2015 Contributors
  7. * Released under the MIT license
  8. * http://opensource.org/licenses/MIT
  9. *
  10. */
  11. ;(function ($, window, document, undefined) {
  12. "use strict";
  13. $.fn.search = function(parameters) {
  14. var
  15. $allModules = $(this),
  16. moduleSelector = $allModules.selector || '',
  17. time = new Date().getTime(),
  18. performance = [],
  19. query = arguments[0],
  20. methodInvoked = (typeof query == 'string'),
  21. queryArguments = [].slice.call(arguments, 1),
  22. returnedValue
  23. ;
  24. $(this)
  25. .each(function() {
  26. var
  27. settings = ( $.isPlainObject(parameters) )
  28. ? $.extend(true, {}, $.fn.search.settings, parameters)
  29. : $.extend({}, $.fn.search.settings),
  30. className = settings.className,
  31. metadata = settings.metadata,
  32. regExp = settings.regExp,
  33. selector = settings.selector,
  34. error = settings.error,
  35. namespace = settings.namespace,
  36. eventNamespace = '.' + namespace,
  37. moduleNamespace = namespace + '-module',
  38. $module = $(this),
  39. $prompt = $module.find(selector.prompt),
  40. $searchButton = $module.find(selector.searchButton),
  41. $results = $module.find(selector.results),
  42. $result = $module.find(selector.result),
  43. $category = $module.find(selector.category),
  44. element = this,
  45. instance = $module.data(moduleNamespace),
  46. module
  47. ;
  48. module = {
  49. initialize: function() {
  50. module.verbose('Initializing module');
  51. module.determine.searchFields();
  52. module.bind.events();
  53. module.set.type();
  54. module.create.results();
  55. module.instantiate();
  56. },
  57. instantiate: function() {
  58. module.verbose('Storing instance of module', module);
  59. instance = module;
  60. $module
  61. .data(moduleNamespace, module)
  62. ;
  63. },
  64. destroy: function() {
  65. module.verbose('Destroying instance');
  66. $module
  67. .off(eventNamespace)
  68. .removeData(moduleNamespace)
  69. ;
  70. },
  71. bind: {
  72. events: function() {
  73. module.verbose('Binding events to search');
  74. if(settings.automatic) {
  75. $module
  76. .on(module.get.inputEvent() + eventNamespace, selector.prompt, module.event.input)
  77. ;
  78. $prompt
  79. .attr('autocomplete', 'off')
  80. ;
  81. }
  82. $module
  83. // prompt
  84. .on('focus' + eventNamespace, selector.prompt, module.event.focus)
  85. .on('blur' + eventNamespace, selector.prompt, module.event.blur)
  86. .on('keydown' + eventNamespace, selector.prompt, module.handleKeyboard)
  87. // search button
  88. .on('click' + eventNamespace, selector.searchButton, module.query)
  89. // results
  90. .on('mousedown' + eventNamespace, selector.results, module.event.result.mousedown)
  91. .on('mouseup' + eventNamespace, selector.results, module.event.result.mouseup)
  92. .on('click' + eventNamespace, selector.result, module.event.result.click)
  93. ;
  94. }
  95. },
  96. determine: {
  97. searchFields: function() {
  98. // this makes sure $.extend does not add specified search fields to default fields
  99. // this is the only setting which should not extend defaults
  100. if(parameters && parameters.searchFields !== undefined) {
  101. settings.searchFields = parameters.searchFields;
  102. }
  103. }
  104. },
  105. event: {
  106. input: function() {
  107. clearTimeout(module.timer);
  108. module.timer = setTimeout(module.query, settings.searchDelay);
  109. },
  110. focus: function() {
  111. module.set.focus();
  112. if( module.has.minimumCharacters() ) {
  113. module.query();
  114. module.showResults();
  115. }
  116. },
  117. blur: function(event) {
  118. var
  119. pageLostFocus = (document.activeElement === this)
  120. ;
  121. if(!pageLostFocus && !module.resultsClicked) {
  122. module.cancel.query();
  123. module.remove.focus();
  124. module.timer = setTimeout(module.hideResults, settings.hideDelay);
  125. }
  126. },
  127. result: {
  128. mousedown: function() {
  129. module.resultsClicked = true;
  130. },
  131. mouseup: function() {
  132. module.resultsClicked = false;
  133. },
  134. click: function(event) {
  135. module.debug('Search result selected');
  136. var
  137. $result = $(this),
  138. $title = $result.find(selector.title).eq(0),
  139. $link = $result.find('a[href]').eq(0),
  140. href = $link.attr('href') || false,
  141. target = $link.attr('target') || false,
  142. title = $title.html(),
  143. // title is used for result lookup
  144. value = ($title.length > 0)
  145. ? $title.text()
  146. : false,
  147. results = module.get.results(),
  148. result = $result.data(metadata.result) || module.get.result(value, results),
  149. returnedValue
  150. ;
  151. if( $.isFunction(settings.onSelect) ) {
  152. if(settings.onSelect.call(element, result, results) === false) {
  153. module.debug('Custom onSelect callback cancelled default select action');
  154. return;
  155. }
  156. }
  157. module.hideResults();
  158. if(value) {
  159. module.set.value(value);
  160. }
  161. if(href) {
  162. module.verbose('Opening search link found in result', $link);
  163. if(target == '_blank' || event.ctrlKey) {
  164. window.open(href);
  165. }
  166. else {
  167. window.location.href = (href);
  168. }
  169. }
  170. }
  171. }
  172. },
  173. handleKeyboard: function(event) {
  174. var
  175. // force selector refresh
  176. $result = $module.find(selector.result),
  177. $category = $module.find(selector.category),
  178. currentIndex = $result.index( $result.filter('.' + className.active) ),
  179. resultSize = $result.length,
  180. keyCode = event.which,
  181. keys = {
  182. backspace : 8,
  183. enter : 13,
  184. escape : 27,
  185. upArrow : 38,
  186. downArrow : 40
  187. },
  188. newIndex
  189. ;
  190. // search shortcuts
  191. if(keyCode == keys.escape) {
  192. module.verbose('Escape key pressed, blurring search field');
  193. $prompt
  194. .trigger('blur')
  195. ;
  196. }
  197. if( module.is.visible() ) {
  198. if(keyCode == keys.enter) {
  199. module.verbose('Enter key pressed, selecting active result');
  200. if( $result.filter('.' + className.active).length > 0 ) {
  201. module.event.result.click.call($result.filter('.' + className.active), event);
  202. event.preventDefault();
  203. return false;
  204. }
  205. }
  206. else if(keyCode == keys.upArrow) {
  207. module.verbose('Up key pressed, changing active result');
  208. newIndex = (currentIndex - 1 < 0)
  209. ? currentIndex
  210. : currentIndex - 1
  211. ;
  212. $category
  213. .removeClass(className.active)
  214. ;
  215. $result
  216. .removeClass(className.active)
  217. .eq(newIndex)
  218. .addClass(className.active)
  219. .closest($category)
  220. .addClass(className.active)
  221. ;
  222. event.preventDefault();
  223. }
  224. else if(keyCode == keys.downArrow) {
  225. module.verbose('Down key pressed, changing active result');
  226. newIndex = (currentIndex + 1 >= resultSize)
  227. ? currentIndex
  228. : currentIndex + 1
  229. ;
  230. $category
  231. .removeClass(className.active)
  232. ;
  233. $result
  234. .removeClass(className.active)
  235. .eq(newIndex)
  236. .addClass(className.active)
  237. .closest($category)
  238. .addClass(className.active)
  239. ;
  240. event.preventDefault();
  241. }
  242. }
  243. else {
  244. // query shortcuts
  245. if(keyCode == keys.enter) {
  246. module.verbose('Enter key pressed, executing query');
  247. module.query();
  248. module.set.buttonPressed();
  249. $prompt.one('keyup', module.remove.buttonFocus);
  250. }
  251. }
  252. },
  253. setup: {
  254. api: function() {
  255. var
  256. apiSettings = {
  257. debug : settings.debug,
  258. on : false,
  259. cache : 'local',
  260. action : 'search',
  261. onError : module.error
  262. },
  263. searchHTML
  264. ;
  265. module.verbose('First request, initializing API');
  266. $module.api(apiSettings);
  267. }
  268. },
  269. can: {
  270. useAPI: function() {
  271. return $.fn.api !== undefined;
  272. },
  273. transition: function() {
  274. return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
  275. }
  276. },
  277. is: {
  278. empty: function() {
  279. return ($results.html() === '');
  280. },
  281. visible: function() {
  282. return ($results.filter(':visible').length > 0);
  283. },
  284. focused: function() {
  285. return ($prompt.filter(':focus').length > 0);
  286. }
  287. },
  288. get: {
  289. inputEvent: function() {
  290. var
  291. prompt = $prompt[0],
  292. inputEvent = (prompt !== undefined && prompt.oninput !== undefined)
  293. ? 'input'
  294. : (prompt !== undefined && prompt.onpropertychange !== undefined)
  295. ? 'propertychange'
  296. : 'keyup'
  297. ;
  298. return inputEvent;
  299. },
  300. value: function() {
  301. return $prompt.val();
  302. },
  303. results: function() {
  304. var
  305. results = $module.data(metadata.results)
  306. ;
  307. return results;
  308. },
  309. result: function(value, results) {
  310. var
  311. lookupFields = ['title', 'id'],
  312. result = false
  313. ;
  314. value = (value !== undefined)
  315. ? value
  316. : module.get.value()
  317. ;
  318. results = (results !== undefined)
  319. ? results
  320. : module.get.results()
  321. ;
  322. if(settings.type === 'category') {
  323. module.debug('Finding result that matches', value);
  324. $.each(results, function(index, category) {
  325. if($.isArray(category.results)) {
  326. result = module.search.object(value, category.results, lookupFields)[0];
  327. // dont continue searching if a result is found
  328. if(result) {
  329. return false;
  330. }
  331. }
  332. });
  333. }
  334. else {
  335. module.debug('Finding result in results object', value);
  336. result = module.search.object(value, results, lookupFields)[0];
  337. }
  338. return result || false;
  339. },
  340. },
  341. set: {
  342. focus: function() {
  343. $module.addClass(className.focus);
  344. },
  345. loading: function() {
  346. $module.addClass(className.loading);
  347. },
  348. value: function(value) {
  349. module.verbose('Setting search input value', value);
  350. $prompt
  351. .val(value)
  352. ;
  353. },
  354. type: function(type) {
  355. type || settings.type;
  356. if(settings.type == 'category') {
  357. $module.addClass(settings.type)
  358. }
  359. },
  360. buttonPressed: function() {
  361. $searchButton.addClass(className.pressed);
  362. }
  363. },
  364. remove: {
  365. loading: function() {
  366. $module.removeClass(className.loading);
  367. },
  368. focus: function() {
  369. $module.removeClass(className.focus);
  370. },
  371. buttonPressed: function() {
  372. $searchButton.removeClass(className.pressed);
  373. }
  374. },
  375. query: function() {
  376. var
  377. searchTerm = module.get.value(),
  378. cache = module.read.cache(searchTerm)
  379. ;
  380. if( module.has.minimumCharacters() ) {
  381. if(cache) {
  382. module.debug('Reading result from cache', searchTerm);
  383. module.save.results(cache.results);
  384. module.addResults(cache.html);
  385. module.inject.id(cache.results);
  386. }
  387. else {
  388. module.debug('Querying for', searchTerm);
  389. if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
  390. module.search.local(searchTerm);
  391. }
  392. else if( module.can.useAPI() ) {
  393. module.search.remote(searchTerm);
  394. }
  395. else {
  396. module.error(error.source);
  397. }
  398. settings.onSearchQuery.call(element, searchTerm);
  399. }
  400. }
  401. else {
  402. module.hideResults();
  403. }
  404. },
  405. search: {
  406. local: function(searchTerm) {
  407. var
  408. results = module.search.object(searchTerm, settings.content),
  409. searchHTML
  410. ;
  411. module.set.loading();
  412. module.save.results(results);
  413. module.debug('Returned local search results', results);
  414. searchHTML = module.generateResults({
  415. results: results
  416. });
  417. module.remove.loading();
  418. module.addResults(searchHTML);
  419. module.inject.id(results);
  420. module.write.cache(searchTerm, {
  421. html : searchHTML,
  422. results : results
  423. });
  424. },
  425. remote: function(searchTerm) {
  426. var
  427. apiSettings = {
  428. onSuccess : function(response) {
  429. module.parse.response.call(element, response, searchTerm);
  430. },
  431. onFailure: function() {
  432. module.displayMessage(error.serverError);
  433. },
  434. urlData: {
  435. query: searchTerm
  436. }
  437. }
  438. ;
  439. if( !$module.api('get request') ) {
  440. module.setup.api();
  441. }
  442. $.extend(true, apiSettings, settings.apiSettings);
  443. module.debug('Executing search', apiSettings);
  444. module.cancel.query();
  445. $module
  446. .api('setting', apiSettings)
  447. .api('query')
  448. ;
  449. },
  450. object: function(searchTerm, source, searchFields) {
  451. var
  452. results = [],
  453. fuzzyResults = [],
  454. searchExp = searchTerm.toString().replace(regExp.escape, '\\$&'),
  455. matchRegExp = new RegExp(regExp.beginsWith + searchExp, 'i'),
  456. // avoid duplicates when pushing results
  457. addResult = function(array, result) {
  458. var
  459. notResult = ($.inArray(result, results) == -1),
  460. notFuzzyResult = ($.inArray(result, fuzzyResults) == -1)
  461. ;
  462. if(notResult && notFuzzyResult) {
  463. array.push(result);
  464. }
  465. }
  466. ;
  467. source = source || settings.source;
  468. searchFields = (searchFields !== undefined)
  469. ? searchFields
  470. : settings.searchFields
  471. ;
  472. // search fields should be array to loop correctly
  473. if(!$.isArray(searchFields)) {
  474. searchFields = [searchFields];
  475. }
  476. // exit conditions if no source
  477. if(source === undefined) {
  478. module.error(error.source);
  479. return [];
  480. }
  481. // iterate through search fields looking for matches
  482. $.each(searchFields, function(index, field) {
  483. $.each(source, function(label, content) {
  484. var
  485. fieldExists = (typeof content[field] == 'string')
  486. ;
  487. if(fieldExists) {
  488. if( content[field].search(matchRegExp) !== -1) {
  489. // content starts with value (first in results)
  490. addResult(results, content);
  491. }
  492. else if(settings.searchFullText && module.fuzzySearch(searchTerm, content[field]) ) {
  493. // content fuzzy matches (last in results)
  494. addResult(fuzzyResults, content);
  495. }
  496. }
  497. });
  498. });
  499. return $.merge(results, fuzzyResults);
  500. }
  501. },
  502. fuzzySearch: function(query, term) {
  503. var
  504. termLength = term.length,
  505. queryLength = query.length
  506. ;
  507. if(typeof query !== 'string') {
  508. return false;
  509. }
  510. query = query.toLowerCase();
  511. term = term.toLowerCase();
  512. if(queryLength > termLength) {
  513. return false;
  514. }
  515. if(queryLength === termLength) {
  516. return (query === term);
  517. }
  518. search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
  519. var
  520. queryCharacter = query.charCodeAt(characterIndex)
  521. ;
  522. while(nextCharacterIndex < termLength) {
  523. if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
  524. continue search;
  525. }
  526. }
  527. return false;
  528. }
  529. return true;
  530. },
  531. parse: {
  532. response: function(response, searchTerm) {
  533. var
  534. searchHTML = module.generateResults(response)
  535. ;
  536. module.verbose('Parsing server response', response);
  537. if(response !== undefined) {
  538. if(searchTerm !== undefined && response.results !== undefined) {
  539. module.addResults(searchHTML);
  540. module.inject.id(response.results);
  541. module.write.cache(searchTerm, {
  542. html : searchHTML,
  543. results : response.results
  544. });
  545. module.save.results(response.results);
  546. }
  547. }
  548. }
  549. },
  550. cancel: {
  551. query: function() {
  552. if( module.can.useAPI() ) {
  553. $module.api('abort');
  554. }
  555. }
  556. },
  557. has: {
  558. minimumCharacters: function() {
  559. var
  560. searchTerm = module.get.value(),
  561. numCharacters = searchTerm.length
  562. ;
  563. return (numCharacters >= settings.minCharacters);
  564. }
  565. },
  566. clear: {
  567. cache: function(value) {
  568. var
  569. cache = $module.data(metadata.cache)
  570. ;
  571. if(!value) {
  572. module.debug('Clearing cache', value);
  573. $module.removeData(metadata.cache);
  574. }
  575. else if(value && cache && cache[value]) {
  576. module.debug('Removing value from cache', value);
  577. delete cache[value];
  578. $module.data(metadata.cache, cache);
  579. }
  580. }
  581. },
  582. read: {
  583. cache: function(name) {
  584. var
  585. cache = $module.data(metadata.cache)
  586. ;
  587. if(settings.cache) {
  588. module.verbose('Checking cache for generated html for query', name);
  589. return (typeof cache == 'object') && (cache[name] !== undefined)
  590. ? cache[name]
  591. : false
  592. ;
  593. }
  594. return false;
  595. }
  596. },
  597. create: {
  598. id: function(resultIndex, categoryIndex) {
  599. var
  600. firstLetterCharCode = 97,
  601. categoryID = (categoryIndex !== undefined)
  602. ? String.fromCharCode(firstLetterCharCode + categoryIndex)
  603. : '',
  604. resultID = resultIndex,
  605. id = categoryID + resultID
  606. ;
  607. module.verbose('Creating unique id', id);
  608. return id;
  609. },
  610. results: function() {
  611. if($results.length === 0) {
  612. $results = $('<div />')
  613. .addClass(className.results)
  614. .appendTo($module)
  615. ;
  616. }
  617. }
  618. },
  619. inject: {
  620. result: function(result, resultID, categoryID) {
  621. module.verbose('Injecting result into results');
  622. var
  623. resultIndex = (resultID - 1),
  624. categoryIndex = (categoryID - 1),
  625. $selectedResult = (categoryID !== undefined)
  626. ? $results
  627. .children().eq(categoryIndex)
  628. .children().eq(resultIndex)
  629. : $results
  630. .children().eq(resultIndex)
  631. ;
  632. module.verbose('Injecting results metadata', $selectedResult);
  633. $selectedResult
  634. .data(metadata.result, result)
  635. ;
  636. },
  637. id: function(results) {
  638. module.debug('Injecting unique ids into results');
  639. var
  640. // since results may be object, we must use counters
  641. categoryIndex = 1,
  642. resultIndex = 1
  643. ;
  644. if(settings.type === 'category') {
  645. // iterate through each category result
  646. resultIndex = 1;
  647. $.each(results, function(index, category) {
  648. $.each(category.results, function(index, value) {
  649. var
  650. result = category.results[index]
  651. ;
  652. if(result.id === undefined) {
  653. result.id = module.create.id(resultIndex, categoryIndex);
  654. }
  655. module.inject.result(result, resultIndex, categoryIndex);
  656. resultIndex++;
  657. });
  658. categoryIndex++;
  659. });
  660. }
  661. else {
  662. // top level
  663. $.each(results, function(index, value) {
  664. var
  665. result = results[index]
  666. ;
  667. if(result.id === undefined) {
  668. result.id = module.create.id(resultIndex);
  669. }
  670. module.inject.result(result, resultIndex);
  671. resultIndex++;
  672. });
  673. }
  674. return results;
  675. }
  676. },
  677. save: {
  678. results: function(results) {
  679. module.verbose('Saving current search results to metadata', results);
  680. $module.data(metadata.results, results);
  681. }
  682. },
  683. write: {
  684. cache: function(name, value) {
  685. var
  686. cache = ($module.data(metadata.cache) !== undefined)
  687. ? $module.data(metadata.cache)
  688. : {}
  689. ;
  690. if(settings.cache) {
  691. module.verbose('Writing generated html to cache', name, value);
  692. cache[name] = value;
  693. $module
  694. .data(metadata.cache, cache)
  695. ;
  696. }
  697. }
  698. },
  699. addResults: function(html) {
  700. if( $.isFunction(settings.onResultsAdd) ) {
  701. if( settings.onResultsAdd.call($results, html) === false ) {
  702. module.debug('onResultsAdd callback cancelled default action');
  703. return false;
  704. }
  705. }
  706. $results
  707. .html(html)
  708. ;
  709. module.showResults();
  710. },
  711. showResults: function() {
  712. if( !module.is.visible() && module.is.focused() && !module.is.empty() ) {
  713. if( module.can.transition() ) {
  714. module.debug('Showing results with css animations');
  715. $results
  716. .transition({
  717. animation : settings.transition + ' in',
  718. debug : settings.debug,
  719. verbose : settings.verbose,
  720. duration : settings.duration,
  721. queue : true
  722. })
  723. ;
  724. }
  725. else {
  726. module.debug('Showing results with javascript');
  727. $results
  728. .stop()
  729. .fadeIn(settings.duration, settings.easing)
  730. ;
  731. }
  732. settings.onResultsOpen.call($results);
  733. }
  734. },
  735. hideResults: function() {
  736. if( module.is.visible() ) {
  737. if( module.can.transition() ) {
  738. module.debug('Hiding results with css animations');
  739. $results
  740. .transition({
  741. animation : settings.transition + ' out',
  742. debug : settings.debug,
  743. verbose : settings.verbose,
  744. duration : settings.duration,
  745. queue : true
  746. })
  747. ;
  748. }
  749. else {
  750. module.debug('Hiding results with javascript');
  751. $results
  752. .stop()
  753. .fadeOut(settings.duration, settings.easing)
  754. ;
  755. }
  756. settings.onResultsClose.call($results);
  757. }
  758. },
  759. generateResults: function(response) {
  760. module.debug('Generating html from response', response);
  761. var
  762. template = settings.templates[settings.type],
  763. isProperObject = ($.isPlainObject(response.results) && !$.isEmptyObject(response.results)),
  764. isProperArray = ($.isArray(response.results) && response.results.length > 0),
  765. html = ''
  766. ;
  767. if(isProperObject || isProperArray ) {
  768. if(settings.maxResults > 0) {
  769. if(isProperObject) {
  770. if(settings.type == 'standard') {
  771. module.error(error.maxResults);
  772. }
  773. }
  774. else {
  775. response.results = response.results.slice(0, settings.maxResults);
  776. }
  777. }
  778. if($.isFunction(template)) {
  779. html = template(response);
  780. }
  781. else {
  782. module.error(error.noTemplate, false);
  783. }
  784. }
  785. else {
  786. html = module.displayMessage(error.noResults, 'empty');
  787. }
  788. settings.onResults.call(element, response);
  789. return html;
  790. },
  791. displayMessage: function(text, type) {
  792. type = type || 'standard';
  793. module.debug('Displaying message', text, type);
  794. module.addResults( settings.templates.message(text, type) );
  795. return settings.templates.message(text, type);
  796. },
  797. setting: function(name, value) {
  798. if( $.isPlainObject(name) ) {
  799. $.extend(true, settings, name);
  800. }
  801. else if(value !== undefined) {
  802. settings[name] = value;
  803. }
  804. else {
  805. return settings[name];
  806. }
  807. },
  808. internal: function(name, value) {
  809. if( $.isPlainObject(name) ) {
  810. $.extend(true, module, name);
  811. }
  812. else if(value !== undefined) {
  813. module[name] = value;
  814. }
  815. else {
  816. return module[name];
  817. }
  818. },
  819. debug: function() {
  820. if(settings.debug) {
  821. if(settings.performance) {
  822. module.performance.log(arguments);
  823. }
  824. else {
  825. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  826. module.debug.apply(console, arguments);
  827. }
  828. }
  829. },
  830. verbose: function() {
  831. if(settings.verbose && settings.debug) {
  832. if(settings.performance) {
  833. module.performance.log(arguments);
  834. }
  835. else {
  836. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  837. module.verbose.apply(console, arguments);
  838. }
  839. }
  840. },
  841. error: function() {
  842. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  843. module.error.apply(console, arguments);
  844. },
  845. performance: {
  846. log: function(message) {
  847. var
  848. currentTime,
  849. executionTime,
  850. previousTime
  851. ;
  852. if(settings.performance) {
  853. currentTime = new Date().getTime();
  854. previousTime = time || currentTime;
  855. executionTime = currentTime - previousTime;
  856. time = currentTime;
  857. performance.push({
  858. 'Name' : message[0],
  859. 'Arguments' : [].slice.call(message, 1) || '',
  860. 'Element' : element,
  861. 'Execution Time' : executionTime
  862. });
  863. }
  864. clearTimeout(module.performance.timer);
  865. module.performance.timer = setTimeout(module.performance.display, 500);
  866. },
  867. display: function() {
  868. var
  869. title = settings.name + ':',
  870. totalTime = 0
  871. ;
  872. time = false;
  873. clearTimeout(module.performance.timer);
  874. $.each(performance, function(index, data) {
  875. totalTime += data['Execution Time'];
  876. });
  877. title += ' ' + totalTime + 'ms';
  878. if(moduleSelector) {
  879. title += ' \'' + moduleSelector + '\'';
  880. }
  881. if($allModules.length > 1) {
  882. title += ' ' + '(' + $allModules.length + ')';
  883. }
  884. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  885. console.groupCollapsed(title);
  886. if(console.table) {
  887. console.table(performance);
  888. }
  889. else {
  890. $.each(performance, function(index, data) {
  891. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  892. });
  893. }
  894. console.groupEnd();
  895. }
  896. performance = [];
  897. }
  898. },
  899. invoke: function(query, passedArguments, context) {
  900. var
  901. object = instance,
  902. maxDepth,
  903. found,
  904. response
  905. ;
  906. passedArguments = passedArguments || queryArguments;
  907. context = element || context;
  908. if(typeof query == 'string' && object !== undefined) {
  909. query = query.split(/[\. ]/);
  910. maxDepth = query.length - 1;
  911. $.each(query, function(depth, value) {
  912. var camelCaseValue = (depth != maxDepth)
  913. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  914. : query
  915. ;
  916. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  917. object = object[camelCaseValue];
  918. }
  919. else if( object[camelCaseValue] !== undefined ) {
  920. found = object[camelCaseValue];
  921. return false;
  922. }
  923. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  924. object = object[value];
  925. }
  926. else if( object[value] !== undefined ) {
  927. found = object[value];
  928. return false;
  929. }
  930. else {
  931. return false;
  932. }
  933. });
  934. }
  935. if( $.isFunction( found ) ) {
  936. response = found.apply(context, passedArguments);
  937. }
  938. else if(found !== undefined) {
  939. response = found;
  940. }
  941. if($.isArray(returnedValue)) {
  942. returnedValue.push(response);
  943. }
  944. else if(returnedValue !== undefined) {
  945. returnedValue = [returnedValue, response];
  946. }
  947. else if(response !== undefined) {
  948. returnedValue = response;
  949. }
  950. return found;
  951. }
  952. };
  953. if(methodInvoked) {
  954. if(instance === undefined) {
  955. module.initialize();
  956. }
  957. module.invoke(query);
  958. }
  959. else {
  960. if(instance !== undefined) {
  961. instance.invoke('destroy');
  962. }
  963. module.initialize();
  964. }
  965. })
  966. ;
  967. return (returnedValue !== undefined)
  968. ? returnedValue
  969. : this
  970. ;
  971. };
  972. $.fn.search.settings = {
  973. name : 'Search',
  974. namespace : 'search',
  975. debug : false,
  976. verbose : false,
  977. performance : true,
  978. type : 'standard',
  979. // template to use (specified in settings.templates)
  980. minCharacters : 1,
  981. // minimum characters required to search
  982. apiSettings : false,
  983. // API config
  984. source : false,
  985. // object to search
  986. searchFields : [
  987. 'title',
  988. 'description'
  989. ],
  990. // fields to search
  991. searchFullText : true,
  992. // whether to include fuzzy results in local search
  993. automatic : true,
  994. // whether to add events to prompt automatically
  995. hideDelay : 0,
  996. // delay before hiding menu after blur
  997. searchDelay : 200,
  998. // delay before searching
  999. maxResults : 7,
  1000. // maximum results returned from local
  1001. cache : true,
  1002. // whether to store lookups in local cache
  1003. // transition settings
  1004. transition : 'scale',
  1005. duration : 200,
  1006. easing : 'easeOutExpo',
  1007. // callbacks
  1008. onSelect : false,
  1009. onResultsAdd : false,
  1010. onSearchQuery : function(){},
  1011. onResults : function(response){},
  1012. onResultsOpen : function(){},
  1013. onResultsClose : function(){},
  1014. className: {
  1015. active : 'active',
  1016. empty : 'empty',
  1017. focus : 'focus',
  1018. loading : 'loading',
  1019. results : 'results',
  1020. pressed : 'down'
  1021. },
  1022. error : {
  1023. source : 'Cannot search. No source used, and Semantic API module was not included',
  1024. noResults : 'Your search returned no results',
  1025. logging : 'Error in debug logging, exiting.',
  1026. noEndpoint : 'No search endpoint was specified',
  1027. noTemplate : 'A valid template name was not specified.',
  1028. serverError : 'There was an issue querying the server.',
  1029. maxResults : 'Results must be an array to use maxResults setting',
  1030. method : 'The method you called is not defined.'
  1031. },
  1032. metadata: {
  1033. cache : 'cache',
  1034. results : 'results',
  1035. result : 'result'
  1036. },
  1037. regExp: {
  1038. escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
  1039. beginsWith : '(?:\s|^)'
  1040. },
  1041. selector : {
  1042. prompt : '.prompt',
  1043. searchButton : '.search.button',
  1044. results : '.results',
  1045. category : '.category',
  1046. result : '.result',
  1047. title : '.title, .name'
  1048. },
  1049. templates: {
  1050. escape: function(string) {
  1051. var
  1052. badChars = /[&<>"'`]/g,
  1053. shouldEscape = /[&<>"'`]/,
  1054. escape = {
  1055. "&": "&amp;",
  1056. "<": "&lt;",
  1057. ">": "&gt;",
  1058. '"': "&quot;",
  1059. "'": "&#x27;",
  1060. "`": "&#x60;"
  1061. },
  1062. escapedChar = function(chr) {
  1063. return escape[chr];
  1064. }
  1065. ;
  1066. if(shouldEscape.test(string)) {
  1067. return string.replace(badChars, escapedChar);
  1068. }
  1069. return string;
  1070. },
  1071. message: function(message, type) {
  1072. var
  1073. html = ''
  1074. ;
  1075. if(message !== undefined && type !== undefined) {
  1076. html += ''
  1077. + '<div class="message ' + type + '">'
  1078. ;
  1079. // message type
  1080. if(type == 'empty') {
  1081. html += ''
  1082. + '<div class="header">No Results</div class="header">'
  1083. + '<div class="description">' + message + '</div class="description">'
  1084. ;
  1085. }
  1086. else {
  1087. html += ' <div class="description">' + message + '</div>';
  1088. }
  1089. html += '</div>';
  1090. }
  1091. return html;
  1092. },
  1093. category: function(response) {
  1094. var
  1095. html = '',
  1096. escape = $.fn.search.settings.templates.escape
  1097. ;
  1098. if(response.results !== undefined) {
  1099. // each category
  1100. $.each(response.results, function(index, category) {
  1101. if(category.results !== undefined && category.results.length > 0) {
  1102. html += ''
  1103. + '<div class="category">'
  1104. + '<div class="name">' + category.name + '</div>'
  1105. ;
  1106. // each item inside category
  1107. $.each(category.results, function(index, result) {
  1108. html += '<div class="result">';
  1109. if(result.url) {
  1110. html += '<a href="' + result.url + '"></a>';
  1111. }
  1112. if(result.image !== undefined) {
  1113. result.image = escape(result.image);
  1114. html += ''
  1115. + '<div class="image">'
  1116. + ' <img src="' + result.image + '" alt="">'
  1117. + '</div>'
  1118. ;
  1119. }
  1120. html += '<div class="content">';
  1121. if(result.price !== undefined) {
  1122. result.price = escape(result.price);
  1123. html += '<div class="price">' + result.price + '</div>';
  1124. }
  1125. if(result.title !== undefined) {
  1126. result.title = escape(result.title);
  1127. html += '<div class="title">' + result.title + '</div>';
  1128. }
  1129. if(result.description !== undefined) {
  1130. html += '<div class="description">' + result.description + '</div>';
  1131. }
  1132. html += ''
  1133. + '</div>'
  1134. + '</div>'
  1135. ;
  1136. });
  1137. html += ''
  1138. + '</div>'
  1139. ;
  1140. }
  1141. });
  1142. if(response.action) {
  1143. html += ''
  1144. + '<a href="' + response.action.url + '" class="action">'
  1145. + response.action.text
  1146. + '</a>';
  1147. }
  1148. return html;
  1149. }
  1150. return false;
  1151. },
  1152. standard: function(response) {
  1153. var
  1154. html = ''
  1155. ;
  1156. if(response.results !== undefined) {
  1157. // each result
  1158. $.each(response.results, function(index, result) {
  1159. if(result.url) {
  1160. html += '<a class="result" href="' + result.url + '">';
  1161. }
  1162. else {
  1163. html += '<a class="result">';
  1164. }
  1165. if(result.image !== undefined) {
  1166. html += ''
  1167. + '<div class="image">'
  1168. + ' <img src="' + result.image + '">'
  1169. + '</div>'
  1170. ;
  1171. }
  1172. html += '<div class="content">';
  1173. if(result.price !== undefined) {
  1174. html += '<div class="price">' + result.price + '</div>';
  1175. }
  1176. if(result.title !== undefined) {
  1177. html += '<div class="title">' + result.title + '</div>';
  1178. }
  1179. if(result.description !== undefined) {
  1180. html += '<div class="description">' + result.description + '</div>';
  1181. }
  1182. html += ''
  1183. + '</div>'
  1184. ;
  1185. html += '</a>';
  1186. });
  1187. if(response.action) {
  1188. html += ''
  1189. + '<a href="' + response.action.url + '" class="action">'
  1190. + response.action.text
  1191. + '</a>';
  1192. }
  1193. return html;
  1194. }
  1195. return false;
  1196. }
  1197. }
  1198. };
  1199. })( jQuery, window , document );