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.

1249 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
9 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
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
10 years ago
10 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
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
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
10 years ago
10 years ago
10 years ago
10 years ago
9 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
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
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
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
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.event.input)
  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. input: function() {
  105. clearTimeout(module.timer);
  106. module.timer = setTimeout(module.query, settings.searchDelay);
  107. },
  108. focus: function() {
  109. module.set.focus();
  110. if( module.has.minimumCharacters() ) {
  111. module.query();
  112. module.showResults();
  113. }
  114. },
  115. blur: function(event) {
  116. var
  117. pageLostFocus = (document.activeElement === this)
  118. ;
  119. if(!pageLostFocus && !module.resultsClicked) {
  120. module.cancel.query();
  121. module.remove.focus();
  122. module.timer = setTimeout(module.hideResults, settings.hideDelay);
  123. }
  124. },
  125. result: {
  126. mousedown: function() {
  127. module.resultsClicked = true;
  128. },
  129. mouseup: function() {
  130. module.resultsClicked = false;
  131. },
  132. click: function(event) {
  133. module.debug('Search result selected');
  134. var
  135. $result = $(this),
  136. $title = $result.find(selector.title).eq(0),
  137. $link = $result.find('a[href]').eq(0),
  138. href = $link.attr('href') || false,
  139. target = $link.attr('target') || false,
  140. title = $title.html(),
  141. // title is used for result lookup
  142. value = ($title.length > 0)
  143. ? $title.text()
  144. : false,
  145. results = module.get.results(),
  146. result = $result.data(metadata.result) || module.get.result(value, results),
  147. returnedValue
  148. ;
  149. if( $.isFunction(settings.onSelect) ) {
  150. if(settings.onSelect.call(element, result, results) === false) {
  151. module.debug('Custom onSelect callback cancelled default select action');
  152. return;
  153. }
  154. }
  155. module.hideResults();
  156. if(value) {
  157. module.set.value(value);
  158. }
  159. if(href) {
  160. module.verbose('Opening search link found in result', $link);
  161. if(target == '_blank' || event.ctrlKey) {
  162. window.open(href);
  163. }
  164. else {
  165. window.location.href = (href);
  166. }
  167. }
  168. }
  169. }
  170. },
  171. handleKeyboard: function(event) {
  172. var
  173. // force selector refresh
  174. $result = $module.find(selector.result),
  175. $category = $module.find(selector.category),
  176. currentIndex = $result.index( $result.filter('.' + className.active) ),
  177. resultSize = $result.length,
  178. keyCode = event.which,
  179. keys = {
  180. backspace : 8,
  181. enter : 13,
  182. escape : 27,
  183. upArrow : 38,
  184. downArrow : 40
  185. },
  186. newIndex
  187. ;
  188. // search shortcuts
  189. if(keyCode == keys.escape) {
  190. module.verbose('Escape key pressed, blurring search field');
  191. $prompt
  192. .trigger('blur')
  193. ;
  194. }
  195. if( module.is.visible() ) {
  196. if(keyCode == keys.enter) {
  197. module.verbose('Enter key pressed, selecting active result');
  198. if( $result.filter('.' + className.active).length > 0 ) {
  199. module.event.result.click.call($result.filter('.' + className.active), event);
  200. event.preventDefault();
  201. return false;
  202. }
  203. }
  204. else if(keyCode == keys.upArrow) {
  205. module.verbose('Up key pressed, changing active result');
  206. newIndex = (currentIndex - 1 < 0)
  207. ? currentIndex
  208. : currentIndex - 1
  209. ;
  210. $category
  211. .removeClass(className.active)
  212. ;
  213. $result
  214. .removeClass(className.active)
  215. .eq(newIndex)
  216. .addClass(className.active)
  217. .closest($category)
  218. .addClass(className.active)
  219. ;
  220. event.preventDefault();
  221. }
  222. else if(keyCode == keys.downArrow) {
  223. module.verbose('Down key pressed, changing active result');
  224. newIndex = (currentIndex + 1 >= resultSize)
  225. ? currentIndex
  226. : currentIndex + 1
  227. ;
  228. $category
  229. .removeClass(className.active)
  230. ;
  231. $result
  232. .removeClass(className.active)
  233. .eq(newIndex)
  234. .addClass(className.active)
  235. .closest($category)
  236. .addClass(className.active)
  237. ;
  238. event.preventDefault();
  239. }
  240. }
  241. else {
  242. // query shortcuts
  243. if(keyCode == keys.enter) {
  244. module.verbose('Enter key pressed, executing query');
  245. module.query();
  246. module.set.buttonPressed();
  247. $prompt.one('keyup', module.remove.buttonFocus);
  248. }
  249. }
  250. },
  251. setup: {
  252. api: function() {
  253. var
  254. apiSettings = {
  255. debug : settings.debug,
  256. on : false,
  257. action : 'search',
  258. onFailure : module.error
  259. },
  260. searchHTML
  261. ;
  262. module.verbose('First request, initializing API');
  263. $module.api(apiSettings);
  264. }
  265. },
  266. can: {
  267. useAPI: function() {
  268. return $.fn.api !== undefined;
  269. },
  270. transition: function() {
  271. return settings.transition && $.fn.transition !== undefined && $module.transition('is supported');
  272. }
  273. },
  274. is: {
  275. empty: function() {
  276. return ($results.html() === '');
  277. },
  278. visible: function() {
  279. return ($results.filter(':visible').length > 0);
  280. },
  281. focused: function() {
  282. return ($prompt.filter(':focus').length > 0);
  283. }
  284. },
  285. get: {
  286. inputEvent: function() {
  287. var
  288. prompt = $prompt[0],
  289. inputEvent = (prompt !== undefined && prompt.oninput !== undefined)
  290. ? 'input'
  291. : (prompt !== undefined && prompt.onpropertychange !== undefined)
  292. ? 'propertychange'
  293. : 'keyup'
  294. ;
  295. return inputEvent;
  296. },
  297. value: function() {
  298. return $prompt.val();
  299. },
  300. results: function() {
  301. var
  302. results = $module.data(metadata.results)
  303. ;
  304. return results;
  305. },
  306. result: function(value, results) {
  307. var
  308. lookupFields = ['title', 'id'],
  309. result = false
  310. ;
  311. value = (value !== undefined)
  312. ? value
  313. : module.get.value()
  314. ;
  315. results = (results !== undefined)
  316. ? results
  317. : module.get.results()
  318. ;
  319. if(settings.type === 'category') {
  320. module.debug('Finding result that matches', value);
  321. $.each(results, function(index, category) {
  322. if($.isArray(category.results)) {
  323. result = module.search.object(value, category.results, lookupFields)[0];
  324. // dont continue searching if a result is found
  325. if(result) {
  326. return false;
  327. }
  328. }
  329. });
  330. }
  331. else {
  332. module.debug('Finding result in results object', value);
  333. result = module.search.object(value, results, lookupFields)[0];
  334. }
  335. return result || false;
  336. },
  337. },
  338. set: {
  339. focus: function() {
  340. $module.addClass(className.focus);
  341. },
  342. loading: function() {
  343. $module.addClass(className.loading);
  344. },
  345. value: function(value) {
  346. module.verbose('Setting search input value', value);
  347. $prompt.val(value);
  348. },
  349. buttonPressed: function() {
  350. $searchButton.addClass(className.pressed);
  351. }
  352. },
  353. remove: {
  354. loading: function() {
  355. $module.removeClass(className.loading);
  356. },
  357. focus: function() {
  358. $module.removeClass(className.focus);
  359. },
  360. buttonPressed: function() {
  361. $searchButton.removeClass(className.pressed);
  362. }
  363. },
  364. query: function() {
  365. var
  366. searchTerm = module.get.value(),
  367. cache = module.read.cache(searchTerm)
  368. ;
  369. if( module.has.minimumCharacters() ) {
  370. if(cache) {
  371. module.debug('Reading result from cache', searchTerm);
  372. module.save.results(cache.results);
  373. module.addResults(cache.html);
  374. module.inject.id(cache.results);
  375. }
  376. else {
  377. module.debug('Querying for', searchTerm);
  378. if($.isPlainObject(settings.source) || $.isArray(settings.source)) {
  379. module.search.local(searchTerm);
  380. }
  381. else if( module.can.useAPI() ) {
  382. module.search.remote(searchTerm);
  383. }
  384. else {
  385. module.error(error.source);
  386. }
  387. settings.onSearchQuery.call(element, searchTerm);
  388. }
  389. }
  390. else {
  391. module.hideResults();
  392. }
  393. },
  394. search: {
  395. local: function(searchTerm) {
  396. var
  397. results = module.search.object(searchTerm, settings.content),
  398. searchHTML
  399. ;
  400. module.set.loading();
  401. module.save.results(results);
  402. module.debug('Returned local search results', results);
  403. searchHTML = module.generateResults({
  404. results: results
  405. });
  406. module.remove.loading();
  407. module.addResults(searchHTML);
  408. module.inject.id(results);
  409. module.write.cache(searchTerm, {
  410. html : searchHTML,
  411. results : results
  412. });
  413. },
  414. remote: function(searchTerm) {
  415. var
  416. apiSettings = {
  417. onSuccess : function(response) {
  418. module.parse.response.call(element, response, searchTerm);
  419. },
  420. urlData: {
  421. query: searchTerm
  422. }
  423. }
  424. ;
  425. if( !$module.api('get request') ) {
  426. module.setup.api();
  427. }
  428. $.extend(true, apiSettings, settings.apiSettings);
  429. module.debug('Executing search', apiSettings);
  430. module.cancel.query();
  431. $module
  432. .api('setting', apiSettings)
  433. .api('query')
  434. ;
  435. },
  436. object: function(searchTerm, source, searchFields) {
  437. var
  438. results = [],
  439. fuzzyResults = [],
  440. searchExp = searchTerm.toString().replace(regExp.escape, '\\$&'),
  441. matchRegExp = new RegExp(regExp.beginsWith + searchExp, 'i'),
  442. // avoid duplicates when pushing results
  443. addResult = function(array, result) {
  444. var
  445. notResult = ($.inArray(result, results) == -1),
  446. notFuzzyResult = ($.inArray(result, fuzzyResults) == -1)
  447. ;
  448. if(notResult && notFuzzyResult) {
  449. array.push(result);
  450. }
  451. }
  452. ;
  453. source = source || settings.source;
  454. searchFields = (searchFields !== undefined)
  455. ? searchFields
  456. : settings.searchFields
  457. ;
  458. // search fields should be array to loop correctly
  459. if(!$.isArray(searchFields)) {
  460. searchFields = [searchFields];
  461. }
  462. // exit conditions if no source
  463. if(source === undefined) {
  464. module.error(error.source);
  465. return [];
  466. }
  467. // iterate through search fields looking for matches
  468. $.each(searchFields, function(index, field) {
  469. $.each(source, function(label, content) {
  470. var
  471. fieldExists = (typeof content[field] == 'string')
  472. ;
  473. if(fieldExists) {
  474. if( content[field].search(matchRegExp) !== -1) {
  475. // content starts with value (first in results)
  476. addResult(results, content);
  477. }
  478. else if(settings.searchFullText && module.fuzzySearch(searchTerm, content[field]) ) {
  479. // content fuzzy matches (last in results)
  480. addResult(fuzzyResults, content);
  481. }
  482. }
  483. });
  484. });
  485. return $.merge(results, fuzzyResults);
  486. }
  487. },
  488. fuzzySearch: function(query, term) {
  489. var
  490. termLength = term.length,
  491. queryLength = query.length
  492. ;
  493. if(typeof query !== 'string') {
  494. return false;
  495. }
  496. query = query.toLowerCase();
  497. term = term.toLowerCase();
  498. if(queryLength > termLength) {
  499. return false;
  500. }
  501. if(queryLength === termLength) {
  502. return (query === term);
  503. }
  504. search: for (var characterIndex = 0, nextCharacterIndex = 0; characterIndex < queryLength; characterIndex++) {
  505. var
  506. queryCharacter = query.charCodeAt(characterIndex)
  507. ;
  508. while(nextCharacterIndex < termLength) {
  509. if(term.charCodeAt(nextCharacterIndex++) === queryCharacter) {
  510. continue search;
  511. }
  512. }
  513. return false;
  514. }
  515. return true;
  516. },
  517. parse: {
  518. response: function(response, searchTerm) {
  519. var
  520. searchHTML = module.generateResults(response)
  521. ;
  522. module.verbose('Parsing server response', response);
  523. if(response !== undefined) {
  524. if(searchTerm !== undefined && response.results !== undefined) {
  525. module.addResults(searchHTML);
  526. module.inject.id(response.results);
  527. module.write.cache(searchTerm, {
  528. html : searchHTML,
  529. results : response.results
  530. });
  531. module.save.results(response.results);
  532. }
  533. }
  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 );