globalSearch.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  1. const subManager = new SubsManager();
  2. BlazeComponent.extendComponent({
  3. events() {
  4. return [
  5. {
  6. 'click .js-due-cards-view-change': Popup.open('globalSearchViewChange'),
  7. },
  8. ];
  9. },
  10. }).register('globalSearchHeaderBar');
  11. Template.globalSearch.helpers({
  12. userId() {
  13. return Meteor.userId();
  14. },
  15. });
  16. BlazeComponent.extendComponent({
  17. events() {
  18. return [
  19. {
  20. 'click .js-due-cards-view-me'() {
  21. Utils.setDueCardsView('me');
  22. Popup.close();
  23. },
  24. 'click .js-due-cards-view-all'() {
  25. Utils.setDueCardsView('all');
  26. Popup.close();
  27. },
  28. },
  29. ];
  30. },
  31. }).register('globalSearchViewChangePopup');
  32. BlazeComponent.extendComponent({
  33. onCreated() {
  34. this.searching = new ReactiveVar(false);
  35. this.hasResults = new ReactiveVar(false);
  36. this.hasQueryErrors = new ReactiveVar(false);
  37. this.query = new ReactiveVar('');
  38. this.resultsHeading = new ReactiveVar('');
  39. this.searchLink = new ReactiveVar(null);
  40. this.myLists = new ReactiveVar([]);
  41. this.myLabelNames = new ReactiveVar([]);
  42. this.myBoardNames = new ReactiveVar([]);
  43. this.results = new ReactiveVar([]);
  44. this.queryParams = null;
  45. this.parsingErrors = [];
  46. this.resultsCount = 0;
  47. this.totalHits = 0;
  48. this.queryErrors = null;
  49. this.colorMap = null;
  50. Meteor.call('myLists', (err, data) => {
  51. if (!err) {
  52. this.myLists.set(data);
  53. }
  54. });
  55. Meteor.call('myLabelNames', (err, data) => {
  56. if (!err) {
  57. this.myLabelNames.set(data);
  58. }
  59. });
  60. Meteor.call('myBoardNames', (err, data) => {
  61. if (!err) {
  62. this.myBoardNames.set(data);
  63. }
  64. });
  65. },
  66. onRendered() {
  67. Meteor.subscribe('setting');
  68. this.colorMap = {};
  69. for (const color of Boards.simpleSchema()._schema['labels.$.color']
  70. .allowedValues) {
  71. this.colorMap[TAPi18n.__(`color-${color}`)] = color;
  72. }
  73. // // eslint-disable-next-line no-console
  74. // console.log('colorMap:', this.colorMap);
  75. if (Session.get('globalQuery')) {
  76. this.searchAllBoards(Session.get('globalQuery'));
  77. }
  78. },
  79. resetSearch() {
  80. this.searching.set(false);
  81. this.results.set([]);
  82. this.hasResults.set(false);
  83. this.hasQueryErrors.set(false);
  84. this.resultsHeading.set('');
  85. this.parsingErrors = [];
  86. this.resultsCount = 0;
  87. this.totalHits = 0;
  88. this.queryErrors = null;
  89. },
  90. getResults() {
  91. // eslint-disable-next-line no-console
  92. // console.log('getting results');
  93. if (this.queryParams) {
  94. const sessionData = SessionData.findOne({
  95. userId: Meteor.userId(),
  96. sessionId: SessionData.getSessionId(),
  97. });
  98. // eslint-disable-next-line no-console
  99. // console.log('session data:', sessionData);
  100. const cards = Cards.find({ _id: { $in: sessionData.cards } });
  101. this.queryErrors = sessionData.errors;
  102. if (this.queryErrors.length) {
  103. this.hasQueryErrors.set(true);
  104. return null;
  105. }
  106. if (cards) {
  107. this.totalHits = sessionData.totalHits;
  108. this.resultsCount = cards.count();
  109. this.resultsHeading.set(this.getResultsHeading());
  110. this.results.set(cards);
  111. }
  112. }
  113. this.resultsCount = 0;
  114. return null;
  115. },
  116. errorMessages() {
  117. if (this.parsingErrors.length) {
  118. return this.parsingErrorMessages();
  119. }
  120. return this.queryErrorMessages();
  121. },
  122. parsingErrorMessages() {
  123. const messages = [];
  124. if (this.parsingErrors.length) {
  125. this.parsingErrors.forEach(err => {
  126. messages.push(TAPi18n.__(err.tag, err.value));
  127. });
  128. }
  129. return messages;
  130. },
  131. queryErrorMessages() {
  132. messages = [];
  133. this.queryErrors.forEach(err => {
  134. let value = err.color ? TAPi18n.__(`color-${err.value}`) : err.value;
  135. if (!value) {
  136. value = err.value;
  137. }
  138. messages.push(TAPi18n.__(err.tag, value));
  139. });
  140. return messages;
  141. },
  142. searchAllBoards(query) {
  143. query = query.trim();
  144. // eslint-disable-next-line no-console
  145. console.log('query:', query);
  146. this.query.set(query);
  147. this.resetSearch();
  148. if (!query) {
  149. return;
  150. }
  151. this.searching.set(true);
  152. const reOperator1 = /^((?<operator>\w+):|(?<abbrev>[#@]))(?<value>\w+)(\s+|$)/;
  153. const reOperator2 = /^((?<operator>\w+):|(?<abbrev>[#@]))(?<quote>["']*)(?<value>.*?)\k<quote>(\s+|$)/;
  154. const reText = /^(?<text>\S+)(\s+|$)/;
  155. const reQuotedText = /^(?<quote>["'])(?<text>\w+)\k<quote>(\s+|$)/;
  156. const operators = {
  157. 'operator-board': 'boards',
  158. 'operator-board-abbrev': 'boards',
  159. 'operator-swimlane': 'swimlanes',
  160. 'operator-swimlane-abbrev': 'swimlanes',
  161. 'operator-list': 'lists',
  162. 'operator-list-abbrev': 'lists',
  163. 'operator-label': 'labels',
  164. 'operator-label-abbrev': 'labels',
  165. 'operator-user': 'users',
  166. 'operator-user-abbrev': 'users',
  167. 'operator-member': 'members',
  168. 'operator-member-abbrev': 'members',
  169. 'operator-assignee': 'assignees',
  170. 'operator-assignee-abbrev': 'assignees',
  171. 'operator-is': 'is',
  172. 'operator-due': 'dueAt',
  173. 'operator-created': 'createdAt',
  174. 'operator-modified': 'modifiedAt',
  175. 'operator-comment': 'comments',
  176. };
  177. const operatorMap = {};
  178. Object.entries(operators).forEach(([key, value]) => {
  179. operatorMap[TAPi18n.__(key).toLowerCase()] = value;
  180. });
  181. // eslint-disable-next-line no-console
  182. // console.log('operatorMap:', operatorMap);
  183. const params = {
  184. boards: [],
  185. swimlanes: [],
  186. lists: [],
  187. users: [],
  188. members: [],
  189. assignees: [],
  190. labels: [],
  191. is: [],
  192. dueAt: null,
  193. createdAt: null,
  194. modifiedAt: null,
  195. comments: [],
  196. };
  197. let text = '';
  198. while (query) {
  199. m = query.match(reOperator1);
  200. if (!m) {
  201. m = query.match(reOperator2);
  202. if (m) {
  203. query = query.replace(reOperator2, '');
  204. }
  205. } else {
  206. query = query.replace(reOperator1, '');
  207. }
  208. if (m) {
  209. let op;
  210. if (m.groups.operator) {
  211. op = m.groups.operator.toLowerCase();
  212. } else {
  213. op = m.groups.abbrev;
  214. }
  215. if (operatorMap.hasOwnProperty(op)) {
  216. let value = m.groups.value;
  217. if (operatorMap[op] === 'labels') {
  218. if (value in this.colorMap) {
  219. value = this.colorMap[value];
  220. }
  221. } else if (
  222. ['dueAt', 'createdAt', 'modifiedAt'].includes(operatorMap[op])
  223. ) {
  224. let days = parseInt(value, 10);
  225. let duration = null;
  226. if (isNaN(days)) {
  227. if (['day', 'week', 'month', 'quarter', 'year'].includes(value)) {
  228. duration = value;
  229. value = moment();
  230. } else if (value === 'overdue') {
  231. value = moment();
  232. duration = 'days';
  233. days = 0;
  234. } else {
  235. this.parsingErrors.push({
  236. tag: 'operator-number-expected',
  237. value: { operator: op, value },
  238. });
  239. value = null;
  240. }
  241. } else {
  242. value = moment();
  243. }
  244. if (value) {
  245. if (operatorMap[op] === 'dueAt') {
  246. value = value.add(days, duration ? duration : 'days').format();
  247. } else {
  248. value = value
  249. .subtract(days, duration ? duration : 'days')
  250. .format();
  251. }
  252. }
  253. } else if (operatorMap[op] === 'sort') {
  254. if (!['due', 'modified', 'created', 'system'].includes(value)) {
  255. this.parsingErrors.push({
  256. tag: 'operator-sort-invalid',
  257. value,
  258. });
  259. }
  260. }
  261. if (Array.isArray(params[operatorMap[op]])) {
  262. params[operatorMap[op]].push(value);
  263. } else {
  264. params[operatorMap[op]] = value;
  265. }
  266. } else {
  267. this.parsingErrors.push({
  268. tag: 'operator-unknown-error',
  269. value: op,
  270. });
  271. }
  272. continue;
  273. }
  274. m = query.match(reQuotedText);
  275. if (!m) {
  276. m = query.match(reText);
  277. if (m) {
  278. query = query.replace(reText, '');
  279. }
  280. } else {
  281. query = query.replace(reQuotedText, '');
  282. }
  283. if (m) {
  284. text += (text ? ' ' : '') + m.groups.text;
  285. }
  286. }
  287. // eslint-disable-next-line no-console
  288. // console.log('text:', text);
  289. params.text = text;
  290. // eslint-disable-next-line no-console
  291. // console.log('params:', params);
  292. this.queryParams = params;
  293. if (this.parsingErrors.length) {
  294. this.searching.set(false);
  295. this.queryErrors = this.parsingErrorMessages();
  296. this.hasQueryErrors.set(true);
  297. return;
  298. }
  299. this.autorun(() => {
  300. const handle = subManager.subscribe(
  301. 'globalSearch',
  302. SessionData.getSessionId(),
  303. params,
  304. );
  305. Tracker.nonreactive(() => {
  306. Tracker.autorun(() => {
  307. if (handle.ready()) {
  308. this.getResults();
  309. this.searching.set(false);
  310. this.hasResults.set(true);
  311. }
  312. });
  313. });
  314. });
  315. },
  316. getResultsHeading() {
  317. if (this.resultsCount === 0) {
  318. return TAPi18n.__('no-cards-found');
  319. } else if (this.resultsCount === 1) {
  320. return TAPi18n.__('one-card-found');
  321. } else if (this.resultsCount === this.totalHits) {
  322. return TAPi18n.__('n-cards-found', this.resultsCount);
  323. }
  324. return TAPi18n.__('n-n-of-n-cards-found', {
  325. start: 1,
  326. end: this.resultsCount,
  327. total: this.totalHits,
  328. });
  329. },
  330. getSearchHref() {
  331. const baseUrl = window.location.href.replace(/([?#].*$|\s*$)/, '');
  332. return `${baseUrl}?q=${encodeURIComponent(this.query.get())}`;
  333. },
  334. searchInstructions() {
  335. tags = {
  336. operator_board: TAPi18n.__('operator-board'),
  337. operator_list: TAPi18n.__('operator-list'),
  338. operator_swimlane: TAPi18n.__('operator-swimlane'),
  339. operator_label: TAPi18n.__('operator-label'),
  340. operator_label_abbrev: TAPi18n.__('operator-label-abbrev'),
  341. operator_user: TAPi18n.__('operator-user'),
  342. operator_user_abbrev: TAPi18n.__('operator-user-abbrev'),
  343. operator_member: TAPi18n.__('operator-member'),
  344. operator_member_abbrev: TAPi18n.__('operator-member-abbrev'),
  345. operator_assignee: TAPi18n.__('operator-assignee'),
  346. operator_assignee_abbrev: TAPi18n.__('operator-assignee-abbrev'),
  347. };
  348. text = `# ${TAPi18n.__('globalSearch-instructions-heading')}`;
  349. text += `\n${TAPi18n.__('globalSearch-instructions-description', tags)}`;
  350. text += `\n${TAPi18n.__('globalSearch-instructions-operators', tags)}`;
  351. text += `\n* ${TAPi18n.__(
  352. 'globalSearch-instructions-operator-board',
  353. tags,
  354. )}`;
  355. text += `\n* ${TAPi18n.__(
  356. 'globalSearch-instructions-operator-list',
  357. tags,
  358. )}`;
  359. text += `\n* ${TAPi18n.__(
  360. 'globalSearch-instructions-operator-swimlane',
  361. tags,
  362. )}`;
  363. text += `\n* ${TAPi18n.__(
  364. 'globalSearch-instructions-operator-label',
  365. tags,
  366. )}`;
  367. text += `\n* ${TAPi18n.__(
  368. 'globalSearch-instructions-operator-hash',
  369. tags,
  370. )}`;
  371. text += `\n* ${TAPi18n.__(
  372. 'globalSearch-instructions-operator-user',
  373. tags,
  374. )}`;
  375. text += `\n* ${TAPi18n.__('globalSearch-instructions-operator-at', tags)}`;
  376. text += `\n* ${TAPi18n.__(
  377. 'globalSearch-instructions-operator-member',
  378. tags,
  379. )}`;
  380. text += `\n* ${TAPi18n.__(
  381. 'globalSearch-instructions-operator-assignee',
  382. tags,
  383. )}`;
  384. text += `\n## ${TAPi18n.__('heading-notes')}`;
  385. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-1', tags)}`;
  386. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-2', tags)}`;
  387. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-3', tags)}`;
  388. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-4', tags)}`;
  389. text += `\n* ${TAPi18n.__('globalSearch-instructions-notes-5', tags)}`;
  390. return text;
  391. },
  392. labelColors() {
  393. return Boards.simpleSchema()._schema['labels.$.color'].allowedValues.map(
  394. color => {
  395. return { color, name: TAPi18n.__(`color-${color}`) };
  396. },
  397. );
  398. },
  399. events() {
  400. return [
  401. {
  402. 'submit .js-search-query-form'(evt) {
  403. evt.preventDefault();
  404. this.searchAllBoards(evt.target.searchQuery.value);
  405. },
  406. 'click .js-label-color'(evt) {
  407. evt.preventDefault();
  408. const input = document.getElementById('global-search-input');
  409. this.query.set(
  410. `${input.value} ${TAPi18n.__('operator-label')}:"${
  411. evt.currentTarget.textContent
  412. }"`,
  413. );
  414. document.getElementById('global-search-input').focus();
  415. },
  416. 'click .js-board-title'(evt) {
  417. evt.preventDefault();
  418. const input = document.getElementById('global-search-input');
  419. this.query.set(
  420. `${input.value} ${TAPi18n.__('operator-board')}:"${
  421. evt.currentTarget.textContent
  422. }"`,
  423. );
  424. document.getElementById('global-search-input').focus();
  425. },
  426. 'click .js-list-title'(evt) {
  427. evt.preventDefault();
  428. const input = document.getElementById('global-search-input');
  429. this.query.set(
  430. `${input.value} ${TAPi18n.__('operator-list')}:"${
  431. evt.currentTarget.textContent
  432. }"`,
  433. );
  434. document.getElementById('global-search-input').focus();
  435. },
  436. 'click .js-label-name'(evt) {
  437. evt.preventDefault();
  438. const input = document.getElementById('global-search-input');
  439. this.query.set(
  440. `${input.value} ${TAPi18n.__('operator-label')}:"${
  441. evt.currentTarget.textContent
  442. }"`,
  443. );
  444. document.getElementById('global-search-input').focus();
  445. },
  446. },
  447. ];
  448. },
  449. }).register('globalSearch');