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.

421 lines
12 KiB

11 years ago
11 years ago
11 years ago
  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>').addClass('icon-search'));
  202. var error = t('core', 'No search results in other folders for {tag}{filter}{endtag}', {filter:lastQuery});
  203. $status.append($('<h2>').html(error.replace('{tag}', '<strong>').replace('{endtag}', '</strong>')));
  204. } else {
  205. $status.removeClass('emptycontent').addClass('status');
  206. $status.text(n('core', '{count} search result in another folder', '{count} search results in other folders', count, {count:count}));
  207. }
  208. }
  209. function renderCurrent() {
  210. var result = $searchResults.find('tr.result')[currentResult];
  211. if (result) {
  212. var $result = $(result);
  213. var currentOffset = $('#app-content').scrollTop();
  214. $('#app-content').animate({
  215. // Scrolling to the top of the new result
  216. scrollTop: currentOffset + $result.offset().top - $result.height() * 2
  217. }, {
  218. duration: 100
  219. });
  220. $searchResults.find('tr.result.current').removeClass('current');
  221. $result.addClass('current');
  222. }
  223. }
  224. this.hideResults = function() {
  225. $searchResults.addClass('hidden');
  226. $searchResults.find('tr.result').remove();
  227. lastQuery = false;
  228. };
  229. this.clear = function() {
  230. self.hideResults();
  231. if(self.hasFilter(getCurrentApp())) {
  232. self.getFilter(getCurrentApp())('');
  233. }
  234. $searchBox.val('');
  235. $searchBox.blur();
  236. };
  237. /**
  238. * Event handler for when scrolling the list container.
  239. * This appends/renders the next page of entries when reaching the bottom.
  240. */
  241. function onScroll() {
  242. if ($searchResults && lastQuery !== false && lastResults.length > 0) {
  243. var resultsBottom = $searchResults.offset().top + $searchResults.height();
  244. var containerBottom = $searchResults.offsetParent().offset().top +
  245. $searchResults.offsetParent().height();
  246. if ( resultsBottom < containerBottom * 1.2 ) {
  247. self.search(lastQuery, lastInApps, lastPage + 1);
  248. }
  249. placeStatus();
  250. }
  251. }
  252. $('#app-content').on('scroll', _.bind(onScroll, this));
  253. /**
  254. * scrolls the search results to the top
  255. */
  256. function scrollToResults() {
  257. setTimeout(function() {
  258. if (isStatusOffScreen()) {
  259. var newScrollTop = $('#app-content').prop('scrollHeight') - $searchResults.height();
  260. console.log('scrolling to ' + newScrollTop);
  261. $('#app-content').animate({
  262. scrollTop: newScrollTop
  263. }, {
  264. duration: 100,
  265. complete: function () {
  266. scrollToResults();
  267. }
  268. });
  269. }
  270. }, 150);
  271. }
  272. $('form.searchbox').submit(function(event) {
  273. event.preventDefault();
  274. });
  275. $searchBox.on('search', function () {
  276. if($searchBox.val() === '') {
  277. if(self.hasFilter(getCurrentApp())) {
  278. self.getFilter(getCurrentApp())('');
  279. }
  280. self.hideResults();
  281. }
  282. });
  283. $searchBox.keyup(function(event) {
  284. if (event.keyCode === 13) { //enter
  285. if(currentResult > -1) {
  286. var result = $searchResults.find('tr.result a')[currentResult];
  287. window.location = $(result).attr('href');
  288. }
  289. } else if(event.keyCode === 38) { //up
  290. if(currentResult > 0) {
  291. currentResult--;
  292. renderCurrent();
  293. }
  294. } else if(event.keyCode === 40) { //down
  295. if(lastResults.length > currentResult + 1){
  296. currentResult++;
  297. renderCurrent();
  298. }
  299. } else {
  300. var query = $searchBox.val();
  301. if (lastQuery !== query) {
  302. currentResult = -1;
  303. if (query.length > 2) {
  304. self.search(query);
  305. } else {
  306. self.hideResults();
  307. }
  308. if(self.hasFilter(getCurrentApp())) {
  309. self.getFilter(getCurrentApp())(query);
  310. }
  311. }
  312. }
  313. });
  314. $(document).keyup(function(event) {
  315. if(event.keyCode === 27) { //esc
  316. $searchBox.val('');
  317. if(self.hasFilter(getCurrentApp())) {
  318. self.getFilter(getCurrentApp())('');
  319. }
  320. self.hideResults();
  321. }
  322. });
  323. $(document).keydown(function(event) {
  324. if ((event.ctrlKey || event.metaKey) && // Ctrl or Command (OSX)
  325. !event.shiftKey &&
  326. event.keyCode === 70 && // F
  327. self.hasFilter(getCurrentApp()) && // Search is enabled
  328. !$searchBox.is(':focus') // if searchbox is already focused do nothing (fallback to browser default)
  329. ) {
  330. $searchBox.focus();
  331. $searchBox.select();
  332. event.preventDefault();
  333. }
  334. });
  335. $searchResults.on('click', 'tr.result', function (event) {
  336. var $row = $(this);
  337. var item = $row.data('result');
  338. if(self.hasHandler(item.type)){
  339. var result = self.getHandler(item.type)($row, item, event);
  340. $searchBox.val('');
  341. if(self.hasFilter(getCurrentApp())) {
  342. self.getFilter(getCurrentApp())('');
  343. }
  344. self.hideResults();
  345. return result;
  346. }
  347. });
  348. $searchResults.on('click', '#status', function (event) {
  349. event.preventDefault();
  350. scrollToResults();
  351. return false;
  352. });
  353. placeStatus();
  354. OC.Plugins.attach('OCA.Search', this);
  355. // hide search file if search is not enabled
  356. if(self.hasFilter(getCurrentApp())) {
  357. return;
  358. }
  359. if ($searchResults.length === 0) {
  360. $searchBox.hide();
  361. }
  362. }
  363. };
  364. OCA.Search = Search;
  365. })();
  366. $(document).ready(function() {
  367. var $searchResults = $('#searchresults');
  368. if ($searchResults.length > 0) {
  369. $searchResults.addClass('hidden');
  370. $('#app-content')
  371. .find('.viewcontainer').css('min-height', 'initial');
  372. $searchResults.load(OC.webroot + '/core/search/templates/part.results.html', function () {
  373. OC.Search = new OCA.Search($('#searchbox'), $('#searchresults'));
  374. });
  375. } else {
  376. _.defer(function() {
  377. OC.Search = new OCA.Search($('#searchbox'), $('#searchresults'));
  378. });
  379. }
  380. $('#searchbox + .icon-close-white').click(function() {
  381. OC.Search.clear();
  382. $('#searchbox').focus();
  383. });
  384. });
  385. /**
  386. * @deprecated use get/setRenderer() instead
  387. */
  388. OC.search.customResults = {};
  389. /**
  390. * @deprecated use get/setRenderer() instead
  391. */
  392. OC.search.resultTypes = {};