search.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /**
  2. * ownCloud - core
  3. *
  4. * This file is licensed under the Affero General Public License version 3 or
  5. * later. See the COPYING file.
  6. *
  7. * @author Jörn Friedrich Dreyer <jfd@owncloud.com>
  8. * @copyright Jörn Friedrich Dreyer 2014
  9. */
  10. (function () {
  11. /**
  12. * @class OCA.Search
  13. * @classdesc
  14. *
  15. * The Search class manages a search queries and their results
  16. *
  17. * @param $searchBox container element with existing markup for the #searchbox form
  18. * @param $searchResults container element for results und status message
  19. */
  20. var Search = function($searchBox, $searchResults) {
  21. this.initialize($searchBox, $searchResults);
  22. };
  23. /**
  24. * @memberof OC
  25. */
  26. Search.prototype = {
  27. /**
  28. * Initialize the search box
  29. *
  30. * @param $searchBox container element with existing markup for the #searchbox form
  31. * @param $searchResults container element for results und status message
  32. * @private
  33. */
  34. initialize: function($searchBox, $searchResults) {
  35. var self = this;
  36. /**
  37. * contains closures that are called to filter the current content
  38. */
  39. var filters = {};
  40. this.setFilter = function(type, filter) {
  41. filters[type] = filter;
  42. };
  43. this.hasFilter = function(type) {
  44. return typeof filters[type] !== 'undefined';
  45. };
  46. this.getFilter = function(type) {
  47. return filters[type];
  48. };
  49. /**
  50. * contains closures that are called to render search results
  51. */
  52. var renderers = {};
  53. this.setRenderer = function(type, renderer) {
  54. renderers[type] = renderer;
  55. };
  56. this.hasRenderer = function(type) {
  57. return typeof renderers[type] !== 'undefined';
  58. };
  59. this.getRenderer = function(type) {
  60. return renderers[type];
  61. };
  62. /**
  63. * contains closures that are called when a search result has been clicked
  64. */
  65. var handlers = {};
  66. this.setHandler = function(type, handler) {
  67. handlers[type] = handler;
  68. };
  69. this.hasHandler = function(type) {
  70. return typeof handlers[type] !== 'undefined';
  71. };
  72. this.getHandler = function(type) {
  73. return handlers[type];
  74. };
  75. var currentResult = -1;
  76. var lastQuery = '';
  77. var lastInApps = [];
  78. var lastPage = 0;
  79. var lastSize = 30;
  80. var lastResults = [];
  81. var timeoutID = null;
  82. this.getLastQuery = function() {
  83. return lastQuery;
  84. };
  85. /**
  86. * Do a search query and display the results
  87. * @param {string} query the search query
  88. * @param inApps
  89. * @param page
  90. * @param size
  91. */
  92. this.search = function(query, inApps, page, size) {
  93. if (query) {
  94. OC.addStyle('core/search','results');
  95. if (typeof page !== 'number') {
  96. page = 1;
  97. }
  98. if (typeof size !== 'number') {
  99. size = 30;
  100. }
  101. if (typeof inApps !== 'object') {
  102. var currentApp = getCurrentApp();
  103. if(currentApp) {
  104. inApps = [currentApp];
  105. } else {
  106. inApps = [];
  107. }
  108. }
  109. // prevent double pages
  110. if ($searchResults && query === lastQuery && page === lastPage && size === lastSize) {
  111. return;
  112. }
  113. window.clearTimeout(timeoutID);
  114. timeoutID = window.setTimeout(function() {
  115. lastQuery = query;
  116. lastInApps = inApps;
  117. lastPage = page;
  118. lastSize = size;
  119. //show spinner
  120. $searchResults.removeClass('hidden');
  121. $status.addClass('status');
  122. $status.html(t('core', 'Searching other places')+'<img class="spinner" alt="search in progress" src="'+OC.webroot+'/core/img/loading.gif" />');
  123. // do the actual search query
  124. $.getJSON(OC.generateUrl('core/search'), {query:query, inApps:inApps, page:page, size:size }, function(results) {
  125. lastResults = results;
  126. if (page === 1) {
  127. showResults(results);
  128. } else {
  129. addResults(results);
  130. }
  131. });
  132. }, 500);
  133. }
  134. };
  135. //TODO should be a core method, see https://github.com/owncloud/core/issues/12557
  136. function getCurrentApp() {
  137. var content = document.getElementById('content');
  138. if (content) {
  139. var classList = document.getElementById('content').className.split(/\s+/);
  140. for (var i = 0; i < classList.length; i++) {
  141. if (classList[i].indexOf('app-') === 0) {
  142. return classList[i].substr(4);
  143. }
  144. }
  145. }
  146. return false;
  147. }
  148. var $status = $searchResults.find('#status');
  149. // summaryAndStatusHeight is a constant
  150. var summaryAndStatusHeight = 118;
  151. function isStatusOffScreen() {
  152. return $searchResults.position() &&
  153. ($searchResults.position().top + summaryAndStatusHeight > window.innerHeight);
  154. }
  155. function placeStatus() {
  156. if (isStatusOffScreen()) {
  157. $status.addClass('fixed');
  158. } else {
  159. $status.removeClass('fixed');
  160. }
  161. }
  162. function showResults(results) {
  163. lastResults = results;
  164. $searchResults.find('tr.result').remove();
  165. $searchResults.removeClass('hidden');
  166. addResults(results);
  167. }
  168. function addResults(results) {
  169. var $template = $searchResults.find('tr.template');
  170. jQuery.each(results, function (i, result) {
  171. var $row = $template.clone();
  172. $row.removeClass('template');
  173. $row.addClass('result');
  174. $row.data('result', result);
  175. // generic results only have four attributes
  176. $row.find('td.info div.name').text(result.name);
  177. $row.find('td.info a').attr('href', result.link);
  178. /**
  179. * Give plugins the ability to customize the search results. see result.js for examples
  180. */
  181. if (self.hasRenderer(result.type)) {
  182. $row = self.getRenderer(result.type)($row, result);
  183. } else {
  184. // for backward compatibility add text div
  185. $row.find('td.info div.name').addClass('result');
  186. $row.find('td.result div.name').after('<div class="text"></div>');
  187. $row.find('td.result div.text').text(result.name);
  188. if (OC.search.customResults && OC.search.customResults[result.type]) {
  189. OC.search.customResults[result.type]($row, result);
  190. }
  191. }
  192. if ($row) {
  193. $searchResults.find('tbody').append($row);
  194. }
  195. });
  196. var count = $searchResults.find('tr.result').length;
  197. $status.data('count', count);
  198. if (count === 0) {
  199. $status.addClass('emptycontent').removeClass('status');
  200. $status.html('');
  201. $status.append('<div class="icon-search"></div>');
  202. $status.append('<h2>' + t('core', 'No search results in other folders') + '</h2>');
  203. } else {
  204. $status.removeClass('emptycontent').addClass('status');
  205. $status.text(n('core', '{count} search result in another folder', '{count} search results in other folders', count, {count:count}));
  206. }
  207. }
  208. function renderCurrent() {
  209. var result = $searchResults.find('tr.result')[currentResult];
  210. if (result) {
  211. var $result = $(result);
  212. var currentOffset = $('#app-content').scrollTop();
  213. $('#app-content').animate({
  214. // Scrolling to the top of the new result
  215. scrollTop: currentOffset + $result.offset().top - $result.height() * 2
  216. }, {
  217. duration: 100
  218. });
  219. $searchResults.find('tr.result.current').removeClass('current');
  220. $result.addClass('current');
  221. }
  222. }
  223. this.hideResults = function() {
  224. $searchResults.addClass('hidden');
  225. $searchResults.find('tr.result').remove();
  226. lastQuery = false;
  227. };
  228. this.clear = function() {
  229. self.hideResults();
  230. if(self.hasFilter(getCurrentApp())) {
  231. self.getFilter(getCurrentApp())('');
  232. }
  233. $searchBox.val('');
  234. $searchBox.blur();
  235. };
  236. /**
  237. * Event handler for when scrolling the list container.
  238. * This appends/renders the next page of entries when reaching the bottom.
  239. */
  240. function onScroll() {
  241. if ($searchResults && lastQuery !== false && lastResults.length > 0) {
  242. var resultsBottom = $searchResults.offset().top + $searchResults.height();
  243. var containerBottom = $searchResults.offsetParent().offset().top +
  244. $searchResults.offsetParent().height();
  245. if ( resultsBottom < containerBottom * 1.2 ) {
  246. self.search(lastQuery, lastInApps, lastPage + 1);
  247. }
  248. placeStatus();
  249. }
  250. }
  251. $('#app-content').on('scroll', _.bind(onScroll, this));
  252. /**
  253. * scrolls the search results to the top
  254. */
  255. function scrollToResults() {
  256. setTimeout(function() {
  257. if (isStatusOffScreen()) {
  258. var newScrollTop = $('#app-content').prop('scrollHeight') - $searchResults.height();
  259. console.log('scrolling to ' + newScrollTop);
  260. $('#app-content').animate({
  261. scrollTop: newScrollTop
  262. }, {
  263. duration: 100,
  264. complete: function () {
  265. scrollToResults();
  266. }
  267. });
  268. }
  269. }, 150);
  270. }
  271. $('form.searchbox').submit(function(event) {
  272. event.preventDefault();
  273. });
  274. $searchBox.on('search', function () {
  275. if($searchBox.val() === '') {
  276. if(self.hasFilter(getCurrentApp())) {
  277. self.getFilter(getCurrentApp())('');
  278. }
  279. self.hideResults();
  280. }
  281. });
  282. $searchBox.keyup(function(event) {
  283. if (event.keyCode === 13) { //enter
  284. if(currentResult > -1) {
  285. var result = $searchResults.find('tr.result a')[currentResult];
  286. window.location = $(result).attr('href');
  287. }
  288. } else if(event.keyCode === 38) { //up
  289. if(currentResult > 0) {
  290. currentResult--;
  291. renderCurrent();
  292. }
  293. } else if(event.keyCode === 40) { //down
  294. if(lastResults.length > currentResult + 1){
  295. currentResult++;
  296. renderCurrent();
  297. }
  298. } else {
  299. var query = $searchBox.val();
  300. if (lastQuery !== query) {
  301. currentResult = -1;
  302. if (query.length > 2) {
  303. self.search(query);
  304. } else {
  305. self.hideResults();
  306. }
  307. if(self.hasFilter(getCurrentApp())) {
  308. self.getFilter(getCurrentApp())(query);
  309. }
  310. }
  311. }
  312. });
  313. $(document).keyup(function(event) {
  314. if(event.keyCode === 27) { //esc
  315. $searchBox.val('');
  316. if(self.hasFilter(getCurrentApp())) {
  317. self.getFilter(getCurrentApp())('');
  318. }
  319. self.hideResults();
  320. }
  321. });
  322. $(document).keydown(function(event) {
  323. if ((event.ctrlKey || event.metaKey) && // Ctrl or Command (OSX)
  324. !event.shiftKey &&
  325. event.keyCode === 70 && // F
  326. self.hasFilter(getCurrentApp()) && // Search is enabled
  327. !$searchBox.is(':focus') // if searchbox is already focused do nothing (fallback to browser default)
  328. ) {
  329. $searchBox.focus();
  330. event.preventDefault();
  331. }
  332. });
  333. $searchResults.on('click', 'tr.result', function (event) {
  334. var $row = $(this);
  335. var item = $row.data('result');
  336. if(self.hasHandler(item.type)){
  337. var result = self.getHandler(item.type)($row, item, event);
  338. $searchBox.val('');
  339. if(self.hasFilter(getCurrentApp())) {
  340. self.getFilter(getCurrentApp())('');
  341. }
  342. self.hideResults();
  343. return result;
  344. }
  345. });
  346. $searchResults.on('click', '#status', function (event) {
  347. event.preventDefault();
  348. scrollToResults();
  349. return false;
  350. });
  351. placeStatus();
  352. OC.Plugins.attach('OCA.Search', this);
  353. // hide search file if search is not enabled
  354. if(self.hasFilter(getCurrentApp())) {
  355. return;
  356. }
  357. if ($searchResults.length === 0) {
  358. $searchBox.hide();
  359. }
  360. }
  361. };
  362. OCA.Search = Search;
  363. })();
  364. $(document).ready(function() {
  365. var $searchResults = $('#searchresults');
  366. if ($searchResults.length > 0) {
  367. $searchResults.addClass('hidden');
  368. $('#app-content')
  369. .find('.viewcontainer').css('min-height', 'initial');
  370. $searchResults.load(OC.webroot + '/core/search/templates/part.results.html', function () {
  371. OC.Search = new OCA.Search($('#searchbox'), $('#searchresults'));
  372. });
  373. } else {
  374. _.defer(function() {
  375. OC.Search = new OCA.Search($('#searchbox'), $('#searchresults'));
  376. });
  377. }
  378. });
  379. /**
  380. * @deprecated use get/setRenderer() instead
  381. */
  382. OC.search.customResults = {};
  383. /**
  384. * @deprecated use get/setRenderer() instead
  385. */
  386. OC.search.resultTypes = {};