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.

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